branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <file_sep>import { createGlobalStyle } from "styled-components";
export default createGlobalStyle`
* {
margin: 0;
padding: 0;
box-sizing: border-box;
outline: 0;
}
body {
background-color: #f4f1de;
color: #e07a5f;
padding: 50px;
}
p {
color: #81b29a;
}
div {
margin-bottom: 30px;
display: flex;
flex-direction: column;
align-items: center;
text-align: center;
width: 100%
}
.buyProducts {
background-color: #f2cc8f;
padding: 10px;
border-radius: 20px;
border: 1px solid #e07a5f;
}
ul, form {
list-style: none;
display: flex;
flex-wrap: wrap;
column-gap: 30px;
}
li {
width: 200px;
height: 300px;
display: flex;
flex-direction: column;
justify-content: space-between;
margin-bottom: 30px;
}
h3 {
color: #3d405b;
}
span {
font-size: 12px;
text-decoration: line-through;
}
form {
justify-content: center;
}
input {
background-color: #81b29a;
font-size: 15px;
padding: 5px;
border-radius: 10px;
color: #f4f1de;
border: 1px solid #f4f1de;
margin: 10px 0 5px 0;
::placeholder {
color:#f2cc8f;
}
}
button {
background-color: #f4f1de;
font-size: 10px;
padding: 5px;
border-radius: 10px;
color: #e07a5f;
border: 1px solid #e07a5f;
}
`;<file_sep>import { useState } from "react"
const BuyProducts = ({buy, products}) => {
const [cartTotal, setCartTotal] = useState(0);
return(
<div className="buyProducts">
<div>
<h3>Subtotal - R${buy.map((shop) => shop)
.reduce((cartTotal, current) => cartTotal + parseFloat(current.price - current.discount), cartTotal)
.toFixed(2)}</h3>
<p>Economizou - R${buy.map((code) => code)
.reduce((cartTotal, current) => (cartTotal + parseFloat(current.discount)), cartTotal)
.toFixed(2)}</p>
</div>
<div>
<h2>Carrinho:</h2>
<ul>{buy.map((product) => (
<li key={product.code}>
<h3>{product.name}</h3>
<h4>{product.description}</h4>
<span>De R$ {product.price}</span>
<p>R$ {(product.price-product.discount).toFixed(2)}</p>
</li>
))}</ul>
</div>
</div>
)
}
export default BuyProducts<file_sep>import { useState } from "react";
import BuyProducts from "../BuyProducts/BuyProducts";
const Products = () => {
const [products, setProducts] = useState([
{
code: 10,
name: "Smart TV Led 50 Semp",
description:
"SK8300 4K HDR Android Wi-Fi 3 HDMI 2 USB Controle Remoto com atalhos Chromecast Integrado",
price: 2299.99,
discount: 190.99,
},
{
code: 11,
name: "Smartphone Samsung Galaxy A72 128GB",
description:
"4G Wi-Fi Tela 6.7 Dual Chip 6GB RAM Câmera Quádrupla + Selfie 32MP - Preto",
price: 1988.4,
discount: 87.89,
},
{
code: 12,
name: "Smartwatch Samsung Galaxy Watch Active",
description:
"4O Galaxy Watch Active é o smartwatch ideal para quem tem um estilo de vida ativo e saudável. Ele é leve, confortável e monitora diariamente suas atividades físicas, e os comportamentos de nível de stress e sono",
price: 678.6,
discount: 110.19,
},
]);
const [code, setCode] = useState('')
const [name, setName] = useState('')
const [description, setDescription] = useState('')
const [price, setPrice] = useState('')
const [discount, setDiscount] = useState('')
const [buy, setBuy] = useState([])
const addProduct = () => {
setProducts([...products, {code,
name,
description,
price,
discount,}])
}
const buyProduct = (product) => {
setBuy([...buy, product])
}
return(
<div>
<BuyProducts buy={buy} products={products}/>
<div>
<div className="buyProducts">
<h2>Cadastre produtos</h2>
<form>
<input value={code} placeholder="Código"
onChange={(event) => setCode(event.target.value)}></input>
<input value={name} placeholder="Nome"
onChange={(event) => setName(event.target.value)}></input>
<input value={description} placeholder="Descrição"
onChange={(event) => setDescription(event.target.value)}></input>
<input value={price} placeholder="Preço"
onChange={(event) => setPrice(event.target.value)}></input>
<input value={discount} placeholder="Desconto"
onChange={(event) => setDiscount(event.target.value)}></input>
<button type='button' onClick={() => addProduct()}>Adicionar</button>
</form>
</div>
<div className="buyProducts">
<ul>{products.map((product, index) => (
<li key={index}>
<h3>{product.name}</h3>
<h4>{product.description}</h4>
<span>De R$ {product.price}</span>
<p>R$ {(product.price-product.discount).toFixed(2)}</p>
<button type="button" onClick={() => buyProduct(product)}>Adicionar ao carrinho</button>
</li>
))}</ul>
</div>
</div>
</div>
)
}
export default Products | 507777c2393a5c78f4ad9484f74206d84fc70d46 | [
"JavaScript"
] | 3 | JavaScript | Kenzie-Academy-Brasil-Developers/react-entrega-s3-projeto-de-nivelamento-Maria-baia | 3380c30bf039f223c327dfcda2a41361893fe6ff | 464a142a2aae15975e4a5fea4cea68d8780a4d11 |
refs/heads/main | <file_sep>FLASK_ENV=development
FLASK_DEBUG=1
FLASK_APP=bluelog
<file_sep>import os
import click
from flask import *
import logging
from flask_login import current_user
from flask_wtf.csrf import CSRFError
from bluelog.blueprints.admin import admin_bp
from bluelog.blueprints.auth import auth_bp
from bluelog.settings import config
from bluelog.blueprints.blog import blog_bp
from bluelog.extensions import *
from bluelog.models import *
def create_app(config_name=None):
if config_name is None:
config_name=os.getenv('FLASK_CONFIG','development')
app=Flask('bluelog')
app.config.from_object(config[config_name])
register_logging(app)
register_extensions(app)
register_blueprints(app)
register_commands(app)
app.register_blueprint(blog_bp)
register_errors(app)
register_template_context(app)
register_request_handlers(app)
return app
def register_logging(app):
pass
def register_extensions(app):
bootstrap.init_app(app)
db.init_app(app)
ckeditor.init_app(app)
mail.init_app(app)
moment.init_app(app)
login_manager.init_app(app)
csrf.init_app(app)
def register_blueprints(app):
app.register_blueprint(blog_bp)
app.register_blueprint(admin_bp, url_prefix='/admin')
app.register_blueprint(auth_bp, url_prefix='/auth')
def register_shell_context(app):
@app.shell_context_processor
def make_shell_context():
return dict(db=db,Admin=Admin,Post=Post,Category=Category,Comment=Comment)
def register_template_context(app):
@app.context_processor
def make_template_context():
admin = Admin.query.first()
categories = Category.query.order_by(Category.name).all()
links = Link.query.order_by(Link.name).all()
if current_user.is_authenticated:
unread_comments = Comment.query.filter_by(reviewed=False).count()
else:
unread_comments = None
return dict(
admin=admin,categories=categories,
links=links,unread_comments=unread_comments)
def register_errors(app):
@app.errorhandler(400)
def bad_request(e):
return render_template('errors/400.html'),400
@app.errorhandler(404)
def page_not_found(e):
return render_template('errors/404.html'), 404
@app.errorhandler(500)
def internal_server_error(e):
return render_template('errors/500.html'), 500
@app.errorhandler(CSRFError)
def handle_csrf_error(e):
return render_template('errors/400.html', description=e.description), 400
def register_commands(app):
@app.cli.command()
@click.option('--drop', is_flag=True, help='Create after drop.')
def initdb(drop):
"""Initialize the database."""
if drop:
click.confirm('This operation will delete the database, do you want to continue?', abort=True)
db.drop_all()
click.echo('Drop tables.')
db.create_all()
click.echo('Initialized database.')
@app.cli.command()
@click.option('--category',default=10,help='fake categories,default is 10')
@click.option('--post',default=50,help='fake posts,default is 50')
@click.option('--comment',default=500,help='fake comments,default is 500')
def forge(category,post,comment):
"""Create fake categories , posts and comments"""
from bluelog.fakes import fake_categories,fake_comments,fake_admin,fake_posts
db.drop_all()
db.create_all()
click.echo('create fake admin')
fake_admin()
click.echo('create %d fake categories'%category)
fake_categories()
click.echo('create %d fake posts'%post)
fake_posts()
click.echo('create %d fake comments'%comment)
fake_comments()
click.echo('done')
@app.cli.command()
@click.option('--username',prompt=True,help='The username used to login')
@click.option('--password',prompt=True,hide_input=True,confirmation_prompt=True,help='The password used to login')
def init(username,password):
"""Init bluelog"""
click.echo('Initialize the blog')
db.create_all()
admin=Admin.query.first()
if admin:
click.echo('The admin already exit,updating...')
admin.username=username
admin.set_password(password)
else:
click.echo('Creating the admin...')
admin=Admin(
username=username,
blog_title='Bluelog',
blog_sub_title='This is a fake blog',
name='Admin',
about='Anything about you.0'
)
admin.set_password(<PASSWORD>)
db.session.add(admin)
category=Category.query.first()
if category is None:
click.echo('Creating the default category...')
category=Category(name='Default')
db.session.add(category)
db.session.commit()
click.echo('done')
def register_request_handlers(app):
pass
<file_sep># blog
A private blog
<file_sep>import random
from faker import Faker
from sqlalchemy.exc import IntegrityError
from bluelog.extensions import db
from bluelog.models import Admin,Comment,Category,Post
def fake_admin():
admin=Admin(
username='admin',
blog_title='blog',
blog_sub_title="This is a fake blog",
name='zyb',
about='A fake admin.Made by zyb,just for the homework.'
)
admin.set_password('<PASSWORD>')
db.session.add(admin)
db.session.commit()
fake=Faker()
def fake_categories(count=10):
category=Category(name='Default')
db.session.add(category)
for i in range(count):
category=Category(name=fake.word())
db.session.add(category)
try:
db.session.commit()
except IntegrityError:
db.session.rollback()
def fake_posts(count=50):
for i in range(count):
post=Post(
title=fake.sentence(),
body=fake.text(2000),
category=Category.query.get(random.randint(1,Category.query.count())),
timestamp=fake.date_time_this_year()
)
db.session.add(post)
db.session.commit()
def fake_comments(count=500):
for i in range(count):
comment=Comment(
author=fake.name(),
email=fake.email(),
site=fake.url(),
body=fake.sentence(),
timestamp=fake.date_time_this_year(),
reviewed=True,
post=Post.query.get(random.randint(1,Post.query.count()))
)
db.session.add(comment)
salt=int(count*0.1)
for i in range(salt):
comment=Comment(
author=fake.name(),
email=fake.email(),
site=fake.url(),
body=fake.sentence(),
timestamp=fake.date_time_this_year(),
reviewed=False,
post=Post.query.get(random.randint(1, Post.query.count()))
)
db.session.add(comment)
for i in range(salt):
comment=Comment(
author='zyb',
email='<EMAIL>',
site='https://mail.163.com/',
body=fake.sentence(),
timestamp=fake.date_time_this_year(),
from_admin=True,
reviewed=True,
post=Post.query.get(random.randint(1,Post.query.count()))
)
db.session.add(comment)
db.session.commit()
for i in range(salt):
comment=Comment(
author=fake.name(),
email=fake.email(),
site=fake.url(),
body=fake.sentence(),
timestamp=fake.date_time_this_year(),
reviewed=True,
replied=Comment.query.get(random.randint(1,Comment.query.count())),
post=Post.query.get(random.randint(1, Post.query.count()))
)
db.session.add(comment)
db.session.commit()
<file_sep>import os
from flask import render_template, flash, redirect, url_for, request, current_app, Blueprint, send_from_directory
from flask_login import login_required, current_user
from flask_ckeditor import upload_success, upload_fail
from bluelog.extensions import db
from bluelog.forms import *
from bluelog.models import Post, Category, Comment, Link
from bluelog.utils import redirect_back, allowed_file
admin_bp=Blueprint('admin',__name__)
@admin_bp.route('/settings',methods=['GET','POST'])
@login_required
def settings():
form=SettingForm()
if form.validate_on_submit():
current_user.name=form.name.data
current_user.blog_title=form.blog_title.data
current_user.blog_sub_title=form.blog_sub_title.data
current_user.about=form.about.data
db.session.commit()
flash('Setting updated','success')
return redirect(url_for('blog.index'))
form.name.data=current_user.name
form.blog_title.data = current_user.blog_title
form.blog_sub_title.data = current_user.blog_sub_title
form.about.data = current_user.about
return render_template('admin/settings.html', form=form)
@admin_bp.route('/post/manage')
@login_required
def manage_post():
page=request.args.get('page',1,type=int)
pagination=Post.query.order_by(Post.timestamp.desc()).paginate(
page,per_page=current_app.config['BLUELOG_MANAGE_POST_PER_PAGE'])
posts=pagination.items
return render_template('admin/manage_post.html',page=page,pagination=pagination,posts=posts)
@admin_bp.route('/post/new',methods=['GET','POST'])
@login_required
def new_post():
form=PostForm()
if form.validate_on_submit():
title=form.title.data
body=form.body.data
category=Category.query.get(form.category.data)
post=Post(title=title,body=body,category=category)
db.session.add(post)
db.session.commit()
flash('Post create','success')
return redirect(url_for('blog.show_post',post_id=post.id))
return render_template('admin/new_post.html',form=form)
@admin_bp.route('/post/<int:post_id>/edit',methods=['GET','POST'])
@login_required
def edit_post(post_id):
form=PostForm()
post=Post.query.get_or_404(post_id)
if form.validate_on_submit():
post.title=form.title.data
post.body=form.body.data
post.category=Category.query.get(form.category.data)
db.session.commit()
flash('Post updated','success')
return redirect(url_for('blog.show_post',post_id=post.id ))
form.title.data=post.title
form.body.data=post.body
form.category.data=post.category_id
return render_template('admin/edit_post.html',form=form)
@admin_bp.route('/post/<int:post_id>/delete',methods=['POST'])
@login_required
def delete_post(post_id):
post=Post.query.get_or_404(post_id)
db.session.delete(post)
db.session.commit()
flash('Post deleted','success')
return redirect_back()
@admin_bp.route('/set-comment/<int:post_id>',methods=['GET','POST'])
@login_required
def set_comment(post_id):
post=Post.query.get_or_404(post_id)
if post.can_comment:
post.can_comment=False
flash('Comment disabled','info')
else:
post.can_comment=True
flash('Comment enabled','info')
db.session.commit()
return redirect_back()
@admin_bp.route('/comment/<int:comment_id>/delete', methods=['POST'])
@login_required
def delete_comment(comment_id):
comment = Comment.query.get_or_404(comment_id)
db.session.delete(comment)
db.session.commit()
flash('Comment deleted.', 'success')
return redirect_back()
@admin_bp.route('/comment/<int:comment_id>/approve', methods=['POST'])
@login_required
def approve_comment(comment_id):
comment=Comment.query.get_or_404(comment_id)
comment.reviewed=True
db.session.commit()
flash('Comment published','success')
return redirect_back()
@admin_bp.route('/comment/manage')
@login_required
def manage_comment():
filter_rule=request.args.get('filter','all')
page=request.args.get('page',1,type=int)
per_page=current_app.config['BLUELOG_COMMENT_PER_PAGE']
if filter_rule=='unreviewed':
filter_comments=Comment.query.filter_by(reviewed=False)
elif filter_rule=='admin':
filter_comments=Comment.query.filter_by(from_admin=True)
else:
filter_comments=Comment.query
pagination=filter_comments.order_by(Comment.timestamp.desc()).paginate(page,per_page=per_page)
comments=pagination.items
return render_template('admin/manage_comment.html',comments=comments,pagination=pagination)
@admin_bp.route('/category/manage')
@login_required
def manage_category():
return render_template('admin/manage_category.html')
@admin_bp.route('/category/new',methods=['GET','POST'])
@login_required
def new_category():
form=CategoryForm()
if form.validate_on_submit():
name=form.name.data
category=Category(name=name)
db.session.add(category)
db.session.commit()
flash('Category created','success')
return redirect(url_for('.manage_category'))
return render_template('admin/new_category.html',form=form)
@admin_bp.route('/category/<int:category_id>/delete',methods=['POST'])
@login_required
def delete_category(category_id):
category=Category.query.get_or_404(category_id)
if category_id==1:
flash('You can not delete the default category','warning')
return redirect(url_for('blog.index'))
category.delete()
flash('Category deleted','success')
return redirect(url_for('.manage_category'))
@admin_bp.route('/category/<int:category_id>/edit',methods=['GET','POST'])
@login_required
def edit_category(category_id):
form=CategoryForm()
category=Category.query.get_or_404(category_id)
if category.id==1:
flash('You can not edit the default category.', 'warning')
return redirect(url_for('blog.index'))
if form.validate_on_submit():
category.name=form.name.data
db.session.commit()
flash('Category create','success')
return redirect(url_for('.manage_category'))
form.name.data=category.name
return render_template('admin/edit_category.html', form=form)
@admin_bp.route('/link/manage')
@login_required
def manage_link():
return render_template('admin/manage_link.html')
@admin_bp.route('/link/new', methods=['GET', 'POST'])
@login_required
def new_link():
form=LinkForm()
if form.validate_on_submit():
name=form.name.data
url= form.url.data
link=Link(name=name, url=url)
db.session.add(link)
db.session.commit()
flash('Link created.', 'success')
return redirect(url_for('.manage_link'))
return render_template('admin/new_link.html', form=form)
@admin_bp.route('/link/<int:link_id>/edit', methods=['GET', 'POST'])
@login_required
def edit_link(link_id):
form=LinkForm()
link=Link.query.get_or_404(link_id)
if form.validate_on_submit():
link.name=form.name.data
link.url=form.url.data
db.session.commit()
flash('Link updated.', 'success')
return redirect(url_for('.manage_link'))
form.name.data=link.name
form.url.data=link.url
return render_template('admin/edit_link.html', form=form)
@admin_bp.route('/link/<int:link_id>/delete', methods=['POST'])
@login_required
def delete_link(link_id):
link=Link.query.get_or_404(link_id)
db.session.delete(link)
db.session.commit()
flash('Link deleted.', 'success')
return redirect(url_for('.manage_link'))
@admin_bp.route('/uploads/<path:filename>')
def get_image(filename):
return send_from_directory(current_app.config['BLUELOG_UPLOAD_PATH'], filename)
@admin_bp.route('/upload', methods=['POST'])
def upload_image():
f = request.files.get('upload')
if not allowed_file(f.filename):
return upload_fail('Image only!')
f.save(os.path.join(current_app.config['BLUELOG_UPLOAD_PATH'], f.filename))
url = url_for('.get_image', filename=f.filename)
return upload_success(url, f.filename)
<file_sep>from threading import Thread
from flask import url_for, current_app
from flask_mail import Message
from bluelog.extensions import mail
def _send_async_mail(app,message):
with app.app_context():
mail.send(message)
def send_mail(subject,to,html):
app = current_app._get_current_object()
message=Message(subject,recipients=[to],html=html)
thr=Thread(target=_send_async_mail,args=[app,message])
thr.start()
return thr
def send_new_comment_email(post):
post_url=url_for('blog.show_post',post_id=post.id,_external=True)+'#comments'
send_mail(subject='New comment',to=current_app.config['BLUELOG_EMAIL'],
html='<p>New comment in post <i>%s</i>, click the link below to check:</p>'
'<p><a href="%s">%s</a></P>'
'<p><small style="color: #868e96">Do not reply this email.</small></p>'
% (post.title, post_url, post_url))
def send_new_reply_email(comment):
post_url=url_for('blog.show_post',post_id=comment.post.id,_external=True)+'#comments'
send_mail(subject='New reply',to=comment.email,
html='<p>New reply for the comment you left in post <i>%s</i>, click the link below to check: </p>'
'<p><a href="%s">%s</a></p>'
'<p><small style="color: #868e96">Do not reply this email.</small></p>'
% (comment.post.title, post_url, post_url))
<file_sep>from flask_ckeditor import CKEditorField
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, SelectField, TextAreaField, ValidationError, HiddenField, \
BooleanField, PasswordField
from wtforms.validators import DataRequired, Email, Length, Optional, URL
from bluelog.models import Category
class LoginForm(FlaskForm):
username=StringField('Username',validators=[DataRequired(),Length(1,20)])
password=PasswordField('<PASSWORD>',validators=[DataRequired(),Length(8,128)])
remember=BooleanField('Remember me')
submit=SubmitField('Log in')
class PostForm(FlaskForm):
title=StringField('Title',validators=[DataRequired(),Length(1,60)])
category=SelectField('Category',coerce=int,default=1)
body=CKEditorField('Body',validators=[DataRequired()])
submit=SubmitField()
def __init__(self,*args,**kwargs):
super(PostForm,self).__init__(*args,**kwargs)
self.category.choices=[(category.id, category.name)
for category in Category.query.order_by(Category.name).all()]
class CategoryForm(FlaskForm):
name=StringField('Name',validators=[DataRequired(),Length(1,30)])
submit=SubmitField()
def validate_name(self,field):
if Category.query.filter_by(name=field.data).first():
raise ValidationError('Name is already use')
class CommentForm(FlaskForm):
author=StringField('Name',validators=[DataRequired(),Length(1,30)])
email=StringField('Email',validators=[DataRequired(),Email(),Length(1,20)])
site=StringField('Site',validators=[Optional(),URL(),Length(0,255)])
body=TextAreaField('Comment',validators=[DataRequired()])
submit=SubmitField()
class AdminCommentForm(CommentForm):
author=HiddenField()
email=HiddenField()
site=HiddenField()
class LinkForm(FlaskForm):
name=StringField('Name', validators=[DataRequired(), Length(1, 300)])
url=StringField('URL', validators=[DataRequired(), URL(), Length(1, 255)])
submit=SubmitField()
class SettingForm(FlaskForm):
name=StringField('Name',validators=[DataRequired(),Length(1,30)])
blog_title=StringField('Blog Title',validators=[DataRequired(),Length(1,60)])
blog_sub_title=StringField('Blog Sub Title',validators=[DataRequired(),Length(1,100)])
about=CKEditorField('About Page',validators=[DataRequired()])
submit=SubmitField()<file_sep>from flask import render_template, flash, redirect, url_for, request, current_app, Blueprint, abort, make_response
from flask_login import current_user
from bluelog.emails import send_new_comment_email, send_new_reply_email
from bluelog.extensions import db
from bluelog.forms import CommentForm, AdminCommentForm
from bluelog.models import Post, Category, Comment
from bluelog.utils import redirect_back
blog_bp=Blueprint('blog',__name__)
@blog_bp.route('/')
def index():
page = request.args.get('page', 1, type=int)
per_page = current_app.config['BLUELOG_POST_PER_PAGE']
pagination = Post.query.order_by(Post.timestamp.desc()).paginate(page, per_page=per_page)
posts = pagination.items
return render_template('blog/index.html', pagination=pagination, posts=posts)
@blog_bp.route('/about')
def about():
return render_template('blog/about.html')
@blog_bp.route('/post/<int:post_id>',methods=['GET','POST'])
def show_post(post_id):
post=Post.query.get_or_404(post_id)
page=request.args.get('page',1,type=int)
per_page=current_app.config['BLUELOG_MANAGE_POST_PER_PAGE']
pagination = Comment.query.with_parent(post).filter_by(reviewed=True).order_by(Comment.timestamp.asc()).paginate(
page, per_page)
comments=pagination.items
if current_user.is_authenticated:
form=AdminCommentForm()
form.author.data=current_user.name
form.email.data=current_app.config['BLUELOG_EMAIL']
form.site.data=url_for('.index')
from_admin=True
reviewed=True
else:
form=CommentForm()
from_admin=False
reviewed=False
if form.validate_on_submit():
author=form.author.data
email=form.email.data
site=form.site.data
body=form.body.data
comment=Comment(
author=author,email=email,site=site,body=body,
from_admin=from_admin,post=post,reviewed=reviewed)
replied_id=request.args.get('reply')
if replied_id:
replied_comment=Comment.query.get_or_404(replied_id)
comment.replied=replied_comment
send_new_reply_email(replied_comment)
db.session.add(comment)
db.session.commit()
if current_user.is_authenticated:
flash('Comment published','success')
else:
flash('Thanks,your comment will be published after reviewed','info')
send_new_comment_email(post)
return redirect(url_for('.show_post',post_id=post_id))
return render_template('blog/post.html',post=post,pagination=pagination,comments=comments,form=form)
@blog_bp.route('/category/<int:category_id>')
def show_category(category_id):
category=Category.query.get_or_404(category_id)
page=request.args.get('page',1,type=int)
per_page=current_app.config['BLUELOG_MANAGE_POST_PER_PAGE']
pagination=Post.query.with_parent(category).order_by(Post.timestamp.desc()).paginate(page,per_page=per_page)
posts=pagination.items
return render_template('blog/category.html',category=category,pagination=pagination,posts=posts)
@blog_bp.route('/reply/comment/<int:comment_id>')
def reply_comment(comment_id):
comment = Comment.query.get_or_404(comment_id)
if not comment.post.can_comment:
flash('Comment is disabled.', 'warning')
return redirect(url_for('.show_post', post_id=comment.post.id))
return redirect(
url_for('.show_post', post_id=comment.post_id, reply=comment_id, author=comment.author) + '#comment-form')
@blog_bp.route('/change-theme/<theme_name>')
def change_theme(theme_name):
if theme_name not in current_app.config['BLUELOG_THEMES'].keys():
abort(404)
response=make_response(redirect_back())
response.set_cookie('theme',theme_name,max_age=30 * 24 * 60 * 60)
return response
<file_sep>from bluelog.extensions import db
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import *
class Admin(db.Model,UserMixin):
id=db.Column(db.Integer,primary_key=True)
username=db.Column(db.String(20))
password_hash=db.Column(db.String(128))
blog_title=db.Column(db.String(60))
blog_sub_title=db.Column(db.String(100))
name=db.Column(db.String(30))
about=db.Column(db.Text)
def set_password(self,password):
self.password_hash=generate_password_hash(password)
def validate_password(self,password):
return check_password_hash(self.password_hash,password)
class Category(db.Model):
id=db.Column(db.Integer,primary_key=True)
name=db.Column(db.String(30),unique=True)
posts=db.relationship('Post',back_populates='category')
def delete(self):
default_category=Category.query.get(1)
posts=self.posts[:]
for post in posts:
post.category=default_category
db.session.delete(self)
db.session.commit()
class Post(db.Model):
id=db.Column(db.Integer,primary_key=True)
title=db.Column(db.String(60))
body=db.Column(db.Text)
timestamp=db.Column(db.DateTime,default=datetime.utcnow)
can_comment=db.Column(db.Boolean,default=True)
category_id=db.Column(db.Integer,db.ForeignKey('category.id'))
category=db.relationship('Category',back_populates='posts')
comments=db.relationship('Comment',back_populates='post',cascade='all,delete-orphan')
class Comment(db.Model):
id=db.Column(db.Integer,primary_key=True)
author=db.Column(db.String(30))
email=db.Column(db.String(254))
site=db.Column(db.String(255))
body=db.Column(db.Text)
from_admin=db.Column(db.Boolean,default=False)
reviewed=db.Column(db.Boolean,default=False)
timestamp=db.Column(db.DateTime,default=datetime.utcnow,index=True)
post_id=db.Column(db.Integer,db.ForeignKey('post.id'))
post=db.relationship('Post',back_populates='comments')
replied_id=db.Column(db.Integer,db.ForeignKey('comment.id'))
replied=db.relationship('Comment',back_populates='replies',remote_side=[id])
replies=db.relationship('Comment',back_populates='replied',cascade='all')
class Link(db.Model):
id=db.Column(db.Integer,primary_key=True)
name=db.Column(db.String(30))
url=db.Column(db.String(255))
| 240ac73e35a40a9d958acad177d2ddb31980d3f7 | [
"Markdown",
"Python",
"Shell"
] | 9 | Shell | zhouyanb/blog | 90b3734b282e98dde14429a236ae6019045fdde9 | a6c832c439b2b59709c20523862fec0a8cbec9ce |
refs/heads/master | <repo_name>DimasCoder/easy_lviv<file_sep>/app/src/main/java/dimasapp/dimas/com/ui/IOnBackPressed.java
package dimasapp.dimas.com.ui;
/**
* Created by Dima on 01.11.2019.
*/
public interface IOnBackPressed {
/**
* If you return true the back press will not be taken into account, otherwise the activity will act naturally
* @return true if your processing has priority if not false
*/
boolean onBackPressed();
}<file_sep>/app/src/main/java/dimasapp/dimas/com/ui/fragments/MapFragment.java
package dimasapp.dimas.com.ui.fragments;
import android.app.AlertDialog;
import android.location.Address;
import android.location.Geocoder;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import dimasapp.dimas.com.ui.R;
import static android.content.ContentValues.TAG;
public class MapFragment extends Fragment implements OnMapReadyCallback {
private static final LatLng OPERA = new LatLng(49.84371, 24.0264523);
private static final LatLng HIGHCASTLE = new LatLng(49.8481849,24.0393758);
private static final LatLng POTOCKIY = new LatLng(49.8379368,24.0267808);
private static final LatLng YURAS = new LatLng(49.8386906,24.0130218);
private static final LatLng RATUSHA = new LatLng(49.8417178, 24.0316819);
private Marker ot;
private Marker hc;
private Marker pp;
private Marker ys;
private Marker rt;
float curLat = (float) 49.8373601;
float curLng = (float) 24.0335928;
GoogleMap map;
private EditText mSearchText;
private ImageView btnSearch;
ImageView dialogImage;
TextView dialogTitle, dialogText;
int otTitle = R.string.otTitle;
int hcTitle = R.string.hcTitle;
int ysTitle = R.string.ysTitle;
int ppTitle = R.string.ppTitle;
int rtTitle = R.string.rtTitle;
int otText = R.string.otText;
int hcText = R.string.hcText;
int ysText = R.string.ysText;
int ppText = R.string.ppText;
int rtText = R.string.rtText;
int otImage = R.drawable.ot_image;
int hcImage = R.drawable.hc_image;
int ysImage = R.drawable.ys_image;
int ppImage = R.drawable.pp_image;
int rtImage = R.drawable.rt_image;
int otAddress = R.string.otAddress;
int hcAddress = R.string.hcAddress;
int ysAddress = R.string.ysAddress;
int ppAddress = R.string.ppAddress;
int rtAddress = R.string.rtAddress;
int otAudio = R.raw.opera;
int hcAudio = R.raw.castle;
int ppAudio = R.raw.palace;
MediaPlayer mediaPlayer;
public MapFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_map, container, false);
mSearchText = (EditText) v.findViewById(R.id.input_search);
btnSearch = (ImageView) v.findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try{
geoLocate();
}catch (Exception e){}
}
});
return v;
}
public void MyCustomDialog(int title, int text, int image, int address, final int audio){
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.dialog_layout, null);
builder.setView(dialogView);
Button btnDialogExit = (Button)dialogView.findViewById(R.id.btnDialogExit);
Button btnPlay = (Button)dialogView.findViewById(R.id.btnPlay);
TextView dialogTitle = (TextView)dialogView.findViewById(R.id.dialogTitle);
TextView dialogText = (TextView)dialogView.findViewById(R.id.dialogText);
ImageView dialogImage = (ImageView)dialogView.findViewById(R.id.dialogImage);
TextView dialogAddress = (TextView)dialogView.findViewById(R.id.dialogAddress);
dialogTitle.setText(title);
dialogText.setText(text);
dialogAddress.setText(address);
dialogImage.setImageResource(image);
final AlertDialog dialog = builder.create();
btnDialogExit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try{
if(mediaPlayer.isPlaying()){
mediaPlayer.stop();
}
dialog.cancel();
}catch (Exception e){}
}
});
if(audio == 1){
btnPlay.setVisibility(View.INVISIBLE);
}
else {
mediaPlayer = MediaPlayer.create(getActivity(), audio);
btnPlay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
else if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}
}
});
}
dialog.show();
}
private void init() {
Log.d(TAG, "init: initializing");
mSearchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent keyEvent) {
if (actionId == EditorInfo.IME_ACTION_SEARCH
|| actionId == EditorInfo.IME_ACTION_DONE
|| keyEvent.getAction() == KeyEvent.ACTION_DOWN
|| keyEvent.getAction() == KeyEvent.KEYCODE_ENTER) {
geoLocate();
}
return false;
}
});
}
private void geoLocate() {
Log.d(TAG, "geoLocate: geolocating");
String searchString = mSearchText.getText().toString();
Geocoder geocoder = new Geocoder(getActivity());
List<Address> list = new ArrayList<>();
try {
list = geocoder.getFromLocationName(searchString, 1);
} catch (IOException e) {
Log.e(TAG, "geoLocate: IOException: " + e.getMessage());
}
if (list.size() > 0) {
Address address = list.get(0);
Log.d(TAG, "geoLocate: found a location: " + address.toString());
//Toast.makeText(this, address.toString(), Toast.LENGTH_SHORT).show();
moveCamera(new LatLng(address.getLatitude(), address.getLongitude()), 15, address.getLocality());
}
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SupportMapFragment mapFragment = (SupportMapFragment)
getChildFragmentManager().findFragmentById(R.id.map1);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
if(map != null){
map.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
@Override
public View getInfoWindow(Marker marker) {
return null;
}
@Override
public View getInfoContents(Marker marker) {
View v = getLayoutInflater().inflate(R.layout.info_window, null);
TextView tvLocality = v.findViewById(R.id.tv_locality);
TextView tvSnippet = v.findViewById(R.id.tv_snippet);
LatLng ll = marker.getPosition();
tvLocality.setText(marker.getTitle());
tvSnippet.setText(marker.getSnippet());
init();
return v;
}
});
}
final String opT = "asdЛьвівський національний академічний театр опери та балету імені Соломії Крушельницької — театр опери і балетуЛьвівський національний академічний театр опери та балету імені Соломії Крушельницької — театр опери і балету у Львові, розташований в історично";
map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {
if(marker.equals(ot)){
MyCustomDialog(otTitle, otText, otImage, otAddress, otAudio);
}
if(marker.equals(hc)){
MyCustomDialog(hcTitle, hcText, hcImage, hcAddress, hcAudio);
}
if(marker.equals(ys)){
MyCustomDialog(ysTitle, ysText, ysImage, ysAddress, 1);
}
if(marker.equals(pp)){
MyCustomDialog(ppTitle, ppText, ppImage, ppAddress, ppAudio);
}
if(marker.equals(rt)){
MyCustomDialog(rtTitle, rtText, rtImage, rtAddress, 1);
}
return true;
}
});
goToLocationZoom(curLat, curLng, 19);
ot = map.addMarker(new MarkerOptions()
.position(OPERA)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ellogo))
);
ot.setTag(0);
hc = map.addMarker(new MarkerOptions()
.position(HIGHCASTLE)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ellogo))
);
hc.setTag(0);
ys = map.addMarker(new MarkerOptions()
.position(YURAS)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ellogo))
);
ys.setTag(0);
pp = map.addMarker(new MarkerOptions()
.position(POTOCKIY)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ellogo))
);
pp.setTag(0);
rt = map.addMarker(new MarkerOptions()
.position(RATUSHA)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ellogo))
);
rt.setTag(0);
}
private void moveCamera(LatLng latLng, float zoom, String title){
Log.d(TAG, "moveCamera: moving the camera to: lat: " + latLng.latitude + ", lng: " + latLng.longitude );
map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title(title);
map.addMarker(options);
}
private void goToLocationZoom(double lat, double lng, float zoom) {
LatLng ll = new LatLng(lat, lng);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, zoom);
map.moveCamera(update);
}
}
<file_sep>/app/src/main/java/dimasapp/dimas/com/ui/fragments/HomeFragment.java
package dimasapp.dimas.com.ui.fragments;
import android.content.Context;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;
import dimasapp.dimas.com.ui.R;
import dimasapp.dimas.com.ui.cardfragments.BeerFragment;
import dimasapp.dimas.com.ui.cardfragments.MonumentsFragment;
public class HomeFragment extends Fragment {
TextView tvLogin;
CardView cardMonuments;
CardView cardMustSee;
CardView cardFood;
CardView cardBeer;
public HomeFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
//String user = getArguments().getString("user");
/*
cardMustSee = (CardView) getView().findViewById(R.id.cardMustSee);
cardFood = (CardView) getView().findViewById(R.id.cardFood);*/
final Context contextThemeWrapper = new ContextThemeWrapper(getActivity(), R.style.AppThemeFragment);
LayoutInflater localInflater = inflater.cloneInContext(contextThemeWrapper);
View v = localInflater.inflate(R.layout.fragment_home, container, false);
v.getContext().getTheme().applyStyle(R.style.AppThemeFragment, true);
// tvLogin = (TextView)v.findViewById(R.id.tvLogin);
// tvLogin.setText(user);
cardMonuments = (CardView) v.findViewById(R.id.cardMonuments);
cardMonuments.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try{
loadFragment(new MonumentsFragment());
}catch (Exception e){}
}
});
cardBeer = (CardView) v.findViewById(R.id.cardBeer);
cardBeer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try{
loadFragment(new BeerFragment());
}catch (Exception e){}
}
});
return v;
}
private void loadFragment(Fragment fragment){
if(fragment != null){
getFragmentManager()
.beginTransaction()
.replace(R.id.fragContainer, fragment)
.addToBackStack(null)
.commit();
}
}
}
<file_sep>/app/src/main/java/dimasapp/dimas/com/ui/auth/LoginFragment.java
package dimasapp.dimas.com.ui.auth;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import dimasapp.dimas.com.ui.BottomActivity;
import dimasapp.dimas.com.ui.R;
import dimasapp.dimas.com.ui.database.DataBaseHelper;
import dimasapp.dimas.com.ui.fragments.HomeFragment;
public class LoginFragment extends Fragment implements View.OnClickListener {
EditText etLogin1;
EditText etPassword1;
Button btnLogin1;
TextView tvReg1;
TextView tvHelp;
ImageView arrowBack;
Button btnLogin;
DataBaseHelper db;
HomeFragment accFrag = new HomeFragment();
public LoginFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_login, container, false);
db = new DataBaseHelper(getActivity());
etLogin1 = (EditText) v.findViewById(R.id.etLogin1);
etPassword1 = (EditText) v.findViewById(R.id.etPassword1);
btnLogin1 = (Button) v.findViewById(R.id.btnLogin1);
btnLogin1.setOnClickListener(this);
tvReg1 = (TextView) v.findViewById(R.id.tvReg1);
tvReg1.setOnClickListener(this);
tvHelp = (TextView)v.findViewById(R.id.tvHelp);
tvHelp.setOnClickListener(this);
arrowBack = (ImageView)v.findViewById(R.id.arrowBack);
arrowBack.setOnClickListener(this);
// Inflate the layout for this fragment
return v;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnLogin1:
String email = etLogin1.getText().toString().trim();
String password = <PASSWORD>1.getText().toString().trim();
Boolean res = db.checkUser(email, password);
Bundle bundle = new Bundle();
bundle.putString("user", "admin");
// accFrag.setArguments(bundle);
if (res == true) {
Toast.makeText(getActivity(), "Successful!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity(), BottomActivity.class);
startActivity(intent);
getActivity().finish();
break;
} else {
Toast.makeText(getActivity(), "Email or password is incorrect!", Toast.LENGTH_SHORT).show();
}
break;
case R.id.tvReg1:
getFragmentManager()
.beginTransaction()
.setCustomAnimations(R.anim.enter_right_to_left, R.anim.exit_right_to_left,
R.anim.enter_left_to_right, R.anim.exit_left_to_right)
.replace(R.id.fragmentContainer, new RegistrationFragment())
.addToBackStack(null)
.commit();
break;
case R.id.arrowBack:
getActivity().onBackPressed();
break;
}
}
/* @Override
public boolean onBackPressed() {
return false;
}*/
}
<file_sep>/app/src/main/java/dimasapp/dimas/com/ui/database/DataBaseHelper.java
package dimasapp.dimas.com.ui.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import static android.icu.text.MessagePattern.ArgType.SELECT;
public class DataBaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "register.db";
public static final String TABLE_NAME = "users";
public static final String COL_1 = "ID";
public static final String COL_2 = "username";
public static final String COL_3 = "usersurname";
public static final String COL_4 = "password";
public static final String COL_5 = "email";
public DataBaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("CREATE TABLE users (ID INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT, usersurname TEXT, password TEXT, email TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
if(newVersion>oldVersion)
onCreate(sqLiteDatabase);
}
public void dropTable(SQLiteDatabase sqLiteDatabase){
sqLiteDatabase.execSQL("DROP TABLE users");
}
public long addUser(String username, String usersurname, String password, String email){
SQLiteDatabase db = this.getReadableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("username", username);
contentValues.put("usersurname", usersurname);
contentValues.put("password", <PASSWORD>);
contentValues.put("email", email);
long res = db.insert("users", null, contentValues);
db.close();
return res;
}
public boolean checkEmail(String email)
{
SQLiteDatabase db = getReadableDatabase();
String query = "SELECT " + COL_5 + " FROM " + TABLE_NAME + " WHERE " + COL_5 + " =?";
Cursor cursor = db.rawQuery(query, new String[]{email});
if (cursor.getCount() > 0)
{
return false;
}
else
return true;
}
public boolean checkUser(String email, String password){
String[] columns = { COL_1 };
SQLiteDatabase db = getReadableDatabase();
String selection = COL_5 + "=?" + " and " + COL_4 + "=?";
String[] selectionArgs = {email, password};
Cursor cursor = db.query(TABLE_NAME, columns, selection, selectionArgs, null, null, null);
int count = cursor.getCount();
cursor.close();
db.close();
if(count > 0)
return true;
else
return false;
}
}
<file_sep>/app/src/main/java/dimasapp/dimas/com/ui/MainActivity.java
package dimasapp.dimas.com.ui;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import dimasapp.dimas.com.ui.auth.LoginFragment;
import dimasapp.dimas.com.ui.auth.RegistrationFragment;
import dimasapp.dimas.com.ui.database.DataBaseHelper;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
TextView tvReg;
Button btnLogin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
btnLogin = (Button)findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(this);
tvReg = (TextView)findViewById(R.id.tvReg);
tvReg.setOnClickListener(this);
}
/* @Override
public void onBackPressed() {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragmentContainer);
if (!(fragment instanceof IOnBackPressed) || !((IOnBackPressed) fragment).onBackPressed()) {
super.onBackPressed();
}
}*/
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.tvReg:
getSupportFragmentManager()
.beginTransaction()
.setCustomAnimations(R.anim.enter_right_to_left, R.anim.exit_right_to_left,
R.anim.enter_left_to_right, R.anim.exit_left_to_right)
.replace(R.id.fragmentContainer, new RegistrationFragment())
.addToBackStack(null)
.commit();
break;
case R.id.btnLogin:
getSupportFragmentManager()
.beginTransaction()
.setCustomAnimations(R.anim.enter_right_to_left, R.anim.exit_right_to_left,
R.anim.enter_left_to_right, R.anim.exit_left_to_right)
.replace(R.id.fragmentContainer, new LoginFragment())
.addToBackStack(null)
.commit();
break;
}
}
}
| 19e89bd5e7b3cada7f1338bfba7c30b77fdd6b11 | [
"Java"
] | 6 | Java | DimasCoder/easy_lviv | 067cb953b538bfd0aa651b015811ada7b531d016 | a2548c6ad926b303fa41a06320cb2ba7068e1b60 |
refs/heads/master | <file_sep>import { ComponentFixture, TestBed } from '@angular/core/testing';
import { LastRaceComponent } from './last-race.component';
describe('LastRaceComponent', () => {
let component: LastRaceComponent;
let fixture: ComponentFixture<LastRaceComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ LastRaceComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(LastRaceComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
<file_sep>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NavBarComponent } from './nav-bar/nav-bar.component';
import { LatestComponent } from './latest/latest.component';
import { TopicComponent } from './latest/topic/topic.component';
import { NewsComponent } from './latest/news/news.component';
import { ScheduleComponent } from './nav-bar/schedule/schedule.component';
import { RaceComponent } from './nav-bar/schedule/race/race.component';
import {StandingsComponent} from './nav-bar/standings/standings.component';
import { DriversComponent } from './nav-bar/drivers/drivers.component';
import { TeamsComponent } from './nav-bar/teams/teams.component';
import { GamingComponent } from './nav-bar/gaming/gaming.component';
import { LiDriverComponent } from './nav-bar/drivers/li-driver/li-driver.component';
import { MainComponent } from './main/main.component';
import { LastestNewComponent } from './main/lastest-new/lastest-new.component';
import { NewComponent } from './main/lastest-new/new/new.component';
import { SecondaryNewsComponent } from './main/secondary-news/secondary-news.component';
import { MoreNewsComponent } from './main/more-news/more-news.component';
import { CalendarComponent } from './main/calendar/calendar.component';
import { RaceCalendarComponent } from './main/calendar/race-calendar/race-calendar.component';
import { RaceSelectedComponent } from './main/calendar/race-selected/race-selected.component';
import { FlagComponent } from './main/calendar/flag/flag.component';
import { DateComponent } from './main/calendar/date/date.component';
import { SeasonInfoComponent } from './main/season-info/season-info.component';
import { ConstructorsComponent } from './main/season-info/constructors/constructors.component';
import { LastRaceComponent } from './main/season-info/last-race/last-race.component';
import { DriversLeaderboardComponent } from './main/season-info/drivers-leaderboard/drivers-leaderboard.component';
import { LiLeaderboardComponent } from './main/season-info/drivers-leaderboard/li-leaderboard/li-leaderboard.component';
@NgModule({
declarations: [
AppComponent,
NavBarComponent,
LatestComponent,
TopicComponent,
NewsComponent,
ScheduleComponent,
RaceComponent,
StandingsComponent,
DriversComponent,
TeamsComponent,
GamingComponent,
LiDriverComponent,
MainComponent,
LastestNewComponent,
NewComponent,
SecondaryNewsComponent,
MoreNewsComponent,
CalendarComponent,
RaceCalendarComponent,
RaceSelectedComponent,
FlagComponent,
DateComponent,
SeasonInfoComponent,
ConstructorsComponent,
LastRaceComponent,
DriversLeaderboardComponent,
LiLeaderboardComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-more-news',
templateUrl: './more-news.component.html',
styleUrls: ['./more-news.component.scss']
})
export class MoreNewsComponent implements OnInit {
colorWhite="string";
constructor() { }
ngOnInit(): void {
}
changecolor(){
this.colorWhite="white";
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-drivers-leaderboard',
templateUrl: './drivers-leaderboard.component.html',
styleUrls: ['./drivers-leaderboard.component.scss']
})
export class DriversLeaderboardComponent implements OnInit {
bottas="../../../../assets/images/drivers/bottas.png";
lewis="../../../../assets/images/drivers/lewis.png";
max="../../../../assets/images/drivers/max.png";
constructor() { }
ngOnInit(): void {
}
}
<file_sep>import { style } from '@angular/animations';
import { THIS_EXPR } from '@angular/compiler/src/output/output_ast';
import { AfterViewInit, Component, HostBinding, HostListener, OnInit, ViewChild } from '@angular/core';
@Component({
selector: 'app-nav-bar',
templateUrl: './nav-bar.component.html',
styleUrls: ['./nav-bar.component.scss']
})
export class NavBarComponent implements OnInit {
url = "../../assets/images/f1-tv-logo.png"
f2="../../assets/images/f2_logo.png"
f3="../../assets/images/f3_logo.png"
next="../../assets/images/next.svg"
next2="../../assets/images/next-black.svg"
fia="../../assets/images/fia_logo.png"
down="../../assets/images/arrow-down-sign-to-navigate.svg"
showAppLatest:boolean;
showAppSchedule:boolean;
showAppStandings:boolean;
showAppDrivers:boolean;
showAppTeams:boolean;
showAppGaming:boolean;
showSubnav: string | null = null;
tSubNav: any = null;
showNav:boolean =true;
teste1:boolean=false;
// isFixedNavbar:boolean=true;
constructor() {
this.showAppLatest=false;
this.showAppSchedule=false;
this.showAppStandings=false;
this.showAppDrivers=false;
this.showAppTeams=false;
this.showAppGaming=false;
}
// timeout(){
// setTimeout(()=>{
// this.showAppDrivers=false;
// },2000)
// }
ngOnInit(): void {
}
activateSubmenu(area: string): void {
window.clearTimeout(this.tSubNav);
this.resetSubmenu();
this.tSubNav = window.setTimeout(() =>{
this.showSubnav = area;
}, 500);
}
resetSubmenu(): void {
console.log("saiu");
window.clearTimeout(this.tSubNav);
this.showSubnav=null;
}
toggleNav(){
this.showNav=!this.showNav;
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-li-driver',
templateUrl: './li-driver.component.html',
styleUrls: ['./li-driver.component.scss']
})
export class LiDriverComponent implements OnInit {
next="../../../../assets/images/next.svg";
constructor() { }
ngOnInit(): void {
}
}
| 52bd85c453ab0d8fbc067db1a5a8f63ca2785ce9 | [
"TypeScript"
] | 6 | TypeScript | echo-Rui-Dias/Formula1-copy | 615ec2061d0f18d7b4ed627f5474f65c10b764b7 | b34a0d134152d8578cb1a5160dc072cdc68db154 |
refs/heads/master | <file_sep>//引入基本模板
let echarts = require('echarts/lib/echarts')
// 引入折线图等组件
require('echarts/lib/chart/line')
require('echarts/lib/chart/bar')
require('echarts/lib/chart/radar')
// 引入提示框和title组件,图例
require('echarts/lib/component/tooltip')
require('echarts/lib/component/title')
require('echarts/lib/component/legend')
require('echarts/lib/component/legendScroll') //图例翻译滚动
export default {
bind: (el) => {
el.resizeEventHandler = () => el.echartsInstance.resize();
if (window.attachEvent) {
window.attachEvent('onresize', el.resizeEventHandler);
} else {
window.addEventListener('resize', el.resizeEventHandler, false);
}
},
inserted: (el, binding) => {
el.echartsInstance = echarts.init(el);
el.echartsInstance.setOption(binding.value);
},
update: (el, binding) => {
el.echartsInstance.setOption(binding.value);
},
unbind: (el) => {
if (window.attachEvent) {
window.detachEvent('onresize', el.resizeEventHandler);
} else {
window.removeEventListener('resize', el.resizeEventHandler, false);
}
el.echartsInstance.dispose();
}
}
| 74b5cbec8b950e310dff49cd83cc16206350a3a1 | [
"JavaScript"
] | 1 | JavaScript | zlook/vue-temp-time-echart | 9cccf0fbc9fc453ae552fecff752460b5c0ebb9f | a372fd6392c0a5f3e911d86262f384f06552c130 |
refs/heads/master | <file_sep>#!/usr/bin/python
# -*- coding: utf-8 -*-
from lstm2lstm_func_model import test_model_all_all, test_model_rush
from lstm2lstm_func_model import mean_absolute_relative_error
from lstm2lstm_func_model import mean_absolute_error
from lstm2lstm_func_model import root_mean_squared_error
from lstm2lstm_func_model import sy_mean_absolute_relative_error
from lstm2lstm_func_model import load_params
from lstm2lstm_func_model import continue_train
from lstm2lstm_func_model import mkdir_file
import argparse
parser = argparse.ArgumentParser()
# given default values
parser.add_argument("--subpath", type=str, default='ALL', help="subpath")
parser.add_argument("--isBi", type=int, default=0, help='LSTM: 0 or BiLSTM: 1')
parser.add_argument("--mode", type=str, default='re_range', help='re_range or all')
parser.add_argument("--n_hidden_encoder", type=int, default=256, help="n_hidden_encoder")
parser.add_argument("--link_ratio", type=float, default= 1.0, help='link_ratio')
parser.add_argument("--n_steps_encoder", type=int, default=300, help="n_steps_encoder")
parser.add_argument("--n_steps_decoder", type=int, default=300, help="n_steps_decoder")
parser.add_argument("--add_epoch", type=int, default=100, help="add_epoch")
# traing and test setting
parser.add_argument("--opt", type=int, help='train or/and test')
parser.add_argument("--cuda", type=str, help='cuda: which gpu')
parser.add_argument("--flag", type=int, help='flag: which model')
parser.add_argument("--total_epoch", type=int, help='total_epoch')
parser.add_argument("--batch_size", type=int, default=256, help="batch_size")
parser.add_argument("--learning_rate", type=float, default=0.001, help='learning_rate')
parser.add_argument("--dropout_rate", type=float, default=0, help='dropout_rate')
# dataset setting
parser.add_argument("--location", type=str, default='amapHK', help="location, HongKong, Seattle, NYC, Los")
parser.add_argument("--region", type=str, default='amapHK', help='start sub-network')
parser.add_argument("--split_id", type=int, default=0, help='split_id')
args = parser.parse_args()
if __name__=='__main__':
params=load_params(args)
if args.opt==2:
print('============================ = train')
continue_train(params)
print('============================ = test')
test_model_all_all(params)
if args.opt == 4:
print('============================ = test')
test_model_all_all(params)
# test_model_rush(params)
if args.opt == 5:
# test_model_rush(params)
test_model_all_mean_links(params)
<file_sep># encoder_inputs: #[-1, number of links]
# encoder_inputs: (number of links, batch_size, 1)
# Global inp: (batch_size, 1)
import tensorflow as tf
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn_ops
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import variable_scope as vs
from tensorflow.python.util import nest
import numpy as np
import pandas as pd
import h5py
import os
def load_data(path):
train_data = np.load(path + 'train.npz')
valid_data = np.load(path + 'valid.npz')
test_data = np.load(path + 'test.npz')
train_data_list = [train_data['x'], train_data['y']]
valid_data_list = [valid_data['x'], valid_data['y']]
test_data_list = [test_data['x'], test_data['y']]
print('train x shape:\t', train_data['x'].shape)
print('train y shape:\t', train_data['y'].shape)
print('valid x shape:\t', valid_data['x'].shape)
print('valid y shape:\t', valid_data['y'].shape)
print('test x shape:\t', test_data['x'].shape)
print('test y shape:\t', test_data['y'].shape)
# train x shape: (267008, 1344, 2)
# train y shape: (267008, 336, 2)
return train_data_list, valid_data_list, test_data_list
def get_train_valid_test(data, batch_size, num_all_days, n_links, train_r=0.8, valid_r=0.1, test_r=0.1):
shape =data[0].shape
x = num_all_days
print('------------------x:\t', x)
print('------------------data:\t', shape)
# print(data[0].shape)
train_data, valid_data, test_data = [[]]*len(data), [[]]*len(data), [[]]*len(data)
for i in range(len(data)):
num_train = int(x * train_r) * n_links
num_train_valid =int(x * (train_r + valid_r)) * n_links
num_all = x * n_links
ind_train = range(num_train)
ind_valid = range(num_train, num_train_valid)
ind_test = range(num_train_valid, num_all)
train_data[i] = data[i][ind_train, :, :]
valid_data[i] = data[i][ind_valid, :, :]
test_data[i] = data[i][ind_test, :, :]
print('train_data shape:\t', train_data[0].shape)
print('valid_data shape:\t', valid_data[0].shape)
print('test_data shape:\t', test_data[0].shape)
return train_data, valid_data, test_data
def get_lstm_flow_data(region, data_path, batch_size, p, n_days, steps_of_one_day):
# reformat traffic flow data from BJ
speedMatrix = np.load(data_path + 'all_amapHK_speedMatrix.npz')
speedMatrix = speedMatrix['x']
input_scale_1, input_scale_7, labels = [], [[]]*p, []
if 1:
# for k in range(len(data_1)):
# speedMatrix = np.array(data_1[k])
print('original size:\t', speedMatrix.shape)
speedMatrix = np.transpose(speedMatrix)
speedMatrix = np.expand_dims(speedMatrix, axis=-1)
(x, y, z) = speedMatrix.shape
print("x, y, z", x, y, z)
print(steps_of_one_day*int(x / steps_of_one_day))
speedMatrix = np.array(speedMatrix[:steps_of_one_day*int(x / steps_of_one_day), :, :])
print(speedMatrix.shape)
(x, y, z) = speedMatrix.shape
speedMatrix = np.transpose(speedMatrix, [1, 0, 2])
print(speedMatrix.shape)
# speedMatrix = np.array(speedMatrix.tolist())
speedMatrix = np.expand_dims(speedMatrix, axis=1)
print('speedMatrix size:\t', speedMatrix.shape) #(5000, 1, 1488, 1)
speedMatrix = np.concatenate(np.split(speedMatrix, int(x / steps_of_one_day), axis=2), axis = 1) # split by day
print('size after split:\t', speedMatrix.shape) #(1024, 101, 48, 2)
num_all_days = speedMatrix.shape[1] - p - n_days
n_links = speedMatrix.shape[0]
speedMatrix = np.transpose(speedMatrix, [3, 0, 1, 2]) # 2, 1024, 101, 48
print('speedMatrix size before sperating:\t', speedMatrix.shape) # (1, 5000, 31, 720)
speedMatrix = speedMatrix[:, :, :, 270:570]
print('speedMatrix size before sperating:\t', speedMatrix.shape) # (1, 5000, 31, 720)
used_steps_of_one_day = speedMatrix.shape[-1]
# traing input
for i in range(n_days, int(x / steps_of_one_day)-p):
# print(speedMatrix[i - n_days: i][0].type)
tmp_sam = speedMatrix[:, :, i - n_days: i, :]
tmp_sam = np.reshape(tmp_sam, [tmp_sam.shape[0], tmp_sam.shape[1], n_days * used_steps_of_one_day])
# print('tmp_samshape:\t', tmp_sam.shape) # (2, 1, 1024, 1344)
tmp_sam_label = speedMatrix[:, :, i : i+p, :]
tmp_sam_label = np.reshape(tmp_sam_label, [tmp_sam_label.shape[0], tmp_sam_label.shape[1], p * used_steps_of_one_day])
if input_scale_1 == []:
input_scale_1 = tmp_sam
else:
input_scale_1 = np.concatenate([input_scale_1, tmp_sam], axis = 1)
if labels == []:
labels = tmp_sam_label
else:
labels = np.concatenate([labels, tmp_sam_label], axis = 1)
input_scale_1 = np.asarray(input_scale_1)
labels = np.asarray(labels)
print('input_scale_1:\t', input_scale_1.shape)
input_scale_1 = np.transpose(input_scale_1, [1, 2, 0])
labels = np.transpose(labels, [1, 2, 0])
# input_scale_1 = np.expand_dims(input_scale_1, axis=-1)
# labels = np.expand_dims(labels, axis=-1)
print('input_scale_1:\t', input_scale_1.shape)
print('labels:\t', labels.shape)
print(input_scale_1.max())
print(input_scale_1.min())
data = [input_scale_1, labels]
# """
train_data, valid_data, test_data = get_train_valid_test(data, batch_size, num_all_days, n_links)
[x_train, y_train] = train_data
[x_valid, y_valid] = valid_data
[x_test, y_test] = test_data
output_dir = '/public/hezhix/DataParse/DurationPre/Data/unScale/%s/lstm2lstm_all_amapHK/' % region
mkdir_file(output_dir)
for cat in ["train", "valid", "test"]:
_x, _y = locals()["x_" + cat], locals()["y_" + cat]
print(cat, "x: ", _x.shape, "y:", _y.shape)
np.savez_compressed(
os.path.join(output_dir, "%s.npz" % cat),
x=_x,
y=_y)
return train_data, valid_data, test_data
def load_taxiBJ_data(batch_size, region):
data_1 = [[]] *4
for i in range(13, 17): # from year 2013 to 2016
file_path = '/public/hezhix/DataParse/DurationPre/dnn/TrafficPre/DeepST/data/TaxiBJ/BJ%d_M32x32_T30_InOut.h5' % i
f = h5py.File(file_path)
j = 0
for ke in f.keys():
if j == 0:
temp = f.get(ke).value
temp = temp.reshape(temp.shape[0], temp.shape[1], int(temp.shape[2]) * int(temp.shape[3]))
temp = temp.transpose([0, 2, 1])
data_1[i-13] = temp
# data_1[i-13] = tp_dset.read_direct(arr)
print(temp.shape)
else:
pass
j +=1
print('j:\t', j)
max_val = np.max([data_1[0].max(), data_1[1].max(), data_1[2].max(), data_1[3].max()])
print(max_val)
data_1 = data_1 / max_val
p = 7
n_days = 28
steps_of_one_day = 48
print('data:\t', data_1[0].shape)
train_data,valid_data, test_data = get_lstm_flow_data(region, data_1, batch_size, p, n_days, steps_of_one_day)
print('train_data shape:\t', train_data[0].shape)
print('valid_data shape:\t', valid_data[0].shape)
print('test_data shape:\t', test_data[0].shape)
# print(train_data[0])
return train_data,valid_data, test_data
def load_taxiBJ_data_split(batch_size, region, split_id):
data_1 = [[[]]*4] *4
max_val = 1292
for i in range(13, 17):
file_path = '/public/hezhix/DataParse/DurationPre/dnn/TrafficPre/DeepST/data/TaxiBJ/BJ%d_M32x32_T30_InOut.h5' % i
f = h5py.File(file_path)
j = 0
for ke in f.keys():
if j == 0:
temp = f.get(ke).value
temp = np.array(temp.tolist())
temp = temp / max_val
temp_split_1 = np.split(temp, 2, axis = 2)
k = 0
for temp_split in temp_split_1:
temp_split_2 = np.split(temp_split, 2, axis = 3)
for temp_split_3 in temp_split_2:
print(temp_split_3.shape)
temp_split_3 = temp_split_3.reshape(temp_split_3.shape[0], temp_split_3.shape[1], int(temp_split_3.shape[2]) * int(temp_split_3.shape[3]))
temp_split_3 = np.transpose(temp_split_3, [0, 2, 1])
print(temp_split_3.shape)
print('\n')
data_1[k][i-13] = temp_split_3
k += 1
# print(temp.shape)
else:
pass
j +=1
print('j:\t', j)
split_data = [[]] * 4
for ii in range(len(data_1)):
split_data[ii] = data_1[ii]
data_need = split_data[split_id]
# max_val = np.max([data_need[0].max(), data_need[1].max(), data_need[2].max(), data_need[3].max()])
# print(max_val)
# data_need = data_need / max_val
pre = 7
n_days = 28
steps_of_one_day = 48
region = region + '%s' % split_id
train_data,valid_data, test_data = get_lstm_flow_data(region, data_need, batch_size, pre, n_days, steps_of_one_day)
def load_bikeNYC_data(batch_size, region):
file_path = '/public/hezhix/DataParse/DurationPre/dnn/TrafficPre/DeepST/data/BikeNYC/NYC14_M16x8_T60_NewEnd.h5'
#
f = h5py.File(file_path)
j = 0
for ke in f.keys():
if j == 0:
temp = f.get(ke).value
temp = temp.reshape(temp.shape[0], temp.shape[1], int(temp.shape[2]) * int(temp.shape[3]))
temp = temp.transpose([0, 2, 1])
data_1= temp
print(temp.shape)
else:
pass
j +=1
print('j:\t', j)
print(data_1)
print(data_1.shape)
data_2 = np.array(data_1.tolist()) # for maximun value
max_val = np.max(data_2)
print(max_val)
data_1 = data_1 / max_val
data = [[]]
data[0] = data_1
pre = 7
n_days = 28
steps_of_one_day = 24
train_data,valid_data, test_data = get_lstm_flow_data(region, data, batch_size, pre, n_days, steps_of_one_day)
# print(train_data[0])
return train_data,valid_data, test_data
def Linear(args,
output_size,
bias,
bias_initializer=None,
kernel_initializer=None):
"""Linear map: sum_i(args[i] * W[i]), where W[i] is a variable.
Args:
args: a 2D Tensor or a list of 2D, batch x n, Tensors.
output_size: int, second dimension of W[i].
bias: boolean, whether to add a bias term or not.
bias_initializer: starting value to initialize the bias
(default is all zeros).
kernel_initializer: starting value to initialize the weight.
Returns:
A 2D Tensor with shape [batch x output_size] equal to
sum_i(args[i] * W[i]), where W[i]s are newly created matrices.
Raises:
ValueError: if some of the arguments has unspecified or wrong shape.
"""
if args is None or (nest.is_sequence(args) and not args):
raise ValueError("`args` must be specified")
if not nest.is_sequence(args):
args = [args]
# Calculate the total size of arguments on dimension 1.
total_arg_size = 0
# print('***************args:\t%s' % args)
shapes = [a.get_shape() for a in args]
for shape in shapes:
if shape.ndims != 2:
raise ValueError(
"linear is expecting 2D arguments: %s" % shapes)
if shape[1].value is None:
raise ValueError("linear expects shape[1] to be provided for shape %s, "
"but saw %s" % (shape, shape[1]))
else:
total_arg_size += shape[1].value
dtype = [a.dtype for a in args][0]
# Now the computation.
scope = vs.get_variable_scope()
# print('*******************scope:\t%s' % scope.original_name_scope)
# weights = tf.Variable([total_arg_size, output_size],
# dtype=tf.float32,
# name='kernel',
# initializer=kernel_initializer)
with vs.variable_scope(scope) as outer_scope:
# with vs.variable_scope(scope, reuse=tf.AUTO_REUSE) as outer_scope:
# print('*************outer_scope:\t%s' % outer_scope.original_name_scope)
weights = vs.get_variable(
"kernel",
[total_arg_size, output_size],
dtype=dtype,
initializer=kernel_initializer)
if len(args) == 1:
res = math_ops.matmul(args[0], weights)
else:
res = math_ops.matmul(array_ops.concat(args, 1), weights)
if not bias:
return res
with vs.variable_scope(outer_scope) as inner_scope:
inner_scope.set_partitioner(None)
if bias_initializer is None:
bias_initializer = init_ops.constant_initializer(
0.0, dtype=dtype)
biases = vs.get_variable(
"bias", [output_size],
dtype=dtype,
initializer=bias_initializer)
return nn_ops.bias_add(res, biases)
def load_link_static_attr_pickle_to_df(location):
file_path = '/public/hezhix/DataParse/DurationPre/Data/Scale/HongKong_721/line_link_static_attr_df_%s.npy' % location
if location == 'Los':
file_path = '/public/hezhix/DataParse/DurationPre/Data/Scale/%s_721/line_link_static_attr_df_%s.npy' % (location, location)
link_static_attr_np = np.load(file_path)
print('static_attr shape:\t', link_static_attr_np.shape)
return link_static_attr_np
def load_data_seq2seq(input_path, mode, n_steps_encoder, n_steps_decoder):
global_inp_index=np.load(
input_path+"{}_{}_{}_global_inp_index.npy".format(mode, n_steps_encoder, n_steps_decoder))
endid = 0 - n_steps_encoder - n_steps_decoder
global_inp_index = global_inp_index[: endid]
global_inp_index=global_inp_index.astype(int)
print(global_inp_index.shape)
print('load --%s-- data successfully!!!\n' % mode)
return [global_inp_index]
def load_global_inputs(input_path1, mode, n_steps_encoder, n_steps_decoder):
global_inputs=np.load(
input_path1 +"{}_{}_{}_samples_input_data_without_nan.npy".format(mode, n_steps_encoder, n_steps_decoder))
print('global_inputs.shape:\t', global_inputs.shape)
# print('-----load global_inputs successfully!!')
print('load --base-- data successfully!!!\n')
return global_inputs
def load_encoder_inputs(input_path1, state_path, mode, n_steps_encoder, n_steps_decoder):
encoder_inputs=np.load(
input_path1 +"{}_{}_{}_samples_input_data_without_nan.npy".format(mode, n_steps_encoder, n_steps_decoder))
print('encoder_inputs.shape:', encoder_inputs.shape)
# print('-----load encoder_inputs successfully!!')
self_attn_states=np.load(
state_path + "{}_{}_1_spatial_attn_states.npy".format(mode, n_steps_encoder))
self_attn_states=self_attn_states[:,:,:,:n_steps_encoder]
print('self_attn_states.shape:', self_attn_states.shape)# [990,617,1,10]
print('load --base-- data successfully!!!\n')
return encoder_inputs, self_attn_states
def load_grid_features(path):
grid_features = np.load(path)
return grid_features
def basic_hyperparams():
return tf.contrib.training.HParams(
# GPU arguments
gpu_id='0',
# model parameters
learning_rate=1e-3,
lambda_l2_reg=1e-3,
gc_rate=2.5, # to avoid gradient exploding
dropout_rate=0.3,
n_stacked_layers=2,
s_attn_flag=True,
t_attn_flag=True,
external_flag=1,
gru_flag=0,
grid_flag=1,
static_attr_flag=1,
# encoder parameter
ass_n_links=0,
n_links=323,
n_input_encoder=1, # nuber of local series features of each sensors
n_steps_encoder=10, # time steps
n_grid = 8,
grid_cnn_output_size=64,
n_hidden_encoder=256, # size of hidden units
# decoder parameter
n_input_decoder=323,
n_external_input=5,
n_steps_decoder=1, # predict 1 time slot
n_hidden_decoder=256,
n_static_attr_output=64,
n_output_decoder=2 # size of the decoder output
)
def count_total_params():
""" count the parameters in the model """
total_parameters = 0
for variable in tf.trainable_variables():
# shape is an array of tf.Dimension
shape = variable.get_shape()
# print(shape)
# print(len(shape))
variable_parameters = 1
for dim in shape:
# print(dim)
variable_parameters *= dim.value
# print(variable_parameters)
total_parameters += variable_parameters
print(total_parameters)
def shuffle_data(training_data, n_steps_encoder, n_steps_decoder):
""" shuffle data"""
# print('---------------training_data[0].shape[0]:\t%s' % training_data[-1].shape[0])
shuffle_index = np.random.permutation(training_data[0].shape[0])
new_training_data = []
for inp in training_data:
new_training_data.append(inp[shuffle_index])
return new_training_data
def mkdir_file(file_path):
directory = os.path.dirname(file_path)
if not os.path.exists(directory):
os.makedirs(directory)
def get_lstm_flow_data_speed(speedMatrix, batch_size, region, region_dict):
print('original size:\t', speedMatrix.shape)
(x, y, z) = speedMatrix.shape
speedMatrix = np.squeeze(speedMatrix)
s_to_e =[0, 202]
if region in ['HK-KL', 'ST', 'TM']:
s_to_e = region_dict[region]
else:
print('need input rational region name')
return
speedMatrix = speedMatrix[s_to_e[0]: s_to_e[1], :]
speedMatrix = np.transpose(speedMatrix)
speedMatrix = speedMatrix/ np.max(speedMatrix)
# speedMatrix = np.split(speedMatrix, int(z / 144), axis=1) # split by day
# print('size after split:\t', speedMatrix.shape)
# traing input
p = 7
n_days = 28
input_scale_1, input_scale_7, labels = [], [[]]*p, []
for i in range(n_days * 144, len(speedMatrix) - p* 144, 144):
# print(list(range(i-28, i, 7)))
# print(slice(i-28, i, 7))
input_scale_1.append(speedMatrix[i - n_days * 144: i, :])
# for j in range(config.pre):
# input_scale_7[j].append(speedMatrix[slice(i-28+j, i, 7)])
labels.append(speedMatrix[i: (i + p * 144), :])
input_scale_1 = np.asarray(input_scale_1)
labels = np.asarray(labels)
num_all_days = input_scale_1.shape[1]
# input_scale_1 = np.expand_dims(input_scale_1, axis=-1)
# labels = np.expand_dims(labels, axis=-1)
print('encoder_inputs:\t', input_scale_1.shape)
print('labels:\t', labels.shape)
print(input_scale_1.max())
print(input_scale_1.min())
data = [input_scale_1, labels]
train_data, valid_data, test_data = get_train_valid_test(data, batch_size, steps_of_one_day)
return train_data, valid_data, test_data
def get_batch_input_dict(model, train_data):
feed_dict = {
model.phs['encoder_inputs']: train_data[0],
model.phs['labels']: train_data[1]}
return feed_dict
# training_data= [mode_local_inp, global_inp_index, global_attn_index, mode_ext_inp, mode_labels]
def get_batch_feed_dict(model, k, batch_size, training_data, global_inputs, n_steps_encoder, n_steps_decoder):
""" get feed_dict of each batch in a training epoch"""
train_global_inp_ind = training_data[0]
batch_global_inp = train_global_inp_ind[k:k + batch_size]
enc_tmp = []
for j in batch_global_inp:
enc_tmp.append(
global_inputs[j: j + n_steps_encoder, :])
enc_tmp = np.array(enc_tmp)
dec_tmp = []
for j in batch_global_inp:
dec_tmp.append(
global_inputs[j + n_steps_encoder:\
j + n_steps_encoder + n_steps_decoder, :])
dec_tmp = np.array(dec_tmp)
# print(enc_tmp.shape)
# print(dec_tmp.shape)
# print('\n')
# # feed_dict
feed_dict = {model.phs['encoder_inputs']: enc_tmp,
model.phs['labels']: dec_tmp}
return feed_dict
def get_valid_batch_feed_dict(model, valid_indexes, k, valid_data, valid_global_inputs, n_steps_encoder, n_steps_decoder):
""" get feed_dict of each batch in the validation set"""
valid_global_inp_ind = valid_data[0]
batch_global_inp = valid_global_inp_ind[valid_indexes[k]:valid_indexes[k + 1]]
# get encoder_inputs
enc_tmp = []
for j in batch_global_inp:
enc_tmp.append(
valid_global_inputs[j: j + n_steps_encoder, :])
enc_tmp = np.array(enc_tmp)
# get decoder_inputs
dec_tmp = []
for j in batch_global_inp:
dec_tmp.append(
valid_global_inputs[j + n_steps_encoder: j + n_steps_encoder + n_steps_decoder, :])
dec_tmp = np.array(dec_tmp)
# feed_dict
feed_dict = {model.phs['encoder_inputs']: enc_tmp,
model.phs['labels']: dec_tmp}
return feed_dict
def override_from_dict(self, values_dict):
"""Override hyperparameter values, parsing new values from a dictionary.
Args:
values_dict: Dictionary of name:value pairs.
Returns:
The `HParams` instance.
Raises:
ValueError: If `values_dict` cannot be parsed.
"""
for name, value in values_dict.items():
self.set_hparam(name, value)
return self
def to_var(var):
if torch.is_tensor(var):
var = Variable(var)
if torch.cuda.is_available():
var = var.cuda()
return var
if isinstance(var, int) or isinstance(var, float):
return var
if isinstance(var, dict):
for key in var:
var[key] = to_var(var[key])
return var
if isinstance(var, list):
var = map(lambda x: to_var(x), var)
return var
if __name__ == "__main__":
region = 'amapHK'
speed_folder = '/public/hezhix/DataParse/DurationPre/Data/unScale/' \
+ 'amapHK/speedMatrix/'
# speedMatrix = np.load(speed_folder + 're_range_amapHK_speedMatrix_without_nan.npy')
npz_dir = speed_folder + 'npz/'
"""
mkdir_file(npz_dir)
np.savez_compressed(
os.path.join(npz_dir, "amapHK_speedMatrix_without_nan.npz"),
x=speedMatrix)
"""
"""
# merge multiple data for months
data = []
for i in range(8):
sub_data = np.load(npz_dir + 'training_duration_%s.npz' % i)
print(sub_data.files)
sub_data = sub_data['x']
print(sub_data.shape) # (5000, 22320) # i = 7: (2886, 22320)
if data == []:
data = sub_data
else:
data = np.concatenate((data, sub_data), axis=0)
test_data = np.load(npz_dir + 'testing_duration.npz')
test_data = test_data['x']
print('test_data shape:\t', test_data.shape) # data shape: (37886, 22320) (n_links, len_slots)
print('data shape:\t', data.shape) # data shape: (37886, 22320) (n_links, len_slots)
data = np.concatenate((data, test_data), axis=1)
print('max:\t', data.max())
print('min:\t', data.min())
print('data shape:\t', data.shape) # data shape: (37886, 22320) (n_links, len_slots)
# compress in .npz
mkdir_file(npz_dir)
np.savez_compressed(
os.path.join(npz_dir, "all_amapHK_speedMatrix.npz"),
x=data)
path = npz_dir
# train_data = np.load(path + 'all_amapHK_speedMatrix.npz')
# print(train_data['x'].shape)
batch_size = 256
p = 1
n_days = 1
steps_of_one_day = 720
get_lstm_flow_data(region, npz_dir, batch_size, p, n_days, steps_of_one_day)
"""
PATH = '/public/hezhix/DataParse/DurationPre/Data/unScale/amapHK/lstm2lstm_all_amapHK/old/'
test_data = np.load(PATH + 'test.npz')
print(test_data['x'].shape)
<file_sep>import os
import json
import math
import pickle
import numpy as np
import pandas as pd
import tensorflow as tf
from lstm2lstm_utils import load_data
from lstm2lstm_utils import load_global_inputs
from lstm2lstm_utils import load_link_static_attr_pickle_to_df
from lstm2lstm_utils import basic_hyperparams
from lstm2lstm_utils import get_batch_feed_dict
from lstm2lstm_utils import shuffle_data
from lstm2lstm_utils import get_valid_batch_feed_dict
from lstm2lstm_utils import override_from_dict
from matplotlib import pyplot as plt
from lstm2lstm_Model import LSTM_Model, BiLSTM_Model
from lstm2lstm_utils import load_taxiBJ_data_split, load_bikeNYC_data, get_lstm_flow_data, get_batch_input_dict, load_taxiBJ_data, load_data
def root_mean_squared_error(labels, preds):
idx = np.nonzero(labels)
total_size = np.size(labels)
return np.sqrt(np.sum(np.square(labels - preds)) / total_size)
def mean_absolute_error(labels, preds):
total_size = np.size(labels)
return np.sum(np.abs(labels - preds)) / total_size
def mean_absolute_percentage_error(y_true, y_pred):
idx = np.nonzero(y_true)
return np.mean(np.abs((y_true[idx] - y_pred[idx]) / y_true[idx])) * 100
def mean_absolute_relative_error(labels, preds):
idx = np.nonzero(labels)
total_size = np.size(labels)
# print(np.sum(np.abs(labels - preds)/labels))
# print(total_size)
# print(np.min(labels))
# return np.sum(np.abs(labels - preds)/labels) / total_size
return np.mean(np.abs((labels[idx] - preds[idx]) / labels[idx])) * 100
def sy_mean_absolute_relative_error(labels, preds):
total_size = np.size(labels)
# print(np.sum(np.abs(labels - preds)/labels))
# print(total_size)
# print(np.min(labels))
# print()
return np.sum(2*np.abs(labels - preds)/(labels+preds)) / total_size
def mkdir_file(file_path):
directory = os.path.dirname(file_path)
if not os.path.exists(directory):
os.makedirs(directory)
def load_params(args):
attn_flag = [[True,True,False,False], [True,False,True,False]]
Models = ['lstm2lstm']
pre_data = {'Seattle': [{'step_size': 5, 'n_links': 323, 'speed_max': 100}],
'HongKong': [{'step_size': 10, 'n_links': 605, 'speed_max': 111}],
'NYC': [{'step_size': 60, 'n_links': 2, 'speed_max': 267}],
'Los': [{'step_size': 5, 'n_links': 207, 'speed_max': 70}],
'BJ':[{'step_size': 30, 'n_links': 2, 'speed_max': 1292}],
'BJs':[{'step_size': 30, 'n_links': 2, 'speed_max': 1292}],
'amapHK':[{'step_size': 2, 'n_links': 1, 'speed_max': 1}] }
basedModels=['LSTM', 'BiLSTM', 'GRU']
params={'location': args.location,
'cuda': args.cuda,
'isBi': args.isBi,
'mode': args.mode,
'region': args.region,
'batch_size': args.batch_size,
'model_name': Models[args.flag],
'total_epoch':args.total_epoch,
'n_hidden_encoder': args.n_hidden_encoder,
'n_steps_encoder': args.n_steps_encoder,
'dropout_rate': args.dropout_rate,
'learning_rate': args.learning_rate,
'n_links': pre_data[args.region][0]['n_links'],
'speed_max': pre_data[args.region][0]['speed_max'],
'baseModel': basedModels[args.isBi],
'args': args
}
return params
def update_hps(params):
hps = basic_hyperparams()
params['n_hidden_encoder'] = params['args'].n_hidden_encoder
hps.n_links = params['n_links']
hps.dropout_rate = params['dropout_rate']
hps.learning_rate = params['learning_rate']
hps.n_steps_encoder = params['n_steps_encoder']
hps.n_hidden_encoder = params['n_hidden_encoder']
hps.n_steps_decoder = params['args'].n_steps_decoder
return hps, params
def continue_train(params):
region = params['region']
location = params['location']
batch_size = params['batch_size']
baseModel=params['baseModel']
model_name = params['model_name']
total_epoch = params['total_epoch']
mode = params['mode']
speed_max = params['speed_max']
print('batch_size:\t', batch_size)
# path ='/public/hezhix/DataParse/DurationPre/Data/unScale/%s/speedMatrix/' % location
if 1:
np.random.seed(2017)
# use specific gpu
os.environ["CUDA_VISIBLE_DEVICES"] = params['cuda']
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
tf_config = tf.ConfigProto()
tf_config.gpu_options.allow_growth = True
session = tf.Session(config = tf_config)
hps, params = update_hps(params)
print(params)
hps.n_output_decoder = hps.n_links
# if params['isBi'] ==2:
# hps.n_hidden_decoder = params['n_hidden_encoder']
if params['isBi'] == 0:
hps.n_hidden_decoder = params['n_hidden_encoder']
if region == 'BJs':
# print(params['args'].split_id)
region = region + '%s' % params['args'].split_i
# print(region, '\n')
# train_data, valid_data, test_data = load_taxiBJ_data_split(batch_size, region, params['args'].split_id)
# if region == 'BJ':
# train_data, valid_data, test_data = load_taxiBJ_data(batch_size, region)
print(hps)
path = '/public/hezhix/DataParse/DurationPre/Data/unScale/%s/lstm2lstm_all_amapHK/' % region
print(path)
train_data, valid_data, test_data = load_data(path)
# logdir = './logs/saved_models' \
# logdir = '/data/zhixhe2/DataParse/lstm2lstm_days/logs' \
# + '/%s-b_%s-nd_%s-np_%s-lr_%4f-dr%4f-hs_%d/' % (region, batch_size, \
# 1, 1, hps.learning_rate, hps.dropout_rate, hps.n_hidden_encoder)
logdir = './logs/%s-b_%s-nd_%s-np_%s-lr_%4f-dr%4f-hs_%d/' % (region, batch_size, \
1, 1, hps.learning_rate, hps.dropout_rate, hps.n_hidden_encoder)
print('logdir:\t%s' % logdir)
model_dir = logdir
mkdir_file(logdir)
mkdir_file(model_dir)
# load speed data
# speedMatrix = np.load(path + '%s_%s_speedMatrix_without_nan.npy' % (mode, location))
# print(subpath_region)
# if region == 'BJ':
# train_data, valid_data, test_data = load_taxiBJ_data(batch_size, region)
# elif region == 'NYC':
# train_data, valid_data, test_data = load_bikeNYC_data(batch_size, region)
num_train = len(train_data[0])
num_valid = len(valid_data[0])
num_test = len(test_data[0])
print('train samples:\t{0}'.format(num_train))
print('eval samples:\t{0}'.format(num_valid))
print('test samples:\t{0}'.format(num_test))
if 1:
# model construction
tf.reset_default_graph()
if params['isBi']==0:
train_model = LSTM_Model(hps)
if params['isBi']==1:
train_model = BiLSTM_Model(hps)
if params['isBi']==2:
train_model = LSTM_Model(hps)
print('build model successfully')
# # print trainable params
# for i in tf.trainable_variables():
# print(i)
# print all placeholders
# hps = [x for x in tf.get_default_graph().get_operations()
# if x.type =="Placeholder"]
# count the parameters in our model
total_parameters = 0
for variable in tf.trainable_variables():
# shape is an array of tf.Dimension
shape = variable.get_shape()
variable_parameters = 1
for dim in shape:
variable_parameters *= dim.value
total_parameters += variable_parameters
print('total parameters: {}'.format(total_parameters))
# train params
display_iter = 500
save_log_iter = 100
# n_split_valid = 200 # times of splitting validation set
valid_losses = [np.inf]
# training process
print(' ==========================================epcho {}'.format(total_epoch))
with tf.Session() as sess:
saver = tf.train.Saver()
summary_writer = tf.summary.FileWriter(logdir)
# initialize
train_model.init(sess)
if os.path.exists(model_dir + 'checkpoint'): #判断模型是否存在
saver.restore(sess, model_dir+'final_model.ckpt') #存在就从模型中恢复变量
iter = 0
for i in range(total_epoch):
print('-------------------epcho {}----------------------'.format(i))
train_data = shuffle_data(train_data, hps.n_steps_encoder, hps.n_steps_decoder)
print(model_dir)
for l in range(0, num_train, batch_size):
batch_train_data = [[]] * len(train_data)
iter+=1
for j in range(len(train_data)): # 10
batch_train_data[j] = train_data[j][l: l + batch_size]
train_model.batch_size = batch_train_data[j].shape[0]
# print('batch_train_data[j].shape:\t', batch_train_data[j].shape)
feed_dict = get_batch_input_dict(train_model, batch_train_data)
_, merged_summary = sess.run(
[train_model.phs['train_op'], train_model.phs['summary']], feed_dict)
if iter % save_log_iter ==0:
print(iter / save_log_iter)
summary_writer.add_summary(merged_summary, iter)
if iter % display_iter ==0:
# train_loss = sess.run(train_model.phs['loss'], input_feed_dict)
# print('training loss:\t%s' % train_loss)
valid_loss = 0
batch_valid_data = [[]] * len(valid_data)
# print('start epoch-%s valid batch!!!' % i)
for l_ in range(0, num_valid, batch_size):
batch_valid_data = [[]] * len(valid_data)
for j_ in range(len(valid_data)):
batch_valid_data[j_] = valid_data[j_][l_: l_ + batch_size]
train_model.batch_size = batch_valid_data[j_].shape[0]
valid_feed_dict = get_batch_input_dict(train_model, batch_valid_data)
batch_loss = sess.run(train_model.phs['loss'], valid_feed_dict)
valid_loss += batch_loss
valid_loss /= int(num_valid / batch_size)
valid_losses.append(valid_loss)
valid_loss_sum = tf.Summary(
value = [tf.Summary.Value(tag = "valid_loss", simple_value = valid_loss)])
summary_writer.add_summary(valid_loss_sum, iter)
if valid_loss < min(valid_losses[:-1]):
print('iter {}\tvalid_loss = {:.6f}\tmodel saved!!'.format(
iter, valid_loss))
saver.save(sess, model_dir +
'model_{}.ckpt'.format(iter))
saver.save(sess, model_dir + 'final_model.ckpt')
else:
print('iter {}\tvalid_loss = {:.6f}\t'.format(
iter, valid_loss))
print('stop training !!!')
def test_model_all_all(params):
print('======================++++++++++++++++++test')
region = params['region']
location = params['location']
batch_size = params['batch_size']
baseModel=params['baseModel']
model_name = params['model_name']
total_epoch = params['total_epoch']
mode = params['mode']
speed_max = params['speed_max']
print('batch_size:\t', batch_size)
if 1:
np.random.seed(2017)
# use specific gpu
# os.environ["CUDA_VISIBLE_DEVICES"] = params['cuda']
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
tf_config = tf.ConfigProto()
tf_config.gpu_options.allow_growth = True
session = tf.Session(config = tf_config)
hps, params = update_hps(params)
hps.n_output_decoder = hps.n_links
# if params['isBi'] ==2:
# hps.n_hidden_decoder = params['n_hidden_encoder']
if region == 'BJs':
# print(params['args'].split_id)
region = region + '%s' % params['args'].split_id
# print(region, '\n')
# train_data, valid_data, test_data = load_taxiBJ_data_split(batch_size, region, params['args'].split_id)
path = '/public/hezhix/DataParse/DurationPre/Data/unScale/%s/lstm2lstm_all_amapHK/' % region
train_data, valid_data, test_data = load_data(path)
# logdir = './logs/saved_models' \
# logdir = '/data/zhixhe2/DataParse/lstm2lstm_days/logs' \
"""
logdir = '/public/hezhix/DataParse/DurationPre/dnn/Baselines/lstm2lstm_amap/scripts/logs' \
+ '/%s-b_%s-nd_%s-np_%s-lr_%4f-dr%4f-hs_%d/' % (region, batch_size, \
1, 1, hps.learning_rate, hps.dropout_rate, hps.n_hidden_encoder)
"""
logdir = './logs/%s-b_%s-nd_%s-np_%s-lr_%4f-dr%4f-hs_%d/' % (region, batch_size, \
1, 1, hps.learning_rate, hps.dropout_rate, hps.n_hidden_encoder)
print('logdir:\t%s' % logdir)
model_dir = logdir
mkdir_file(logdir)
mkdir_file(model_dir)
train_data, valid_data, test_data = load_data(path)
loop_num = 2
am_rmses = np.zeros((loop_num))
am_maes = np.zeros((loop_num))
am_MAREs = np.zeros((loop_num))
am_sMAREs = np.zeros((loop_num))
pm_rmses = np.zeros((loop_num))
pm_maes = np.zeros((loop_num))
pm_MAREs = np.zeros((loop_num))
pm_sMAREs = np.zeros((loop_num))
decoders = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
thefile = open(model_dir + 'test_res.txt', 'a')
if os.path.exists(model_dir + 'checkpoint'): #判断模型是否存在
num_test = len(test_data[0])
print('test samples: {0}'.format(num_test))
# model construction
tf.reset_default_graph()
if params['isBi']==0:
test_model = LSTM_Model(hps)
if params['isBi']==1:
test_model = BiLSTM_Model(hps)
if params['isBi']==2:
test_model = LSTM_Model(hps)
saver = tf.train.Saver()
# # print trainable params
# for i in tf.trainable_variables():
# print(i)
n_split_test = 200 # times of splitting test set
# restore model
print("Starting loading model...")
with tf.Session() as sess:
test_model.init(sess)
saver.restore(sess, model_dir+'final_model.ckpt') #存在就从模型中恢复变量
print('restore successfully')
test_loss = 0
batch_test_data = [[]] * len(test_data)
preds = []
for l_ in range(0, num_test, batch_size):
batch_test_data = [[]] * len(test_data)
for j_ in range(len(test_data)):
batch_test_data[j_] = test_data[j_][l_: l_ + batch_size]
# print(batch_test_data[j_].shape)
# print('start batch!!!')
# print(batch_test_data[j_].shape)
test_feed_dict = get_batch_input_dict(test_model, batch_test_data)
batch_preds = sess.run(test_model.phs['preds'], test_feed_dict)
batch_preds = np.array(batch_preds)
# print(batch_preds.shape) # (168, 256, 2)
if preds == []:
preds=batch_preds
# print(len(preds))
else:
# print(batch_preds.shape)
preds=np.concatenate((preds, batch_preds), axis=1)
preds = np.transpose(np.array(preds), [1, 0, 2])
labels = test_data[1]
# preds = np.transpose(preds, [1, 0, 2])
labels = labels * speed_max
preds = preds * speed_max
# 1896,168,2) (44856,256,2)
# print(labels.shape)
# print(preds.shape)
# preds = np.reshape(preds, [preds.shape[0]*preds.shape[1], -1])*speed_max
# labels = np.reshape(labels, [labels.shape[0]*labels.shape[1], -1])*speed_max
print('reshape labels:\t', labels.shape)
loop_num=2
pred_path = model_dir + '%s_preds_%s.npz' % (region, model_name)
gt_path = model_dir + '%s_gt_%s.npz' % (region, model_name)
print('pred_path', pred_path)
print('gt_path', gt_path)
np.savez_compressed(pred_path, pred=preds)
np.savez_compressed(gt_path, gt=labels)
test_maes = mean_absolute_error(labels, preds)
test_rmses = root_mean_squared_error(labels, preds)
test_MAREs = mean_absolute_relative_error(labels, preds)
test_sMAREs = sy_mean_absolute_relative_error(labels, preds)*100
print('test_maes:\t', test_maes)
print('test_rmses:\t', test_rmses)
thefile.write('all\t%s\t%s\t' % \
(region, model_name))
thefile.write('epoch-%s\t%.6f\t%.6f\t%.6f\t%.6f' % \
(total_epoch, speed_max, test_rmses, test_maes, test_MAREs))
thefile.write('\n')
else:
print('%s\nchedkpoint not exists!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!' % model_dir)
def test_model_rush(params):
print('======================++++++++++++++++++test')
subpath = params['subpath']
location = params['location']
batch_size = params['batch_size']
baseModel=params['baseModel']
model_name = params['model_name']
total_epoch = params['total_epoch']
# link_ids = params['link_ids']
mode = params['mode']
subpath_region = params['subpath_region']
if subpath in ['HongKong_HK', 'HongKong_KL', 'HongKong_HK-KL']:
params['speed_max'] = 88
if subpath in ['HongKong_ST', 'HongKong_TM']:
params['speed_max'] = 111
speed_max = params['speed_max']
am_tmp_path = './logs/rush_hour/am_%s_results_%s_%s.txt' % (params['location'], baseModel, params['subpath'])
pm_tmp_path = './logs/rush_hour/pm_%s_results_%s_%s.txt' % (params['location'], baseModel, params['subpath'])
mkdir_file(am_tmp_path)
mkdir_file(pm_tmp_path)
am_thefile = open(am_tmp_path, 'a')
pm_thefile = open(pm_tmp_path, 'a')
# for n_steps_decoder in [3, 6, 9, 12]:
if 1:
n_steps_decoder = params['args'].n_steps_decoder
np.random.seed(2017)
# use specific gpu
os.environ["CUDA_VISIBLE_DEVICES"] = params['cuda']
tf_config = tf.ConfigProto()
tf_config.gpu_options.allow_growth = True
session = tf.Session(config = tf_config)
link_ids = params['link_ids']
hps, params = update_hps(params)
if params['isBi'] ==2:
hps.n_hidden_decoder = params['n_hidden_encoder']
if params['isBi'] == 0:
hps.n_hidden_decoder = params['n_hidden_encoder']
if params['isBi'] == 1:
hps.n_hidden_decoder = 2*params['n_hidden_encoder']
hps.n_steps_decoder = n_steps_decoder
hps.n_output_decoder = hps.n_links
print(hps)
if hps.static_attr_flag and hps.grid_flag:
model_name += '-gr'
elif hps.static_attr_flag:
model_name += '-g'
elif hps.grid_flag:
model_name += '-r'
print('model_name:\t%s' % model_name)
logdir = '/data/zhixhe2/DataParse/GeoMan_my/STNN/logs/{}_721/{}/{}-{}/encoder_{}-decoder_{}/'.format(location,
subpath,
subpath_region,
baseModel,
hps.n_steps_encoder,
hps.n_steps_decoder) \
+ 'epoch_{}-{}/grid_{}_{}_{}-ext_{}-static_{}_{}/{}-{}-{}-{}-{:.3f}-{:.4f}/'.format(total_epoch,
params['n_split_link'],
hps.grid_flag,
hps.n_grid,
hps.grid_cnn_output_size,
hps.external_flag,
hps.static_attr_flag,
hps.n_static_attr_output_size,
model_name,
batch_size,
hps.n_hidden_decoder,
hps.n_stacked_layers,
hps.dropout_rate,
hps.learning_rate)
model_dir = logdir
input_path = '/public/hezhix/DataParse/DurationPre/Data/Scale/%s_721/' % (location)
input_path1 = input_path + '%s_steps_encoder/%s_steps_decoder/%s/%s/' % \
(hps.n_steps_encoder, hps.n_steps_decoder, subpath, mode)
# state_path = input_path + '%s_steps_decoder/%s/%s/' % (hps.n_steps_decoder, subpath_region, mode)
state_path = '/public/hezhix/DataParse/DurationPre/Data/Scale/%s_721/%s_steps_encoder/1_steps_decoder/%s/%s/' % (location, hps.n_steps_encoder, subpath, mode)
# print(model_dir)
print('-----------------1')
loop_num = len(link_ids)
am_rmses = np.zeros((loop_num))
am_maes = np.zeros((loop_num))
am_MAREs = np.zeros((loop_num))
am_sMAREs = np.zeros((loop_num))
pm_rmses = np.zeros((loop_num))
pm_maes = np.zeros((loop_num))
pm_MAREs = np.zeros((loop_num))
pm_sMAREs = np.zeros((loop_num))
if os.path.exists(model_dir+'saved_models/checkpoint'): #判断模型是否存在
test_data = load_data(input_path, input_path1,
'test',
hps.n_steps_encoder,
hps.n_steps_decoder,
hps.n_grid,
params['region'])
global_inputs_test, self_attn_states_test = load_global_inputs(input_path1,
state_path,
'test',
hps.n_steps_encoder,
hps.n_steps_decoder)
static_attr = load_link_static_attr_pickle_to_df(params['region'])
num_test = len(test_data[0])
print('test samples: {0}'.format(num_test))
# model construction
tf.reset_default_graph()
if params['isBi']==0:
model = LSTM_Model(hps)
if params['isBi']==1:
model = BiLSTM_Model(hps)
if params['isBi']==2:
model = LSTM_Model(hps)
saver = tf.train.Saver()
n_split_test = 500 # times of splitting test set
# restore model
print("Starting loading model...")
with tf.Session() as sess:
model.init(sess)
saver.restore(sess, model_dir+'saved_models/final_model.ckpt') #存在就从模型中恢复变量
print('restore successfully')
test_loss = 0
test_indexes = np.int64(
np.linspace(0, num_test, n_split_test))
for k in range(n_split_test - 1):
feed_dict = get_valid_batch_feed_dict(
model, test_indexes, k, test_data, global_inputs_test, self_attn_states_test, static_attr)
batch_preds = sess.run(model.phs['preds'], feed_dict)
if k==0:
preds=batch_preds
else:
preds=np.concatenate((preds, batch_preds), axis=1)
preds = np.transpose(preds, [1, 0, 2])
preds=preds*speed_max # num_test, n_steps_decoder, loop_num
labels = test_data[4]*speed_max
# try:
# np.save('./logs/%s_%s_preds.npy' % (subpath_region, baseModel), preds)
# np.save('./logs/%s_%s_labels.npy' % (subpath_region, baseModel), labels)
indices = range(labels.shape[0])
# prepare indices for am and pm
am_idx = []
pm_idx = []
for i in range(1, int(labels.shape[0]/144)):
am_idx.append(list(range(97+42+i*144, 97+42+18+i*144)))
pm_idx.append(list(range(97+96+i*144, 97+96 + 18 + i*144)))
am_idx = np.array(am_idx)
am_idx = am_idx.flatten()
pm_idx = np.array(pm_idx)
pm_idx = pm_idx.flatten()
am_idx = am_idx.tolist()
pm_idx = pm_idx.tolist()
# print('labels.shape')
# print(labels.shape)
# print(preds.shape)
# for loop_idx in range(loop_num):
# true_speed = labels[:, :, loop_idx]
# preds_speed = preds[:, :, loop_idx]
# # ground truth
# am_true_speed = np.reshape(true_speed[am_idx], [true_speed[am_idx].shape[0] * n_steps_decoder])
# pm_true_speed = np.reshape(true_speed[pm_idx], [true_speed[pm_idx].shape[0] * n_steps_decoder])
# # prediction results
# am_preds_speed = np.reshape(preds_speed[am_idx], [preds_speed[am_idx].shape[0] * n_steps_decoder])
# pm_preds_speed = np.reshape(preds_speed[pm_idx], [preds_speed[pm_idx].shape[0] * n_steps_decoder])
# if loop_idx == 0:
# print(true_speed[am_idx].shape) # 636* 12
# print(true_speed[pm_idx].shape)
# print(pm_preds_speed.shape)
# print(am_preds_speed.shape)
for horizon in [2, 5, 8, 11]:
for loop_idx in range(loop_num):
true_speed = labels[:, horizon, loop_idx]
# print(true_speed.shape)
preds_speed = preds[:, horizon, loop_idx] # pred of the last step
# print(preds_speed.shape)
# ground truth
am_true_speed = np.reshape(true_speed[am_idx], [true_speed[am_idx].shape[0]])
pm_true_speed = np.reshape(true_speed[pm_idx], [true_speed[pm_idx].shape[0]])
# prediction results
am_preds_speed = np.reshape(preds_speed[am_idx], [preds_speed[am_idx].shape[0]])
pm_preds_speed = np.reshape(preds_speed[pm_idx], [preds_speed[pm_idx].shape[0]])
if loop_idx == 0:
print(true_speed[am_idx].shape) # 636* 12
print(true_speed[pm_idx].shape)
print(pm_preds_speed.shape)
print(am_preds_speed.shape)
# print(am_true_speed)
# print(pm_true_speed)
# print(pm_preds_speed)
# print(am_preds_speed)
# metrics for am
# print(mean_absolute_error(am_true_speed, am_preds_speed))
am_maes[loop_idx] = mean_absolute_error(am_true_speed, am_preds_speed)
am_rmses[loop_idx] = root_mean_squared_error(am_true_speed, am_preds_speed)
am_MAREs[loop_idx] = mean_absolute_relative_error(am_true_speed, am_preds_speed)
am_sMAREs[loop_idx] = sy_mean_absolute_relative_error(am_true_speed, am_preds_speed)
# print(mean_absolute_error(pm_true_speed, pm_preds_speed))
# print('\n')
# metrics for pm
pm_maes[loop_idx] = mean_absolute_error(pm_true_speed, pm_preds_speed)
pm_rmses[loop_idx] = root_mean_squared_error(pm_true_speed, pm_preds_speed)
pm_MAREs[loop_idx] = mean_absolute_relative_error(pm_true_speed, pm_preds_speed)
pm_sMAREs[loop_idx] = sy_mean_absolute_relative_error(pm_true_speed, pm_preds_speed)
print('metric shape')
# print(pm_maes)
# print(am_maes)
pm_thefile.write('\n%s\tgrid_%s_%s_%s\text_%s\tstatic_%s_%s\t\n%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t' % (\
horizon + 1, params['args'].grid_flag, hps.n_grid, hps.grid_cnn_output_size,\
hps.external_flag, params['args'].static_attr_flag, hps.n_static_attr_output_size,\
params['subpath'], params['subpath_region'], params['n_steps_encoder'], \
n_steps_decoder, model_name, baseModel, hps.external_flag, batch_size, \
hps.n_hidden_encoder, hps.dropout_rate, hps.learning_rate, hps.n_stacked_layers))
pm_thefile.write('epoch-%s\t%.6f\t%.6f\t%.6f\t%.6f\t%f\n' % \
(total_epoch, speed_max, np.mean(am_rmses), np.mean(am_maes), \
np.mean(am_MAREs), np.mean(am_sMAREs)))
pm_thefile.write('%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t' % \
(params['subpath'], params['subpath_region'], params['n_steps_encoder'],\
n_steps_decoder, model_name, baseModel, hps.external_flag, batch_size, \
hps.n_hidden_encoder, hps.dropout_rate, hps.learning_rate, hps.n_stacked_layers))
pm_thefile.write('epoch-%s\t%.6f\t%.6f\t%.6f\t%.6f\t%f\n' % \
(total_epoch, speed_max, np.mean(pm_rmses), np.mean(pm_maes), \
np.mean(pm_MAREs), np.mean(pm_sMAREs)))
am_thefile.write('%s\tgrid_%s_%s_%s\text_%s\tstatic_%s_%s\tMean\tepoch-%s\t%.6f\t%.6f\t%.6f\t%.6f\t%f\n' % \
(horizon+1, params['args'].grid_flag, hps.n_grid, hps.grid_cnn_output_size, \
hps.external_flag, params['args'].static_attr_flag, hps.n_static_attr_output_size,\
total_epoch, speed_max, 0.5*(np.mean(am_rmses) + np.mean(pm_rmses)),\
0.5*(np.mean(am_maes)+ np.mean(pm_maes)), 0.5* ( np.mean(am_MAREs)+ np.mean(pm_MAREs)),\
0.5*(np.mean(am_sMAREs)+np.mean(pm_sMAREs))))
print('epoch-%s\t%.6f\t%.6f\t%.6f\t%.6f\t%f\n' % \
(total_epoch, speed_max, np.mean(am_rmses), np.mean(am_maes), \
np.mean(am_MAREs), np.mean(am_sMAREs)))
print('epoch-%s\t%.6f\t%.6f\t%.6f\t%.6f\t%f\n' % \
(total_epoch, speed_max, np.mean(pm_rmses), np.mean(pm_maes), \
np.mean(pm_MAREs), np.mean(pm_sMAREs)))
else:
print('final_model not exists..')
<file_sep>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from tensorflow.python.layers import base
def root_mean_squared_error(labels, preds):
total_size = tf.to_float(tf.size(labels))
return tf.sqrt(tf.reduce_sum(tf.square(labels - preds)) / total_size)
def mean_absolute_error(labels, preds):
total_size = 1. * tf.to_float(tf.size(labels))
return tf.reduce_sum(tf.abs(labels - preds)) / total_size
def mean_squared_error(labels, preds):
total_size = tf.to_float(tf.size(labels))
return tf.reduce_sum(tf.squared_difference(labels, preds)) / total_size
class BaseModel(base.Layer):
def __init__(self, hps, mode='train'):
self.phs = {} # placeholders
self.hps = hps
self.mode = mode
self.lambda_l2_reg = tf.constant(hps.lambda_l2_reg, dtype=tf.float32)
with tf.variable_scope('inputs'):
# the input of global spatial attention, [batch_size, n_steps_encoder, n_links]
self.phs['encoder_inputs'] = tf.placeholder(tf.float32,
[None, hps.n_steps_encoder,
hps.n_links],
name='encoder_inputs')
with tf.variable_scope('groundtruth'):
# Ground truth, [batch_size, n_steps_decoder, n_output_decoder], if no multi-task, n_output_decoder = 1
self.phs['labels'] = tf.placeholder(tf.float32,
[None, hps.n_steps_decoder,
hps.n_output_decoder],
name='labels')
self.phs['preds'] = None
def build(self):
pass
@property
def get_metric(self):
metric_list = [root_mean_squared_error(self.phs['labels'], self.phs['preds']),
mean_absolute_error(self.phs['labels'], self.phs['preds'])]
return metric_list
def get_loss(self):
pass
def get_l2reg_loss(self):
pass
@property
def loss(self):
with tf.variable_scope('Loss'):
return self.get_loss() + self.get_l2reg_loss()
@property
def train_op(self):
pass
def init(self, sess):
sess.run(tf.global_variables_initializer())
def summary(self, hps):
pass
def mod_fn(self):
pass
<file_sep>python ../main.py --region amapHK --opt 2 --cuda 0 --flag 0 --total_epoch 100;
<file_sep># -*- coding: utf-8 -*-
"""
# Created on July 6, 2018
@author zhixianghe
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
from base_model import BaseModel
from tensorflow.contrib import rnn
from tensorflow.python.framework import dtypes
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn_ops
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import variable_scope as vs
from tensorflow.python.util import nest
from six.moves import xrange
from six.moves import zip
from lstm2lstm_utils import Linear
def input_transform(encoder_inputs, decoder_inputs, n_links, n_steps_encoder, n_steps_decoder, n_output_decoder):
# transform the inputs from global view into encoder_inputs
# print(encoder_inputs.shape)
_encoder_inputs = tf.transpose(encoder_inputs, [1, 0, 2])
_encoder_inputs = tf.reshape(_encoder_inputs, [-1, n_links])
_encoder_inputs = tf.split(_encoder_inputs, n_steps_encoder, 0) #segment a row into small batches
# print('encoder_inputs[0][0].shape:\t', _encoder_inputs[0][0].get_shape())
encoder_inputs=_encoder_inputs
# since we have only one travel time (traffic speed) series,
# attention_input (local features) is SAME as the series which we are going to predict
# transform the variables into listgs as the input of different function
_decoder_inputs = tf.transpose(decoder_inputs, [1, 0, 2])
_decoder_inputs = tf.reshape(_decoder_inputs, [-1, n_output_decoder])
_decoder_inputs = tf.split(_decoder_inputs, n_steps_decoder, 0)
# not useful when the loop function is employed
decoder_inputs=[tf.zeros_like(
_decoder_inputs[0], dtype=tf.float32, name="GO")] + _decoder_inputs[:-1]
return encoder_inputs, decoder_inputs
def grid_spatial_cnn_model(grid_features, cnn_output_size): # dynamical spatial features
""" Model function for CNN. """
# Input layer
input_layer = grid_features
# input_layer = tf.reshape(grid_features, [-1, 8, 8, 1])
# print(input_layer)
# Convolutional layer #1
filter1 = tf.get_variable('spatial_weights', [3, 3, 1, 64], \
initializer=tf.truncated_normal_initializer(stddev=5e-2, dtype=tf.float32), dtype=tf.float32)
conv1 = nn_ops.conv2d(input_layer, filter1, strides = [1,1,1,1], padding = 'SAME')
## We shall be using max-pooling.
# This is 2x2 max-pooling, which means that we
# consider 2x2 windows and select the largest value
# in each window. Then we move 2 pixels to the next window.
layer = tf.nn.max_pool(value=conv1,
ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1],
padding='SAME')
# Dense layer, also called fully connected layer
pool_flat = tf.reshape(layer, [-1, layer.get_shape()[1] * layer.get_shape()[2] * layer.get_shape()[3]])
with vs.variable_scope("GridOutputProjection"):
dense = tf.contrib.layers.fully_connected(pool_flat, cnn_output_size, activation_fn=tf.nn.relu)
return dense
def spatial_static_cnn_model(static_attr, cnn_output_size):
""" Model function for CNN. """
# Input layer
input_layer = tf.reshape(static_attr, [1, 8, 8, 5])
# Convolutional layer #1
filter1 = tf.get_variable('static_attr_weights', [3, 3, 5, 32], \
initializer=tf.truncated_normal_initializer(stddev=5e-2, dtype=tf.float32), dtype=tf.float32)
conv1 = nn_ops.conv2d(input_layer, filter1, strides = [1,1,1,1], padding = 'SAME')
## We shall be using max-pooling.
layer = tf.nn.max_pool(value=conv1,
ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1],
padding='SAME')
# Dense layer, also called fully connected layer
pool_flat = tf.reshape(layer, [1, -1])
with vs.variable_scope("static_GridOutputProjection"):
static_dense = tf.contrib.layers.fully_connected(pool_flat, cnn_output_size, activation_fn = tf.nn.relu)
return static_dense
def static_attr_fcl_model(static_attr, fcl_output_size):
""" Model function for FCL on static link attr. """
pool_flat = tf.reshape(static_attr, [1, -1])
with vs.variable_scope("static_OutputProjection"):
output = tf.contrib.layers.fully_connected(pool_flat, 4*fcl_output_size, activation_fn=None)
output = tf.contrib.layers.batch_norm(output)
output = tf.nn.relu(output)
output = tf.contrib.layers.fully_connected(output, 2*fcl_output_size, activation_fn=None)
output = tf.contrib.layers.batch_norm(output)
output = tf.nn.relu(output)
output = tf.contrib.layers.fully_connected(output, fcl_output_size, activation_fn=None)
output = tf.contrib.layers.batch_norm(output)
output = tf.nn.relu(output)
return output
class LSTM_Model(BaseModel):
"""docstring for LSTM_Model"""
def __init__(self, hps, mode='train'):
super(LSTM_Model, self).__init__(hps, mode)
preds=self.mod_fn()
self.phs['preds'] = preds
self.phs['loss'] = self.get_loss() # see at eq.[11]
tf.add_to_collection('loss', self.phs['loss'])
self.phs['train_op'] = self.train_op()
self.phs['summary'] = self.summary()
def general_encoder(self, encoder_inputs, cell, output_size=None, dtype=dtypes.float32, scope=None):
# check inputs
if not encoder_inputs:
raise ValueError(
"Must provide at least 1 input to attention encoder.")
if output_size is None:
output_size=cell.output_size
batch_size=array_ops.shape(encoder_inputs[0])[0]
# how to get initial state
initial_state_size=array_ops.stack([batch_size, output_size])
initial_state_one=[array_ops.zeros(
initial_state_size, dtype=dtype) for _ in xrange(2)]
initial_state=[
initial_state_one for _ in range(len(cell._cells))]
state=initial_state
# cell = tf.nn.rnn_cell.GRUCell(2)
outputs=[]
i=0
# print ('encoder_inputs:\t', encoder_inputs)
for s_inp in zip(encoder_inputs):
# print(s_inp)
if i>0:
vs.get_variable_scope().reuse_variables()
cell_output, state=cell(s_inp[0], state)#
#output projection
with vs.variable_scope("OutputProjection"):
output=cell_output
outputs.append(output)
i+=1
# print('...............................state')
# print(state)
# print('...............................outputs')
# print(outputs)
return outputs, state
def temporal_attention(self,
decoder_inputs,
grid_features,
decoder_external_inputs,
s_attn_weights,
initial_state,
attention_states,
cell,
static_attr_dense,
loop_function=None,
external_flag=0,
s_attn_flag = 0,
t_attn_flag=0,
grid_flag=0,
static_attr_flag=0,
output_size=None,
dtype=tf.float32,
scope=None,
initial_state_attention=False,
):
"""
Temporal attention in LSTM_Model
"""
# print('<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<')
# if self.hps.s_attn_flag=='1':
# print('s_attn_flag')
if not decoder_inputs:
raise ValueError(
"Please give at leat 1 input to temporal attention decoder.")
if not decoder_external_inputs:
raise ValueError(
"Please give at least 1 ext_input to temporal attention decoder.")
if output_size is None:
output_size=cell.output_size
print('============================cell_output_size:\t', output_size)
# implement of temporal attention
with vs.variable_scope(
scope or "temporal_attn", dtype=dtype) as scope:
dtype=scope.dtype
batch_size=array_ops.shape(decoder_inputs[0])[0]
t_attn_length=attention_states.get_shape()[1].value
if t_attn_length is None:
t_attn_length=array_ops.shape(attention_states)[1]
t_attn_size=attention_states.get_shape()[2].value
hidden=array_ops.reshape(attention_states,
[-1, t_attn_length, 1, t_attn_size])
# Size of state vector for attention
t_attn_vec_size=t_attn_size
w=vs.get_variable(
"Attn_Wd", [1,2,t_attn_size, t_attn_vec_size]) # W_d
hidden_feature=nn_ops.conv2d(
hidden, w, [1, 1,1,1], "SAME") #W_d * h_o
v=vs.get_variable("Attn_v",[t_attn_vec_size]) # v_d
state = initial_state
def temporal_attention_weight(query):
"""
Put attention masks on self_hidden using self_hidden_features and query.
"""
if nest.is_sequence(query):
query_list=nest.flatten(query)
for q in query_list:
ndims=q.get_shape().ndims
if ndims:
assert ndims==2
query = array_ops.concat(query_list, 1)
# print('*************8***********state:\t%s' % tf.shape(state[0]))
with vs.variable_scope("Attn_Wpd"):
# Linear map
y=Linear(query, t_attn_vec_size, True)
y=array_ops.reshape(
y, [-1,1,1,t_attn_vec_size])
# Attention mask is a softmax of v_d^{\top} * tanH(...)
s=math_ops.reduce_sum(v*math_ops.tanh(hidden_feature + y + 1e-10),
[2, 3])
a=nn_ops.softmax(s)
d=math_ops.reduce_sum(
array_ops.reshape(a, [-1,t_attn_length, 1, 1])* hidden, [1,2])
return array_ops.reshape(d, [-1, t_attn_size])
if initial_state_attention:
t_attn=temporal_attention_weight(inital_state) # temporal attention vector
else:
batch_attn_size=array_ops.stack([batch_size, t_attn_size])
t_attn=array_ops.zeros(batch_attn_size, dtype=dtype)
t_attn.set_shape([None, t_attn_size])
i=0
outputs=[]
prev=None
for inp, ext_inp in zip(decoder_inputs, decoder_external_inputs):
# print(inp)
if i>0:
vs.get_variable_scope().reuse_variables()
# If loop_function is set, we use it instead of decoder_inputs.
if loop_function is not None and prev is not None:
# with vs.get_variable_scope("loop_function", reuse=True):
with vs.variable_scope("loop_function", reuse=True):
inp=loop_function(prev, i)
# print('----------inp')
# print(inp)
# Merge input and previous attentions into one vector of the right size.
# print(inp.get_shape())
input_size = inp.get_shape().with_rank(2)[1]
if input_size.value is None:
raise ValueError(
"Could not infer input size from input: %s" % inp.name)
grid_flag = 0
# we map the concatenation to shape [batch_size, input_size]
if external_flag and t_attn_flag:
x = Linear([inp] + [ext_inp] + [t_attn], input_size, True)
elif t_attn_flag:
x = Linear([inp] + [t_attn], input_size, True)
else:
x = Linear([inp], input_size, True)
cell_output, state = cell(x, state) # query: cell state
static_dense= tf.tile(static_attr_dense, [batch_size, 1]) #self attention vector
# Run the attention mechanism.
if i == 0 and initial_state_attention:
with vs.variable_scope(vs.get_variable_scope(), reuse=True):
t_attn = temporal_attention_weight(state)
else:
t_attn = temporal_attention_weight(state)
with vs.variable_scope("AttnOutputProjection"):
if t_attn_flag and static_attr_flag:
fclInput = tf.concat([cell_output, t_attn, static_dense], 1)
elif static_attr_flag:
fclInput = tf.concat([cell_output, t_attn], 1)
else:
fclInput = cell_output
output = tf.contrib.layers.fully_connected(fclInput, output_size, activation_fn=tf.nn.relu)
# output = tf.contrib.layers.batch_norm(output)
# output = tf.nn.relu(output)
# print('---=============================arrived at loop_function')
if loop_function is not None:
prev = output
outputs.append(output)
i += 1
return outputs, state
def general_decoder(self, decoder_inputs, initial_state, cell, loop_function=None, output_size=None, dtype=tf.float32, scope=None, initial_state_attention=False):
"""
"""
if not decoder_inputs:
raise ValueError(
"Please give at leat 1 input to temporal attention decoder.")
if output_size is None:
output_size=cell.output_size
print('============================cell_output_size:\t', output_size)
# implement of temporal attention
with vs.variable_scope(
scope or "general_decoder", dtype=dtype) as scope:
dtype=scope.dtype
batch_size=array_ops.shape(decoder_inputs[0])[0]
state = initial_state
i=0
outputs=[]
prev=None
# print ('decoder_inputs:\t', decoder_inputs)
for inp in zip(decoder_inputs):
# print(inp)
if i>0:
vs.get_variable_scope().reuse_variables()
# # If loop_function is set, we use it instead of decoder_inputs.
# if loop_function is not None and prev is not None:
# # with vs.get_variable_scope("loop_function", reuse=True):
# with vs.variable_scope("loop_function", reuse=True):
# inp=loop_function(prev, i)
# x = tf.reshape(inp[0], [-1, self.hps.n_links])
# print('decoder cell inputs:\t', inp)
cell_output, state = cell(inp[0], state) # query: cell state
with vs.variable_scope("AttnOutputProjection"):
output = tf.contrib.layers.fully_connected(cell_output, output_size, activation_fn=tf.nn.relu)
if loop_function is not None:
prev = output
outputs.append(output)
i += 1
return outputs, state
def _loop_function(self, prev, _):
"""loop function used in the decoder to generate the next inupt"""
return tf.matmul(prev, self.phs['w_out']) + self.phs['b_out']
def mod_fn(self):
encoder_inputs, decoder_inputs \
= input_transform(self.phs['encoder_inputs'],
self.phs['labels'],
self.hps.n_links,
self.hps.n_steps_encoder,
self.hps.n_steps_decoder,
self.hps.n_output_decoder)
n_stacked_layers = self.hps.n_stacked_layers # num of layer stacked in RNN
# dimension of encoder hidden/cell state
n_hidden_encoder = self.hps.n_hidden_encoder
# dimension of decoder hidden/cell state
n_hidden_decoder = self.hps.n_hidden_decoder
dropout_rate = self.hps.dropout_rate # dropout rate in RNN unit
n_output_decoder = self.hps.n_output_decoder
# Define weights in the transformation layer of decoder
self.phs['w_out'] = tf.get_variable('Weights_out',
[n_hidden_decoder, n_output_decoder],
dtype=tf.float32,
initializer=tf.truncated_normal_initializer())
self.phs['b_out'] = tf.get_variable('Biases_out',
shape=[n_output_decoder],
dtype=tf.float32,
initializer=tf.constant_initializer(0.))
# print('hps.s_attn_flag:\t%s' % self.hps.s_attn_flag)
with tf.variable_scope('LSTM_Model'):
# the implement of encoder
with tf.variable_scope('Encoder'):
cells = []
for i in range(n_stacked_layers):
with tf.variable_scope('LSTM_{}'.format(i)):
# tf.nn.rnn_cell.LSTMCell
# tf.nn.rnn_cell.LSTMCell(name='basic_lstm_cell',
# cell = tf.nn.rnn_cell.LSTMCell(name='basic_lstm_cell',
cell = tf.nn.rnn_cell.LSTMCell(
n_hidden_encoder, forget_bias=1.0, state_is_tuple=True)
cell = tf.nn.rnn_cell.DropoutWrapper(
cell, output_keep_prob=1.0 - dropout_rate)
cells.append(cell)
encoder_cell = tf.contrib.rnn.MultiRNNCell(cells)
encoder_outputs, encoder_state=self.general_encoder(encoder_inputs,
encoder_cell)
# attn_weights = 0
# # Calculate a concatenation of encoder outputs to put attention on.
# top_states = [tf.reshape(e, [-1, 1, encoder_cell.output_size])
# for e in encoder_outputs]
# attention_states = tf.concat(top_states, 1) #hidden states from t1 to T
# the implement of decoder
print('starting decoder----------------------------')
with tf.variable_scope('Decoder'):
cells = []
for i in range(n_stacked_layers):
with tf.variable_scope('LSTM_{}'.format(i)):
# cell = tf.nn.rnn_cell.LSTMCell(name='basic_lstm_cell',
cell = rnn.BasicLSTMCell(
n_hidden_decoder,
forget_bias=1.0,
state_is_tuple=True)
cell = tf.nn.rnn_cell.DropoutWrapper(cell,
output_keep_prob=1.0 - dropout_rate)
cells.append(cell)
decoder_cell = tf.contrib.rnn.MultiRNNCell(cells)
# using FCL over static_attr
decoder_outputs, states = self.general_decoder(decoder_inputs,
encoder_state, # as initial state for decoder
decoder_cell,
loop_function=self._loop_function,
)
# generate outputs
with tf.variable_scope('Prediction'):
preds = [tf.matmul(i, self.phs['w_out']) +
self.phs['b_out'] for i in decoder_outputs]
return preds
def get_loss(self):
"""MSE loss"""
# reshape
n_steps_decoder = self.phs['labels'].get_shape()[1].value
n_output_decoder = self.phs['labels'].get_shape()[2].value
labels = tf.transpose(self.phs['labels'], [1, 0, 2])
labels = tf.reshape(labels, [-1, n_output_decoder])
labels = tf.split(labels, n_steps_decoder, 0)
# compute empirical loss
empirical_loss = 0
# Extra: we can also get separate error at each future time slot
# print(self.phs)
for _y, _Y in zip(self.phs['preds'], labels):
empirical_loss += tf.reduce_mean(tf.pow(_y - _Y , 2))
self.phs['empirical_loss'] = empirical_loss
# print(empirical_loss)
return empirical_loss
def get_l2reg_loss(self):
"""l2 reg loss"""
reg_loss = 0
for tf_var in tf.trainable_variables():
if 'kernel:' in tf_var.name or 'bias:' in tf_var.name:
reg_loss += tf.reduce_mean(tf.nn.l2_loss(tf_var))
return self.lambda_l2_reg * reg_loss
def train_op(self):
# Training optimizer
with tf.variable_scope('Optimizer'):
global_step = tf.Variable(
initial_value=0,
name="global_step",
trainable=False,
collections=[tf.GraphKeys.GLOBAL_STEP,
tf.GraphKeys.GLOBAL_VARIABLES])
optimizer = tf.contrib.layers.optimize_loss(
loss=self.phs['loss'],
learning_rate=self.hps.learning_rate,
global_step=global_step,
optimizer="Adam",
clip_gradients=self.hps.gc_rate)
return optimizer
def summary(self):
tf.summary.scalar("loss", self.phs['loss'])
for var in tf.trainable_variables():
tf.summary.histogram(var.name, var)
return tf.summary.merge_all()
class BiLSTM_Model(BaseModel):
# """docstring for BiLSTM_Model"""
def __init__(self, hps, mode='train'):
super(BiLSTM_Model, self).__init__(hps, mode)
preds=self.mod_fn()
self.phs['preds'] = preds
self.phs['loss'] = self.get_loss() # see at eq.[11]
tf.add_to_collection('loss', self.phs['loss'])
self.phs['train_op'] = self.train_op()
self.phs['summary'] = self.summary()
def my_self_attention(self,
encoder_inputs,
grid_features,
attention_states,
cell,
grid_flag=0,
output_size=None,
dtype=dtypes.float32,
scope=None
):
"""self attention in BiLSTM_Model
@param encoder_inputs: encoder_inputs - the inputs of self attention,
i.e., a list of 2d tensor with shape of [batch_size, n_links]
@param attention_states: global_attention_states-
4D tensor [batch_size, n_links, n_steps_encoder]
@return: A tuple of form (outputs, state), where:
"""
# check inputs
if not encoder_inputs:
raise ValueError(
"Must provide at least 1 input to attention encoder.")
if output_size is None:
output_size=cell.output_size
if attention_states.get_shape()[0:2].is_fully_defined():
raise ValueError('Shape[1] and Shape[2] of attention_states must be know: %s'\
% attention_states.get_shape())
batch_size=array_ops.shape(encoder_inputs[0])[0]
with vs.variable_scope('self_attn'):
s_attn_length=attention_states.get_shape()[1].value
s_n_inputs=attention_states.get_shape()[2].value
s_attn_size=attention_states.get_shape()[3].value
# print('attention_states.shape: \t%s', attention_states.shape)
# print('s_attn_length: \t%s' % s_attn_length)
# print('s_n_inputs: \t%s' % s_n_inputs)
# print('s_attn_size: \t%s' % s_attn_size)
s_hidden=array_ops.reshape(attention_states,
[-1, s_attn_length, s_n_inputs, s_attn_size])
s_attn_vec_size=s_attn_size
self_k=vs.get_variable('AttnUs',
[1, s_n_inputs, s_attn_size,s_attn_vec_size])
s_hidden_feature=nn_ops.conv2d(
s_hidden, self_k, [1,1,1,1], "SAME") # U_s * y^l
self_v=vs.get_variable(
"AttenVs", [s_attn_vec_size])
# print('++++++++++++++++++++++++++++self_v')
# print(self_v)
batch_attn_size=array_ops.stack(
[batch_size, s_attn_length])
s_attn_fw=array_ops.zeros(batch_attn_size, dtype=dtype)
s_attn_bw=array_ops.zeros(batch_attn_size, dtype=dtype)
def self_attention_weight(state): # state: query
"""
"""
if nest.is_sequence(state):
state_list=nest.flatten(state)
for q in state_list:
ndims=q.get_shape().ndims
if ndims:
assert ndims==2
state=array_ops.concat(state_list, 1)
# print("**************state:\t" % tf.shape(state))
with tf.variable_scope("AttnWs"):
# linear map
y=Linear(state, s_attn_vec_size, True)
y=array_ops.reshape(
y, [-1,1,1,s_attn_vec_size])
# Attention mask is a softmax of v_s^{}*tanh(...)
s=math_ops.reduce_sum(#g_l^t
self_v * math_ops.tanh(s_hidden_feature+y), [2,3])
# Sometimes it's not easy to find a measurement to denote similarity between sensors,
# here we omit such prior knowledge in eq.[4].
# You can use "a = nn_ops.softmax((1-lambda)*s + lambda*sim)" to encode similarity info,
# where:
# sim: a vector with length n_sensors, describing the sim between the target sensor and the others
# lambda: a trade-off.
a = nn_ops.softmax(s)
# a = nn_ops.softmax((1 - lambda) * s + lambda * sim)
return a
# how to get initial state
initial_state_size=array_ops.stack([batch_size, output_size])
initial_state_one=[array_ops.zeros(
initial_state_size, dtype=dtype) for _ in xrange(2)]
initial_state=[
initial_state_one for _ in range(len(cell._cells))]
output_state_fw=initial_state
output_state_bw=initial_state
outputs_bw=[]
outputs_fw=[]
outputs=[]
state=[]
s_attn_weights_fw=[]
s_attn_weights_bw=[]
i=0 # time slot index
# print(len(encoder_inputs))
# forward
print('---------------------forward')
for s_inp in zip(encoder_inputs):
if i>0:
vs.get_variable_scope().reuse_variables()
# print('segmentline--------------------------')
# print(s_attn_fw.shape) #64, 617
# print(s_inp[0].get_shape()) # 10, 617
# print('segmentline--------------------------')
s_weight = tf.reshape(s_attn_fw[i], [-1, output_size], 's_weight')
S_weight = tf.reshape(tf.tile(s_weight, [batch_size, 1]), [-1, output_size])
grid_feature = grid_features[:, i, :, :, :]
grid_dense = grid_spatial_cnn_model(grid_feature, 64)
if grid_flag:
self_x= tf.concat([s_inp[0], S_weight, grid_dense], 1) #self attention vector
else:
self_x= tf.concat([s_inp[0], S_weight], 1) #self attention vector
cell_output_fw, output_state_fw=cell(self_x, output_state_fw)# hidde state, cell state
with tf.variable_scope('self_attn'):
s_attn_fw=self_attention_weight(output_state_fw)
s_attn_weights_fw.append(s_attn_fw)
with vs.variable_scope("AttentionOutput_fw_Projection"):
output=cell_output_fw
outputs_fw.append(output)
i+=1
# backward
print('---------------------backward')
# print(encoder_inputs)
for j in range(len(encoder_inputs)):
s_b_inp=encoder_inputs[len(encoder_inputs)-j-1]
# Attention output projection
if j ==len(encoder_inputs)-1:
vs.get_variable_scope().reuse_variables()
# self_x= s_attn_bw * s_b_inp[0]
s_weight = tf.reshape(s_attn_bw[i], [-1, output_size], 's_weight')
S_weight = tf.reshape(tf.tile(s_weight, [batch_size, 1]), [-1, output_size])
# self_x= tf.concat([encoder_inputs[j], S_weight], 1) #self attention vector
grid_feature = grid_features[:, j, :, :, :]
grid_dense = grid_spatial_cnn_model(grid_feature, 64)
if grid_flag:
self_x= tf.concat([encoder_inputs[j], S_weight, grid_dense], 1) #self attention vector
else:
self_x= tf.concat([encoder_inputs[j], S_weight], 1) #self attention vector
cell_output_bw, output_state_bw=cell(self_x, output_state_bw)# hidde state, cell state
with tf.variable_scope('self_attn'):
s_attn_bw=self_attention_weight(output_state_bw)
# print(s_attn_bw.get_shape())
s_attn_weights_bw.append(s_attn_bw)
with vs.variable_scope("AttentionOutput_bw_Projection"):
output=cell_output_bw
outputs_bw.append(output)
j+=1
# combine fw and bw
if isinstance(output_state_fw, rnn.LSTMStateTuple): # LstmCell
state_c = tf.concat(
(output_state_fw.c, output_state_bw.c), 1, name="bidirectional_concat_c")
state_h = tf.concat(
(output_state_fw.h, output_state_bw.h), 1, name="bidirectional_concat_h")
state = rnn.LSTMStateTuple(c=state_c, h=state_h)
elif isinstance(output_state_fw, tuple) \
and isinstance(output_state_fw[0], rnn.LSTMStateTuple): # MultiLstmCell
state = tuple(map(
lambda fw_state, bw_state: rnn.LSTMStateTuple(
c=tf.concat((fw_state.c, bw_state.c), 1,
name="bidirectional_concat_c"),
h=tf.concat((fw_state.h, bw_state.h), 1,
name="bidirectional_concat_h")),
output_state_fw, output_state_bw))
else:
state = tf.concat((output_state_fw, output_state_bw), 1, name="bidirectional_state_concat")
for k in range(len(encoder_inputs)):
outputs.append(tf.concat((outputs_fw[k], outputs_bw[len(encoder_inputs)-k-1]), 1))
return outputs, state, s_attn_weights_bw# return outputs, state, s_attn_weights
def general_encoder(self,
encoder_inputs,
cell,
output_size=None,
dtype=dtypes.float32,
scope=None
):
# check inputs
if not encoder_inputs:
raise ValueError(
"Must provide at least 1 input to attention encoder.")
if output_size is None:
output_size=cell.output_size
batch_size=array_ops.shape(encoder_inputs[0])[0]
# how to get initial state
initial_state_size=array_ops.stack([batch_size, output_size])
initial_state_one=[array_ops.zeros(
initial_state_size, dtype=dtype) for _ in xrange(2)]
initial_state=[
initial_state_one for _ in range(len(cell._cells))]
state=initial_state
initial_state_bw = state
initial_state_fw = state
outputs=[]
cell_fw = cell
cell_bw = cell
# print(len(encoder_inputs))
# print(encoder_inputs[0].get_shape())
# for s_inp in encoder_inputs:
# s_inp = tf.expand_dims(s_inp, axis=1)
i = 0
for t in encoder_inputs:
tmp= tf.expand_dims(t, axis = 1)
if i == 0:
inputs = tmp
else:
inputs = tf.concat([inputs, tmp], axis = 1 )
print(inputs.get_shape())
i +=1
# inputs = tf.concat([tf.expand_dims(t, axis = 1) for t in encoder_inputs], axis = 1)
# print('reshape inputs:\t', print(inputs.get_shape()))
outputs, state= tf.nn.bidirectional_dynamic_rnn(cell_fw,
cell_bw,
inputs,
dtype=dtype)
# cell_output, state=cell(s_inp[0], state)#
#output projection
# outputs=tf.concat(outputs, 2)
# combine fw and bw
output_state_fw = state[0]
output_state_bw = state[1]
if isinstance(output_state_fw, rnn.LSTMStateTuple): # LstmCell
state_c = tf.concat(
(output_state_fw.c, output_state_bw.c), 1, name="bidirectional_concat_c")
state_h = tf.concat(
(output_state_fw.h, output_state_bw.h), 1, name="bidirectional_concat_h")
state = rnn.LSTMStateTuple(c=state_c, h=state_h)
elif isinstance(output_state_fw, tuple) \
and isinstance(output_state_fw[0], rnn.LSTMStateTuple): # MultiLstmCell
state = tuple(map(
lambda fw_state, bw_state: rnn.LSTMStateTuple(
c=tf.concat((fw_state.c, bw_state.c), 1,
name="bidirectional_concat_c"),
h=tf.concat((fw_state.h, bw_state.h), 1,
name="bidirectional_concat_h")),
output_state_fw, output_state_bw))
else:
state = tf.concat((output_state_fw, output_state_bw), 1, name="bidirectional_state_concat")
# for k in range(len(encoder_inputs)):
# outputs.append(tf.concat((outputs_fw[k], outputs_bw[len(encoder_inputs)-k-1]), 1))
with vs.variable_scope("OutputProjection"):
outputs=outputs
return outputs, state
def temporal_attention(self,
decoder_inputs,
grid_features,
external_inputs,
s_attn_weights,
initial_state,
attention_states,
cell,
static_attr_dense,
loop_function=None,
external_flag=0,
s_attn_flag = 0,
t_attn_flag=0,
grid_flag=0,
static_attr_flag=0,
output_size=None,
dtype=tf.float32,
scope=None,
initial_state_attention=False,
):
""" Temporal attention in BiLSTM_Model
"""
# print('temporal_attention<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<')
# if self.hps.s_attn_flag=='1':
# print('s_attn_flag')
# if not decoder_inputs:
# raise ValueError(
# "Please give at leat 1 input to temporal attention decoder.")
# if not external_inputs:
# raise ValueError(
# "Please give at least 1 ext_input to temporal attention decoder.")
if output_size is None:
output_size=cell.output_size
# implement of temporal attention
with vs.variable_scope(
scope or "temporal_attn", dtype=dtype) as scope:
dtype=scope.dtype
batch_size=array_ops.shape(decoder_inputs[0])[0]
t_attn_length=attention_states.get_shape()[1].value
if t_attn_length is None:
t_attn_length=array_ops.shape(attention_states)[1]
t_attn_size=attention_states.get_shape()[2].value
hidden=array_ops.reshape(attention_states,
[-1, t_attn_length, 1, t_attn_size])
# Size of state vector for attention
t_attn_vec_size=t_attn_size
w=vs.get_variable(
"Attn_Wd", [1,2,t_attn_size, t_attn_vec_size]) # W_d
hidden_feature=nn_ops.conv2d(
hidden, w, [1, 1,1,1], "SAME") #W_d * h_o
v=vs.get_variable("Attn_v",[t_attn_vec_size]) # v_d
state = initial_state
def temporal_attention_weight(query):
"""
Put attention masks on self_hidden using self_hidden_features and query.
"""
if nest.is_sequence(query):
query_list=nest.flatten(query)
for q in query_list:
ndims=q.get_shape().ndims
if ndims:
assert ndims==2
query = array_ops.concat(query_list, 1)
# print('*************8***********state:\t%s' % tf.shape(state[0]))
with vs.variable_scope("Attn_Wpd"):
# Linear map
y=Linear(query, t_attn_vec_size, True)
y=array_ops.reshape(
y, [-1,1,1,t_attn_vec_size])
# Attention mask is a softmax of v_d^{\top} * tanH(...)
s=math_ops.reduce_sum(v*math_ops.tanh(hidden_feature + y + 1e-10),
[2, 3])
# cross_entropy = -tf.reduce_sum(y_*tf.log(tf.clip_by_value(y,1e-10,1.0)))
a=nn_ops.softmax(s)
d=math_ops.reduce_sum(
array_ops.reshape(a, [-1,t_attn_length, 1, 1])* hidden, [1,2])
return array_ops.reshape(d, [-1, t_attn_size])
if initial_state_attention:
t_attn=temporal_attention_weight(inital_state) # temporal attention vector
else:
batch_attn_size=array_ops.stack([batch_size, t_attn_size])
t_attn=array_ops.zeros(batch_attn_size, dtype=dtype)
t_attn.set_shape([None, t_attn_size])
# decoder for labels
i=0
outputs=[]
prev=None
print('==========================decoder_inputs')
print(decoder_inputs)
for inp, ext_inp in zip(decoder_inputs, external_inputs):
# print(i)
if i>0:
vs.get_variable_scope().reuse_variables()
# If loop_function is set, we use it instead of decoder_inputs.
if loop_function is not None and prev is not None:
# with vs.get_variable_scope("loop_function", reuse=True):
with vs.variable_scope("loop_function", reuse=True):
inp=loop_function(prev, i)
# Merge input and previous attentions into one vector of the right size.
input_size = inp.get_shape().with_rank(2)[1]
if input_size.value is None:
raise ValueError(
"Could not infer input size from input: %s" % inp.name)
if external_flag and t_attn_flag:
x = Linear([inp] + [ext_inp] + [t_attn], input_size, True)
elif t_attn_flag:
x = Linear([inp] + [t_attn], input_size, True)
else:
x = Linear([inp], input_size, True)
# # Run the RNN.
cell_output, state = cell(x, state) # query: cell state
if i == 0 and initial_state_attention:
with vs.variable_scope(vs.get_variable_scope(), reuse=True):
t_attn = temporal_attention_weight(state)
else:
t_attn = temporal_attention_weight(state)
with vs.variable_scope("AttnOutputProjection"):
if t_attn_flag and static_attr_flag:
fclInput = tf.concat([cell_output, t_attn, static_attr_dense], 1)
elif t_attn_flag:
fclInput = tf.concat([cell_output, t_attn], 1)
else:
fclInput = cell_output
output = tf.contrib.layers.fully_connected(fclInput, output_size, activation_fn=tf.nn.relu)
if loop_function is not None:
prev = output
outputs.append(output)
i += 1
return outputs, state
def _loop_function(self, prev, _):
"""loop function used in the decoder to generate the next inupt"""
return tf.matmul(prev, self.phs['w_out']) + self.phs['b_out']
def mod_fn(self):
encoder_attention_states, \
encoder_inputs, decoder_inputs,\
encoder_external_inputs, decoder_external_inputs,\
grid_features, static_attr \
= input_transform(self.phs['encoder_inputs'],
self.phs['labels'], # decoder_inputs
self.phs['self_attn_states'],
self.phs['encoder_external_inputs'],
self.phs['decoder_external_inputs'],
self.phs['grid_features'],
self.phs['static_attr'])
n_stacked_layers = self.hps.n_stacked_layers # num of layer stacked in RNN
# dimension of encoder hidden/cell state
n_hidden_encoder = self.hps.n_hidden_encoder
# dimension of decoder hidden/cell state
n_hidden_decoder = self.hps.n_hidden_decoder
dropout_rate = self.hps.dropout_rate # dropout rate in RNN unit
n_output_decoder = self.hps.n_output_decoder
# Define weights in the transformation layer of decoder
self.phs['w_out'] = tf.get_variable('Weights_out',
[n_hidden_decoder, n_output_decoder],
dtype=tf.float32,
initializer=tf.truncated_normal_initializer())
self.phs['b_out'] = tf.get_variable('Biases_out',
shape=[n_output_decoder],
dtype=tf.float32,
initializer=tf.constant_initializer(0.))
# print('hps.s_attn_flag:\t%s' % self.hps.s_attn_flag)
with tf.variable_scope('BiLSTM_Model'):
# the implement of encoder
with tf.variable_scope('Encoder'):
cells = []
for i in range(n_stacked_layers):
with tf.variable_scope('LSTM_{}'.format(i)):
cell = rnn.BasicLSTMCell(
n_hidden_encoder, forget_bias=1.0, state_is_tuple=True)
cell = tf.nn.rnn_cell.DropoutWrapper(
cell, output_keep_prob=1.0 - dropout_rate)
cells.append(cell)
encoder_cell = tf.contrib.rnn.MultiRNNCell(cells)
if self.hps.s_attn_flag:
encoder_outputs, encoder_state, attn_weights = self.my_self_attention(encoder_inputs,
grid_features,
encoder_attention_states,
encoder_cell,
grid_flag=self.hps.grid_flag)
print('s_attn_flag:\t%s' % self.hps.s_attn_flag)
print(len(encoder_outputs))
print(encoder_outputs[0].get_shape()) # (?, 646)
top_states = [tf.reshape(e, [-1, 1, 2*encoder_cell.output_size])
for e in encoder_outputs]
attention_states = tf.concat(top_states, 1) #hidden states from t1 to T (?, time_lag, size): (?, 6, 646)
# print(encoder_state[0].get_shape())
else:
print('s_attn_flag:\t%s' % 'no')
encoder_outputs, encoder_state=self.general_encoder(encoder_inputs,
encoder_cell)
print(encoder_outputs[0].get_shape())
encoder_outputs = tf.concat([encoder_outputs[0], encoder_outputs[1]], axis = 2) # concat final fw hidden state and final bw state
print('prepare for temporal_attention')
attention_states = tf.concat(encoder_outputs, 1) #hidden states from t1 to T
print('attention_states.shape')
print(encoder_state)
print(attention_states.get_shape())
# the implement of decoder
with tf.variable_scope('Decoder'):
cells = []
for i in range(n_stacked_layers):
with tf.variable_scope('LSTM_{}'.format(i)):
cell = rnn.BasicLSTMCell(n_hidden_decoder,
forget_bias=1.0,
state_is_tuple=True)
cell = tf.nn.rnn_cell.DropoutWrapper(cell,
output_keep_prob=1.0 - dropout_rate)
cells.append(cell)
decoder_cell = tf.contrib.rnn.MultiRNNCell(cells)
# using FCL over static_attr
static_attr_output_size = self.hps.n_static_attr_output_size
static_attr_dense = static_attr_fcl_model(static_attr, static_attr_output_size)
decoder_outputs, states = self.temporal_attention(decoder_inputs,
grid_features,
decoder_external_inputs,
attn_weights,
encoder_state,
attention_states,
decoder_cell,
static_attr_dense,
loop_function=self._loop_function,
s_attn_flag=self.hps.s_attn_flag,
external_flag=self.hps.external_flag,
t_attn_flag=self.hps.t_attn_flag,
grid_flag=self.hps.grid_flag,
static_attr_flag=self.hps.static_attr_flag)
# print('...........................decoder_outputs')
# print(decoder_outputs)
# print('...........................decoder_state')
# print(states)
# generate outputs
with tf.variable_scope('Prediction'):
preds = [tf.matmul(i, self.phs['w_out']) +
self.phs['b_out'] for i in decoder_outputs]
return preds
def get_loss(self):
"""MSE loss"""
# reshape
n_steps_decoder = self.phs['labels'].get_shape()[1].value
n_output_decoder = self.phs['labels'].get_shape()[2].value
labels = tf.transpose(self.phs['labels'], [1, 0, 2])
labels = tf.reshape(labels, [-1, n_output_decoder])
labels = tf.split(labels, n_steps_decoder, 0)
# compute empirical loss
empirical_loss = 0
# Extra: we can also get separate error at each future time slot
# print(self.phs)
for _y, _Y in zip(self.phs['preds'], labels):
empirical_loss += tf.reduce_mean(tf.pow(_y - _Y , 2))
self.phs['empirical_loss'] = empirical_loss
# print(empirical_loss)
return empirical_loss
def get_l2reg_loss(self):
"""l2 reg loss"""
reg_loss = 0
for tf_var in tf.trainable_variables():
if 'kernel:' in tf_var.name or 'bias:' in tf_var.name:
reg_loss += tf.reduce_mean(tf.nn.l2_loss(tf_var))
return self.lambda_l2_reg * reg_loss
def train_op(self):
# Training optimizer
with tf.variable_scope('Optimizer'):
global_step = tf.Variable(
initial_value=0,
name="global_step",
trainable=False,
collections=[tf.GraphKeys.GLOBAL_STEP,
tf.GraphKeys.GLOBAL_VARIABLES])
optimizer = tf.contrib.layers.optimize_loss(
loss=self.phs['loss'],
learning_rate=self.hps.learning_rate,
global_step=global_step,
optimizer="Adam",
clip_gradients=self.hps.gc_rate)
return optimizer
def summary(self):
tf.summary.scalar("loss", self.phs['loss'])
for var in tf.trainable_variables():
tf.summary.histogram(var.name, var)
return tf.summary.merge_all()
| 29f1e85475edb53861d2ebdee9472157820677de | [
"Python",
"Shell"
] | 6 | Python | GabbyHE/lstm_amap | d354bc52b2d1f9b9ab41652a716525afedea6f7c | 51eae97477fa9c5e56b50fad211c7051ee5a4786 |
refs/heads/master | <repo_name>WillyMaikowski/KDTreeExperiment<file_sep>/src/secondary/MedianKDTreeNodeSecMem.java
package secondary;
import java.io.IOException;
import java.util.List;
import KDTree.Axis;
import KDTree.KDTree;
import KDTree.MedianXAxis;
import KDTree.Point;
import recordfile.RecordsFileException;
@SuppressWarnings( "serial" )
public class MedianKDTreeNodeSecMem extends AbstractKDTreeNodeSecMemory {
public MedianKDTreeNodeSecMem( List<Point> points ) throws IOException, RecordsFileException {
this( points, new MedianXAxis() );
}
public MedianKDTreeNodeSecMem( List<Point> points, Axis axis ) throws IOException, RecordsFileException {
super( points, axis );
}
public KDTree createNode( List<Point> points, Axis axis ) {
KDTree node = null;
try {
node = new MedianKDTreeNodeSecMem( points, axis );
}
catch( RecordsFileException|IOException e ) {
e.printStackTrace();
}
return node;
}
}
<file_sep>/README.md
KDTreeExperiment
================
Investigación para el curso "Diseño y Analisis de Algoritmos".
<file_sep>/src/secondary/AbstractKDTreeNodeSecMemory.java
package secondary;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import KDTree.Axis;
import KDTree.KDTree;
import KDTree.KDTreeLeaf;
import KDTree.Point;
import recordfile.RecordsFileException;
@SuppressWarnings( "serial" )
public abstract class AbstractKDTreeNodeSecMemory implements KDTree {
protected Axis axis;
protected KDTree right;
protected KDTree left;
public AbstractKDTreeNodeSecMemory(){
}
public AbstractKDTreeNodeSecMemory( List<Point> listofPoints, Axis axis ) throws IOException, RecordsFileException {
this.axis = axis;
this.axis.setL( listofPoints );
ArrayList<Point> p1 = new ArrayList<Point>();
ArrayList<Point> p2 = new ArrayList<Point>();
for( Point p : listofPoints )
if( this.axis.compare( p ) >= 0 ) p1.add( p );
else p2.add( p );
listofPoints = null;
Axis nAxis = axis.getPerpendicular();
if( p1.size() <= Math.pow( 2, 6.38 ) ) this.left = new MedianKDTreeNodeFile( p1, nAxis );
else if( p1.size() > 1 ) this.left = this.createNode( p1, nAxis );
p1 = null;
if( p2.size() <= Math.pow( 2, 6.38 ) ) this.right = new MedianKDTreeNodeFile( p2, nAxis );
else if( p2.size() > 1 ) this.right = this.createNode( p2, nAxis );
axis = null;
p2 = null;
}
public void reInitialize(){
this.left.reInitialize();
this.right.reInitialize();
}
public Point VecinoMasCercano( KDTree T, Point q ) {
return T.VecinoMasCercano( q );
}
public int height() {
return Math.max( this.left.height(), this.right.height() ) + 1;
}
public Point VecinoMasCercano( Point q ) {
return VecinoMasCercano( q, new Point( Double.MAX_VALUE, Double.MAX_VALUE ), Double.MAX_VALUE );
}
public Point VecinoMasCercano( Point q, Point mejorPrevio, double distMejorPrevio ) {
Point mejorActual;
double distActual;
if( this.axis.compare( q ) < 0 ) {// el eje es menor al punto => buscar a
// la derecha
mejorActual = this.right.VecinoMasCercano( q, mejorPrevio, distMejorPrevio );
distActual = q.distance( mejorActual );
if( distActual > distMejorPrevio ) {
mejorActual = mejorPrevio;
distActual = distMejorPrevio;
}
if( Math.abs( this.axis.compare( q ) ) < distActual ) {
Point mejorActualIzq = this.left.VecinoMasCercano( q );
double distActualIzq = q.distance( mejorActualIzq );
if( distActual > distActualIzq ) {
mejorActual = mejorActualIzq;
distActual = distActualIzq;
}
}
}
else {
mejorActual = this.left.VecinoMasCercano( q );
distActual = q.distance( mejorActual );
if( distActual > distMejorPrevio ) {
mejorActual = mejorPrevio;
distActual = distMejorPrevio;
}
if( Math.abs( this.axis.compare( q ) ) < distActual ) {
Point mejorActualDer = this.right.VecinoMasCercano( q );
double distActualDer = q.distance( mejorActualDer );
if( distActual > distActualDer ) {
mejorActual = mejorActualDer;
distActual = distActualDer;
}
}
}
return mejorActual;
}
public KDTree createLeaf( Point q ) {
return new KDTreeLeaf( q );
}
public int getNumAccess() {
return this.left.getNumAccess() + this.right.getNumAccess();
}
public int getLenghtOfFile() throws IOException, RecordsFileException{
return this.left.getLenghtOfFile() + this.right.getLenghtOfFile();
}
}
<file_sep>/src/KDTree/MeanYAxis.java
package KDTree;
import KDTree.Point;
import java.util.List;
@SuppressWarnings( "serial" )
public class MeanYAxis extends AbstractAxis {
public Axis getPerpendicular() {
return new MeanXAxis();
}
public void setL( List<Point> points ) {
Point min = points.get( 0 );
Point max = points.get( 0 );
for( Point p : points ) {
if( p.getY() < min.getY() ) min = p;
if( p.getY() > max.getY() ) max = p;
}
points = null;
this.coord = 1.0 * ( min.getY() + max.getY() ) / 2.0;
}
/**
* > 0 si p1 > p2 = < 0 si p1 < p2
*/
public double compare( Point p2 ) {
return this.coord - p2.getY();
}
}
<file_sep>/src/recordfile/RecordsFile.java
package recordfile;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
public class RecordsFile extends BaseRecordsFile {
/**
* Hashtable which holds the in-memory index. For efficiency, the entire
* index is cached in memory. The hashtable maps a key of type String to a
* RecordHeader.
*/
protected Hashtable<String, RecordHeader> memIndex;
/**
* Creates a new database file. The initialSize parameter determines the
* amount of space which is allocated for the index. The index can grow
* dynamically, but the parameter is provide to increase efficiency.
*/
public RecordsFile( String dbPath, int initialSize ) throws IOException,
RecordsFileException {
super( dbPath, initialSize );
memIndex = new Hashtable<String, RecordHeader>( initialSize );
}
/**
* Opens an existing database and initializes the in-memory index.
*/
public RecordsFile( String dbPath, String accessFlags ) throws IOException,
RecordsFileException {
super( dbPath, accessFlags );
int numRecords = readNumRecordsHeader();
memIndex = new Hashtable<String, RecordHeader>( numRecords );
for( int i = 0; i < numRecords; i++ ) {
String key = readKeyFromIndex( i );
RecordHeader header = readRecordHeaderFromIndex( i );
header.setIndexPosition( i );
memIndex.put( key, header );
}
}
/**
* Returns an enumeration of all the keys in the database.
*/
public synchronized Enumeration<String> enumerateKeys() {
return memIndex.keys();
}
/**
* Returns the current number of records in the database.
*/
public synchronized int getNumRecords() {
return memIndex.size();
}
/**
* Checks if there is a record belonging to the given key.
*/
public synchronized boolean recordExists( String key ) {
return memIndex.containsKey( key );
}
/**
* Maps a key to a record header by looking it up in the in-memory index.
*/
protected RecordHeader keyToRecordHeader( String key ) throws RecordsFileException {
RecordHeader h = (RecordHeader) memIndex.get( key );
if( h == null ) {
throw new RecordsFileException( "Key not found: " + key );
}
return h;
}
/**
* This method searches the file for free space and then returns a
* RecordHeader which uses the space. (O(n) memory accesses)
*/
protected RecordHeader allocateRecord( String key, int dataLength ) throws RecordsFileException, IOException {
// search for empty space
RecordHeader newRecord = null;
Enumeration<RecordHeader> e = memIndex.elements();
while( e.hasMoreElements() ) {
RecordHeader next = (RecordHeader) e.nextElement();
if( dataLength <= next.getFreeSpace() ) {
newRecord = next.split();
writeRecordHeaderToIndex( next );
break;
}
}
if( newRecord == null ) {
// append record to end of file - grows file to allocate space
long fp = getFileLength();
setFileLength( fp + dataLength );
newRecord = new RecordHeader( fp, dataLength );
}
return newRecord;
}
/**
* Returns the record to which the target file pointer belongs - meaning the
* specified location in the file is part of the record data of the
* RecordHeader which is returned. Returns null if the location is not part
* of a record. (O(n) mem accesses)
*/
protected RecordHeader getRecordAt( long targetFp ) throws RecordsFileException {
Enumeration<RecordHeader> e = memIndex.elements();
while( e.hasMoreElements() ) {
RecordHeader next = (RecordHeader) e.nextElement();
if( targetFp >= next.dataPointer
&& targetFp < next.dataPointer + (long) next.dataCapacity ) {
return next;
}
}
return null;
}
/**
* Closes the database.
*/
public synchronized void close() throws IOException, RecordsFileException {
try {
super.close();
}
finally {
memIndex.clear();
memIndex = null;
}
}
/**
* Adds the new record to the in-memory index and calls the super class add
* the index entry to the file.
*/
protected void addEntryToIndex( String key, RecordHeader newRecord, int currentNumRecords ) throws IOException, RecordsFileException {
super.addEntryToIndex( key, newRecord, currentNumRecords );
memIndex.put( key, newRecord );
}
/**
* Removes the record from the index. Replaces the target with the entry at
* the end of the index.
*/
protected void deleteEntryFromIndex( String key, RecordHeader header,
int currentNumRecords ) throws IOException, RecordsFileException {
super.deleteEntryFromIndex( key, header, currentNumRecords );
memIndex.remove( key );
}
}
<file_sep>/src/experiment/MainPointVisualization.java
package experiment;
import java.util.List;
import javax.swing.JFrame;
import draw.DrawablePoint;
import KDTree.Point;
public class MainPointVisualization {
public static void main( String[] args ) {
int c = 1;
int n = 10;
int x = (int) ( c * Math.sqrt( Math.pow( 2, n ) ) ) * 10;
int y = (int) ( c * Math.sqrt( Math.pow( 2, n ) ) ) * 10;
List<Point> randomPoints = MainExperiment.generateRandomPoints( c, n );
List<Point> lowPoints = MainExperiment.generateLowDiscrepancyPoints( c, n );
JFrame frame = new JFrame( "Random Points" );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setSize( x, y );
frame.add( new DrawablePoint( randomPoints ) );
frame.setVisible( true );
JFrame frame2 = new JFrame( "Low Discrepancy Points" );
frame2.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame2.setSize( x, y );
frame2.add( new DrawablePoint( lowPoints ) );
frame2.setVisible( true );
}
}
<file_sep>/src/KDTree/Point.java
package KDTree;
@SuppressWarnings( "serial" )
public class Point implements java.io.Serializable{
private double x;
private double y;
public Point( double x, double y ) {
super();
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public void setX( double x ) {
this.x = x;
}
public double getY() {
return y;
}
public void setY( double y ) {
this.y = y;
}
public double distance( Point q ) {
return Math.sqrt( Math.pow( this.getX() - q.getX(), 2 )
+ Math.pow( this.getY() - q.getY(), 2 ) );
}
public String toString() {
return getClass().getName() + "[x=" + x + ",y=" + y + "]";
}
}
<file_sep>/src/experiment/StructExperimentContainer.java
package experiment;
import java.util.ArrayList;
import java.util.List;
public class StructExperimentContainer {
private List<Integer> heightContainer;
private List<Long> timeContainer;
private List<Integer> sizeContainer;
private double heightSum;
private double timeSum;
private double sizeSum;
private String kdTreeName;
private String pointType;
private int n;
private int size;
public StructExperimentContainer( String kdTreeName, String pointType,
int size ) {
this.heightContainer = new ArrayList<Integer>();
this.timeContainer = new ArrayList<Long>();
this.sizeContainer = new ArrayList<Integer>();
this.heightSum = 0.0;
this.timeSum = 0.0;
this.sizeSum = 0.0;
this.kdTreeName = kdTreeName;
this.pointType = pointType;
this.n = 0;
this.size = size;
}
public double getAverageHeight() {
if( this.n > 0 ) return 1.0 * this.heightSum / this.n;
return 0.0;
}
public double getAverageTime() {
if( this.n > 0 ) return 1.0 * this.timeSum / this.n;
return 0L;
}
public double getAverageSize() {
if( this.n > 0 ) return 1.0 * this.sizeSum / this.n;
return 0.0;
}
public double getTimeStd() {
if( n == 0 ) return 0;
double avg = this.getAverageTime();
double var = 0;
for( Long time : this.timeContainer ) {
var += Math.pow( time - avg, 2 );
}
return Math.sqrt( var / this.n );
}
public double getheightStd() {
if( n == 0 ) return 0;
double avg = this.getAverageHeight();
double var = 0;
for( int height : this.heightContainer ) {
var += Math.pow( height - avg, 2 );
}
return Math.sqrt( var / this.n );
}
public double getsizeStd() {
if( n == 0 ) return 0;
double avg = this.getAverageSize();
double var = 0;
for( int size : this.sizeContainer ) {
var += Math.pow( size - avg, 2 );
}
return Math.sqrt( var / this.n );
}
public void addObservation( int height, long time, int size ) {
this.heightContainer.add( height );
this.timeContainer.add( time );
this.sizeContainer.add( size );
this.heightSum += height;
this.timeSum += time;
this.sizeSum += size;
n++;
}
public int getNumberOBservations() {
return this.n;
}
public boolean finished() {
int mayorq = 30;
return this.n >= mayorq;
}
/**
* NombreAlgoritmo tipoDePuntos size n avgHeight avgTime avgSize stdHeight
* stdTime stdSize
*
* @return
*/
//
public String getResult() {
return "[" + this.kdTreeName + "\t" + this.pointType + "\t" + this.size
+ "\t" + this.n + "\t" + this.getAverageHeight() + "\t"
+ this.getAverageTime() + "\t" + this.getAverageSize() + "\t"
+ this.getheightStd() + "\t" + this.getTimeStd() + "\t"
+ this.getsizeStd() + "\t" + "]";
}
}
<file_sep>/src/KDTree/MedianXAxis.java
package KDTree;
import KDTree.Point;
import java.util.List;
@SuppressWarnings( "serial" )
public class MedianXAxis extends AbstractAxis {
public Axis getPerpendicular() {
return new MedianYAxis();
}
public void setL( List<Point> points ) {
this.coord = this.randomizedSelect(
points.toArray( new Point[points.size()] ), 0, points.size() - 1,
points.size() / 2 );
}
private double randomizedSelect( Point[] A, int p, int r, int i ) {
if( p == r ) return A[p].getX();
int q = randomized_Partition( A, p, r );
int k = q - p + 1;
if( i == k ) return A[q].getX();
else if( i < k ) return randomizedSelect( A, p, q - 1, i );
else return randomizedSelect( A, q + 1, r, i - k );
}
private int randomized_Partition( Point[] A, int p, int r ) {
int i = this.random( p, r );
Point aux = A[i];
A[i] = A[r];
A[r] = aux;
return partition( A, p, r );
}
private int partition( Point A[], int p, int r ) {
Point pivot = A[r];
int i = p - 1;
for( int j = p; j <= r - 1; j++ ) {
if( A[j].getX() <= pivot.getX() ) {
i++;
Point dummy = A[i];
A[i] = A[j];
A[j] = dummy;
}
}
Point dummy = A[i + 1];
A[i + 1] = A[r];
A[r] = dummy;
return i + 1;
}
public double compare( Point p2 ) {
return this.coord - p2.getX();
}
}
<file_sep>/src/KDTree/KDTree.java
package KDTree;
import KDTree.Point;
import java.io.IOException;
import java.util.List;
import recordfile.RecordsFileException;
public interface KDTree extends java.io.Serializable {
public Point VecinoMasCercano( KDTree T, Point q );
public Point VecinoMasCercano( Point q );
public Point VecinoMasCercano( Point q, Point mejorPrevio, double distMejorPrevio );
public KDTree createLeaf( Point q );
public KDTree createNode( List<Point> points, Axis axis );
public int height();
public int getNumAccess();
public int getLenghtOfFile() throws IOException, RecordsFileException;
public void reInitialize();
}
<file_sep>/src/experiment/MainExperimentSecondayMemory.java
package experiment;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import recordfile.RecordsFileException;
import secondary.MedianKDTreeNodeSecMem;
import KDTree.KDTree;
import KDTree.Point;
public class MainExperimentSecondayMemory {
public static void main( String[] args ) {
int minN = 25;
int maxN = 30;
KDTree experimentTree;
long startTime;
long stopTime;
long elapsedTime;
String treeName;
String pointName;
PrintWriter writer;
double c = 1.0;
try {
// MeanKDTree con puntos de baja discrepancia
{
treeName = "MeanKDTreeSecondaryMemory";
pointName = "LowDiscrepancy";
writer = new PrintWriter( "resultados_construccion_" + treeName
+ "_" + pointName + " _" + Math.random() + ".txt" );
for( int size = minN; size <= maxN; size++ ) {
SecondaryMemoryExperimentContainer expCont = new SecondaryMemoryExperimentContainer(
treeName, pointName, (int) Math.pow( 2, size ) );
while( !expCont.finished() ) {
List<Point> listofPoints = generateLowDiscrepancyPoints( c,
size );
startTime = System.currentTimeMillis();
experimentTree = new MedianKDTreeNodeSecMem( listofPoints );
stopTime = System.currentTimeMillis();
elapsedTime = stopTime - startTime;
expCont.addObservation( experimentTree.height(), elapsedTime,
experimentTree.getLenghtOfFile(), experimentTree.getNumAccess() );
}
writer.println( expCont.getResult() );
System.out.println( "Termino 2^" + size + " " + treeName + " "
+ pointName );
}
writer.close();
}
}
catch( FileNotFoundException e ) {
e.printStackTrace();
}
catch( IOException e ) {
e.printStackTrace();
}
catch( RecordsFileException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* genera 2^n puntos al azar
*
* @param n
* @return
*/
public static List<Point> generateRandomPoints( double c, int n ) {
List<Point> result = new ArrayList<Point>();
double numPoints = Math.pow( 2, n );
for( int i = 1; i <= numPoints; i++ ) {
result.add( generateRandomPoint( 0, 0, ( c * Math.sqrt( numPoints ) ),
( c * Math.sqrt( numPoints ) ) ) );
}
return result;
}
public static List<Point> generateLowDiscrepancyPoints( double c, int n ) {
List<Point> result = new ArrayList<Point>();
double numPoints = Math.pow( 2, n );
double delta = c;
int numPuntosA = 0;
for( double i = 0; i < c * Math.sqrt( numPoints ) && numPuntosA < numPoints; i = i + delta ) {
for( double j = 0; j < c * Math.sqrt( numPoints ) && numPuntosA < numPoints; j = j + delta ) {
result.add( generateRandomPoint( i, j, i + delta, j + delta ) );
numPuntosA++;
}
}
return result;
}
public static Point generateRandomPoint( double x0, double y0, double x1,
double y1 ) {
Point result = new Point( random( x0, x1 ), random( y0, y1 ) );
return result;
}
public static double random( double i, double n ) {
return i + ( n - i ) * Math.random();
}
}
| 53cbb47742be8af2becfa196bae44e60adb03fc7 | [
"Markdown",
"Java"
] | 11 | Java | WillyMaikowski/KDTreeExperiment | 5b3ca15251ac1a3d90ded1934e859336746fa968 | 11c9af2d28e0debb6f2477e94f5a9112061d4e86 |
refs/heads/master | <file_sep>package com.softechsol.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class TargetServlet
*/
public class TargetServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public TargetServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
String userName = (String)session.getAttribute("userName");
response.getWriter().append("UserName is :" +userName);
Cookie cookies[] = request.getCookies();
for (int i = 0; i < cookies.length; i++) {
System.out.println("Cookie Name"+cookies[i].getName() + " Value : "+cookies[i].getValue());
}
session.invalidate();
}
}
| b0f27859a56c304eb4b117b68a55fa044c2fcd1a | [
"Java"
] | 1 | Java | NaeemHHassan/SessionManagementInServlets | 0c9cf289dd6b963a8fd342c8546b20fab9b87614 | 08b0167753701461fc12f7c64ca86918b8f9184a |
refs/heads/master | <repo_name>daybydae/Baxter<file_sep>/frontend/components/search/sitter_index.jsx
import React from 'react';
import SitterIndexItem from './sitter_index_item';
class SitterIndex extends React.Component {
render () {
return (
<div className="index">
<ul className="">
{
this.props.sitters.map( (sitter, idx) => {
return (
<li className="sitter-item-box" key={idx}>
<SitterIndexItem
key={sitter.id}
sitter={sitter}
num={idx}
/>
</li>
);
})
}
</ul>
</div>
);
}
}
export default SitterIndex;
<file_sep>/app/models/sitter.rb
# == Schema Information
#
# Table name: sitters
#
# id :integer not null, primary key
# sittername :string not null
# location :string not null
# rates :float not null
# description :text
# lat :float not null
# lng :float not null
# created_at :datetime not null
# updated_at :datetime not null
# image_file_name :string
# image_content_type :string
# image_file_size :integer
# image_updated_at :datetime
#
class Sitter < ApplicationRecord
validates :sittername, :location, :rates, presence: true
validates :lat, :lng, presence: true
has_attached_file :image, default_url: "pug.jpg", styles: {thumb: "500x500#"}
validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
has_many :bookings
def self.in_bounds(bounds)
lat_low = bounds["south"].to_f
lat_high = bounds["north"].to_f
lng_low = bounds["west"].to_f
lng_high = bounds["east"].to_f
Sitter.all.select { |sitter| sitter.in_bounds?(lat_low, lat_high, lng_low, lng_high)}
end
def in_bounds?(lat_low, lat_high, lng_low, lng_high)
self.lat.between?(lat_low, lat_high) && self.lng.between?(lng_low, lng_high)
end
end
<file_sep>/app/views/api/users/_user.json.jbuilder
json.extract! user, :id, :username, :email, :address, :description, :lat, :lng
json.image_thumb asset_path(user.image(:thumb))
json.image_url asset_path(user.image.url)
<file_sep>/db/seeds.rb
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
Sitter.delete_all
User.delete_all
maurice = Sitter.new(
sittername: "Maurice",
location: "107 E 105th Street, New York, NY 10029",
rates: 100.00,
description: "I'm a cool guy who loves to help Dae. Like really loves to help Dae, who happens to be a swell guy. I mean, who wouldn't want to help Dae?",
lat: 40.792145,
lng: -73.947738,
)
file = File.open("app/assets/images/maurice.jpeg")
maurice.image = file
maurice.save
david = Sitter.new(
sittername: "David",
location: "102 103rd Street, New York, NY 10029",
rates: 75.00,
description: "I'm a cool guy who loves to help Dae and walks him off cliffs on the reg.",
lat: 40.751352,
lng: -73.983934,
)
file = File.open("app/assets/images/david.jpeg")
david.image = file
david.save
matthias = Sitter.new(
sittername: "Matthias",
location: "315 E 105th Street, New York, NY 10029",
rates: 85.00,
description: "I'm the best. For reals doe.",
lat: 40.789661,
lng: -73.941932
)
file = File.open("app/assets/images/matthias.jpg")
matthias.image = file
matthias.save
al = Sitter.new(
sittername: "Al",
location: "315 East 95th Street, New York, NY 10029",
rates: 95.00,
description: "I'm out of here!!! Goodluck ya'll!",
lat: 40.783250,
lng: -73.946484,
)
file = File.open("app/assets/images/al.jpg")
al.image = file
al.save
kati = Sitter.new(
sittername: "Kati",
location: "167 Rikers Lane, New York, NY 10029",
rates: 85.00,
description: "I'm a cool girl who loves to help Dae not think he's a complete idiot.",
lat: 40.759552,
lng: -73.952109
)
file = File.open("app/assets/images/tina.jpg")
kati.image = file
kati.save
jeremiah = Sitter.new(
sittername: "Jeremiah",
location: "315 East Hipster Lane, Brooklyn, NY 11238",
rates: 95.00,
description: "I'm cool guy who loves to help Dae despite the fact I broke his brain by playing a super cruel prank on him.",
lat: 40.679823,
lng: -73.961797,
)
file = File.open("app/assets/images/jeremiah.jpg")
jeremiah.image = file
jeremiah.save
cody = Sitter.new(
sittername: "Cody",
location: "88 Main Street, Long Island, NY 11755",
rates: 55.00,
description: "I'm a super cool guy despite being from Long Island. I also love to help Dae.",
lat: 40.854553,
lng: -73.117459,
)
file = File.open("app/assets/images/cody.jpg")
cody.image = file
cody.save
luke = Sitter.new(
sittername: "Luke",
location: "100 Keep It Real Lane, Bay Shore, NY 11706",
rates: 45.00,
description: "I'm a super cool guy despite being from Long Island. I also love to help Dae.",
lat: 40.745010,
lng: -73.253987,
)
file = File.open("app/assets/images/luke.jpg")
luke.image = file
luke.save
abby = Sitter.new(
sittername: "Abby",
location: "177 Abbay Street, New York, NY 10029",
rates: 105.00,
description: "I'm a super cool girl who loves to help Dae. Also, I'm the other half of the 'Dream Team'.",
lat: 40.798192,
lng: -73.951843,
)
file = File.open("app/assets/images/abby.jpg")
abby.image = file
abby.save
matt = Sitter.new(
sittername: "Matt",
location: "100 Keep It Real Lane, Bay Shore, NY 11706",
rates: 80.00,
description: "I'm a super cool dude who loves to help Dae. Also, did you know Dae is like the coolest?",
lat: 40.761463,
lng: -73.931366,
)
file = File.open("app/assets/images/matt.jpg")
matt.image = file
matt.save
monica = Sitter.new(
sittername: "Monica",
location: "35 Treat Yo Self Ave, New York, NY 11706",
rates: 90.00,
description: "I'm a super cool girl who loves to help Dae. I have 2 cats named <NAME> and <NAME>. Yeah, you read that right.",
lat: 40.810035,
lng: -73.950426,
)
file = File.open("app/assets/images/monica.jpg")
monica.image = file
monica.save
chris = Sitter.new(
sittername: "Chris",
location: "399 MyGFMayHaveAnEelBoneInHerThroat Ave, New York, NY 11706",
rates: 90.00,
description: "I'm a super cool dood with a super cute frenchie.",
lat: 40.795352,
lng: -73.970940,
)
file = File.open("app/assets/images/chris.jpg")
chris.image = file
chris.save
dae = User.new(
username: 'dae',
password: '<PASSWORD>',
email: '<EMAIL>',
address: "10029",
description: "Super cool guy with 2 super cute but crazy dogs.",
lat: 40.789242,
lng: -73.942804
)
file = File.open("app/assets/images/tinasleep.jpg")
dae.image = file
dae.save
alison = User.new(
username: 'alison',
password: '<PASSWORD>',
email: '<EMAIL>',
address: "10029",
description: "Super cool girl with a super cute but quite large yorkie named Bougie.",
lat: 40.789242,
lng: -73.942804
)
file = File.open("app/assets/images/alison.jpg")
alison.image = file
alison.save
demo = User.new(
username: 'demo',
password: '<PASSWORD>',
email: '<EMAIL>',
address: "10029",
description: "Super cool demo with a super cute bulldog.",
lat: 40.789242,
lng: -73.942804
)
file = File.open("app/assets/images/baxtertina.jpg")
demo.image = file
demo.save
<file_sep>/frontend/components/app/app_container.js
import { connect } from 'react-redux';
import { closeDropdown } from '../../actions/app_actions';
import App from '../App';
import {toggleDropdown} from '../../actions/dropdown_actions';
import { withRouter } from 'react-router-dom';
const mapStateToProps = (state) => {
return {
currentUser: state.session.currentUser,
dropDownOpen: state.ui.dropDown.open
};
};
const mapDispatchToProps = dispatch => {
return {
toggleDropdown: () => dispatch(toggleDropdown())
};
};
export default withRouter(connect(
mapStateToProps,
mapDispatchToProps
)(App));
<file_sep>/frontend/components/nav/nav_container.jsx
import { connect } from 'react-redux';
import { login, logout, removeErrors } from '../../actions/session_actions';
import Nav from './nav';
import {toggleDropdown} from '../../actions/dropdown_actions';
const mapStateToProps = ({ session, ui }) => {
return {
currentUser: session.currentUser,
dropDownOpen: ui.dropDown.open
};
};
const mapDispatchToProps = dispatch => {
return {
logout: () => dispatch(logout()),
login: (user) => dispatch(login(user)),
removeErrors: () => dispatch(removeErrors()),
toggleDropdown: () => dispatch(toggleDropdown())
}
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(Nav);
<file_sep>/app/models/booking.rb
# == Schema Information
#
# Table name: bookings
#
# id :integer not null, primary key
# sitter_id :integer not null
# user_id :integer not null
# start_date :datetime not null
# end_date :datetime not null
# created_at :datetime not null
# updated_at :datetime not null
#
class Booking < ApplicationRecord
validates :sitter, presence: true
validates :start_date, :end_date, presence: true
validates :sitter_id, :user_id, presence: true
belongs_to :sitter
end
<file_sep>/frontend/components/bookings/booking_form_container.js
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import { createBooking, removeErrors } from '../../actions/booking_actions';
import { fetchSitter } from '../../actions/sitter_actions';
import BookingForm from './booking_form';
const mapStateToProps = (state, ownProps) => {
return {
currentUser: state.session.currentUser,
sitter: state.entities.sitters[ownProps.match.params.sitter_id] || {}
};
};
const mapDispatchToProps = (dispatch, ownProps) => {
return {
createBooking: booking => dispatch(createBooking(booking)),
fetchSitter: sitterId => dispatch(fetchSitter(sitterId))
};
};
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(BookingForm));
<file_sep>/frontend/components/sitter_show/sitter_detail.jsx
import React from 'react';
import { Link } from 'react-router-dom';
const SitterDetail = ({ sitter }) => {
return (
<div className="sitter-summary-wrap">
<div className="sitter-summary-wrap-margin-bottom-15">
<div className="sitter-summary-media">
<span className="sitter-show-profile-icon">
<img
className="sitter-profile-icon"
src={sitter.image_thumb}
/>
</span>
<div className="media-body">
<div className="sitter-name-profile">
<strong>{sitter.sittername}</strong>
</div>
<div className="sitter-neighborhood">
{sitter.location}
</div>
<div className="sitter-rating-profile">
RATING
{
// {sitter.ratings}
// {sitter.rating.count}
}
</div>
</div>
</div>
</div>
<div className="sitter-services-wrap">
<div className="sitter-rates-summary-wrap">
<div>
<label>
WHILE YOU'RE AWAY
</label>
<div className="sitter-rates-summary-margin-bottom">
<div className="title-row fluid-row center">
<div className="fluid-col">
<h2 className="h5">
Dog Sitting
</h2>
</div>
<div className="fluid-col text-right">
<div className="h2">
<strong>
${sitter.rates}
</strong>
</div>
</div>
</div>
<div className="subtext-row fluid-row">
<div className="fluid-col">
<h2 className="text-muted">
in your home
</h2>
</div>
<div className="fluid-col text-right">
<h2 className="text-muted">
per night
</h2>
</div>
</div>
</div>
</div>
</div>
</div>
<div className="contact-wrap">
<div className="contact-favorite-wrap">
<div className="favorite-button-col">
<button type="button" title="Save to Favorites" className="favorite-button">
<span className="default-state">
<i className="far fa-heart fa-lg" id="open-heart"></i>
</span>
<span className="favorited-state">
<i className="fas fa-heart fa-lg"></i>
</span>
</button>
</div>
<div className="contact-button-col">
<Link to={`/sitters/${sitter.id}/bookings`} className="contact-button">
Contact {sitter.sittername}
</Link>
</div>
</div>
</div>
</div>
);
}
export default SitterDetail;
<file_sep>/frontend/actions/dropdown_actions.js
export const TOGGLE_DROPDOWN = "TOGGLE_DROPDOWN";
export const toggleDropdown = () => {
return {
type: TOGGLE_DROPDOWN
};
};
<file_sep>/app/views/api/bookings/_booking.json.jbuilder
json.extract! booking, :id, :sitter_id, :user_id, :start_date, :end_date
<file_sep>/frontend/reducers/entities_reducer.js
import { combineReducers } from 'redux';
import sitterReducer from './sitters_reducer';
const entitiesReducer = combineReducers({
sitters: sitterReducer,
});
export default entitiesReducer;
<file_sep>/frontend/actions/app_actions.js
export const CLOSE_DROPDOWN = "CLOSE_DROPDOWN";
export const closeDropdown = () => {
return {
type: CLOSE_DROPDOWN,
};
};
<file_sep>/frontend/reducers/sitters_reducer.js
import { RECEIVE_ALL_SITTERS, RECEIVE_SITTER, REMOVE_SITTER } from '../actions/sitter_actions';
import { merge } from 'lodash';
const sitterReducer = (oldState = {}, action) => {
Object.freeze(oldState);
switch (action.type) {
case RECEIVE_ALL_SITTERS:
return action.sitters;
case RECEIVE_SITTER:
return merge({}, oldState, {[action.sitter.id]: action.sitter});
case REMOVE_SITTER:
let newState = merge({}, oldState);
delete newState[action.sitterId];
return newState;
default:
return oldState;
}
};
export default sitterReducer;
<file_sep>/app/views/api/sitters/_sitter.json.jbuilder
json.extract! sitter, :id, :description, :lat, :lng, :location, :rates, :sittername
json.image_thumb asset_path(sitter.image(:thumb))
json.image_url asset_path(sitter.image.url)
<file_sep>/frontend/components/search/sitter_index_item.jsx
import React from 'react';
import { withRouter, Link } from 'react-router-dom';
import SitterIndexContainer from './sitter_index_container';
class IndexItem extends React.Component {
constructor(props) {
super(props);
}
render () {
const { sittername, rates, description, location } = this.props.sitter;
return (
<Link to={`sitters/${this.props.sitter.id}`} className="sitter-item-link">
<div className="sitter-card">
<div className="profile-pic-box-sitter">
<img className="profile-pic-index"
src={this.props.sitter.image_thumb}
/>
</div>
<div className="index-item-info">
<div className="list-num">
{this.props.num + 1}.
</div>
<div className="index-item-name">
{ sittername }
</div>
<div className="index-item-rate">
<div className="text-muted-index">
from
</div>
<div className="rate">
${ rates }
</div>
<div className="text-muted-index">
per night
</div>
</div>
<div className="index-item-address">
{ location }
</div>
<div className="index-item-description">
{ description || ""}
</div>
</div>
</div>
</Link>
);
}
}
export default withRouter(IndexItem);
<file_sep>/frontend/actions/sitter_actions.js
import * as SitterApiUtil from '../util/sitter_api_util';
export const RECEIVE_ALL_SITTERS = "RECEIVE_ALL_SITTERS";
export const RECEIVE_SITTER = "RECEIVE_SITTER";
export const REMOVE_SITTER = "REMOVE_SITTER";
export const RECEIVE_ERRORS = "RECEIVE_ERRORS";
export const REMOVE_ERRORS = "REMOVE_ERRORS";
export const receiveSitters = (sitters) => {
return {
type: RECEIVE_ALL_SITTERS,
sitters
};
};
export const receiveSitter = sitter => {
return {
type: RECEIVE_SITTER,
sitter
};
};
export const receiveErrors = (errors) => {
return {
type: RECEIVE_ERRORS,
errors
};
};
export const removeSitter = (sitterId) => {
return {
type: REMOVE_SITTER,
sitterId
};
};
export const fetchSitters = (filters) => dispatch => {
return SitterApiUtil.fetchSitters(filters).then( sitters => dispatch(receiveSitters(sitters)), errors => dispatch(receiveErrors(errors)));
};
export const fetchSitter = (sitterId) => dispatch => {
return SitterApiUtil.fetchSitter(sitterId).then( sitter => dispatch(receiveSitter(sitter)), errors => dispatch(receiveErrors(errors)));
};
export const createSitter = sitter => dispatch => {
return SitterApiUtil.createSitter(sitter).then( sitter => dispatch(receiveSitter(sitter)), errors => dispatch(receiveErrors(errors)));
};
export const deleteSitter = (sitterId) => dispatch => {
return SitterApiUtil.deleteSitter(sitterId).then( () => dispatch(removeSitter(sitterId)), errors => dispatch(receiveErrors(errors)));
};
export const removeErrors = () => {
return {
type: REMOVE_ERRORS
};
};
<file_sep>/app/controllers/api/sitters_controller.rb
class Api::SittersController < ApplicationController
def show
@sitter = Sitter.find(params[:id])
end
def index
@sitters = bounds ? Sitter.in_bounds(bounds) : Sitter.all
# render :index
end
def create
@sitter = Sitter.new(sitter_params)
if @sitter.save!
render :show
else
render json: @sitter.errors.full_messages, status: 422
end
end
private
def bounds
params[:bounds]
end
def sitter_params
params.require(:sitter).permit(:sittername, :location, :rates, :lat, :lng)
end
end
<file_sep>/frontend/reducers/bookings_reducer.js
import { RECEIVE_ALL_BOOKINGS, RECEIVE_BOOKING } from '../actions/booking_actions';
import { merge } from 'lodash';
const bookingReducer = (oldState = {}, action) => {
Object.freeze(oldState);
switch (action.type) {
case RECEIVE_ALL_BOOKINGS:
return action.bookings;
case RECEIVE_BOOKING:
return merge({}, oldState, {[action.booking.id]: action.booking});
case REMOVE_BOOKING:
let newState = merge({}, oldState);
delete newState[action.bookingId];
return newState;
default:
return oldState;
}
};
export default bookingsReducer;
<file_sep>/frontend/components/sitter_show/sitter_about.jsx
import React from 'react';
import { Link } from 'react-router-dom';
const SitterAbout = ({ sitter }) => {
return (
<div className="sitter-description-wrap">
<div className="section-row">
<div className="section-col-main">
<h2 className="about-title">
About {sitter.sittername}
</h2>
</div>
</div>
<div className="section-row">
<div className="section-col-meta">
</div>
<div className="section-col-main">
<h4>
Description
</h4>
<div className="sitter-description">
<p>
{sitter.description}
</p>
</div>
</div>
</div>
</div>
);
};
export default SitterAbout;
<file_sep>/frontend/components/sitter_show/sitter_preferences.jsx
import React from 'react';
import { Link } from 'react-router-dom';
const SitterPreferences = ({ sitter }) => {
};
export default SitterPreferences;
<file_sep>/frontend/reducers/ui_reducer.js
import { combineReducers } from 'redux';
import filterReducer from './filter_reducer';
import dropDownReducer from './drop_down_reducer';
export default combineReducers({
dropDown: dropDownReducer
});
<file_sep>/frontend/components/sitter_show/sitter_show_container.js
import { connect } from 'react-redux';
import SitterShow from './sitter_show';
import { fetchSitter } from '../../actions/sitter_actions';
const mapStateToProps = (state, ownProps) => {
const sitterId = parseInt(ownProps.match.params.sitterId);
return {
sitter: state.entities.sitters[sitterId] || {}
};
};
const mapDispatchToProps = (dispatch) => {
return {
fetchSitter: (sitterId) => dispatch(fetchSitter(sitterId))
};
};
export default connect(mapStateToProps, mapDispatchToProps)(SitterShow);
<file_sep>/frontend/actions/booking_actions.js
import * as BookingApiUtil from '../util/booking_api_util';
import { RECEIVE_ERRORS, receiveErrors } from './sitter_actions';
export const RECEIVE_ALL_BOOKINGS = "RECEIVE_ALL_BOOKINGS";
export const RECEIVE_BOOKING = "RECEIVE_BOOKING";
export const REMOVE_BOOKING = "REMOVE_BOOKING";
export const receiveBookings = (bookings) => {
return {
type: RECEIVE_ALL_BOOKINGS,
bookings
};
};
export const receiveBooking = (booking) => {
return {
type: RECEIVE_BOOKING,
booking
};
};
export const removeBooking = (bookingId) => {
return {
type: REMOVE_BOOKING,
bookingId
};
};
export const fetchBookings = () => dispatch => {
return BookingApiUtil.fetchBookings().then( bookings => dispatch(receiveBookings(bookings)), errors => dispatch(receiveErrors(errors)));
};
export const fetchBooking = () => dispatch => {
return BookingApiUtil.fetchBooking().then( booking => dispatch(receiveBooking(booking)), errors => dispatch(receiveErrors(errors)));
};
export const createBooking = (booking) => dispatch => {
return BookingApiUtil.createBooking(booking).then( booking => dispatch(receiveBooking(booking)), errors => dispatch(receiveErrors(errors)));
};
export const deleteBooking = (bookingId) => dispatch => {
return BookingApiUtil.deleteBooking(bookingId).then( () => dispatch(removeBooking(bookingId)), errors => dispatch(receiveErrors(errors)));
};
<file_sep>/frontend/util/marker_manager.js
import React from 'react';
class MarkerManager extends React.Component {
constructor(map) {
super(map);
this.map = map;
this.markers = {};
this.createMarkerFromSitter = this.createMarkerFromSitter.bind(this);
}
updateMarkers(sitters) {
const sittersObj = {};
sitters.forEach( (sitter) => {
sittersObj[sitter.id] = sitter;
});
sitters.forEach( (sitter) => {
if (!this.markers[sitter.id]) {
this.createMarkerFromSitter(sitter);
}
});
Object.keys(this.markers)
.filter(sitterId => !sittersObj[sitterId])
.forEach((sitterId) => this.removeMarker(this.markers[sitterId]));
}
removeMarker(marker) {
this.markers[marker.sitterId].setMap(null);
delete this.markers[marker.sitterId];
}
createMarkerFromSitter(sitter) {
const position = new google.maps.LatLng(sitter.lat, sitter.lng);
const marker = new google.maps.Marker({
position,
map: this.map,
sitterId: sitter.id
});
this.markers[marker.sitterId] = marker;
}
}
export default MarkerManager;
<file_sep>/frontend/reducers/drop_down_reducer.js
import { TOGGLE_DROPDOWN } from '../actions/dropdown_actions';
const initialState = {
open: false
};
const dropDownReducer = (oldState = initialState, action) => {
Object.freeze(oldState);
switch (action.type) {
case TOGGLE_DROPDOWN:
let newState = {open: !oldState.open};
return newState;
default:
return oldState;
}
};
export default dropDownReducer;
<file_sep>/frontend/reducers/sitter_errors_reducer.js
import { RECEIVE_ERRORS, REMOVE_ERRORS } from '../actions/sitter_actions';
const sitterErrorsReducer = (oldState = {}, action) => {
Object.freeze(oldState);
switch (action.type) {
case RECEIVE_ERRORS:
return action.type.responseJSON;
case REMOVE_ERRORS:
return [];
default:
return oldState;
}
};
export default sitterErrorsReducer;
<file_sep>/app/views/api/sitters/index.json.jbuilder
@sitters.each do |sitter|
json.set! sitter.id do
json.partial! 'sitter', sitter: sitter
end
end
<file_sep>/frontend/components/user_show/user_show.jsx
import React from 'react';
import { Link } from 'react-router-dom';
import UserShowForm from './user_show_form';
class UserShow extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="main-content-user-show">
<div className="hero-container-user">
<div className="row">
<div className ="col-two-fifths">
<div className="profile-pic-box">
<div className="widget-body">
<img
className="profile-pic"
src={this.props.currentUser.image_thumb}
/>
</div>
</div>
</div>
<div className="col-three-fifths">
<div className="inner-profile-right">
<div className="username">
{this.props.currentUser.username}
</div>
<div className="profile-description">
<UserShowForm
currentUser={this.props.currentUser}
updateUser={this.props.updateUser}
/>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default UserShow;
<file_sep>/frontend/components/sitter_show/sitter_show.jsx
import React from 'react';
import { Link } from 'react-router-dom';
import SitterDetail from './sitter_detail';
import SitterPreferences from './sitter_preferences';
import SitterAbout from './sitter_about';
import SitterReviews from './sitter_reviews';
class SitterShow extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
this.props.fetchSitter(this.props.match.params.sitterId);
}
render () {
return (
<div className="main-content-sitter-show">
{
// <div className="fixed-contact-bar">
//
// </div>
//
}
<div className="hero-container">
<div className="member-profile-hero-wrap">
<div className="member-profile-photos-row-row">
<div className="member-profile-photos-row">
<div className="member-profile-photos-col">
<div className="hero-image" style={{backgroundImage: `url(${this.props.sitter.image_url})`}}>
</div>
</div>
</div>
<div className="member-profile-details-col">
<SitterDetail
sitter={this.props.sitter}
/>
</div>
</div>
</div>
</div>
<div className="member-profile-bottom-half">
<div className="member-profile-bottom-half-container">
<div className="member-profile-primary-wrap">
<div className="member-profile-bottom-half-row">
<div className="col-right">
<section className="dog-preferences">
</section>
<section className="availability">
</section>
</div>
<div className="col-left">
<section className="reviews">
{
//<SitterReviews
// sitter={this.props.sitter}
// />
}
</section>
<section className="about">
<SitterAbout
sitter={this.props.sitter}
/>
</section>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default SitterShow;
<file_sep>/sample state.js
{
entities: {
sitters: {
1: {
id: 1,
sittername: "",
reviews: [],
rates: ,
description: ,
img_url: ,
verified: true,
current_user_favorite: false,
location: ,
},
2: {
id: 1,
sittername: "",
reviews: [],
rates: ,
description: ,
img_url: ,
verified: true,
current_user_favorite: false,
location: ,
},
3: {
id: 1,
sittername: ,
reviews: [],
rates: ,
description: ,
img_url: ,
verified: true,
current_user_favorite: false,
location: ,
}
},
users: {
11: {
id: 11,
dog_id: 1
username: ,
reviews: [],
description: ,
img_url: ,
location: ,
}
},
23: {
id: 23,
dog_id: 2,
username: ,
reviews: [],
description: ,
img_url: ,
location: ,
},
25: {
id: 25,
dog_id: 3,
username: ,
reviews: [],
description: ,
img_url: ,
location: ,
}
}
},
pets: {
1: {
id: 1,
owner_id: 11,
dogname: ,
breed: ,
age: ,
sex: ,
weight: ,
house-trained: true,
description: ,
img_url: ,
location: ,
},
2: {
id: 2,
owner_id: 11,
dogname: ,
breed: ,
age: ,
sex: ,
weight: ,
house-trained: true,
description: ,
img_url: ,
location: ,
},
3: {
id: 3,
owner_id: 23,
dogname: ,
breed: ,
age: ,
sex: ,
weight: ,
house-trained: true,
description: ,
img_url: ,
location: ,
}
},
4: {
id: 4,
owner_id: 25,
dogname: ,
breed: ,
age: ,
sex: ,
weight: ,
house-trained: true,
description: ,
img_url: ,
location: ,
}
}
reviews: {
1: {
id: 1,
booking_id: 2104,
sitter_id: ,
dog_id: ,
user_id: ,
description: ,
img_url: ,
verified: true,
location: ,
},
2: {
id: 2,
booking_id: 11,
sitter_id: ,
dog_id: ,
user_id: ,
description: ,
img_url: ,
verified: true,
location: ,
},
3: {
id: 3,
booking_id: 202,
sitter_id: ,
dog_id: ,
user_id: ,
description: ,
img_url: ,
verified: true,
location: ,
}
},
bookings: {
1: {
id: 1,
sitter_id: ,
dog_id: ,
user_id: ,
rate: ,
dates: ,
location: ,
},
2: {
id: 1,
sitter_id: ,
dog_id: ,
user_id: ,
rate: ,
dates: ,
location: ,
},
3: {
id: 1,
sitter_id: ,
dog_id: ,
user_id: ,
rate: ,
dates: ,
location: ,
}
},
ui: {
loading: true/false
},
errors: {
login: ["Incorrect username/password combination"],
},
session: {
id: 23,
username: ,
reviews: [],
description: ,
img_url: ,
location: ,
}
}
<file_sep>/db/migrate/20180104170601_create_sitters.rb
class CreateSitters < ActiveRecord::Migration[5.1]
def change
create_table :sitters do |t|
t.string :sittername, null: false
t.string :location, null: false
t.float :rates, null: false
t.text :description
t.float :lat, null: false
t.float :lng, null: false
t.timestamps
end
add_index :sitters, :lat
add_index :sitters, :lng
end
end
<file_sep>/frontend/components/nav/nav.jsx
import React from 'react';
import { Link, withRouter } from 'react-router-dom';
import ReactDOM from 'react-dom';
class Nav extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleLogout = this.handleLogout.bind(this);
this.handleClick = this.handleClick.bind(this);
}
handleSubmit(e) {
e.preventDefault();
this.props.login({email: "<EMAIL>", password: "<PASSWORD>"});
}
handleLogout(e) {
e.preventDefault();
this.props.logout().then( () => this.props.history.push("/login"));
}
handleClick(e) {
this.props.toggleDropdown();
}
userNavLinks() {
if (!this.props.currentUser) {
return (
<nav className="header-logged-in-links">
<button
type="button"
onClick={this.handleSubmit}
className="demo-login-button"
>Demo Login</button>
<a href="#/signup" onClick={this.props.removeErrors}>Sign Up</a>
<a href="#/login" onClick={this.props.removeErrors}>Sign In</a>
</nav>
);
} else {
const dropDownClasses = this.props.dropDownOpen ? "header-dropdown-content show" : "header-dropdown-content";
const dropDownProfileClasses = this.props.dropDownOpen ? "nav-right-box myClickState" : "nav-right-box";
return (
<nav className="header-login-signup-links">
<ul className="nav-right">
<li className="profile-box">
<div className={dropDownProfileClasses} id="dropdown-profile">
<button className="dropbtn" onClick={this.handleClick}>
<div className="profile-icon-box">
<img
className="profile-icon"
src={this.props.currentUser.image_url}
/>
</div>
<div className="username-nav">
{this.props.currentUser.username}
</div>
<span className="caret">
<i className="fas fa-caret-down fa-xs"></i>
</span>
</button>
</div>
<ul className={dropDownClasses} id="dropdown">
<li>
<Link to={`/users/${this.props.currentUser.id}`}>
Dashboard
</Link>
</li>
<li><a href="#">Settings</a></li>
<li className="divider"></li>
<li><button className="logout-button" onClick={this.handleLogout}>
Log Out
</button></li>
</ul>
</li>
<li>
<div className="nav-right-box">
<Link to={"/"}>
<span className="bookings-icon">
<i className="far fa-envelope">
</i>
</span>
Bookings
</Link>
</div>
</li>
</ul>
</nav>
);
}
};
render () {
return this.userNavLinks();
}
}
export default withRouter(Nav);
<file_sep>/app/helpers/api/sitters_helper.rb
module Api::SittersHelper
end
<file_sep>/frontend/util/sitter_api_util.js
export const fetchSitters = (filters) => {
let bounds;
if (filters) {
bounds = filters.bounds;
} else {
bounds = {
north: 40.792706,
south: 40.780294,
east: -73.937692,
west : -73.985414
};
}
return $.ajax({
method: 'get',
url: 'api/sitters',
data: { bounds }
});
};
export const fetchSitter = (sitterId) => {
return $.ajax({
method: 'get',
url: `api/sitters/${sitterId}`
});
};
export const createSitter = (sitter) => {
return $.ajax({
method: 'post',
url: 'api/sitters',
data: { sitter }
});
};
export const deleteSitter = (sitterId) => {
return $.ajax({
method: 'delete',
url: `api/sitters/${sitterId}`
});
};
<file_sep>/README.md
<h1> Baxter
<h3> Summary </h3>
Baxter is a single-page full-stack web application inspired by Rover built using Ruby on Rails on the backend, a PostgreSQL database, and React.js with a Redux architectural framework on the frontend.
Baxter enables users to search for dog sitters according to location, price, sitter availability, and other preferences, and allows them to send a request to book a dog sitter.
[Baxter][https://aa-baxter.herokuapp.com/]
<h3> Overall Structure </h3>
<h3> Primary Components </h3>
<h3> List of techs/languages/plugins/APIs </h3>
Backend
* BCrypt
* Paperclip/AWS
* figaro
* SQL
* JSON
Frontend
* GoogleMap API
* React DOM
* React Router
* jQuery
* React.js
* Flux
* Webpack
Hosting
* Heroku platform
<h3> Future of the App </h3>
I would like to add/improve these future features:
1. Have a distinct home page
2. Improve Sitter profile page
3. Improve User profile page
4. Have a bookings page that displays past, current, and future bookings
5. Add a reviews function
6. Improve the Bookings component
<file_sep>/app/views/api/sitters/show.json.jbuilder
json.partial! '/api/sitters/sitter', sitter: @sitter
<file_sep>/frontend/components/session_form/session_form.jsx
import React from 'react';
import { Link, withRouter } from 'react-router-dom';
class SessionForm extends React.Component {
constructor(props) {
super(props);
this.state = {
email: "",
password: "",
username: "",
address: "",
imageFile: null,
imageUrl: null
};
this.handleSubmit = this.handleSubmit.bind(this);
this.updateFile = this.updateFile.bind(this);
}
componentWillReceiveProps(nextProps) {
if (nextProps.loggedIn) {
this.props.history.push('/login');
}
}
componentWillUnmount() {
this.props.removeErrors();
}
update(field) {
return e => {
this.setState({ [field]: e.currentTarget.value });
};
}
updateFile(e) {
const file = e.currentTarget.files[0];
const fileReader = new FileReader();
fileReader.onloadend = () => {
this.setState({ imageFile: file, imageUrl: fileReader.result });
};
if (file) {
fileReader.readAsDataURL(file);
}
}
handleSubmit(e) {
e.preventDefault();
if (this.props.formType === 'login') {
const user = Object.assign({}, this.state);
this.props.processForm(user);
} else {
const formData = new FormData();
formData.append("user[username]", this.state.username);
formData.append("user[address]", this.state.address);
formData.append("user[email]", this.state.email);
formData.append("user[password]", <PASSWORD>.password);
if (this.state.imageFile) {
formData.append("user[image]", this.state.imageFile);
}
this.props.processForm(formData);
}
}
renderSignupFields() {
if (this.props.formType === 'signup' ) {
return (
<ul>
<label className = "session-form-label">Name:
<br />
<input
type="text"
value={this.state.username}
onChange={this.update('username')}
className="login-input"
/>
</label>
<br />
<label className = "session-form-label">Zip Code:
<br />
<input
type="text"
value={this.state.address}
onChange={this.update('address')}
className="login-input"
/>
</label>
<br />
<label className = "session-form-label">Email:
<br />
<input
type="text"
value={this.state.email}
onChange={this.update('email')}
className="login-input"
/>
</label>
<br />
<label className = "session-form-label">Create a password:
<br />
<input
type="<PASSWORD>"
value={this.state.password}
onChange={this.update('password')}
className="login-input"
/>
</label>
<label className = "session-form-label">Upload a Profile Picture:
<br />
<input
type="file"
onChange={this.updateFile}
className="login-input"
/>
</label>
<img src={this.state.imageUrl} />
</ul>
);
}
}
renderSigninFields() {
if (this.props.formType === 'login' ) {
return (
<ul>
<label className = "session-form-label">Email:
<br />
<input
type="text"
value={this.state.email}
onChange={this.update('email')}
className="login-input"
/>
</label>
<br />
<label className = "session-form-label">Password:
<br />
<input
type="<PASSWORD>"
value={this.state.password}
onChange={this.update('<PASSWORD>')}
className="login-input"
/>
</label>
</ul>
);
}
}
renderFinePrint() {
if (this.props.formType === 'signup' ) {
return (
<div>
<p className="fine-print">
Already have a Baxter account?
<Link className="signinLink" to="/login">Sign in now</Link>
</p>
</div>
);
} else {
return (
<div>
<p className="fine-print">
Don't have a Baxter account?
<Link className="signinLink" to="/signup">Sign up now</Link>
</p>
</div>
);
}
}
renderErrors() {
if (this.props.errors !== null ) {
return (
<ul className="session-errors">
{
this.props.errors.map( (error, i) => (
<li className="errors" key={`error-${i}`}>
{error}
</li>
))
}
</ul>
);
}
}
render() {
const text = this.props.formType === 'login' ? "Sign In" : "Sign Up";
const title = this.props.formType === 'login' ? "Sign In to Baxter" : "Sign Up for Baxter";
return (
<div className="login-form-container">
<div className="primary-content-block">
<div className="form-box">
<div className="form">
<div className="padding-form">
<header className="page-header">
<h1 className="header-title">
<span>
{title}
</span>
</h1>
</header>
<form onSubmit={this.handleSubmit} className="login-form-box">
{this.renderErrors()}
<div className="login-form">
{this.renderSignupFields()}
{this.renderSigninFields()}
<br/>
<input className="form-submit-button" type="submit" value={text} />
</div>
<br />
{this.renderFinePrint()}
</form>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default withRouter(SessionForm);
<file_sep>/frontend/components/search/search_container.js
import { connect } from 'react-redux';
import Search from './search';
import { fetchSitters } from '../../actions/sitter_actions';
import { updateFilter } from '../../actions/filter_actions';
const mapStateToProps = (state) => {
return {
sitters: Object.values(state.entities.sitters),
};
};
const mapDispatchToProps = (dispatch) => {
return {
fetchSitters: (filters) => dispatch(fetchSitters(filters)),
updateFilter: (filter, value) => dispatch(updateFilter(filter, value))
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Search);
<file_sep>/frontend/actions/filter_actions.js
import { fetchSitters } from './sitter_actions';
export const UPDATE_FILTER = "UPDATE_FILTER";
export const changeFilter = (filter, value) => {
return {
type: UPDATE_FILTER,
filter,
value
};
};
export const updateFilter = (filter, value) => (dispatch, getState) => {
dispatch(changeFilter(filter, value));
return fetchSitters(getState().filter)(dispatch);
};
| d42a0122ce9f90998d2bbbf626e81a5444ea15b9 | [
"JavaScript",
"Ruby",
"Markdown"
] | 40 | JavaScript | daybydae/Baxter | bacc0d33faade9d9044922839df3ec63cf992fcd | 17a71ca70fc8c5dd840ea73f80bcca7057a5e651 |
refs/heads/master | <repo_name>linwb-0924/Hotel<file_sep>/src/main/java/org/fjnu/springboot/bean/Room.java
package org.fjnu.springboot.bean;
import java.io.Serializable;
/**
* @author wb_Lin
* @create 2020-06-13 10:02
*/
public class Room implements Serializable {
private String rno;
private String rname;
private String rstatus;
private double rprice;
public Room() {
}
public Room(String rno, String rname, String rstatus, double rprice) {
this.rno = rno;
this.rname = rname;
this.rstatus = rstatus;
this.rprice = rprice;
}
public Room(String rno, String rname, double rprice) {
this.rno = rno;
this.rname = rname;
this.rprice = rprice;
}
public String getRno() {
return rno;
}
public void setRno(String rno) {
this.rno = rno;
}
public String getRname() {
return rname;
}
public void setRname(String rname) {
this.rname = rname;
}
public String getRstatus() {
return rstatus;
}
public void setRstatus(String rstatus) {
this.rstatus = rstatus;
}
public double getRprice() {
return rprice;
}
public void setRprice(double rprice) {
this.rprice = rprice;
}
}
<file_sep>/src/main/java/org/fjnu/springboot/bean/Customer.java
package org.fjnu.springboot.bean;
/**
* @author wb_Lin
* @create 2020-06-13 15:59
*/
public class Customer {
private String cno;
private String cname;
private String telephone;
public Customer() {
}
public Customer(String cno, String cname, String telephone) {
this.cno = cno;
this.cname = cname;
this.telephone = telephone;
}
public String getCno() {
return cno;
}
public void setCno(String cno) {
this.cno = cno;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
}
<file_sep>/src/main/java/org/fjnu/springboot/mapper/RoomMapper.java
package org.fjnu.springboot.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.fjnu.springboot.bean.Room;
import java.util.List;
/**
* @author wb_Lin
* @create 2020-06-13 10:01
*/
@Mapper
public interface RoomMapper {
List<Room> SelectAll();
Integer SelectByCount();
Room SelectById(String rno);
void InsertByRoom(Room room);
List<Room> SelectByEmpty();
void UpdateByRno(String rno);
}
<file_sep>/src/main/java/org/fjnu/springboot/confjg/MvcConfig.java
package org.fjnu.springboot.confjg;
import org.fjnu.springboot.Interceptor.LoginInterceptor;
import org.fjnu.springboot.LocalResolver.MyLocalResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author wb_Lin
* @create 2020-04-12 11:47
*/
@Configuration
public class MvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/zhuce1").setViewName("zhuce");
registry.addViewController("/success").setViewName("success");
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**").excludePathPatterns("/").excludePathPatterns("/zhuce")
.excludePathPatterns("/user/signup").excludePathPatterns("/signup").excludePathPatterns("/user/login");
}
@Bean
public LocaleResolver localeResolver(){
return new MyLocalResolver();
}
}
<file_sep>/src/main/java/org/fjnu/springboot/controler/MyControler.java
package org.fjnu.springboot.controler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author wb_Lin
* @create 2020-04-12 11:42
*/
@Controller
public class MyControler {
@RequestMapping("/")
public String login(){
return "index";
}
@RequestMapping("/zhuce")
public String zhuce(){
return "mail";
}
}
<file_sep>/src/main/resources/i18n/login_zh_CN.properties
login.btn=\u767B\u9646
login.btn1=\u6CE8\u518C
login.code=\u6FC0\u6D3B\u7801
login.mail=\u90AE\u7BB1\u8D26\u53F7
login.password=\<PASSWORD>
login.remember=\u8BB0\u4F4F\u6211
login.tip=\u8BF7\u767B\u5F55
login.tip1=\u8BF7\u6CE8\u518C
login.username=\u7528\u6237\u540D<file_sep>/src/main/java/org/fjnu/springboot/exception/MailException.java
package org.fjnu.springboot.exception;
/**
* @author wb_Lin
* @create 2020-04-13 21:43
*/
public class MailException extends Exception {
public MailException() {
super("这是一个不合法的邮件地址");
}
}
<file_sep>/src/main/java/org/fjnu/springboot/mapper/CustomerMapper.java
package org.fjnu.springboot.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.fjnu.springboot.bean.Customer;
import org.fjnu.springboot.bean.Room;
import java.util.List;
/**
* @author wb_Lin
* @create 2020-06-13 10:01
*/
@Mapper
public interface CustomerMapper {
List<Customer> SelectAll();
Integer SelectByCount();
Customer SelectById(String cno);
void InsertByCustomer(Customer customer);
}
<file_sep>/src/main/resources/i18n/login_en_US.properties
login.btn=Sign In
login.btn1=Sign up
login.code=Activation code
login.mail=Mail
login.password=<PASSWORD>
login.remember=Remember Me
login.tip=Please sign in
login.tip1=Please Sign up
login.username=UserName<file_sep>/src/main/java/org/fjnu/springboot/controler/SignupControler.java
package org.fjnu.springboot.controler;
import org.apache.catalina.connector.Response;
import org.fjnu.springboot.bean.Mail;
import org.fjnu.springboot.bean.User;
import org.fjnu.springboot.service.UserService;
import org.fjnu.springboot.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Map;
import java.util.Random;
/**
* @author wb_Lin
* @create 2020-04-12 14:01
*/
@Controller
public class SignupControler {
@Resource
UserService userService;
@Autowired
JavaMailSenderImpl javaMailSender;
@RequestMapping("/user/signup")
public String signup(@Valid Mail mail,Map<String,Object> map){
Random random = new Random();
int number=random.nextInt(10000)+1000 ;
map.put("jihuoma",number);
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setSubject("激活码通知");
simpleMailMessage.setText("您的激活码为:"+number);
simpleMailMessage.setTo(mail.getEmail());
simpleMailMessage.setFrom("345504450@<EMAIL>");
javaMailSender.send(simpleMailMessage);
return "zhuce";
}
@RequestMapping("/signup")
public String sign(HttpServletRequest request, HttpServletResponse response,Map<String,Object> map) throws ServletException, IOException {
String jihuoma = request.getParameter("jihuoma");
String code = request.getParameter("code");
String username = request.getParameter("username");
String password = request.getParameter("password");
if(code.equals(jihuoma)&&username!=null&&password!=null){
userService.InsertByUser(new User(username,MD5Utils.code(password)));
return "index";
}else if (code==null||username==null||password==null){
map.put("msg","信息不能为空");
map.put("jihuoma",jihuoma);
return "zhuce";
}else{
map.put("msg","激活码错误");
map.put("jihuoma",jihuoma);
return "zhuce";
}
}
}
<file_sep>/src/main/java/org/fjnu/springboot/service/InfoService.java
package org.fjnu.springboot.service;
import org.fjnu.springboot.bean.Information;
import org.fjnu.springboot.mapper.InfoMapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* @author wb_Lin
* @create 2020-06-13 16:19
*/
@Service
public class InfoService {
@Resource
InfoMapper infoMapper;
public List<Information> SelectAll(){
return infoMapper.SelectAll();
}
public Integer SelectByCount(){
return infoMapper.SelectByCount();
}
public Information SelectById(String cno){
return infoMapper.SelectById(cno);
}
public void InsertByInformation(Information information){
infoMapper.InsertByInformation(information);
}
}
<file_sep>/README.md
## 前言
因为最近比较空闲,因为无聊所以把很早之前的一个又jsp+serlvet开发的酒店管理系统重新编写成基于Springboot框架开发,界面设计美化。
## 源码地址
github:[https://github.com/linwb-0924](https://github.com/linwb-0924)
(上面还有作者开发的其他的项目源码)
## 技术栈
- Springboot框架
- 前端页面采用thymeleaf模板引擎,bootstrap+semantic框架
- mail邮件发送
- cahce数据缓存
- rabbitmq消息中间件
- Mybatis
- mysql
- ======================================
## 项目启动
因为这是很久之前开发的系统,数据库并没有重新编写,故源码中无sql文件运行,如要运行还得自己创建数据库及数据表。
- 数据库
数据库名:hotel
customer表

employee表

room表

information表

- 修改配置文件
修改数据库连接用户名和密码

修改rabbitmq相关配置

修改邮箱发送的相关配置(邮箱需开启smtp服务)

以上修改完成即可运行。
## 功能演示
- 登录页面国际化
- 
- 
- 注册发送邮件验证码(填写的邮件需开启smtp)



- 与注册相关的密码加密

- 登录拦截(这就不演示了)
- 注销

- 实名认证(主要是姓名和照片)

- 实名认证完个人信息显示

- CRUD:包括分页展示,搜索查询(用chche实现数据缓存),新增(用rabbitmq消息队列监听)




## 总结
该系统并未对功能实现更加具体的完善,也是对springboot框架的应用,整体架构较简单,springboot小白完全适合读懂,初学springboot框架的推荐观看源码。
<file_sep>/src/main/java/org/fjnu/springboot/controler/CustomerControler.java
package org.fjnu.springboot.controler;
import com.github.pagehelper.PageHelper;
import org.fjnu.springboot.bean.Customer;
import org.fjnu.springboot.bean.Information;
import org.fjnu.springboot.bean.Room;
import org.fjnu.springboot.service.CustomerService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* @author wb_Lin
* @create 2020-06-13 16:07
*/
@Controller
public class CustomerControler {
@Resource
CustomerService customerService;
@GetMapping("/searchcustomer")
public String selectroom(Model model, HttpServletRequest request){
String pagenum =request.getParameter("pagenum") ;
Integer totalpage = customerService.SelectByCount()%3==0 ? (customerService.SelectByCount()/3) : (customerService.SelectByCount()/3)+1;
if(pagenum !=null){
if(Integer.parseInt(pagenum)==0){
PageHelper.startPage(totalpage, 3);
model.addAttribute("pagenum",totalpage);
}else if(Integer.parseInt(pagenum)==totalpage+1){
PageHelper.startPage(1, 3);
model.addAttribute("pagenum",1);
}else{
PageHelper.startPage(Integer.parseInt(pagenum), 3);
model.addAttribute("pagenum",Integer.parseInt(pagenum));
}
}else{
PageHelper.startPage(1, 3);
model.addAttribute("pagenum",1);
}
List<Customer> customers = customerService.SelectAll();
model.addAttribute("customers",customers);
return "select-customer";
}
@PostMapping("/searchcustomer")
public String searchone(@RequestParam String query, Model model){
if(query==""){
return "redirect:/searchcustomer";
}
Customer customers = customerService.SelectById(query);
model.addAttribute("customers",customers);
return "customer-one";
}
}
<file_sep>/src/main/java/org/fjnu/springboot/mapper/UserMapper.java
package org.fjnu.springboot.mapper;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.fjnu.springboot.bean.User;
import java.util.List;
/**
* @author wb_Lin
* @create 2020-04-12 11:49
*/
@Mapper
public interface UserMapper {
List<User> SelectAll();
User SelectByUser(User user);
void InsertByUser(User user);
void UpdateByusername(User user);
}
<file_sep>/src/main/resources/i18n/login.properties
login.btn=\u767B\u9646~
login.btn1=\u6CE8\u518C
login.code=\u6FC0\u6D3B\u7801
login.mail=\u90AE\u7BB1\u8D26\u53F7
login.password=\<PASSWORD>~
login.remember=\u8BB0\u4F4F\u6211~
login.tip=\u8BF7\u767B\u9646~
login.tip1=\u8BF7\u6CE8\u518C
login.username=\u7528\u6237\u540D~
<file_sep>/src/main/java/org/fjnu/springboot/service/UserService.java
package org.fjnu.springboot.service;
import org.fjnu.springboot.bean.User;
import org.fjnu.springboot.mapper.UserMapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* @author wb_Lin
* @create 2020-06-12 20:34
*/
@Service
public class UserService {
@Resource
UserMapper userMapper;
public List<User> SelectAll(){
return userMapper.SelectAll();
}
public User SelectByUser(User user){
return userMapper.SelectByUser(user);
}
public void InsertByUser(User user){
userMapper.InsertByUser(user);
}
public void UpdateByusername(User user){
userMapper.UpdateByusername(user);
}
}
| 44cd31a97ebb8d623b9e4e01489d65eeddf3290e | [
"Markdown",
"Java",
"INI"
] | 16 | Java | linwb-0924/Hotel | 694069723bdaa78ef03dd9fd797e0cf862df0baa | d4ae6576554905b5c398ce3654e4f3c6d22f6e5f |
refs/heads/master | <file_sep>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-trackby-component',
templateUrl: './trackby-component.component.html',
styleUrls: ['./trackby-component.component.scss']
})
export class TrackbyComponentComponent implements OnInit {
fruits = []
constructor() { }
ngOnInit(): void {
this.fruits = [
{ name: "Mango", id: 1 },
{ name: "Apple", id: 2 },
{ name: "Banana", id: 3 },
{ name: "Strawberry", id: 4 }
]
}
processFruits(){
// this.fruits.push({ name: "grapes", id: 5 })
this.fruits = [
{ name: "Mango", id: 1 },
{ name: "Banana", id: 3 },
{ name: "Strawberry", id: 4 },
{ name: "Apple", id: 2 }
]
}
trackById(index,fruit){
return fruit.id;
}
}
| 814338dccaadf6783811f0579151d4070fc99d3e | [
"TypeScript"
] | 1 | TypeScript | PurnaChandraRaoK/trackByAngular | d35c47a89daead1650d2d850f26c701da6e68fa2 | a52baa2cdd4af92696feb203d3bfbf9361d01728 |
refs/heads/master | <file_sep>import { of, merge, interval, timer, from, Subject, BehaviorSubject, ReplaySubject } from 'rxjs';
import { map, tap, defaultIfEmpty, every, mapTo, delay, delayWhen, timeInterval } from 'rxjs/operators';
function getSubscriber(_type: string) {
return {
next (value: any) { console.log(`${_type} completed successfully: ${value}`); },
error (err: any) { console.log(err); },
complete () { console.log(`${_type} completed`); }
};
}
// subject is a bridge between observer and observable
const subject$ = new Subject();
subject$.subscribe(getSubscriber('subject'));
subject$.next('hello');
subject$.next('world');
subject$.complete();
const interval$ = interval(1000);
const intervalSubject$ = new Subject();
interval$.subscribe(intervalSubject$);
intervalSubject$.subscribe();
// behaviour subject: starts with a initial value, and continous to emmit values by the source obsevable
const behaviourSubject$ = new BehaviorSubject(45);
behaviourSubject$.subscribe(getSubscriber('behaviour subject'));
subject$.next(55);
subject$.complete();
// replaySubject: same behaviour of behaviourSubject, but don't repeat values
const replaySubject$ = new ReplaySubject(3);
replaySubject$.next(1);
replaySubject$.next(2);
replaySubject$.next(3);
replaySubject$.next(4);
replaySubject$.subscribe(getSubscriber('replay subject')); | 1e058e0a5672a8e6cbeedc8b6348f4308b2e893a | [
"TypeScript"
] | 1 | TypeScript | yurireeis/rxjs-study | 49ff9a5bc07258d50181a0bf03881a6f23d9c691 | b9759255465014ccce14667dbbe50799f714e520 |
refs/heads/main | <repo_name>Boontay/Systems-Analyis-and-Design<file_sep>/OnlineStore/src/main/java/com/online/store/exceptions/UnsuccessfulAccountCreationException.java
package com.online.store.exceptions;
public class UnsuccessfulAccountCreationException extends RuntimeException {
public UnsuccessfulAccountCreationException() {
super("Unsuccessful account Creation.", new Exception());
}
}
<file_sep>/OnlineStore/src/main/java/com/online/store/services/ProductServiceImplementation.java
package com.online.store.services;
import com.online.store.models.Product;
import com.online.store.repositories.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class ProductServiceImplementation implements ProductService {
private ProductRepository productRepository;
@Autowired
public void setProductRepository(ProductRepository productRepository) {
this.productRepository = productRepository;
}
/**
* This gets all the unique categories stored in the database.
* @return The Iterable list of all the unique categories in the database.
*/
@Override
public Iterable<String> listUniqueCategories() {
List<String> allUniqueCategories = new ArrayList<>();
Iterable<Product> allCategories = productRepository.findAll();
allCategories.forEach((element)->{
if(!allUniqueCategories.contains(element.getCategory())) {
allUniqueCategories.add(element.getCategory());
}
});
return allUniqueCategories;
}
/**
* This gets all the category Items stored in the database.
* @param category the specific category type we wish to search for.
* @return list of all the Items in the category.
*/
@Override
public Iterable<Product> listCategoryItems(String category) {
List<Product> allCategoryItems = new ArrayList<>();
Iterable<Product> allItems = productRepository.findAll();
allItems.forEach((item)->{
if(item.getCategory().equals(category)) {
allCategoryItems.add(item);
}
});
return allCategoryItems;
}
/**
* This gets all the category Items stored in the database.
* @param itemSearch of the item you want to search
* @return list of all the Items in the category.
*/
@Override
public Iterable<Product> searchForItemByName(String itemSearch) {
List<Product> searchItems = new ArrayList<>();
Iterable<Product> allRelativeSearchItems = productRepository.findAll();
allRelativeSearchItems.forEach((item)->{
if(item.getName().equalsIgnoreCase(itemSearch) ||item.getName().toUpperCase().contains(itemSearch) || item.getName().toLowerCase().contains(itemSearch) ){
searchItems.add(item);
}
});
return searchItems;
}
/**
* This allows a system admin to add a new product to the database.
* @param product The Product that the system admin wishes to add to the database.
* @return The Product that was added to the database, as a form of validation.
*/
public Product saveProduct(Product product) {
return productRepository.save(product);
}
/**
* This allows a system admin to a delete a specific product from the database.
* @param id The id of the product that the system admin wishes to delete from the database.
*/
public void deleteProduct(Integer id) {
productRepository.deleteById(id);
}
@Override
public Object save(Object object) {
saveProduct((Product)object);
return object;
}
@Override
public void delete(Integer id) {
deleteProduct(id);
}
}
<file_sep>/OnlineStore/src/main/java/com/online/store/exceptions/searchItemException.java
package com.online.store.exceptions;
public class searchItemException extends RuntimeException {
public searchItemException() {
super("No items to browse.", new Exception());
}
}<file_sep>/OnlineStore/src/main/java/com/online/store/services/PaymentServiceImplementation.java
package com.online.store.services;
import com.online.store.exceptions.UnsuccessfulPaymentException;
import com.online.store.models.PaymentInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Service
public class PaymentServiceImplementation implements PaymentService {
private final Logger LOGGER = LoggerFactory.getLogger(PaymentServiceImplementation.class);
@Override
public boolean validatePaymentInfo(PaymentInfo paymentInfo) {
if (!validateFirstName(paymentInfo.getFirstName())) {
throwInvalidPaymentInfoException("first name", paymentInfo.getFirstName());
return false;
}
if (!validateLastName(paymentInfo.getLastName())) {
throwInvalidPaymentInfoException("last name", paymentInfo.getLastName());
return false;
}
if (!validateAddress(paymentInfo.getAddress())) {
throwInvalidPaymentInfoException("address", Arrays.toString(paymentInfo.getAddress()));
return false;
}
if (!validateCardNumber(paymentInfo.getCardNumber())) {
throwInvalidPaymentInfoException("card number", paymentInfo.getCardNumber());
return false;
}
if (!validateCardCVV(paymentInfo.getCardCVV())) {
throwInvalidPaymentInfoException("card CVV", paymentInfo.getCardCVV());
return false;
}
return true;
}
private boolean validateFirstName(String firstName) {
String regex = "[A-Z][a-z]*";
return checkPaymentInfoRegex(regex, firstName);
}
private boolean validateLastName(String lastName) {
String regex = "[A-Z][a-z]*";
return checkPaymentInfoRegex(regex, lastName);
}
private boolean validateAddress(String[] address) {
if (address.length > 5) {
return false;
} else {
String regex = "^[a-zA-Z0-9 ,]+$";
for (String s : address) {
if (!checkPaymentInfoRegex(regex, s)) {
return false;
}
}
}
return true;
}
private boolean validateCardNumber(String cardNumber) {
String regex = "^[0-9]{12}$";
String validatingCardStringNumber = cardNumber.replaceAll("-", "");
return checkPaymentInfoRegex(regex, validatingCardStringNumber);
}
private boolean validateCardCVV(String cardCVV) {
String regex = "^[0-9]{3}$";
return checkPaymentInfoRegex(regex, cardCVV);
}
private void throwInvalidPaymentInfoException(String paymentInfo, String invalidData) {
LOGGER.error("Invalid {} : {}.", paymentInfo, invalidData);
throw new UnsuccessfulPaymentException();
}
private boolean checkPaymentInfoRegex(String regex, String validatingData) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(validatingData);
return matcher.matches();
}
}
<file_sep>/OnlineStore/src/main/java/com/online/store/controllers/JavaFxController.java
package com.online.store.controllers;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.online.store.Constants;
import com.online.store.exceptions.UnsuccessfulEndpointCommunicationException;
import com.online.store.exceptions.UnsuccessfulPaymentException;
import com.online.store.models.Product;
import com.online.store.models.User;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@Component
public class JavaFxController {
private final Logger LOGGER = LoggerFactory.getLogger(JavaFxController.class);
@FXML
public Button registerAccountButton;
public Text registerAccountPasswordText;
public Text registerAccountEmailText;
public Text registerAccountUsernameText;
public PasswordField registerAccountPasswordTextField;
public TextField registerAccountEmailTextField;
public TextField registerAccountUsernameTextField;
public Button registerToLoginButton;
@FXML
public Button loginButton;
public PasswordField loginPasswordTextField;
public TextField loginUsernameTextField;
public Text loginUsernameText;
public Text loginPasswordText;
public Button loginToRegisterAccountButton;
@FXML
public Text deliveryFirstNameText;
public Text deliveryLastNameText;
public Text deliveryAddressText;
public TextField deliveryFirstNameTextField;
public TextField deliveryLastNameTextField;
public TextField deliveryAddressFirstLineTextField;
public TextField deliveryAddressSecondLineTextField;
public TextField deliveryAddressThirdLineTextField;
public TextField deliveryAddressFourthLineTextField;
public TextField deliveryAddressFifthLineTextField;
public Button arrangeDeliveryButton;
@FXML
public Button removeItemButton;
public Button searchItemButton;
@FXML public TextArea listOfItemsViewCartTextArea;
@FXML
public TextField searchBar;
public Button viewCartButton;
public Button addToCartButton;
public Button checkoutButton;
@FXML
public Text paymentFirstNameText;
public Text paymentLastNameText;
public Text paymentAddressText;
public Text paymentCardNumberText;
public Text paymentCvvText;
public TextField paymentFirstNameTextField;
public TextField paymentLastNameTextField;
public TextField paymentAddressFirstLineTextField;
public TextField paymentAddressSecondLineTextField;
public TextField paymentAddressThirdLineTextField;
public TextField paymentAddressFourthLineTextField;
public TextField paymentAddressFifthLineTextField;
public TextField paymentCardNumberTextField;
public TextField paymentCvvTextField;
public Button payForOrderButton;
public Button firstCategoryButton;
public Button secondCategoryButton;
public Button thirdCategoryButton;
public Button fourthCategoryButton;
public TextArea listOfItemsBrowseItemsTextArea;
public Button loadViewCart;
public static User user = new User();
@FXML
private void handleRegisterAccountButtonAction(ActionEvent event) throws Exception {
JSONObject registrationJson = new JSONObject();
registrationJson.put("username", registerAccountUsernameTextField.getText());
registrationJson.put("email", registerAccountEmailTextField.getText());
registrationJson.put("password", registerAccountPasswordTextField.getText());
hitPostEndpoint(Constants.registrationEndpointWithBase, registrationJson.toString());
loadNewScene(Constants.browseItemsFxmlFileName, registerAccountButton);
}
@FXML
private void handleLoginButtonAction(ActionEvent event) throws Exception {
JSONObject loginJson = new JSONObject();
loginJson.put("username", loginUsernameTextField.getText());
loginJson.put("password", loginPasswordTextField.getText());
hitPostEndpoint(Constants.loginEndpointWithBase, loginJson.toString());
loadNewScene(Constants.browseItemsFxmlFileName, loginButton);
}
@FXML
private void handleLoginToRegisterAccountButtonAction(ActionEvent event) throws Exception {
loadNewScene(Constants.registerAccountFxmlFileName, loginToRegisterAccountButton);
}
@FXML
private void handleRegisterToLoginButtonAction(ActionEvent event) throws Exception {
loadNewScene(Constants.loginFxmlFileName, registerToLoginButton);
}
@FXML
private void handleDeliveryButtonAction(ActionEvent event) throws Exception {
List<String> deliveryAddressList = new ArrayList<>(5);
deliveryAddressList.add(deliveryAddressFirstLineTextField.getText());
deliveryAddressList.add(deliveryAddressSecondLineTextField.getText());
deliveryAddressList.add(deliveryAddressThirdLineTextField.getText());
deliveryAddressList.add(deliveryAddressFourthLineTextField.getText());
deliveryAddressList.add(deliveryAddressFifthLineTextField.getText());
JSONArray jsonArray = new JSONArray(deliveryAddressList);
JSONObject deliveryJson = new JSONObject();
deliveryJson.put("firstName", deliveryFirstNameTextField.getText());
deliveryJson.put("lastName", deliveryLastNameTextField.getText());
deliveryJson.put("address", jsonArray);
hitPostEndpoint(Constants.deliveryEndpointWithBase, deliveryJson.toString());
loadNewScene(Constants.successfulDeliveryFxmlFileName, arrangeDeliveryButton);
}
public void handleViewCartButton(ActionEvent actionEvent) throws IOException {
loadNewScene(Constants.viewCartFileName, viewCartButton);
}
private void getUserCartInfo() {
List<Product> products = user.getCart();
ArrayList<String> productNames = getProductNamesFromProductsArrayList((ArrayList<Product>) products);
StringBuilder namesStringBuilder = new StringBuilder();
for (String s : productNames) {
namesStringBuilder.append(s).append(System.lineSeparator());
}
listOfItemsViewCartTextArea.setText(namesStringBuilder.toString());
}
public void handleCheckoutButton(ActionEvent actionEvent) throws IOException {
loadNewScene(Constants.paymentFxmlFileName, checkoutButton);
}
public void handlePaymentButtonAction(ActionEvent actionEvent) throws IOException {
LOGGER.info("Loading delivery page.");
List<String> addressList = new ArrayList<>(5);
addressList.add(paymentAddressFirstLineTextField.getText());
addressList.add(paymentAddressSecondLineTextField.getText());
addressList.add(paymentAddressThirdLineTextField.getText());
addressList.add(paymentAddressFourthLineTextField.getText());
addressList.add(paymentAddressFifthLineTextField.getText());
JSONArray jsonArray = new JSONArray(addressList);
JSONObject paymentJson = new JSONObject();
paymentJson.put("firstName", paymentFirstNameTextField.getText());
paymentJson.put("lastName", paymentLastNameTextField.getText());
paymentJson.put("address", jsonArray);
paymentJson.put("cardNumber", paymentCardNumberTextField.getText());
paymentJson.put("cardCVV", paymentCvvTextField.getText());
// hit endpoint here, calling the right endpoint for the payment controller, sending the paymentJson as the parameter.
hitPostEndpoint(Constants.paymentEndpointWithBase, paymentJson.toString());
loadNewScene(Constants.DeliveryFxmlFileName, payForOrderButton);
}
private void hitPostEndpoint(String endpoint, String input) {
String postMethodName = "POST";
try {
URL url = new URL(endpoint);
HttpURLConnection postConnection = (HttpURLConnection)url.openConnection();
postConnection.setRequestMethod(postMethodName);
postConnection.setRequestProperty("Content-Type", "application/json");
postConnection.setDoOutput(true);
OutputStream outputStream = postConnection.getOutputStream();
outputStream.write(input.getBytes());
outputStream.flush();
outputStream.close();
int responseCode = postConnection.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
getEndpointErrorLogger(postMethodName, endpoint, responseCode);
} else {
getEndpointInfoLogger(postMethodName, endpoint);
}
} catch (IOException ex) {
throw new UnsuccessfulEndpointCommunicationException();
}
}
private void getEndpointInfoLogger(String requestMethod, String endpoint) {
LOGGER.info("Successful communication with {} endpoint: {}", requestMethod, endpoint);
}
private void getEndpointErrorLogger(String requestMethod, String endpoint, int errorCode) {
LOGGER.error("Unsuccessful communication with {} endpoint: {}. Error code: {}", requestMethod, endpoint, errorCode);
}
private String hitGetEndpoint(String endpoint) {
String getMethodName = "GET";
try {
URL url = new URL(endpoint);
String readLine;
HttpURLConnection getConnection = (HttpURLConnection)url.openConnection();
getConnection.setRequestMethod(getMethodName);
int responseCode = getConnection.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
getEndpointErrorLogger(getMethodName, endpoint, responseCode);
} else {
BufferedReader in = new BufferedReader(new InputStreamReader(getConnection.getInputStream()));
StringBuilder response = new StringBuilder();
while ((readLine = in.readLine()) != null) {
response.append(readLine);
}
in.close();
getEndpointInfoLogger(getMethodName, endpoint);
return response.toString();
}
} catch (IOException ex) {
throw new UnsuccessfulEndpointCommunicationException();
}
return String.format("Unsuccessful communication with GET endpoint: %s", endpoint);
}
private void loadNewScene(String filename, Button button) throws IOException {
Stage stage = (Stage) button.getScene().getWindow();
FXMLLoader fxmlLoader = new FXMLLoader();
Parent root = fxmlLoader.load(getClass().getResourceAsStream(filename));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
private ArrayList<Product> convertStringToProductsArrayList(String string) throws JsonProcessingException {
JSONArray jsonArray = new JSONArray(string);
ArrayList<Product> products = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Product product = new ObjectMapper().readValue(jsonObject.toString(), Product.class);
products.add(product);
}
return products;
}
private ArrayList<String> getProductNamesFromProductsArrayList(ArrayList<Product> products) {
ArrayList<String> names = new ArrayList<>();
for (Product p : products) {
names.add(p.getName());
}
return names;
}
public void handleFirstCategoryButtonAction(ActionEvent actionEvent) throws JsonProcessingException {
handleCategoryButton("123");
}
public void handleAddToCartButton(ActionEvent actionEvent) throws JsonProcessingException {
// checks database that item exists in database.
// thi is done with searchForItemByName endpoint.
String productString = hitGetEndpoint(Constants.searchItemsByNameEndpointWithBase + Objects.requireNonNull(searchBar.getText()));
ArrayList<Product> productArrayList = convertStringToProductsArrayList(productString);
// adds product to user's catalog.
ObjectMapper mapper = new ObjectMapper();
String jsonMapper = mapper.writeValueAsString(productArrayList.get(0));
hitPostEndpoint(Constants.addItemsToCartEndpointWithBase, jsonMapper);
}
private void handleCategoryButton(String categoryName) throws JsonProcessingException {
String productsString = hitGetEndpoint(Constants.browseProductsInCategoryEndpointWithBase + categoryName);
ArrayList<Product> productsArrayList = convertStringToProductsArrayList(productsString);
ArrayList<String> productNamesArrayList = getProductNamesFromProductsArrayList(productsArrayList);
StringBuilder namesStringBuilder = new StringBuilder();
for (String s : productNamesArrayList) {
namesStringBuilder.append(s).append(System.lineSeparator());
}
listOfItemsBrowseItemsTextArea.setText(namesStringBuilder.toString());
}
public void handleSecondCategoryButtonAction(ActionEvent actionEvent) throws JsonProcessingException {
handleCategoryButton("12345");
}
public void handleThirdCategoryButtonAction(ActionEvent actionEvent) throws JsonProcessingException {
handleCategoryButton("Example1");
}
public void handleFourthCategoryButtonAction(ActionEvent actionEvent) throws JsonProcessingException {
handleCategoryButton("1234");
}
public void handleLoadViewCartButton(ActionEvent actionEvent) {
getUserCartInfo();
}
}
<file_sep>/OnlineStore/src/main/java/com/online/store/Constants.java
package com.online.store;
import org.springframework.beans.factory.annotation.Value;
public class Constants {
// GUI Object constants.
public static final String passwordPromptString = "<PASSWORD>";
// FXML constants.
public static final String fxmlFileBasePath = "/views/";
public static final String registerAccountFxmlFileName = fxmlFileBasePath + "RegisterAccount.fxml";
public static final String loginFxmlFileName = fxmlFileBasePath + "login.fxml";
public static final String DeliveryFxmlFileName = fxmlFileBasePath + "Delivery.fxml";
public static final String successfulDeliveryFxmlFileName = fxmlFileBasePath + "successfulDelivery.fxml";
public static final String viewCartFileName = fxmlFileBasePath + "viewCart.fxml";
public static final String applicationName = "Online Store";
public static final String browseItemsFxmlFileName = fxmlFileBasePath + "browseItems.fxml";
public static final String paymentFxmlFileName = fxmlFileBasePath + "Payment.fxml";
public static final String serverPort = "8080";
public static final String baseEndpointPath = "http://localhost:" + serverPort;
public static final String registrationEndpoint = "/register-account";
public static final String registrationEndpointWithBase = baseEndpointPath + registrationEndpoint;
public static final String loginEndpoint = "/log-in";
public static final String loginEndpointWithBase = baseEndpointPath + loginEndpoint;
public static final String deliveryEndpoint = "/arrange-delivery";
public static final String deliveryEndpointWithBase = baseEndpointPath + deliveryEndpoint;
public static final String browseProductsInCategoryEndpoint = "/browse-category-items/";
public static final String browseProductsInCategoryEndpointWithBase = baseEndpointPath + browseProductsInCategoryEndpoint;
public static final String searchItemsByNameEndpointWithBase = baseEndpointPath + "/search-items-by-name/";
public static final String addItemsToCartEndpoint = "/add-items-to-cart";
public static final String addItemsToCartEndpointWithBase = baseEndpointPath + "/add-items-to-cart";
public static final String paymentEndpoint = "/pay-for-order";
public static final String paymentEndpointWithBase = baseEndpointPath + "/pay-for-order";
}
<file_sep>/OnlineStore/src/main/java/com/online/store/controllers/AddItemsToCartController.java
package com.online.store.controllers;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.online.store.Constants;
import com.online.store.exceptions.CartIsEmptyException;
import com.online.store.exceptions.ItemNotInCartException;
import com.online.store.exceptions.ItemOutOfStockException;
import com.online.store.models.Product;
import com.online.store.services.ProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import java.math.BigDecimal;
/**
* Contains the endpoint for allowing a user to browse the items available in the store.
*/
@Controller
public class AddItemsToCartController extends com.online.store.controllers.Controller {
private final Logger LOGGER = LoggerFactory.getLogger(AddItemsToCartController.class);
@Autowired
public void setProductService(ProductService productService) {
super.setService(productService);
}
/**
* This allows a user to add items to their.
* @param string An input provided by the body of the request.
* @return A ResponseEntity with the HttpStatus response.
*/
@PostMapping(Constants.addItemsToCartEndpoint)
public ResponseEntity<String> addItemsToCart(@RequestBody String string) {
try {
/*
Parsing the inputted String to a Product object.
*/
Product product = new ObjectMapper().readValue(string, Product.class);
// todo add in stuff to add items to cart here.
if (product.getQuantityInStock() > 0) {
JavaFxController.user.addCartItem(product);
LOGGER.info("Item is in stock and has been added to cart.");
} else {
throw new ItemOutOfStockException();
}
return ResponseEntity.ok(string);
} catch (ItemOutOfStockException | JsonProcessingException ex) {
LOGGER.error("Item cannot be added to cart. It is out of stock.");
return ResponseEntity.badRequest().build();
}
}
@PostMapping("/remove-items-from-cart")
public ResponseEntity<String> removeItemFromCart(@RequestBody String string) {
try {
Product product = new ObjectMapper().readValue(string, Product.class);
if (JavaFxController.user.isItemInCart(product)) {
JavaFxController.user.removeCartItem(product);
} else {
throw new ItemNotInCartException();
}
LOGGER.info("Item removal from cart successful.");
return ResponseEntity.ok(string);
} catch (ItemNotInCartException ex) {
LOGGER.error("Item removal from cart unsuccessful. Item is not in cart.");
return ResponseEntity.badRequest().build();
} catch (Exception ex) {
LOGGER.error("Failed to remove item from cart.");
return ResponseEntity.badRequest().build();
}
}
public BigDecimal getCartPrice() {
try {
BigDecimal total = JavaFxController.user.getTotalCartPrice();
LOGGER.info("Total returned.");
return total;
} catch (Exception ex) {
LOGGER.error("Total NOT returned.");
return new BigDecimal(-1);
}
}
public Product getCartItem(int ind) {
try {
Product prod = new Product();
if (ind >= JavaFxController.user.getCartSize()) {
prod = JavaFxController.user.getCartItem(ind);
} else {
throw new IndexOutOfBoundsException();
}
if (prod == null) {
throw new CartIsEmptyException();
}
LOGGER.info("Cart index is in bounds and cart is not empty.");
return prod;
} catch (IndexOutOfBoundsException ex) {
LOGGER.error("The cart does not contain that many items.");
return null;
} catch (CartIsEmptyException ex) {
LOGGER.error("Cart is empty.");
return null;
}
}
}
<file_sep>/OnlineStore/src/main/java/com/online/store/controllers/BrowseItemsController.java
package com.online.store.controllers;
import com.online.store.exceptions.emptyBrowseExceptions;
import com.online.store.exceptions.searchItemException;
import com.online.store.models.Product;
import com.online.store.services.ProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
/**
* Contains the endpoint for allowing a user to browse the items available in the store.
*/
@Controller
public class BrowseItemsController {
private final Logger LOGGER = LoggerFactory.getLogger(BrowseItemsController.class);
private ProductService productService;
public BrowseItemsController(ProductService productService) {
this.productService = productService;
}
@Autowired
public void setProductService(ProductService productService) {
this.productService = productService;
}
/**
* This allows a user to view all the products.
* @return A ResponseEntity with the HttpStatus response.
*/
@GetMapping("/browse-categories")
public ResponseEntity< Iterable<String>> browseAllCategories() {
try {
Iterable<String> listAllCategories = productService.listUniqueCategories();
LOGGER.info("Product browsing successful.");
return ResponseEntity.ok().body(listAllCategories);
} catch (Exception ex) {
LOGGER.error("Product browsing unsuccessful.");
return ResponseEntity.badRequest().build();
}
}
/**
* This return all the items within the category.
* @param category
* @return A ResponseEntity with all category items.
*/
@GetMapping("/browse-category-items/{category}")
public ResponseEntity<Iterable<Product>>browseCategoryItems(@PathVariable("category") String category) {
try {
Iterable<Product> listAllCategoryItems = productService.listCategoryItems(category);
if(ifBrowseExists(category)){
LOGGER.info("Successful Browse.");
return ResponseEntity.ok().body(listAllCategoryItems);
} else {
LOGGER.info("Unsuccessful Browse.");
throw new emptyBrowseExceptions();
}
} catch (Exception ex) {
LOGGER.error("Couldn't Browse for your desired product.");
return ResponseEntity.badRequest().build();
}
}
@GetMapping("/search-items-by-name/{itemName}")
public ResponseEntity< Iterable<Product>>searchForItemByName( @PathVariable("itemName") String itemName) {
try {
Iterable<Product> listAllSearchItems = productService.searchForItemByName(itemName);
if(ifItemNotInDatabase(itemName)){
LOGGER.info("Successful Search.");
return ResponseEntity.ok().body(listAllSearchItems);
} else {
LOGGER.info("Unsuccessful Search, Try again!.");
throw new searchItemException();
}
} catch (Exception ex) {
LOGGER.error("Item not in Database.");
return ResponseEntity.badRequest().build();
}
}
private Boolean ifBrowseExists(String category) {
Iterable<Product> listAllCategoryItems = productService.listCategoryItems(category);
for (Product p : listAllCategoryItems) {
if(!p.getCategory().equals(category))
return false;
}
return true;
}
private Boolean ifItemNotInDatabase(String itemSearch) {
Iterable<Product> listAllSearchItems = productService.searchForItemByName(itemSearch);
for (Product p : listAllSearchItems) {
if(!p.getName().equals(itemSearch))
return false;
}
return true;
}
}<file_sep>/OnlineStore/src/main/java/com/online/store/services/Service.java
package com.online.store.services;
public interface Service {
Object save(Object object);
void delete(Integer id);
}
<file_sep>/OnlineStore/database/script.sql
-- table structure for table 'product'
SHOW DATABASES;
CREATE DATABASE IF NOT EXISTS online_store;
SHOW DATABASES;
USE online_store;
DROP TABLE IF EXISTS products;
CREATE TABLE products (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(512) CHARACTER SET utf8 NOT NULL,
description varchar(1024) CHARACTER SET utf8 NOT NULL,
category varchar(1024) CHARACTER SET utf8 NOT NULL,
price int(11) DEFAULT 0,
product_id varchar(255) COLLATE utf8_unicode_ci NOT NULL,
quantity_in_stock INT(11) DEFAULT 0,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
DROP TABLE IF EXISTS users;
CREATE TABLE users (
id int(11) NOT NULL AUTO_INCREMENT,
username varchar(512) CHARACTER SET utf8 NOT NULL,
email varchar(512) CHARACTER SET utf8 NOT NULL,
password varchar(512) CHARACTER SET utf8 NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;<file_sep>/OnlineStore/src/main/java/com/online/store/services/ServiceImplementation.java
package com.online.store.services;
public class ServiceImplementation {
}
<file_sep>/OnlineStore/src/main/java/com/online/store/exceptions/ItemNotInCartException.java
package com.online.store.exceptions;
public class ItemNotInCartException extends RuntimeException {
public ItemNotInCartException() {
super("This cart does not have this item.", new Exception());
}
}
<file_sep>/OnlineStore/src/main/java/com/online/store/OnlineStoreApplication.java
package com.online.store;
import javafx.application.Application;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class OnlineStoreApplication {
public static void main(String[] args) {
Application.launch(JavaFxApplication.class, args);
}
}
<file_sep>/OnlineStore/src/main/java/com/online/store/exceptions/UnsuccessfulDeliveryException.java
package com.online.store.exceptions;
public class UnsuccessfulDeliveryException extends RuntimeException {
public UnsuccessfulDeliveryException() {
super("Delivery unsuccessful.", new Exception());
}
}
<file_sep>/OnlineStore/src/main/java/com/online/store/controllers/LogInController.java
package com.online.store.controllers;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.online.store.Constants;
import com.online.store.exceptions.UnsuccessfulLoginException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.online.store.models.User;
import com.online.store.services.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
/**
* Contains the endpoint for logging a user in.
*/
@Controller
public class LogInController {
private final Logger LOGGER = LoggerFactory.getLogger(LogInController.class);
private UserService userService;
@Autowired
public void setProductService(UserService userService) {
this.userService = userService;
}
/**
* The method allows a user to login to their account.
* @param user the data relating to the user logging in.
* @return A boolean to indicate if a login attempt is valid.
*/
public boolean checkIfValidLogin(User user) {
Iterable<User> existingUsers = userService.listAllUsers();
for (User u : existingUsers) {
String userPassword = user.getPassword();
String userUsername = user.getUsername();
boolean userAccountUsernameExistsInDatabase = u.getUsername().equals(userUsername);
boolean userAccountPasswordExistsInDatabase = u.getPassword().equals(userPassword);
if (userAccountPasswordExistsInDatabase && userAccountUsernameExistsInDatabase) {
return true;
}
}
return false;
}
public void validLogin(User user) {
if (checkIfValidLogin(user)) {
LOGGER.info("Login has been Successful.");
}
else {
LOGGER.error("No matching Login Details have been found in the Database.");
throw new UnsuccessfulLoginException();
}
}
@PostMapping(Constants.loginEndpoint)
public ResponseEntity<String> logIn(@RequestBody String string) {
try {
User user = new ObjectMapper().readValue(string, User.class);
validLogin(user);
return ResponseEntity.ok(string);
} catch (UnsuccessfulLoginException | JsonProcessingException ex) {
LOGGER.error("Account registration unsuccessful.");
return ResponseEntity.badRequest().build();
}
}
}
<file_sep>/README.md
# Systems-Analysis-and-Design
This was part of a assignment that I completed with other students in my course.
This has been run on IntelliJ.
Create MySQL database "online_store".
Update application.properties file to the password and username of your MySQL config, for me, it was "root" for both.
Assign the database to the project. In IntelliJ, this can be done in the "Database" side menu, and then adding a MySQL database called "online_store".
Run script.sql.
Run mvn clean install. In IntelliJ, this can be done with a side menu "Maven", which can be use to select the options for a "mvn clean install".
In the Product and User classes, there may be an error shown for the line "@Table(name=<table_name>", where table_name is the appropriate table for the class. A solution to this in IntelliJ is to click on the error line, and click "Assign Data Source", then reshape the window that pops up as it may be small, then click on the database that was created to the store the data above. In my case, it was "online_store".
Run the OnlineStoreApplication.java class.
If the application does not run because of a port the application requires is being used by another application, then change the server.port in application.properties file if necessary. For example, the port can be changed from 8080 to 8090. The same applies to the serverPort variable in the Constants.java file in the repo.
server.port: 8090
When the application is run, a JavaFX window will appear. The REST endpoints will still be accessible when the JavaFX GUI is running. In Postman, hit the endpoint (change "8080" to "8090"):
http://localhost:8080/add-items-to-catalog
And have the following be the input of the body in Postman, in a JSON format. The name of product can be changed, so as to allow for multiple items to be added to the store's database of available products.
{
"productId": "134560",
"name": "Example1",
"description": "Example Product Description",
"category" : "Example1",
"price": "5.60",
"quantityInStock": "1000"
}
Run the application again. Enter a username (which must be more than 6 characters long), email (which must end with "@gmail.com"), and a password (which must be more than 6 characters long). An example could be "Anila1" for usename, "<EMAIL>" for email, and "<PASSWORD>" for password. Then click on "Register Account" to load the screen to browse items.
When the above details are inputted and verified, the browse items screen will appear. To load items in the first category, click on "First Category". The same applies to the second, third, and fourth categories. When the category is selected, the list of available products will be shown.
To add a specfic product in a category, type in the name of the product in the TextField on the top of the screen, and click on "Add to Cart".
Once you have added enough items have been added to the cart, click on the "View Cart" button.
The viewCart screen will then be loaded. To load the list of products in the cart, click on the button "Load Cart Items".
When you wish to pay for the order, click on the "Checkout" button.
You can pay for the order by providing these details, but you can feel free to test for other details. Then click on the "Pay for Order" button to verify the inputs and load the delivery screen.
"First Name": "Anila"
"Last Name": "Mjeda"
"Address Line 1": "Address Line 1"
"Address Line 2": "Address Line 2"
"Address Line 3": "Address Line 3"
"Address Line 4": "Address Line 4"
"Address Line 5": "Address Line 5"
"Card Number": "132465897012"
"CVV": "231"
You can arrange for delivery by providing these details, but you can feel free to test for other details. Then click on the "Arrange Delivery" to verify the delivery info provided, and to load the success screen for the order.
"First Name": "Anila"
"Last Name": "Mjeda"
"Address Line 1": "Address Line 1"
"Address Line 2": "Address Line 2"
"Address Line 3": "Address Line 3"
"Address Line 4": "Address Line 4"
"Address Line 5": "Address Line 5"
You can run through this process again, clicking on the "Login" button to log into your existing account, instead of having to create a new account.
<file_sep>/OnlineStore/src/main/java/com/online/store/controllers/RegisterAccountController.java
package com.online.store.controllers;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.online.store.Constants;
import com.online.store.exceptions.UnsuccessfulAccountCreationException;
import com.online.store.models.User;
import com.online.store.services.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.regex.Pattern;
/**
* Contains the endpoint for allowing a user to register their account in the store.
*/
@Controller
public class RegisterAccountController {
private final Logger LOGGER = LoggerFactory.getLogger(RegisterAccountController.class);
private UserService userService;
@Autowired
public void setProductService(UserService userService) {
this.userService = userService;
}
/**
* The method to allow a user to register an account.
* @param email the string relating to the data of the user.
* @param username the string relating to the data of the user.
* @param password the string relating to the data of the user.
* @return A ResponseEntity with the HttpStatus response.
*/
public boolean validUserData(String email, String username, String password) {
String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\." + "[a-zA-Z0-9_+&*-]+)*@" + "(?:[a-zA-Z0-9-]+\\.)+[a-z" + "A-Z]{2,7}$";
Pattern emailPattern = Pattern.compile(emailRegex);
if(email.equals("") || username.equals("") || password.equals("")) {
LOGGER.error("You Can't Leave any of the Required Fields Empty.");
return false;
}
else if(username.length() < 6 || password.length() < 6) {
LOGGER.error("Username and Password Length must be 6 Characters or More.");
return false;
}
else if(!emailPattern.matcher(email).matches()) {
LOGGER.error("Email must be in the Form of '<EMAIL>'");
return false;
}
else {
LOGGER.info("Login was Successful");
return true;
}
}
public boolean checkIfUserExists(User user) {
Iterable<User> existingUsers = userService.listAllUsers();
for (User u : existingUsers) {
String userEmail = user.getEmail();
String userUsername = user.getUsername();
boolean userAccountEmailAlreadyExistsInDatabase = u.getEmail().equals(userEmail);
boolean userAccountUsernameAlreadyExistsInDatabase = u.getUsername().equals(userUsername);
if (userAccountEmailAlreadyExistsInDatabase || userAccountUsernameAlreadyExistsInDatabase) {
return true;
}
}
return false;
}
public void registerUserAccount(User user) {
if (!checkIfUserExists(user) && validUserData(user.getEmail(), user.getUsername(), user.getPassword())) {
userService.save(user);
LOGGER.info("Account has been Created and Registered Correctly.");
}
else {
LOGGER.error("Account Creation was Unsuccessful");
throw new UnsuccessfulAccountCreationException();
}
}
@PostMapping(Constants.registrationEndpoint)
public ResponseEntity<String> registerAccount(@RequestBody String string) {
try {
User user = new ObjectMapper().readValue(string, User.class);
registerUserAccount(user);
return ResponseEntity.ok(string);
} catch (UnsuccessfulAccountCreationException | JsonProcessingException ex) {
LOGGER.error("Account Creation was Unsuccessful.");
return ResponseEntity.badRequest().build();
}
}
}
<file_sep>/OnlineStore/src/main/java/com/online/store/services/UserService.java
package com.online.store.services;
import com.online.store.models.User;
import java.util.Optional;
public interface UserService extends Service {
Iterable<User> listAllUsers();
Optional<User> getUserById(Integer id);
}
<file_sep>/OnlineStore/src/main/java/com/online/store/models/Product.java
package com.online.store.models;
import javax.persistence.*;
import java.io.Serializable;
import java.math.BigDecimal;
@Entity
@Table(schema = "products")
public class Product implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String productId;
private String name;
private String description;
private String category;
private BigDecimal price;
private Integer quantityInStock;
public Product(Integer id, String productId, String name, String description, String category, BigDecimal price, Integer quantityInStock) {
this.id = id;
this.productId = productId;
this.name = name;
this.description = description;
this.category = category;
this.price = price;
this.quantityInStock = quantityInStock;
}
public Product() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public Integer getQuantityInStock() {
return quantityInStock;
}
public void setQuantityInStock(Integer quantityInStock) {
this.quantityInStock = quantityInStock;
}
}
<file_sep>/OnlineStore/src/main/java/com/online/store/models/User.java
package com.online.store.models;
import javax.persistence.*;
import java.util.ArrayList;
import java.math.BigDecimal;
import java.util.List;
@Entity
@Table(schema = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String username;
private String email;
private String password;
private String first_name;
private String last_name;
private String address;
@OneToMany
private List<Product> cart;
public User() {
cart = new ArrayList<>();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
// Cart related methods
public List<Product> getCart() {
return cart;
}
public int getCartSize() {
return cart.size();
}
public void addCartItem(Product item) {
this.cart.add(item);
}
public void removeCartItem(Product item) {
this.cart.remove(item);
}
public boolean isItemInCart(Product item) {
return this.cart.contains(item);
}
public Product getCartItem(int index) {
if (this.cart.size() <= index) {
return this.cart.get(index);
}
else {
return null;
}
}
public BigDecimal getTotalCartPrice() {
BigDecimal totalCost = new BigDecimal(0);
for (int i = 0; i < this.cart.size(); i++) {
BigDecimal itemPrice = this.cart.get(i).getPrice();
totalCost.add(itemPrice);
}
return totalCost;
}
}
| c6ac9c2898769be3fa3185f8bf6c57fa93084716 | [
"Markdown",
"Java",
"SQL"
] | 20 | Java | Boontay/Systems-Analyis-and-Design | 81b2aba6928bdb64ce0a2b186f24d6dee3555522 | 950e2d6878c9c0d2679411072856f460f8a5585a |
refs/heads/master | <file_sep> //On page ready
$(function() {
//get API json
$.getJSON('https://www.chapelhillopendata.org/api/records/1.0/search/?dataset=ts_dashboard_test&rows=1000&apikey=<KEY>&callback=?', function(data) {
//create array to hold the separate budgets
var budgets = {};
//loop through data
for (var i = 0; i < data.records.length; i++) {
var item = data.records[i]; //Relevant info
var fund = item.fields.description; //budget name
//If we've never seen this fund name for the given object
//before, create a new listing for it
if (!budgets[fund]) {
//And populate listing with zero values
budgets[fund] = {
"Revised Budget": 0,
"Actual": 0,
"Encumbrances": 0,
"Available": 0
}
}
//Add each subcatgory to main budget fund
budgets[fund]["Revised Budget"] += item.fields["2017_revised_budget"];
budgets[fund]["Actual"] += item.fields["2017_actual"];
budgets[fund]["Encumbrances"] += item.fields["2017_encumbrances"];
budgets[fund]["Available"] += item.fields["2017_available"];
}
//Tranform the fund mapping object into an array of fund names
var funds = $.map(budgets, function(value, index) {
return index;
});
//Get 4 data series from the formatted data
var datasets = [
getData("Revised Budget", budgets),
getData("Actual", budgets),
getData("Encumbrances", budgets),
getData("Available", budgets),
];
//Helper method to create datasets that are properly
//formatted for highcharts
function getData(dataName, dataSet) {
//Set series name
var ret = {
name: dataName
};
//Set series values
ret.data = $.map(dataSet, function(value, key) {
return Math.round(value[dataName]);
});
return ret;
};
// draw chart
$('#container3').highcharts({
chart: {
type: "area"
},
title: {
text: "2017 Technology Solutions Budget"
},
xAxis: {
categories: funds,
title: {
text: "Funds"
},
labels: {
enabled: true
}
},
yAxis: {
title: {
text: "Dollars"
}
},
series: datasets,
legend: {}
});
});
});
<file_sep> //get API json
$.getJSON('https://www.chapelhillopendata.org/api/records/1.0/search/?dataset=ts_dashboard_test&rows=1000&apikey=<KEY>&callback=?', function(data) {
//To hold our JSON data after we've parsed it into highcharts format
var chartData2 = [];
//Loops through our data and formats it for high charts, stores into chartData array
for (var i = 0; i < data.records.length; i++) {
chartData2.push([data.records[i].fields.description, data.records[i].fields['2017_actual']])
}
Highcharts.chart('container2', {
chart: {
type: 'pie',
options3d: {
enabled: true,
alpha: 45,
beta: 0
}
},
title: {
text: '2017 Actual Budget'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
depth: 35,
dataLabels: {
enabled: true,
format: '{point.name}',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
name: 'Budget',
colorByPoint: true,
data: chartData2
}]
});
});
<file_sep>Dashboards Project for Open Data (http://www.chapelhillopendata.org)
------------
<pre>
_____ _ _ _ _ _ _ _
/ __ \ | | | | | | (_) | |
| / \/ |__ __ _ _ __ ___| | | |_| |_| | |
| | | '_ \ / _` | '_ \ / _ \ | | _ | | | |
| \__/\ | | | (_| | |_) | __/ | | | | | | | |
\____/_| |_|\__,_| .__/ \___|_| \_| |_/_|_|_|
| |
|_|
</pre>
<br>
This repository outlines changes and additions to charts, scripts, and more in regards to data sets for the Town of Chapel Hill. Specifically looks at changes in the 2017 Budget and Actuals data set.
| 7beebd65ed5f6c3d0d147ab1915c64d9933243b4 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | townofchapelhill/dashboards | 489ab53e5c017154155b54e038e715b51a047d4e | 73a64372a6ab0f1b82ad77f0d6bfa6b3ad047b4c |
refs/heads/master | <file_sep>ABOUT THIS PROJECT
------------------
Client for the iOS app "Notifications" (aka "Push 4.0").
REQUIREMENTS
------------
- [Python](http://www.python.org/) 2.6 or higher, 3.2 or higher (will probably work on older versions, but these are the supported versions)
- [Push 4.0](http://itunes.apple.com/us/app/push-4.0/id350973572?mt=8) for iOS.
- An [appnotifications.com](http://www.appnotifications.com/) account
INSTALLATION
------------
```$ python setup.py install```
TODO
----
<file_sep>#!/usr/bin/env python
import sys
from setuptools import setup
from notifications import __version__
_py3 = sys.version_info > (3,)
required_pkgs = []
if not _py3: required_pkgs.append("simplejson")
setup(name="notifications",
version=__version__,
description="""Client for the iOS app "Notifications" (aka "Push 4.0").""",
author="<NAME>",
author_email="<EMAIL>",
maintainer="<NAME>",
maintainer_email="<EMAIL>",
url="https://github.com/cjlucas/notifications",
license="ISC",
py_modules=['notifications'],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Intended Audience :: End Users/Desktop',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Communications',
'Topic :: Internet :: WWW/HTTP',
],
install_requires=required_pkgs,
)
| 54c96ac89aa697920f012c7b5370ca2562393533 | [
"Markdown",
"Python"
] | 2 | Markdown | cjlucas/notifications | 6667c9c22c912ab3bae2b19ce9a1b74b6a36e40b | bfdd36a7149eac594a2e18b27a06d330b7c364dc |
refs/heads/master | <file_sep># sp-problem
os teamwork
<file_sep>package onlyfun;
import java.util.Random;
public class InThread extends Thread {
private boolean active;
private int number;
private int situ;
private int temp;
public InThread(int num) {
active = true;
number = num;
situ = 0;
}
public void setActive(boolean active) {
this.active = active;
}
public boolean isActive() {
return active;
}
public void run () {
while(situ<5) {
switch(situ) {
case 0:{
System.out.println(number + "找房間中");
for(int i=0; i<10; i++) {
if(Demo.cubicle[i] == 0) {
Demo.cubicle[i] = number;
temp = i;
situ++;
break;
}
if(i==9)
System.out.println(number + "找不到房間");
}
break;
}
case 1:{
System.out.println(number + "找籃子中");
Demo.cubicle[temp] = 0;
for(int i=0; i<15; i++) {
if(Demo.basket[i] == 0) {
Demo.basket[i] = number;
temp = i;
situ++;
break;
}
if(i==14)
System.out.println(number + "找不到籃子");
}
break;
}
case 2:{
System.out.println(number + "游泳中");
situ++;
break;
}
case 3:{
System.out.println(number + "找房間回家");
for(int i=0; i<10; i++) {
if(Demo.cubicle[i] == 0) {
//Demo.basket[temp] = 0;
Demo.cubicle[i] = number;
temp = i;
situ++;
break;
}
if(i==9)
System.out.println(number + "找不到房間");
}
break;
}
case 4:{
System.out.println(number + "回家囉");
Demo.basket[temp] = 0;
situ++;
Demo.cubicle[temp] = 0;
break;
}
}
try {
Thread.currentThread().sleep(3000);
}
catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}
<file_sep>package osGUI;
public class Demo {
public static int[] cubicle = new int[5];
public static int[] basket = new int[10];
public static int basket_num;
public int number;
public Demo(){
start();
}
public void start() {
number = 0;
basket_num = 0;
}
public void add(){
number++;
InThread inThread = new InThread(number);
inThread.start();
}
}
| 2897969770a711a094ee8d344dc16405eb9c463b | [
"Markdown",
"Java"
] | 3 | Markdown | OS-swimming-pool-30-31/sp-problem | 650d4be8a36530879ca8c140b74a511ee557850b | 32a97f7d1bcaa625f7f2db43dec4ce5ee13ca273 |
refs/heads/master | <file_sep>EXECUTABLE := SometimesRedSometimesBlue.exe
.PHONY: all clean
all: $(EXECUTABLE)
$(EXECUTABLE): Program.cs
gmcs -r:System.Windows.Forms.dll -r:System.Drawing.dll -out:$(EXECUTABLE) Program.cs
clean:
rm -f $(EXECUTABLE)
<file_sep>#include <time.h>
#include <stdlib.h>
#include <windows.h>
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
static WNDCLASSEX wndclass;
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow)
{
static char appName[] = "SomtimesRedSometimesBlue";
HWND hwnd;
MSG msg;
wndclass.cbSize = sizeof(wndclass);
wndclass.style = CS_HREDRAW | CS_VREDRAW;
wndclass.lpfnWndProc = WndProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = hInstance;
wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndclass.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndclass.lpszClassName = appName;
wndclass.lpszMenuName = NULL;
// Red or blue
srand((unsigned int)time(NULL));
if ((rand() % 2) == 0)
{
wndclass.hbrBackground = (HBRUSH)CreateSolidBrush(RGB(255, 0, 0));
}
else
{
wndclass.hbrBackground = (HBRUSH)CreateSolidBrush(RGB(0, 0, 255));
}
RegisterClassEx(&wndclass);
hwnd = CreateWindow(appName,
"Sometimes red sometimes blue",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, CW_USEDEFAULT,
NULL, NULL, hInstance, NULL);
ShowWindow(hwnd, iCmdShow);
UpdateWindow(hwnd);
// Main loop
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT ps;
HDC hdc;
RECT r;
switch (iMsg)
{
case WM_PAINT:
hdc = BeginPaint(hwnd, &ps);
GetClientRect(hwnd, &r);
FillRect(hdc, &r, wndclass.hbrBackground);
EndPaint(hwnd, &ps);
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hwnd, iMsg, wParam, lParam);
}
<file_sep>extern crate piston_window;
extern crate rand;
use piston_window::*;
use rand::Rng;
fn main() {
let mut rng = rand::thread_rng();
let colour = if rng.gen() {
[1.0, 0.0, 0.0, 1.0] // Red
} else {
[0.0, 0.0, 1.0, 1.0] // Blue
};
let mut window: PistonWindow =
WindowSettings::new("Hello Piston!", [640, 480])
.exit_on_esc(true).build().unwrap();
while let Some(event) = window.next() {
window.draw_2d(&event, |_context, graphics| {
clear(colour, graphics);
});
}
}
<file_sep>.PHONY : all fun clean
all: c_rand_test mono_test.exe arc4random-test
c_rand_test: c_rand_test.c
gcc -Wall -lglut -o $@ $<
mono_test.exe: mono_test.cs
gmcs -r:System.Windows.Forms.dll -r:System.Drawing.dll -out:mono_test.exe mono_test.cs
arc4random-test: arc4random-test.c
gcc -lbsd -o $@ $<
fun: arc4random-test
watch -n0.5 ./arc4random-test
clean:
rm -f c_rand_test
rm -f mono_test.exe
rm -f arc4random-test
<file_sep>using System;
using System.Windows.Forms;
using System.Drawing;
namespace SometimesRedSomeTimesBlue
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form()
{
BackColor = ((new Random()).Next(0, 2) == 0) ? Color.Red : Color.Blue,
WindowState = FormWindowState.Maximized,
Text = "Sometimes red, sometimes blue",
});
}
}
}
<file_sep>function love.load()
if (math.random(0, 1) == 0) then
love.graphics.setBackgroundColor(255, 0, 0)
else
love.graphics.setBackgroundColor(0, 0, 255)
end
end
--[[
function love.update(dt)
end
function love.draw()
end
function love.quit()
end
--]]
<file_sep>using System;
namespace SometimesRedSomeTimesBlue
{
static class Program
{
[STAThread]
static void Main()
{
int counts = 0;
int red = 0;
int blue = 0;
while (counts < 1000 * 1000)
{
if ((new Random()).Next(0, 2) == 0)
{
++red;
}
else
{
++blue;
}
counts++;
}
Console.WriteLine("Red = {0}, {1:00.00} percent", red, (double)red / counts * 100);
Console.WriteLine("Blue = {0}, {1:00.00} percent", blue, (double)blue / counts * 100);
}
}
}
<file_sep>Sometimes Red, Sometimes Blue using the SFML
============================================
A desktop GUI implementation of Sometimes Red, Sometimes Blue written in C++ using [SFML (Simple and Fast Multimedia Library)](http://sfml-dev.org/).
## Building
A make file is provided for building on Linux:
$ cd SometimesRedSometimesBlue/Mono/
$ make
The source code for this implementation is cross platform but it will need to be compiled separately for each OS/processor architecture combination.
## Todo
This implementation is still not complete. The following still needs to be done:
* [ ] Open a SFML window with background set to red or blue
* [ ] Build on Windows
<file_sep>CPP := g++
CFLAGS := -Wall -g
all: sometimesredsometimesblue
sometimesredsometimesblue.o: sometimesredsometimesblue.cpp
$(CPP) $(CFLAGS) -c -o $@ $^
sometimesredsometimesblue: sometimesredsometimesblue.o
$(CPP) $(CFLAGS) -lsfml-system -o $@ $^
clean:
rm -f sometimesredsometimesblue
rm -f sometimesredsometimesblue.o
<file_sep>Sometimes red, sometimes blue with git
======================================
Ok, this one is really stupid idea. Basically the script writes either "Red" or "Blue" to `output.txt` and then commits it to a git repository.
Once I write this silly script, I'll probably run it a few times and push the results. Of course if you're reading this, then that has probably already happened.
<file_sep>CC := gcc
CFLAGS := -Wall -O3
#ifeq ($(shell test $$RANDOM -gt 16383; echo $$?),1)
ifeq ($(shell awk 'BEGIN{srand(); printf("%d", 2*rand())}'),0)
RANDOM_COLOUR := red
else
RANDOM_COLOUR := blue
endif
define C_SOURCE_CODE
#include <stdio.h>
int main()
{
puts("Hello $(RANDOM_COLOUR) world");
return 0;
}
endef
export C_SOURCE_CODE
all: main
main: main.c
gcc $(CFLAGS) -o $@ $<
main.c:
echo "$$C_SOURCE_CODE" > $@
clean:
rm -f main
rm -f main.c
<file_sep>.PHONY : all win32 win64 clean
WIN32_CC := i586-mingw32msvc-gcc
WIN64_CC := amd64-mingw32msvc-gcc
WIN32_BIN := SometimesRedSomtimesBlue_win32.exe
WIN64_BIN := SometimesRedSomtimesBlue_win64.exe
all: win32 win64
win32: $(WIN32_BIN)
win64: $(WIN64_BIN)
$(WIN32_BIN): SometimesRedSomtimesBlue.c
$(WIN32_CC) -mwindows SometimesRedSomtimesBlue.c -o $(WIN32_BIN)
$(WIN64_BIN): SometimesRedSomtimesBlue.c
$(WIN64_CC) -mwindows SometimesRedSomtimesBlue.c -o $(WIN64_BIN)
clean:
rm -f $(WIN32_BIN) $(WIN64_BIN)
<file_sep>#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
int counts = 0;
int red = 0;
int blue = 0;
while(counts < 100 * 1000)
{
srand((unsigned int)time(NULL));
if ((rand() % 2) == 0)
{
++red;
}
else
{
++blue;
}
counts++;
}
printf("red = %i, %2.2f percent\n", red, (double)red / counts * 100);
printf("blue = %i, %2.2f percent\n", blue, (double)blue / counts * 100);
return 0;
}
<file_sep>CC := gcc
CFLAGS := -Wall -g
LIBS := -lbsd -lglut -lGL
all: sometimesredsometimesblue
sometimesredsometimesblue.o: sometimesredsometimesblue.c
$(CC) $(CFLAGS) -c -o $@ $<
sometimesredsometimesblue: sometimesredsometimesblue.o
$(CC) $(CFLAGS) $(LIBS) -o $@ $<
clean:
rm -f sometimesredsometimesblue
rm -f sometimesredsometimesblue.o
<file_sep>Making with a Makefile
======================
Building source code with make isn't enough, I want make to generate my source code too.
MakingWithAMakefile$ ls
Makefile README.txt
MakingWithAMakefile$ make
echo "$C_SOURCE_CODE" > main.c
gcc -Wall -O3 -o main main.c
MakingWithAMakefile$ ls
Makefile README.txt main main.c
MakingWithAMakefile$ ./main
Hello red world
MakingWithAMakefile$ ./main
Hello red world
MakingWithAMakefile$ make -s clean && make -s && ./main
Hello blue world
Thanks
------
Thankyou to the following web pages, and their authors, who's help allowed me to churn this makefile out in single-glass-of-scotch time ... I had a second glass to celebrate of course.
* https://askubuntu.com/questions/400888/how-can-i-get-the-bash-random-in-a-makefile
* http://www.tldp.org/LDP/abs/html/randomvar.html
* https://stackoverflow.com/questions/8281345/how-to-get-current-linux-process-id-pid-from-cmdline-in-shell-and-language-i/8281456#8281456
* https://stackoverflow.com/questions/649246/is-it-possible-to-create-a-multi-line-string-variable-in-a-makefile
<file_sep># Somtimes Red, Sometimes Blue
A desktop implementation of the fantastic web page [www.sometimesredsometimesblue.com](http://www.sometimesredsometimesblue.com) written in [Clojure](http://clojure.org/) using the [Seesaw library](https://github.com/daveray/seesaw).
## Usage
This project is managed with [Leiningen](http://leiningen.org/). You can build and run it like this:
$ lein run
and you can package the project and dependencies as standalone jar like this:
$ lein uberjar
## License
Copyright © 2014 <NAME>
Distributed under the zlib license.
<file_sep>CC := gcc
CFLAGS := -Wall -g
LIBS := -lbsd
.PHONY : all clean
all: fbsometimesredsometimesblue
fbsometimesredsometimesblue: fbsometimesredsometimesblue.o
$(CC) $(CFLAGS) $(LIBS) -o $@ $<
fbsometimesredsometimesblue.o: fbsometimesredsometimesblue.c
$(CC) $(CFLAGS) -c -o $@ $<
clean:
rm -f fbsometimesredsometimesblue
rm -f fbsometimesredsometimesblue.o
<file_sep>def setup():
size(800, 600);
if (random(0, 1) > 0.5):
background(255, 0, 0); # Red
else:
background(0, 0, 255); # Blue
<file_sep>[package]
name = "sometimes_red_sometimes_blue"
version = "0.1.0"
authors = ["Phil <<EMAIL>>"]
[dependencies]
piston_window = "0.81.0"
rand = "0.6.1"
<file_sep>#!/usr/bin/env python
import random
counts = 0;
red = 0.0;
blue = 0.0;
while (counts < 1000 * 1000):
color = random.choice(['red', 'blue'])
counts = counts + 1
if color == 'red':
red = red + 1
else:
blue = blue + 1
print 'Red = ', red, ',', (red / counts * 100), 'percent'
print 'Blue = ', blue, ',', (blue / counts * 100), 'percent'
<file_sep>#include <SFML/System.hpp>
#include <iostream>
int main()
{
if (sf::Randomizer::Random(0, 1) == 0)
{
std::cout << "Red" << std::endl;
}
else
{
std::cout << "Blue" << std::endl;
}
return 0;
}
<file_sep>Sometimes Red, Sometimes Blue for .NET/Mono
===========================================
A desktop GUI implementation of Sometimes Red, Sometimes Blue using the .NET or [Mono](http://www.mono-project.com/Main_Page) frameworks.
A make file is provided for building on Linux:
$ cd SometimesRedSometimesBlue/Mono/
$ make
The executable should run on any platform supported by either the .NET or [Mono](http://www.mono-project.com/Main_Page) frameworks.
<file_sep>#include <QPalette>
#include <QDateTime>
#include "mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
time_t t = QDateTime::currentDateTime().toTime_t();
qsrand(t);
if (qrand() % 2 == 0)
{
this->window()->setPalette(QPalette( Qt::red ));
}
else
{
this->window()->setPalette(QPalette( Qt::blue ));
}
}
MainWindow::~MainWindow()
{
}<file_sep>[package]
name = "sometimes-red-sometimes-blue-rust-glutin"
version = "0.1.0"
authors = ["Phil <<EMAIL>>"]
[dependencies]
gl = "0.6.1"
glutin = "0.9.2"
rand = "0.3"
<file_sep>Sometimes Red, Sometimes Blue randomness tests
==============================================
Randomness tests in a few different languages. Don't mistake this code as a serious test of randomness, I just wrote one because I was mildly curious about what the result would be and wrote the others so the first wouldn't feel alone.
Sometime Red, Sometimes blue does not require truly random numbers anyway.
<file_sep>#!/bin/sh
SHUF_CMD=$(which shuf 2>/dev/null || which gshuf 2>/dev/null)
if [ ! -x "$SHUF_CMD" ]; then
echo "You'll need to install the `shuf` command or rewrite this script" >&1
exit 1
fi
if [ $("$SHUF_CMD" -i0-1 -n1) -eq 0 ]; then
COLOUR="Red"
else
COLOUR="Blue"
fi
echo "$COLOUR"
if [ $(head -n1 output.txt) = "$COLOUR" ]; then
echo "$COLOUR" >> output.txt # Same colour last time - Append to file
else
echo "$COLOUR" > output.txt # Different colour - Overwrite file
fi
git add output.txt
git commit -m "Git script: $COLOUR" output.txt
<file_sep>Sometimes Red, Sometimes Blue with win32
========================================
A desktop GUI implementation Sometimes Red, Sometimes Blue win32 written in C using the win32 API.
Building
--------
To build on Linux you need to the mingw32 development files and you need to have i586-mingw32msvc-gcc and amd64-mingw32msvc-gcc in you $PATH. On Debian you can achieve all of this by installing the gcc-mingw32 package:
$ sudo apt-get install gcc-mingw32
Then you can use the provided make file to build both 32-bit and 64-bit executables:
$ cd SometimesRedSometimesBlue/win32/
$ make
Reference
---------
* http://winapi.freetechsecrets.com/win32/WIN32Window_Background.htm
* http://msdn.microsoft.com/en-us/library/bb384843.aspx
* http://www.fredosaurus.com/notes-cpp/misc/random.html
<file_sep>coffee.editor.tabs.size=2
mode.id=de.bezier.mode.coffeescript.CoffeeScriptMode
mode=de.bezier.mode.coffeescript.CoffeeScriptMode
<file_sep>#!/usr/bin/env python
#-------------------------------------------------------------------------------
# Name: Sometimes red, sometimes blue
# Purpose: A desktop recreation of www.sometimesredsometimesblue.com
# Author: phil
# Created: 2011-09-14
# Copyright: (c) <NAME> 2011
# Licence: zlib license
#-------------------------------------------------------------------------------
import random
import Tkinter
color = random.choice(["#FFF000000", "#000000FFF"])
root = Tkinter.Tk()
root.state("zoomed")
canvas = Tkinter.Canvas(root, width=root.winfo_screenwidth(),
height=root.winfo_screenheight(), background=color)
canvas.pack()
Tkinter.mainloop()
<file_sep>EXT := png
RESOLUTION := 800x800
ALL := red.$(EXT) blue.$(EXT)
.PHONY: all clean
all: $(ALL)
red.$(EXT):
convert -size $(RESOLUTION) xc:red $@
blue.$(EXT):
convert -size $(RESOLUTION) xc:blue $@
clean:
rm $(ALL)
<file_sep>Sometimes Red, Sometimes Blue for Love 2D
=========================================
A desktop implementation of Sometimes Red, Sometimes Blue using the [Love 2D](https://love2d.org/).
Use the play.sh script to run the game on Linux or use the play.bat script to play on Windows.
You can use the provided make file to create a .love package:
$ cd SometimesRedSometimesBlue/Love/
$ make
<file_sep>SOURCES := main.lua conf.lua
GAME_NAME := SomtimesRedSometimesBlue
LOVE_PACKAGE := bin/$(GAME_NAME).love
LOVE_BIN := $(shell which love)
ifeq ($(LOVE_BIN),)
$(warning Love binary not found, unable to make Linux binary)
LINUX_EXECUTABLE :=
else
LINUX_EXECUTABLE := bin/$(GAME_NAME).bin
endif
.PHONY : all clean
all: $(LOVE_PACKAGE) $(LINUX_EXECUTABLE)
$(LOVE_PACKAGE): $(SOURCES)
mkdir -p bin/
zip $(LOVE_PACKAGE) $(SOURCES)
$(LINUX_EXECUTABLE): $(LOVE_PACKAGE)
cat $(LOVE_BIN) $(LOVE_PACKAGE) > $(LINUX_EXECUTABLE)
chmod +x $(LINUX_EXECUTABLE)
clean:
rm -rf bin/
<file_sep>Sometimes red, sometimes blue
=============================
Inspired by the truly inspirational [www.sometimesredsometimesblue.com](http://www.sometimesredsometimesblue.com).
<file_sep>
-- GLOBALS: math, display, os, Runtime
local function SometimesRedSometimesBlue()
local zeroOrOne = math.round(math.random())
if zeroOrOne == 0 then
display.setDefault( "background", 0, 0, 1 ) -- Red
else
display.setDefault( "background", 1, 0, 0 ) -- Blue
end
-- Always return true in case this function is used as an event handler
return true
end
local function main()
math.randomseed(os.time())
display.setStatusBar(display.HiddenStatusBar)
Runtime:addEventListener('touch', SometimesRedSometimesBlue)
Runtime:addEventListener('system', function(event)
if event.type == "applicationStart" or
event.type == 'applicationResume' then
return SometimesRedSometimesBlue()
end
end)
Runtime:addEventListener("accelerometer", function(event)
if event.isShake then
return SometimesRedSometimesBlue()
end
end)
end
main()
<file_sep>Sometimes Red, Sometimes Blue using the QT framework
====================================================
A desktop GUI implementation of Sometimes Red, Sometimes Blue written in C++ using the [QT framework](https://qt-project.org/).
This project can be build using [QTCreator](http://qt-project.org/wiki/Category:Tools::QtCreator) or from the command line using qmake:
$ cd SometimesRedSometimesBlue/qtSometimesRedSometimesBlue/
$ qmake
$ make
$ ./qtSometimesRedSometimesBlue
Building from the command line might work slightly differntly on different operating systems, for example on Windows the resulting executable will be called qtSometimesRedSometimesBlue.exe and be located in Debug or Release subdirectories.
<file_sep>/* Sometimes red, sometimes blue using OGL (Open Graphics Library) */
#include <GL/glut.h>
#include <time.h>
#include <stdlib.h>
#include <bsd/stdlib.h>
void setBackgroundColour(void)
{
if (arc4random_uniform(2) == 0)
{
glClearColor(255, 0, 0, 0); // Red
}
else
{
glClearColor(0, 0, 255, 0); // Blue
}
}
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glFlush();
}
void reshape(int width, int height)
{
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-1, 1, -1, 1, -1, 1);
glMatrixMode(GL_MODELVIEW);
display();
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowPosition(50, 50);
glutInitWindowSize(500, 500);
glutCreateWindow("Sometimes red, sometimes blue");
setBackgroundColour();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMainLoop();
return 0;
}
<file_sep>/*
* Comparing arc4random() to rand()
*
* Build it like this:
*
* $ gcc -o arc4random-test arc4random-test.c -lbsd
*
*/
#include <stdio.h>
#include <bsd/stdlib.h>
int main()
{
//u_int32_t arc4random(void);
//void arc4random_buf(void *buf, size_t nbytes);
//u_int32_t arc4random_uniform(u_int32_t upper_bound);
//void arc4random_stir(void);
//void arc4random_addrandom(unsigned char *dat, int datlen);
u_int32_t a = arc4random();
printf("arc4random() = 0x%x, %u\n", a, a);
int r = rand();
printf("rand() = 0x%x, %i\n", r, r);
char* arc4Colour = (arc4random_uniform(2) == 0) ? "Red" : "Blue";
char* randColour = (rand() % 2 == 0) ? "Red" : "Blue";
printf("arc4Colour = %s\n", arc4Colour);
printf("randColour = %s\n", randColour);
return 0;
}
<file_sep>Sometimes Red, Sometimes Blue for OpenGL
========================================
An OpenGL implementation of Sometimes Red, Sometimes Blue written in C using the [FreeGLUT](http://freeglut.sourceforge.net/) library.
To build on Linux you need to the FreeGLUT library and it's development files. On Debian you can install them like this:
$ sudo apt-get install freeglut3 freeglut3-dev
After those dependencies are installed you can use the provided make file to build the executable:
$ cd SometimesRedSometimesBlue/OpenGL/
$ make
<file_sep>#!/bin/sh
exec love .
<file_sep>Sometimes Red, Sometimes Blue direct to a framebuffer near you
==============================================================
Sometimes Red, Sometimes Blue written straight to your framebuffer.
This code was shamelessly stolen from [this Stack Overflow question](http://stackoverflow.com/questions/4996777/paint-pixels-to-screen-via-linux-framebuffer) and modified to provide the classic Sometimes Red, Sometimes Blue pizazz.
As pointed out on the Stack Overflow answers; writing directly to the framebuffer while an X server is running is a bad idea leading to undefined behaviour, burning cats and the end of days. So this application probably shouldn't be used that way, however it could be very useful in the future implementations such as the bootable Sometimes Red, Sometimes Blue operating system.
Building
--------
A make file is provided for building on Linux:
$ cd SometimesRedSometimesBlue/DirectToFrameBuffer/
$ make
Running
-------
If the application is run without arguements it will will to /dev/fb0
$ ./fbsometimesredsometimesblue
or you can specify a framebuffer to write to like this:
$ ./fbsometimesredsometimesblue /dev/fb1
<file_sep>extern crate gl;
extern crate glutin;
extern crate rand;
use glutin::GlContext;
use rand::Rng;
fn main() {
let mut events_loop = glutin::EventsLoop::new();
let window = glutin::WindowBuilder::new()
.with_title("Sometimes red, sometimes blur")
//.with_dimensions(1024, 768)
;
let context = glutin::ContextBuilder::new()
.with_vsync(true);
let gl_window = glutin::GlWindow::new(window, context, &events_loop).unwrap();
unsafe {
gl_window.make_current().unwrap();
}
gl::load_with(|symbol| gl_window.get_proc_address(symbol) as *const _);
let mut rng = rand::thread_rng();
if rng.gen() {
unsafe { gl::ClearColor(1.0, 0.0, 0.0, 1.0); } // Red
} else {
unsafe { gl::ClearColor(0.0, 0.0, 1.0, 1.0); } // Blue
}
let mut running = true;
while running {
unsafe { gl::Clear(gl::COLOR_BUFFER_BIT) };
gl_window.swap_buffers().unwrap();
events_loop.poll_events(|event| {
match event {
glutin::Event::WindowEvent{ event, .. } => match event {
glutin::WindowEvent::Closed => running = false,
_ => ()
},
_ => ()
}
});
}
}
| 3b6f8fd76ba15977616d0f79f33825fe10ea6d31 | [
"Lua",
"Markdown",
"TOML",
"Makefile",
"INI",
"C#",
"Rust",
"Python",
"C",
"C++",
"Shell"
] | 41 | Makefile | PhilboBaggins/SometimesRedSometimesBlue | cb2f899df2bbad102d964d29227f67312dc1e38a | f0a0315a47057d09a258bcd5ac7dc5c663a295d5 |
refs/heads/master | <repo_name>jsuarezbaron/Proy_BOD_CESE<file_sep>/PWM_Motor_V2/src/PWM_Motor_V2.c
/*============================================================================
* Test si puedo modificar el código
* Autor: <NAME>
* Licencia:
* Fecha:09/05/2018
*
* * Programa para controlar el sentido y velocidad de giro de un motor Dc de 12v
* con el driver basado en el L298n
* Pines de configuración del L298n:
*ENA ------> GPIO8 Salida de PWM de la Edu CIAA: PWM6
*ENB ------> GPIO2 Salida de PWM de la Edu CIAA: PWM10
*IN1 ------> GPIO5
*IN2 ------> GND
*IN3 ------> GPIO6
*IN4 ------> GND
*
* Pines para otras conexiones:
* Solenoide1: GPIO7
*
*
*
*
*===========================================================================*/
/*==================[inlcusiones]============================================*/
//#include "program.h" // <= su propio archivo de cabecera (opcional)
#include "sapi.h" // <= Biblioteca sAPI
/*==================[definiciones y macros]==================================*/
// Esto es pensando en que el driver del motor tiene un pin donde si se
// pone en ON se gira a la derecha y si se pone en OFF gira a la izquierda.
// Ver si va asi o invertido segun el driver
/* Se modifica el código para el driver VNH2SP30 de ST:
/* Ref: SparkFun Monster Moto Shield
* https://www.sparkfun.com/products/10182
*
// Monster Motor Shield VNH2SP30 Pinout:
A0 : Enable pin for motor 1 (INA)
A1 : Enable pin for motor 2 (INB)
A2 : Current sensor for motor 1 (CS)
A3 : Current sensor for motor 2 (CS)
D7 : Clockwise (CW) for motor 1
D8 : Counterclockwise (CCW) for motor 1
D4 : Clockwise (CW) for motor 2
D9 : Counterclockwise (CCW) for motor 2
D5 : PWM for motor 1
D6 : PWM for motor 2 */
#define BRAKE 0
#define CW 1
#define CCW 2
#define CS_THRESHOLD 150 // Definition of safety current (Check: "1.3 Monster Shield Example").
#define MOTOR_1 0
#define MOTOR_2 1
#define MOTOR_3 2
#define GIRO_DERECHA ON
#define GIRO_IZQUIERDA OFF
// Pines a utilizar
#define PIN_PWM_MOTOR PWM7 // Es (CAMBIAR) Pin de salida PWM donde conecto el motor (PWM7 = LED1)
#define PIN_GPIO_SENTIDO_IN1 LEDB // (CAMBIAR) Pin que le da al driver el sentido de giro
#define PIN_GPIO_MOT_DER LED2 // Pin de led que indica el sentido de giro a la derecha
#define PIN_GPIO_MOT_IZQ LED3 // Pin de led que indica el sentido de giro a la izquierda
// Si LED2 y LED3 apagados, entonces motor detenido
// Pines a utilizar //
#define ENA PWM7 // (CAMBIAR) Pin de salida PWM donde conecto el motor (PWM7 = LED1)
#define ENB PWM6 // Salida de PWM de la Edu CIAA: PWM6
#define IN1 GPIO5 // Entrada 1 del L298n
#define IN3 GPIO6 // Entrada 3 del L298n*/
#define LED_INDICADOR_SENTIDO LEDR
/*==================[definiciones de datos internos]=========================*/
DEBUG_PRINT_ENABLE
//CONSOLE_PRINT_ENABLE
/*==================[definiciones de datos externos]=========================*/
static uint8_t menu[] =
"\n\r"
"********************* MENU DE SELECCION********************\n\r"
"TEC1: Encender Motor.\n\r"
"TEC2: Detener la secuencia.\n\r"
"TEC3: Invertir Sentido De Giro.\n\r"
"TEC4: Iniciar secuencia no bloqueante.\n\r"
"1. Detener Motor.\n\r"
"2. Girar Adelante.\n\r"
"3. Girar Atrás.\n\r"
"+. Incrementar Velocidad.\n\r"
"-. Disminuir Velocidad.\n\r"
""
;
/*==================[declaraciones de funciones internas]====================*/
/*==================[declaraciones de funciones externas]====================*/
bool_t sentidoGiro = GIRO_DERECHA; // Sentido de giro actual. Inicialmente gira a la derecha
uint8_t velocidad = 0; // Velocidad del motor, de 0 a 100
uint8_t secuencia = OFF; // Iniciar secuencia
delay_t tiempoEncendido; // Variable de Retardo no bloqueante
void driverInicializarMotor( void ){
gpioConfig( PIN_GPIO_SENTIDO_IN1, GPIO_OUTPUT ); // Configurar los pines GPIO utilizados
gpioConfig( PIN_GPIO_MOT_DER, GPIO_OUTPUT );
gpioConfig( PIN_GPIO_MOT_IZQ, GPIO_OUTPUT );
gpioConfig( LED_INDICADOR_SENTIDO, GPIO_OUTPUT );
gpioWrite( PIN_GPIO_SENTIDO_IN1, sentidoGiro ); // Inicialmente gira a la derecha
gpioWrite( LED_INDICADOR_SENTIDO, sentidoGiro );
pwmConfig( 0, PWM_ENABLE ); // Configurar timers para modo PWM
pwmConfig( PIN_PWM_MOTOR, PWM_ENABLE_OUTPUT ); // Enciendo el pin de salida que quiero en modo PWM
// 0=0% a 255=100%
pwmWrite( PIN_PWM_MOTOR, 0 ); // Inicio el PWM detenido (duty cycle = 0%)
// Inicializar Retardo no bloqueante con tiempo en milisegundos
// (1000ms = 1s)
delayConfig( &tiempoEncendido, 0 );
}
void driverActualizarLedsIndicadores( void ){
if( velocidad == 0 ){
// Apagar los leds indicadores de sentido de giro
gpioWrite( PIN_GPIO_MOT_DER, OFF );
gpioWrite( PIN_GPIO_MOT_IZQ, OFF );
} else{
if( sentidoGiro == GIRO_DERECHA ){
// Setear debidamente los leds indicadores de sentido de giro
gpioWrite( PIN_GPIO_MOT_DER, ON );
gpioWrite( PIN_GPIO_MOT_IZQ, OFF );
//debugPrintlnString( "Bomba girando a la der.\n\r\0" );
} else{
// Setear debidamente los leds indicadores de sentido de giro
gpioWrite( PIN_GPIO_MOT_DER, OFF );
gpioWrite( PIN_GPIO_MOT_IZQ, ON );
//debugPrintlnString( "Bomba girando a la izq.\n\r\0" );
}
}
}
void driverSetearVelocidad( uint8_t vel ){
velocidad = vel;
// Seteo el ciclo de trabajo del PWM al dutyCycle % = velociad
// Seteo el ciclo de trabajo del PWM va de 0 a 255
pwmWrite( PIN_PWM_MOTOR, velocidad*255/100 );
// Actualizar leds indicadores
driverActualizarLedsIndicadores();
}
void driverEncenderMotor( void ){
secuencia = OFF;
debugPrintlnString( "Motor Encendido.\n\r\0" )
driverSetearVelocidad( 10 );
}
void driverDetenerMotor( void ){
secuencia = OFF;
debugPrintlnString( "Motor Apagado.\n\r\0" )
driverSetearVelocidad( 0 );
}
void driverCambiarSentidoDeGiro( bool_t sentido ){
sentidoGiro = sentido;
// Cambiar sentido de giro (pin)
gpioWrite( PIN_GPIO_SENTIDO, sentidoGiro );
// Actualizar leds indicadores
driverActualizarLedsIndicadores();
}
void driverInvertirSentidoDeGiro( void ){
if( sentidoGiro == GIRO_DERECHA ){
driverCambiarSentidoDeGiro( GIRO_IZQUIERDA );
debugPrintlnString( "Girando a la izquierda.\n\r\0" )
} else{
driverCambiarSentidoDeGiro( GIRO_DERECHA );
debugPrintlnString( "Girando a la derecha.\n\r\0" )
}
}
void driverIncrementarVelocidad( void ){
velocidad = velocidad + 10;
if( velocidad > 255 ){
velocidad = 255;
}
debugPrintlnString( "Velocidad +=:\r\0" )
debugPrintIntFormat( velocidad, DEC_FORMAT );
debugPrintlnString( "\r" );
//printf("Velocidad +=: %d", velocidad);
driverSetearVelocidad( velocidad );
}
void driverDecrementarVelocidad ( void ){
velocidad = velocidad - 10 ;
if( velocidad < 0){
velocidad = 0;
}
debugPrintlnString( "Velocidad -=:\r\0 " )
debugPrintIntFormat( velocidad, DEC_FORMAT );
debugPrintlnString( "\r" );
driverSetearVelocidad( velocidad );
}
void driverElegirSentido_y_Velocidad ( void ){
char entradaUsuario;
//uint8_t entradaUsuario;
if (uartReadByte( UART_USB, &entradaUsuario ) != FALSE) {
if(entradaUsuario != 0)
switch ( entradaUsuario ) {
case '1':{
driverDetenerMotor();
}break;
case '2':{
driverInvertirSentidoDeGiro();
}break;
case '3':{
driverInvertirSentidoDeGiro();
}break;
case '+':{
driverIncrementarVelocidad();
}break;
case '-':{
driverDecrementarVelocidad();
}break;
default:
uartWriteString(UART_USB, menu);
uartWriteString(UART_USB, "Caracter recibido fuera de menu\n\r");
break;
}
}
}
// Secuencia Bloqueante:
// Encender motor con ciclio de trabajo (duty cycle) al:
// - 25%, por 4 segundos
// - 50%, por 3 segundos
// - 75%, por 2 segundos
// - 100%, por 1 segundos
// Luego detener el motor.
// Al ser bloqueante hay que esperar a que complete la secuencia
// para que permita responder a otros botones.
void driverSecuenciaBloqueante( void ){
// Seteo la velocidad al 25%
driverSetearVelocidad( 25 );
delay(4*1000);
// Seteo la velocidad al 50%
driverSetearVelocidad( 50 );
delay(3*1000);
// Seteo la velocidad al 75%
driverSetearVelocidad( 75 );
delay(2*1000);
// Seteo la velocidad al 100%
driverSetearVelocidad( 100 );
delay(3*1000);
// Detener motor
driverDetenerMotor();
}
// Secuencia No bloqueante:
// Encender motor con ciclio de trabajo (duty cycle) al:
// - 25%, por 4 segundos
// - 50%, por 3 segundos
// - 75%, por 2 segundos
// - 100%, por 1 segundos
// Luego detener el motor.
// Al ser no bloqueante se puede detener la secuencia con TEC2 en cualquier momento.
void driverSecuenciaNoBloqueante( void ){
static uint8_t fase = 0;
if( secuencia == ON ){
// Si se cumple el tiempo, cambiar de estado
if( delayRead( &tiempoEncendido ) ){
switch( fase ){
case 0:
// Seteo la velocidad al 25%
driverSetearVelocidad( 25 );
fase++;
delayWrite( &tiempoEncendido, 4*1000 );
debugPrintlnString( "Bomba al 25% \n\r\0" );
break;
case 1:
// Seteo la velocidad al 50%
driverSetearVelocidad( 50 );
fase++;
delayWrite( &tiempoEncendido, 3*1000 );
debugPrintlnString( "Motor al 50% \n\r\0" );
break;
case 2:
// Seteo la velocidad al 75%
driverSetearVelocidad( 75 );
fase++;
delayWrite( &tiempoEncendido, 2*1000 );
debugPrintlnString( "Motor al 75% \n\r\0" );
break;
case 3:
// Seteo la velocidad al 100%
driverSetearVelocidad( 100 );
fase++;
delayWrite( &tiempoEncendido, 1*1000 );
debugPrintlnString( "Motor al 100% \n\r\0 " );
break;
default:
fase = 0;
secuencia = OFF;
driverDetenerMotor();
delayWrite( &tiempoEncendido, 0 );
break;
}
}
} else{
fase = 0;
}
}
void driverSecuencaTemporizada(void){
if( delayRead( &tiempoEncendido ) ){
driverSetearVelocidad( 100 );
delayWrite( &tiempoEncendido, 1*10000 );
}
}
/*==================[funcion principal]======================================*/
// FUNCION PRINCIPAL, PUNTO DE ENTRADA AL PROGRAMA LUEGO DE ENCENDIDO O RESET.
int main( void ){
// ---------- CONFIGURACIONES ------------------------------
// Inicializar y configurar la plataforma
boardConfig();
// Inicializar UART_USB como salida Serial de debug
debugPrintConfigUart( UART_USB, 115200 );
debugPrintlnString( "DEBUG: UART_USB configurada." );
// Inicializar driver de motor
driverInicializarMotor();
debugPrintlnString(menu);
// ---------- REPETIR POR SIEMPRE --------------------------
while( TRUE )
{
driverElegirSentido_y_Velocidad();
// Iniciar Motor con TEC1
if( !gpioRead( TEC1 ) ){
driverEncenderMotor(); // Enciende el motor con un duty cyle al 100%
}
// Detener Motor con TEC2
if( !gpioRead( TEC2 ) ){
driverDetenerMotor();
}
// Invertir sentido de giro con TEC3
if( !gpioRead( TEC3 ) ){
driverInvertirSentidoDeGiro();
delay(500); // Para evitar rebotes
}
/* ---------- Opcion 1, bloqueante ---------------- */
// Iniciar secuencia bloqueante con TEC4:
/*if( !gpioRead( TEC4 ) ){
driverSecuenciaBloqueante();
}*/
/* ---------- Opcion 2, no bloqueante ------------- */
// Iniciar secuencia no bloqueante con TEC4:
if( !gpioRead( TEC4 ) ){
secuencia = ON;
}
driverSecuenciaNoBloqueante();
}
// NO DEBE LLEGAR NUNCA AQUI, debido a que a este programa se ejecuta
// directamenteno sobre un microcontroladore y no es llamado por ningun
// Sistema Operativo, como en el caso de un programa para PC.
return 0;
}
/*==================[definiciones de funciones internas]=====================*/
/*==================[definiciones de funciones externas]=====================*/
/*==================[fin del archivo]========================================*/
<file_sep>/README.md
# Proy_BOD_CESE
Preliminares de Requerimientos Pro_BOD_CESE
| 0af8821b4e7ee2d7c10e2c00927d6c64870643b2 | [
"Markdown",
"C"
] | 2 | C | jsuarezbaron/Proy_BOD_CESE | 2f9d0fe6372ce9af416c4840b4aa4f613df7feae | 9f4f01fc85f99eea4ebc154d959e83b8de86ea76 |
refs/heads/master | <file_sep># csv_reader
Simple CSV file reader
<br><br>
<table>
<tr style="padding:5px;">
<td>Install app</td>
<td>npm install</td>
</tr>
<tr style="padding:5px;">
<td>Run app</td>
<td>npm start</td>
</tr>
<tr style="padding:5px;">
<td>Run test</td>
<td>npm test</td>
</tr>
</table>
<file_sep>
var chai = require('chai');
var chaiHttp = require('chai-http');
var should = chai.should();
var app = require("../app");
chai.use(chaiHttp);
describe('Tests', function () {
describe('/ping', function () {
it('it should ping service', function (done) {
chai.request(app)
.get('/')
.end(function (err, res) {
res.should.have.status(200);
done();
});
});
});
});
<file_sep>var express = require('express');
var formidable = require('formidable');
var path = require('path');
var fs = require('fs');
var sqlLite = require('../models/sqlLite');
var router = express.Router();
router.get('/', function(req, res, next) {
res.render('index', { title: 'Simple csv file reader' });
});
router.post('/upload', function(req, res){
var form = new formidable.IncomingForm();
var fileName;
form.uploadDir = path.join(__dirname, '..', 'uploads');
form.parse(req);
form.on('file', function(field, file) {
fileName = file.name;
fs.rename(file.path, path.join(form.uploadDir, file.name));
});
form.on('error', function(err) {
console.log('An error has occured: \n' + err);
res.status(500).send(JSON.stringify(err));
});
form.on('end', function() {
var stream = fs.createReadStream(path.join(__dirname, '..', 'uploads', fileName));
stream.pipe(res);
stream.on('error', function(err){
console.log('An error has occured: \n' + err);
res.status(500).send(JSON.stringify(err));
});
stream.on('end', function(){
sqlLite.save(fileName, function(err, done){
if (err) {
console.log('An error has occured durring save file to DB: \n' + err);
} else {
console.log('Done');
}
})
});
});
});
module.exports = router;
<file_sep>var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database(':memory:');
var fs = require('fs');
var path = require('path');
var csv = require('fast-csv');
var model = {};
model.save = function(fileName, cb) {
db.serialize(function() {
db.run("CREATE TABLE IF NOT EXISTS customers (firstName TEXT, lastName TEXT, email TEXT)");
var stream = fs.createReadStream(path.join(__dirname, '..', 'uploads', fileName));
var stmt = db.prepare("INSERT INTO customers VALUES (?,?,?)");
var csvStream = csv()
.on("data", function(data){
if (3 === data.length){
stmt.run(data[0], data[1], data[2]);
}
})
.on("end", function(){
stmt.finalize();
//Uncoment to see resulls in sqLite
// db.each("SELECT rowid AS id, firstName, lastName, email FROM customers", function(err, row) {
// console.log(row.id + ": " + row.firstName + ', ' + row.lastName + ', ' + row.email);
// });
cb(null,'OK');
});
stream.pipe(csvStream);
});
}
process.on('SIGINT', function() {
db.close();
});
module.exports = model; | 019ee1177014f8355b59f226ac21066c21315060 | [
"Markdown",
"JavaScript"
] | 4 | Markdown | Dinaris/csv_reader | 347dc2bd577dac2c1d6b5421e89a6433d474cc3f | 8b423c730b591ba61d6fcc4b5ca649df6c9525dc |
refs/heads/master | <file_sep>var gulp = require('gulp');
var flatten = require('gulp-flatten');
var debug = require('gulp-debug');
var del = require('del')
gulp.task('clean', function() {
del(['./flat/*.*', '!./flat/.gitkeep']).sync;
});
gulp.task('flat', function() {
return gulp
.src(['./source/**/*.{jpeg,pjpeg,jpg,png,svg}'])
.pipe(debug({title: 'file found:'}))
.pipe(flatten())
.pipe(gulp.dest('./flat'));
});
gulp.task('default', ['clean', 'flat']);
<file_sep># flat-catalog-images
Simple tool to flat catalog images
| 35104dddece812197e902983bbfadbb20051e62b | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | ihaltsou/flat-catalog-images | 7dd66076448bdf0e8b233364fb1638784cff3ee1 | e7a8ba944ada7c63bccf150c0b8d20bb21e77f44 |
refs/heads/main | <file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SoundScript : MonoBehaviour
{
//The sounds that will when when an objects enters this trigger
public AudioClip triggersound;
//The audio source that will play that sound
public AudioSource source;
private AudioClip triggerSound;
private void OnTriggerEnter(Collider other)
{
//Tell the source to play sound triggerSound once
source.PlayOneShot(triggerSound);
}
}
| 9e5baaf4e1b1d9bff85c27bc4cb3fa06d48a2f29 | [
"C#"
] | 1 | C# | Ebove25/Unity-Projects | 38e2b71a7c157bcd6bf5ed248c2f1fe2f3978def | 245a2a9fb1ae8dd97081ff4ba3719d1722e2acef |
refs/heads/master | <repo_name>JoshuaSG3161/FRCPractice<file_sep>/Locks.java
package Basics_201;
public class Locks {
public int password;
private boolean locked;
Locks Locky = new Locks();
Locks Lockette = new Locks();
public Locks() {
password = (int)(Math.random() * 500);
System.out.println(password);
locked = true;
}
public boolean getLocked() {
//Returns if the lock is locked
return this.locked;
}
public void openLock(int pass) {
//User attepmts to unlock the lock
if(pass == this.password) {
//Changes boolean value inside 'this' lock
this.locked = false;
System.out.print("Unlocked");
}
}
}
<file_sep>/README.md
# FRCPractice
Use for 2017 bot and Solenoids
<file_sep>/GearMech.java
package offseason.java;
import edu.wpi.first.wpilibj.DoubleSolenoid;
/** This is for the 2017 code package. That code is not on Github
* I randomly created a package and when i know what the package name is,
* i will fix it then
*/
public class GearMech {
private final DoubleSolenoid claw;
private final DoubleSolenoid flap;
public GearMech (DoubleSolenoid claw, DoubleSolenoid flap){
this.claw = claw;
this.flap = flap;
flap.set(DoubleSolenoid.Value.kOff);
claw.set(DoubleSolenoid.Value.kOff);
}
/**Classifying where the solenoids will be in PCM
*/
/**
* Release the flap
*/
public void pullflap() {
flap.set(DoubleSolenoid.Value.kForward);
}
/**
* Set the Flap back in
*/
public void returnflap() {
flap.set(DoubleSolenoid.Value.kReverse);
}
/**
* Open the Claw
*/
public void openclaw() {
claw.set(DoubleSolenoid.Value.kForward);
}
/**
* Close the Claw
*/
public void closeclaw() {
claw.set(DoubleSolenoid.Value.kReverse);
}
}
| 2584260e227aa4a062d7d50e3ef722689bcc841e | [
"Markdown",
"Java"
] | 3 | Java | JoshuaSG3161/FRCPractice | d15749e47e8ef1533ae8bf5ad35b9f66eb3f45e0 | cb7da4394f8c1c6777c5a15e7a7d6fc6b73da4da |
refs/heads/master | <file_sep>var express = require('express');
var path = require('path');
var sass = require('node-sass-middleware');
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.set('views', path.join(__dirname, 'views'));
app.use(sass({
src: path.join(__dirname, 'public'),
dest: path.join(__dirname, 'public'),
sourceMap: true
}));
app.use(express.static(path.join(__dirname, 'public'), { maxAge: 31557600000 }));
app.get('/', function(req,res){res.render('home.html')});
app.listen(app.get('port'), function() {
console.log('Express server listening on port %d in %s mode', app.get('port'), app.get('env'));
});
module.exports = app; | 884fee55a4d79854b76142ae1206aca03015359d | [
"JavaScript"
] | 1 | JavaScript | eddiewang/frontend-styling-boilerplate | 976ff7113b60fbb8c015c8b4fbcddde43be1f1a7 | e418f28a218a9dedd8b0fdab46f5b775b85827be |
refs/heads/master | <repo_name>EddieB94/THE-GREAT-PAIR-GAME<file_sep>/src/gameConfig.js
"use strict";
var game = {
state: {
currentLevel: 1,//window.localStorage.getItem("currentLevel"),
time: {
second: 0,
minute: 0,
hour: 0,
total: function () {
return (this.time.hour * 100) + this.time.minute + (this.time.second * 0.01);
}
},
moves: 0
},
levels: {
one: {
id: 1,
gridWidth: 4,
targetTime: {
second: 0,
minute: 1,
hour: 0
},
targetMoves: 20
},
two: {
id: 2,
gridWidth: 4,
targetTime: {
second: 0,
minute: 1,
hour: 0
},
targetMoves: 20
},
three: {
id: 3,
gridWidth: 4,
targetTime: {
second: 0,
minute: 1,
hour: 0
},
targetMoves: 20
}
}
};
module.exports = game;<file_sep>/src/methods.js
import {
openSquare,
} from "./index.js";
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
while (currentIndex !== 0) {
randomIndex = Math.floor(Math.random() * array.length);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
};
function checkMedia() {
if(/iP(hone|ad)/.test(window.navigator.userAgent)) {
var elements = document.querySelectorAll('.square');
for(var i = 0; i < elements.length; i++) {
elements[i].addEventListener('touchstart', openSquare);
}
} else {
var elements = document.querySelectorAll('.square');
for(var i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', openSquare);
}
}
}
export {
shuffle,
checkMedia,
}<file_sep>/README.md
# Pair Game
A simple pair game with a 10 x 10 Board
INSTALL
please run 'npm install' so node can install all the dependencies listed in the package.json.
USAGE
the command
npm run lint
will run ESLint on all javascript files inside the repo using the eslint config file that has uses the .eslintrc.json file as config.
npm run build
will compile the html and javascript files from the src/ directory into a build directory in which you will find index.html and main.js, please open the index.html into any browser of your choosing.
pairs/
the cordova project dir, run 'cordova prepare' to build the files required for xCode to simulate the app.
| 5a6c6cc4ea011ddd76d37184f1d4d97b85fa1eb5 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | EddieB94/THE-GREAT-PAIR-GAME | 28cadd4da90d0f95916624d794c84ec4b2695d6b | c3bddfe8540f5a6386df49bc491009c182d8afeb |
refs/heads/master | <file_sep># edit-osm
Tools for editing OSM files for BNA scenario planning
The BNA can be used as a scenario planning tool by running the analysis on proposed/hypothetical infrastructure and comparing the results to BNA scores for the existing/actual network. Generating data for hypothetical infrastructure requires modifying OpenStreetMap (OSM) data and saving the modified file without uploading the modifications back to OSM. JOSM is the easiest tool to make modifications, providing a GUI and the ability to make edits to OSM data offline. Instructions for modifying OSM data to run the BNA for scenario planning follow.
## How to Create Hypothetical OSM Data for the BNA
1. Download OSM data for the target area using JOSM. You can download JOSM here: https://josm.openstreetmap.de/. Keep in mind that the BNA uses a buffer of <0.5 * bikeshed distance> around the area boundary, so the data downloaded via JOSM should include the region with the buffer area.
2. Modify OSM data using JOSM to include proposed infrastructure (with JOSM, editing can be done offline). For guidance on using JOSM, visit the Learn OSM website: https://learnosm.org/en/josm/start-josm/
NOTE: IT IS CRITICALLY IMPORTANT NOT TO UPLOAD THE HYPOTHETICAL DATA BACK TO OPENSTREETMAP, AS THIS WILL CONTRIBUTE ERRONEOUS DATA TO THE WORLD MAP. When you exit JOSM, be sure you save the file locally but do not select the "Upload" option.
Note: For a large area like an entire city this process may be difficult without significant computing resources, due to large file sizes.
3. If new features were added to OSM (i.e. new lines or polygons drawn on the map), run the OSM file through the number.py script first. When new features are added but not uploaded to OSM, they are assigned negative ID numbers. Those numbers need to be rearranged in increasing order, as the standard positive ID numbers are.
Once you've created the file with hypothetical data, run it through the BNA to obtain scenario planning results.
Keep in mind that changes to the overall scores will depend on the extent and significance of proposed infrastructure changes and the extent of the measured region. For instance, adding a protected bike lane on a dangerous street that connects a residential neighborhood to a business district could produce significant score improvements at the neighborhood scale. However, that single improvement might not affect the overall BNA score on the city scale, because it is a small part of a big region.
Also keep in mind that in some cases intersections or crossings of busy streets are major barriers to connectivity. Road improvements may not make a significant difference unless they include safe intersection treatments.
<file_sep># -*- coding: utf-8 -*-
"""
Created on Mon Sep 10 15:30:17 2018
@author: rebec
When editing OpenStreetMap (OSM) data in JOSM, new features are tagged
with a negative ID number. The negative numbers are listed
with a decreasing value (e.g. -1, -3, -5). However the BNA
requires ID values to run in increasing order, (e.g. -5, -3, -1).
This script ingests a modified OSM file with negative ID values and
reverses the order of the IDs for both nodes and ways.
Inputs: Modified OSM file
Outputs: Modified OSM file with numbers reordered by magnitude
"""
# Library to edit XML files
from lxml import etree
import os
# default file path
fpath = os.getcwd()
# function to re-sort nodes or ways
def reorder(osm_object, root):
object_len = len(osm_object)
if object_len <= 0:
return
while object_len > 0:
root.insert(root.index(osm_object[0]), osm_object[object_len-1])
object_len-=1
return
# parent function to ingest file, identify components to sort, and return edited file
def order_osm(file_name):
# read osm file
tree = etree.parse(fpath)
# identify nodes with negative id
ways = tree.xpath('.//way[starts-with(@id, "-")]')
# identify ways with negative id
nodes = tree.xpath('.//node[starts-with(@id, "-")]')
if len(nodes)+len(ways) <= 0:
return "No negative values to sort."
# Set root, which is OSM tag
root = tree.getroot()
# run reorder function for nodes and ways
reorder(nodes, root)
reorder(ways, root)
return tree
revised_xml = order_osm(fpath)
# Write to file
revised_xml.write(fpath + '/revised_xml.osm', pretty_print=True, xml_declaration=True, encoding="utf-8")
| b86ea6d3433ebdfa9263b3e4bc0ff475c51e6352 | [
"Markdown",
"Python"
] | 2 | Markdown | PeopleForBikes/edit-osm | 4ade92a481d6435b736a67a5dcb10a2509e99195 | 4ee0b67e8d6ca841af7fd6247a2d96ab4d6ca972 |
refs/heads/master | <file_sep>hello world
developer add something
master add something
<file_sep># expriment
=======
## new expriment
| dea379e76c1ef9459b03c968a981040bd0f89ffc | [
"Markdown",
"Python"
] | 2 | Python | NINJAFURRY/expriment | 4f140e6a3e5d34e8fac5562da65e9a0fdf17cbb3 | 1f608f3f1f3e3621e8c3b02d3ae529ce4ecdbae6 |
refs/heads/master | <repo_name>KrishnamurariB-Hexaware/voice-assistant-ga<file_sep>/webhook.js
var apiLibrary = require('./api')
module.exports = {
"ApplyLeave": function(req, res, callback){
console.log("ApplyLeave Module!");
var description = req.body.queryResult.parameters.desc;
var employee_id = req.body.queryResult.parameters.emp_id;
var start_date = req.body.queryResult.parameters.start_date;
var end = req.body.queryResult.parameters.end_date;
apiLibrary.GetLeaveAPI(description, employee_id, start_date, end, (err, result)=>{
console.log("Response from API : " + JSON.stringify(result))
callback(null, result.value)
})
},
"GetLeaveStatus": function(req, res, callback){
console.log("GetLeaveStatus Module!");
var description = req.body.queryResult.parameters.desc;
var employee_id = req.body.queryResult.parameters.emp_id;
var start_date = req.body.queryResult.parameters.start_date;
var end = req.body.queryResult.parameters.end_date;
callback(null, 'Callback Value')
}
}<file_sep>/index.js
//Required local file Dependencies
var module_loader = require('./webhook');
//------------------------------------UNCOMMENT FOR LOCAL DEBUGGING------------------------------------
//------------------------------------------------------------------------------------------------------
// Load Up the Dependencies
var express = require('express');
var bodyParser = require('body-parser');
require('dotenv').config()
//Configuring the Express Middleware
app = express()
// http = require('http'),
// httpServer = http.Server(app);
//Set PORT to Dynamic Environments to run on any Server
var port = process.env.PORT || 5000;
//Configure Express to Recieve JSON and extended URLencoded formats
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
//Set RESTful routes
app.get('/', function(req, res) {
res.send('API Running. Successful!');
});
app.post('/api/webhook', function(req, res) {
//var url = req.body.url;
// var token = req.body.token;
// var geo = req.body.geo;
console.log("REQUEST : " + JSON.stringify(req.body))
if(req.body.queryResult.action == "ApplyLeaveIntent"){
module_loader.ApplyLeave(req, res, (err, result)=>{
console.log("Callback Result : " + result)
response = {
"fulfillmentText": result,
"source": "myserver"
}
res.send(response)
});
}//Route to ApplyLeaveAPI
else if(req.body.queryResult.action == "SomethingElse"){
module_loader.GetLeaveStatus(req, res, (err, result)=>{
console.log("Callback Result : " + result)
response = {
"fulfillmentText": result,
"source": "myserver"
}
res.send(response)
});
}//Route to ApplyLeaveAPI
});
// Start the server
app.listen(port);
console.log("Server has booted up successfully at PORT : " + port);<file_sep>/api.js
var request = require("request");
module.exports = {
"GetLeaveAPI": function(description, employee_id, start_date, end, callback){
var options = { method: 'GET',
url: 'https://api.chucknorris.io/jokes/random',
headers:
{ 'Postman-Token': '<PASSWORD>',
'Cache-Control': 'no-cache' } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
callback(null, JSON.parse(body))//Add this
});
},
"ApplyLeave": function(x, y, callback){
var options = { method: 'GET',
url: 'https://api.chucknorris.io/jokes/random',
headers:
{ 'Postman-Token': '<PASSWORD>',
'Cache-Control': 'no-cache' } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
callback(null, body)
});
}
}
| aabe5724ab46e209ea4f3bc78ad6851fd3040178 | [
"JavaScript"
] | 3 | JavaScript | KrishnamurariB-Hexaware/voice-assistant-ga | e259a136be803488e512400dc0b42043d76d1d30 | 2f89f9ca7674a1cbdfae3fa6ea266856310d33c1 |
refs/heads/master | <repo_name>bsalha1/STM32F0-Bare-Metal<file_sep>/lib/includes/rcc.h
#ifndef RCC_H
#define RCC_H
#include "int.h"
struct rcc {
uint32_t cr; // Clock control register
uint32_t cfgr; // Clock configuration register
uint32_t cir; // Clock interrupt register
uint32_t apb2rstr; // APB peripheral reset register 2
uint32_t apb1rstr; // APB peripheral reset register 1
uint32_t ahbenr; // AHB peripheral clock enable register
uint32_t apb2enr; // APB peripheral clock enable register 2
uint32_t apb1enr; // APB peripheral clock enable register 1
uint32_t bdcr; // RTC domain control register
uint32_t csr; // Control/status register
uint32_t ahbrstr; // AHB peripheral reset register
uint32_t cfgr2; // Clock configuration register 2
uint32_t cfgr3; // Clock configuration register 3
uint32_t cr2; // Clock control register 2
};
#define RCC ((volatile struct rcc*)0x40021000)
#endif // RCC_H<file_sep>/lib/includes/compile.h
#ifndef COMPILE_H
#define COMPILE_H
#define STACK_SIZE 256
#define __attribute_section__(sec) __attribute__((section(sec)))
#define __weak__ __attribute__((weak))
#define __interrupt__ __attribute__((interrupt))
#define __vector__ __attribute_section__(".vectors")
#endif // COMPILE_H<file_sep>/README.md
# STM32F0-Kernel
This is a basic kernel for an STM32F091RC microcontroller. No API is used except for the C language itself.
## Purpose
The purpose of this project is to outline a very simple yet functional kernel for a barebones operating system.
It will have dynamic peripheral handling from user input devices to memory expansion (volatile and nonvolatile).
## Architecture
This microcontroller can be connected to an I2C-EEPROM via I2C port 1, and an SPI-OLED display via SPI port 2.
More compatibility and diversity will be added and supported over time.
<file_sep>/lib/includes/i2c.h
#ifndef I2C_H
#define I2C_H
#include "gpio.h"
#define I2C_CR1_PE (1 << 0)
#define I2C_CR1_TXIE (1 << 1)
#define I2C_CR1_RXIE (1 << 2)
#define I2C_CR1_ADDRIE (1 << 3)
#define I2C_CR1_NACKIE (1 << 4)
#define I2C_CR1_STOPIE (1 << 5)
#define I2C_CR1_TCIE (1 << 6)
#define I2C_CR1_ERRIE (1 << 7)
#define I2C_CR1_ANFOFF (1 << 12)
#define I2C_CR1_TXDMAEN (1 << 14)
#define I2C_CR1_RXDMAEN (1 << 15)
#define I2C_CR1_SBC (1 << 16)
#define I2C_CR1_NOSTRETCH (1 << 17)
#define I2C_CR2_SADD 0x3FFF // 10 1's
#define I2C_CR2_RD_WRN (1 << 10)
#define I2C_CR2_ADD10 (1 << 11)
#define I2C_CR2_HEAD10R (1 << 12)
#define I2C_CR2_START (1 << 13)
#define I2C_CR2_STOP (1 << 14)
#define I2C_CR2_NACK (1 << 15)
#define I2C_CR2_NBYTES (0xFF << 16)
#define I2C_CR2_RELOAD (1 << 24)
#define I2C_CR2_AUTOEND (1 << 25)
#define I2C_CR2_PECBYTE (1 << 26)
#define I2C_OAR1_OA1EN (1 << 15)
#define I2C_OAR2_OA2EN (1 << 15)
#define I2C_ISR_TXIS (1 << 1)
#define I2C_ISR_RXNE (1 << 2)
#define I2C_ISR_NACKF (1 << 4)
#define I2C_ISR_STOPF (1 << 5)
#define I2C_ISR_TC (1 << 6)
#define I2C_ISR_BUSY (1 << 15)
#define I2C_ICR_NACKCF (1 << 4)
#define I2C_ICR_STOPCF (1 << 5)
#define I2C_TXDR_TXDATA 0xFF
#define I2C_RXDR_RXDATA 0xFF
struct i2c {
uint32_t cr1;
uint32_t cr2;
uint32_t oar1;
uint32_t oar2;
uint32_t timingr;
uint32_t timeoutr;
uint32_t isr;
uint32_t icr;
uint32_t pecr;
uint32_t rxdr;
uint32_t txdr;
};
#define I2C_1 ((volatile struct i2c*)0x40005400)
#define I2C_2 ((volatile struct i2c*)0x40005800)
enum i2c_port {
I2C_PORT_1 = 0,
I2C_PORT_2 = 1
};
struct i2c_config {
struct gpio_pin sda_1;
struct gpio_pin scl_1;
struct gpio_pin sda_2;
struct gpio_pin scl_2;
};
void enable_i2c(enum i2c_port port);
#endif // I2C_H<file_sep>/lib/includes/spi.h
#ifndef SPI_H
#define SPI_H
#include "int.h"
struct spi {
uint32_t cr1; // Control register 1
uint32_t cr2; // Control register 2
uint32_t sr; // Status register
uint32_t dr; // Data register
uint32_t crcpr; // CRC polynomial register
uint32_t rxcrcr; // RX CRC register
uint32_t txcrcr; // TX CRC register
uint32_t i2scfgr; // I2S configuration register
uint32_t i2spr; // I2S prescaler register
};
#define SPI_1 ((volatile struct spi*)0x40013000)
#define SPI_2 ((volatile struct spi*)0x40003800)
#define SPI_CR1_CPHA (1 << 0)
#define SPI_CR1_CPOL (1 << 1)
#define SPI_CR1_MSTR (1 << 2)
#define SPI_CR1_BR (0x7 << 3)
#define SPI_CR1_SPE (1 << 6)
#define SPI_CR1_LSBFIRST (1 << 7)
#define SPI_CR1_SSI (1 << 8)
#define SPI_CR1_SSM (1 << 9)
#define SPI_CR1_RXONLY (1 << 10)
#define SPI_CR1_CRCL (1 << 11)
#define SPI_CR1_CRCNEXT (1 << 12)
#define SPI_CR1_CRCEN (1 << 13)
#define SPI_CR1_BIDIOE (1 << 14)
#define SPI_CR1_BIDIMODE (1 << 15)
#define SPI_CR2_RXDMAEN (1 << 0)
#define SPI_CR2_TXDMAEN (1 << 1)
#define SPI_CR2_SSOE (1 << 2)
#define SPI_CR2_NSSP (1 << 3)
#define SPI_CR2_FRF (1 << 4)
#define SPI_CR2_ERRIE (1 << 5)
#define SPI_CR2_RXNEIE (1 << 6)
#define SPI_CR2_TXNEIE (1 << 7)
#define SPI_CR2_DS (0xF << 8)
#define SPI_CR2_FRXTH (1 << 12)
#define SPI_CR2_LDMA_RX (1 << 13)
#define SPI_CR2_LDMA_TX (1 << 14)
#define SPI_SR_TXE (1 << 1)
enum spi_port {
SPI_PORT_1 = 0,
SPI_PORT_2 = 1
};
void enable_spi(enum spi_port port);
#endif // SPI_H<file_sep>/lib/includes/math.h
#ifndef MATH_H
#define MATH_H
#include "int.h"
uint32_t abs(int num);
int divide(int dividend, int divisor);
/**
* @brief Calculates the log10 of a number floored.
* @param num The number to calculate the log10 of
* @return The log10 of num
**/
// uint32_t log10(uint32_t num);
#endif // MATH_H<file_sep>/lib/includes/eeprom_aa32af.h
#ifndef EEPROM_AA32AF_H
#define EEPROM_AA32AF_H
/**
* This is a driver for a 4KB EEPROM http://ww1.microchip.com/downloads/en/devicedoc/22184a.pdf
* 1 Page = 32 Bytes
*/
#include "int.h"
#include "i2c.h"
#include "os_assert.h"
#define MAX_ADDRESS 0xFFF
#define EEPROM_ASSERT(cond, message) OS_ASSERT(cond, message)
/**
* @brief Initializes EEPROM to run on given I2C port
* @param port The I2C port to run on
*/
void eeprom_init(enum i2c_port port);
/**
* @brief Writes data to EEPROM memory
* @param devaddr I2C address of device
* @param address Address in EEPROM memory to write to
* @param data Data to write to EEPROM memory
*/
void eeprom_flash_write(uint8_t devaddr, uint16_t address, uint8_t data);
/**
* @brief Sends address to read from without a STOP. Used by eeprom_flash_read to tell chip which address to read from.
* @param devaddr I2C address of device
* @param address Address in EEPROM memory to send
*/
static void send_address(uint8_t devaddr, uint16_t address);
/**
* @brief Reads one byte at EEPROM address
* @param devaddr I2C address of device
* @param address Address in EEPROM memory to read from
* @return Value of byte read
*/
uint8_t eeprom_flash_read(uint8_t devaddr, uint16_t address);
/**
* @brief Reads bytes starting from (address) to (address + data_length - 1) and puts into data
* @param devaddr I2C address of device
* @param address Address in EEPROM memory to start reading from
* @param data Buffer to put read bytes into
* @param data_length Number of bytes to read & number of ints allocated for data pointer
*/
void eeprom_flash_read_sequential(uint8_t devaddr, uint16_t address, uint8_t* data, uint32_t data_length);
#endif // EEPROM_AA32AF_H<file_sep>/lib/src/eeprom_aa32af.c
#include "eeprom_aa32af.h"
#include "os_assert.h"
#include "time.h"
void eeprom_init(enum i2c_port port)
{
volatile struct i2c* i2c_slot;
// PB5 AF3 = I2C1_SMBA
if(port == I2C_PORT_1)
{
i2c_slot = I2C_1;
enable_gpio(GPIO_PORT_B);
// PA9 AF4 = I2C1_SCL
// PA10 AF4 = I2C1_SDA
// PB6 AF1 = I2C1_SCL
// PB7 AF1 = I2C1_SDA
// PB8 AF1 = I2C1_SCL
// PB9 AF1 = I2C1_SDA
// PF0 AF1 = I2C1_SDA
// PF1 AF1 = I2C1_SCL
set_gpio_mode(GPIO_PORT_B, 8, MODE_ALTERNATE_FUNCTION);
set_gpio_mode(GPIO_PORT_B, 9, MODE_ALTERNATE_FUNCTION);
set_gpio_alternate_function(GPIO_PORT_B, 8, 1);
set_gpio_alternate_function(GPIO_PORT_B, 9, 1);
enable_i2c(I2C_PORT_1);
}
else if(port == I2C_PORT_2)
{
i2c_slot = I2C_2;
enable_gpio(GPIO_PORT_B);
// PA11 AF4 = I2C2_SCL
// PA12 AF4 = 12C2_SDA
// PB10 AF1 = I2C2_SCL
// PB11 AF1 = I2C2_SDA
// PB13 AF5 = I2C2_SCL
// PB14 AF5 = I2C2_SDA
set_gpio_mode(GPIO_PORT_B, 10, MODE_ALTERNATE_FUNCTION);
set_gpio_mode(GPIO_PORT_B, 11, MODE_ALTERNATE_FUNCTION);
set_gpio_alternate_function(GPIO_PORT_B, 10, 1);
set_gpio_alternate_function(GPIO_PORT_B, 11, 1);
}
// Disable channel
i2c_slot->cr1 &= ~I2C_CR1_PE;
// Configure channel
i2c_slot->cr1 &= ~(I2C_CR1_ANFOFF | I2C_CR1_ERRIE | I2C_CR1_NOSTRETCH);
// Configure clock
i2c_slot->timingr = 0;
i2c_slot->timingr |= 3 << 20; // SCLDEL = 3
i2c_slot->timingr |= 1 << 16; // SCADEL = 1
i2c_slot->timingr |= 9 << 0; // SCLL = 9
i2c_slot->timingr |= 3 << 8; // SCLH = 3
// Configure addressing
i2c_slot->oar1 &= ~I2C_OAR1_OA1EN;
i2c_slot->oar2 &= ~I2C_OAR2_OA2EN;
i2c_slot->cr2 &= ~I2C_CR2_ADD10; // 7 bit addressing mode
// Enable Channel
i2c_slot->cr1 |= I2C_CR1_PE;
}
void eeprom_flash_write(uint8_t devaddr, uint16_t address, uint8_t data)
{
if(address > MAX_ADDRESS)
{
// TODO: assert
}
uint8_t address_high_byte = (address & 0xFF00) >> 8;
uint8_t address_low_byte = (address & 0x00FF);
while((I2C_1->isr & I2C_ISR_BUSY) == I2C_ISR_BUSY);
// Configure CR2 //
uint32_t tmpreg = I2C_1->cr2;
tmpreg &= ~(I2C_CR2_SADD | I2C_CR2_NBYTES | I2C_CR2_RELOAD | I2C_CR2_AUTOEND | I2C_CR2_RD_WRN | I2C_CR2_START | I2C_CR2_STOP);
tmpreg |= I2C_CR2_START | ((devaddr << 1) & I2C_CR2_SADD) | ((3 << 16) & I2C_CR2_NBYTES);
I2C_1->cr2 = tmpreg;
// Send data
while((I2C_1->isr & I2C_ISR_TXIS) == 0);
I2C_1->txdr = address_high_byte & I2C_TXDR_TXDATA;
while((I2C_1->isr & I2C_ISR_TXIS) == 0);
I2C_1->txdr = address_low_byte & I2C_TXDR_TXDATA;
while((I2C_1->isr & I2C_ISR_TXIS) == 0);
I2C_1->txdr = data & I2C_TXDR_TXDATA;
// Wait for transfer complete or for a NACK to be received from slave
while((I2C_1->isr & I2C_ISR_TC) == 0 && (I2C_1->isr & I2C_ISR_NACKF) == 0);
EEPROM_ASSERT(I2C_1->isr & I2C_ISR_NACKF == 0, "EEPROM: Unexpected NACK");
// Generate STOP bit
I2C_1->cr2 |= I2C_CR2_STOP;
while((I2C_1->isr & I2C_ISR_STOPF) == 0); // Wait till STOP detected
I2C_1->icr |= I2C_ICR_STOPCF; // Clear STOPF in ISR
small_sleep();
}
static void send_address(uint8_t devaddr, uint16_t address)
{
uint8_t address_high_byte = (address & 0xFF00) >> 8;
uint8_t address_low_byte = (address & 0x00FF);
while((I2C_1->isr & I2C_ISR_BUSY) == I2C_ISR_BUSY);
// Configure CR2 //
uint32_t cr2 = I2C_1->cr2;
cr2 &= ~(I2C_CR2_SADD | I2C_CR2_NBYTES | I2C_CR2_RELOAD | I2C_CR2_AUTOEND | I2C_CR2_RD_WRN | I2C_CR2_START | I2C_CR2_STOP);
cr2 |= I2C_CR2_START | ((devaddr << 1) & I2C_CR2_SADD) | ((2 << 16) & I2C_CR2_NBYTES);
I2C_1->cr2 = cr2;
// Send data
while((I2C_1->isr & I2C_ISR_TXIS) == 0);
I2C_1->txdr = address_high_byte & I2C_TXDR_TXDATA;
while((I2C_1->isr & I2C_ISR_TXIS) == 0);
I2C_1->txdr = address_low_byte & I2C_TXDR_TXDATA;
// Wait for transfer complete or for a NACK to be received
while((I2C_1->isr & I2C_ISR_TC) == 0 && (I2C_1->isr & I2C_ISR_NACKF) == 0);
EEPROM_ASSERT(I2C_1->isr & I2C_ISR_NACKF == 0, "EEPROM: Unexpected NACK");
}
uint8_t eeprom_flash_read(uint8_t devaddr, uint16_t address)
{
EEPROM_ASSERT(address <= MAX_ADDRESS, "EEPROM: Max address exceeded");
// Send address without setting STOP bit
send_address(devaddr, address);
// Configure CR2 //
uint32_t cr2 = I2C_1->cr2;
cr2 &= ~(I2C_CR2_NBYTES);
cr2 |= I2C_CR2_START | I2C_CR2_RD_WRN | ((1 << 16) & I2C_CR2_NBYTES);
I2C_1->cr2 = cr2;
// Wait till RXDR not empty
while((I2C_1->isr & I2C_ISR_RXNE) == 0);
uint8_t data = I2C_1->rxdr & I2C_RXDR_RXDATA;
// NACK must be received
EEPROM_ASSERT(I2C_1->isr & I2C_ISR_NACKF != 0, "EEPROM: NACK expected");
I2C_1->icr |= I2C_ICR_NACKCF;
// Generate STOP bit
I2C_1->cr2 |= I2C_CR2_STOP;
while((I2C_1->isr & I2C_ISR_STOPF) == 0); // Wait till STOP detected
I2C_1->icr |= I2C_ICR_STOPCF; // Clear STOPF in ISR
small_sleep();
return data;
}
void eeprom_flash_read_sequential(uint8_t devaddr, uint16_t address, uint8_t* data, uint32_t data_length)
{
// Send address without setting STOP bit
send_address(devaddr, address);
// Configure CR2 //
uint32_t cr2 = I2C_1->cr2;
cr2 &= ~I2C_CR2_NBYTES;
cr2 |= I2C_CR2_START | I2C_CR2_RD_WRN | ((data_length << 16) & I2C_CR2_NBYTES);
I2C_1->cr2 = cr2;
for(int i = 0; i < data_length; i++)
{
// Wait till RXDR not empty or for a NACK to be received
while((I2C_1->isr & I2C_ISR_RXNE) == 0);
// Read received byte
data[i] = I2C_1->rxdr & I2C_RXDR_RXDATA;
}
// NACK must be received
EEPROM_ASSERT(I2C_1->isr & I2C_ISR_NACKF != 0, "EEPROM: NACK expected");
I2C_1->icr |= I2C_ICR_NACKCF;
// Generate STOP bit
I2C_1->cr2 |= I2C_CR2_STOP;
while((I2C_1->isr & I2C_ISR_STOPF) == 0); // Wait till STOP detected
I2C_1->icr |= I2C_ICR_STOPCF; // Clear STOPF in ISR
small_sleep();
}<file_sep>/lib/includes/int.h
#ifndef INT_H
#define INT_H
#define int8_t char
#define int16_t short
#define int32_t int
#define int64_t long
#define uint8_t unsigned char
#define uint16_t unsigned short
#define uint32_t unsigned int
#define uint64_t unsigned long
#endif // INT_H<file_sep>/lib/src/scb.c
#include "scb.h"
uint8_t cpu_get_revision()
{
return SCB->cpuid & SCB_CPUID_REVISION;
}
uint16_t cpu_get_partno()
{
return (SCB->cpuid & SCB_CPUID_PARTNO) >> 4;
}
uint8_t cpu_get_arch()
{
return (SCB->cpuid & SCB_CPUID_CONSTANT) >> 16;
}
uint8_t cpu_get_variant()
{
return (SCB->cpuid & SCB_CPUID_VARIANT) >> 20;
}
uint8_t cpu_get_implementer()
{
return (SCB->cpuid & SCB_CPUID_IMPLEMENTER) >> 24;
}<file_sep>/lib/src/i2c.c
#include "i2c.h"
#include "gpio.h"
void enable_i2c(enum i2c_port port)
{
if(port == I2C_PORT_1)
{
RCC->apb1enr |= 1 << 21;
}
else if(port == I2C_PORT_2)
{
RCC->apb1enr |= 1 << 22;
}
else
{
// TODO: assert
}
}<file_sep>/lib/src/oled_1602a.c
#include "rcc.h"
#include "gpio.h"
#include "spi.h"
#include "oled_1602a.h"
#include "math.h"
#include <stdarg.h>
// Points to next index to put a char
volatile uint8_t oled_char_pointer = 0;
void oled_init()
{
oled_char_pointer = 0;
enable_gpio(GPIO_PORT_B);
set_gpio_mode(GPIO_PORT_B, 12, MODE_ALTERNATE_FUNCTION);
set_gpio_mode(GPIO_PORT_B, 13, MODE_ALTERNATE_FUNCTION);
set_gpio_mode(GPIO_PORT_B, 15, MODE_ALTERNATE_FUNCTION);
set_gpio_alternate_function(GPIO_PORT_B, 12, 0);
set_gpio_alternate_function(GPIO_PORT_B, 13, 0);
set_gpio_alternate_function(GPIO_PORT_B, 15, 0);
enable_spi(SPI_PORT_2);
SPI_2->cr1 |= SPI_CR1_MSTR | SPI_CR1_BIDIMODE | SPI_CR1_BIDIOE | SPI_CR1_BR;
SPI_2->cr2 = (SPI_2->cr2 & ~SPI_CR2_DS) | (0x9 << 8) // 10 bit transfer size
| SPI_CR2_NSSP | SPI_CR2_SSOE;
// Enable SPI2
SPI_2->cr1 |= SPI_CR1_SPE;
for(int i = 0; i < 300000; i++);
oled_cmd(0x38);
oled_display_control(false, false, false);
oled_clear_display();
for(int i = 0; i < 300000; i++);
oled_entry_mode_set(ENTRY_MODE_AUTO_INCREMENT, false);
oled_return_home();
oled_display_control(true, false, false);
}
static void oled_cmd(uint8_t cmd)
{
// Wait Till Transmit Buffer Empty
while((SPI_2->sr & SPI_SR_TXE) == 0);
SPI_2->dr = cmd;
}
static void oled_data(uint16_t data)
{
// Wait Till Transmit Buffer Empty
while((SPI_2->sr & SPI_SR_TXE) == 0);
SPI_2->dr = data | 0x200;
}
void oled_clear_display()
{
oled_cmd(0x01);
}
void oled_return_home()
{
oled_cmd(0x02);
}
void oled_entry_mode_set(enum entry_mode mode, bool shift_display)
{
uint8_t cmd = 0x04;
if(mode == ENTRY_MODE_AUTO_INCREMENT)
{
cmd |= 0x02;
}
if(shift_display)
{
cmd |= 0x01;
}
oled_cmd(cmd);
}
void oled_display_control(bool display_on, bool cursor_on, bool blinking_cursor)
{
uint8_t cmd = 0x08;
if(display_on)
{
cmd |= 0x04;
}
if(cursor_on)
{
cmd |= 0x02;
}
if(blinking_cursor)
{
cmd |= 0x01;
}
oled_cmd(cmd);
}
void oled_display_shift(enum display_type display_type, enum direction direction)
{
uint8_t cmd = 0x10;
if(display_type == DISPLAY_TYPE_SCREEN)
{
cmd |= 0x08;
}
if(direction == DIRECTION_RIGHT)
{
cmd |= 0x04;
}
oled_cmd(cmd);
}
void oled_set_ddram_address(uint8_t address)
{
if((address > 0x0F && address < 0x40) || address > 0x4F)
{
// TODO: assert
return;
}
oled_cmd(0x80 | address);
}
void oled_display1(const char * message)
{
oled_return_home();
int i = 0;
while(message[i] != 0)
{
oled_data(message[i]);
i++;
}
}
void oled_display2(const char * message)
{
oled_set_ddram_address(0x40); // Second line
int i = 0;
while(message[i] != 0)
{
oled_data(message[i]);
i++;
}
}
void oled_clear_display1()
{
oled_display1(" ");
}
void oled_clear_display2()
{
oled_display2(" ");
}
void oled_putchar_offset(char character, uint8_t offset)
{
if(offset >= NUM_LINES * CHARACTERS_PER_LINE)
{
/// @todo assert
return;
}
if(offset < CHARACTERS_PER_LINE)
{
oled_set_ddram_address(offset);
}
else
{
oled_set_ddram_address(0x40 + (offset - 16));
}
oled_data(character);
}
void oled_putchar(char character)
{
oled_putchar_offset(character, oled_char_pointer);
if(oled_char_pointer >= NUM_LINES * CHARACTERS_PER_LINE)
{
oled_char_pointer = 0;
}
else
{
oled_char_pointer++;
}
}
void oled_puts(char* string)
{
int i = 0;
while(string[i] != 0)
{
oled_putchar(string[i]);
i++;
}
}
void oled_putint(uint32_t num)
{
int32_t power = 1;
while(num > power)
power *= 10;
power = divide(power, 10);
while(num != 0)
{
int digit = divide(num, power);
oled_putchar('0' + digit);
if(digit != 0)
num = num - digit * power;
if(power != 1)
power = divide(power, 10);
}
}
void oled_printf(char* format,...)
{
char *traverse;
unsigned int i;
char *s;
va_list arg;
va_start(arg, format);
for(traverse = format; *traverse != '\0'; traverse++)
{
while(*traverse != '%')
{
if(*traverse == '\0')
{
va_end(arg);
return;
}
oled_putchar(*traverse);
traverse++;
}
traverse++;
switch(*traverse)
{
case 'c':
i = va_arg(arg, int);
oled_putchar(i);
break;
case 'd':
i = va_arg(arg, int);
if(i < 0)
{
i = -i;
oled_putchar('-');
}
oled_putint(i);
break;
case 's': s = va_arg(arg, char *);
oled_puts(s);
break;
}
}
//Module 3: Closing argument list to necessary clean-up
va_end(arg);
} <file_sep>/lib/includes/gpio.h
#ifndef GPIO_H
#define GPIO_H
#include "int.h"
#include "bool.h"
#include "rcc.h"
struct gpio {
uint32_t moder; // GPIO port mode register
uint32_t otyper; // GPIO port output type register
uint32_t ospeedr; // GPIO port output speed register
uint32_t pupdr; // GPIO port pull-up/pull-down register
uint32_t idr; // GPIO port input data register
uint32_t odr; // GPIO port output data register
uint32_t bsrr; // GPIO port bit set/reset register
uint32_t lckr; // GPIO port configuration lock register
uint32_t afrl; // GPIO alternate function low register
uint32_t afrh; // GPIO alternate function high register
uint32_t brr; // GPIO port bit reset register
};
#define GPIO_A ((volatile struct gpio *)0x48000000)
#define GPIO_B ((volatile struct gpio *)0x48000400)
#define GPIO_C ((volatile struct gpio *)0x48000800)
#define GPIO_D ((volatile struct gpio *)0x48000C00)
#define GPIO_E ((volatile struct gpio *)0x48001000)
#define GPIO_F ((volatile struct gpio *)0x48001400)
enum gpio_port {
GPIO_PORT_A = 0,
GPIO_PORT_B = 1,
GPIO_PORT_C = 2,
GPIO_PORT_D = 3,
GPIO_PORT_E = 4,
GPIO_PORT_F = 5,
};
struct gpio_pin {
enum gpio_port port;
uint8_t pin;
};
enum gpio_mode {
MODE_INPUT = 0x00,
MODE_OUTPUT = 0x01,
MODE_ALTERNATE_FUNCTION = 0x02,
MODE_ANALOG = 0x03,
};
/**
* @brief Converts enum gpio_port to its structure
* @param port GPIO port (A-F) to convert
* @return Pointer to GPIO structure
**/
volatile struct gpio* gpio_port_to_struct(enum gpio_port port);
/**
* @brief Sets GPIO mode for given port and number
* @param port GPIO port (A-F) to use
* @param pin GPIO pin to use
* @param mode GPIO mode to use
**/
void set_gpio_mode(enum gpio_port port, uint8_t pin, enum gpio_mode mode);
/**
* @brief Obtains current value of GPIO output
* @param port GPIO port (A-F) to use
* @param pin GPIO pin to use
**/
unsigned int get_gpio_output(enum gpio_port port, uint8_t pin);
/**
* @brief Sets value of GPIO output (1 or 0)
* @param port GPIO port (A-F) to use
* @param pin GPIO pin to use
**/
void set_gpio_output(enum gpio_port port, uint8_t pin, bool value);
/**
* @brief Enables GPIO
* @param port GPIO port (A-F) to enable
**/
void enable_gpio(enum gpio_port port);
/**
* @brief Disables GPIO
* @param port GPIO port (A-F) to disable
**/
void disable_gpio(enum gpio_port port);
/**
* @brief Sets alternate function to use on a GPIO port and pin
* @param port GPIO port (A-F) to use
* @param pin GPIO pin to use
* @param function Alternate function to use (0-7)
**/
void set_gpio_alternate_function(enum gpio_port port, uint8_t pin, uint8_t function);
#endif // GPIO_H<file_sep>/lib/includes/os_assert.h
#ifndef OS_ASSERT_H
#define OS_ASSERT_H
#include "oled_1602a.h"
#define OS_ASSERT(cond, message) \
if (!(cond)) { \
oled_clear_display1(); \
oled_display1(message); \
} \
#endif // OS_ASSERT_H<file_sep>/lib/includes/nvic.h
#ifndef NVIC_H_
#define NVIC_H_
#define NVIC 0xE000E100
#define NVIC_ISER ((volatile uint32_t *) NVIC + 0x000)
#define NVIC_ICER ((volatile uint32_t *) NVIC + 0x080)
#define NVIC_ISPR ((volatile uint32_t *) NVIC + 0x100)
#define NVIC_ICPR ((volatile uint32_t *) NVIC + 0x180)
#define NVIC2 0xE000EF00
#define NVIC2_ISER ((volatile uint32_t *) NVIC2 + 0x000)
#define NVIC2_ICER ((volatile uint32_t *) NVIC2 + 0x080)
#define NVIC2_ISPR ((volatile uint32_t *) NVIC2 + 0x100)
#define NVIC2_ICPR ((volatile uint32_t *) NVIC2 + 0x180)
#endif // NVIC_H_<file_sep>/lib/includes/bool.h
#ifndef BOOL_H
#define BOOL_H
#include "int.h"
#define bool uint8_t
#define true 1
#define false 0
#endif // BOOL_H<file_sep>/lib/src/rcc.c
#include "rcc.h"<file_sep>/lib/includes/log.h
#ifndef LOG_H
#define LOG_H
#define LOG_SIZE 1024
void log_message(char* message);
#endif // LOG_H<file_sep>/lib/src/gpio.c
#include "gpio.h"
volatile struct gpio* gpio_port_to_struct(enum gpio_port port)
{
switch(port)
{
case GPIO_PORT_A: return GPIO_A;
case GPIO_PORT_B: return GPIO_B;
case GPIO_PORT_C: return GPIO_C;
case GPIO_PORT_D: return GPIO_D;
case GPIO_PORT_E: return GPIO_E;
case GPIO_PORT_F: return GPIO_F;
default: return 0x0;
}
}
void set_gpio_mode(enum gpio_port port, uint8_t pin, enum gpio_mode mode)
{
if(pin > 15)
{
// TODO: assert
return;
}
volatile struct gpio* gpio = gpio_port_to_struct(port);
gpio->moder &= ~(0x03 << (pin * 2));
gpio->moder |= mode << (pin * 2);
}
unsigned int get_gpio_output(enum gpio_port port, uint8_t pin)
{
if(pin > 15)
{
// TODO: assert
return 0xFF;
}
volatile struct gpio* gpio = gpio_port_to_struct(port);
return (gpio->odr & (1 << pin)) >> pin;
}
void set_gpio_output(enum gpio_port port, uint8_t pin, bool value)
{
if(pin > 15)
{
// TODO: assert
return;
}
volatile struct gpio* gpio = gpio_port_to_struct(port);
if(value == 0)
{
gpio->odr &= ~(1 << pin);
}
else if(value == 1)
{
gpio->odr |= 1 << pin;
}
else
{
// TODO: assert
}
}
void enable_gpio(enum gpio_port port)
{
int gpio_en_offset = port; // Convert A -> 1, B -> 2, ...
RCC->ahbenr |= 1 << (gpio_en_offset + 17);
}
void disable_gpio(enum gpio_port port)
{
int gpio_en_offset = port + 17;
RCC->ahbenr &= ~(1 << gpio_en_offset);
}
void set_gpio_alternate_function(enum gpio_port port, uint8_t pin, uint8_t function)
{
if(function > 0x7)
{
// TODO: assert
return;
}
if(pin > 15)
{
// TODO: assert
return;
}
volatile struct gpio* gpio = gpio_port_to_struct(port);
if(pin < 8)
{
gpio->afrl &= ~(0xF << (pin * 4));
gpio->afrl |= function << (pin * 4);
}
else
{
gpio->afrh &= ~(0xF << ((pin - 8) * 4));
gpio->afrh |= function << ((pin - 8) * 4);
}
}<file_sep>/lib/includes/time.h
#ifndef TIME_H
#define TIME_H
#include "int.h"
/**
* @brief Initializes time to the starting point
**/
void time_init();
void small_sleep();
/**
* @brief Increments the internal system time
**/
void time_increment_millis();
/**
* @brief Gets the internal system time
* @return Internal system time
**/
uint64_t time_get_millis_since_reset();
#endif // TIME_H<file_sep>/Makefile
TARGETS=blink.c lib/gpio.c
LINKER_SCRIPT=stm32.ld
PROGRAM_NAME=prog1
TTL_NODE=/dev/ttyUSB0
BUILD_DIRECTOR=build/
GCC = arm-none-eabi-gcc -mcpu=cortex-m0 -mthumb -c -I'lib/includes/'
BASE_SRCS = $(wildcard *.c)
LIB_SRCS = $(wildcard lib/src/*.c)
all:
@make clean
@make compile
@make link
@make copy
clean:
rm -rf build/
rm -f *.o
compile:
@echo "=-=-=-=-COMPILING-=-=-=-="
$(GCC) $(BASE_SRCS)
$(GCC) $(LIB_SRCS)
link:
@echo "\n=-=-=-=-=LINKING=-=-=-=-="
@mkdir -p build
arm-none-eabi-ld -T ${LINKER_SCRIPT} -o build/${PROGRAM_NAME}.elf $(wildcard *.o)
copy:
@echo "\n=-=-=-COPYING BINARY-=-=-="
arm-none-eabi-objcopy -O binary build/${PROGRAM_NAME}.elf build/${PROGRAM_NAME}.bin
flash:
sudo stm32flash -w build/${PROGRAM_NAME}.bin -v ${TTL_NODE}<file_sep>/lib/includes/scb.h
#ifndef SCB_H
#define SCB_H
#include "int.h"
#define SCB_CPUID_REVISION 0xF
#define SCB_CPUID_PARTNO (0xFFF << 4)
#define SCB_CPUID_CONSTANT (0xF << 16)
#define SCB_CPUID_VARIANT (0xF << 20)
#define SCB_CPUID_IMPLEMENTER (0xFF << 24)
struct scb {
uint32_t cpuid; // CPUID base register
uint32_t icsr; // Interrupt control and state register
uint32_t aircr; // Application interrupt and reset control register
uint32_t scr; // System control register
uint32_t ccr; // Configuration and control register
uint32_t shpr2; // System handler priority register 2
uint32_t shpr3; // System handler priority register 3
};
#define SCB ((volatile struct scb*)0xE000ED00)
/**
* @brief Returns revision of CPU ex: patch 0
*/
uint8_t cpu_get_revision();
/**
* @brief Returns part number of CPU ex: Cortex-M0 = 0xC20
*/
uint16_t cpu_get_partno();
/**
* @brief Returns architecture of CPU ex: ARMv6-M = 0xC
*/
uint8_t cpu_get_arch();
/**
* @brief Returns variant of CPU ex: revision 0
*/
uint8_t cpu_get_variant();
/**
* @brief Returns implementer code ex: ARM = 0x41
*/
uint8_t cpu_get_implementer();
#endif // SCB_H<file_sep>/lib/includes/oled_1602a.h
#ifndef OLED_1602A_H
#define OLED_1602A_H
#define CHARACTERS_PER_LINE 16
#define NUM_LINES 2
enum entry_mode {
ENTRY_MODE_AUTO_INCREMENT,
ENTRY_MODE_AUTO_DECREMENT
};
enum display_type {
DISPLAY_TYPE_CURSOR,
DISPLAY_TYPE_SCREEN
};
enum direction {
DIRECTION_LEFT,
DIRECTION_RIGHT
};
void oled_init();
static void oled_cmd(uint8_t cmd);
static void oled_data(uint16_t data);
void oled_display1(const char * message);
void oled_display2(const char * message);
void oled_clear_display();
void oled_return_home();
void oled_entry_mode_set(enum entry_mode mode, bool shift_display);
void oled_display_control(bool display_on, bool cursor_on, bool blinking_cursor);
void oled_display_shift(enum display_type display_type, enum direction direction);
void oled_set_ddram_address(uint8_t address);
void oled_clear_display1();
void oled_clear_display2();
void oled_putchar_offset(char character, uint8_t offset);
void oled_putchar(char character);
void oled_puts(char* string);
void oled_printf(char* format,...);
#endif // OLED_1602A_H<file_sep>/lib/src/spi.c
#include "spi.h"
#include "rcc.h"
void enable_spi(enum spi_port port)
{
if(port == SPI_PORT_1)
{
RCC->apb2enr |= 1 << 12;
}
else if(port == SPI_PORT_2)
{
RCC->apb1enr |= 1 << 14;
}
else
{
// TODO: assert
}
}
<file_sep>/lib/src/log.c
#include "log.h"
volatile char log_text[LOG_SIZE] = {0};
static int log_ptr;
void log_message(char* message)
{
for(int i = 0; log_ptr < LOG_SIZE; log_ptr++, i++)
{
log_text[log_ptr] = message[i];
}
}
int log_get_current_length()
{
return log_ptr;
}
void log_copy(char* dest, int size)
{
if(size >= LOG_SIZE)
{
// TODO: assert
return;
}
for(int i = 0; i < size; i++)
{
dest[i] = log_text[i];
}
}
<file_sep>/main.c
#include "compile.h"
#include "bool.h"
#include "rcc.h"
#include "gpio.h"
#include "i2c.h"
#include "eeprom_aa32af.h"
#include "oled_1602a.h"
#include "time.h"
#include "stk.h"
#include "nvic.h"
#include "scb.h"
void reset_handler(void)
{
// Initialize Time-Keeping //
time_init();
enable_stk(1); // 1 millisecond timer on SysTick interrupt
enable_gpio(GPIO_PORT_C);
set_gpio_mode(GPIO_PORT_C, 11, MODE_OUTPUT);
set_gpio_mode(GPIO_PORT_C, 12, MODE_OUTPUT);
set_gpio_output(GPIO_PORT_C, 11, 1);
set_gpio_output(GPIO_PORT_C, 12, 1);
// Initialize Display //
oled_init();
oled_display1("Booting up...");
// TEST: EEPROM //
eeprom_init(I2C_PORT_1);
uint8_t write = 0xee;
uint8_t dev_address = 0x57;
uint16_t address = 0x0;
oled_clear_display2();
oled_display2("EEPROM: RAR");
// TEST: Random-Access Read
eeprom_flash_write(dev_address, address, write);
uint8_t read = eeprom_flash_read(dev_address, address);
if(read == write)
{
oled_display2("EEPROM: RAR pass");
}
else
{
oled_display2("EEPROM: RAR fail");
return;
}
oled_clear_display2();
oled_display2("EEPROM: SR");
// TEST: Sequential Read
eeprom_flash_write(dev_address, address + 0, 0xaa);
eeprom_flash_write(dev_address, address + 1, 0xbb);
eeprom_flash_write(dev_address, address + 2, 0xcc);
eeprom_flash_write(dev_address, address + 3, 0xdd);
uint8_t data[4] = {0};
eeprom_flash_read_sequential(dev_address, address, data, sizeof(data));
if(data[0] == 0xaa && data[1] == 0xbb && data[2] == 0xcc && data[3] == 0xdd)
{
oled_display2("EEPROM: SR pass");
}
else
{
oled_display2("EEPROM: SR fail");
return;
}
oled_printf("Hello world this is a dbg: %d", 689);
while(1)
{
for(int i = 0; i < 500000; i++);
set_gpio_output(GPIO_PORT_C, 12, 1 ^ get_gpio_output(GPIO_PORT_C, 12));
}
}
__interrupt__ void nmi_handler(void) { }
__interrupt__ void hard_fault_handler(void) {}
__interrupt__ void svcall_handler(void) { }
__interrupt__ void pendsv_handler(void) { }
__interrupt__ void systick_handler(void)
{
time_increment_millis();
}
__interrupt__ void wwdg_handler(void) { }
__interrupt__ void pvd_vddio_2_handler(void) { }
__interrupt__ void rtc_handler(void) { }
__interrupt__ void flash_handler(void) { }
__interrupt__ void rcc_crs_handler(void) { }
__interrupt__ void exti0_1_handler(void) { }
__interrupt__ void exti2_3_handler(void) { }
__interrupt__ void exti4_15_handler(void) { }
__interrupt__ void tsc_handler(void) { }
__interrupt__ void dma_ch1_handler(void) { }
__interrupt__ void dma_ch2_3_dma2_ch1_2_handler(void) { }
__interrupt__ void dma_ch4_7_dma2_ch3_5_handler(void) { }
__interrupt__ void adc_comp_handler(void) { }
__interrupt__ void tim1_brk_up_trg_com_handler(void) { }
__interrupt__ void tim1_cc_handler(void) { }
__interrupt__ void tim2_handler(void) { }
__interrupt__ void tim3_handler(void) { }
__interrupt__ void tim6_dac_handler(void) { }
__interrupt__ void tim7_handler(void) { }
__interrupt__ void tim14_handler(void) { }
__interrupt__ void tim15_handler(void) { }
__interrupt__ void tim16_handler(void) { }
__interrupt__ void tim17_handler(void) { }
__interrupt__ void i2c1_handler(void) { }
__interrupt__ void i2c2_handler(void) { }
__interrupt__ void spi1_handler(void) { }
__interrupt__ void spi2_handler(void) { }
__interrupt__ void usart1_handler(void) { }
__interrupt__ void usart2_handler(void) { }
__interrupt__ void usart3_8_handler(void) { }
__interrupt__ void cec_can_handler(void) { }
__interrupt__ void usb_handler(void) { }
int stack[STACK_SIZE];
// Interrupt Vector Table
// In ARMv6 Manual Table B1-3 Exception Numbers
__vector__ const void* vectors[] = {
// Initialize stack to one value higher than highest memory in stack
(void*) &stack[STACK_SIZE],
// ARM Interrupts //
reset_handler, // Reset
nmi_handler, // Non maskable interrupt
hard_fault_handler, // All class of fault
0,
0,
0,
0,
0,
0,
0,
svcall_handler, // System service call via SWI instruction
0,
0,
pendsv_handler, // Pendable request for system service
systick_handler, // System tick timer
// External Interrupts //
wwdg_handler, // Window watchdog interrupt
pvd_vddio_2_handler, // PVD and VDDIO2 supply comparator interrupt
rtc_handler, // RTC interrupts
flash_handler, // Flash global interrupt
rcc_crs_handler, // RCC and CRS global interrupts
exti0_1_handler, // EXTI Line[1:0] interrupts
exti2_3_handler, // EXTI Line[3:2] interrupts
exti4_15_handler, // EXTI Line[15:4] interrupts
tsc_handler, // Touch sensing interrupt
dma_ch1_handler, // DMA channel 1 interrupt
dma_ch2_3_dma2_ch1_2_handler, // DMA channel 2 and 3, DMA2 channel 1 and 2 interrupt
dma_ch4_7_dma2_ch3_5_handler, // DMA channel 4-7 and DMA2 channel 3-5 interrupts
adc_comp_handler, // ADC and COMP interrupts
tim1_brk_up_trg_com_handler, // TIM1 break, update, trigger and commutation interrupt
tim1_cc_handler, // TIM1 capture compare interrupt
tim2_handler, // TIM2 global interrupt
tim3_handler, // TIM3 global interrupt
tim6_dac_handler, // TIM6 global interrupt and DAC underrun interrupt
tim7_handler, // TIM7 global interrupt
tim14_handler, // TIM14 global interrupt
tim15_handler, // TIM15 global interrupt
tim16_handler, // TIM16 global interrupt
tim17_handler, // TIM17 global interrupt
i2c1_handler, // I2C1 global interrupt
i2c2_handler, // I2C2 global interrupt
spi1_handler, // SPI1 global interrupt
spi2_handler, // SPI2 global interrupt
usart1_handler, // USART1 global interrupt
usart2_handler, // USART2 global interrupt
usart3_8_handler, // USART3-8 global interrupt
cec_can_handler, // CEC and CAN global interrupts
usb_handler, // USB global interrupt
};<file_sep>/lib/includes/stk.h
#ifndef STK_H_
#define STK_H_
#include "int.h"
#define STK_CSR_ENABLE (1)
#define STK_CSR_TICKINT (1 << 1)
#define STK_CSR_CLKSOURCE (1 << 2)
#define STK_CSR_COUNTFLAG (1 << 16)
#define STK_RVR_RELOAD (0xFFFFFF)
#define STK_CVR_CURRENT (0xFFFFFF)
#define STK ((volatile struct stk*) 0xE000E010)
struct stk {
uint32_t csr;
uint32_t rvr;
uint32_t cvr;
uint32_t calib;
};
/**
* @brief Enables SysTick interrupt every period_ms milliseconds
* @param period_ms The period of the SysTick interrupt in milliseconds
**/
void enable_stk(uint32_t period_ms);
#endif // STK_H_<file_sep>/lib/src/time.c
#include "time.h"
#include "int.h"
static volatile uint64_t millis_since_reset;
void time_init()
{
millis_since_reset = 0;
}
void small_sleep()
{
for(int i = 0; i < 5000; i++);
}
void time_increment_millis()
{
millis_since_reset++;
}
uint64_t time_get_millis_since_reset()
{
return millis_since_reset;
}<file_sep>/lib/src/stk.c
#include "stk.h"
void enable_stk(uint32_t period_ms)
{
// Disable timer
STK->csr &= ~STK_CSR_ENABLE;
// Set reload value
STK->rvr &= ~STK_RVR_RELOAD;
STK->rvr |= (period_ms * STK->calib) & 0xFFFFFF;
// Reset current value
STK->cvr &= ~STK_CVR_CURRENT;
// Enable interrupt and use processor as clock source
STK->csr |= STK_CSR_TICKINT | STK_CSR_CLKSOURCE;
// Enable timer
STK->csr |= STK_CSR_ENABLE;
} | 954676219af57d0ac3c71d7c3d77b04870c8d4a1 | [
"Markdown",
"C",
"Makefile"
] | 29 | C | bsalha1/STM32F0-Bare-Metal | 06a2cf2f180471368803b43a1de44a740adfbf3a | 5c60b2f98eddd11848502ff38da491ed0cf1d211 |
refs/heads/master | <repo_name>Qi811/czs_MinPro<file_sep>/pmys/cash/cash.js
// pages/pmys/cash/cash.js
const app = getApp()
Page({
/**
* 页面的初始数据
*/
data: {
money: '',
content: '',
user: '',
bankNumber: '',
tixianPrice: ''
},
getMoney(e){
this.setData({
money:e.detail.value
})
},
getContent(e){
this.setData({
content:e.detail.value
})
},
getCash(e) {
var that = this
if (that.data.money == '') {
wx.showToast({
title: '请输入要提现的金额',
icon:'none'
})
} else if (Number(that.data.money) < 10) {
wx.showToast({
title: '提现金额最低额度10元',
icon:'none'
})
} else if (Number(that.data.money) > Number(that.data.tixianPrice)) {
wx.showToast({
title: '余额不足',
icon:'none'
})
} else if (!that.data.bankNumber) {
wx.showToast({
title: '请先设置提现账号',
icon:'none'
})
} else {
wx.request({
url: app.globalData.url + '/tiXianSubmit',
data:{
member_id:wx.getStorageSync('id'),
price:that.data.money,
admin_remark:that.data.content
},
success(res){
if (res.data.code == 0) {
wx.showToast({
title: '提现成功'
})
this.userInfo();
} else {
wx.showToast({
title: res.data.message,
icon:'none'
})
}
},
fail(err) {
wx.hideLoading()
wx.showToast({
title: err.errMsg,
icon: 'none'
})
}
})
}
},
getcashInfo(e){
wx.navigateTo({
url: '../cashInfo/cashInfo',
})
},
gojr(e){
wx.navigateTo({
url: '../income/income',
})
},
quwei:function(){
wx.setNavigationBarTitle({
title:'余额提现'
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.quwei()
var that = this
wx.request({
url: app.globalData.url + '/userInfo',
data:{
id:wx.getStorageSync('id')
},
success(res){
that.setData({
user:res.data,
tixianPrice:res.data.price,
bankNumber:res.data.bank_number
})
},
fail(err) {
wx.hideLoading()
wx.showToast({
title: err.errMsg,
icon: 'none'
})
}
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})<file_sep>/pages/my/my.js
// pages/my/my.js
const app = getApp()
Page({
/**
* 页面的初始数据
*/
data: {
list: [],
price: null,
pricenum: null,
spanwidth: 100,
du: 69,
navleft: 200,
hin: false,
exit: false,
tishi: "",
},
sonmoney(e){
wx.navigateTo({
url: '../../pmys/cashlist/cashlist',
})
},
balance(e){
wx.navigateTo({
url: '../../pmys/cash/cash',
})
},
received(e){
wx.navigateTo({
url: '../../pmys/all/all',
})
},
beginner(e){
wx.navigateTo({
url: '../../pmys/beginner/beginner',
})
},
uptdPaw(e){
wx.navigateTo({
url: '../../pmys/uptPd/uptPd',
})
},
business(e){
wx.navigateTo({
url: '../../pmys/business/business',
})
},
clearLogin(e){
this.setData({
exit:true
})
},
cancelbtn(e){
this.setData({
exit:false
})
},
surebtn(e){
wx.removeStorageSync('id')
wx.redirectTo({
url: '../../plors/setting/setting',
})
this.setData({
exit:false
})
},
quwei:function(){
wx.setNavigationBarTitle({
title:'我的'
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
this.quwei()
var that = this
wx.request({
url: app.globalData.url + '/userInfo',
data:{
id:wx.getStorageSync('id')
},
success(res){
that.setData({
list:res.data,
price:res.data.price,
pricenum:res.data.total_price,
du:res.data.percentage,
spanwidth:220 * (res.data.percentage * 0.01),
navleft:220 * (res.data.percentage * 0.01)-20,
})
},
fail(err) {
wx.hideLoading()
wx.showToast({
title: err.errMsg,
icon: 'none'
})
}
})
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})<file_sep>/pmys/income/income.js
// pages/usermy/income/income.js
const app = getApp();
var timefor = require('../../utils/util.js');
Page({
/**
* 页面的初始数据
*/
data: {
list: [],
moneycolor: true,
rightmo: 'rightmo',
rightney: 'rightney',
timeBottom: 'timeBottom',
size: 50,
nullson: false,
max:0
},
quwei:function(){
wx.setNavigationBarTitle({
title:'收支记录'
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.quwei()
var that = this
wx.request({
url: app.globalData.url + '/incomeInfo',
data:{
id:wx.getStorageSync('id'),
page:1,
size:that.data.size,
nullson:false
},
success(res){
that.setData({
list:res.data.data
})
for (let i = 0; i < that.data.list.length; i++) {
const aa = that.data.list[i].create_time;
that.setData({
['list['+i+'].create_time']:timefor.formatTimeTwo(aa,'Y/M/D h:m:s'),
max:that.data.max + that.data.list[i].price
})
}
if(res.data.data.length == 0){
that.setData({
nullson:false
})
}else{
that.setData({
nullson:true
})
}
}
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})<file_sep>/pmys/uptPd/uptPd.js
// pmys/uptPd/uptPd.js
const app = getApp();
Page({
/**
* 页面的初始数据
*/
data: {
nowpwd:'',
newpwd:'',
agapwd:''
},
nowpwdIpt(e){
this.setData({
nowpwd:e.detail.value
})
},
newpwdIpt(e){
this.setData({
newpwd:e.detail.value
})
},
agapwdIpt(e){
this.setData({
agapwd:e.detail.value
})
},
isOK(e){
var that = this
if(that.data.nowpwd == ''){
wx.showToast({
title: '请输入旧密码',
icon: 'none'
})
}else if(that.data.nowpwd.length < 6){
wx.showToast({
title: '旧密码不正确',
icon: 'none'
})
}else if(that.data.newpwd == ''){
wx.showToast({
title: '请输入新密码',
icon: 'none'
})
}else if(that.data.newpwd.length < 6){
wx.showToast({
title: '密码不安全,建议6位以上',
icon: 'none'
})
}else if(that.data.nowpwd == that.data.newpwd){
wx.showToast({
title: '新密码和旧密码不能一样',
icon: 'none'
})
}else if(that.data.newpwd != that.data.agapwd){
wx.showToast({
title: '新密码和确认密码不一致',
icon: 'none'
})
}else{
wx.showLoading({
title: '修改中...',
})
wx.request({
url: app.globalData.url + '/revisepwd',
data:{
userId:wx.getStorageSync('id'),
oldpassword:that.data.nowpwd,
newpassword:<PASSWORD>,
password:<PASSWORD>
},
success(res){
wx.hideLoading()
if(res.data.code == 0){
wx.showToast({
title: '修改成功',
icon: 'none'
})
}else{
wx.showToast({
title: res.data.message,
icon: 'none'
})
}
},
fail(err){
wx.hideLoading()
wx.showToast({
title: err.errMsg,
icon: 'none'
})
}
})
}
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
wx.setNavigationBarTitle({
title:'修改密码'
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})<file_sep>/utils/util.js
// const formatTime = date => {
// const year = date.getFullYear()
// const month = date.getMonth() + 1
// const day = date.getDate()
// const hour = date.getHours()
// const minute = date.getMinutes()
// const second = date.getSeconds()
// return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
// }
// const formatNumber = n => {
// n = n.toString()
// return n[1] ? n : '0' + n
// }
let getQueryString = function (url, name) {
console.log("url = " + url)
console.log("name = " + name)
var reg = new RegExp('(^|&|/?)' + name + '=([^&|/?]*)(&|/?|$)', 'i')
var r = url.substr(1).match(reg)
if (r != null) {
console.log("r = " + r)
console.log("r[2] = " + r[2])
return r[2]
}
return null;
}
//导出方法,外部调用
module.exports = {
getQueryString: getQueryString,
}
//计算时间差
function shijiancha(faultDate, completeTime) {
var stime = Date.parse(new Date(faultDate));
var etime = Date.parse(new Date(completeTime));
var usedTime = etime - stime; //两个时间戳相差的毫秒数
var days = Math.floor(usedTime / (24 * 3600 * 1000));
//计算出小时数
var leave1 = usedTime % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
var hours = Math.floor(leave1 / (3600 * 1000));
//计算相差分钟数
var leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
var minutes = Math.floor(leave2 / (60 * 1000));
var dayStr = days == 0 ? "" : days + "天";
var hoursStr = hours == 0 ? "" : hours + "时";
var time = dayStr + hoursStr + minutes + "分";
return time;
}
function formatTime(date) {
var year = date.getFullYear()
var month = date.getMonth() + 1
var day = date.getDate()
var hour = date.getHours()
var minute = date.getMinutes()
var second = date.getSeconds()
return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
function formatNumber(n) {
n = n.toString()
return n[1] ? n : '0' + n
}
/**
* 时间戳转化为年 月 日 时 分 秒
* number: 传入时间戳
* format:返回格式,支持自定义,但参数必须与formateArr里保持一致
*/
function formatTimeTwo(number, format) {
var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
var returnArr = [];
var date = new Date(number * 1000);
returnArr.push(date.getFullYear());
returnArr.push(formatNumber(date.getMonth() + 1));
returnArr.push(formatNumber(date.getDate()));
returnArr.push(formatNumber(date.getHours()));
returnArr.push(formatNumber(date.getMinutes()));
returnArr.push(formatNumber(date.getSeconds()));
for (var i in returnArr) {
format = format.replace(formateArr[i], returnArr[i]);
}
return format;
}
module.exports = {
formatTime: formatTime, //日期转时间戳
formatTimeTwo: formatTimeTwo, //时间戳转日期
shijiancha:shijiancha //计算时间差
}
<file_sep>/app.js
App({
//设置全局请求URL
globalData:{
// url: 'http://192.168.0.15:8080/externalApi',
// url: 'http://192.168.127.12:8080/externalApi',
url:'https://www.hnchengben.com/cheng/externalApi',
memberId:'',
currentTab:0,
},
})<file_sep>/pages/qrcode/qrcode.js
// pages/pshare/qrcode/qrcode.js
const app = getApp();
Page({
/**
* 页面的初始数据
*/
data: {
imgList: ['http://m.qpic.cn/psc?/V50dOJzn1X8x9j30JRSn1m2wvI1zBnm3/ruAMsa53pVQWN7FLK88i5nLi1sIIu5.7eCpl5folP7WCXBqPfWI*t3RqNjs.Puw1MvX1pQY4f0kXWmn9vJ.qT0Jh*UV0Yw*FBlnclXuvlTQ!/b&bo=ggNFBgAAAAABB.I!&rf=viewer_4',
'http://m.qpic.cn/psc?/V50dOJzn1X8x9j30JRSn1m2wvI1zBnm3/ruAMsa53pVQWN7FLK88i5hPHDn.hWioWf8qgKmPGfptdbXR1VQCc3*T9coTXUoRHyM1JO3z.5VEYumiGJiiVWA1rXzmgxEanzNCiw2x3vJI!/b&bo=ggNABgAAAAABB.c!&rf=viewer_4'],
timer: '',
dataImg: [],
url: '',
teamPrice: '',
teamSuccess: '',
},
lookFriend(e) {
wx.navigateTo({
url: '../../pshare/friend/friend',
})
},
// copyText(e){
// if(this.data.url == '' || this.data.url == undefined){
// wx.showToast({
// title: '复制失败',
// icon:'none'
// })
// }else{
// wx.setClipboardData({
// data: this.data.url,
// success(res){
// }
// })
// }
// },
shareLink(e) {
},
onShareAppMessage: function (options) {
let that = this
return {
title: '诚助手',
desc: '一个做任务就能赚钱的小程序',
path: '../../plors/setting/setting',
success: function (res) {
let shareTickets = res.shareTickets
if (shareTickets && shareTickets.length === 0) {
return false;
}
wx.getShareInfo({
shareTicket: shareTicket[0],
success: function (res) {
let encryptedData = res.encryptedData
let iv = res.iv
}
})
}
}
},
LookBig(e) {
wx.previewImage({
urls: this.data.dataImg
})
},
save(e) {
var that = this
wx.getImageInfo({
src: that.data.dataImg[0],
success(res) {
var path = res.path
wx.getSetting({
success(res) {
if (!res.authSetting['scope.writePhotosAlbum']) {
wx.authorize({
scope: 'scope.writePhotosAlbum',
success(res) {
wx.saveImageToPhotosAlbum({
filePath: path,
success(res) {
wx.showToast({
title: '保存成功',
icon: 'none'
})
},
faile: (err) => {
wx.showToast({
title: '保存失败',
icon: 'none'
})
}
})
}
})
} else {
wx.saveImageToPhotosAlbum({
filePath: path,
success(res) {
wx.showToast({
title: '保存成功',
icon: 'none'
})
},
faile: (err) => {
wx.showToast({
title: '保存失败',
icon: 'none'
})
}
})
}
}
})
}
})
},
getRandom(minNum, maxNum) {
this.setData({
num: Math.floor(Math.random() * (maxNum - minNum + 1) + minNum)
})
},
quwei: function () {
wx.setNavigationBarTitle({
title: '我的二维码'
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
if (wx.getStorageSync('id') == '' || wx.getStorageSync('id') == undefined) {
wx.navigateTo({
url: '../../plors/setting/setting',
})
}
wx.showShareMenu({
withShareTicket: true,
})
this.quwei()
this.getRandom(0, this.data.imgList.length - 1)
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
if (wx.getStorageSync('id')) {
var that = this
let lis = []
wx.request({
url: app.globalData.url + '/shareInfo',
data: {
userId: wx.getStorageSync('id')
},
success(res) {
lis = lis.concat(res.data.data)
that.setData({
dataImg: lis,
url: res.data.url
})
},
fail(err) {
wx.showToast({
title: err.errMsg,
icon: 'none'
})
}
})
wx.request({
url: app.globalData.url + '/teamMoney',
data: {
userId: wx.getStorageSync('id')
},
success(res) {
that.setData({
teamPrice: res.data.teamMoney
})
},
fail(err) {
wx.showToast({
title: err.errMsg,
icon: 'none'
})
}
})
wx.request({
url: app.globalData.url + '/inviteNum',
data: {
id: wx.getStorageSync('id')
},
success(res) {
that.setData({
teamSuccess: res.data.number
})
},
fail(err) {
wx.showToast({
title: err.errMsg,
icon: 'none'
})
}
})
}else{
wx.navigateTo({
url: '../../plors/setting/setting',
})
}
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})<file_sep>/plors/login/login.js
// pages/login/login/login.js
const app = getApp();
Page({
/**
* 页面的初始数据
*/
data: {
tel: '',
pwd: ''
},
telInp(e) {
this.setData({
tel: e.detail.value
})
},
pwdInp(e) {
this.setData({
pwd: e.detail.value
})
},
logins(e) {
var that = this
if (that.data.tel == '') {
wx.showToast({
title: '请输入手机号',
icon: 'none'
})
} else if (that.data.tel.length != 11) {
wx.showToast({
title: '请输入正确的手机号',
icon: 'none'
})
} else if (!(/^1[3-9]{1}[0123456789]{9}$/.test(that.data.tel))) {
wx.showToast({
title: '请输入正确的手机号',
icon: 'none'
})
} else if (that.data.pwd == '') {
wx.showToast({
title: '请输入密码',
icon: 'none'
})
} else {
wx.showLoading({
title: '登录中...',
})
wx.request({
url: app.globalData.url + '/login',
data: {
username: that.data.tel,
password: that.<PASSWORD>
},
success(res) {
wx.hideLoading()
if(res.data.code == 1){
wx.showToast({
title: res.data.message,
icon: 'none'
})
}else{
wx.setStorageSync('id', res.data.id)
wx.showToast({
title: '登录成功',
icon: 'none'
})
wx.switchTab({
url: '../../pages/home/home',
})
}
},
fail(err) {
wx.hideLoading()
wx.showToast({
title: err.errMsg,
icon: 'none'
})
}
})
}
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
wx.setNavigationBarTitle({
title:'登录'
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})<file_sep>/plors/setting/setting.js
// pages/login/setting/setting.js
const app = getApp();
Page({
/**
* 页面的初始数据
*/
data: {
currentTab: 0,
// memberid: 'http://www.hnchengben.com/new.html#/setting/register?userId=9680',
memberid: '',
newid: '',
tel: '',
pwd: '',
nickname: '',
tels: '',
pwds: '',
twopwd: '',
memberId: '',
motto: '诚助手',
userInfo: {},
hasUserInfo: false,
canIUse: wx.canIUse('button.open-type.getUserInfo')
},
swichNav: function (e) {
var that = this;
if (this.data.currentTab === e.target.dataset.current) {
return false
} else {
that.setData({
currentTab: e.target.dataset.current
})
}
},
swiperChange: function (e) {
this.setData({
currentTab: e.detail.current
})
if(e.detail.current == 0){
wx.setNavigationBarTitle({
title: '登录'
})
} else {
wx.setNavigationBarTitle({
title: '注册'
})
}
},
telInp(e) {
this.setData({
tel: e.detail.value
})
},
pwdInp(e) {
this.setData({
pwd: e.detail.value
})
},
loginss(e) {
var that = this
if (that.data.tel == '') {
wx.showToast({
title: '请输入手机号',
icon: 'none'
})
} else if (that.data.tel.length != 11) {
wx.showToast({
title: '请输入正确的手机号',
icon: 'none'
})
} else if (!(/^1[3-9]{1}[0123456789]{9}$/.test(that.data.tel))) {
wx.showToast({
title: '请输入正确的手机号',
icon: 'none'
})
} else if (that.data.pwd == '') {
wx.showToast({
title: '请输入密码',
icon: 'none'
})
} else {
wx.showLoading({
title: '登录中...',
})
wx.request({
url: app.globalData.url + '/login',
data: {
username: that.data.tel,
password: <PASSWORD>
},
success(res) {
wx.hideLoading()
if (res.data.code == 1) {
wx.showToast({
title: res.data.message,
icon: 'none'
})
} else {
wx.setStorageSync('id', res.data.id)
wx.showToast({
title: '登录成功',
icon: 'none'
})
wx.switchTab({
url: '../../pages/home/home',
})
}
},
fail(err) {
wx.hideLoading()
wx.showToast({
title: err.errMsg,
icon: 'none'
})
}
})
}
},
nicknameInp(e) {
this.setData({
nickname: e.detail.value
})
},
telsInp(e) {
this.setData({
tels: e.detail.value
})
},
passInp(e) {
this.setData({
pwds: e.detail.value
})
},
twopassInp(e) {
this.setData({
twopwd: e.detail.value
})
},
regis(res) {
var that = this
if (that.data.nickname == '') {
wx.showToast({
title: '请输入昵称',
icon: 'none'
})
} else if (that.data.tels == '') {
wx.showToast({
title: '请输入手机号',
icon: 'none'
})
} else if (that.data.tels.length != 11) {
wx.showToast({
title: '请输入正确的手机号',
icon: 'none'
})
} else if (!(/^1[3-9]{1}[0123456789]{9}$/.test(that.data.tels))) {
wx.showToast({
title: '请输入正确的手机号',
icon: 'none'
})
} else if (that.data.pwds == '') {
wx.showToast({
title: '请设置密码',
icon: 'none'
})
} else if (that.data.pwds.length < 6) {
wx.showToast({
title: '密码不安全,建议6位或6位以上',
icon: 'none'
})
} else if (that.data.twopwd == '') {
wx.showToast({
title: '确认密码不能为空',
icon: 'none'
})
} else if (that.data.pwds != that.data.twopwd) {
wx.showToast({
title: '密码和确认密码输入不一致',
icon: 'none'
})
} else if (that.data.memberId == '') {
wx.showToast({
title: '邀请码不能为空',
icon: 'none'
})
} else {
wx.showLoading({
title: '注册中...',
})
wx.request({
url: app.globalData.url + '/register',
data: {
username: that.data.tels,
password: <PASSWORD>,
twopassword: <PASSWORD>,
nickname: that.data.nickname,
MemberId: that.data.memberId
},
success(res) {
wx.hideLoading()
if (res.data.code == 0) {
// wx.setStorageSync('id', res.data.id)
wx.showToast({
title: '注册成功',
icon: 'none'
})
that.setData({
currentTab:0
})
} else {
wx.showToast({
title: '注册失败' + res.data.message,
icon: 'none'
})
}
},
fail(err) {
wx.hideLoading()
wx.showToast({
title: err.errMsg,
icon: 'none'
})
}
})
}
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
if (app.globalData.userInfo) {
this.setData({
userInfo: app.globalData.userInfo,
hasUserInfo: true
})
} else if (this.data.canIUse){
// 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
// 所以此处加入 callback 以防止这种情况
app.userInfoReadyCallback = res => {
this.setData({
userInfo: res.userInfo,
hasUserInfo: true
})
}
} else {
// 在没有 open-type=getUserInfo 版本的兼容处理
wx.getUserInfo({
success: res => {
app.globalData.userInfo = res.userInfo
this.setData({
userInfo: res.userInfo,
hasUserInfo: true
})
}
})
}
if(options.q){
let qrUrl = decodeURIComponent(options.q)
let memberId = qrUrl.substring(qrUrl.lastIndexOf("=")+1, qrUrl.length);
this.setData({
memberId:memberId,
currentTab:1
})
}
if (wx.getStorageSync('id')) {
wx.switchTab({
url: '../../pages/home/home',
})
}
// var mid = this.data.memberid.substring(this.data.memberid.indexOf("=") + 1, this.data.memberid.length)
// if (mid.length > 9) {
// mid = ''
// }else{
// this.setData({
// memberId:mid,
// currentTab:1
// })
// }
},
getUserInfos: function(e){
if(e.detail.errMsg == 'getUserInfo:ok'){
this.loginss()
app.globalData.userInfo = e.detail.userInfo
this.setData({
userInfo: e.detail.userInfo,
hasUserInfo: true
})
}else{
wx.showToast({
title: '授权之后再能继续操作',
icon:'none'
})
}
},
getUserInfo: function(e) {
if(e.detail.errMsg == 'getUserInfo:ok'){
this.regis()
app.globalData.userInfo = e.detail.userInfo
this.setData({
userInfo: e.detail.userInfo,
hasUserInfo: true
})
}else{
wx.showToast({
title: '授权之后再能继续操作',
icon:'none'
})
}
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})<file_sep>/pmys/cashInfo/cashInfo.js
// pages/usermy/cashInfo/cashInfo.js
const app = getApp();
Page({
/**
* 页面的初始数据
*/
data: {
isbank:true,
iszfb:true,
zflx:['支付宝','银行卡'],
zflxindex:wx.getStorageSync('zflxindex')?wx.getStorageSync('zflxindex'):0,
bankName:'',
subbranchName:'',
bankUser: '',
bankNumber: '',
zfbUser:'',
zfbkNumber:'',
status:0
},
isSelect(e){
this.setData({
zflxindex:e.detail.value
})
},
bankNameInp(e){
this.setData({
bankName:e.detail.value
})
},
subbranchNameInp(e){
this.setData({
subbranchName:e.detail.value
})
},
bankUserInp(e){
this.setData({
bankUser:e.detail.value
})
},
bankNumberInp(e){
this.setData({
bankNumber:e.detail.value
})
},
zfbUserInp(e){
this.setData({
zfbUser:e.detail.value
})
},
zfbkNumberInp(e){
this.setData({
zfbkNumber:e.detail.value
})
},
quwei:function(){
wx.setNavigationBarTitle({
title:'提现资料'
})
},
save(e){
var that = this
if(that.data.zflxindex == 0){
if(!that.data.zfbUser){
wx.showToast({
title: '请输入支付宝名称',
icon:'none'
})
}else if(!that.data.zfbkNumber){
wx.showToast({
title: '请输入支付宝账号',
icon:'none'
})
}else{
wx.request({
url: app.globalData.url + '/userInfoSave',
data:{
userId:wx.getStorageSync('id'),
bankName:'支付宝',
subbranchName:'',
bankUser:that.data.zfbUser,
bankNumber:that.data.zfbkNumber,
status:2
},
success(res){
if(res.data.code == 0){
// that.setData({
// zflxindex:0
// })
wx.setStorageSync('zflxindex',0)
wx.showToast({
title: '修改成功',
icon:'none'
})
wx.navigateTo({
url: '../cash/cash'
})
}else{
wx.showToast({
title: res.data.message,
icon:'none'
})
}
}
})
console.log(that.data.zflxindex)
}
}else if(that.data.zflxindex == 1){
if(!that.data.bankName){
wx.showToast({
title: '请输入银行名称',
icon:'none'
})
}else if(!that.data.subbranchName){
wx.showToast({
title: '请输入支行名称',
icon:'none'
})
}else if(!that.data.bankUser){
wx.showToast({
title: '请输入收款人姓名',
icon:'none'
})
}else if(!that.data.bankNumber){
wx.showToast({
title: '请输入卡号',
icon:'none'
})
}else{
wx.request({
url: app.globalData.url + '/userInfoSave',
data:{
userId:wx.getStorageSync('id'),
bankName:that.data.bankName,
subbranchName:that.data.subbranchName,
bankUser:that.data.bankUser,
bankNumber:that.data.bankNumber,
status:3
},
success(res){
if(res.data.code == 0){
// that.setData({
// zflxindex:1
// })
wx.setStorageSync('zflxindex',1)
wx.showToast({
title: '修改成功',
icon:'none'
})
console.log(that.data.zflxindex)
wx.navigateTo({
url: '../cash/cash'
})
}else{
wx.showToast({
title: res.data.message,
icon:'none'
})
}
}
})
}
console.log(that.data.zflxindex)
}
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.quwei()
console.log('load',this.data.zflxindex)
var that = this
if(wx.getStorageSync('zflxindex') == 1){
//银行卡
wx.request({
url: app.globalData.url + '/payInfo',
data:{
userId:wx.getStorageSync('id')
},
success(res){
that.setData({
bankName:res.data.bank_name,
subbranchName:res.data.subbranch_name,
bankUser:res.data.bank_user,
bankNumber:res.data.bank_number
})
}
})
}else if(wx.getStorageSync('zflxindex') == 0){
//支付宝
wx.request({
url: app.globalData.url + '/payInfo',
data:{
userId:wx.getStorageSync('id')
},
success(res){
that.setData({
zfbUser:res.data.bank_user,
zfbkNumber:res.data.bank_number
});
}
});
}
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
}) | 5f384027e61e4e238e4ce617be3e7b20a650bf95 | [
"JavaScript"
] | 10 | JavaScript | Qi811/czs_MinPro | 0075944ec8429202853e80fda7ec49836c062bf0 | 0b39e1897dae651a0af20791dfbc92ea6201bdeb |
refs/heads/master | <file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* fillit.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: okrifa <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/08/30 22:40:19 by okrifa #+# #+# */
/* Updated: 2016/08/30 22:40:22 by okrifa ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef FILLIT_H
# define FILLIT_H
# include <fcntl.h>
# include <stdlib.h>
# include <unistd.h>
# define TRUE 1
# define FALSE 0
# define BUF_SIZE 21
int ft_puterror(void);
int ft_get_tetri(char *av, char tab[26][4][4]);
int ft_count(char buf[BUF_SIZE]);
int ft_check_file(int fd, char tab[26][4][4]);
int ft_content(char buf[BUF_SIZE]);
int ft_check_tetri(char buf[BUF_SIZE], int n_read, int i);
int ft_char(char c);
void ft_up_left(char tab[4][4]);
int ft_get_offset_col(char tab[4][4]);
int ft_get_offset_line(char tab[4][4]);
void ft_rmoffset_line(char tab[4][4], int offset);
void ft_rmoffset_col(char tab[4][4], int offset);
int ft_strlen(char *str);
void ft_stock_tetri(char buf[BUF_SIZE], char tab[4][4], int pos);
void ft_rm_tetri(char **map, int size, char c);
int ft_tetri_left(char **map, int size, int nb_total);
int ft_finished(char **map, int nb_tetri, char tab[26][4][4], int tetris);
int ft_solve_print(char **map, int nb_total, char tab[26][4][4]);
int ft_next_alpha(int j, char tab[4]);
void ft_init(int *check, int *i, int *j);
int ft_checknext(char c, int *pos_i, int *pos_j);
int ft_tetrifit(char tab[4][4], char **map, int m_i, int m_j);
void ft_free_map(char **map, int size);
void ft_addtomap(char **map, char tab[4][4], int k, int l);
int ft_sqrt(int nb);
char **ft_sqmap_dotalloc(int len);
void ft_print_map(char **grid, int len);
#endif
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* algo.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: snassour <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/02/25 22:06:06 by snassour #+# #+# */
/* Updated: 2016/08/30 22:41:55 by okrifa ### ########.fr */
/* */
/* ************************************************************************** */
#include "fillit.h"
void ft_rm_tetri(char **map, int size, char c)
{
int i;
int j;
int check;
i = -1;
check = 0;
while (++i < size && check < 4)
{
j = -1;
while (++j < size && check < 4)
if (map[i][j] == c)
{
map[i][j] = '.';
++check;
}
}
}
int ft_tetris_left(char **map, int size, int nb_total)
{
int nb_tetri;
int i;
int j;
i = -1;
nb_tetri = 0;
while (++i < size)
{
j = -1;
while (++j < size)
if (map[i][j] >= 'A' && map[i][j] <= 'Z')
++nb_tetri;
}
return (nb_total * 4 - nb_tetri);
}
int ft_finished(char **map, int nb_t, char tab[26][4][4], int tetris)
{
int start;
int size;
int max;
size = ft_strlen(map[0]);
start = -1;
if (!ft_tetris_left(map, size, nb_t))
return (TRUE);
max = size * size - 1;
while (++start < max)
if (ft_tetrifit(tab[tetris], map, start / size, start % size))
{
ft_addtomap(map, tab[tetris], start / size, start % size);
if (ft_finished(map, nb_t, tab, tetris + 1) == TRUE)
return (TRUE);
ft_rm_tetri(map, size, tetris + 'A');
}
return (FALSE);
}
<file_sep># fillit42
Automatic Tetris game - but in a rectangle !
## Run
`make ; make clean ; ./fillit [FILE]`
## Input
Described in the pdf
## PDF Link <a href="https://github.com/snassour/fillit42/blob/master/fillit.fr.pdf">Fillit</a>
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* check.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: snassour <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/02/25 22:06:06 by snassour #+# #+# */
/* Updated: 2016/02/25 22:06:06 by snassour ### ########.fr */
/* */
/* ************************************************************************** */
#include "fillit.h"
int ft_char(char c)
{
return (c == '.' || c == '#' || c == '\n' ? TRUE : FALSE);
}
int ft_count(char buf[BUF_SIZE])
{
int i;
int n;
n = 0;
i = -1;
while (++i < 20)
if (buf[i] == '#')
++n;
return (n == 4 ? TRUE : FALSE);
}
int ft_content(char buf[BUF_SIZE])
{
int i;
int check;
int prev;
i = -1;
check = 0;
while (++i < 20 && check < 3)
{
prev = check;
if (buf[i] == '#')
{
if (buf[i + 1] == '#')
++check;
if (buf[i + 5] == '#')
++check;
if (prev == 2 && check == 2)
continue ;
else if (prev == check)
return (FALSE);
}
}
return (check != 3 ? FALSE : TRUE);
}
int ft_check_tetri(char buf[BUF_SIZE], int n_read, int i)
{
while (i < n_read)
if (ft_char(buf[i++]) == FALSE)
return (FALSE);
if (n_read == 21 && buf[i - 1] != '\n')
return (FALSE);
n_read == 21 ? --i : i;
while (i > 0)
{
if (buf[i - 1] != '\n')
return (FALSE);
i -= 5;
}
if (ft_count(buf) == FALSE)
return (FALSE);
return (ft_content(buf) == FALSE ? FALSE : TRUE);
}
int ft_check_file(int fd, char tab[26][4][4])
{
char buf[BUF_SIZE];
int n_read;
int prev;
int pos;
pos = 0;
while ((n_read = read(fd, buf, BUF_SIZE)) == 21 || n_read == 20)
{
if ((ft_check_tetri(buf, n_read, 0)) == FALSE)
return (FALSE);
ft_stock_tetri(buf, tab[pos], pos);
++pos;
if (pos > 25)
return (FALSE);
prev = n_read;
}
return (n_read != 0 || prev != 20 ? FALSE : pos);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* map.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: okrifa <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/08/30 22:42:56 by okrifa #+# #+# */
/* Updated: 2016/08/30 22:42:59 by okrifa ### ########.fr */
/* */
/* ************************************************************************** */
#include "fillit.h"
void ft_free_map(char **map, int size)
{
int i;
i = -1;
while (++i < size)
free(map[i]);
free(map);
}
void ft_addtomap(char **map, char tab[4][4], int k, int l)
{
int i;
int j;
int check;
i = 0;
check = 0;
while (map[k] && check < 4)
{
j = -1;
while (++j < 4)
if (map[k][l + j] == '.' && (tab[i][j] >= 'A' && tab[i][j] <= 'Z'))
{
map[k][l + j] = tab[i][j];
++check;
}
++i;
++k;
}
}
int ft_sqrt(int nb)
{
int i;
i = 1;
while (i * i < nb)
++i;
return (i);
}
char **ft_sqmap_dotalloc(int len)
{
char **map;
int i;
int len_line;
int set_o;
i = -1;
len_line = len + 1;
if (!len)
return (NULL);
if (!(map = (char **)malloc(sizeof(char *) * (len_line))))
return (NULL);
while (++i < len)
{
if (!(map[i] = (char *)malloc(sizeof(char) * (len_line))))
return (NULL);
set_o = -1;
while (++set_o < len)
map[i][set_o] = '.';
map[i][set_o] = 0;
}
map[len] = 0;
return (map);
}
void ft_print_map(char **grid, int len)
{
int i;
i = 0;
while (i < len)
{
write(1, grid[i], len);
write(1, "\n", 1);
i++;
}
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: snassour <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/02/25 22:06:06 by snassour #+# #+# */
/* Updated: 2016/02/25 22:06:06 by snassour ### ########.fr */
/* */
/* ************************************************************************** */
#include "fillit.h"
int ft_puterror(void)
{
write(1, "error\n", 6);
return (1);
}
int ft_get_tetri(char *av, char tab[26][4][4])
{
int fd;
int i;
fd = open(av, O_RDONLY);
if (fd < 0)
return (FALSE);
i = ft_check_file(fd, tab);
close(fd);
return (i);
}
int main(int ac, char **av)
{
char tab[26][4][4];
char **map;
int nb_tetri;
int size;
if (ac != 2)
return (ft_puterror());
nb_tetri = ft_get_tetri(av[1], tab);
if (nb_tetri == FALSE)
return (ft_puterror());
size = ft_sqrt(nb_tetri * 4);
map = ft_sqmap_dotalloc(size);
while (!ft_finished(map, nb_tetri, tab, 0))
{
ft_free_map(map, size);
++size;
map = ft_sqmap_dotalloc(size);
}
ft_print_map(map, size);
ft_free_map(map, size);
return (0);
}
<file_sep>
# on completera le fichier makefile
# en utilisant les cibles suivantes
CC = gcc
CFLAGS = -g -Wall -Wextra -Werror
SRC_PATH = ./
OBJ_PATH = ./obj/
INC_PATH = ./includes
NAME = fillit
SRC_NAME = check.c\
main.c\
algo.c\
ft_fillmap.c\
map.c\
move_up_left.c\
ft_stock.c
TMP = tmp.txt
OBJ_NAME = $(SRC_NAME:.c=.o)
SRC = $(addprefix $(SRC_PATH), $(SRC_NAME))
OBJ = $(addprefix $(OBJ_PATH), $(OBJ_NAME))
INC = $(addprefix -I, $(INC_PATH))
all : $(NAME)
$(NAME) : $(OBJ)
@echo "\033[33mCompilation OBJ done !\033[0m"
@$(CC) $(CFLAGS) $(OBJ) -o $(NAME)
@echo "\033[32mCompilation EXE done !\033[0m"
$(OBJ_PATH)%.o : $(SRC_PATH)%.c
@mkdir -p $(OBJ_PATH)
@$(CC) $(CFLAGS) $(INC) -o $@ -c $<
clean:
@rm -rf $(OBJ_PATH)
@echo "\033[36mClean !\033[0m"
fclean : clean
@rm -rf $(NAME)
re : fclean all
.PHONY: all clean
| caf4be95fe5b3357b5036be8dc0f89c11529c84a | [
"Markdown",
"C",
"Makefile"
] | 7 | C | snassour/fillit42 | 1fd6b8e6ec7eae960c5253f121fd5cd19940c02b | 707f6ad2b7a6694ca1f2c28f75798e2f09e3fe4b |
refs/heads/master | <repo_name>romanstrakhov/rs-slider<file_sep>/src/rs-slider.js
import { addDOMElement, uniteObjects } from './helpers';
export default class Slider {
constructor(id, config = {}) {
this.slides = []; // list of all slider slides as DOM objects
this.position = 1;
this.parseConfig(config);
this.wrapper = document.getElementById(id);
switch (this.config.style) {
case 'slide-h':
break;
case 'slide-v':
break;
default:
this.config.style = 'fade';
}
this.wrapper.classList.add(`rsslider_style_${this.config.style}`);
// Add slides from HTML markup
this.wrapper.querySelectorAll('.rsslider__item').forEach((element) => {
switch (this.config.style) {
case 'slide-h':
element.classList.add('hidden_right');
break;
case 'slide-v':
element.classList.add('hidden_down');
break;
case 'fade':
default:
element.classList.add('hidden');
}
this.slides.push(element);
}, this);
if (this.config.controls.arrows === true) this.addArrows();
if (this.config.controls.pagination) this.addPaginator(this.config.controls.pagination);
this.showSlide(this.position);
}
// Methods
parseConfig(config) {
// Defaults
const defaults = {
controls: {
arrows: true,
pagination: 'dots',
},
style: 'fade',
};
if (config) { this.config = uniteObjects(defaults, config); }
}
/**
* Add 'prev' and 'next' arrows
*/
addArrows() {
this.arrows = {};
this.arrows.prev = addDOMElement(this.wrapper, 'button', ['rsslider__prev']);
this.arrows.next = addDOMElement(this.wrapper, 'button', ['rsslider__next']);
this.redrawArrowsOnSides();
// Set event listeners
this.arrows.prev.addEventListener('click', () => this.move(-1));
this.arrows.next.addEventListener('click', () => this.move(1));
}
/**
* Update 'prev'/'next' arrows on sides
* @param {int} toPosition
* @param {int} fromPosition optional
*/
redrawArrowsOnSides(toPosition = this.position, fromPosition = this.position) {
// Do nothing with DOM if there is no reason to redraw arrows
// 'cause their state changes only if toPosition or fromPosition is on side
// TODO: Make a little test & benchmark it
if (Math.min(fromPosition, toPosition) > 1 &&
Math.max(fromPosition, toPosition) < this.slides.length) return;
// Define conditions to show arrows
const arrowsStates = [
{
name: 'prev',
show: toPosition !== 1,
},
{
name: 'next',
show: toPosition !== this.slides.length,
},
];
arrowsStates.forEach(arrow => this.showArrows(arrow.name, arrow.show));
}
addPaginator(style) {
this.paginator = addDOMElement(this.wrapper, 'div', ['rsslider__paginator']);
this.paginatorElements = [];
let num = 1;
switch (style) {
case ('numbers'):
this.slides.forEach(() => {
this.paginatorElements.push(addDOMElement(this.paginator, 'button', ['rsslider__paginator_numbered__button'], {}, num));
num += 1;
});
break;
default: // dots
this.slides.forEach(() =>
this.paginatorElements.push(addDOMElement(this.paginator, 'button', ['rsslider__paginator__button'])));
}
// Set event listeners to each paginator element
this.paginatorElements.forEach((element, index) => {
element.addEventListener('click', () => this.jump(index + 1));
});
this.updatePaginator();
}
/**
* Redraws paginator
* @param {int} toPosition=this.position
* @param {int} fromPosition=this.position
*/
updatePaginator(toPosition = this.position, fromPosition = this.position) {
this.paginatorElements[fromPosition - 1].classList.remove('active');
this.paginatorElements[toPosition - 1].classList.add('active');
}
move(delta) {
this.setPosition(this.position + delta);
}
jump(position) {
this.setPosition(position);
}
/**
* Set new position of slider, update all controls depending on initial and target position
* @param {int} position
*/
setPosition(position) {
if (position < 1 || position > this.slides.length) {
return; // error, no action
} else if (position === this.position) {
return; // TODO: Decide should we handle this excusively
}
const oldPosition = this.position;
this.position = position;
let direction = '';
let step = 0;
switch (this.config.style) {
case 'slide-h':
if (position !== oldPosition) {
step = (position > oldPosition) ? 1 : -1;
direction = (position > oldPosition) ? 'left' : 'right';
}
this.showSlide(oldPosition, false, direction);
if (Math.abs(position - oldPosition) > 1) {
for (let i = oldPosition + step; i !== position; i += step) {
this.showSlide(i, true, direction);
this.showSlide(i, false, direction);
}
}
this.showSlide(position, true, direction);
break;
case 'slide-v':
if (position !== oldPosition) {
step = (position > oldPosition) ? 1 : -1;
direction = (position > oldPosition) ? 'up' : 'down';
}
this.showSlide(oldPosition, false, direction);
if (Math.abs(position - oldPosition) > 1) {
for (let i = oldPosition + step; i !== position; i += step) {
this.showSlide(i, true, direction);
this.showSlide(i, false, direction);
}
}
this.showSlide(position, true, direction);
break;
case 'fade':
default:
this.showSlide(oldPosition, false);
this.showSlide(position, true);
} // switch style
// Update controls
if (this.config.controls.arrows) this.redrawArrowsOnSides(position, oldPosition);
if (this.config.controls.pagination && this.config.controls.pagination !== 'none') this.updatePaginator(position, oldPosition);
}
/**
* Show or hide 'prev'/'next' arrow
* @param {String} button 'prev' or 'next'
* @returns {Boolean} show
*/
showArrows(button, show) {
if (show) {
this.arrows[button].classList.remove('hidden');
} else {
this.arrows[button].classList.add('hidden');
}
}
/**
* Show or hide slide of given position. Show current slide by default
* @param {Int} position = this.position
* @param {Bool} state = true
* @param {String} dir = ''
*/
showSlide(position = this.position, state = true, dir = '') {
if (position < 1 || position > this.slides.length) {
return;
}
let direction = dir;
let indirection = '';
switch (this.config.style) {
case 'slide-h':
direction = (direction === 'right') ? 'right' : 'left'; // set left by default
indirection = (direction === 'left') ? 'right' : 'left';
if (state) {
this.slides[position - 1].classList.remove(`hidden_${indirection}`);
} else {
this.slides[position - 1].classList.add(`hidden_${direction}`);
}
break;
case 'slide-v':
direction = (direction === 'down') ? 'down' : 'up'; // set up by default
indirection = (direction === 'up') ? 'down' : 'up';
if (state) {
this.slides[position - 1].classList.remove(`hidden_${indirection}`);
} else {
this.slides[position - 1].classList.add(`hidden_${direction}`);
}
break;
case 'fade':
default:
if (state) {
this.slides[position - 1].classList.remove('hidden');
} else {
this.slides[position - 1].classList.add('hidden');
}
} // switch style
}
}
<file_sep>/src/test.js
import { uniteObjects } from './helpers';
const a = {
a: 1,
b: 'one',
c: {
a: 1,
b: 'one',
},
d: [1, 2],
};
const b = {
a: 2,
b: 'two',
c: {
b: 'two',
c: 0.2,
},
d: [2, 3, { a: 4, b: 5 }],
e: 'fine',
};
const d = {
a: 2,
b: 'two',
c: {
a: 1,
b: 'two',
c: 0.2,
},
d: [1, 2, 3, { a: 4, b: 5 }],
e: 'fine',
};
console.log('Here we go:');
const c = uniteObjects(a, b);
console.log('Here we get:');
console.log(c);
console.log(d);
console.log(JSON.stringify(c) === JSON.stringify(d) ? 'EQUAL' : 'different');
<file_sep>/README.md
# rs-slider
JS slider implementation
## Project goals
The code is written for educational purposes.
## We are using `yarn` and `parcel` bundler.
## Installing
- install [parcel](https://en.parceljs.org/)
- install [yarn](https://yarnpkg.com/lang/en/docs/install/#mac-stable)
- run `yarn install` into folder
## Run app
- run `yarn dev` for start
## Demo
[Demo](https://romanstrakhov.github.com/rs-slider/demo/)
| 24d59e3af8b971202c9bd5e833e1225a5ecd1683 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | romanstrakhov/rs-slider | bbbe7f4494e1198bcc95c1ad0963013982ffc04b | ae92cee3afb2786f8692d89428ce505ffb3d299f |
refs/heads/main | <file_sep># Teoria dos Graficos - Trabalho Pratico 1
## Nome dos integrantes do grupo
### <NAME>
### <NAME>
| 79083fe030fac6b6c75eb99bde66ff56f2e83aaa | [
"Markdown"
] | 1 | Markdown | gleydistonbr/Teoria-dos-Graficos-Trabalho-Pratico-1 | 794725fe385a0b74082b5917f4e56e7408ee6ed2 | f2b16e902ceb8a9fc1c3535226b366fbbc3ba562 |
refs/heads/master | <file_sep>package com.faith.test;
public class SalesData {
void display()
{
System.out.println("welcome");
System.out.println("Test2-Second commit");
}
}
| ccdb44d73fab99852b41d7b24a82bf535f34454d | [
"Java"
] | 1 | Java | naufananma/MyProject | d826196e074f712360016a9511ca6cc4c99d9cfe | bf7b6e5b82c0884087044b0a471e11b5d2cc3680 |
refs/heads/master | <repo_name>wedsonlima/semaforo<file_sep>/semaforo.c
#include <16F874.h>
#use delay (clock=1000000)
#fuses XT, NOWDT, NOPUT
/**
* Semaforo inteligente com controle de tempo de sinal verde por fluxo de veiculos
*/
/**
* Constantes
*/
// constantes para os displays das unidades
const BYTE unidade[10] = {
0b00000000,
0b00010000,
0b00100000,
0b00110000,
0b01000000,
0b01010000,
0b01100000,
0b01110000,
0b10000000,
0b10010000
};
// constantes para os displays das dezenas
const BYTE dezena[10] = {
0b00000000,
0b00000001,
0b00000010,
0b00000011,
0b00000100,
0b00000101,
0b00000110,
0b00000111,
0b00001000,
0b00001001
};
const int DISTANCIA_LACOS = 40; // metros
const int INFRACAO_VELOCIDADE = 60; // Km/h
// Definicao dos pinos //
// via A
const int PIN_CAMERA_VIA_A = PIN_A0;
const int PIN_L1_VIA_A = PIN_B4;
const int PIN_L2_VIA_A = PIN_B5;
// via B
const int PIN_CAMERA_VIA_B = PIN_A1;
const int PIN_L1_VIA_B = PIN_B6;
const int PIN_L2_VIA_B = PIN_B7;
// pinos dos semaforos via a
const int PIN_SEMAFORO_VERDE_A = PIN_D0;
const int PIN_SEMAFORO_AMARELO_A = PIN_D1;
const int PIN_SEMAFORO_VERMELHO_A = PIN_D2;
// pinos dos semaforos via b
const int PIN_SEMAFORO_VERDE_B = PIN_D3;
const int PIN_SEMAFORO_AMARELO_B = PIN_D4;
const int PIN_SEMAFORO_VERMELHO_B = PIN_D5;
// estado dos semaforos
const int SEMAFORO_VERMELHO = 0;
const int SEMAFORO_AMARELO = 1;
const int SEMAFORO_VERDE = 2;
// tipo de exibicao dos valores nos displays
int tipo_exibicao = 1; // 1 = tempo do semaforo; 2 = velocidade
int qtd_veiculos_via_a = 0;
int qtd_veiculos_via_b = 0;
/**
* Tempos
*/
// contador de segundos
long int segundos = 0;
int vtimer = 0;
// via A
int tempo_verde_via_a = 15;
int tempo_amarelo_via_a = 3;
// int tempo_vermelhor_via_a = tempo verde + tempo amarelo via b;
// via B
int tempo_verde_via_b = 15;
int tempo_amarelo_via_b = 3;
// int tempo_vermelhor_via_b = tempo verde + tempo amarelo via a;
// estado dos semaforos
int estado_semaforo_via_a = SEMAFORO_VERMELHO;
int estado_semaforo_via_b = SEMAFORO_VERMELHO;
/**
* Funcoes
*/
/**
* Exibe tempo nos displays
*/
void exibe_tempo(int tempo) {
int dez = 0;
int uni = 0;
dez = tempo / 10;
uni = tempo % 10;
output_c(dezena[dez]|unidade[uni]);
}
/**
* Exibe velocidade nos displays
*/
void exibe_velocidade(int velocidade) {
int dez = 0;
int uni = 0;
if (velocidade < 100) { // exibe velocidade apenas se for menor que 100
dez = velocidade / 10;
uni = velocidade % 10;
}
output_c(dezena[dez]|unidade[uni]);
}
/**
* Velocidade do veiculo
* Os tempos sao dados em segundos e a velocidade eh retornada em Km/h
*/
int velocidade(int tempo1, int tempo2) {
return (DISTANCIA_LACOS / (tempo2 - tempo1)) * 3.6;
}
/**
* Verifica se a velocidade esta acima da maxima permitida
* A velocidade recebida esta em Km/h
*/
int veiculo_infrator(int velocidade, int estado_semaforo) {
if (velocidade > INFRACAO_VELOCIDADE || estado_semaforo == SEMAFORO_VERMELHO) return 1;
return 0; // veiculo ok
}
void retira_foto_via_a() {
output_high(PIN_CAMERA_VIA_A);
}
void retira_foto_via_b() {
output_high(PIN_CAMERA_VIA_B);
}
/**
* VIA A
*/
int passou_primeiro_laco_via_a = 0; // informa que veiculo passou pelo primeiro laco da via a
int relogio_primeiro_laco_via_a = 0; // tempo em que o veiculo passou pelo primeiro laco
/**
* Primeiro laco da via A
*/
void primeiro_laco_via_a(int relogio) {
output_low(PIN_CAMERA_VIA_A);
passou_primeiro_laco_via_a = 1; // informa que veiculo passou pelo primeiro laco da via a
relogio_primeiro_laco_via_a = relogio; // tempo em que o veiculo passou pelo primeiro laco
}
/**
* Segundo laco da via A
*/
void segundo_laco_via_a(int relogio) {
if (passou_primeiro_laco_via_a == 1) { // veiculo passou pelo primeiro laco
int v = 0;
v = velocidade(relogio_primeiro_laco_via_a, relogio);
if (tipo_exibicao == 2) exibe_velocidade(v);
if (veiculo_infrator(v, estado_semaforo_via_a)) retira_foto_via_a();
// volta ao estado inicial, esperando novos veiculos
passou_primeiro_laco_via_a = 0;
relogio_primeiro_laco_via_a = 0;
qtd_veiculos_via_a++;
}
}
/**
* VIA B
*/
int passou_primeiro_laco_via_b = 0; // informa que veiculo passou pelo primeiro laco da via a
int relogio_primeiro_laco_via_b = 0; // tempo em que o veiculo passou pelo primeiro laco
/**
* Primeiro laco da via B
*/
void primeiro_laco_via_b(int relogio) {
output_low(PIN_CAMERA_VIA_B);
passou_primeiro_laco_via_b = 1; // informa que veiculo passou pelo primeiro laco da via a
relogio_primeiro_laco_via_b = relogio; // tempo em que o veiculo passou pelo primeiro laco
}
/**
* Segundo laco da via B
*/
void segundo_laco_via_b(int relogio) {
if (passou_primeiro_laco_via_b == 1) { // veiculo passou pelo primeiro laco
int v = 0;
v = velocidade(relogio_primeiro_laco_via_b, relogio);
if (tipo_exibicao == 2) exibe_velocidade(v);
if (veiculo_infrator(v, estado_semaforo_via_b)) retira_foto_via_b();
// volta ao estado inicial, esperando novos veiculos
passou_primeiro_laco_via_b = 0;
relogio_primeiro_laco_via_b = 0;
qtd_veiculos_via_b++;
}
}
/**
* Controle do semaforo da via a
*/
void controle_semaforo_via_a(int estado_semaforo) {
// muda estado do semaforo
estado_semaforo_via_a = estado_semaforo;
// limpa o semaforo
output_low(PIN_SEMAFORO_VERDE_A);
output_low(PIN_SEMAFORO_AMARELO_A);
output_low(PIN_SEMAFORO_VERMELHO_A);
// estado semaforo
switch (estado_semaforo) {
case SEMAFORO_VERDE:
output_high(PIN_SEMAFORO_VERDE_A);
break;
case SEMAFORO_AMARELO:
output_high(PIN_SEMAFORO_AMARELO_A);
break;
case SEMAFORO_VERMELHO:
output_high(PIN_SEMAFORO_VERMELHO_A);
break;
}
}
/**
* Controle de semaforo da via b
*/
void controle_semaforo_via_b(int estado_semaforo) {
// muda estado do semaforo
estado_semaforo_via_b = estado_semaforo;
// limpa o semaforo
output_low(PIN_SEMAFORO_VERDE_B);
output_low(PIN_SEMAFORO_AMARELO_B);
output_low(PIN_SEMAFORO_VERMELHO_B);
// estado semaforo
switch (estado_semaforo) {
case SEMAFORO_VERDE:
output_high(PIN_SEMAFORO_VERDE_B);
break;
case SEMAFORO_AMARELO:
output_high(PIN_SEMAFORO_AMARELO_B);
break;
case SEMAFORO_VERMELHO:
output_high(PIN_SEMAFORO_VERMELHO_B);
break;
}
}
/**
* Inicializa os semaforos
*/
void start_semaforos() {
controle_semaforo_via_a(SEMAFORO_VERMELHO);
controle_semaforo_via_b(SEMAFORO_VERMELHO);
}
void modifica_tempos_via_a(int fluxo_via_a, int fluxo_via_b) {
if (fluxo_via_a > 0) {
if ( fluxo_via_a <= (fluxo_via_b + 0.3*fluxo_via_b) ) tempo_verde_via_a = 30;
if ( (fluxo_via_b + 0.3*fluxo_via_b) < fluxo_via_a && fluxo_via_a <= (fluxo_via_b + 0.6*fluxo_via_b) ) tempo_verde_via_a = 35;
if ( fluxo_via_a > (fluxo_via_b + 0.6*fluxo_via_b) ) tempo_verde_via_a = 40;
} else {
tempo_verde_via_a = 15;
}
}
void modifica_tempos_via_b(int fluxo_via_a, int fluxo_via_b) {
if (fluxo_via_b > 0) {
if ( fluxo_via_b <= (fluxo_via_a + 0.3*fluxo_via_a) ) tempo_verde_via_b = 30;
if ( (fluxo_via_a + 0.3*fluxo_via_a) < fluxo_via_b && fluxo_via_b <= (fluxo_via_a + 0.6*fluxo_via_a) ) tempo_verde_via_b = 35;
if ( fluxo_via_b > (fluxo_via_a + 0.6*fluxo_via_a) ) tempo_verde_via_b = 40;
} else {
tempo_verde_via_b = 15;
}
}
/**
* Interrupcoes
*/
// para controle de fluxo de veiculos
int fluxo_veiculos_via_a = 0;
int fluxo_veiculos_via_b = 0;
int tempo_inicial_verde = 0; // tempo em que o sinal verde foi acionado
int tempo_inicial_amarelo = 0; // tempo em que o sinal amarelo foi acionado
int tempo_inicial_vermelho = 0; // tempo em que o sinal vermelho foi acionado
int ultima_via = 0; // informa ultima via liberada (1 => a; 2 => b)
int fluxo = 0; // qndo fluxo chega a 2, devera ser calculado e os valores modificados
/**
* Contador de segundos a partir da interrupcao do timer0
**/
#INT_TIMER0
void trata_timer0() {
set_timer0(131 + get_timer0());
vtimer++;
if (vtimer == 125) { // 1 segundo = 125
vtimer = 0;
segundos++; // incrementa os segundos
if (tipo_exibicao == 1) {
if (estado_semaforo_via_a == SEMAFORO_VERDE) {
exibe_tempo(tempo_verde_via_a - (segundos - tempo_inicial_verde));
} else if (estado_semaforo_via_b == SEMAFORO_VERDE) {
exibe_tempo(tempo_verde_via_b - (segundos - tempo_inicial_verde));
}
}
if ((segundos - tempo_inicial_vermelho) >= 3) { // transicao de vias
// primeira mudanca no estado dos semaforos
if (estado_semaforo_via_a == estado_semaforo_via_b && estado_semaforo_via_a == SEMAFORO_VERMELHO) {
tempo_inicial_vermelho = 0;
tempo_inicial_verde = segundos;
if (ultima_via == 0 || ultima_via == 2) {
ultima_via = 1;
controle_semaforo_via_a(SEMAFORO_VERDE);
if (fluxo == 0) fluxo = 1; // calcular fluxo da via a
} else {
ultima_via = 2;
controle_semaforo_via_b(SEMAFORO_VERDE);
}
} else {
// fluxo de veiculos nas vias //
if (estado_semaforo_via_a == SEMAFORO_VERDE && fluxo == 1 && segundos - tempo_inicial_verde == 15) {
// recupera o valor da quantidade de veiculos da via a e armazena
fluxo_veiculos_via_a = qtd_veiculos_via_a;
qtd_veiculos_via_a = 0; // zera para nova contagem
fluxo = 2;
modifica_tempos_via_a(fluxo_veiculos_via_a, fluxo_veiculos_via_b);
}
if (estado_semaforo_via_b == SEMAFORO_VERDE && fluxo == 2 && segundos - tempo_inicial_verde == 15) {
// recupera o valor da quantidade de veiculos da via b e armazena
fluxo_veiculos_via_b = qtd_veiculos_via_b;
qtd_veiculos_via_b = 0; // zera para nova contagem
fluxo = 1;
modifica_tempos_via_b(fluxo_veiculos_via_a, fluxo_veiculos_via_b);
}
// via A liberada //
// muda estado do semaforo para amarelo
if (estado_semaforo_via_a == SEMAFORO_VERDE && (segundos - tempo_inicial_verde) == tempo_verde_via_a) {
tempo_inicial_verde = 0; // reinicia contagem do tempo verde
tempo_inicial_amarelo = segundos;
controle_semaforo_via_a(SEMAFORO_AMARELO);
}
// muda estado do semaforo para vermelho
if (estado_semaforo_via_a == SEMAFORO_AMARELO && (segundos - tempo_inicial_amarelo) == tempo_amarelo_via_a) {
tempo_inicial_amarelo = 0; // reinicia contagem do tempo amarelo
tempo_inicial_vermelho = segundos;
controle_semaforo_via_a(SEMAFORO_VERMELHO);
}
// via B liberada //
// muda estado do semaforo para amarelo
if (estado_semaforo_via_b == SEMAFORO_VERDE && (segundos - tempo_inicial_verde) == tempo_verde_via_b) {
tempo_inicial_verde = 0; // reinicia contagem do tempo verde
tempo_inicial_amarelo = segundos;
controle_semaforo_via_b(SEMAFORO_AMARELO);
}
// muda estado do semaforo para vermelho
if (estado_semaforo_via_b == SEMAFORO_AMARELO && (segundos - tempo_inicial_amarelo) == tempo_amarelo_via_b) {
tempo_inicial_amarelo = 0; // reinicia contagem do tempo amarelo
tempo_inicial_vermelho = segundos;
controle_semaforo_via_b(SEMAFORO_VERMELHO);
}
}
}
}
}
/**
* Interrupcoes da porta B
*/
#INT_RB
void trata_rb() {
int x;
// via A
if (input(PIN_L1_VIA_A) == 0) primeiro_laco_via_a(segundos);
if (input(PIN_L2_VIA_A) == 0) segundo_laco_via_a(segundos);
// via B
if (input(PIN_L1_VIA_B) == 0) primeiro_laco_via_b(segundos);
if (input(PIN_L2_VIA_B) == 0) segundo_laco_via_b(segundos);
x = input_b(); // reinicia leitura porta B
}
#INT_EXT
void trata_ext() {
// modifica o tipo de exibicao
if (tipo_exibicao == 1) tipo_exibicao = 2;
else tipo_exibicao = 1;
output_c(dezena[0]|unidade[0]);
}
void main() {
enable_interrupts(GLOBAL|INT_RB|INT_TIMER0|INT_EXT); // habilita interrupção global, na porta B e do timer 0
setup_timer_0(RTCC_INTERNAL|RTCC_DIV_16); // define uso do timer 0 com prescaler 16
set_timer0(131); // inicia contagem do timer 0
start_semaforos(); // inicializa o sistema
while(true);
}
| 77aa7ed1c5a1ce734b18f70317e08e47b2c59925 | [
"C"
] | 1 | C | wedsonlima/semaforo | bf4733df9625f91de6bd38be9eced1bc11107302 | 999a4bf28cfa92bdd0eed523b6409efa7a7cdfba |
refs/heads/master | <file_sep>"""robotController controller."""
# You may need to import some classes of the controller module. Ex:
# from controller import Robot, Motor, DistanceSensor
from controller import Robot
from deepbots.robots.controllers.robot_emitter_receiver_csv import RobotEmitterReceiverCSV
class CartpoleRobot(RobotEmitterReceiverCSV):
def __init__(self):
super().__init__()
self.positionSensor = self.robot.getPositionSensor("polePosSensor")
self.positionSensor.enable(self.get_timestep())
self.wheel1 = self.robot.getMotor("wheel1")
self.wheel1.setPosition(float("inf"))
self.wheel1.setVelocity(0.0)
self.wheel2 = self.robot.getMotor("wheel2")
self.wheel2.setPosition(float('inf'))
self.wheel2.setVelocity(0.0)
self.wheel3 = self.robot.getMotor("wheel3")
self.wheel3.setPosition(float("inf"))
self.wheel3.setVelocity(0.0)
self.wheel4 = self.robot.getMotor("wheel4")
self.wheel4.setPosition(float("inf"))
self.wheel4.setVelocity(0.0)
def create_message(self):
# Read the sensor value, convert to string and save it in a list
message = str(self.positionSensor.getValue())
return message
def use_message_data(self, message):
action = int(message[0]) # Convert the string message into an action integer
if action == 0:
motorSpeed = 5.0
elif action == 1:
motorSpeed = -5.0
else:
motorSpeed = 0.0
# Set the motor's velocities based on the action received
self.wheel1.setVelocity(motorSpeed)
self.wheel2.setVelocity(motorSpeed)
self.wheel3.setVelocity(motorSpeed)
self.wheel4.setVelocity(motorSpeed)
# Create the robot controller object and run it
robot_controller = CartpoleRobot()
robot_controller.run() # Run method is implemented by the framework, just need to call it
# create the Robot instance.
robot = Robot()
# get the time step of the current world.
timestep = int(robot.getBasicTimeStep())
# You should insert a getDevice-like function in order to get the
# instance of a device of the robot. Something like:
# motor = robot.getMotor('motorname')
# ds = robot.getDistanceSensor('dsname')
# ds.enable(timestep)
# Main loop:
# - perform simulation steps until Webots is stopping the controller
while robot.step(timestep) != -1:
# Read the sensors:
# Enter here functions to read sensor data, like:
# val = ds.getValue()
# Process sensor data here.
# Enter here functions to send actuator commands, like:
# motor.setPosition(10.0)
pass
# Enter here exit cleanup code.
<file_sep>import numpy as np
from sklearn.multioutput import MultiOutputRegressor
from sklearn.linear_model import Ridge
from sklearn import svm
from torch.utils.data import Dataset
import torch
import csv
class dataset(Dataset):
def __init__(self, file_name, root_dir):
self.file_name = file_name
self.__get_data_from_csv()
self.root_dir = root_dir
self.IOI = [3,4,5,6]
self.IOT = [0,1,2]
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
if torch.is_tensor(idx):
idx = idx.tolist()
#print(idx)
lst = self.data[idx]
#print(lst)
lst = [float(i) for i in lst]
lst = np.array(lst)
#print(lst)
return lst[self.IOI], lst[self.IOT]
def __get_data_from_csv(self):
with open(self.file_name, newline='') as csvfile:
self.data = list(csv.reader(csvfile))
def loadXy(dataset):
X, y = [], []
for i in range(len(dataset)):
x, t = dataset[i]
#x, t = x.reshape(-1, 1), t.reshape(-1, 1)
X.append(x)
y.append(t)
return X, y
if __name__ == "__main__":
ds = dataset('data.txt', '')
X, y = loadXy(ds)
#clf = MultiOutputRegressor(Ridge(random_state=123)).fit(X, y)
clf =
print(X[0])
print(clf.predict([X[0]]))<file_sep>import os
from os import path
import torch
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import csv
from torch.utils.data import Dataset, DataLoader
import torch
from torch import nn
import torch.nn.functional as F
import torch.optim as optim
import math
# Notes: two layer with 4->4 and 4->1 works well batch 10
# three layers with (4,4), (4,3), (4,1) batch 10
# DEFAULT VARIABLES
UNCER = math.pi / 180
TERRAIN = 0 # mean even
DATAFILE= 'data.txt' if TERRAIN == 1 else 'data_even.txt'
ENSEMBLESIZE = 5
DEBUG=True
SAVE=True
class predictor(nn.Module):
def __init__(self):
super(predictor, self).__init__()
self.fc1 = nn.Linear(4, 4)
#self.fc2 = nn.Linear(1000, 500)
#self.fc3 = nn.Linear(500, 250)
#self.fc4 = nn.Linear(250, 120)
#self.fc5 = nn.Linear(120, 60)
#self.fc6 = nn.Linear(4, 3)
#self.fc7 = nn.Linear(3, 2)
self.fc8 = nn.Linear(4, 1)
def forward(self, x):
x = F.relu(self.fc1(x))
#x = F.relu(self.fc2(x))
#x = F.relu(self.fc3(x))
#x = F.relu(self.fc4(x))
#x = F.relu(self.fc5(x))
#x = F.relu(self.fc6(x))
#x = F.relu(self.fc7(x))
x = self.fc8(x)
return x
class dataset(Dataset):
def __init__(self, file_name, root_dir):
self.file_name = file_name
self.__get_data_from_csv()
self.root_dir = root_dir
self.IOI = [11,12,13,14]
self.IOT = [0]
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
if torch.is_tensor(idx):
idx = idx.tolist()
#print(idx)
lst = self.data[idx]
#print(lst)
lst = [float(i) for i in lst]
#for i in self.IOI:
# lst[i] = math.cos(lst[i])
lst = np.array(lst)
#print(lst)
return lst[self.IOI], lst[self.IOT]
def __get_data_from_csv(self):
with open(self.file_name, newline='') as csvfile:
self.data = list(csv.reader(csvfile))
def split(ds):
test = len(ds) // 10
train = len(ds) - test
return torch.utils.data.random_split(ds, [train, test])
def train_model(model, trainloader, criterion, max_epoches, thres=1e-3, debug=DEBUG):
optimizer = optim.Adam(model.parameters(), lr=0.001)
hl, = plt.plot([], [])
loss = 0.0
for epoch in range(max_epoches):
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
inputs, labels = data
inputs, labels = inputs[0], labels[0]
optimizer.zero_grad()
outputs = model(inputs.float())
loss = criterion(outputs, labels.float())
loss.backward()
optimizer.step()
running_loss += loss.item()
loss = running_loss / len(trainloader)
if debug: print("train_model: loss is {l}".format(l=loss))
if loss < thres:
if debug: print("train_model: training done")
return
def eval_model(model, ld, uncer=UNCER, debug=DEBUG):
correct = 0
total = 0
with torch.no_grad():
for data in ld:
input, labels = data
input, labels = input[0], labels[0]
outputs = model(input.float())
total += 1
#print(outputs, labels)
if abs(outputs[0] - labels[0]) < uncer:
correct += 1
acc = 100 * correct / total
if debug: print("eval_model: Accuracy is %d %%" % acc)
return acc
def ensemble(models, input):
output = None
for model in models:
if output is None: output = model(input)
else: output += model(input)
return output / len(models)
def eval_ensemble(uncer=UNCER, debug=DEBUG):
ds = dataset(DATAFILE, '')
print("splitting")
_, test = split(ds)
ld = DataLoader(test, batch_size=10, shuffle=True, num_workers=1)
models = load_ensemble()
correct = 0
total = 0
with torch.no_grad():
for data in ld:
input, labels = data
input, labels = input[0], labels[0]
outputs = ensemble(models, input.float())
total += 1
#print(outputs, labels)
if abs(outputs[0] - labels[0]) < uncer:
correct += 1
acc = 100 * correct / total
if debug: print("Accuracy is %d %%" % acc)
return acc
def full_train_process(uncer=math.pi/180):
model = predictor()
ds = dataset(DATAFILE, '')
#print("splitting")
train, test = split(ds)
train_ld = DataLoader(train, batch_size=10, shuffle=True, num_workers=1)
test_ld = DataLoader(test, batch_size=10, shuffle=True, num_workers=1)
#print("training")
train_model(model, train_ld, criterion=nn.MSELoss(), max_epoches=200, thres=1e-3)
#print("evaluating")
return eval_model(model, test_ld, uncer)
def full_train_ensemble(models, uncer=UNCER, save=SAVE):
for i, model in enumerate(models):
ds = dataset(DATAFILE, '')
train, test = split(ds)
train_ld = DataLoader(train, batch_size=10, shuffle=True, num_workers=1)
# test_ld = DataLoader(test, batch_size=10, shuffle=True, num_workers=1)
train_model(model, train_ld, criterion=nn.MSELoss(), max_epoches=200, thres=1e-3)
if save: torch.save(model.state_dict(), './model_ensemble_{i}.pt'.format(i=i))
return models
def stability(epoches, uncer=UNCER):
acc = 0
for e in range(epoches):
acc += full_train_process(uncer=uncer)
print("stability epoch {e}".format(e=e))
return acc / epoches
def load_ensemble():
models = []
if not path.exists("./model_ensemble_0.pt"):
print("load_ensemble: ERROR, no pretrained weights found")
return
i = 0
while path.exists("./model_ensemble_{i}.pt".format(i=i)):
model = predictor()
model.load_state_dict(torch.load("./model_ensemble_{i}.pt".format(i=i)))
models.append(model)
i += 1
return models
def stability_ensemble(epoches, uncer=UNCER, debug=DEBUG):
acc = 0
for e in range(epoches):
models = []
for _ in range(ENSEMBLESIZE): models.append(predictor())
full_train_ensemble(models, uncer=uncer)
acc += eval_ensemble(uncer=uncer, debug=debug)
print("stability epoch {e}".format(e=e))
return acc / epoches
def test(ts):
model = predictor()
model.load_state_dict(torch.load('./model.pt'))
for s in ts:
s = [s]
o = model(torch.tensor(s).float())
print(s, o * 180 / math.pi)
if __name__ == '__main__':
op = 1
if op == 0:
model = predictor()
ds = dataset(DATAFILE, '')
print("splitting")
train, test = split(ds)
train_ld = DataLoader(train, batch_size=10, shuffle=True, num_workers=1)
test_ld = DataLoader(test, batch_size=10, shuffle=True, num_workers=1)
print("training")
train_model(model, train_ld, criterion=nn.MSELoss(), max_epoches=200)
print("evaluating")
uncer = 2 * math.pi / 180
print("Train accuracy is %d %%" % eval_model(model, train_ld, uncer=uncer))
print("Test accuracy is %d %%" % eval_model(model, test_ld, uncer=uncer))
torch.save(model.state_dict(), './model.pt')
elif op == 1: # ensemble learning
models = []
for i in range(ENSEMBLESIZE): models.append(predictor())
models = full_train_ensemble(models)
eval_ensemble(uncer=2*UNCER)
elif op == 2:
print("stability is: ", stability(20, uncer=5*UNCER))
elif op == 3: # ensemble stability
print("emsemble stability is: ", stability_ensemble(20))
elif op == 4: # eval_ensemble using pretrained weights
print("ensemble accuracy is: ", eval_ensemble())
else:
test([[0.4, 0.4, 0.4, 0.4]])
<file_sep># Inputs: 1) position of four motors 2) velocity of four motors 3) IMU
# Outputs: 4)
from controller import Robot
import numpy as np
from deepbots.supervisor.controllers.supervisor_emitter_receiver import SupervisorCSV
import ast
from PPOAgent import PPOAgent, Transition
from utilities import normalizeToRange
class ddpg_controller(SupervisorCSV):
def __init__(self):
super().__init__()
self.observationSpace = 30 # The agent has four inputs
self.actionSpace = 8 # the agent can perform two actions
self.robot = None
self.respawnRobot()
self.IMU = self.supervisor.getFromDef("IMU")
#self.poleEndpoint = self.supervisor.getFromDef("POLE_ENDPOINT")
self.messageReceived = None # Variable to save the messages received from the robot
self.episodeCount = 0 # Episode counter
self.episodeLimit = 20000 # Max number of episodes allowed
self.stepPerEpisode = 100 # Max number of steps per episode
self.episodeScore = 0 # Score accumulated during an episode
self.episodeScoreList = [] # A list to save all the episode scores, used to check if task is solved
self.abs_last = 0
self.got_big_reward = 0
def respawnRobot(self):
#print("respawn called")
if self.robot is not None:
# Despawn existing robot
# print("called")
self.robot.remove()
# Respawn robot in starting position and state
#print("self.robot is None")
rootNode = self.supervisor.getRoot() # This gets the root of the scene tree
childrenField = rootNode.getField("children") # This gets a list of all the children, ie. objects of the scene
childrenField.importMFNode(-2, "Robot_walk.wbo") # Load robot from file and add to second-to-last position
# Get the new robot and pole endpoint references
self.robot = self.supervisor.getFromDef("ROBOT")
def get_observations(self):
# Leg positions
#hipy_a_pos = normalizeToRange(self.robot.hip()[2], -0.4, 0.4, -1.0, 1.0)
# Linear velocity on z axis
#cartVelocity = normalizeToRange(self.robot.getVelocity()[2], -0.2, 0.2, -1.0, 1.0, clip=True)
# Angular velocity x of endpoint
#endPointVelocity = normalizeToRange(self.poleEndpoint.getVelocity()[3], -1.5, 1.5, -1.0, 1.0, clip=True)
self.messageReceived = self.handle_receiver()
#if self.messageReceived is not None:
# poleAngle = normalizeToRange(float(self.messageReceived[0]), -0.23, 0.23, -1.0, 1.0, clip=True)
#else:
# # Method is called before self.messageReceived is initialized
# poleAngle = 0.0
if self.messageReceived is not None:
message = self.messageReceived
message = [float(i) for i in message]
#print("message received", message)
return message
else:
return [0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0]
def get_reward(self, action=None):
# TODO: change this to match our robot
# -10 for topple
# abs(pos, orig) as reward ?
if self.messageReceived is not None:
message = self.messageReceived
message = [float(i) for i in message]
roll, pitch, yaw, hipy_a_pos, hipy_b_pos, hipy_c_pos, hipy_d_pos\
= message[0], message[1], message[2],\
message[3], message[4], message[5],\
message[6]
x, y = message[11], message[13]
#print("reward", (abs(roll) + abs(pitch) - self.abs_last) * 10)
cri = (abs(roll) + abs(pitch))
if cri < self.abs_last:
reward = (self.abs_last - cri) * 1000
else:
reward = -0.1
self.abs_last = cri
if (cri < 0.0005):
self.got_big_reward += 1
reward += 500000
elif (cri < 0.001):
self.got_big_reward += 1
reward += 200000
elif (cri < 0.005):
self.got_big_reward += 1
reward += 100000
elif (cri < 0.01):
self.got_big_reward += 1
# print("got 20000")
reward += 40000
elif (cri < 0.05):
self.got_big_reward += 1
# print("got 10000")
reward += 1000
elif (cri < 0.1):
self.got_big_reward += 1
# print("got 5000")
#reward += 5000
#elif (cri < 0.3):
# self.got_big_reward += 1
# print("got 2000")
# reward += 2000
#elif (cri < 0.5):
# print("got 500")
# reward += 500
else:
reward -= 100000
if abs(hipy_a_pos) < 0.01 or \
abs(hipy_a_pos) < 0.01 or \
abs(hipy_a_pos) < 0.01 or \
abs(hipy_a_pos) < 0.01:
reward -= 1000
#else:
# print(cri)
# if (self.got_big_reward > 0):
# reward -= 1000
# else:
# reward -= 1000
#if (cri < 0.002):
# print("got big reward")
# reward += 10000
#if (cri > 0.02):
# reward = cri * 100
#if (cri > 0.01):
# reward = cri
#else:
# reward = -0.01
#print(self.abs_last)
return reward
return 0
def is_done(self):
if self.messageReceived is not None:
message = self.messageReceived
message = [float(i) for i in message]
roll, pitch, yaw = message[0], message[1], message[2]
#print("reward", (abs(roll) + abs(pitch) - self.abs_last) * 10)
cri = abs(roll) + abs(pitch)
#if abs(cri) > 0.1:
#return True
return False
def solved(self):
#if len(self.episodeScoreList) > 100: # Over 100 trials thus far
# if np.mean(self.episodeScoreList[-100:]) > 1000.0: # Last 100 episodes' scores average value
# return True
return False
def reset(self):
#print("reset called")
self.respawnRobot()
self.supervisor.simulationResetPhysics() # Reset the simulation physics to start over
self.messageReceived = None
return [0.0 for _ in range(self.observationSpace)]
def get_info(self):
return None
supervisor = ddpg_controller()
agent = PPOAgent(supervisor.observationSpace, supervisor.actionSpace)
solved = False
# Run outer loop until the episodes limit is reached or the task is solved
while not solved and supervisor.episodeCount < supervisor.episodeLimit:
observation = supervisor.reset() # Reset robot and get starting observation
supervisor.episodeScore = 0
for step in range(supervisor.stepPerEpisode):
#print(step)
# In training mode the agent samples from the probability distribution, naturally implementing exploration
selectedAction, actionProb = agent.work(observation, type_="selectAction")
# Step the supervisor to get the current selectedAction's reward, the new observation and whether we reached
# the done condition
newObservation, reward, done, info = supervisor.step([selectedAction])
# Save the current state transition in agent's memory
trans = Transition(observation, selectedAction, actionProb, reward, newObservation)
agent.storeTransition(trans)
if done:
# Save the episode's score
supervisor.episodeScoreList.append(supervisor.episodeScore)
agent.trainStep(batchSize=step)
solved = supervisor.solved() # Check whether the task if solved
break
supervisor.episodeScore += reward # Accumulate episode reward
observation = newObservation # observation for next step is current step's newObservation
print("Episode #", supervisor.episodeCount, "score:", supervisor.episodeScore)
agent.save("")
supervisor.episodeCount += 1 # Increment episode counter
if not solved:
print("Task is not solved, deploying agent for testing")
elif solved:
print("Task is solved, deploying agent for testing...")
observation = supervisor.reset()
while True:
selectedAction, actionProb = agent.work(observation, type_="selectActionMax")
observation, _, _, _ = supervisor.step([selectedAction])<file_sep># Webots Simulation
## Controllers:
### ddpg_controller:
### levelingController:
### robotController:
### simple_joint_controller:
### simple_walking_controller:
## Libraries:
## Plugins:
### physics:
### remote_controls:
### robot_windows:
## Samples:
### ddpg-bipedal:
### deepbots_cartPoleWorld:
## Worlds:
### 4Leggy-V1-ddpg:
### 4Leggy-V1:
### empty:
<file_sep>import torch
import torch.nn as nn
import torch.nn.functional as F
class predictor(nn.Module):
def __init__(self):
super(predictor, self).__init__()
self.fc1 = nn.Linear(12, 8)
self.fc2 = nn.Linear(8, 5)
self.fcx = nn.Linear(5, 3)
def forward(self, x):
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
<file_sep>"""simple_joint_controller controller."""
# You may need to import some classes of the controller module. Ex:
# from controller import Robot, Motor, DistanceSensor
import time
PLOT = True
import matplotlib.pyplot as plt
from controller import Robot, Motor
# create the Robot instance.
robot = Robot()
# get the time step of the current world.
timestep = int(robot.getBasicTimeStep())
# You should insert a getDevice-like function in order to get the
# instance of a device of the robot. Something like:
# motor = robot.getMotor('motorname')
# ds = robot.getDistanceSensor('dsname')
# ds.enable(timestep)
control_structures = [["hipx_a", "hipy_a", "leg_a"],
["hipx_b", "hipy_b", "leg_b"],
["hipx_c", "hipy_c", "leg_c"],
["hipx_d", "hipy_d", "leg_d"]]
def set_motor_speed(motorName, speed):
motor = robot.getMotor(motorName)
motor.setPosition(float("inf"))
motor.setVelocity(speed)
def set_motor_position(motorName, pos):
motor = robot.getMotor(motorName)
motor.setPosition(pos)
# set motor speed
def set_all_motors(speed):
for structure in control_structures:
for motor_name in structure:
set_motor_speed(motor_name, speed)
def leg_forward(leg, speed, sleep = None):
set_motor_speed("hipx_" + leg, speed)
if sleep is not None:
robot.step(sleep)
def leg_raise(leg, speed, sleep = None):
set_motor_speed("hipy_" + leg, -abs(speed))
if sleep is not None:
robot.step(sleep)
def leg_plant(leg, sleep = None):
motor = robot.getMotor("hipy_" + leg)
motor.setPosition(0.7)
#set_motor_position("hipy_" + leg, 0.5)
if sleep is not None:
robot.step(sleep)
def leg_raise_type1(leg):
set_motor_speed("hipy_" + leg, -0.2)
set_motor_speed("leg_" + leg, -0.5)
set_motor_speed("hipx_" + leg, 0.2)
robot.step(2000)
def gait_1():
set_motor_position("hipy_c", 0)
set_motor_position("hipy_d", 0)
set_motor_position("hipy_a", 0)
set_motor_position("hipy_b", 0)
set_motor_position("leg_c", 1.57)
set_motor_position("leg_d", 1.57)
set_motor_position("leg_a", 1.57)
set_motor_position("leg_b", 1.57)
robot.step(2000)
while True:
set_motor_position("hipx_a", 0.5)
set_motor_position("hipx_b", -0.5)
robot.step(2000)
set_motor_position("hipy_c", -0.5)
set_motor_position("leg_c", 0.5)
robot.step(2000)
set_motor_position("hipx_a", -0.5)
set_motor_position("hipx_b", 0.5)
set_motor_position("hipy_c", 0)
set_motor_position("leg_c", 1.57)
robot.step(2000)
set_motor_position("hipx_a", 0.5)
set_motor_position("leg_a", 0.5)
robot.step(500)
set_motor_position("leg_a", 1.57)
robot.step(2000)
set_motor_position("hipx_b", -0.5)
set_motor_position("leg_b", 0.5)
robot.step(500)
set_motor_position("leg_b", 1.57)
def get_tilt():
RPT = imu.getRollPitchYaw()
return abs(RPT[0]) + abs(RPT[1])
def record_tilt():
tilt_data.append(get_tilt())
def get_tilt_data():
return tilt_data
def plot_tilt():
plt.plot(get_tilt_data())
plt.ylabel('tile = abs(roll) + abs(pitch)')
plt.show()
tilt_data = []
def gait_2():
set_motor_position("hipy_c", 0)
set_motor_position("hipy_d", 0)
set_motor_position("hipy_a", 0)
set_motor_position("hipy_b", 0)
set_motor_position("leg_c", 1.57)
set_motor_position("leg_d", 1.57)
set_motor_position("leg_a", 1.57)
set_motor_position("leg_b", 1.57)
robot.step(2000)
record_tilt()
set_motor_position("hipx_a", 0.2)
set_motor_position("hipx_b", -0.2)
set_motor_position("leg_c", 1.57)
set_motor_position("leg_d", 1.57)
set_motor_position("leg_a", 1.57)
set_motor_position("leg_b", 1.57)
robot.step(2000)
record_tilt()
while True:
set_motor_position("hipy_c", -0.5)
set_motor_position("leg_c", 0.5)
robot.step(2000)
record_tilt()
set_motor_position("hipx_a", -0.2)
set_motor_position("hipx_b", 0.2)
set_motor_position("leg_c", 1.57)
set_motor_position("leg_d", 1.57)
set_motor_position("leg_a", 1.57)
set_motor_position("leg_b", 1.57)
robot.step(2000)
record_tilt()
set_motor_position("hipx_c", -0.5)
set_motor_position("hipx_d", 0.5)
robot.step(2000)
record_tilt()
set_motor_position("hipy_a", -0.5)
robot.step(500)
record_tilt()
set_motor_position("hipx_a", 0.5)
robot.step(500)
record_tilt()
set_motor_position("hipy_a", -0.2)
robot.step(2000)
record_tilt()
set_motor_position("hipx_c", 0)
set_motor_position("hipx_d", 0)
robot.step(2000)
record_tilt()
set_motor_position("hipx_c", 0.5)
set_motor_position("hipx_d", -0.5)
robot.step(2000)
record_tilt()
set_motor_position("hipy_b", -0.5)
robot.step(500)
record_tilt()
set_motor_position("hipx_b", -0.5)
robot.step(500)
record_tilt()
set_motor_position("hipy_b", 0)
set_motor_position("hipx_c", 0)
set_motor_position("hipx_d", 0)
if PLOT: plot_tilt()
imu = robot.getInertialUnit("inertial unit")
imu.enable(200)
robot.step(2000)
print(imu.getRollPitchYaw())
# 0. get data
# 1. graph
# 2. make dynamic
# Next steps
# 0) update motor characteristics
# 1) reduce tilt, motor usage, etc
# 2) test on uneven terrain
gait_2()
#set_motor_position("hipy_a", 0)
#set_motor_position("leg_a", 1.57)
# Main loop:
# - perform simulation steps until Webots is stopping the controller
while robot.step(timestep) != -1:
# Read the sensors:
# Enter here functions to read sensor data, like:
# val = ds.getValue()
# Process sensor data here.
# Enter here functions to send actuator commands, like:
# motor.setPosition(10.0)
pass
# Enter here exit cleanup code.
<file_sep>"""simple_joint_controller controller."""
# You may need to import some classes of the controller module. Ex:
# from controller import Robot, Motor, DistanceSensor
from controller import Robot, Motor
# create the Robot instance.
robot = Robot()
# get the time step of the current world.
timestep = int(robot.getBasicTimeStep())
# You should insert a getDevice-like function in order to get the
# instance of a device of the robot. Something like:
# motor = robot.getMotor('motorname')
# ds = robot.getDistanceSensor('dsname')
# ds.enable(timestep)
control_structures = [["hipx_a", "hipy_a", "leg_a"],
["hipx_b", "hipy_b", "leg_b"],
["hipx_c", "hipy_c", "leg_c"],
["hipx_d", "hipy_d", "leg_d"]]
def set_motor_speed(motorName, speed):
motor = robot.getMotor(motorName)
motor.setPosition(float("inf"))
motor.setVelocity(speed)
# set motor speed
def set_all_motors(speed):
for structure in control_structures:
for motor_name in structure:
set_motor_speed(motor_name, speed)
set_all_motors(0.05)
# Main loop:
# - perform simulation steps until Webots is stopping the controller
while robot.step(timestep) != -1:
# Read the sensors:
# Enter here functions to read sensor data, like:
# val = ds.getValue()
# Process sensor data here.
# Enter here functions to send actuator commands, like:
# motor.setPosition(10.0)
pass
# Enter here exit cleanup code.
<file_sep># Inputs: 1) position of four motors 2) velocity of four motors 3) IMU
# Outputs: 4)
from controller import Robot
import numpy as np
from deepbots.supervisor.controllers.supervisor_emitter_receiver import SupervisorCSV
import ast
import math
import csv
from PPOAgent import PPOAgent, Transition
from utilities import normalizeToRange
LOG = False
STATIONARY_THRES = 5000
MOVE_THRES = 1e-3
class ddpg_controller(SupervisorCSV):
def __init__(self):
super().__init__()
self.observationSpace = 30 # The agent has four inputs
self.actionSpace = 36 # the agent can perform two actions
self.robot = None
self.respawnRobot()
self.IMU = self.supervisor.getFromDef("IMU")
#self.poleEndpoint = self.supervisor.getFromDef("POLE_ENDPOINT")
self.messageReceived = None # Variable to save the messages received from the robot
self.episodeCount = 0 # Episode counter
self.episodeLimit = 2000000 # Max number of episodes allowed
self.stepPerEpisode = 400000 # Max number of steps per episode
self.episodeScore = 0 # Score accumulated during an episode
self.episodeScoreList = [] # A list to save all the episode scores, used to check if task is solved
self.last_x = -0.5
self.max_x = 0
self.stationary_count = 0
self.step_count = 1
self.last_big_x = 0
self.done = False
self.state = 0 # 0 means level, 1 means step, 2 means level, 3 means turn
self.last_hipx_pos = [0, 0, 0, 0]
self.last_leg_raised = 0
self.last_leg_raised_count = 0
self.last_leg_raised_THRES = 30
self.last_cri = 0
self.last_cri_count = 0
self.last_h = 0
self.last_h_count = 0
self.last_yaw = 0
self.last_yaw_count = 0
def respawnRobot(self):
#print("respawn called")
if self.robot is not None:
# Despawn existing robot
# print("called")
self.robot.remove()
# Respawn robot in starting position and state
#print("self.robot is None")
rootNode = self.supervisor.getRoot() # This gets the root of the scene tree
childrenField = rootNode.getField("children") # This gets a list of all the children, ie. objects of the scene
childrenField.importMFNode(-2, "Robot_walk.wbo") # Load robot from file and add to second-to-last position
# Get the new robot and pole endpoint references
self.robot = self.supervisor.getFromDef("ROBOT")
def get_observations(self):
# Leg positions
#hipy_a_pos = normalizeToRange(self.robot.hip()[2], -0.4, 0.4, -1.0, 1.0)
# Linear velocity on z axis
#cartVelocity = normalizeToRange(self.robot.getVelocity()[2], -0.2, 0.2, -1.0, 1.0, clip=True)
# Angular velocity x of endpoint
#endPointVelocity = normalizeToRange(self.poleEndpoint.getVelocity()[3], -1.5, 1.5, -1.0, 1.0, clip=True)
self.messageReceived = self.handle_receiver()
#if self.messageReceived is not None:
# poleAngle = normalizeToRange(float(self.messageReceived[0]), -0.23, 0.23, -1.0, 1.0, clip=True)
#else:
# # Method is called before self.messageReceived is initialized
# poleAngle = 0.0
if self.messageReceived is not None:
message = self.messageReceived
message = [float(i) for i in message]
#print("message received", message)
self.store_message(message)
return message
else:
return [0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0]
def is_topple(self, message):
roll, pitch, yaw = message[0], message[1], message[2]
cri = abs(roll) + abs(pitch)
if abs(cri) > 2.1:
return True
def is_leg_raised(self, hipy):
for hip in hipy:
if hip < 0.45:
return True
return False
def get_reward(self, action=None):
# TODO: change this to match our robot
# -10 for topple
# abs(pos, orig) as reward ?
if self.messageReceived is not None:
message = self.messageReceived
message = [float(i) for i in message]
roll, pitch, yaw = message[0], message[1], message[2]
x, h, y = message[27], message[28], message[29]
[hipx_a_pos, hipx_b_pos, hipx_c_pos, hipx_d_pos] = [message[3], message[4], message[5], message[6]]
[hipy_a_pos, hipy_b_pos, hipy_c_pos, hipy_d_pos] = [message[11], message[12], message[13], message[14]]
hipx_pos = [hipx_a_pos, hipx_b_pos, hipx_c_pos, hipx_d_pos]
hipy_pos = [hipy_a_pos, hipy_b_pos, hipy_c_pos, hipy_d_pos]
leg_raised = np.argmax(hipy_pos)
is_leg_raised = self.is_leg_raised(hipy_pos)
if self.last_leg_raised == leg_raised:
self.last_leg_raised_count += 1
else:
self.last_leg_raised = leg_raised
self.last_leg_raised_count = 0
posture = hipy_a_pos + hipy_b_pos + hipy_c_pos + hipy_d_pos
posture = 4 - posture + h * 10
movement = [self.last_hipx_pos[i] - hipx_pos[i] for i in range(len(self.last_hipx_pos))]
movement = [abs(i) for i in movement]
movement = sum(movement)
posture += movement
if is_leg_raised:
posture += 1
else:
posture = 0
if self.state == 0 or self.state == 2:
cri = abs(roll) + abs(pitch)
#if abs(h - self.last_h) < MOVE_THRES:
# self.last_h_count += 1
#else:
# self.last_h = h
# self.last_h_count = 0
#cri = abs(roll) + abs(pitch)
#if abs(self.last_cri - cri) < MOVE_THRES:
# self.last_cri_count += 1
#else:
# self.last_cri_count = 0
# self.last_cri = cri
return 0.25 - cri
#if self.last_cri_count > STATIONARY_THRES / 2:
# return -10
#return 0.15 - cri
elif self.state == 1:
#if self.stationary_count > STATIONARY_THRES / 2:
# return -1
#if self.last_leg_raised_count > self.last_leg_raised_THRES:
# return -1
if self.messageReceived is not None:
# if abs(cri) > 2.1:
# return -self.stepPerEpisode // 2
if self.is_topple(message):
return -1000000
return x - self.last_x
#if math.floor(x) > self.last_big_x:
# self.last_big_x = math.floor(x)
# return 100 * self.last_big_x + posture * 100
#if x - self.max_x < MOVE_THRES:
# self.stationary_count += 1
#else:
# self.stationary_count = 0
# self.max_x = x
# return 1000
#if self.stationary_count > STATIONARY_THRES / 2:
# return -1
#return 0
print("no message received in state 1")
return 0
elif self.state == 3:
if self.messageReceived is not None:
message = self.messageReceived
message = [float(i) for i in message]
roll, pitch, yaw = message[0], message[1], message[2]
if not yaw < self.last_yaw and abs(yaw - self.last_yaw) < MOVE_THRES:
self.last_yaw_count += 1
else:
self.last_yaw = yaw
self.last_h_count = 0
return 0.5 - yaw
else:
return -100
print("no message received")
return -1000 / self.stepPerEpisode
# 0 is not done, 1 is done, 2 is we are not waiting
def is_done(self):
if self.messageReceived is not None:
message = self.messageReceived
message = [float(i) for i in message]
if self.is_topple(message):
self.state = 4
return 2
else:
return 0
if self.state == 0 or self.state == 2:
if self.messageReceived is not None:
message = self.messageReceived
message = [float(i) for i in message]
roll, pitch, yaw = message[0], message[1], message[2]
x, h, y = message[27], message[28], message[29]
#print(y)
#print("reward", (abs(roll) + abs(pitch) - self.abs_last) * 10)
cri = abs(roll) + abs(pitch)
if abs(cri) < 0.2:
return 1
if self.last_h_count > STATIONARY_THRES or self.last_cri_count > STATIONARY_THRES:
#return 2
return 0
#return False
return 0
elif self.state == 1:
if self.messageReceived is not None:
message = self.messageReceived
message = [float(i) for i in message]
roll, pitch, yaw = message[0], message[1], message[2]
x, h, y = message[27], message[28], message[29]
if self.stationary_count > STATIONARY_THRES:
#return 2
return 0
if x - self.last_x > 0.001:
self.last_x = x
return 1
return 0
elif self.state == 3:
if self.messageReceived is not None:
message = self.messageReceived
message = [float(i) for i in message]
roll, pitch, yaw = message[0], message[1], message[2]
if yaw < 0.2:
return 1
if self.last_yaw_count > STATIONARY_THRES:
# return 2
return 0
return 0
def solved(self):
#if len(self.episodeScoreList) > 100: # Over 100 trials thus far
# if np.mean(self.episodeScoreList[-100:]) > 1000.0: # Last 100 episodes' scores average value
# return True
return False
def reset(self):
#print("reset called")
self.respawnRobot()
self.supervisor.simulationResetPhysics() # Reset the simulation physics to start over
self.messageReceived = None
self.last_x = -0.5
self.max_x = 0
self.stationary_count = 0
self.step_count = 0
self.done = False
self.state = 0
self.last_hipx_pos = [0, 0, 0, 0]
self.last_leg_raised = 0
self.last_leg_raised_count = 0
self.last_leg_raised_THRES = 30
self.last_cri = 0
self.last_cri_count = 0
return [0.0 for _ in range(self.observationSpace)]
def update_state(self):
self.state = (self.state + 1 ) % 4
self.stationary_count = 0
print("state is " + str(self.state))
def get_info(self):
return None
def store_message(self, message):
roll, pitch, yaw, \
hipx_a_pos, hipx_b_pos, hipx_c_pos, hipx_d_pos, \
hipx_a_vel, hipx_b_vel, hipx_c_vel, hipx_d_vel, \
hipy_a_pos, hipy_b_pos, hipy_c_pos, hipy_d_pos, \
hipy_a_vel, hipy_b_vel, hipy_c_vel, hipy_d_vel, \
leg_a_pos, leg_b_pos, leg_c_pos, leg_d_pos, \
leg_a_vel, leg_b_vel, leg_c_vel, leg_d_vel, \
x, h, y = message
if LOG:
with open("data.txt", mode="a") as csv_file:
csv_writer = csv.writer(csv_file, delimiter=',')
csv_writer.writerow(message)
supervisor = ddpg_controller()
agent = PPOAgent(supervisor.observationSpace, supervisor.actionSpace)
agent.load("")
solved = False
def chooseWeight(state):
if state == 0 or state == 2:
return ""
elif state == 1:
return "reset"
else:
return "turn"
# Run outer loop until the episodes limit is reached or the task is solved
while not solved and supervisor.episodeCount < supervisor.episodeLimit:
observation = supervisor.reset() # Reset robot and get starting observation
supervisor.episodeScore = 0
for step in range(supervisor.stepPerEpisode):
agent.load(chooseWeight(supervisor.state))
#print(step)
# In training mode the agent samples from the probability distribution, naturally implementing exploration
selectedAction, actionProb = agent.work(observation, type_="selectAction")
# Step the supervisor to get the current selectedAction's reward, the new observation and whether we reached
# the done condition
newObservation, reward, done, info = supervisor.step([selectedAction])
print(supervisor.state, reward)
# Save the current state transition in agent's memory
trans = Transition(observation, selectedAction, actionProb, reward, newObservation)
agent.storeTransition(trans)
if done != 0:
if supervisor.state == 4:
print("topple")
break
if done == 2:
supervisor.episodeScoreList.append(supervisor.episodeScore)
agent.trainStep(batchSize=step)
agent.save(chooseWeight(supervisor.state))
break
# Save the episode's score
supervisor.episodeScoreList.append(supervisor.episodeScore)
agent.trainStep(batchSize=step)
#solved = supervisor.solved() # Check whether the task if solved
agent.save(chooseWeight(supervisor.state))
supervisor.update_state()
#break
supervisor.episodeScore += reward # Accumulate episode reward
observation = newObservation # observation for next step is current step's newObservation
print("Episode #", supervisor.episodeCount, "score:", supervisor.episodeScore)
supervisor.episodeCount += 1 # Increment episode counter
if not solved:
print("Task is not solved, deploying agent for testing")
elif solved:
print("Task is solved, deploying agent for testing...")
observation = supervisor.reset()
while True:
selectedAction, actionProb = agent.work(observation, type_="selectActionMax")
observation, _, _, _ = supervisor.step([selectedAction])<file_sep># Inputs: 1) position of four motors 2) velocity of four motors 3) IMU
# Outputs: 4)
# You may need to import some classes of the controller module. Ex:
# from controller import Robot, Motor, DistanceSensor
import math
import random
from controller import Robot
from deepbots.robots.controllers.robot_emitter_receiver_csv import RobotEmitterReceiverCSV
import ast # for string to list
class loggingRobot(RobotEmitterReceiverCSV):
def __init__(self):
super().__init__()
self.IMU = self.robot.getInertialUnit("inertial unit")
self.IMU.enable(self.get_timestep())
self.GPS = self.robot.getGPS("GPS")
self.GPS.enable(self.get_timestep())
self.init_motors()
#self.random_init()
def create_message(self):
roll, pitch, yaw = self.IMU.getRollPitchYaw()
x, h, y = self.GPS.getValues()
hipx_a_pos = self.hipx_a.getPositionSensor().getValue()
hipx_b_pos = self.hipx_b.getPositionSensor().getValue()
hipx_c_pos = self.hipx_c.getPositionSensor().getValue()
hipx_d_pos = self.hipx_d.getPositionSensor().getValue()
hipx_a_vel = self.hipx_a.getVelocity()
hipx_b_vel = self.hipx_b.getVelocity()
hipx_c_vel = self.hipx_c.getVelocity()
hipx_d_vel = self.hipx_d.getVelocity()
hipy_a_pos = self.hipy_a.getPositionSensor().getValue()
hipy_b_pos = self.hipy_b.getPositionSensor().getValue()
hipy_c_pos = self.hipy_c.getPositionSensor().getValue()
hipy_d_pos = self.hipy_d.getPositionSensor().getValue()
hipy_a_vel = self.hipy_a.getVelocity()
hipy_b_vel = self.hipy_b.getVelocity()
hipy_c_vel = self.hipy_c.getVelocity()
hipy_d_vel = self.hipy_d.getVelocity()
leg_a_pos = self.leg_a.getPositionSensor().getValue()
leg_b_pos = self.leg_b.getPositionSensor().getValue()
leg_c_pos = self.leg_c.getPositionSensor().getValue()
leg_d_pos = self.leg_d.getPositionSensor().getValue()
leg_a_vel = self.leg_a.getVelocity()
leg_b_vel = self.leg_b.getVelocity()
leg_c_vel = self.leg_c.getVelocity()
leg_d_vel = self.leg_d.getVelocity()
message_list = [roll, pitch, yaw, # 3
hipx_a_pos, hipx_b_pos, hipx_c_pos, hipx_d_pos, # 7
hipx_a_vel, hipx_b_vel, hipx_c_vel, hipx_d_vel, # 11
hipy_a_pos, hipy_b_pos, hipy_c_pos, hipy_d_pos, # 15
hipy_a_vel, hipy_b_vel, hipy_c_vel, hipy_d_vel, # 19
leg_a_pos, leg_b_pos, leg_c_pos, leg_d_pos, # 23
leg_a_vel, leg_b_vel, leg_c_vel, leg_d_vel, # 27
x, h, y] # 30
# print(ast.literal_eval(str(message_list))[0])
# print("message:", str(message_list))
return message_list
def use_message_data(self, message):
#motors = [self.hipx_a, self.hipx_b, self.hipx_c, self.hipx_d]
#print ("actor got this:", message)
#action = math.floor(float(message[0])) # Convert the string message into an action integer
#motor_idx = action // 3
#action = action % 3
#motor = motors[motor_idx]
pass
def init_motors(self):
self.hipx_a = self.robot.getMotor("hipx_a")
self.hipx_a.setPosition(0)
#self.hipx_a.setPosition(float("inf"))
#self.hipx_a.setVelocity(0)
self.hipx_a.getPositionSensor().enable(self.get_timestep())
self.hipx_b = self.robot.getMotor("hipx_b")
self.hipx_b.setPosition(0)
#self.hipx_b.setPosition(float("inf"))
#self.hipx_b.setVelocity(0)
self.hipx_b.getPositionSensor().enable(self.get_timestep())
self.hipx_c = self.robot.getMotor("hipx_c")
self.hipx_c.setPosition(0)
#self.hipx_c.setPosition(float("inf"))
#self.hipx_c.setVelocity(0)
self.hipx_c.getPositionSensor().enable(self.get_timestep())
self.hipx_d = self.robot.getMotor("hipx_d")
self.hipx_d.setPosition(0)
#self.hipx_d.setPosition(float("inf"))
#self.hipx_d.setVelocity(0)
self.hipx_d.getPositionSensor().enable(self.get_timestep())
self.hipy_a = self.robot.getMotor("hipy_a")
self.hipy_a.setPosition(self.r())
self.hipy_a.getPositionSensor().enable(self.get_timestep())
self.hipy_b = self.robot.getMotor("hipy_b")
self.hipy_b.setPosition(self.r())
self.hipy_b.getPositionSensor().enable(self.get_timestep())
self.hipy_c = self.robot.getMotor("hipy_c")
self.hipy_c.setPosition(self.r())
self.hipy_c.getPositionSensor().enable(self.get_timestep())
self.hipy_d = self.robot.getMotor("hipy_d")
self.hipy_d.setPosition(self.r())
self.hipy_d.getPositionSensor().enable(self.get_timestep())
self.leg_a = self.robot.getMotor("leg_a")
self.leg_a.setPosition(0)
#self.leg_a.setPosition(float("inf"))
#self.leg_a.setVelocity(0)
self.leg_a.getPositionSensor().enable(self.get_timestep())
self.leg_b = self.robot.getMotor("leg_b")
self.leg_b.setPosition(0)
#self.leg_b.setPosition(float("inf"))
#self.leg_b.setVelocity(0)
self.leg_b.getPositionSensor().enable(self.get_timestep())
self.leg_c = self.robot.getMotor("leg_c")
self.leg_c.setPosition(0)
#self.leg_c.setPosition(float("inf"))
#self.leg_c.setVelocity(0)
self.leg_c.getPositionSensor().enable(self.get_timestep())
self.leg_d = self.robot.getMotor("leg_d")
self.leg_d.setPosition(0)
#self.leg_d.setPosition(float("inf"))
#self.leg_d.setVelocity(0)
self.leg_d.getPositionSensor().enable(self.get_timestep())
def r(self):
return random.random()
def random_init(self):
motors = [self.hipy_a, self.hipy_b, self.hipy_c, self.hipy_d]
log = []
for motor in motors:
r = 1 #if random.random() > 0.5 else -1
r *= random.random() * 10
log.append(r)
motor.setPosition(r)
print(log)
# Create the robot controller object and run it
robot_controller = loggingRobot()
robot_controller.run() # Run method is implemented by the framework, just need to call it
# create the Robot instance.
robot = Robot()
# get the time step of the current world.
timestep = int(robot.getBasicTimeStep())
# You should insert a getDevice-like function in order to get the
# instance of a device of the robot. Something like:
# motor = robot.getMotor('motorname')
# ds = robot.getDistanceSensor('dsname')
# ds.enable(timestep)
# Main loop:
# - perform simulation steps until Webots is stopping the controller
while robot.step(timestep) != -1:
# Read the sensors:
# Enter here functions to read sensor data, like:
# val = ds.getValue()
# Process sensor data here.
# Enter here functions to send actuator commands, like:
# motor.setPosition(10.0)
pass
# Enter here exit cleanup code.
| 4ed75318be87a4e8d6db6f40a39fd2b102ffed33 | [
"Markdown",
"Python"
] | 10 | Python | vadl-2021/webots_simulation | 0fcc2c36f6b62e90bef3894da42c908051667be8 | 5f2cecda7bdf576b06286dafe4840626b93dd8df |
refs/heads/master | <repo_name>jonovotny/VruiScalable<file_sep>/3DVisualizerRawMRI
#!/bin/bash
./install_linux/bin/3DVisualizer -class ImageStack /gpfs/data/dhl/gfx/VisualizationData/Volumes/Medical/TTTS/2016-04-05/RawMRI/stack.stack
<file_sep>/timing_scripts/tmp/MeshViewerTiny
#!/bin/bash
../../install_linux/bin/MeshViewer /tmp/model-tmp/tiny.obj
<file_sep>/MeshViewerWall
#!/bin/bash
./install_linux/bin/MeshViewer /gpfs/data/dhl/gfx/VisualizationData/Misc/wall.obj
<file_sep>/import/vrui/Makefile
######################## import/vrui/Makefile ################################
#
SHELL=/bin/bash
.PHONY: download all
all: download
rm $G/import/vrui/src/Share/Vrui.cfg
cp $G/import/vrui/Vrui.cfg $G/import/vrui/src/Share
rm $G/import/vrui/src/Share/VRDevices.cfg
cp $G/import/vrui/VRDevices.cfg $G/import/vrui/src/Share
rm $G/import/vrui/src/GL/GLWindow.cpp
cp $G/import/vrui/GLWindow.cpp $G/import/vrui/src/GL/
cd $G/import/vrui/src; make
cd $G/import/vrui/src; make install
# Only download the whole thing if it's older than half a day.
download:
if [ ! -d src ] || [ $$(( $(shell date +'%s') - \
$(shell stat -c '%Y' src) )) -gt 43200 ]; then \
rm -rf src ; \
wget -O src.tar.gz http://www.idav.ucdavis.edu/~okreylos/ResDev/Vrui/Vrui-3.1-002.tar.gz ; \
mkdir src && tar xzvf src.tar.gz -C src --strip-components 1 ; \
rm src.tar.gz ; \
sed -i '/INSTALLDIR := $$(HOME)/c\INSTALLDIR := $(G)\/install_linux' $G/import/vrui/src/makefile ; \
fi
#
#################### end import/vrui/Makefile ###############################
<file_sep>/build
#!/bin/bash
cd $G/import/vrui
./build
cd $G/project/meshviewer
make -j16 all
make install
cd $G/import/vrui/src/ExamplePrograms
make
make install
cd $G/import/3dvisualizer
make all
<file_sep>/VRDeviceDaemon
#!/bin/bash
./install_linux/bin/VRDeviceDaemon "$@"
<file_sep>/MeshViewer270
#!/bin/bash
./install_linux/bin/MeshViewer /gpfs/data/dhl/gfx/VisualizationData/Misc/coordcross2.obj -vislet SceneGraphViewer /gpfs/data/dhl/gfx/VisualizationData/Elements/VirtualWalls/FOR270.vrml
<file_sep>/timing_scripts/gpfs/MeshViewerBig
#!/bin/bash
../../install_linux/bin/MeshViewer /gpfs/data/dhl/gfx/VisualizationData/Surfaces/Test/big.obj
<file_sep>/MeshViewerBodyLung
#!/bin/bash
./install_linux/bin/MeshViewer /gpfs/data/dhl/gfx/VisualizationData/Surfaces/Medical/Body/*.obj
<file_sep>/userStudyCAVE/Platynus270Mono
#!/bin/bash
rm ../install_linux/etc/Vrui-3.1/Vrui.cfg
cp ../install_linux/etc/Vrui-3.1/Vrui_Mono.cfg ../install_linux/etc/Vrui-3.1/Vrui.cfg
../install_linux/bin/MeshViewer ../../Objects/RotatedPlatynusTrachea/*.obj -vislet SceneGraphViewer ../../Walls/FOR270.vrml
<file_sep>/MeshViewer
#!/bin/bash
./install_linux/bin/MeshViewer "$@" /gpfs/data/dhl/gfx/VisualizationData/Misc/coordcross2.obj
<file_sep>/MeshViewerHeart
#!/bin/bash
./install_linux/bin/MeshViewer /gpfs/data/dhl/gfx/VisualizationData/Surfaces/Medical/Heart/*.obj
<file_sep>/README.md
# VruiScalable
To Build
--------
* Open up a shell on login001 or login002
* Define $G as the root of this cloned repository
* Load cave, cave-utils/yurt, centos-libs/6.7, cmake/3.2.2, gcc, nvidia-driver, and vrpn modules
* Run ./build
To Run
------
* Open two shells on cave001
* In one, run ./VRDeviceDaemon script
* In the other, run ./MeshViewer, ./3DVisualizer, or any other application script
Files Modified for Scalable Integration
---------------------------------------
* import/vrui/src/BuildRoot/Packages.System
* import/vrui/src/BuildRoot/Packages.Vrui
* import/vrui/src/Vrui/Scalable.cpp
* import/vrui/src/Vrui/Scalable.h
* import/vrui/src/Vrui/VRWindow.cpp
* import/vrui/src/Vrui/VRWindow.h
<file_sep>/userStudyYURT/Platynus90Stereo
#!/bin/bash
rm ../install_linux/etc/Vrui-3.1/Vrui.cfg
cp ../install_linux/etc/Vrui-3.1/Vrui_Stereo.cfg ../install_linux/etc/Vrui-3.1/Vrui.cfg
../install_linux/bin/MeshViewer /gpfs/data/dhl/gfx/VisualizationData/Surfaces/Biological/PlatynusTrachea/*.obj -vislet SceneGraphViewer /gpfs/data/dhl/gfx/VisualizationData/Elements/VirtualWalls/FOR90.vrml
<file_sep>/MeshViewerGut
#!/bin/bash
./install_linux/bin/MeshViewer /gpfs/data/dhl/gfx/VisualizationData/Surfaces/Biological/Gut/*.obj
<file_sep>/import/3dvisualizer/Makefile
######################## import/3dvisualizer/Makefile ########################
#
SHELL=/bin/bash
.PHONY: all
all:
sed -i '/VRUI_MAKEDIR := $$(HOME)/c\VRUI_MAKEDIR = $(G)\/import\/vrui\/src\/BuildRoot' $G/import/3dvisualizer/src/makefile ; \
sed -i '/INSTALLDIR := $$(shell pwd)/c\INSTALLDIR = $(G)\/install_linux' $G/import/3dvisualizer/src/makefile ; \
cd $G/import/3dvisualizer/src; make
cd $G/import/3dvisualizer/src; make install
#
#################### end import/3dvisualizer/Makefile #######################
<file_sep>/import/vrui/GLWindow.cpp
/***********************************************************************
GLWindow - Class to encapsulate details of the underlying window system
implementation from an application wishing to use OpenGL windows.
Copyright (c) 2001-2013 <NAME>
This file is part of the OpenGL/GLX Support Library (GLXSupport).
The OpenGL/GLX Support Library is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
The OpenGL/GLX Support Library is distributed in the hope that it will
be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License along
with the OpenGL/GLX Support Library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
***********************************************************************/
#include <GL/GLWindow.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <X11/cursorfont.h>
#include <Misc/SizedTypes.h>
#include <Misc/ThrowStdErr.h>
#include <Misc/CallbackData.h>
/**************************
Methods of class GLWindow:
**************************/
void GLWindow::initWindow(const char* windowName,bool decorate)
{
/* Check if the screen index is valid: */
if(screen<0||screen>=ScreenCount(context->getDisplay()))
Misc::throwStdErr("GLWindow: Screen %d does not exist on display %s",screen,DisplayString(context->getDisplay()));
/* Get a handle to the root window: */
root=RootWindow(context->getDisplay(),screen);
/* Create an X colormap (visual might not be default): */
colorMap=XCreateColormap(context->getDisplay(),root,context->getVisual(),AllocNone);
/* Create an X window with the selected visual: */
XSetWindowAttributes swa;
swa.colormap=colorMap;
swa.border_pixel=0;
if(fullscreen) // Create a fullscreen window
{
windowPos.origin[0]=0;
windowPos.origin[1]=0;
windowPos.size[0]=DisplayWidth(context->getDisplay(),screen);
windowPos.size[1]=DisplayHeight(context->getDisplay(),screen);
decorate=false;
}
swa.override_redirect=False;
swa.event_mask=PointerMotionMask|ButtonPressMask|ButtonReleaseMask|KeyPressMask|KeyReleaseMask|ExposureMask|StructureNotifyMask;
unsigned long attributeMask=CWBorderPixel|CWColormap|CWOverrideRedirect|CWEventMask;
window=XCreateWindow(context->getDisplay(),root,
windowPos.origin[0],windowPos.origin[1],windowPos.size[0],windowPos.size[1],
0,context->getDepth(),InputOutput,context->getVisual(),attributeMask,&swa);
XMoveWindow(context->getDisplay(), window, 0, 0);
XSetStandardProperties(context->getDisplay(),window,windowName,windowName,None,0,0,0);
if(!decorate)
{
/*******************************************************************
Ask the window manager not to decorate this window:
*******************************************************************/
/* Create and fill in window manager hint structure inherited from Motif: */
struct MotifHints // Structure to pass hints to window managers
{
/* Elements: */
public:
Misc::UInt32 flags;
Misc::UInt32 functions;
Misc::UInt32 decorations;
Misc::SInt32 inputMode;
Misc::UInt32 status;
} hints;
hints.flags=2U; // Only change decorations bit
hints.functions=0U;
hints.decorations=0U;
hints.inputMode=0;
hints.status=0U;
/* Get the X atom to set hint properties: */
Atom hintProperty=XInternAtom(context->getDisplay(),"_MOTIF_WM_HINTS",True);
if(hintProperty!=None)
{
/* Set the window manager hint property: */
XChangeProperty(context->getDisplay(),window,hintProperty,hintProperty,32,PropModeReplace,reinterpret_cast<unsigned char*>(&hints),5);
}
}
/* Initiate window manager communication: */
wmProtocolsAtom=XInternAtom(context->getDisplay(),"WM_PROTOCOLS",False);
wmDeleteWindowAtom=XInternAtom(context->getDisplay(),"WM_DELETE_WINDOW",False);
XSetWMProtocols(context->getDisplay(),window,&wmDeleteWindowAtom,1);
/* Display the window on the screen: */
XMapWindow(context->getDisplay(),window);
/*********************************************************************
Since modern window managers ignore window positions when opening
windows, we now need to move the window to its requested position.
Fix suggested by <NAME>.
*********************************************************************/
if(decorate)
{
/* Query the window tree to get the window's parent (the one containing the decorations): */
Window win_root,win_parent;
Window* win_children;
unsigned int win_numChildren;
XQueryTree(context->getDisplay(),window,&win_root,&win_parent,&win_children,&win_numChildren);
/* Query the window's and the parent's geometry to calculate the window's offset inside its parent: */
int win_parentX,win_parentY,win_x,win_y;
unsigned int win_width,win_height,win_borderWidth,win_depth;
XGetGeometry(context->getDisplay(),win_parent,&win_root,&win_parentX,&win_parentY,&win_width,&win_height,&win_borderWidth,&win_depth);
XGetGeometry(context->getDisplay(),window,&win_root,&win_x,&win_y,&win_width,&win_height,&win_borderWidth,&win_depth);
/* Move the window's interior's top-left corner to the requested position: */
XMoveWindow(context->getDisplay(),window,windowPos.origin[0]-(win_x-win_parentX),windowPos.origin[1]-(win_y-win_parentY));
}
else
{
/* Move the window's top-left corner to the requested position: */
XMoveWindow(context->getDisplay(),window,windowPos.origin[0],windowPos.origin[1]);
}
if(fullscreen)
{
/* Grab pointer and keyboard: */
XGrabPointer(context->getDisplay(),window,True,0,GrabModeAsync,GrabModeAsync,None,None,CurrentTime);
XGrabKeyboard(context->getDisplay(),window,True,GrabModeAsync,GrabModeAsync,CurrentTime);
}
/* Gobble up the initial rush of X events regarding window creation: */
#if 1
XEvent event;
while(XCheckWindowEvent(context->getDisplay(),window,ExposureMask|StructureNotifyMask,&event))
{
switch(event.type)
{
case Expose:
/* Put the event back into the queue to let caller handle it: */
XPutBackEvent(context->getDisplay(),&event);
goto doneWithEvents;
break;
case ConfigureNotify:
/* Retrieve the final window size: */
windowPos.origin[0]=event.xconfigure.x;
windowPos.origin[1]=event.xconfigure.y;
windowPos.size[0]=event.xconfigure.width;
windowPos.size[1]=event.xconfigure.height;
break;
}
}
doneWithEvents:
;
#else
while(true)
{
/* Look at the next event: */
XEvent event;
XPeekEvent(context->getDisplay(),&event);
if(event.type==Expose)
break; // Leave this event for the caller to process
/* Process the next event: */
XNextEvent(context->getDisplay(),&event);
switch(event.type)
{
case ConfigureNotify:
/* Retrieve the final window position and size: */
windowPos.origin[0]=event.xconfigure.x;
windowPos.origin[1]=event.xconfigure.y;
windowPos.size[0]=event.xconfigure.width;
windowPos.size[1]=event.xconfigure.height;
break;
}
}
#endif
/* Initialize the OpenGL context: */
context->init(window);
}
GLWindow::GLWindow(GLContext* sContext,int sScreen,const char* windowName,const GLWindow::WindowPos& sWindowPos,bool decorate)
:context(sContext),
screen(sScreen),
windowPos(sWindowPos),fullscreen(windowPos.size[0]==0||windowPos.size[1]==0)
{
/* Call common part of window initialization routine: */
initWindow(windowName,decorate);
}
GLWindow::GLWindow(const char* displayName,const char* windowName,const GLWindow::WindowPos& sWindowPos,bool decorate,int* visualProperties)
:context(new GLContext(displayName,visualProperties)),
screen(context->getDefaultScreen()),
windowPos(sWindowPos),fullscreen(windowPos.size[0]==0||windowPos.size[1]==0)
{
/* Call common part of window initialization routine: */
initWindow(windowName,decorate);
}
GLWindow::GLWindow(const char* windowName,const GLWindow::WindowPos& sWindowPos,bool decorate,int* visualProperties)
:context(new GLContext(0,visualProperties)),
screen(context->getDefaultScreen()),
windowPos(sWindowPos),fullscreen(windowPos.size[0]==0||windowPos.size[1]==0)
{
/* Call common part of window initialization routine: */
initWindow(windowName,decorate);
}
GLWindow::GLWindow(GLWindow* source,int sScreen,const char* windowName,const GLWindow::WindowPos& sWindowPos,bool decorate)
:context(source->context),
screen(sScreen),
windowPos(sWindowPos),fullscreen(windowPos.size[0]==0||windowPos.size[1]==0)
{
/* Call common part of window initialization routine: */
initWindow(windowName,decorate);
}
GLWindow::GLWindow(GLWindow* source,const char* windowName,const GLWindow::WindowPos& sWindowPos,bool decorate)
:context(source->context),
screen(source->screen),
windowPos(sWindowPos),fullscreen(windowPos.size[0]==0||windowPos.size[1]==0)
{
/* Call common part of window initialization routine: */
initWindow(windowName,decorate);
}
GLWindow::~GLWindow(void)
{
if(fullscreen)
{
/* Release the pointer and keyboard grab: */
XUngrabPointer(context->getDisplay(),CurrentTime);
XUngrabKeyboard(context->getDisplay(),CurrentTime);
}
/* Close the window: */
XUnmapWindow(context->getDisplay(),window);
context->release();
XDestroyWindow(context->getDisplay(),window);
XFreeColormap(context->getDisplay(),colorMap);
/* Context pointer's destructor will detach from GL context and possible destroy it */
}
GLWindow::WindowPos GLWindow::getRootWindowPos(void) const
{
return WindowPos(DisplayWidth(context->getDisplay(),screen),DisplayHeight(context->getDisplay(),screen));
}
double GLWindow::getScreenWidthMM(void) const
{
return double(DisplayWidthMM(context->getDisplay(),screen));
}
double GLWindow::getScreenHeightMM(void) const
{
return double(DisplayHeightMM(context->getDisplay(),screen));
}
void GLWindow::makeFullscreen(void)
{
/*********************************************************************
"Sane" version of fullscreen switch: Use the window manager protocol
when supported; otherwise, fall back to hacky method.
*********************************************************************/
/* Get relevant window manager protocol atoms: */
Atom netwmStateAtom=XInternAtom(context->getDisplay(),"_NET_WM_STATE",True);
Atom netwmStateFullscreenAtom=XInternAtom(context->getDisplay(),"_NET_WM_STATE_FULLSCREEN",True);
if(netwmStateAtom!=None&&netwmStateFullscreenAtom!=None)
{
/* Ask the window manager to make this window fullscreen: */
XEvent fullscreenEvent;
memset(&fullscreenEvent,0,sizeof(XEvent));
fullscreenEvent.xclient.type=ClientMessage;
fullscreenEvent.xclient.serial=0;
fullscreenEvent.xclient.send_event=True;
fullscreenEvent.xclient.display=context->getDisplay();
fullscreenEvent.xclient.window=window;
fullscreenEvent.xclient.message_type=netwmStateAtom;
fullscreenEvent.xclient.format=32;
fullscreenEvent.xclient.data.l[0]=1; // Should be _NET_WM_STATE_ADD, but that doesn't work for some reason
fullscreenEvent.xclient.data.l[1]=netwmStateFullscreenAtom;
fullscreenEvent.xclient.data.l[2]=0;
XSendEvent(context->getDisplay(),RootWindow(context->getDisplay(),screen),False,SubstructureRedirectMask|SubstructureNotifyMask,&fullscreenEvent);
XFlush(context->getDisplay());
}
else
{
/*******************************************************************
Use hacky method of adjusting window size just beyond the root
window. Only method available if there is no window manager, like on
dedicated cluster rendering nodes.
*******************************************************************/
/* Query the window's geometry to calculate its offset inside its parent window (the window manager decoration): */
Window win_root;
int win_x,win_y;
unsigned int win_width,win_height,win_borderWidth,win_depth;
XGetGeometry(context->getDisplay(),window,&win_root,&win_x,&win_y,&win_width,&win_height,&win_borderWidth,&win_depth);
/* Set the window's position and size such that the window manager decoration falls outside the root window: */
XMoveResizeWindow(context->getDisplay(),window,-win_x,-win_y,DisplayWidth(context->getDisplay(),screen),DisplayHeight(context->getDisplay(),screen));
}
/* Raise the window to the top of the stacking hierarchy: */
XRaiseWindow(context->getDisplay(),window);
}
void GLWindow::disableMouseEvents(void)
{
/* Get the window's current event mask: */
XWindowAttributes wa;
XGetWindowAttributes(context->getDisplay(),window,&wa);
/* Disable mouse-related events: */
XSetWindowAttributes swa;
swa.event_mask=wa.all_event_masks&~(PointerMotionMask|EnterWindowMask|LeaveWindowMask|ButtonPressMask|ButtonReleaseMask);
XChangeWindowAttributes(context->getDisplay(),window,CWEventMask,&swa);
}
void GLWindow::hideCursor(void)
{
/* Why is it so goshdarn complicated to just hide the friggin' cursor? */
static char emptyCursorBits[]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
Pixmap emptyCursorPixmap=XCreatePixmapFromBitmapData(context->getDisplay(),window,emptyCursorBits,16,16,1,0,1);
XColor black,white; // Actually, both are dummy colors
Cursor emptyCursor=XCreatePixmapCursor(context->getDisplay(),emptyCursorPixmap,emptyCursorPixmap,&black,&white,0,0);
XDefineCursor(context->getDisplay(),window,emptyCursor);
XFreeCursor(context->getDisplay(),emptyCursor);
XFreePixmap(context->getDisplay(),emptyCursorPixmap);
}
void GLWindow::showCursor(void)
{
XUndefineCursor(context->getDisplay(),window);
}
bool GLWindow::grabPointer(void)
{
/* Do nothing if the window is in fullscreen mode: */
if(fullscreen)
return true;
bool result;
/* Try grabbing the pointer: */
result=XGrabPointer(context->getDisplay(),window,False,
ButtonPressMask|ButtonReleaseMask|PointerMotionMask,
GrabModeAsync,GrabModeAsync,None,None,CurrentTime)==GrabSuccess;
if(result)
{
/* Try grabbing the keyboard as well: */
result=XGrabKeyboard(context->getDisplay(),window,False,GrabModeAsync,GrabModeAsync,CurrentTime)==GrabSuccess;
if(!result)
{
/* Release the pointer again: */
XUngrabPointer(context->getDisplay(),CurrentTime);
}
}
return result;
}
void GLWindow::releasePointer(void)
{
/* Do nothing if the window is in fullscreen mode: */
if(fullscreen)
return;
XUngrabPointer(context->getDisplay(),CurrentTime);
XUngrabKeyboard(context->getDisplay(),CurrentTime);
}
void GLWindow::setCursorPos(int newCursorX,int newCursorY)
{
XWarpPointer(context->getDisplay(),None,window,0,0,0,0,newCursorX,newCursorY);
}
void GLWindow::redraw(void)
{
/* Send an expose X event for the entire area to this window: */
XEvent event;
memset(&event,0,sizeof(XEvent));
event.type=Expose;
event.xexpose.display=context->getDisplay();
event.xexpose.window=window;
event.xexpose.x=0;
event.xexpose.y=0;
event.xexpose.width=windowPos.size[0];
event.xexpose.height=windowPos.size[1];
event.xexpose.count=0;
XSendEvent(context->getDisplay(),window,False,0x0,&event);
XFlush(context->getDisplay());
}
void GLWindow::processEvent(const XEvent& event)
{
switch(event.type)
{
case ConfigureNotify:
{
/* Retrieve the new window size: */
windowPos.size[0]=event.xconfigure.width;
windowPos.size[1]=event.xconfigure.height;
/* Calculate the window's position on the screen: */
Window child;
XTranslateCoordinates(context->getDisplay(),window,root,0,0,&windowPos.origin[0],&windowPos.origin[1],&child);
break;
}
case ClientMessage:
if(event.xclient.message_type==wmProtocolsAtom&&event.xclient.format==32&&(Atom)(event.xclient.data.l[0])==wmDeleteWindowAtom)
{
/* Call the close callbacks: */
Misc::CallbackData cbData;
closeCallbacks.call(&cbData);
}
break;
}
}
<file_sep>/import/vrui/build
#!/bin/bash
#rm $G/import/vrui/src/Share/Vrui.cfg
#cp $G/import/vrui/Vrui.cfg $G/import/vrui/src/Share
#rm $G/import/vrui/src/Share/VRDevices.cfg
#cp $G/import/vrui/VRDevices.cfg $G/import/vrui/src/Share
cd src
make
make install
| a67ac6508ab681437ef2211412b4c0ecf028e4dd | [
"Markdown",
"Makefile",
"C++",
"Shell"
] | 18 | Shell | jonovotny/VruiScalable | 63162b0035383b50d45fb7badffd848e21698690 | 069853c95f35ed63ff49248fba4a98a21d0a3fc1 |
refs/heads/master | <file_sep>package com.example.abhinav.customdialog;
import java.util.ArrayList;
/**
* Created by Abhinav on 8/29/2017.
*/
public class Group {
String mradioName;
ArrayList<String> children;
ArrayList<Boolean> isChecked=new ArrayList<>();
boolean selectable=false;
public Group(String radioName,ArrayList<String> children)
{
this.mradioName=radioName;
this.children=children;
for(int i=0;i<children.size();i++)
{
isChecked.add(false);
}
}
public void setSelectable(boolean selectable)
{
this.selectable=selectable;
}
}
<file_sep>"# CustomDialog"
<file_sep>package com.example.abhinav.customdialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewPropertyAnimator;
import android.view.animation.Animation;
import android.view.animation.LayoutAnimationController;
import android.view.animation.Transformation;
import android.widget.AdapterView;
import android.widget.ExpandableListView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
/**
* Created by Abhinav on 8/29/2017.
*/
public class CustomDialog extends Dialog implements AdapterView.OnItemClickListener, ExpandableListView.OnGroupClickListener {
ExpandableListView mexpandableListView;
private SparseArray<Group> groups=new SparseArray<>();
String genre[]={"HORROR","DRAMA","COMEDY"};
String year[]={"1990-2000","2000-2010","2010-Present"};
MainActivity mainActivity;
Animation a;
public CustomDialog(@NonNull MainActivity context){
super(context);
mainActivity=context;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog);
createData();
mexpandableListView = (ExpandableListView) findViewById(R.id.list_view);
CustomAdapter customAdapter = new CustomAdapter(mainActivity, groups);
mexpandableListView.setAdapter(customAdapter);
final int targtetHeight = mexpandableListView.getMeasuredHeight();
a = new Animation()
{
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
mexpandableListView.getLayoutParams().height = interpolatedTime == 1
? ViewGroup.LayoutParams.WRAP_CONTENT
: (int)(targtetHeight * interpolatedTime);
mexpandableListView.requestLayout();
}
@Override
public boolean willChangeBounds() {
return true;
}
};
a.setDuration((int)(targtetHeight / mexpandableListView.getContext().getResources().getDisplayMetrics().density));
}
public void createData() {
ArrayList<String> x= new ArrayList<String>();
x.addAll(Arrays.asList(genre));
Group group=new Group("GENRE",x);
groups.append(0, group);
x=new ArrayList<>();
x.addAll(Arrays.asList(year));
group=new Group("YEAR",x);
groups.append(1, group);
// groups.append(j, group);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.v("onitemclick","click");
mexpandableListView.expandGroup(position,true);
}
@Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
Log.v("ongroupclick","click");
mexpandableListView.expandGroup(groupPosition,true);
return false;
}
public void expandGroup(final int position){
mexpandableListView.expandGroup(position,true);
}
public void collapseGroup(int position)
{
mexpandableListView.collapseGroup(position);
if(position==0)
{
groups.get(1).setSelectable(false);
}
else if(position==1)
{
groups.get(0).setSelectable(false);
}
}
}
| 172ee5d50b6eef23ed14982d49e07b6907001fd4 | [
"Markdown",
"Java"
] | 3 | Java | abhinavpApostek/CustomDialog | dc9d2af99b47877978cc9dade5cb3362989b04b0 | 4915e1644ab925baf0ab239af8bc2e7909e67141 |
refs/heads/main | <file_sep>#include <ros.h>
#include <ros/time.h>
#include <sensor_msgs/Range.h>
ros::NodeHandle nh;
#define echoPin1 2 // Echo Pin
#define trigPin1 10 // Trigger Pin
#define echoPin2 4 // Echo Pin
#define trigPin2 5 // Trigger Pin
#define echoPin3 6 // Echo Pin
#define trigPin3 7 // Trigger Pin
int maximumRange = 200; // Maximum range needed
int minimumRange = 0; // Minimum range needed
long duration, distance; // Duration used to calculate distance
sensor_msgs::Range range_msg1;
sensor_msgs::Range range_msg2;
sensor_msgs::Range range_msg3;
ros::Publisher pub_range_1( "/ultrasound_1", &range_msg1);
ros::Publisher pub_range_2( "/ultrasound_2", &range_msg2);
ros::Publisher pub_range_3( "/ultrasound_3", &range_msg3);
char frameid_1[] = "/ultrasound_1";
char frameid_2[] = "/ultrasound_2";
char frameid_3[] = "/ultrasound_3";
void setup() {
nh.initNode();
nh.advertise(pub_range_1);
nh.advertise(pub_range_2);
nh.advertise(pub_range_3);
range_msg1.radiation_type = sensor_msgs::Range::ULTRASOUND;
range_msg1.header.frame_id = frameid_1;
range_msg1.field_of_view = 0.1; //fake
range_msg1.min_range = 0.0;
range_msg1.max_range = 60;
range_msg2.radiation_type = sensor_msgs::Range::ULTRASOUND;
range_msg2.header.frame_id = frameid_2;
range_msg2.field_of_view = 0.1; //fake
range_msg2.min_range = 0.0;
range_msg2.max_range = 60;
range_msg3.radiation_type = sensor_msgs::Range::ULTRASOUND;
range_msg3.header.frame_id = frameid_3;
range_msg3.field_of_view = 0.1; //fake
range_msg3.min_range = 0.0;
range_msg3.max_range = 60;
pinMode(trigPin1, OUTPUT);
pinMode(echoPin1, INPUT);
pinMode(trigPin2, OUTPUT);
pinMode(echoPin2, INPUT);
pinMode(trigPin3, OUTPUT);
pinMode(echoPin3, INPUT);
}
float getRange_Ultrasound_1(){
int val = 0;
for(int i=0; i<4; i++) {
digitalWrite(trigPin1, LOW);
delayMicroseconds(2);
digitalWrite(trigPin1, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin1, LOW);
duration = pulseIn(echoPin1, HIGH);
//Calculate the distance (in cm) based on the speed of sound.
val += duration;
}
return val / 232.8 ;
}
float getRange_Ultrasound_2(){
int val = 0;
for(int i=0; i<4; i++) {
digitalWrite(trigPin2, LOW);
delayMicroseconds(2);
digitalWrite(trigPin2, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin2, LOW);
duration = pulseIn(echoPin2, HIGH);
//Calculate the distance (in cm) based on the speed of sound.
val += duration;
}
return val / 232.8 ;
}
float getRange_Ultrasound_3(){
int val = 0;
for(int i=0; i<4; i++) {
digitalWrite(trigPin3, LOW);
delayMicroseconds(2);
digitalWrite(trigPin3, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin3, LOW);
duration = pulseIn(echoPin3, HIGH);
//Calculate the distance (in cm) based on the speed of sound.
val += duration;
}
return val / 232.8 ;
}
long range_time_1;
long range_time_2;
long range_time_3;
void loop() {
/* The following trigPin/echoPin cycle is used to determine the
distance of the nearest object by bouncing soundwaves off of it. */
if ( millis() >= range_time_1 ){
int r =0;
range_msg1.range = getRange_Ultrasound_1();
range_msg1.header.stamp = nh.now();
pub_range_1.publish(&range_msg1);
range_time_1 = millis() + 50;
}
if ( millis() >= range_time_2 ){
int r =0;
range_msg2.range = getRange_Ultrasound_2();
range_msg2.header.stamp = nh.now();
pub_range_2.publish(&range_msg2);
range_time_2 = millis() + 50;
}
if ( millis() >= range_time_3 ){
int r =0;
range_msg3.range = getRange_Ultrasound_3();
range_msg3.header.stamp = nh.now();
pub_range_3.publish(&range_msg3);
range_time_3 = millis() + 50;
}
nh.spinOnce();
delay(250);
}
<file_sep># Multiple_ultrasound_sensors
Code for three HC-SR04 ultrasound sensors using ROS
| aefc564e3334beda983ec87347aff717255ba9f8 | [
"Markdown",
"C++"
] | 2 | C++ | nasetooo99/Multiple_ultrasound_sensors | 897312619e21de75be7c0c16ef3741c30140378b | af69c8d29dd113f151b14cf26850a6908b62d0ab |
refs/heads/master | <repo_name>Beckyme/Py104<file_sep>/ex16.py
# -*- coding:utf-8 -*-
from sys import argv
# 将sys模组import进argv
script, filename = argv
# 将script和filename赋值给grav
print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."
# 输出We're going to erase文件名
# 输出If you don't want that, hit CTRL-C (^C)
# 输出If you do want that, hit RETURN.
raw_input("?")
# 输入提示符?输出
print "Opening the file..."
target = open(filename, 'w')
# 输出Opening the file...
# 变量target被赋予打开文件名的文件使其处于可编辑模式
print "Truncating the file. Goodbye!"
target.truncate()
# 输出Truncating the file. Goodbye!
# 将target变量所被赋予的文件内容清空
print "Now I'm going to ask you for three lines."
# 输出Now I'm going to ask you for three lines.
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
# line1被赋值为所输入的内容,提示内容为line1:
# line2被赋值为所输入的内容,提示内容为line2:
# line3被赋值为所输入的内容,提示内容为line3:
print "I'm going to write these to the file."
# 输出I'm going to write these to the file.
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
# 在target变量所被赋予的文件内写入line1变量所被输入的内容
# 在target变量所被赋予的文件内换行
# 在target变量所被赋予的文件内写入line2变量所被输入的内容
# 在target变量所被赋予的文件内换行
# 在target变量所被赋予的文件内写入line3变量所被输入的内容
# 在target变量所被赋予的文件内换行
print "And finally, we close it."
target.close()
# 输出And finally, we close it.
# 将target变量所被赋予的文件关闭<file_sep>/ex4add.py
1.程序中使用的4.0是个浮点数,这样在和其他整数型(int)数值运算时依然能够得出浮点数(小数)。
2.浮点数是属于有理数中某特定子集的数的数字表示,在计算机中用以近似表示任意某个实数。
3.ex4.py中已完成。
4-5 已记住,=是赋值,_是下划线。
6.已在python中运行。<file_sep>/ex33add.py
# -*- coding:utf-8 -*-
i = 1
numbers = []
while i < 100:
print "At the top i is %d" % i
numbers.append(i)
n = int(raw_input("Give me a number"))
i = i + n
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
print "The numbers: "
for num in numbers:
print num<file_sep>/ex3add.py
# -*- coding:utf-8 -*-
#1.已经在ex3.py完成。
#2.在powershell中运行过了。
#3.
from __future__ import division
a = 244158112/1024
print a
'''
4.浮点数是属于有理数中某特定子集的数的数字表示,在计算机中用以近似表示任意某个实数。
浮点数在表示数字的时候直接阶段,而不是四舍五入得到的整数,如8/3得整数2。
python能很好地支持浮点数运算,但是python中浮点数是用二进制分数进行表示的。
通常代码中的浮点数是由十进制分数表示,因此在其转换为二进制分数时面临着尾数上的截断误差。
网上有很多浮点数精度的文章可供参考。
'''
# 5
print "I will now count my chickens:"
# 输出母鸡的数量,先乘除后加减。
print "Hens", 25.0 + 30 / 6
# 输出公鸡的数量,%是取余数,和乘除的优先级一样。
print "Roosters", 100.0 - 25 * 3 % 4
# 输出"Now I will count the eggs:"
print "Now I will count the eggs:"
# 3+2+1-5+0-0+6
print 3.0 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
# 输出"Is it true that 3 + 2 < 5 - 7?"
print "Is it true that 3 + 2 < 5 - 7?"
# If print <, >, <=, >=, print out TRUE or FALSE.
print 3 + 2 < 5 - 7
# If the calculate in a print "", just print the formula.
print "What is 3.0 + 2?", 3 + 2
print "What is 5.0 - 7?", 5 - 7
# print string
print "Oh, that's why it's False."
# print string
print "How about some more."
# 输出布尔值。
print "Is it greater?", 5 > -2
print "Is it greater or equal?", 5 >= -2
print "Is it less or equal?", 5<= -2<file_sep>/ex10.py
# -*- coding:utf-8 -*-
"I am 6'2\" tall." # 将字符串中的双引号转义
'I am 6\'2" tall.' # 将字符串中的单引号转义
"转义序列\"escape sequences\"" # 将字符串中的双引号转义
tabby_cat = "\tI'm tabbed in." # \t横向制表符 \v纵向制表符
persian_cat = "I'm split\non a line." # \n换行 \r回车
backslash_cat = "I'm \\ a \\ cat."
# 给变量赋值时也可用'''赋值多行str,内含\t\n转义字符。
fat_cat = """
I'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
"""
# 输出变量。
print tabby_cat
print persian_cat
print backslash_cat
print fat_cat
<file_sep>/ex21add.py
# -*- coding:utf-8 -*-
def circle(a, b):
print "If we have a cicle, we know the radius is %.2f." % a
return 2 * a * b
perimeter = circle(15,3.1415)
print "The perimeter is %.3f." % perimeter
def circle_new(a, b):
print "If you have a cicle, you can decide the radius you want."
return a * b * b
area = circle(float(raw_input("Please type the radius you want: ")), 3.1415)
print "The area is %.3f." % area
print ""
def program(a, b):
print "You know the first program in the word?"
return a + b
programmer = program("hello ", "word!")
print "The program is: %s" % programmer
def operation(a, b, c, d, e):
print "I want to know the answer of a operation."
return c
a = float(raw_input("Please type the first number: "))
b = float(raw_input("Please type the second number: "))
c = float(raw_input("Please type the third number: "))
d = float(raw_input("Please type the forth number: "))
e = a + b / c * d
print "The answer is %.2f." % e
def format_new(dd, ee):
return dd / ee
def format(aa, bb, cc):
return aa + bb - cc
the_answer = format(24, format_new(34, 100), 1023)
print "The answer of 24 + 34 / 100 -1023 is: ", the_answer
def other(aaa, bbb, ccc, ddd):
return aaa + bbb / ccc - ddd
coo = other(24, 34, 100, 1023)
print "So, the answer of 24 + 34 / 100 -1023 is: %.2f." % coo
def what(ab, cd, ef, gh):
return ab + cd / ef - gh
ab = float(raw_input("Please type the first number: "))
cd = float(raw_input("Please type the second number: "))
ef = float(raw_input("Please type the third number: "))
gh = float(raw_input("Please type the forth number: "))
co = what(ab, cd, ef, gh)
print "So, you want to know %.2f + %.2f / %.2f - %.2f is " % (ab, cd, ef, gh, ), co, "."<file_sep>/ex1add.py
# -*- coding:utf-8 -*-
print "Hello World!"
#print "Hello Again"
#print "I like typing this."
#print "This is fun."
#print 'Yey! Printing.'
#print "I'd much rather you 'not'."
#print 'I "said" do not touch this.'
print "Again"
print "\n"
print "Hello Everyone!",
print "This is a test."
#1. 只打印一行可在print前加#,作为注释出现,不会被打印出来。
#2. 多打印一行可以使用[print ""],python3.x中使用[print("")]。
#3. #是注释,在一行开头使用,主要用于人类查看,"""..."""或者'''...'''也可以用作注释。<file_sep>/ex11add.py
# -*- coding:utf-8 -*-
#1.raw_input()能够接收用户输入的字符串,Python3.x开始使用input()替代该函数。
#2.
# 1输入字符串 13222319810101****
nID = ''
while 1:
nID = raw_input("Input your id plz")
if len(nID) != len("13222319810101****"):
print 'wring lenth of id, input again'
else:
break
print 'your id is %s' % (nID)
# 2输入整数
nAge = int(raw_input("input your age plz:\n"))
if nAge > 0 and nAge < 120:
print 'thanks!'
else:
print 'bad age'
print 'your age is %d\n' % nAge
# 3输入浮点型
fWeight = 0.0
fWeight = float(raw_input("input your weight\n"))
print 'your weight is %f' % fWeight
# 4输入16进制数据
nHex = int(raw_input('input hex value(like 0x20):\n'),16)
print 'nHex = %x,nOct = %d\n' %(nHex,nHex)
# 5输入8进制数据
nOct = int(raw_input('input oct value(like 020):\n'),8)
print 'nOct = %o,nDec = %d\n' % (nOct,nOct)
#3.
print "What kind of sugar would you like?"
suger = raw_input()
print "What kind of book would you read?"
book = raw_input()
print "Now I know you like %r and %r, but I still not really knowing you..." % (suger, book)
#4.一开始确实没有注意。。。
<file_sep>/ex13add3.py
# -*- coding:utf-8 -*-
from sys import argv
name, age, hobby = argv
name = raw_input("Your name is:")
age = raw_input("Your age is:")
hobby = raw_input("You like:")
print "Maybe your name is ", name
print "You interested in ", hobby
print "And you are ", age
<file_sep>/ex13add2.py
# -*- coding:utf-8 -*-
from sys import argv
name, word, type, animal, foot = argv
print "The name of the file is:", name
print "The word you want to say is:", word
print "The type of the traffic is:", type
print "The animal you see is:", animal
print "The animal have foots number is", foot<file_sep>/README.md
# Py104
Homework
ex26.py适用于3.x。
<file_sep>/ex16add.py
# -*- coding:utf-8 -*-
from sys import argv
script, filename = argv
txt = open(filename,"r+")
print "This is the file %r 's content:" % filename
print txt.read()
print "Please write something to celebrate the New Year."
line1 = raw_input("Wish1: ")
line2 = raw_input("Wish2: ")
line3 = raw_input("Wish3: ")
print "I'm going to write these to the file."
txt.seek(0,2)
txt.write('\n{0}\n{1}\n{2}\n'.format(line1,line2,line3))
txt.write('%s\n%s\n%s\n' %(line1,line2,line3))
print "Then I'll closed this file."
print txt.close()<file_sep>/ex14add.py
# -*- coding:utf-8 -*-
from sys import argv
script, fav, user_name = argv
prompt = '* '
print """
This is %s, I'm so glad to see you, %s.
I know that you like %s.
I wish you answer these questions.
""" % (script, user_name, fav)
print "Why do you like %s, %s?" % (fav, user_name)
reason = raw_input(prompt)
print "How deep you like %s, %s?" %(fav, user_name)
deep = raw_input(prompt)
print "How long you like %s, %s?" %(fav, user_name)
long = raw_input(prompt)
print """
So, you like %s because of %s.
And you %s like %s.
You spend %s do this work, and I wish you will keep going.
""" % (fav, reason, deep, fav, long)<file_sep>/ex17add.py
# -*- coding:utf-8 -*-
# copy 1.txt 2.txt 则将1.txt中的文本拷贝至2.txt
# type 1.txt 可将1.txt中的内容打印至屏幕上
'''
from sys import argv
from os.path import exists
script, from_file, to_file =argv
print "Copying from %s to %s" % (from_file, to_file)
input = open(from_file).read()
output = open(to_file, 'w')
output.write(input)
print "Alright, all done."
'''
# 上述代码可以使用
from sys import argv; open(argv[2],'w').write(open(argv[1]).read())<file_sep>/ex19add.py
# -*- coding:utf-8 -*-
def people_in_boat(a, b, c, d):
print "Now we are in Beagle."
print "This in not the trip which we could saw Darwin."
print "We can see 4 people in the boat:"
print "%s, %s, %s and %s." % (a, b, c, d)
print "This is the first method to run this function:"
people_in_boat(11951, 11952, 11953, 11954)
print "Have this kind of \"name\" maybe too strange."
print ""
print "This is the second method to run this function:"
a = "John"
b = "Jimmy"
c = "Xiaoming"
d = "Yono"
people_in_boat(a, b, c, d)
print ""
print "This is the third method to run this function:"
print "You can give them name as you like."
name_a = raw_input("You want to call 11951 as?")
name_b = raw_input("You want to call 11952 as?")
name_c = raw_input("You want to call 11953 as?")
name_d = raw_input("You want to call 11954 as?")
people_in_boat(name_a, name_b, name_c, name_d)
print ""
print "This is the forth method to run this function:"
print "You should give them a number."
number_a = int(raw_input("What number will you give to John?"))
number_b = int(raw_input("What number will you give to Jimmy?"))
number_c = int(raw_input("What number will you give to Xiaoming?"))
number_d = int(raw_input("What number will you give to Yono?"))
people_in_boat(number_a, number_b, number_c, number_d)
print""
print "This is the fifth method to run this function:"
new_a = "You give 11951 a name %s, a new number %d.\n" % (name_a, number_a)
new_b = "You give 11952 a name %s, a new number %d.\n" % (name_b, number_b)
new_c = "You give 11953 a name %s, a new number %d.\n" % (name_c, number_c)
new_d = "You give 11954 a name %s, a new number %d.\n" % (name_d, number_d)
people_in_boat(new_a, new_b, new_c, new_d)
print""
print "This is the sixth method to run this function:"
print "And I want to use the name you give it to these people to run forth again."
print "You should give them a number."
new_number_a = int(raw_input("What number will you give to %s?" % (name_a)))
new_number_b = int(raw_input("What number will you give to %s?" % (name_b)))
new_number_c = int(raw_input("What number will you give to %s?" % (name_c)))
new_number_d = int(raw_input("What number will you give to %s?" % (name_d)))
people_in_boat(new_number_a, new_number_b, new_number_c, new_number_d)
print""
print "This is the seventh method to run this function:"
print "I change them number to float type."
f_number_a = float(new_number_a)
f_number_b = float(new_number_b)
f_number_c = float(new_number_c)
f_number_d = float(new_number_d)
people_in_boat(f_number_a, f_number_b, f_number_c, f_number_d)
print""
print "This is the eighth method to run this function:"
print "Now I change them number to binary."
b_number_a = bin(new_number_a)
b_number_b = bin(new_number_b)
b_number_c = bin(new_number_c)
b_number_d = bin(new_number_d)
people_in_boat(b_number_a, b_number_b, b_number_c, b_number_d)
print""
print "This is the ninth method to run this function:"
print "Now I change them number to hexadecimal."
# 十六进制
h_number_a = hex(new_number_a)
h_number_b = hex(new_number_b)
h_number_c = hex(new_number_c)
h_number_d = hex(new_number_d)
people_in_boat(h_number_a, h_number_b, h_number_c, h_number_d)
print""
print "This is the tenth method to run this function:"
print "Now I change them number to Octal."
# 八进制
o_number_a = oct(new_number_a)
o_number_b = oct(new_number_b)
o_number_c = oct(new_number_c)
o_number_d = oct(new_number_d)
people_in_boat(o_number_a, o_number_b, o_number_c, o_number_d)<file_sep>/ex3.py
# -*- coding:utf-8 -*-
# 输出"I will now count my chickens:"
print "I will now count my chickens:"
# 输出母鸡的数量,先乘除后加减。
print "Hens", 25 + 30 / 6
# 输出公鸡的数量,%是取余数,和乘除的优先级一样。
print "Roosters", 100 - 25 * 3 % 4
# 输出"Now I will count the eggs:"
print "Now I will count the eggs:"
# 3+2+1-5+0-0+6
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
# 输出"Is it true that 3 + 2 < 5 - 7?"
print "Is it true that 3 + 2 < 5 - 7?"
# If print <, >, <=, >=, print out TRUE or FALSE.
print 3 + 2 < 5 - 7
# If the calculate in a print "", just print the formula.
print "What is 3 + 2?", 3 + 2
print "What is 5 - 7?", 5 - 7
# print string
print "Oh, that's why it's False."
# print string
print "How about some more."
# 输出布尔值。
print "Is it greater?", 5 > -2
print "Is it greater or equal?", 5 >= -2
print "Is it less or equal?", 5<= -2
# 整数运算结果为整数,浮点数运算结果为浮点数,整数浮点数混合运算结果为浮点数
# 不会 from __future__ import division 实除法模块,下行再输入整数运算,可得到浮点值
#int("4.56")==4 浮点数转换为整数,简单取整,不涉及四舍五入。
#float(5)==5.0 整数转换为浮点数
#str(0xcc)==‘204’ 整数和浮点数转换为字符串。
<file_sep>/ex30add.py
robots = 52
rabbits = 10
cats = 15
dogs = 13
foods = 30
oil = 50
if foods >= cats and robots >= cats:
print "We creat some robots to feed cats."
elif foods < cats and robots < cats:
print "We need to purchase some food to feed cat."
else:
print "We are confused."
robots -= cats
foods -= cats
if foods >= rabbits and robots >= rabbits:
print "We creat some robots to feed rabbits."
elif foods < rabbits and robots < rabbits:
print "We need to purchase some food to feed rabbits."
else:
print "We are confused."
robots -= rabbits
foods -= rabbits
if foods >= dogs and robots >= dogs:
print "We creat some robots to feed dogs."
elif foods < dogs and robots < dogs:
print "We need to purchase some food to feed dogs."
else:
print "We are confused."
robots += rabbits + cats
print robots
if oil >= robots:
print "We should maintain robots use oil."
else:
print "We need purchase some oil to maintain the robots."<file_sep>/ex15add.py
# -*- coding:utf-8 -*-
filename = raw_input("What file you want to open?")
txt = open(filename)
print txt.read()
txt.close()
# 比起用argv,我更喜欢raw_input,互动性强~<file_sep>/ex6.py
# -*- coding:utf-8 -*-
# 给x赋值str,%d是将10转换为有符号整数的格式化字符,如果添加的是10.0(浮点数),输出时也会输出10(整数)。
x = "There are %d types of people." % 10
# 给binary赋值str。
binary = "binary"
# 给do_not赋值str。
do_not = "don't"
# 给y赋值str, %s是输出字符串的格式化字符,输出binary和do_not变量。
y = "These who know %s and those who %s." % (binary, do_not)
# 输出x和y
print x
print y
# 输出str,%r用rper()方法处理对象,打印时能够重现它所代表的对象。
print "I said: %r." % x
# 输出str,%s用str()方法处理对象,输出str,更适合面向用户。
print "I also said: %s'." % y
# 给hilarious赋予布尔值False。
hilarious = False
# 给joke_evaluation赋值str。
joke_evaluation = "Isn't that joke so funny?! %r"
# 输出str。
print joke_evaluation % hilarious
# 给w赋值str。
w = "This is the left side of..."
# 给e赋值str。
e = "a string with a right side."
# 输出w + e,+ 可以连接字符串。
print w + e<file_sep>/ex11.py
# -*- coding:utf-8 -*-
print "How old are you?",
age = raw_input()
print "How tall are you?",
height = raw_input()
print "How much do you weigh?",
weight = raw_input()
print "So, you're %r old, %r tall and %r heavy." % (age, height, weight)
print "What lbs you want to transform?",
lbs = input()
print "So, %f lbs equal %f kg." % (lbs, lbs * 0.4532)<file_sep>/ex10add.py
# -*- coding:utf-8 -*-
print "I am 6'2\" tall." # 将字符串中的双引号转义
print 'I am 6\'2" tall.' # 将字符串中的单引号转义
print "转义序列\"escape sequences\"\n" # 将字符串中的双引号转义
print ''' I don't want to give up.''' #不知道例子里为什么这里会有空行0.0
tabby_cat = "\vI'm tabbed in."
persian_cat = "I'm split\ron a line."
backslash_cat = "I'm \\ a \\ cat."
how_much_cat = 56
fat_cat = '''
I\'ll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
'''
print 'Today I made a misstake. I\'ll not repetition it again.'
print tabby_cat
print persian_cat
print backslash_cat
print fat_cat,
print "\v"
print "\r %f" % how_much_cat
print "\t %x" % how_much_cat # 十六进制
print "\t %o" % how_much_cat # 八进制
pa = "I\'ll show you all I typed \""
pb = "And this is anothers\' \""
print "\r %s \ I want show you something special" % how_much_cat
print "It write: %r ." % pa
print "It write: %s ." % pb
<file_sep>/ex20.py
# -*- coding:utf-8 -*-
from sys import argv
# 将sys模组import进argv
script, input_file = argv
# 将script和input_file赋值给argv
def print_all(f):
print f.read()
# 定义函数print_all并给其赋值f,f代表了一个文件
# 输出f文件中的内容
def rewind(f):
f.seek(0)
# 定义函数rewind并给其赋值f,f代表了一个文件
# seek(0)代表回到文件开头
def print_a_line(line_count, f):
print line_count, f.readline()
# 定义函数print_a_line并给其赋值line_count和f,f代表了一个文件
# 输出line_count, f文件中所读取的那行
current_file = open(input_file)
# current_line赋值为打开input_file(输入的文件)
print "First let's print the whole file:\n"
# 输入"First let's print the whole file:换行"
print_all(current_file)
# print_all赋值为current_file(即打开所输入文件)
print "Now let's rewind, kind of like a tape."
# 输入"Now let's rewind, kind of like a tape."
rewind(current_file)
# rewind赋值为current_file(即打开所输入文件,并回到开头位置)
print "Let's print three lines:"
# 输入"Let's print three lines:"
current_line = 1
print_a_line(current_line, current_file)
# current_line赋值为1
# print_a_line赋值为current_line和current_file(即先输出1,再输出1行所在内容)
current_line = current_line + 1
print_a_line(current_line, current_file)
# current_line赋值为自+1
# print_a_line赋值为current_line和current_file(即先输出2,再输出2行所在内容)
current_line = current_line + 1
print_a_line(current_line, current_file)
# current_line赋值为自+1
# print_a_line赋值为current_line和current_file(即先输出3,再输出3行所在内容)<file_sep>/ex31add.py
# -*- coding:utf-8 -*-
print "You enter a dark room with two doors. Do you go through door #1 or door #2?"
prompt = "> "
door = raw_input(prompt)
if door == "1":
print "There's a red box in the room. What do you do?"
print "1. Open this box."
print "2. ignor the box, and go away."
room1 = raw_input(prompt)
if room1 == "1":
print "There is a knife in the box. What do you do?"
print "1. Keep search the box."
print "2. Take the knife."
box1 = raw_input(prompt)
if box1 == "1":
print "You find some coin. So lucky!"
elif box1 == "2":
print "A snake is under the knife and bite you. You died."
else:
print "You waste your time off. You died."
elif room1 == "2":
print "You find some water and foods. So lucky!"
else:
print "Well, %s is not a good idea, game over." % room1
elif door == "2":
print "You stare into the endless abyss at Cthuhlu's retina."
print "1. Blueberries."
print "2. Yellow jacket clothespins."
print "3. Understanding revolvers yelling melodies."
insanity = raw_input(prompt)
if insanity == "1" or insanity == "2":
print "Your body survives powered by a mind of jello. Good job!"
else:
print "The insanity rots your eyes into a pool of muck. Good job!"
else:
print "You stumble around and fall on a knife and die. Good job!"<file_sep>/ex16a.py
# -*- coding:utf-8 -*-
from sys import argv
script, filename = argv
txt = open(filename,"w")
print "Truncating the file. Goodbye!"
txt.truncate()
print "Please write something to celebrate the New Year."
wish1 = raw_input("Wish1: ")
wish2 = raw_input("Wish2: ")
wish3 = raw_input("Wish3: ")
print "I'm going to write these to the file."
txt.write("%r\n%r\n%r" % (wish1, wish2, wish3))
print "Then I'll closed this file."
print txt.close()
# 可以运行但输出结果每行都会被加单引号,无论我是使用单引号还是使用双引号将字符串扩起。<file_sep>/ex20add.py
# -*- coding:utf-8 -*-
'''
from sys import argv
script, input_file = argv
def print_all(f):
print f.read()
def rewind(f):
f.seek(0)
def print_a_line(line_count,f):
print line_count, f.readline()
current_file = open(input_file)
print "First let's print the whole file:\n"
print_all(current_file)
print "Now let's rewind, kind of like a tape."
rewind(current_file)
print "Let's print three lines:"
current_line = 1
print_a_line(current_line, current_file)
print current_line
current_line += 1
print_a_line(current_line, current_file)
print current_line
current_line += 1
print_a_line(current_line, current_file)
print current_line
'''
def number(a, b, c):
print "Now you tpye:", a,b,c
print "Now please type 3 numbers (arithmetic progression) here."
print "I will tell you the next number."
a = float(raw_input("The first number is: "))
b = float(raw_input("The second number is: "))
c = float(raw_input("The third number is: "))
number(a,b,c)
current_number = c
current_number += c -b
print "The next number is:", current_number<file_sep>/ex4.py
# -*- coding:utf-8 -*-
# 车 = 100
cars = 100
# 每辆车的空座数 = 4.0(浮点数)
space_in_a_car = 4.0
# 司机 = 30
drivers = 30
# 乘客 = 90
passengers = 90
# 空车(无驾驶员) = 车 - 司机
cars_not_driven = cars - drivers
# 可行驶车辆数 = 司机数量
cars_driven = drivers
# 车辆可载人数 = 可行驶车辆数 * 每辆车的空座数
carpool_capacity = cars_driven * space_in_a_car
# 平均每车乘客数 = 乘客 / 可行驶车辆数
average_passengers_per_car = passengers / cars_driven
# 输出所需变量。
print "There are", cars, "cars available."
print "There are only", drivers, "drivers available."
print "There will be", cars_not_driven, "empty cars today."
print "We can transport", carpool_capacity, "people today."
print "We have", passengers, "to carpool today."
print "We need to put about", average_passengers_per_car, "in each car."
#Traceback (most recent call last):
# File "ex4.py", line 8, in <module>
# average_passengers_per_car = car_pool_capacity / passenger
#NameError: name 'car_pool_capacity' is not defined
#文件ex4.py中的第8行,‘car_pool_capacity'没有被定义<file_sep>/ex9.py
# -*- coding:utf-8 -*-
# Here's some new strange stuff, remember type is exactly.
# 给days赋值str。
days = "Mon Tue Wed Thu Fri Sat Sun"
# 给months赋值str,内含转义字符\n。
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
# 输出str和变量。
print "Here are the days: ", days
print "Here are the months: ", months
# 输出多行str。
print """
There's something going on here.
With the three double-quotes.
We'll be albe to type as much as we like.
"""<file_sep>/ex30.py
# -*- coding:utf-8 -*-
people = 30
# 定义people变量赋值30
cars = 40
# 定义cars变量赋值40
buses = 15
# 定义buses变量赋值15
if cars > people:
print "We should take the cars."
elif cars < people:
print "We should not take the cars."
else:
print "We can't decide."
"""
如果 cars > people,则输出We should take the cars.
如果 cars < people,则输出We should not take the cars.
其他则输出We can't decide.
"""
if buses > cars:
print "That's too many buses."
elif buses < cars:
print "Maybe we could take the buses."
else:
print "We still can't decide."
"""
如果 buses > cars,则输出That's too many buses.
如果 buses < cars,则输出Maybe we could take the buses.
其他则输出We still can't decide.
"""
if people > buses:
print "Alright, let's just take the buses."
else:
print "Fine, let's stay home then."
"""
如果people > buses,则输出Alright, let's just take the buses.
其他则输出Fine, let's stay home then.
"""<file_sep>/ex13add.py
# -*- coding:utf-8 -*-
from sys import argv
name, age, hobby = argv
print "The file name is:", name
print "Your age is:", age
print "Your hobby is:", hobby
'''
ValueError: not enough values to unpack (expected 3, got 1)
当给出的参数不足时,错误提示就会提示参数不足。
并在括号内提示需要几个参数,输入了几个参数。
'''
<file_sep>/ex27.py
and 与
or 或
not 非
!= (not equal) 不等于
== (equal) 等于
>= (greater-than-equal) 大于等于
<= (less-than-equal) 小于等于
True 真
False 假<file_sep>/summary.md
# Python 总结
## 回顾
### 整体流畅度
整体流畅度较高,因为没有具体计时,不知道具体使用了多少时间,使用教材为中文版。
### 难易度分析
- 在做习题的时候,附加题中不需要敲代码的地方我并没有编辑答案存档,现已补充至21题。
- 习题0-12非常容易上手,但是习题6中附加题“字符串包含字符串”有几个位置这道题我不确定自己的答案是否正确。
- 习题13 import了argv,这个练习的时候尝试了很多种错误方式,得到了一些错误信息,对于什么场景更适用于argv(在运行时需要先将参数输入)并没有什么好想法。
- 习题14-17与文件的打开编辑关闭相关,书中给出的例子不算难,当时搜索过相关信息,不过现在忘的也差不多了。
- 习题18-21将了函数新建、函数读取文件、函数返回,敲代码没难度,做了一些尝试在add中。习题20的附加题3很有趣。
- 习题22-26是小总结&测验,这部分做的不太好,费了很多时间,而且看到总结就拖延,难度算高,另外,ex26.py适用于Python3.x。
- 习题27-28是布尔值练习,难度较小,and 和or 需要注意一下。
- 习题29-31是“if-else”语句的使用,这个很实用,难度不大,经常忘记“:”,需注意。
- 习题32-34是列表、for和while循环。列表在循环中比较常用,while循环有时会出现没有结束的情况,慎用。
- 习题35,一个小AVG游戏,附加题5花了些时间。
- 习题36-40使用的教材是旧版本,40是字典的相关学习,附加题中使用for循环代替while循环卡死了一阵子,后来才发现是for k in i,不是for d[k]
in i。
- 总体难度两星半。
***
## 复盘
### 难题解决
#### 问题描述(发现及探索)
做习题的时候记忆不深了,写最近遇到的在Python3.6中导入builtwith模块出现的问题吧。
刚开始看,书里代码基于Python2.7,我的电脑安装的Python版本是3.6。书的开端说需要使用builtwith模块,我就直接在3.6中easy_install builtwith,其后,在import builtwith时开始出现报错。
“ ...Python36\lib\site-packages\builtwith\__init__.py, line 43
except Exception, e:
^
SyntaxError: invalid syntax ”
#### 问题解决
在网上搜索后,发现除了需将“,”替换成“as”,print的语句也需要更改。另外,在Python3中没有urllib2,需要将其替换为urllib.request和urllib.error,相关代码也需要更改。
但在操作过程中,我遇到的第一个问题是我无法在lib文件夹中找到__init__.py文件。双击builtwith文件打不开,在网上搜索无果后,我发现builtwith文件的后缀我没法查看,就在文件夹选项中更改相关选项,看到该文件后缀为.egg。搜索.egg格式文件发现该格式可用解压缩软件打开,就用7z打开,找到了__init__.py文件。
在该文件中更改相关语句后,系统仍然报错,错误信息为“zlib.error: Error -5 while decompressing data: incomplete or truncated stream”。网上相关信息较少,求助后被告知是环境问题,被安利pyenv。在进一步了解时发现Windows系统没有pyenv,但网上有如何在Windows系统进行Python的版本切换。参考相关网址进行了环境变量配置,并参考另一篇文章install virtualenv,当天在Python2.7中顺利install builtwith,并没有深入验证就睡觉去了。结果第二天powershell运行时virtualenv又跑不起来,并且要求我参阅https://technet.microsoft.com/zh-CN/library/hh847748.aspx ,未解决该问题,我决定再换种思路。
到此为止我纠结的地方其实是如果我现在easy_install始终会安装在Python3.6而非2.7,因此如果能够控制easy_install版本,将builtwith安装在Python2.7,我就可以顺利运行builtwith了。在上网搜索和各种自行尝试后,发现“python2 -m pip install 模块”即在需要的python后+ “-m”即可顺利安装。确认该模块可以运行后,又确认相关路径下已有相关.egg文件,终于算是顺利解决了。
#### 过程改进
- 方向比较重要,弄清楚需要解决的问题的核心要点,对症下药,否则容易做着做着就不可自拔,不知道跑哪里去了。
- 或许需要在电脑里安装Linux系统,这样很多问题不会出现,Windows做开发劣势比较多。。。
***
## 改进计划
- 这次练习是断断续续完成的,所以在做回顾的时候才发现,很多东西当时觉得已经完全掌握,现在看来已经相对模糊了。//今后在学习时尽量每天抽出一定时间,直到学有小成。
- 文档注释做的不够,很多需要做笔记的地方也偷懒没做,造成现在回来看发现有些东西需要重新上网搜索,费时费力。//每次学习做当日小结。
- 英文文档读起来比较吃力,需要提升。//多读多看多查。。。
- 特别容易钻进牛角尖出不来。//自己找答案超过半小时就开始上网搜素或者问人吧...
***
## 期待
课程结束时制作AVG游戏无压力,爬虫和数据分析也能够入门。
还请大家多多指教,谢谢~
<file_sep>/Git for Windows [undone].md
### Git安装及仓库创建
在廖雪峰老师提供的[网址](https://pan.baidu.com/s/1kU5OCOB#list/path=%2Fpub%2Fgit)下载exe文件后,双击打开并按默认选项安装。
开始菜单找到"Git"->"Git Bash"在跳出的命令行窗口中添加姓名和E-mail地址。命令如下:
```
$ git config --global user.name "Name"
$ git config --global user.email "E-mail Address"
```
`git config`命令中`--global`参数的使用表示当前计算机上所有的Git仓库都会使用这个配置。
`mkdir`会在当前路径中创建一个空目录,所以如果不想在当前路径创建仓库,需先使用`cd`命令进入想创建仓库的路径,再使用`mkdir`命令。`pwd`命令可显示当前路径。
也可以手动新建文件夹,然后使用`cd`命令切换到该路径中(不推荐)。
__注意:__ 路径中各级都推荐使用英文。
`git init`命令可以将当前目录变成Git可管理的仓库,使用后当前目录会生成`.git`的隐藏文件,使用`ls -ah`命令可以显示隐藏文件夹。若仍不能显示,可以在文件夹选项中更改显示隐藏文件夹的复选框。
### 文件操作
#### 新建及提交文件
【补充新建文件】`vi`文件名.txt,`i`进入编辑模式输入完内容后按ESC键,键盘输入`:wq`即可保存退出。
在当前目录下新建.txt文档,输入内容保存。
使用`git add <file>`命令将文件添加到仓库:
```
$ git add readme.txt
```
使用`git commit -m "XXX"`命令告诉Git,将文件提交到仓库,该命令`-m`后输入的是本次提交的说明,方便从历史记录中找到改动记录。`comit`命令可一次性上传多次`add`的文件。
Git有工作区和缓存区,其中`git add`将修改放至缓存区。如果不`add`到缓存区,使用`git commit`无法将该修改提交到`master`或`branch`。
#### 修改文件状态查询
`git status`命令用于查看仓库当前状态,如文件是否修改,修改是否被提交。
修改过的文档提交与提交新文档相同(`git add` + `git commit`)。
`git diff`命令可以查看文档修改内容。
`git log`命令可以查看历史记录。使用`--pretty=oneline`参数可以简化历史记录,只显示`commit id`以及该版本的提交说明。
#### 版本切换
在Git中,`HEAD`表示当前版本,上一个版本为`HEAD^`,上上个版本为`head^^`,往上的第n个版本为`head~n`。
`git reset --hard`命令可以返回之前的版本。返回原来的版本,其后的版本就在`git log`中看不到了。
该命令行窗口没被关掉,查找到最新版本的`commit id`就可以继续使用`git reset --hard`命令回到未来的那个最新版本。`commit id`可以不用写全,但要能与其他版本号区别开。
当命令行窗口被关掉,仍要恢复到之前的最新版,可以使用`git reflog`命令找到最新版的`commit id`,同上使用`git reset --hard commit_id`返回。
#### 撤销修改
撤销工作区的修改使用`git checkout --<file>`命令。
撤销暂存区的修改首先用`git reset HEAD <file>`命令,之后与撤销工作区修改相同。
没有推送至远程仓库但commit的情况参考 __版本切换__ 。
__注意:__ `git checkout --<file>`命令中如果没有`--`就变成了“切换到另一个分支”的命令。
#### 删除文件
使用`rm`命令删除该设备文件。
使用`git rm`命令删除版本库中的文件,并且需要继续`git commit`。
__注意 :__ `git checkout`其实是用版本库中的版本替换工作区的版本,无论工作区是修改还是删除都可还原。提交至版本库中的文件如果恢复只能恢复到最新版本,最后一次提交后作出的修改会丢失。
### GitHub仓库
#### 本地Git仓库与GitHub仓库连接
1. 创建SSH Key。
`$ ssh-keygen -t rsa -C "E-mail Address"`
之后使用默认值即可。
在用户主目录中找到`.ssh`目录,其中的`id_rsa`是私钥,不能泄露出去;`id_rsa.pub`是公钥。
2. 登陆GitHub,打开“Settings”->“SSH and GPG keys”->“New SSH Key”页面。Title任意填,Key中国粘贴`id_rsa.pub`文件的内容,然后“Add Key”。
#### 远程仓库克隆
使用`git clone`命令可以将远程仓库克隆至一个本地仓库。
1. ```$ git clone <EMAIL>:YourGitHubName/YourGitHubRepository.git```
2.```$ git clone https://github.com/YourGitHubName/YourGitHubRepository.git```
Git支持多种协议,默认的`git://`使用ssh,也可以使用`https`等其他协议。
`https`协议传输速度慢,每次推送都必须输入口令,但推荐只开放`http`端口的公司使用。
### 分支管理
#### 分支的创建与合并
`git checkout -b "BranchName"`命令创建并切换到该分支。相当于命令`git branch ""`和`git checkout ""`的合并。
`git branch`命令会列出所有分支,其中当前分支以`*`区分。
`git merge "BranchName"`命令可以将指定分支合并到当前分支。
`git checkout -d "BranchName"`命令用于删除指定分支。
使用分支完成某个任务,合并后再删掉分支,这和直接在`master`分支上工作效果相同,但过程更安全。<file_sep>/ex15.py
# coding:utf-8
from sys import argv
# 将sys模组import进argv
script, filename = argv
# 将script和filename赋值给grav
txt = open(filename)
# 变量txt等于打开(文件名)的文件
print "Here's your file %r:" % filename
# 输出Here's your file 文件名
print txt.read()
# 输出txt变量内文件所被读取的内容
print "I'll also ask you to type it again:"
file_again = raw_input("> ")
# 输出I'll also ask you to type it again:
# file_again变量等于>用户输入的文件名
txt_again = open(file_again)
# txt_again变量等于打开file_again中用户输入的文件名所代表的文件
print txt_again.read()
# 输出txt_again变量内文件所被读取的内容
txt_again.close()
txt.close()
<file_sep>/ex36.py
# -*- coding:utf-8 -*-
from sys import exit
end1 = "You're already dead."
end2 = '''
The room is empty.
The door is closed.
You can not find a way to get away from there.
You dead.
'''
end3 = '''
The ghost cause you to lose yourself.
You became a ghost too.
'''
end4 = '''
The enemy is too strong, You can not kill it.
Even though,the ghost appreciate you for your trying.
It self-destruction with enemy, you are alive.
'''
def room3():
print 'The ghost show you why it dead and wants you to revenge for it.'
print 'You will:'
print "1 help it."
print '2 say no.'
print "Please input the number for your choose: "
next = int(raw_input('> '))
if next == 1:
print end4
elif next == 2:
print end3
else:
print "The ghost eat you step by step."
def room2():
print 'This room is rely on past of the ghost.'
print 'You see:'
print "1 a lot of dead person."
print '2 a lot of money.'
print '3 a lot of water.'
print "Please input the number for your choose: "
next = int(raw_input('> '))
if next == 1 or next ==3:
room3()
elif next == 2:
print end3
else:
print "The ghost eat you step by step."
def room1():
print "There is a ghost here."
print "You can:"
print "1 Run away."
print '2 Kill it.'
print '3 Talk with it.'
print "Please input the number for your choose: "
next = int(raw_input('> '))
if next == 1:
print end1
elif next == 2:
print end2
elif next == 3:
room2()
else:
print "The ghost eat you step by step."
room1()
<file_sep>/ex5add.py
# -*- coding: utf-8 -*-
# 如果要加入中文上面这行代码必须加在第一行,否则将会报错。
name = '<NAME>'
age = 35 # not a lie
height = 74 # inches 英尺
weight = 180 # lbs 英镑
eyes = 'Blue'
teeth = 'Black'
hair = 'Brown'
print "Let's talk about %s." % name
print "He's %d inches tall." % height
print "He's %d pounds heavy." % weight
print "Actually that's not too Heavy."
print "He's got %s eyes and %s hair." % (eyes, hair)
print "His teeth are usually %s depending on the coffee." % teeth
# this line is tricky, try to get it exactly right
print "If I add %d, %d, and %d I get %d." % (age, height, weight, age + height + weight)
# 3
lbs = 0.454
inches = 30.48 # 1英尺等于30.48厘米
print "5 lbs = %f kg." % (lbs * 5)
print "7 inches = %f cm." % (inches * 7)
print "%r '' use it" % (inches)
print lbs * 6
'''
4
%% 百分号标记 #就是输出一个%
%c 字符及其ASCII码
%s 字符串
%d 有符号整数(十进制)
%u 无符号整数(十进制)
%o 无符号整数(八进制)
%x 无符号整数(十六进制)
%X 无符号整数(十六进制大写字符)
%e 浮点数字(科学计数法)
%E 浮点数字(科学计数法,用E代替e)
%f 浮点数字(用小数点符号)
%g 浮点数字(根据值的大小采用%e或%f)
%G 浮点数字(类似于%g)
%p 指针(用十六进制打印值的内存地址)
%n 存储输出字符的数量放进参数列表的下一个变量中
'''
| 074a3fc6dc65d1843982b522c162bbcb725e6d30 | [
"Markdown",
"Python"
] | 35 | Python | Beckyme/Py104 | 37f05a04cd9b8b413a54baf937e59c09d4ad595b | a0e2a7077f72ac2ab4580a2e04bb8582a4d76e58 |
refs/heads/master | <repo_name>LIUQingpei-HKU/LeetCode27_RemoveElement<file_sep>/main.cpp
#include <iostream>
#include <vector>
using namespace std;
//71.62% 3ms
//time O(n)
//space O(1)
class SolutionMe1 {
public:
int removeElement(vector<int>& nums, int val) {
//for [0,k)
int k=0;
for(int i=0;i<nums.size();i++){
if(nums[i]!=val){
swap(nums[k],nums[i]);
k++;
}
}
return k;
}
};
//1% 9ms
class SolutionME2 {
public:
int removeElement(vector<int>& nums, int val) {
//for [0,k)
int k=0;
for(int i=0;i<nums.size();i++){
if(nums[i]!=val){
if(i!=k){
swap(nums[k],nums[i]);
k++;
}else k++;
}
}
return k;
}
};
//
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
} | 19047b204b9afefcb9a49c8606e9f7afc1634e6b | [
"C++"
] | 1 | C++ | LIUQingpei-HKU/LeetCode27_RemoveElement | 37b4b97f227d72d1c02a3fa819c70179cf7f3a2f | dbca79c44a5c0423e97e670ac8c9c7919d82f979 |
refs/heads/master | <repo_name>VladStroganoff/Coast-Light-Game<file_sep>/TableTopLegions_V1/Assets/Systems/HandManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HandManager : MonoBehaviour
{
public CanvasManager canvasManager;
public BudgetManager budgetManager;
Transform cardPool;
Transform cardHand;
Transform upNextCard;
void Start ()
{
cardPool = canvasManager.cardPool;
cardHand = canvasManager.cardHand;
upNextCard = canvasManager.upNextCard;
}
public void ShufflePool()
{
foreach(Transform card in cardPool)
{
card.SetSiblingIndex(Random.Range(0, cardPool.childCount));
}
}
public void DealCards()
{
ShufflePool();
if(cardPool.childCount != 0)
{
int childCount = cardPool.childCount;
for (int i = (childCount - 1); i < childCount && i > -1; i--)
{
if (cardHand.childCount < 4)
{
Transform card = cardPool.GetChild(i);
card.SetParent(cardHand);
card.localScale = new Vector3(1,1,1);
card.GetComponent<CanvasCard>().handManager = this;
}
else if (upNextCard.childCount == 0)
{
Transform card = cardPool.GetChild(i);
card.SetParent(upNextCard);
card.localScale = new Vector3(1, 1, 1);
card.GetComponent<CanvasCard>().handManager = this;
}
else
{
return;
}
}
}
}
public void DrawNewCard()
{
if (cardHand.childCount != 4)
{
ShufflePool();
Transform handCard = upNextCard.GetChild(0);
handCard.SetParent(cardHand);
handCard.localScale = new Vector3(1, 1, 1);
handCard.GetComponent<CanvasCard>().handManager = this;
Transform nextCard = cardPool.GetChild(0);
nextCard.SetParent(upNextCard);
nextCard.localScale = new Vector3(1, 1, 1);
nextCard.GetComponent<CanvasCard>().handManager = this;
}
}
}
<file_sep>/TableTopLegions_V1/Assets/Systems/Unit/TargetManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TargetManager : MonoBehaviour
{
Unit myUnit;
public List<Transform> inMeleeRange;
public List<Transform> inDistanceRange;
public List<string> targetPreferences;
public List<Transform> totalTargets = new List<Transform>();
public List<Transform> wayPoints = new List<Transform>();
private GameManager gameManager;
private GameObject closestGO;
private float closest;
private float distance;
private bool havePassedWayPoint = false;
public void Awake()
{
myUnit = GetComponent<Unit>();
}
void Start()
{
ReferenceGather();
}
void ReferenceGather()
{
gameManager = GameObject.FindGameObjectWithTag("Manager").GetComponent<GameManager>();
}
public Transform FindClosestEnemy(List<Transform> _GOs, Team _myTeam)
{
totalTargets.Clear();
if (!havePassedWayPoint)
{
foreach(Transform wayPoint in gameManager.wayPoints)
{
wayPoints.Add(wayPoint);
}
return FindCLosestUnit(wayPoints);
}
else
{
foreach (Transform unit in _GOs)
{
totalTargets.Add(unit);
}
}
return FindCLosestUnit(_GOs);
}
public Transform FindCLosestUnit(List<Transform> units)
{
if (units.Count > 0)
{
bool closestObtained = false;
closestGO = null;
for (int i = 0; i < units.Count; i++)
{
if (!closestObtained)
{
closestObtained = true;
closest = Vector3.Distance(this.transform.position, units[i].transform.position);
closestGO = units[i].gameObject;
}
distance = Vector3.Distance(this.transform.position, units[i].transform.position);
if (distance <= closest)
{
closestGO = units[i].gameObject;
}
}
if (closestGO == null)
{
return null;
}
return closestGO.transform;
}
return null;
}
public void HavePassedWayPoint()
{
havePassedWayPoint = true;
myUnit.myTarget = null;
}
}
<file_sep>/TableTopLegions_V1/Assets/Systems/DebugSetCameraPosition.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DebugSetCameraPosition : MonoBehaviour
{
public GameObject Camera;
void Start ()
{
Invoke("RestCameraPosition", 1f);
}
void RestCameraPosition()
{
Camera.transform.position = this.transform.position;
Camera.transform.rotation = this.transform.rotation;
Invoke("RestCameraPosition", 5f);
}
}
<file_sep>/TableTopLegions_V1/Assets/Systems/Unit/GameManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
public enum GameState { ObservationMode, InLobby, GameInProgress, GameEnded};
public static GameState game;
public Team playedTeam;
public Image teamColor;
private CanvasManager canvasManager;
private GameObject worldPlane;
public List<Transform> wayPoints;
public List<Transform> totalUnits;
public List<Transform> redTeam;
public List<Transform> redGraveYard;
public List<Transform> blueTeam;
public List<Transform> blueGraveYard;
public List<Transform> greyTeam;
public List<Transform> greyGraveYard;
void Start()
{
Setup();
}
void Setup()
{
if (GameObject.Find("World Plane") != null)
{
worldPlane = GameObject.Find("World Plane");
}
else
{
worldPlane = GameObject.Find("Budget World Plane");
}
teamColor.color = Color.gray;
canvasManager = GameObject.Find("MainCanvas").GetComponent<CanvasManager>();
}
public void StartGame()
{
game = GameState.GameInProgress;
AssignUIColor();
foreach (Transform unit in totalUnits)
{
Unit thisUnit = unit.GetComponent<Unit>();
thisUnit.SetupUnit();
if(thisUnit.myTeam == Team.blue)
{
blueTeam.Add(thisUnit.transform);
}
else if (thisUnit.myTeam == Team.red)
{
redTeam.Add(thisUnit.transform);
}
else
{
greyTeam.Add(thisUnit.transform);
}
}
}
public void RestartGame()
{
totalUnits.Clear();
redTeam.Clear();
redGraveYard.Clear();
blueTeam.Clear();
blueGraveYard.Clear();
greyTeam.Clear();
greyGraveYard.Clear();
playedTeam = Team.none;
canvasManager.ClearAllCards();
foreach (Transform child in worldPlane.transform)
{
if(child.transform.name != "Ground")
{
Destroy(child.gameObject);
}
}
}
public void PlayerTower(Team _playerTeam)
{
playedTeam = _playerTeam;
AssignUIColor();
}
void AssignUIColor()
{
if (playedTeam == Team.red)
{
teamColor.color = Color.red;
}
else if (playedTeam == Team.blue)
{
teamColor.color = Color.blue;
}
else
{
teamColor.color = Color.grey;
}
}
public void ReportDeath(Transform deadUnit)
{
if (deadUnit.GetComponent<Unit>().myTeam == Team.red)
{
redTeam.Remove(deadUnit);
totalUnits.Remove(deadUnit);
redGraveYard.Add(deadUnit);
}
else if(deadUnit.GetComponent<Unit>().myTeam == Team.blue)
{
blueTeam.Remove(deadUnit);
totalUnits.Remove(deadUnit);
blueGraveYard.Add(deadUnit);
}
else if (deadUnit.GetComponent<Unit>().myTeam == Team.none)
{
greyTeam.Remove(deadUnit);
totalUnits.Remove(deadUnit);
greyGraveYard.Add(deadUnit);
}
CheckWinningConditions();
}
void CheckWinningConditions()
{
if (redTeam.Count <= 0)
{
GiveEndReportOnGame(Team.red);
game = GameState.GameEnded;
}
else if(blueTeam.Count <= 0)
{
GiveEndReportOnGame(Team.blue);
game = GameState.GameEnded;
}
else
{
GiveEndReportOnGame(Team.none);
}
}
void GiveEndReportOnGame(Team _loosingTeam)
{
if(playedTeam != _loosingTeam)
{
if (_loosingTeam != Team.none && playedTeam != Team.none)
{
canvasManager.PlayerWonGame();
}
else if(playedTeam == Team.none)
{
canvasManager.SimulationOver();
}
else
{
}
}
else if(playedTeam == _loosingTeam && playedTeam != Team.none)
{
canvasManager.PlayerLost();
}
}
public void CheckInWayPoint(Transform _wayPoint)
{
wayPoints.Add(_wayPoint);
}
}
<file_sep>/TableTopLegions_V1/Assets/Systems/Unit/DamageCalc.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class DamageCalc
{
public static float Hit(int _damage, int _critChange, DamageType _damageType, int _armour)
{
bool crit = CritCalculate(_critChange);
_damage = _damage * (crit ? 2 : 1);
switch (_damageType)
{
case DamageType.Blunt:
//strong against armour
return((_damage * 10) / ArmourReduced(_armour, 0.6f));
case DamageType.Piercing:
//shitty against armour unless it crits, then it ignores armour,
if (crit)
{
return(_damage * 10);
}
else
{
return((_damage * 10) / ArmourReduced(_armour, 0.3f));
}
case DamageType.Slashing:
//shitty against armour, stroink against flesh
return ((_damage * 10) / ArmourReduced(_armour, 0.2f));
case DamageType.Magic:
return 0;
}
return 0;
}
public static bool CritCalculate(int _chance)
{
return (Random.Range(1, 100) < _chance);
}
public static float ArmourReduced(int _armour, float _reduction)
{
float armour = _armour * _reduction;
return armour;
}
}
<file_sep>/TableTopLegions_V1/Assets/Systems/AgentManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class AgentManager : MonoBehaviour
{
public LayerMask layerMask;
RaycastHit hit;
Unit myUnit;
Vector3 groundPos;
NavMeshAgent agent;
void Start()
{
myUnit = GetComponent<Unit>();
CheckFloor();
agent = this.GetComponent<NavMeshAgent>();
}
void CheckFloor ()
{
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.down), out hit, Mathf.Infinity, layerMask))
{
Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.down) * hit.distance, Color.yellow);
Debug.Log(myUnit.name + "'s distance to the ground is: " + Vector3.Distance(this.transform.position, hit.point).ToString() + "m");
groundPos = hit.point;
}
Invoke("MoveUp", 2f);
}
void MoveUp()
{
agent.Warp(new Vector3(groundPos.x, 1f, groundPos.z));
Invoke("MoveDown", 1f);
}
void MoveDown()
{
Invoke("CheckFloor", 2f);
agent.Warp(groundPos);
}
}
<file_sep>/TableTopLegions_V1/Assets/Systems/ObservationModeManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ObservationModeManager : MonoBehaviour
{
public Unit myUnit;
[Space(30)]
public Text unitName;
public Image unitTypeIcon;
public Text health;
public Text movement;
public Text meleeSpeed;
public Text rangeSpeed;
public Text meleeDistance;
public Text rangeDistance;
public Text attackDamage;
public Text Agression;
public Sprite meleeUnitType;
public Sprite rangeUnitType;
public Sprite mixedUnitType;
public RectTransform observationUI;
public float speedOfObservationUI = 20f;
private GameManager gameManager;
private Camera gameCamera;
private float HPVale;
private float HPFill;
public Image healthDisplay;
public Image teamDisplay;
private GameObject InactiveUICard;
void Start ()
{
gameManager = GameObject.FindGameObjectWithTag("Manager").GetComponent<GameManager>();
gameCamera = Camera.main;
SetStatistics();
}
void Update()
{
if (myUnit.myGameState == UnitGameState.HasTeam)
{
observationUI.gameObject.SetActive(false);
}
else
{
RotateInspectorUI();
}
}
void SetStatistics()
{
unitName.text = myUnit.m_MyName;
health.text = myUnit.m_Health.ToString();
movement.text = myUnit.m_MovementSpeed.ToString();
meleeSpeed.text = myUnit.m_MeleeSpeed.ToString();
rangeSpeed.text = myUnit.m_RangedSpeed.ToString();
meleeDistance.text = myUnit.m_AttackDistance.ToString();
rangeDistance.text = myUnit.m_RangeDistance.ToString();
attackDamage.text = myUnit.m_AttackDamage.ToString();
Agression.text = myUnit.m_Aggression.ToString();
switch (myUnit.myAttackModes)
{
case AttackModes.Melee:
unitTypeIcon.sprite = meleeUnitType;
break;
case AttackModes.Ranged:
unitTypeIcon.sprite = rangeUnitType;
break;
case AttackModes.MeleeRanged:
unitTypeIcon.sprite = mixedUnitType;
break;
}
teamDisplay.color = Color.grey;
}
void RotateInspectorUI()
{
var lookPos = gameCamera.transform.position - observationUI.transform.position;
lookPos.y = 0;
var rotation = Quaternion.LookRotation(lookPos);
observationUI.transform.rotation = Quaternion.Slerp(observationUI.transform.rotation, rotation, Time.deltaTime * speedOfObservationUI);
}
}
<file_sep>/TableTopLegions_V1/Assets/Systems/VuforiaHacking/AnchorTargetListener.cs
using UnityEngine;
using Vuforia;
public class AnchorTargetListener : MonoBehaviour, ITrackableEventHandler
{
//The Goal of this class is to automatically Initiate a Ground Plane when the Image Target is detected
// Use this classs in combination with the PlaceContentFromImageTarget if you want to move the content
// of an image target onto the Ground Plane Stage
//This class should replace the default AnchorInputListenerBehaviour in the PlaneFinder GameObject
//Don't forget to set the OnInputReceivedEvent of this component to call the PlaneFinderBehaviour
public ImageTargetBehaviour ImageTarget;
private bool _planeFound = false;
public AnchorInputListenerBehaviour.InputReceivedEvent OnInputReceivedEvent;
void Start()
{
if (ImageTarget != null)
{
ImageTarget.RegisterTrackableEventHandler(this);
}
}
public void OnTrackableStateChanged(TrackableBehaviour.Status previousStatus, TrackableBehaviour.Status newStatus)
{
if (_planeFound)
{
return;
}
if (newStatus == TrackableBehaviour.Status.DETECTED ||
newStatus == TrackableBehaviour.Status.TRACKED)
{
Debug.Log("Target Found!");
if (OnInputReceivedEvent != null)
{
//TODO: is Camera.main still slow?
var hitTestLocation = Camera.main.WorldToScreenPoint(this.ImageTarget.transform.position);
Debug.Log("hit test location: " + hitTestLocation);
this.OnInputReceivedEvent.Invoke(hitTestLocation);
_planeFound = true;
}
}
}
}
<file_sep>/TableTopLegions_V1/Assets/Systems/Unit/UnitAudioClips.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UnitAudioClips : MonoBehaviour {
public AudioClip[] BluntHits;
public AudioClip[] BluntKills;
public AudioClip[] SharpHits;
public AudioClip[] Deaths;
public AudioClip[] BowHits;
}
<file_sep>/TableTopLegions_V1/Assets/Systems/Unit/UnitPriority.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class UnitPriority : IComparable<UnitPriority>
{
public string name;
public int ID;
public int priority;
public float score;
public Transform target;
public int CompareTo(UnitPriority other)
{
if(other == null)
{
return 0;
}
return priority - other.priority;
}
}
public class UnitDistance : IComparable<UnitDistance>
{
public int ID;
public float distance;
public int CompareTo(UnitDistance other)
{
if (other == null)
{
return 0;
}
return distance.CompareTo(other.distance);
}
}<file_sep>/TableTopLegions_V1/Assets/Systems/ProjectileManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ProjectileManager : MonoBehaviour
{
public float lifeTime = 3f;
public float speed = 5f;
public float hightOffset;
[HideInInspector]
public Transform target;
[HideInInspector]
public CombatManager myCombatManager;
void Start()
{
// Invoke("Miss", lifeTime);
Invoke("Hit", TimeToTarget());
}
void Hit()
{
myCombatManager.Hit();
Destroy(this.gameObject);
}
float TimeToTarget()
{
return Vector3.Distance(transform.position, target.position) / speed;
}
/*
void OnTriggerEnter(Collider col)
{
if(col.transform.tag == "HitBox")
{
if (col.transform.parent == target.transform)
{
myCombatManager.Hit();
Destroy(this.gameObject);
}
}
}
void OnTriggerStay(Collider col)
{
if (col.transform.tag == "HitBox")
{
if(col.transform.parent == target.transform)
{
myCombatManager.Hit();
Destroy(this.gameObject);
}
}
}
*/
void Update()
{
float step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, new Vector3(target.transform.position.x, (target.transform.position.y + hightOffset) , target.transform.position.z), step);
}
void Miss()
{
Destroy(this.gameObject);
}
}
<file_sep>/TableTopLegions_V1/Assets/Systems/VuforiaHacking/PlaceContentFromImageTarget.cs
using System;
using UnityEngine;
using Vuforia;
public class PlaceContentFromImageTarget : MonoBehaviour
{
//This class should replace the default ContentPositioningBehaviour in the PlaneFinder GameObject
//Don't forget to set the OnInteractiveHitTest of the PlaneFinderBehaviour to call this class
//IMPORTANT:
// Be sure to enable Device Tracker and set mode to POSITIONAL in the Vuforia Configuration
public AnchorBehaviour AnchorStage;
public ImageTargetBehaviour ImageTarget;
private PositionalDeviceTracker _deviceTracker;
private bool _anchorSet;
public void Start()
{
var x = new ContentPositioningBehaviour();
var y = x.AnchorStage;
if (AnchorStage == null)
{
Debug.LogWarning("AnchorStage must be specified");
return;
}
if (ImageTarget == null)
{
Debug.LogWarning("Image Target must be specified");
return;
}
AnchorStage.gameObject.SetActive(false);
}
public void Awake()
{
VuforiaARController.Instance.RegisterVuforiaStartedCallback(OnVuforiaStarted);
}
public void OnDestroy()
{
VuforiaARController.Instance.UnregisterVuforiaStartedCallback(OnVuforiaStarted);
}
private void OnVuforiaStarted()
{
_deviceTracker = TrackerManager.Instance.GetTracker<PositionalDeviceTracker>();
}
public void OnInteractiveHitTest(HitTestResult result)
{
if (_anchorSet)
{
//Leave if the anchor has already been set
return;
}
if (result == null || AnchorStage == null)
{
Debug.LogWarning("Hit test is invalid or AnchorStage not set");
return;
}
//Let's go ahead and create the anchor at the position of the hit test
var anchor = _deviceTracker.CreatePlaneAnchor(Guid.NewGuid().ToString(), result);
if (anchor != null)
{
//AnchorStage.transform.SetParent(anchor.transform);
AnchorStage.transform.localPosition = Vector3.zero;
AnchorStage.transform.localRotation = Quaternion.identity;
AnchorStage.gameObject.SetActive(true);
//Make sure that the Image Target is currently tracking
if (ImageTarget.CurrentStatus == TrackableBehaviour.Status.DETECTED ||
ImageTarget.CurrentStatus == TrackableBehaviour.Status.TRACKED ||
ImageTarget.CurrentStatus == TrackableBehaviour.Status.EXTENDED_TRACKED)
{
//Note: If you are handling objects differently, there is an opportunity to optimize this section
var defaultEventHandler = this.ImageTarget.GetComponent<DefaultTrackableEventHandler>();
if (defaultEventHandler != null)
{
defaultEventHandler.OnTrackableStateChanged(TrackableBehaviour.Status.UNKNOWN,
TrackableBehaviour.Status.TRACKED);
}
//Let's move the contents of the image target onto the ground plane
for (var i = 0; i < ImageTarget.transform.childCount; i++)
{
var content = ImageTarget.transform.GetChild(i);
content.SetParent(AnchorStage.transform);
}
}
_anchorSet = true;
}
}
}<file_sep>/TableTopLegions_V1/Assets/DebugPosition.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DebugPosition : MonoBehaviour
{
public TextMesh myText;
void Update ()
{
if(myText)
{
myText.text = transform.position.ToString();
}
}
}
<file_sep>/TableTopLegions_V1/Assets/Systems/CanvasCard.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class CanvasCard : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
public int myID;
public Sprite attackModeIcon;
public Sprite holdModeIcon;
public Image modeIcon;
public Image myHP;
[HideInInspector]
public CanvasManager canvasManager;
[HideInInspector]
public Unit myBuilding;
[HideInInspector]
public Team myTeam;
[HideInInspector]
public HandManager handManager;
[HideInInspector]
public BudgetManager budgetManager;
public GameObject myUnit;
public float VanishTreshold;
public float myCost;
bool canBuy;
GameObject myBuildingGO;
GameObject unitInstance;
GameObject cursor;
GameObject unavalablePortrait;
Transform cardPool = null;
Transform cardHand;
Vector3 originalPos;
GameObject worldPlane;
void Start()
{
Setup();
// OldSetup();
}
void Setup()
{
unavalablePortrait = this.transform.GetChild(0).GetChild(1).gameObject;
cardPool = this.transform.parent;
cardHand = canvasManager.cardHand;
cursor = GameObject.Find("Cursor");
myBuildingGO = myBuilding.gameObject;
if (GameObject.Find("World Plane") != null)
{
worldPlane = GameObject.Find("World Plane");
}
else
{
worldPlane = GameObject.Find("Budget World Plane");
}
}
public void OnBeginDrag(PointerEventData eventData)
{
if(canBuy)
{
if (this.transform.parent == cardHand)
{
originalPos = this.transform.position;
this.transform.SetParent(this.transform.parent.parent);
unitInstance = Instantiate(myUnit);
unitInstance.transform.SetParent(cursor.transform);
unitInstance.transform.localPosition = Vector3.zero;
unitInstance.GetComponent<Unit>().myTeam = myTeam;
unitInstance.GetComponent<Unit>().myGameState = UnitGameState.HasTeam;
unitInstance.SetActive(false);
}
}
}
public void OnDrag(PointerEventData eventData)
{
if(canBuy)
{
this.transform.position = eventData.position;
if (Vector3.Distance(this.transform.position, originalPos) > VanishTreshold)
{
this.transform.GetChild(0).gameObject.SetActive(false);
unitInstance.gameObject.SetActive(true);
}
}
}
public void OnEndDrag(PointerEventData eventData)
{
if(canBuy)
{
if (Vector3.Distance(this.transform.position, originalPos) > VanishTreshold)
{
unitInstance.transform.SetParent(worldPlane.transform);
this.transform.SetParent(cardPool);
this.transform.localScale = new Vector3(1, 1, 1);
this.transform.GetChild(0).gameObject.SetActive(true);
canvasManager.DrawNewCard();
budgetManager.BuyUnit(myCost);
}
else
{
this.transform.SetParent(cardHand);
this.transform.GetChild(0).gameObject.SetActive(true);
Destroy(unitInstance);
}
}
}
public void Resize()
{
this.transform.localScale = new Vector3(1, 1, 1);
}
void Update()
{
if(!budgetManager.CheckBalance(myCost) && !unavalablePortrait.active)
{
unavalablePortrait.SetActive(true);
canBuy = false;
}
else if(budgetManager.CheckBalance(myCost) && unavalablePortrait.active)
{
unavalablePortrait.SetActive(false);
canBuy = true;
}
}
bool BuyThisUnit()
{
return canBuy = budgetManager.BuyUnit(myCost);
}
}
<file_sep>/TableTopLegions_V1/Assets/Systems/RotateCanvas.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RotateCanvas : MonoBehaviour
{
public float damping = 50f;
Camera mainCamera;
void Start()
{
mainCamera = Camera.main;
}
void Update ()
{
Vector3 lookPos = mainCamera.transform.position - transform.position;
lookPos.y = 0;
Quaternion rotation = Quaternion.LookRotation(lookPos);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping);
}
}
<file_sep>/TableTopLegions_V1/Assets/Systems/ARInput.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class ARInput : MonoBehaviour
{
public LayerMask rayCastLayer = 11;
public GameObject cursor;
bool moveCursor = false;
void Start()
{
if(!cursor)
{
cursor = GameObject.Find("Cursor");
}
}
void Update ()
{
MoveCursor();
}
void MoveCursor()
{
if (Input.GetButtonDown("Fire1"))
{
moveCursor = true;
}
if (Input.GetButtonUp("Fire1"))
{
moveCursor = false;
}
if (moveCursor)
{
if (EventSystem.current.IsPointerOverGameObject(0)) // is the touch on the GUI
{
return;
}
else
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 1000f, rayCastLayer))
{
cursor.transform.position = hit.point;
//OldFunctionallity(hit);
}
}
}
}
void OldFunctionallity(RaycastHit hit)
{
GameObject target = hit.transform.gameObject;
target.GetComponent<SpawnManager>().InstanciateChild();
target.GetComponent<CardManager>().Flash();
}
}
<file_sep>/TableTopLegions_V1/Assets/Systems/BudgetManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class BudgetManager : MonoBehaviour
{
Slider budgetSlider;
public float maxBudget = 100f;
public float currentBudget;
public float minBudget = 0f;
public float valuePerSec = 1f;
bool sliderHidden = false;
public List<GameObject> sliderUI = new List<GameObject>();
void Start ()
{
budgetSlider = GetComponent<Slider>();
HideSlider(true);
}
void Update ()
{
if(GameManager.game == GameManager.GameState.GameInProgress)
{
IncreaseBudget();
DisplayBudget();
if(sliderHidden)
{
HideSlider(false);
}
}
}
public bool BuyUnit(float cost)
{
if(cost < currentBudget)
{
currentBudget = currentBudget - cost;
return true;
}
else
{
Debug.Log("Dedut motherfucker");
return false;
}
}
public bool CheckBalance(float cost)
{
if (cost < currentBudget)
{
return true;
}
else
{
return false;
}
}
void IncreaseBudget()
{
if(currentBudget < maxBudget)
{
currentBudget += valuePerSec * Time.deltaTime;
}
}
void DisplayBudget()
{
budgetSlider.value = currentBudget;
}
void HideSlider(bool hide)
{
if(!sliderHidden)
{
sliderHidden = true;
}
else
{
sliderHidden = false;
}
if(hide)
{
foreach (GameObject child in sliderUI)
{
child.gameObject.SetActive(false);
}
this.transform.parent.GetComponent<Image>().enabled = false;
}
else
{
foreach (GameObject child in sliderUI)
{
child.gameObject.SetActive(true);
}
this.transform.parent.GetComponent<Image>().enabled = true;
}
}
}
<file_sep>/TableTopLegions_V1/Assets/Systems/Unit/ColliderManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class ColliderManager : MonoBehaviour
{
[SerializeField]
private Unit myUnit;
public SphereCollider MeleeCollider;
public SphereCollider RangedCollider;
public SphereCollider HitBox;
void Update()
{
if(myUnit)
{
if(MeleeCollider)
{
MeleeCollider.radius = myUnit.m_AttackDistance;
}
if(RangedCollider)
{
RangedCollider.radius = myUnit.m_RangeDistance;
}
}
}
}
<file_sep>/TableTopLegions_V1/Assets/Systems/SpawnManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class SpawnManager : MonoBehaviour
{
public GameObject child;
GameObject worldPlane;
void Start()
{
child = this.transform.GetChild(0).gameObject;
if(GameObject.Find("World Plane") != null)
{
worldPlane = GameObject.Find("World Plane");
}
else
{
worldPlane = GameObject.Find("Budget World Plane");
}
}
public void InstanciateChild()
{
GameObject childInstance = Instantiate(child);
Vector3 position = child.transform.position;
Quaternion rotation = child.transform.rotation;
childInstance.transform.SetParent(worldPlane.transform);
childInstance.transform.position = position;
childInstance.transform.localPosition = new Vector3(childInstance.transform.localPosition.x, 0f, childInstance.transform.localPosition.z);
childInstance.transform.localEulerAngles = new Vector3(0.0f, childInstance.transform.localEulerAngles.y, 0.0f);
if(childInstance.GetComponent<Unit>() != null)
{
childInstance.GetComponent<Unit>().myGameState = UnitGameState.HasNoTeam;
}
}
}
<file_sep>/TableTopLegions_V1/Assets/Systems/WayPointScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WayPointScript : MonoBehaviour
{
public Transform wayPointPosition;
bool hasChekedIn;
GameManager gameManager;
void Update ()
{
if(GameManager.game == GameManager.GameState.GameInProgress && !hasChekedIn)
{
if(gameManager == null)
{
hasChekedIn = true;
gameManager = GameObject.FindGameObjectWithTag("Manager").GetComponent<GameManager>();
gameManager.CheckInWayPoint(wayPointPosition);
}
}
}
void OnTriggerEnter(Collider collider)
{
if(collider.tag == "HitBox")
{
collider.transform.parent.GetComponent<TargetManager>().HavePassedWayPoint();
}
}
}
<file_sep>/TableTopLegions_V1/Assets/Systems/Unit/RangeCollider.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RangeCollider : MonoBehaviour {
SphereCollider myCollder;
public Unit myUnit;
public TargetManager myTargetManager;
void Start ()
{
if (myUnit.myAttackModes == AttackModes.Melee)
{
gameObject.SetActive(false);
}
myCollder = GetComponent<SphereCollider>();
}
void OnTriggerStay(Collider _col)
{
/*
if (myUnit.myTarget != null && myUnit.myUnitStatus == UnitStatus.MovingToTarget)
{
if (_col.gameObject == myUnit.myTarget.gameObject && _col.gameObject.GetComponent<Unit>().myUnitStatus != UnitStatus.Dead)
{
myUnit.SetState(UnitStatus.MeleeAttacking);
}
}
*/
}
void OnTriggerExit(Collider _col)
{
/*
if (_col.transform == myUnit.myTarget)
{
myUnit.SetState(UnitStatus.LookingForTarget);
}
*/
}
}
<file_sep>/TableTopLegions_V1/Assets/Systems/Building.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Building : MonoBehaviour, IKillable, IDamageable<float>
{
public float Health = 1000;
public void Kill()
{
//expload for now
}
public void Damage(float _damageTaken)
{
//decrease health
}
}
<file_sep>/TableTopLegions_V1/Assets/Systems/BuildingDeathFX.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BuildingDeathFX : MonoBehaviour
{
List<GameObject> deathFX = new List<GameObject>();
Unit myUnit;
GameObject unitGraphics;
GameObject unitUI;
void Start ()
{
myUnit = this.transform.parent.GetComponent<Unit>();
foreach(Transform child in this.transform.parent)
{
if(child.name == "Graphics")
{
unitGraphics = child.gameObject;
}
if(child.name == "UnitInfo")
{
unitUI = child.gameObject;
}
}
foreach (Transform child in this.transform)
{
deathFX.Add(child.gameObject);
}
}
public void ReportDeath()
{
unitGraphics.SetActive(false);
unitUI.SetActive(false);
foreach (GameObject fx in deathFX)
{
fx.SetActive(true);
}
}
}
<file_sep>/TableTopLegions_V1/Assets/Systems/Unit/UnitAnimationEvents.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UnitAnimationEvents : MonoBehaviour {
public Unit myUnit;
void Start()
{
myUnit = transform.parent.GetComponent<Unit>();
}
public void Hit()
{
myUnit.myCombatManager.Hit();
}
public void FootR()
{
}
public void FootL()
{
}
void Update ()
{
}
public void Shoot()
{
myUnit.myCombatManager.Shoot();
}
}
<file_sep>/TableTopLegions_V1/Assets/Systems/Unit/AttackRange.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AttackRange : MonoBehaviour
{
private Unit myUnit;
private SphereCollider mySphereCollider;
void Awake ()
{
mySphereCollider = GetComponent<SphereCollider>();
myUnit = GetComponent<Unit>();
}
void OnTriggerEnter(Collider _col)
{
if (myUnit.myTarget != null && myUnit.myUnitStatus == UnitStatus.MovingToTarget)
{
if(_col.transform.tag == "HitBox")
{
if (_col.transform.parent.gameObject == myUnit.myTarget.gameObject && _col.gameObject.GetComponentInParent<Unit>().myUnitStatus != UnitStatus.Dead)
{
if (myUnit.myAttackModes == AttackModes.Melee)
{
myUnit.SetState(UnitStatus.MeleeAttacking);
}
else
{
myUnit.SetState(UnitStatus.RangeAttacking);
}
}
}
}
}
void OnTriggerStay(Collider _col)
{
if (myUnit.myTarget != null && myUnit.myUnitStatus == UnitStatus.MovingToTarget)
{
if(_col.transform.tag == "HitBox")
{
if (_col.transform.parent.gameObject == myUnit.myTarget.gameObject && _col.gameObject.GetComponentInParent<Unit>().myUnitStatus != UnitStatus.Dead)
{
if (myUnit.myAttackModes == AttackModes.Melee)
{
myUnit.SetState(UnitStatus.MeleeAttacking);
}
else
{
myUnit.SetState(UnitStatus.RangeAttacking);
}
}
}
}
}
void OnTriggerExit(Collider _col)
{
if(_col.transform == myUnit.myTarget)
{
myUnit.SetState(UnitStatus.LookingForTarget);
}
}
}
<file_sep>/TableTopLegions_V1/Assets/Systems/Unit/MeleeCollider.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MeleeCollider : MonoBehaviour {
public Unit myUnit;
private SphereCollider mySphereCollider;
void Start()
{
mySphereCollider = GetComponent<SphereCollider>();
}
void OnTriggerStay(Collider _col)
{
/*
if (myUnit.myTarget != null && myUnit.myUnitStatus == UnitStatus.MovingToTarget)
{
if (_col.gameObject == myUnit.myTarget.gameObject && _col.gameObject.GetComponent<Unit>().myUnitStatus != UnitStatus.Dead)
{
myUnit.SetState(UnitStatus.MeleeAttacking);
}
}
*/
}
void OnTriggerExit(Collider _col)
{
/*
if (_col.transform == myUnit.myTarget)
{
myUnit.SetState(UnitStatus.LookingForTarget);
}
*/
}
}
<file_sep>/TableTopLegions_V1/Assets/Systems/WorldPlaneBehaviur.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WorldPlaneBehaviur : MonoBehaviour
{
GameObject child;
void Start ()
{
child = this.transform.GetChild(0).gameObject;
child.SetActive(false);
}
public void PlaneDetected ()
{
child.SetActive(true);
}
}
<file_sep>/TableTopLegions_V1/Assets/Systems/Unit/UnitData.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// This class holds data for the unit and performs no functions.
/// Consider moving some state and status enums to the AI class.
/// </summary>
///
public enum Team {blue, red, none}
//Damage type based on the weapon this unit uses
public enum DamageType{Piercing, Blunt, Slashing, Magic}
//Damage type based on the armour this unit uses
public enum DefenceType{HeavyArmour, MediumArmour, LightArmour}
public enum UnitMode{Attacking, Holding}
public enum UnitStatus{Idle, LookingForTarget, MovingToTarget, Holding, MeleeAttacking, Dead, RangeAttacking }
public enum UnitType{Mounted, Afoot}
public enum AttackModes {Melee, Ranged, MeleeRanged}
public enum UnitGameState { ObservationMode, HasNoTeam, HasTeam}
public class UnitData : MonoBehaviour
{
public int myID;
public UnitGameState myGameState = UnitGameState.ObservationMode;
public Team myTeam;
public DamageType myDamageType;
public DefenceType myDefenceType;
public UnitMode myUnitMode;
public UnitStatus myUnitStatus;
public AttackModes myAttackModes;
public string m_MyName;
public int m_Armour;
public int m_CritChange;
public float m_Health;
public float m_MovementSpeed;
public float m_MeleeSpeed;
public float m_RangedSpeed;
public float m_AttackDistance;
public float m_RangeDistance;
public int m_AttackDamage;
public int m_Aggression;
}
<file_sep>/TableTopLegions_V1/Assets/Systems/Unit/AudioManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AudioManager : MonoBehaviour {
public UnitAudioClips myClips;
void Start () {
myClips = GetComponent<UnitAudioClips>();
}
public void PlayClip(AudioClip[] _clips)
{
AudioSource.PlayClipAtPoint(_clips[Random.Range(0, _clips.Length)], transform.position);
}
}
<file_sep>/TableTopLegions_V1/Assets/Systems/CanvasManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CanvasManager : MonoBehaviour
{
public RectTransform cardPool;
public Transform cardHand;
public Transform upNextCard;
public HandManager handManager;
public BudgetManager budgetManager;
private GameManager gameManager;
public List<GameObject> Units;
private List<GameObject> uiCards = new List<GameObject>();
private Tower tower;
public GameObject winningSign;
public GameObject losingSign;
public GameObject gameEndedSign;
bool gameAllreadyInProgress;
void Start()
{
gameManager = GameObject.FindGameObjectWithTag("Manager").GetComponent<GameManager>();
}
void Update()
{
if(GameManager.game == GameManager.GameState.GameInProgress && !gameAllreadyInProgress)
{
gameAllreadyInProgress = true;
handManager.DealCards();
}
if(GameManager.game == GameManager.GameState.GameEnded && gameAllreadyInProgress)
{
gameAllreadyInProgress = false;
}
}
public void AddCard(GameObject _unit, GameObject _uiCard, Tower _tower, int _ID)
{
tower = _tower;
GameObject uiCard = Instantiate(_uiCard);
_unit.GetComponent<Unit>().UICard = uiCard;
CanvasCard canvasManager = uiCard.GetComponent<CanvasCard>();
canvasManager.myID = _ID;
canvasManager.myBuilding = _unit.GetComponent<Unit>();
canvasManager.canvasManager = this;
canvasManager.budgetManager = budgetManager;
if(_tower.towerColor == Team.blue)
{
uiCard.transform.GetChild(0).GetChild(4).GetComponent<Image>().color = Color.blue;
uiCard.transform.GetComponent<CanvasCard>().myTeam = Team.blue;
}
else if(_tower.towerColor == Team.red)
{
uiCard.transform.GetChild(0).GetChild(4).GetComponent<Image>().color = Color.red;
uiCard.transform.GetComponent<CanvasCard>().myTeam = Team.red;
}
uiCard.transform.SetParent(cardPool);
uiCard.transform.position = Vector3.zero;
uiCard.transform.localScale = new Vector3(1,1,1);
uiCards.Add(uiCard);
}
public void RemoveCard (int _ID)
{
foreach(GameObject card in uiCards)
{
if (card.GetComponent<CanvasCard>().myID == _ID)
{
uiCards.Remove(card);
Destroy(card);
}
}
}
public void ClearAllCards()
{
if(cardPool.transform.childCount > 0)
{
uiCards.Clear();
foreach (Transform child in cardPool)
{
Destroy(child.gameObject);
}
tower.ResetInfluencedUnits();
}
}
public void DrawNewCard()
{
handManager.DrawNewCard();
}
public void PlayerWonGame()
{
winningSign.SetActive(true);
}
public void PlayerLost()
{
losingSign.SetActive(true);
}
public void SimulationOver()
{
gameEndedSign.SetActive(true);
}
}
<file_sep>/TableTopLegions_V1/Assets/Systems/Unit/Unit.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.AI;
/// <summary>
/// FUNCTIONALITY TO ADD: add self to list if not already registered
/// </summary>
///
public enum UnitName { Knight, Archer }
public class Unit : UnitData
{
public UnitName thisUnit;
public bool isBuilding = false;
[SerializeField]
public Transform myTarget;
private Unit targetUnitStatus;
[HideInInspector]
public GameManager myGameManager;
[HideInInspector]
public TargetManager myTargetManager;
[HideInInspector]
public CombatManager myCombatManager;
[HideInInspector]
public AudioManager myAudioManager;
[HideInInspector]
public UnitAudioClips myAudioClips;
public GameObject UICard;
public GameObject UnitPrefab;
[HideInInspector]
public float referenceHP;
private Image UICardHP;
private GameObject InactiveUICard;
private UnitAnimator myUnitAnimator;
private NavMeshAgent myAgent;
private float MeleeTimer;
private float RangedTimer;
public bool doReset;
private GameObject myUnitGO;
void ReferenceGather()
{
myID = 1 - GetInstanceID();
myAudioClips = GetComponent<UnitAudioClips>();
myAudioManager = GetComponent<AudioManager>();
myGameManager = GameObject.FindGameObjectWithTag("Manager").GetComponent<GameManager>();
InactiveUICard = UICard;
referenceHP = m_Health;
if(!isBuilding)
{
myUnitAnimator = GetComponent<UnitAnimator>();
myTargetManager = GetComponent<TargetManager>();
myAgent = GetComponent<NavMeshAgent>();
myCombatManager = GetComponent<CombatManager>();
}
}
void Start()
{
ReferenceGather();
if (myGameState == UnitGameState.HasNoTeam)
{
myGameManager.totalUnits.Add(this.transform);
}
SetState(UnitStatus.Idle);
}
public void Update()
{
ExecuteState();
}
public void SetupUnit()
{
if(myUnitMode == UnitMode.Holding)
{
SetState(UnitStatus.Holding);
}
else
SetState(UnitStatus.Idle);
}
public void ResetUnit()
{
m_Health = 300;
SetState(UnitStatus.LookingForTarget);
myGameManager.totalUnits.Add(this.transform);
}
public void SetState(UnitStatus _unitStatus)
{
myUnitStatus = _unitStatus;
switch (myUnitStatus)
{
case UnitStatus.Idle:
StopAgent();
if(!isBuilding)
myUnitAnimator.Trigger(Anim.Idle);
break;
case UnitStatus.LookingForTarget:
myUnitAnimator.Trigger(Anim.Idle);
StopAgent();
Debug.Log("setting looking for target");
break;
case UnitStatus.MovingToTarget:
Debug.Log("MovingToTarget");
myUnitAnimator.Trigger(Anim.Run);
break;
case UnitStatus.MeleeAttacking:
MeleeTimer = 0;
StopAgent();
break;
case UnitStatus.RangeAttacking:
RangedTimer = 0;
StopAgent();
break;
case UnitStatus.Holding:
StopAgent();
break;
case UnitStatus.Dead:
if(!isBuilding)
{
myUnitAnimator.Trigger(Anim.Death);
myAgent.enabled = false;
}
else
{
foreach(Transform child in this.transform)
{
if(child.name == "DeathFX")
{
child.GetComponent<BuildingDeathFX>().ReportDeath();
}
}
}
m_Health = 0;
if(myTarget != null)
myTarget = null;
myGameManager.ReportDeath(this.transform);
break;
}
}
public void ExecuteState() //Called at update
{
switch (myUnitStatus)
{
case UnitStatus.MeleeAttacking:
MeleeTimer -= Time.deltaTime;
if (myTarget.GetComponent<Unit>().m_Health > 0f)
{
if (MeleeTimer <= 0)
{
myCombatManager.Attack();
MeleeTimer = m_MeleeSpeed;
}
}
if (myTarget.GetComponent<Unit>().myUnitStatus == UnitStatus.Dead)
{
myTarget = null;
SetState(UnitStatus.LookingForTarget);
}
break;
case UnitStatus.RangeAttacking:
RangedTimer -= Time.deltaTime;
if (myTarget.gameObject.GetComponent<Unit>().m_Health > 0f)
{
if (RangedTimer <= 0)
{
myCombatManager.RangedAttack(myTarget.transform);
RangedTimer = m_RangedSpeed;
}
}
if (myTarget.gameObject.GetComponent<Unit>().myUnitStatus == UnitStatus.Dead)
{
myTarget = null;
SetState(UnitStatus.LookingForTarget);
}
break;
case UnitStatus.MovingToTarget:
MoveToTarget();
break;
case UnitStatus.LookingForTarget:
myTarget = null;
if(myTeam == Team.blue)
{
myTarget = myTargetManager.FindClosestEnemy(myGameManager.redTeam, myTeam);
}
else if(myTeam == Team.red)
{
myTarget = myTargetManager.FindClosestEnemy(myGameManager.blueTeam, myTeam);
}
else
{
myTarget = myTargetManager.FindClosestEnemy(myGameManager.totalUnits, myTeam);
}
if (myTarget)
{
targetUnitStatus = myTarget.GetComponent<Unit>();
Debug.Log("SettingMovingTotarget");
SetState(UnitStatus.MovingToTarget);
}
else
{
if(myUnitStatus != UnitStatus.Idle)
{
SetState(UnitStatus.Idle);
}
}
break;
}
}
public void ChangeTeam(Team _team)
{
myTeam = _team;
//change ui colour, the tower manadge the ui color, but maybe we need something for the Unit to?
}
void MoveToTarget()
{
if (myAgent != null && myAgent.isStopped == true)
{
Invoke("RefreshAgent", 2f);
myAgent.isStopped = false;
myAgent.Warp(this.transform.position);
myAgent.SetDestination(myTarget.transform.position);
}
}
void StopAgent()
{
if(myAgent != null && myAgent.isStopped == false)
{
myAgent.isStopped = true;
}
}
void RefreshAgent()
{
myAgent.Warp(this.transform.position);
myAgent.enabled = false;
myAgent.enabled = true;
myAgent.SetDestination(myTarget.transform.position);
Debug.Log("Refreshing Agent");
Invoke("RefreshAgent", 2f);
}
public void RestUICard()
{
UICard = InactiveUICard;
}
}<file_sep>/TableTopLegions_V1/Assets/Systems/Tower.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Tower : MonoBehaviour
{
public int myID;
public Team towerColor;
public List <GameObject> influencedTroops;
private SphereCollider sphereOfInfluence;
private Team none = Team.none;
private CanvasManager canvasManager;
private GameManager gameManager;
private Camera camera;
public GameObject myUI;
public float myUISpeed = 3;
void Start()
{
Setup();
}
void Update()
{
RotateInspectorUI();
}
void Setup()
{
myID = 1 - GetInstanceID();
canvasManager = GameObject.Find("MainCanvas").GetComponent<CanvasManager>();
sphereOfInfluence = GetComponent<SphereCollider>();
gameManager = GameObject.FindGameObjectWithTag("Manager").GetComponent<GameManager>();
camera = Camera.main;
}
void OnTriggerExit(Collider collider)
{
if (collider.gameObject.GetComponent<Unit>() != null)
{
Unit exitingUnit = collider.gameObject.GetComponent<Unit>();
if (GameManager.game != GameManager.GameState.GameInProgress)
{
exitingUnit.ChangeTeam(Team.none);
influencedTroops.Remove(collider.gameObject);
if (gameManager.playedTeam == towerColor)
{
canvasManager.RemoveCard(collider.GetComponent<Unit>().myID);
}
}
}
}
void OnTriggerEnter(Collider collider)
{
if(GameManager.game != GameManager.GameState.GameInProgress)
{
if (collider.transform.tag == "Unit")
{
Unit unit = collider.gameObject.GetComponent<Unit>();
if(unit.myGameState == UnitGameState.HasNoTeam && unit.isBuilding == true)
{
if (unit.myTeam == Team.none && unit.myGameState == UnitGameState.HasNoTeam)
{
unit.ChangeTeam(towerColor);
unit.myGameState = UnitGameState.HasTeam;
}
if (gameManager.playedTeam == towerColor)
{
canvasManager.AddCard(collider.gameObject, collider.gameObject.GetComponent<Unit>().UICard, this, collider.gameObject.GetComponent<Unit>().myID);
}
influencedTroops.Add(collider.gameObject);
}
}
}
}
public void PlayTower()
{
canvasManager.ClearAllCards();
gameManager.PlayerTower(towerColor);
if (gameManager.playedTeam == towerColor)
{
foreach(GameObject unit in influencedTroops)
{
canvasManager.AddCard(unit, unit.gameObject.GetComponent<Unit>().UICard, this, unit.gameObject.GetComponent<Unit>().myID);
}
}
else
{
gameManager.playedTeam = Team.none;
canvasManager.ClearAllCards();
}
}
public void ResetInfluencedUnits()
{
foreach(GameObject unit in influencedTroops)
{
unit.GetComponent<Unit>().RestUICard();
}
}
void RotateInspectorUI()
{
var lookPos = camera.transform.position - myUI.transform.position;
lookPos.y = 0;
var rotation = Quaternion.LookRotation(lookPos);
myUI.transform.rotation = Quaternion.Slerp(myUI.transform.rotation, rotation, Time.deltaTime * myUISpeed);
}
}
<file_sep>/TableTopLegions_V1/Assets/Systems/CardManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CardManager : MonoBehaviour
{
public GameObject cardFlash;
public float animLength = 0.1f;
public void Flash ()
{
cardFlash.SetActive(true);
Invoke("HideFlash", animLength);
}
public void HideFlash()
{
cardFlash.SetActive(false);
}
}
<file_sep>/TableTopLegions_V1/Assets/Systems/VuforiaHacking/GroundPlaneTrackableEventHandler.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Vuforia;
using System;
public class GroundPlaneTrackableEventHandler : DefaultTrackableEventHandler
{
public GameObject AnchorStage;
private PositionalDeviceTracker _deviceTracker;
private GameObject _previousAnchor;
private List<GameObject> trackedObjects = new List<GameObject>();
private GameObject trackingParent;
AnchorInputListenerBehaviour anchorInput;
protected override void Start()
{
base.Start();
if (AnchorStage == null)
{
Debug.Log("AnchorStage must be specified");
return;
}
OnTrackingLost();
}
public void Awake()
{
VuforiaARController.Instance.RegisterVuforiaStartedCallback(OnVuforiaStarted);
}
public void OnDestroy()
{
VuforiaARController.Instance.UnregisterVuforiaStartedCallback(OnVuforiaStarted);
}
private void OnVuforiaStarted()
{
_deviceTracker = TrackerManager.Instance.GetTracker<PositionalDeviceTracker>();
}
protected override void OnTrackingFound()
{
base.OnTrackingFound();
if (trackingParent == null)
{
trackingParent = new GameObject("trackingParent");
trackingParent.transform.SetParent(transform, false);
}
if (transform.childCount > 0)
{
for (int i = 0; i < transform.childCount; i++)
{
trackedObjects.Add(transform.GetChild(i).gameObject);
}
foreach (GameObject trackedObj in trackedObjects)
{
trackedObj.transform.SetParent(trackingParent.transform, true);
}
trackingParent.transform.SetParent(transform.parent, true);
}
trackingParent.transform.position = transform.position;
trackingParent.transform.rotation = transform.rotation;
}
protected override void OnTrackingLost()
{
if (_previousAnchor != null)
{
return;
}
base.OnTrackingLost();
}
public void OnInteractiveHitTest(HitTestResult result)
{
if (_previousAnchor != null)
{
return;
}
if (result == null || AnchorStage == null)
{
Debug.LogWarning("Hit test is invalid or AnchorStage not set");
return;
}
var anchor = _deviceTracker.CreatePlaneAnchor(Guid.NewGuid().ToString(), result);
if (anchor != null)
{
// AnchorStage.transform.parent = anchor.transform;
AnchorStage.transform.localPosition = Vector3.zero;
AnchorStage.transform.localRotation = Quaternion.identity;
AnchorStage.SetActive(true);
}
if (_previousAnchor != null)
{
Destroy(_previousAnchor);
}
//_previousAnchor = anchor;
}
}<file_sep>/TableTopLegions_V1/Assets/Systems/MoveTowardsTarget.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveTowardsTarget : MonoBehaviour {
public Transform target;
public float speed = 5;
void Update ()
{
float step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, new Vector3(target.transform.position.x, target.transform.position.y, target.transform.position.z), step);
}
}
<file_sep>/TableTopLegions_V1/Assets/Systems/Unit/IngameHUD.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class IngameHUD : MonoBehaviour
{
public Unit myUnit;
[Space(30)]
private float HPFill;
public Image healthDisplay;
public Image teamDisplay;
private GameObject InactiveUICard;
void Update ()
{
UpdateHPUI();
}
void UpdateHPUI()
{
HPFill = (myUnit.m_Health / myUnit.referenceHP);
healthDisplay.fillAmount = HPFill;
if (myUnit.myGameState == UnitGameState.HasTeam)
{
if (myUnit.myTeam == Team.blue)
{
teamDisplay.color = Color.cyan;
}
else if (myUnit.myTeam == Team.red)
{
teamDisplay.color = Color.red;
}
else
{
teamDisplay.color = Color.grey;
}
}
}
}
<file_sep>/TableTopLegions_V1/Assets/Systems/Unit/CombatManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CombatManager : MonoBehaviour
{
private Unit myUnit;
private UnitAnimator myUnitAnimator;
public GameObject projectile;
public Transform projectileSocket;
private Transform target;
private void Start()
{
myUnit = GetComponent<Unit>();
myUnitAnimator = GetComponent<UnitAnimator>();
}
public void Attack()
{
myUnitAnimator.Trigger(Anim.MeleeAttack);
}
public void RangedAttack(Transform _target)
{
target = _target;
myUnitAnimator.Trigger(Anim.RangedAttack);
}
public void Hit() //Called by an animation event
{
if (myUnit.myTarget)
{
myUnit.myTarget.GetComponent<CombatManager>().TakeDamage(DamageCalc.Hit(myUnit.m_AttackDamage, myUnit.m_CritChange, myUnit.myDamageType, myUnit.myTarget.GetComponent<Unit>().m_Armour));
myUnit.myAudioManager.PlayClip(myUnit.myAudioClips.BluntHits);
}
}
public void Shoot() //Called by an animation event
{
projectileSocket.LookAt(target);
GameObject projectileInstance = Instantiate(projectile, projectileSocket);
ProjectileManager projectileManager = projectileInstance.GetComponent<ProjectileManager>();
projectileManager.target = target;
projectileManager.myCombatManager = this;
projectileInstance.transform.SetParent(null);
}
public void TakeDamage(float _damage)
{
myUnit.m_Health -= _damage;
if (myUnit.m_Health <= 0 && myUnit.myUnitStatus != UnitStatus.Dead)
{
myUnit.SetState(UnitStatus.Dead);
myUnit.myAudioManager.PlayClip(myUnit.myAudioClips.BluntKills);
myUnit.myAudioManager.PlayClip(myUnit.myAudioClips.Deaths);
}
}
}
<file_sep>/TableTopLegions_V1/Assets/Systems/Unit/UnitAnimator.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum Anim{Run, MeleeAttack, Death, Idle, RangedAttack};
public class UnitAnimator : MonoBehaviour
{
public Animator myAnimator;
private Transform child;
bool WaitFrame;
//Hashing the variables saves us the performance of passing strings
static readonly int anim_Attack = Animator.StringToHash("Attack");
static readonly int anim_Run = Animator.StringToHash("Run");
static readonly int anim_Death = Animator.StringToHash("Death");
static readonly int anim_Idle = Animator.StringToHash("Idle");
static readonly int anim_RangedAttack = Animator.StringToHash("RangedAttack");
void Start()
{
child = this.transform.GetChild(0);
Invoke("KeepChildInPlace", 1f);
}
void KeepChildInPlace() // this is because the nac mesh agent collides with enemyes and gets pushed alitle.
{
child.transform.localPosition = Vector3.zero;
Invoke("KeepChildInPlace", 1f);
}
public void Trigger(Anim _anim)
{
StartCoroutine(TriggerOneAtTime(_anim));
}
IEnumerator TriggerOneAtTime(Anim _anim)
{
ResestAllTriggers();
switch (_anim)
{
case Anim.Run:
myAnimator.SetTrigger(anim_Run);
break;
case Anim.MeleeAttack:
myAnimator.SetTrigger(anim_Attack);
break;
case Anim.Death:
myAnimator.SetTrigger(anim_Death);
break;
case Anim.Idle:
myAnimator.SetTrigger(anim_Idle);
break;
case Anim.RangedAttack:
myAnimator.SetTrigger(anim_RangedAttack);
break;
}
yield return null;
}
void ResestAllTriggers()
{
foreach(AnimatorControllerParameter param in myAnimator.parameters)
{
myAnimator.ResetTrigger(param.name);
}
}
}
<file_sep>/TableTopLegions_V1/Assets/Systems/TargetIndicator.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TargetIndicator : MonoBehaviour
{
Unit myUnit;
LineRenderer targetIndicator;
void Start ()
{
myUnit = this.transform.parent.GetComponent<Unit>();
targetIndicator = this.GetComponent<LineRenderer>();
}
void Update ()
{
if (myUnit.myUnitStatus == UnitStatus.Dead)
{
targetIndicator.SetPosition(0, this.transform.position);
targetIndicator.SetPosition(1, this.transform.position);
return;
}
if (myUnit.myTarget == null)
{
targetIndicator.SetPosition(0, this.transform.position);
targetIndicator.SetPosition(1, this.transform.position);
return;
}
else
{
targetIndicator.SetPosition(1, myUnit.myTarget.transform.position);
targetIndicator.SetPosition(0, this.transform.position);
}
}
}
<file_sep>/TableTopLegions_V1/Assets/Systems/DebugLogRecever.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DebugLogRecever : MonoBehaviour
{
public Text debugLog;
public string output = "";
public string stack = "";
void OnEnable()
{
Application.logMessageReceived += HandleLog;
}
void OnDisable()
{
Application.logMessageReceived -= HandleLog;
}
void HandleLog(string logString, string stackTrace, LogType type)
{
Print(output + "/n" + logString);
stack = stackTrace;
}
void Print (string input)
{
debugLog.text = input;
}
}
<file_sep>/README.md
# Coast-Light-Game<file_sep>/TableTopLegions_V1/Assets/Systems/Unit/AI.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class AI : MonoBehaviour
{
private Unit myUnit;
private NavMeshAgent myAgent;
private SphereCollider attackRange;
private CombatManager combatManagaer;
private bool isBuilding;
void Start()
{
myUnit = GetComponent<Unit>();
myAgent = GetComponent<NavMeshAgent>();
combatManagaer = GetComponent<CombatManager>();
if(myUnit.isBuilding)
{
isBuilding = true;
}
}
void Update()
{
if(!isBuilding)
{
UnitAI();
}
else
{
BuildingAI();
}
}
void BuildingAI()
{
if (GameManager.game == GameManager.GameState.GameInProgress)
{
if(myUnit.m_Health < 0 && myUnit.myUnitStatus != UnitStatus.Dead)
{
myUnit.SetState(UnitStatus.Dead);
}
if(myUnit.myUnitStatus != UnitStatus.Dead)
{
myUnit.SetState(UnitStatus.Idle);
}
}
}
void UnitAI()
{
if (GameManager.game == GameManager.GameState.GameInProgress)
{
if (myUnit.myUnitStatus != UnitStatus.Dead)
{
myAgent.enabled = true;
if (myUnit.myTarget == null)
{
myUnit.SetState(UnitStatus.LookingForTarget);
}
else if(myUnit.myTarget.GetComponent<Unit>() == null && myUnit.myUnitStatus != UnitStatus.MovingToTarget)
{
myUnit.SetState(UnitStatus.MovingToTarget);
}
else if(myUnit.myTarget.GetComponent<Unit>() != null && myUnit.myTarget.GetComponent<Unit>().myUnitStatus == UnitStatus.Dead)
{
myUnit.SetState(UnitStatus.LookingForTarget);
}
else
{
if (myUnit.myUnitStatus == UnitStatus.LookingForTarget)
{
myUnit.SetState(UnitStatus.MovingToTarget);
}
}
}
else
{
myAgent.enabled = false;
}
}
}
void OnTriggerEnter(Collider enemy)
{
if(myUnit.myUnitStatus != UnitStatus.Dead)
{
if (myUnit.isBuilding == false)
{
if(enemy.transform.parent != null)
{
if (enemy.transform.parent.GetComponent<Unit>() != null)
{
if (enemy.transform.parent.GetComponent<Unit>().myTeam != myUnit.myTeam)
{
if (enemy.transform.tag == "HitBox")
{
if (myUnit.myAttackModes == AttackModes.Melee)
{
myUnit.myTarget = enemy.transform.parent;
myUnit.SetState(UnitStatus.MeleeAttacking);
}
else if (myUnit.myAttackModes == AttackModes.Ranged)
{
myUnit.myTarget = enemy.transform.parent;
myUnit.SetState(UnitStatus.RangeAttacking);
}
else
{
myUnit.SetState(UnitStatus.RangeAttacking);
}
}
}
}
}
}
}
}
}<file_sep>/TableTopLegions_V1/Assets/Content/Audio/DestroyAfterAudio.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DestroyAfterAudio : MonoBehaviour {
public AudioSource audioSource;
public bool destroyAfterTime = false; //do we destroy after a set amount of time rather than the length of the audio?
public float timeUntilDestroy = 2f;
// Use this for initialization
void Start () {
if (audioSource == null){ //if the audio source hasn't been assigned, try assign it from the gameObject
audioSource = GetComponent<AudioSource> ();
}
if (destroyAfterTime) {
Destroy (this.gameObject, timeUntilDestroy); //destroy this gameObject after time if that boolean is true;
}
}
// Update is called once per frame
void Update () {
if (!destroyAfterTime) {
if (!audioSource.isPlaying) {
Destroy (this.gameObject); //if the audio clip has finished or there isn't one, destroy this gameObject
}
}
}
}
| 4f0598766dafb4d088129e7016c6e461a6cd0ddc | [
"Markdown",
"C#"
] | 43 | C# | VladStroganoff/Coast-Light-Game | a2b98496f9dd6275e3660b4b775a8d781be4e5b9 | bbcd5a61f454a773e959b152e684a4c9dd916987 |
refs/heads/master | <file_sep><?php
echo "hello from inside ahmed page" ;
echo "hello from the other side "; | a323f7eb41a3697491bc19e0a96d609bec70a90b | [
"PHP"
] | 1 | PHP | alaaamohammed/projet_test | c0af2de251f2e31fd9a79b226e939ced0bfb0190 | b9d992fdbbb932bedbebf31d177fe73e9fb4a00b |
refs/heads/master | <repo_name>macjoan/ExData_Plotting1<file_sep>/plot2.R
# REading the file andsaving in a R object mfor power consumption data
powerDF <- read.table("household_power_consumption.txt", header = TRUE, sep = ";", na.strings = "?")
powerDF <- subset(powerDF, powerDF$Date=="1/2/2007" | powerDF$Date == "2/2/2007")
# Convert date an time as Date and time type
powerDF$Date <- as.Date(powerDF$Date, format="%d/%m/%Y")
powerDF$Time <- strptime(powerDF$Time, format="%H:%M:%S")
powerDF[powerDF$Date=="2007-02-01", "Time"] <- format(powerDF[powerDF$Date=="2007-02-01", "Time"],
"2007-02-01 %H:%M:%S")
powerDF[powerDF$Date=="2007-02-02", "Time"] <- format(powerDF[powerDF$Date=="2007-02-02", "Time"],
"2007-02-02 %H:%M:%S")
#Making the plot 2
png("plot2.png", width=480, height=480)
with(powerDF, plot(Time, Global_active_power, xlab = "", ylab = "Global Active Power (kilowatts)", type = "l"))
title(main="Global Active Power Vs Time")
dev.off()<file_sep>/plot4.R
# REading the file andsaving in a R object mfor power consumption data
powerDF <- read.table("household_power_consumption.txt", header = TRUE, sep = ";", na.strings = "?")
powerDF <- subset(powerDF, powerDF$Date=="1/2/2007" | powerDF$Date == "2/2/2007")
# Convert date an time as Date and time type
powerDF$Date <- as.Date(powerDF$Date, format="%d/%m/%Y")
powerDF$Time <- strptime(powerDF$Time, format="%H:%M:%S")
powerDF[powerDF$Date=="2007-02-01", "Time"] <- format(powerDF[powerDF$Date=="2007-02-01", "Time"],
"2007-02-01 %H:%M:%S")
powerDF[powerDF$Date=="2007-02-02", "Time"] <- format(powerDF[powerDF$Date=="2007-02-02", "Time"],
"2007-02-02 %H:%M:%S")
#makikng the plot 4
png("plot4.png", width=480, height=480)
par(mfrow=c(2,2))
plot(powerDF$Time, powerDF$Global_active_power, type = "l", xlab = "", ylab = "Global Activity Power")
plot(powerDF$Time, powerDF$Voltage, type = "l", xlab = "datetime", ylab = "Voltage")
plot(powerDF$Time, powerDF$Sub_metering_1, type = "l", xlab = "", ylab = "Energy Sub metering")
lines(powerDF$Time, powerDF$Sub_metering_2, col = "red")
lines(powerDF$Time, powerDF$Sub_metering_3, col = "blue")
legend("topright", col=c("black","red","blue")
, c("Sub_metering_1 ","Sub_metering_2 ", "Sub_metering_3 ")
, lty=c(1,1)
, bty="n"
, cex = 0.5)
plot(powerDF$Time, powerDF$Global_reactive_power, type = "l", xlab = "datetime", ylab = "Global reactive power")
dev.off()
<file_sep>/plot1.R
# REading the file andsaving in a R object mfor power consumption data
powerDF <- read.table("household_power_consumption.txt", header = TRUE, sep = ";", na.strings = "?")
powerDF <- subset(powerDF, powerDF$Date=="1/2/2007" | powerDF$Date == "2/2/2007")
#making an histagram
png("plot1.png", width=480, height=480)
hist(powerDF$Global_active_power, col = "red", main="Global Active Power",xlab="Global Active Power(kilowatts)")
dev.off()<file_sep>/plot3.R
# REading the file andsaving in a R object mfor power consumption data
powerDF <- read.table("household_power_consumption.txt", header = TRUE, sep = ";", na.strings = "?")
powerDF <- subset(powerDF, powerDF$Date=="1/2/2007" | powerDF$Date == "2/2/2007")
# Convert date an time as Date and time type
powerDF$Date <- as.Date(powerDF$Date, format="%d/%m/%Y")
powerDF$Time <- strptime(powerDF$Time, format="%H:%M:%S")
powerDF[powerDF$Date=="2007-02-01", "Time"] <- format(powerDF[powerDF$Date=="2007-02-01", "Time"],
"2007-02-01 %H:%M:%S")
powerDF[powerDF$Date=="2007-02-02", "Time"] <- format(powerDF[powerDF$Date=="2007-02-02", "Time"],
"2007-02-02 %H:%M:%S")
#makikng the plot 3
png("plot3.png", width=480, height=480)
plot(powerDF$Time, powerDF$Sub_metering_1, type="n", xlab="", ylab="Energy sub metering")
lines(powerDF$Time, powerDF$Sub_metering_1)
lines(powerDF$Time, powerDF$Sub_metering_2, col = "red")
lines(powerDF$Time, powerDF$Sub_metering_3, col = "blue")
legend("topright", lty=1, col=c("black","red","blue"),
legend=c("Sub_metering_1","Sub_metering_2","Sub_metering_3"))
title(main="Energy sub-metering")
dev.off()
| 00de211efeabe8582a307c517f83ed0f3dcd9e98 | [
"R"
] | 4 | R | macjoan/ExData_Plotting1 | bdc78ce47bd05e579e7692bcb507112ddce5d2b6 | ff91a22f1b71177d67cae6aa32972885f199c79b |
refs/heads/master | <repo_name>kleberfranklin/SGPatri<file_sep>/test/teste/normalizacao/Padronizar.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package teste.normalizacao;
/**
*
* @author d732229
*/
public class Padronizar {
public int pkInt;
public String txtDados;
public Padronizar() {
}
public int getPkInt() {
return pkInt;
}
public void setPkInt(int pkInt) {
this.pkInt = pkInt;
}
public String getTxtDados() {
return txtDados;
}
public void setTxtDados(String txtDados) {
this.txtDados = txtDados;
}
}
<file_sep>/src/java/br/com/Modelo/SetorDAO.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.Modelo;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author d732229
*/
public class SetorDAO {
//Atrituto
private final Connection connection;
//Construtor
public SetorDAO() {
this.connection = new FabricaConexao().getConnetion();
}
//METODO utilizado para inserir uma nova Setor no BANCO
public void cSetor(Setor st) throws SQLException{
PreparedStatement stmt = null;
String sql = "INSERT INTO tbl_setor "
+"(fk_divisao, sg_setor, nm_setor, nm_nrsimproc, nm_nrsei, nm_login, dthr_atualizacao) "
+"VALUES (?,?,?,?,?,?,?)";
try{
stmt = connection.prepareStatement(sql);
stmt.setInt(1, st.getFkDivisao());
stmt.setString(2, st.getSgSetor());
stmt.setString(3, st.getNmSetor());
stmt.setString(4, st.getNmNrSimprocSetor());
stmt.setString(5, st.getNmNrSei());
stmt.setString(6, st.getNmLogin());
stmt.setTimestamp(7,java.sql.Timestamp.valueOf(java.time.LocalDateTime.now()));
stmt.execute();
}catch (SQLException e){
throw new RuntimeException(e);
}finally{
stmt.close();
connection.close();
}
}
//MEDOTO utilizado para realizar a alteração das informações do Setor
public void upSetor(Setor st) throws SQLException{
PreparedStatement stmt = null;
String sql = "UPDATE tbl_setor "
+ "SET sg_setor=?, nm_setor=?, nm_nrsimproc=?, nm_login=?, dthr_atualizacao=?, fk_divisao=?, nm_nrsei=? "
+ "WHERE id_setor = ?";
try{
stmt = connection.prepareStatement(sql);
stmt.setString(1, st.getSgSetor());
stmt.setString(2, st.getNmSetor());
stmt.setString(3, st.getNmNrSimprocSetor());
stmt.setString(4, st.getNmLogin());
stmt.setTimestamp(5,java.sql.Timestamp.valueOf(java.time.LocalDateTime.now()));
stmt.setInt(6, st.getFkDivisao());
stmt.setString(7, st.getNmNrSei());
stmt.setInt(8, st.getPkSetor());
stmt.execute();
}catch (SQLException e){
throw new RuntimeException(e);
}finally{
stmt.close();
connection.close();
}
}
//METODO utilizado para retornar as informação de um Setor/Núcleo
public Setor detalheSetor(int pkSetor) throws SQLException{
PreparedStatement stmt = null;
ResultSet rs = null;
Setor st = new Setor();
String sql = "SELECT fk_divisao, id_setor, sg_divisao, nm_divisao, sg_setor, nm_setor, "
+ "nm_nrsimproc, nm_nrsei, nm_login, dthr_atualizacao "
+"FROM vw_setorcompleto "
+"WHERE id_setor = ?";
try{
stmt = connection.prepareStatement(sql);
stmt.setInt(1, pkSetor);
rs = stmt.executeQuery();
if(rs.next()){
st.setFkDivisao(rs.getInt("fk_divisao"));
st.setPkSetor(rs.getInt("id_setor"));
st.setSgDivisao(rs.getString("sg_divisao"));
st.setNmDivisao(rs.getString("nm_divisao"));
st.setSgSetor(rs.getString("sg_setor"));
st.setNmSetor(rs.getString("nm_setor"));
st.setNmNrSimprocSetor(rs.getString("nm_nrsimproc"));
st.SetNmNrSei(rs.getString("nm_nrsei"));
st.setNmLogin(rs.getString("nm_login"));
st.setDthrAtualiza(rs.getString("dthr_atualizacao"));
}
return st;
}catch (SQLException e){
throw new RuntimeException(e);
}finally{
rs.close();
stmt.close();
connection.close();
}
}
//METODO lista os setor de um Divisão, utilizado no o select da pagina cadastro e alteração de ususário
public List<Setor> selecSetor(int pkDivisao) throws SQLException {
PreparedStatement stmt = null;
ResultSet rs = null;
List<Setor> stLista = new ArrayList<Setor>();
String sql = ("SELECT id_setor, sg_setor, nm_setor "
+"FROM tbl_setor "
+ "WHERE fk_divisao = ?");
try {
stmt = connection.prepareStatement(sql);
stmt.setInt(1, pkDivisao);
rs = stmt.executeQuery();
while (rs.next()){
Setor st = new Setor();
st.setPkSetor(rs.getInt("id_setor"));
st.setSgSetor(rs.getString("sg_setor"));
st.setNmSetor(rs.getString("nm_setor"));
stLista.add(st);
}
return stLista;
} catch (SQLException e) {
throw new RuntimeException(e);
}finally{
rs.close();
stmt.close();
connection.close();
}
}
//METODO lista os setor de pesquisa e paginado
public List<Setor> listSetor(int qtLinha, int offset, String q) throws SQLException{
PreparedStatement stmt = null;
ResultSet rs = null;
List<Setor> setorList = new ArrayList<Setor>();
String sql = ("SELECT id_setor, fk_divisao, sg_divisao, nm_divisao, sg_setor, nm_setor, nm_nrSimproc, nm_login, dthr_atualizacao "
+"FROM vw_setorcompleto "
+"WHERE (sg_setor ILIKE ? OR nm_setor ILIKE ? ) "
+"ORDER BY sg_divisao, sg_setor ASC "
+"LIMIT ? OFFSET ? ");
try{
stmt = connection.prepareStatement(sql);
stmt.setString(1,'%'+q+'%');
stmt.setString(2,'%'+q+'%');
stmt.setInt(3, qtLinha);
stmt.setInt(4, offset);
rs = stmt.executeQuery();
while (rs.next()){
Setor st = new Setor();
st.setPkSetor(rs.getInt("id_setor"));
st.setFkDivisao(rs.getInt("fk_divisao"));
st.setSgDivisao(rs.getString("sg_divisao"));
st.setNmDivisao(rs.getString("nm_divisao"));
st.setSgSetor(rs.getString("sg_setor"));
st.setNmSetor(rs.getString("nm_setor"));
st.setNmNrSimprocSetor(rs.getString("nm_nrSimproc"));
st.setNmLogin(rs.getString("nm_login"));
st.setDthrAtualiza(rs.getString("dthr_atualizacao"));
setorList.add(st);
}
return setorList;
} catch (SQLException e){
throw new RuntimeException (e);
}finally{
rs.close();
stmt.close();
connection.close();
}
}
//Metodo de quantidade de linhas
public int qdSetor (String q) throws SQLException{
PreparedStatement stmt = null;
ResultSet rs = null;
int total = 0;
String sql = ("SELECT COUNT(*) as total "
+"FROM vw_setorcompleto "
+"WHERE (sg_setor ILIKE ? OR nm_setor ILIKE ? ) ");
try{
stmt = connection.prepareStatement(sql);
stmt.setString(1, '%'+q+'%');
stmt.setString(2, '%'+q+'%');
rs = stmt.executeQuery();
if(rs.next()){
total = rs.getInt("total");
}
return total;
}catch (SQLException e){
throw new RuntimeException(e);
}finally{
rs.close();
stmt.close();
connection.close();
}
}
}
<file_sep>/src/java/br/com/Modelo/DivisaoDAO.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.Modelo;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author d732229
*/
public class DivisaoDAO {
//Atrituto
private final Connection connection;
//Construtor
public DivisaoDAO() {
this.connection = new FabricaConexao().getConnetion();
}
//METODO utilizado para inserir uma nova Divisao no BANCO
public void cDivisao(Divisao dv) throws SQLException{
PreparedStatement stmt = null;
String sql = "INSERT INTO tbl_divisao "
+ "(sg_divisao, nm_divisao, nm_nrsimproc, dthr_atualizacao, nm_login, nm_nrsei) "
+ "VALUES (?, ?, ?, ?, ?, ?)";
try{
stmt = connection.prepareStatement(sql);
stmt.setString(1, dv.getSgDivisao());
stmt.setString(2, dv.getNmDivisao());
stmt.setString(3, dv.getNmNrSimproc());
stmt.setTimestamp(4, java.sql.Timestamp.valueOf(java.time.LocalDateTime.now()));
stmt.setString(5, dv.getNmLogin());
stmt.setString(6, dv.getnmNrSei());
stmt.execute();
}catch (SQLException e){
throw new RuntimeException(e);
}finally{
stmt.close();
connection.close();
}
}
//MEDOTO utilizado para realizar a alteração das informações da Divisão
public void upDivisao(Divisao dv) throws SQLException{
PreparedStatement stmt = null;
String sql = "UPDATE tbl_divisao "
+ "SET sg_divisao = ?, nm_divisao = ?, nm_nrsimproc = ?, dthr_atualizacao = ?, nm_login = ?, nm_nrsei = ? "
+ "WHERE id_divisao = ?";
try{
stmt = connection.prepareStatement(sql);
stmt.setString(1, dv.getSgDivisao());
stmt.setString(2, dv.getNmDivisao());
stmt.setString(3, dv.getNmNrSimproc());
stmt.setTimestamp(4, java.sql.Timestamp.valueOf(java.time.LocalDateTime.now()));
stmt.setString(5, dv.getNmLogin());
stmt.setString(6, dv.getnmNrSei());
stmt.setInt(7, dv.getPkDivisao());
stmt.execute();
}catch(SQLException e){
throw new RuntimeException(e);
}finally{
stmt.close();
connection.close();
}
}
//METODO retorna as informações de um Divisão
public Divisao detalheDivisao(int pkDivisao) throws SQLException{
PreparedStatement stmt = null;
ResultSet rs = null;
Divisao dv = new Divisao();
String sql = "SELECT id_divisao, sg_divisao, nm_divisao, nm_nrsimproc, nm_nrsei, dthr_atualizacao, nm_login "
+ "FROM tbl_divisao "
+ "WHERE id_divisao = ?";
try {
stmt = connection.prepareStatement(sql);
stmt.setInt(1, pkDivisao);
rs = stmt.executeQuery();
if (rs.next()){
dv.setPkDivisao(rs.getInt("id_divisao"));
dv.setSgDivisao(rs.getString("sg_divisao"));
dv.setNmDivisao(rs.getString("nm_divisao"));
dv.setNmNrSimproc(rs.getString("nm_nrsimproc"));
dv.setNmNrSei(rs.getString("nm_nrsei"));
dv.setDthrAtualizacao(rs.getString("dthr_atualizacao"));
dv.setNmLogin(rs.getString("nm_login"));
}
return dv;
} catch (SQLException e) {
throw new RuntimeException(e);
}finally{
stmt.close();
// connection.close();
}
}
//METODO utilizado para lista as divisões paginada e realiza pesquisa por sigla e nome da divisão
public List<Divisao> listDivisao(int qtdLinha, int offset, String q) throws SQLException {
PreparedStatement stmt = null;
ResultSet rs = null;
List<Divisao> divLista = new ArrayList<Divisao>();
String sql = "SELECT id_divisao, sg_divisao, nm_divisao, nm_nrSimproc, nm_nrsei, nm_login, dthr_atualizacao "
+ "FROM tbl_divisao "
+ "WHERE (sg_divisao ILIKE ? or nm_divisao ILIKE ?) "
+ "ORDER BY sg_divisao ASC "
+ "LIMIT ? OFFSET ?";
try {
stmt = connection.prepareStatement(sql);
stmt.setString(1,'%'+q+'%');
stmt.setString(2,'%'+q+'%');
stmt.setInt(3, qtdLinha);
stmt.setInt(4, offset);
rs = stmt.executeQuery();
while (rs.next()){
Divisao di = new Divisao();
di.setPkDivisao(rs.getInt("id_divisao"));
di.setSgDivisao(rs.getString("sg_divisao"));
di.setNmDivisao(rs.getString("nm_divisao"));
di.setNmNrSimproc(rs.getString("nm_nrSimproc"));
di.setNmNrSei(rs.getString("nm_nrsei"));
di.setNmLogin(rs.getString("nm_login"));
di.setDthrAtualizacao(rs.getString("dthr_atualizacao"));
divLista.add(di);
}
return divLista;
} catch (SQLException e) {
throw new RuntimeException(e);
}finally{
rs.close();
stmt.close();
connection.close();
}
}
//METODO uilizado para retornar a quantidade divisao cadastradas na pesquisa por nome ou sigla
public int qtdDivisao(String q) throws SQLException{
PreparedStatement stmt = null;
ResultSet rs = null;
int total = 0;
String sql = "SELECT COUNT(*) as total "
+ "FROM tbl_divisao "
+ "WHERE (sg_divisao ILIKE ? or nm_divisao ILIKE ? )";
try{
stmt = connection.prepareStatement(sql);
stmt.setString(1,'%'+q+'%');
stmt.setString(2,'%'+q+'%');
rs = stmt.executeQuery();
if(rs.next()){
total = rs.getInt("total");
}
return total;
}catch (SQLException e) {
throw new RuntimeException(e);
}finally{
rs.close();
stmt.close();
connection.close();
}
}
//METODO utilizado para lista as Divisçoes, utilizado nos campos select da pagina cadastro e alteração de usuário
public List<Divisao> selectLisDivisao() throws SQLException{
PreparedStatement stmt = null;
ResultSet rs = null;
List<Divisao> divLista = new ArrayList<Divisao>();
String sql = "SELECT id_divisao, sg_divisao, nm_divisao "
+ "FROM tbl_divisao "
+ "ORDER BY sg_divisao";
try{
stmt = connection.prepareStatement(sql);
rs = stmt.executeQuery();
while(rs.next()){
Divisao dv = new Divisao();
dv.setPkDivisao(rs.getInt("id_divisao"));
dv.setSgDivisao(rs.getString("sg_divisao"));
dv.setNmDivisao(rs.getString("nm_divisao"));
divLista.add(dv);
}
stmt.executeQuery();
return divLista;
}catch(SQLException e){
throw new RuntimeException(e);
}finally{
rs.close();
stmt.close();
connection.close();
}
}
}
<file_sep>/src/java/br/com/Controle/CatAutoCessaoDetalhe.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.Controle;
import br.com.Modelo.CatAutoCessao;
import br.com.Modelo.CatAutoCessaoDAO;
import br.com.Modelo.Logica;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author d732229
*/
public class CatAutoCessaoDetalhe implements Logica {
@Override
public String executa(HttpServletRequest req,
HttpServletResponse res) throws Exception {
//Atributo
int pkCatAutoCessao;
String execucao;
//Carregando os atributos com as informações do formulário
pkCatAutoCessao = Integer.parseInt(req.getParameter("pkCatAutoCessao"));
execucao = req.getParameter("execucao");
//Consulta no banco e populando o objeto
CatAutoCessaoDAO catautoDAO = new CatAutoCessaoDAO();
CatAutoCessao catauto = catautoDAO.detalheCatAuto(pkCatAutoCessao);
req.setAttribute("catauto", catauto);
req.setAttribute("execucao", execucao);
return "CatAutoCessaoCRU.jsp";
}
}
<file_sep>/build/generated/src/org/apache/jsp/include/nav_jsp.java
package org.apache.jsp.include;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class nav_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.List<String> _jspx_dependants;
private org.glassfish.jsp.api.ResourceInjector _jspx_resourceInjector;
public java.util.List<String> getDependants() {
return _jspx_dependants;
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
_jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("<div id=\"sidebar\" class=\"sidebar responsive ace-save-state\">\r\n");
out.write(" <ul class=\"nav nav-list\">\r\n");
out.write(" <li class=\"\">\r\n");
out.write(" <a href=\"ControllerServlet?acao=Dashborad\">\r\n");
out.write(" <i class=\"menu-icon fa fa-tachometer\"></i>\r\n");
out.write(" <span class=\"menu-text\"> Dashboard </span>\r\n");
out.write(" </a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" </li>\r\n");
out.write(" \r\n");
out.write("<!-- Menu Gabinete-->\r\n");
out.write(" <li class=\"\">\r\n");
out.write(" <a href=\"#\" class=\"dropdown-toggle\" title=\"Gabinete da Coordenadoria\">\r\n");
out.write(" <i class=\"menu-icon fa fa-folder\"></i>\r\n");
out.write(" <span class=\"menu-text\">Gabinete</span>\r\n");
out.write(" <b class=\"arrow fa fa-angle-down\"></b>\r\n");
out.write(" </a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" <ul class=\"submenu\">\r\n");
out.write(" <li class=\"\">\r\n");
out.write(" <a href=\"#\" title=\"Gestão de Pessoas\">\r\n");
out.write(" <i class=\"menu-icon fa fa-caret-right\"></i> Gestão de Pessoas\r\n");
out.write(" </a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" </li>\r\n");
out.write(" <li class=\"\">\r\n");
out.write(" <a href=\"#\" title=\"Protocolo\">\r\n");
out.write(" <i class=\"menu-icon fa fa-caret-right\"></i> Protocolo \r\n");
out.write(" </a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" </li>\r\n");
out.write(" <li class=\"\">\r\n");
out.write(" <a href=\"#\" title=\"Autuação de Processos\">\r\n");
out.write(" <i class=\"menu-icon fa fa-caret-right\"></i>Autuação Processos\r\n");
out.write(" </a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" </li>\r\n");
out.write(" \r\n");
out.write(" <li class=\"\">\r\n");
out.write(" <a href=\"#\" title=\"Comissão Municipal do Patrimônio Imobiliário\">\r\n");
out.write(" <i class=\"menu-icon fa fa-caret-right\"></i> CMPT\r\n");
out.write(" </a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" </li>\r\n");
out.write(" </ul>\r\n");
out.write(" </li>\r\n");
out.write(" \r\n");
out.write("<!-- Menu DDPI -->\r\n");
out.write(" <li class=\"\">\r\n");
out.write(" <a href=\"#\" class=\"dropdown-toggle\" title=\"Divisão de Destinação\">\r\n");
out.write(" <i class=\"menu-icon fa fa-folder\"></i>\r\n");
out.write(" <span class=\"menu-text\">Destinação</span>\r\n");
out.write(" <b class=\"arrow fa fa-angle-down\"></b>\r\n");
out.write(" </a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" <ul class=\"submenu\">\r\n");
out.write(" <li class=\"\">\r\n");
out.write(" <a href=\"#\" class=\"dropdown-toggle\" title=\"Núcleo de Administração dos Imóveis\">\r\n");
out.write(" <i class=\"menu-icon fa fa-caret-right\"></i> SAI\r\n");
out.write(" <b class=\"arrow fa fa-angle-down\"></b>\r\n");
out.write(" </a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" <ul class=\"submenu disabled-li-menu\">\r\n");
out.write(" <li class=\"\">\r\n");
out.write(" <a href=\"#\" title=\"Herança vacante\">Herança vacante </a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" </li>\r\n");
out.write(" </ul>\r\n");
out.write(" </li>\r\n");
out.write(" <li class=\"\">\r\n");
out.write(" <a href=\"#\" class=\"dropdown-toggle\" title=\"Núcleo de Análise de Processos\">\r\n");
out.write(" <i class=\"menu-icon fa fa-caret-right\"></i> SAP\r\n");
out.write(" <b class=\"arrow fa fa-angle-down\"></b>\r\n");
out.write(" </a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" <ul class=\"submenu disabled-li-menu\">\r\n");
out.write(" <li class=\"\">\r\n");
out.write(" <a href=\"#\" title=\"Análise de processos / Destinação do patrimônio\">Análise de processos</a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" </li>\r\n");
out.write(" </ul>\r\n");
out.write(" </li>\r\n");
out.write(" <li class=\"\">\r\n");
out.write(" <a href=\"#\" class=\"dropdown-toggle\" title=\"Núcleo de Controle de Lavratura de Cessão\">\r\n");
out.write(" <i class=\"menu-icon fa fa-caret-right\"></i> SCL\r\n");
out.write(" <b class=\"arrow fa fa-angle-down\"></b>\r\n");
out.write(" </a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" <ul class=\"submenu\">\r\n");
out.write(" <li class=\"\">\r\n");
out.write(" <a href=\"AutoCessao.jsp\" title=\"Auto de Cessão\">Autos de Cessão</a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" </li>\r\n");
out.write(" </ul>\r\n");
out.write(" </li>\r\n");
out.write(" </ul>\r\n");
out.write(" </li>\r\n");
out.write(" \r\n");
out.write("<!-- Menu DIPI -->\r\n");
out.write(" <li class=\"\">\r\n");
out.write(" <a href=\"#\" class=\"dropdown-toggle\" title=\"Divisão de Informação\">\r\n");
out.write(" <i class=\"menu-icon fa fa-folder\"></i>\r\n");
out.write(" <span class=\"menu-text\">Informação</span>\r\n");
out.write(" <b class=\"arrow fa fa-angle-down\"></b>\r\n");
out.write(" </a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" <ul class=\"submenu\">\r\n");
out.write(" <li class=\"\">\r\n");
out.write(" <a href=\"#\" class=\"dropdown-toggle\" title=\"Núcleo de Cadastro de Áreas Públicas\">\r\n");
out.write(" <i class=\"menu-icon fa fa-caret-right\"></i> SCA\r\n");
out.write(" <b class=\"arrow fa fa-angle-down\"></b>\r\n");
out.write(" </a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" <ul class=\"submenu \">\r\n");
out.write(" <li class=\"disabled-li-menu\">\r\n");
out.write(" <a href=\"#\" title=\"Gerenciamento do Usuário do CAP/QGIS\">Usuários CAP/QGIS</a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" </li>\r\n");
out.write(" <li class=\"disabled-li-menu\">\r\n");
out.write(" <a href=\"#\" title=\"Restauração de CAP alterado/inserido/deletado\">Restaurar CAP/QGIS</a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" </li>\r\n");
out.write(" </ul> \r\n");
out.write(" </li>\r\n");
out.write(" <li class=\"\">\r\n");
out.write(" <a href=\"#\" class=\"dropdown-toggle\" title=\"Núcleo de Guardar de Documentos Imobiliários\">\r\n");
out.write(" <i class=\"menu-icon fa fa-caret-right\"></i> SGD\r\n");
out.write(" <b class=\"arrow fa fa-angle-down\"></b>\r\n");
out.write(" </a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" <ul class=\"submenu\">\r\n");
out.write(" <li class=\"disabled-li-menu\">\r\n");
out.write(" <a href=\"PesquisaSGD.jsp\" title=\"Documentos Imobiliários\">Guarda Documental</a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" </li>\r\n");
out.write(" </ul> \r\n");
out.write(" </li>\r\n");
out.write(" <li class=\"\">\r\n");
out.write(" <a href=\"#\" class=\"dropdown-toggle\" title=\"Núcleo de Anotação e Informação Cadastral\">\r\n");
out.write(" <i class=\"menu-icon fa fa-caret-right\"></i> SIC\r\n");
out.write(" <b class=\"arrow fa fa-angle-down\"></b>\r\n");
out.write(" </a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" <ul class=\"submenu \">\r\n");
out.write(" <li class=\"disabled-li-menu\">\r\n");
out.write(" <a href=\"#\" title=\"Anotação de Expediente\">Anotação Expediente </a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" </li>\r\n");
out.write(" </ul> \r\n");
out.write(" </li>\r\n");
out.write(" </ul>\r\n");
out.write(" </li>\r\n");
out.write(" \r\n");
out.write("<!-- Menu DEAPI -->\r\n");
out.write(" <li class=\"\">\r\n");
out.write(" <a href=\"#\" class=\"dropdown-toggle\" title=\"Divisão de Engenharia\">\r\n");
out.write(" <i class=\"menu-icon fa fa-folder\"></i>\r\n");
out.write(" <span class=\"menu-text\">Engenharia</span>\r\n");
out.write(" <b class=\"arrow fa fa-angle-down\"></b>\r\n");
out.write(" </a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" <ul class=\"submenu\">\r\n");
out.write(" <li class=\"\">\r\n");
out.write(" <a href=\"#\" class=\"dropdown-toggle\" title=\"Núcleo de Informação de Áreas Públicas\">\r\n");
out.write(" <i class=\"menu-icon fa fa-caret-right\"></i> SI\r\n");
out.write(" <b class=\"arrow fa fa-angle-down\"></b>\r\n");
out.write(" </a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" <ul class=\"submenu disabled-li-menu\">\r\n");
out.write(" <li class=\"\">\r\n");
out.write(" <a href=\"#\" title=\"-\">-</a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" </li>\r\n");
out.write(" </ul> \r\n");
out.write(" </li>\r\n");
out.write(" <li class=\"\">\r\n");
out.write(" <a href=\"#\" class=\"dropdown-toggle\" title=\"Núcleo de Elaboração de Peças Gráficas\">\r\n");
out.write(" <i class=\"menu-icon fa fa-caret-right\"></i> SP\r\n");
out.write(" <b class=\"arrow fa fa-angle-down\"></b>\r\n");
out.write(" </a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" <ul class=\"submenu disabled-li-menu\">\r\n");
out.write(" <li class=\"\">\r\n");
out.write(" <a href=\"#\" title=\"Elaboração de planta (alienação/cessão), análise de processo (sobreposição e domínio)\">Elaboração de planta</a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" </li>\r\n");
out.write(" </ul> \r\n");
out.write(" </li>\r\n");
out.write(" <li class=\"\">\r\n");
out.write(" <a href=\"#\" class=\"dropdown-toggle\" title=\"Núcleo de Levantamento Topográfico\">\r\n");
out.write(" <i class=\"menu-icon fa fa-caret-right\"></i> ST\r\n");
out.write(" <b class=\"arrow fa fa-angle-down\"></b>\r\n");
out.write(" </a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" <ul class=\"submenu disabled-li-menu\">\r\n");
out.write(" <li class=\"\">\r\n");
out.write(" <a href=\"#\" title=\"Topografia\">Topografia</a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" </li>\r\n");
out.write(" </ul> \r\n");
out.write(" </li>\r\n");
out.write(" </ul>\r\n");
out.write(" </li>\r\n");
out.write(" \r\n");
out.write("<!-- Menu DAPI -->\r\n");
out.write(" <li class=\"\">\r\n");
out.write(" <a href=\"#\" class=\"dropdown-toggle\" title=\"Divisão de Avaliação\">\r\n");
out.write(" <i class=\"menu-icon fa fa-folder\"></i>\r\n");
out.write(" <span class=\"menu-text\">Avaliação</span>\r\n");
out.write(" <b class=\"arrow fa fa-angle-down\"></b>\r\n");
out.write(" </a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" <ul class=\"submenu\">\r\n");
out.write(" <li class=\"\">\r\n");
out.write(" <a href=\"#\" class=\"dropdown-toggle\" title=\"Núcleo de Avaliação\">\r\n");
out.write(" <i class=\"menu-icon fa fa-caret-right\"></i> SA\r\n");
out.write(" <b class=\"arrow fa fa-angle-down\"></b>\r\n");
out.write(" </a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" <ul class=\"submenu disabled-li-menu\">\r\n");
out.write(" <li class=\"\">\r\n");
out.write(" <a href=\"#\" title=\"Avaliações / Internas e CPOS (locação, indenização, alienação etc)\">Avaliações</a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" </li>\r\n");
out.write(" </ul> \r\n");
out.write(" </li>\r\n");
out.write(" <li class=\"\">\r\n");
out.write(" <a href=\"#\" class=\"dropdown-toggle\" title=\"Núcleo de Vistória\">\r\n");
out.write(" <i class=\"menu-icon fa fa-caret-right\"></i> SV\r\n");
out.write(" <b class=\"arrow fa fa-angle-down\"></b>\r\n");
out.write(" </a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" <ul class=\"submenu disabled-li-menu\">\r\n");
out.write(" <li class=\"\">\r\n");
out.write(" <a href=\"#\" title=\"\">-</a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" </li>\r\n");
out.write(" </ul> \r\n");
out.write(" </li>\r\n");
out.write(" </ul>\r\n");
out.write(" </li>\r\n");
out.write(" \r\n");
out.write("<!-- Menu INDICADORES -->\r\n");
out.write(" <li class=\"\">\r\n");
out.write(" <a class=\"disabled-li-menu\" href=\"#\" title=\"\">\r\n");
out.write(" <i class=\"menu-icon fa fa-bar-chart-o\"></i>\r\n");
out.write(" <span class=\"menu-text\">Indicadores</span>\r\n");
out.write(" </a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" </li>\r\n");
out.write(" \r\n");
out.write("<!-- Menu DECRETOS -->\r\n");
out.write(" <li class=\"\">\r\n");
out.write(" <a class=\"disabled-li-menu\" href=\"#\" title=\"\">\r\n");
out.write(" <i class=\"menu-icon fa fa-balance-scale\"></i>\r\n");
out.write(" <span class=\"menu-text\">Decretos</span>\r\n");
out.write(" </a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" </li>\r\n");
out.write(" \r\n");
out.write("<!-- Menu PROJETOS -->\r\n");
out.write(" <li class=\"\">\r\n");
out.write(" <a class=\"disabled-li-menu\" href=\"#\" title=\"\">\r\n");
out.write(" <i class=\"menu-icon fa fa-laptop\"></i>\r\n");
out.write(" <span class=\"menu-text\">Projetos</span>\r\n");
out.write(" </a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" </li>\r\n");
out.write(" \r\n");
out.write("<!--Menu Tarefas-->\r\n");
out.write(" <li class=\"\">\r\n");
out.write(" <a class=\"disabled-li-menu\" href=\"#\" title=\"\">\r\n");
out.write(" <i class=\"menu-icon fa fa-tags\"></i>\r\n");
out.write(" <span class=\"menu-text\"> Tarefas \r\n");
out.write(" <span class=\"badge badge-transparent tooltip-error\" title=\"2 Eventos importantes\">\r\n");
out.write(" <i class=\"ace-icon fa fa-exclamation-triangle red bigger-130\"></i>\r\n");
out.write(" </span>\r\n");
out.write(" </span>\r\n");
out.write(" \r\n");
out.write(" </a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" </li>\r\n");
out.write("\r\n");
out.write("<!-- Menu Calendario-->\r\n");
out.write(" <li class=\"\">\r\n");
out.write(" <a class=\"disabled-li-menu\" href=\"#\" title=\"\">\r\n");
out.write(" <i class=\"menu-icon fa fa-calendar\"></i>\r\n");
out.write(" <span class=\"menu-text\"> Calendário </span>\r\n");
out.write(" </a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" </li>\r\n");
out.write(" \r\n");
out.write("<!-- Wikipedia CGPatri-->\r\n");
out.write(" <li class=\"\">\r\n");
out.write(" <a class=\"disabled-li-menu\" href=\"#\" title=\"\">\r\n");
out.write(" <i class=\"menu-icon fa fa-book\"></i>\r\n");
out.write(" <span class=\"menu-text\"> Wikipedia CGPatri </span>\r\n");
out.write(" </a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" </li>\r\n");
out.write("<!-- Vesrsão do Aplicação--> \r\n");
out.write(" <li class=\"\">\r\n");
out.write(" <a class=\"\" href=\"#\" title=\"\">\r\n");
out.write(" <i class=\"menu-icon fa fa-info-circle\"></i>\r\n");
out.write(" <span class=\"menu-text\"> Versão 1.0.4</span>\r\n");
out.write(" </a>\r\n");
out.write(" <b class=\"arrow\"></b>\r\n");
out.write(" </li>\r\n");
out.write(" \r\n");
out.write(" </ul><!-- /.nav-list -->\r\n");
out.write("</div>\r\n");
out.write("\r\n");
out.write("<!--Inicio DIV do body -->\r\n");
out.write("<div class=\"main-content\">\r\n");
out.write("<div class=\"main-content-inner\">\r\n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
<file_sep>/src/java/br/com/Modelo/ArquivoDAO.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.Modelo;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author d732229
*/
public class ArquivoDAO {
private final Connection connection;
public ArquivoDAO (){
this.connection = new FabricaConexao().getConnetion();
}
//METODO utilizado para lista os arquivos realiconado com o Auto de Cessão
public List<Arquivo> listArquivo(int pkAutoCessao) throws SQLException {
PreparedStatement stmt = null;
ResultSet rs = null;
List<Arquivo> arList = new ArrayList<Arquivo>();
String sql = ("SELECT id_arquivo, fk_autocessao, nm_tipo, nm_arquivo, nm_extensao, nm_nomeclatura, nm_diretorio, nr_reti_ratificacao "
+ "FROM tbl_anexo_auto_cessao "
+ "WHERE fk_autocessao = ? "
+ "ORDER BY nm_tipo ASC, id_arquivo DESC" );
try {
stmt = connection.prepareStatement(sql);
stmt.setInt(1, pkAutoCessao);
rs = stmt.executeQuery();
while (rs.next()){
Arquivo arquivo = new Arquivo();
arquivo.setPkArquivo(rs.getInt("id_arquivo"));
arquivo.setFkAutocessao(rs.getInt("fk_autocessao"));
arquivo.setNmTipo(rs.getString("nm_tipo"));
arquivo.setNmArquivo(rs.getString("nm_arquivo"));
arquivo.setNmExtensao(rs.getString("nm_extensao"));
arquivo.setNmNomeclatura(rs.getString("nm_nomeclatura"));
arquivo.setNmDiretorio(rs.getString("nm_diretorio"));
arquivo.setNrRetiRatificacao(rs.getInt("nr_reti_ratificacao"));
arList.add(arquivo);
}
return arList;
}catch (SQLException e) {
throw new RuntimeException(e);
}finally{
rs.close();
stmt.close();
connection.close();
}
}
//METODO utilizado para retorno id e o diretorio do Arquivo
public Arquivo pkArquivo(int pkArquivo) throws SQLException {
PreparedStatement stmt = null;
ResultSet rs = null;
Arquivo arquivo = new Arquivo();
String sql = ("SELECT id_arquivo, nm_tipo, nm_arquivo, nm_extensao, nm_diretorio, nm_nomeclatura, nr_reti_ratificacao "
+ "FROM tbl_anexo_auto_cessao "
+ "WHERE id_arquivo = ? ");
try {
stmt = connection.prepareStatement(sql);
stmt.setInt(1, pkArquivo);
rs = stmt.executeQuery();
if (rs.next()){
arquivo.setPkArquivo(rs.getInt("id_arquivo"));
arquivo.setNmTipo(rs.getString("nm_tipo"));
arquivo.setNmArquivo(rs.getString("nm_arquivo"));
arquivo.setNmExtensao(rs.getString("nm_extensao"));
arquivo.setNmDiretorio(rs.getString("nm_diretorio"));
arquivo.setNmNomeclatura(rs.getString("nm_nomeclatura"));
arquivo.setNrRetiRatificacao(rs.getInt("nr_reti_ratificacao"));
}
return arquivo;
} catch (SQLException e) {
throw new RuntimeException(e);
}finally{
rs.close();
stmt.close();
connection.close();
}
}
//METODO utilizado para inserir uma nova Arquivo no BANCO
public void cArquivo(Arquivo ar) throws SQLException{
PreparedStatement stmt = null;
String sql = "INSERT INTO tbl_anexo_auto_cessao "
+ "(fk_autocessao, nm_tipo, nm_arquivo, nm_extensao, nm_diretorio, nm_nomeclatura, nr_reti_ratificacao, nm_login, dthr_atualizacao) "
+ "VALUES (?,?,?,?,?,?,?,?,?)";
try{
stmt = connection.prepareStatement(sql);
stmt.setInt(1, ar.getFkAutocessao());
stmt.setString(2, ar.getNmTipo());
stmt.setString(3, ar.getNmArquivo());
stmt.setString(4, ar.getNmExtensao());
stmt.setString(5, ar.getNmDiretorio());
stmt.setString(6, ar.getNmNomeclatura());
stmt.setInt(7, ar.getNrRetiRatificacao());
stmt.setString(8, ar.getNmLogin());
stmt.setTimestamp(9,java.sql.Timestamp.valueOf(java.time.LocalDateTime.now()));
stmt.execute();
}catch (SQLException e){
throw new RuntimeException(e);
}finally{
// stmt.close();
// connection.close();
}
}
//METODO utilizado para atualizar Arquivo no BANCO
public void upArquivo(Arquivo ar) throws SQLException{
PreparedStatement stmt = null;
String sql = "UPDATE tbl_anexo_auto_cessao "
+ "SET fk_autocessao=?, nm_tipo=?, nm_arquivo=?, nm_extensao=?, nm_diretorio=?, nm_nomeclatura=?, nr_reti_ratificacao=?, nm_login=?, dthr_atualizacao=? "
+ "WHERE id_arquivo=? ";
try{
stmt = connection.prepareStatement(sql);
stmt.setInt(1, ar.getFkAutocessao());
stmt.setString(2, ar.getNmTipo());
stmt.setString(3, ar.getNmArquivo());
stmt.setString(4, ar.getNmExtensao());
stmt.setString(5, ar.getNmDiretorio());
stmt.setString(6, ar.getNmNomeclatura());
stmt.setInt(7, ar.getNrRetiRatificacao());
stmt.setString(8, ar.getNmLogin());
stmt.setTimestamp(9,java.sql.Timestamp.valueOf(java.time.LocalDateTime.now()));
stmt.setInt(10, ar.getPkArquivo());
stmt.execute();
}catch (SQLException e){
throw new RuntimeException(e);
}finally{
// stmt.close();
// connection.close();
}
}
//METODO utilizado para deletar arquivo do banco
public void deleteArquvio (int pkArquivo) throws SQLException{
PreparedStatement stmt = null;
String sql = "DELETE FROM tbl_anexo_auto_cessao "
+"WHERE id_arquivo = ? ";
try{
stmt = connection.prepareCall(sql);
stmt.setInt(1, pkArquivo);
stmt.execute();
}catch (SQLException e){
throw new RuntimeException(e);
}finally{
// stmt.close();
// connection.close();
}
}
//METODO utilizado para não ocorrer duplicidade
public int qtdRepetidos (int pkAutoCessao, String nmTipo) throws SQLException{
PreparedStatement stmt = null;
ResultSet rs = null;
int qtd = 10;
String sql = "SELECT COUNT(*) AS qtd "
+ "FROM tbl_anexo_auto_cessao "
+ "WHERE fk_autocessao = ? and nm_tipo = ? ";
try{
stmt = connection.prepareCall(sql);
stmt.setInt(1, pkAutoCessao);
stmt.setString(2, nmTipo);
rs = stmt.executeQuery();
if(rs.next()){
qtd = rs.getInt("qtd");
}
return qtd;
}catch (SQLException e){
throw new RuntimeException(e);
}finally{
rs.close();
stmt.close();
// connection.close();
}
}
}
<file_sep>/src/java/br/com/Modelo/CatSubFinalidade.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.Modelo;
/**
*
* @author d732229
*/
public class CatSubFinalidade {
private int pkCatSubFinalidade, fkCatFinalidade;
private String sgCatFinalidade, nmCatFinalidade, sgCatSubFinalidade, nmCatSubFinalidade, nmLogin ,dthrAtualizacao;
public CatSubFinalidade() {
}
public CatSubFinalidade(int fkCatFinalidade, String sgCatSubFinalidade, String nmCatSubFinalidade, String nmLogin) {
this.fkCatFinalidade = fkCatFinalidade;
this.sgCatSubFinalidade = sgCatSubFinalidade;
this.nmCatSubFinalidade = nmCatSubFinalidade;
this.nmLogin = nmLogin;
}
public CatSubFinalidade(int pkCatSubFinalidade, int fkCatFinalidade, String sgCatSubFinalidade, String nmCatSubFinalidade, String nmLogin) {
this(fkCatFinalidade, sgCatSubFinalidade, nmCatSubFinalidade, nmLogin);
this.pkCatSubFinalidade = pkCatSubFinalidade;
}
public String getSgCatFinalidade() {
return sgCatFinalidade;
}
public void setSgCatFinalidade(String sgCatFinalidade) {
this.sgCatFinalidade = sgCatFinalidade;
}
public String getNmCatFinalidade() {
return nmCatFinalidade;
}
public void setNmCatFinalidade(String nmCatFinalidade) {
this.nmCatFinalidade = nmCatFinalidade;
}
public int getPkCatSubFinalidade() {
return pkCatSubFinalidade;
}
public void setPkCatSubFinalidade(int pkCatSubFinalidade) {
this.pkCatSubFinalidade = pkCatSubFinalidade;
}
public int getFkCatFinalidade() {
return fkCatFinalidade;
}
public void setFkCatFinalidade(int fkCatFinalidade) {
this.fkCatFinalidade = fkCatFinalidade;
}
public String getSgCatSubFinalidade() {
return sgCatSubFinalidade;
}
public void setSgCatSubFinalidade(String sgCatSubFinalidade) {
this.sgCatSubFinalidade = sgCatSubFinalidade;
}
public String getNmCatSubFinalidade() {
return nmCatSubFinalidade;
}
public void setNmCatSubFinalidade(String nmCatSubFinalidade) {
this.nmCatSubFinalidade = nmCatSubFinalidade;
}
public String getNmLogin() {
return nmLogin;
}
public void setNmLogin(String nmLogin) {
this.nmLogin = nmLogin;
}
public String getDthrAtualizacao() {
return dthrAtualizacao;
}
public void setDthrAtualizacao(String dthrAtualizacao) {
this.dthrAtualizacao = dthrAtualizacao;
}
}
<file_sep>/src/java/br/com/Controle/DispositivoLegalDelete.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.Controle;
import br.com.Modelo.AutoCessaoDAO;
import br.com.Modelo.DispositivoLegal;
import br.com.Modelo.DispositivoLegalDAO;
import br.com.Modelo.Logica;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author d732229
*/
public class DispositivoLegalDelete implements Logica {
@Override
public String executa(HttpServletRequest req,
HttpServletResponse res) throws Exception {
DispositivoLegalDAO disDAO = new DispositivoLegalDAO();
AutoCessaoDAO autoDAO = new AutoCessaoDAO();
String execucao;
int pkDispLegal, pkAutoCessao;
execucao = req.getParameter("execucao");
pkDispLegal = Integer.parseInt(req.getParameter("pkDispLegal"));
pkAutoCessao = Integer.parseInt(req.getParameter("pkAutoCessao"));
disDAO.delDispositivo(pkDispLegal, pkAutoCessao);
List <DispositivoLegal> listDisp = disDAO.listDispositivo(pkAutoCessao);
if(listDisp.isEmpty()){
autoDAO.upAutoCessaoVerificadoDisLegal(pkAutoCessao, 0);
}
req.setAttribute("msg", "true");
req.setAttribute("tipoAler", "success");
req.setAttribute("alert", "Sucesso! ");
req.setAttribute("txtAlert", "O dispositivo legal foi excluido.");
return "ControllerServlet?acao=AutoCessaoDetalhe&pkAutoCessao="+pkAutoCessao+"&execucao="+execucao;
}
}
<file_sep>/src/java/br/com/Controle/UsuarioAltStatus.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.Controle;
import br.com.Modelo.Logica;
import br.com.Modelo.Usuario;
import br.com.Modelo.UsuarioDAO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author d732229
*/
public class UsuarioAltStatus implements Logica {
@Override
public String executa(HttpServletRequest req,
HttpServletResponse res) throws Exception {
UsuarioDAO usDAO = new UsuarioDAO();
HttpSession session = req.getSession();
//Atributos
int status=0, pkUs;
String loginSession = (String) session.getAttribute("sessionLogin");
//Carregando os atributos com as informações do formulário
status = Integer.parseInt(req.getParameter("status"));
pkUs = Integer.parseInt(req.getParameter("pkUs"));
//Populando o objeto e alterando informações
Usuario us = new Usuario(pkUs, status, loginSession);
usDAO.atuStatus(us);
us = usDAO.detalheUsuario(pkUs);
return "ControllerServlet?acao=UsuarioListaPaginada";
}
}
<file_sep>/test/teste/servidorAD/LoginAD2.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package teste.servidorAD;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
/**
*
* @author d732229
*/
public class LoginAD2 {
public static boolean authenticateJndi(String username, String password) throws Exception{
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
props.put(Context.PROVIDER_URL, "ldap://c68v43i:389");
props.put(Context.SECURITY_PRINCIPAL, "usr_sj2408_ldap");//adminuser - User with special priviledge, dn user
props.put(Context.SECURITY_CREDENTIALS, "At<PASSWORD>");//dn user password
InitialDirContext context = new InitialDirContext(props);
SearchControls ctrls = new SearchControls();
ctrls.setReturningAttributes(new String[] { "givenName", "sn","memberOf" });
ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<javax.naming.directory.SearchResult> answers = context.search("o=xx.com", "(uid=" + username + ")", ctrls);
javax.naming.directory.SearchResult result = answers.nextElement();
String user = result.getNameInNamespace();
try {
props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
props.put(Context.PROVIDER_URL, "ldap://c68v43i:389");
props.put(Context.SECURITY_PRINCIPAL, user);
props.put(Context.SECURITY_CREDENTIALS, password);
context = new InitialDirContext(props);
} catch (Exception e) {
return false;
}
return true;
}
}
<file_sep>/src/java/br/com/Modelo/CargoDAO.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.Modelo;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author d732229
*/
public class CargoDAO {
private final Connection connection;
//Construtor
public CargoDAO() {
this.connection = new FabricaConexao().getConnetion();
}
//METODO lista todos os cargo cadastrados, utilizado com campo select do pagaina cadastro e alteração de usuário
public List<Cargo> listCargo() throws SQLException {
PreparedStatement stmt= null;
ResultSet rs = null;
List<Cargo> cgLista = new ArrayList<Cargo>();
String sql = "SELECT id_cargo, nm_cargo, ds_cargo, nm_login, dthr_atualizacao "
+ "FROM tbl_cargo";
try {
stmt = connection.prepareStatement(sql);
rs = stmt.executeQuery();
while (rs.next()){
Cargo cg = new Cargo();
cg.setPkCargo(rs.getInt("id_cargo"));
cg.setNmCargo(rs.getString("nm_cargo"));
cg.setDsCargo(rs.getString("ds_cargo"));
cg.setNmLogin(rs.getString("nm_login"));
cg.setDsCargo(rs.getString("dthr_atualizacao"));
cgLista.add(cg);
}
return cgLista;
} catch (SQLException e) {
throw new RuntimeException(e);
}finally{
rs.close();
stmt.close();
connection.close();
}
}
}
<file_sep>/test/teste/utilitarios/KeyTool.java
package teste.utilitarios;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author d732229
*/
public class KeyTool {
//Ler o certificad do keyStore JKS
public static void main(String[] args) throws Exception {
String pathKeyStore = "C://MeukeyStore.jks";
String senhaKeyStore = "changeit";
String senhaChavePrivada ="<PASSWORD>";
String alias = "aliasDaMinhaChave";
InputStream entrada = new FileInputStream(pathKeyStore);
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());//JKS
try {
//carregar o arquivo no keyStore
ks.load(entrada, senhaKeyStore.toCharArray());
//obter a chave privada
KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry)
ks.getEntry(alias, new KeyStore.PasswordProtection(senhaChavePrivada.toCharArray()));
System.out.println("----------------- chave privada----------------------");
System.out.println(keyEntry.getPrivateKey());
//certificado correspondente a chave privada
System.out.println("----------------- chave publica (Certificado)----------------------");
System.out.println(keyEntry.getCertificate());
} catch (Exception e) {
e.printStackTrace();
}
}
}
<file_sep>/src/java/br/com/Controle/CatSubFinalidadeDetalhe.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.Controle;
import br.com.Modelo.CatSubFinalidade;
import br.com.Modelo.CatSubFinalidadeDAO;
import br.com.Modelo.Logica;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author d732229
*/
public class CatSubFinalidadeDetalhe implements Logica {
@Override
public String executa(HttpServletRequest req,
HttpServletResponse res) throws Exception {
//Atributo
int pkCatSubFinalidade;
String execucao;
//Carregando os atributos com as informações do formulário
pkCatSubFinalidade = Integer.parseInt(req.getParameter("pkCatSubFinalidade"));
execucao = req.getParameter("execucao");
//Consulta no banco e populando o objeto
CatSubFinalidadeDAO catSubFinDAO = new CatSubFinalidadeDAO();
CatSubFinalidade catSub = catSubFinDAO.detalheCatSubFinalidade(pkCatSubFinalidade);
req.setAttribute("catSub", catSub);
req.setAttribute("execucao", execucao);
return "CatSubFinalidadeCRU.jsp";
}
}
<file_sep>/build/generated/src/org/apache/jsp/PerfilCRU_jsp.java
package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class PerfilCRU_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.List<String> _jspx_dependants;
static {
_jspx_dependants = new java.util.ArrayList<String>(1);
_jspx_dependants.add("/include/ControleAcesso.jsp");
}
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_set_var_value_nobody;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_redirect_url_nobody;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_set_var_value_scope_nobody;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_out_value_nobody;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_choose;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_if_test;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_otherwise;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_when_test;
private org.glassfish.jsp.api.ResourceInjector _jspx_resourceInjector;
public java.util.List<String> getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_jspx_tagPool_c_set_var_value_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_c_redirect_url_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_c_set_var_value_scope_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_c_out_value_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_c_choose = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_c_if_test = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_c_otherwise = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_c_when_test = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
}
public void _jspDestroy() {
_jspx_tagPool_c_set_var_value_nobody.release();
_jspx_tagPool_c_redirect_url_nobody.release();
_jspx_tagPool_c_set_var_value_scope_nobody.release();
_jspx_tagPool_c_out_value_nobody.release();
_jspx_tagPool_c_choose.release();
_jspx_tagPool_c_if_test.release();
_jspx_tagPool_c_otherwise.release();
_jspx_tagPool_c_when_test.release();
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html charset=UTF-8;");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
_jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("<!DOCTYPE html>\r\n");
out.write("<html>\r\n");
out.write(" \r\n");
out.write(" ");
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "include/head.jsp", out, false);
out.write("\r\n");
out.write(" <body class=\"no-skin\">\r\n");
out.write(" ");
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "include/top.jsp", out, false);
out.write("\r\n");
out.write(" <div class=\"main-container ace-save-state\" id=\"main-container\">\r\n");
out.write(" ");
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "include/nav.jsp", out, false);
out.write("\r\n");
out.write(" ");
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "javaScritp/alertSigla.html", out, false);
out.write("\r\n");
out.write("\r\n");
out.write("<!--Verificação de acesso -->\r\n");
out.write(" ");
if (_jspx_meth_c_set_0(_jspx_page_context))
return;
out.write("\r\n");
out.write(" ");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
if (_jspx_meth_c_choose_0(_jspx_page_context))
return;
out.write("\r\n");
out.write("\r\n");
out.write(" \r\n");
out.write("<!--Parametros para paginação e exibir campos do View, Edit, Inserit--> \r\n");
out.write(" ");
if (_jspx_meth_c_set_3(_jspx_page_context))
return;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_set_4(_jspx_page_context))
return;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_set_5(_jspx_page_context))
return;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_set_6(_jspx_page_context))
return;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_set_7(_jspx_page_context))
return;
out.write("\r\n");
out.write(" \r\n");
out.write(" \r\n");
out.write(" <div class=\"breadcrumbs ace-save-state\" id=\"breadcrumbs\">\r\n");
out.write(" <ul class=\"breadcrumb\">\r\n");
out.write(" <li><i class=\"ace-icon fa fa-folder\"></i> Núcleo</li>\r\n");
out.write(" </ul>\r\n");
out.write(" </div> \r\n");
out.write(" <div class=\"page-content\">\r\n");
out.write(" <div class=\"row\">\r\n");
out.write(" <div class=\"col-xs-12\">\r\n");
out.write(" \r\n");
out.write(" \r\n");
out.write(" <div class=\"col-sm-6 col-sm-offset-2\">\r\n");
out.write(" <div class=\"widget-box\">\r\n");
out.write(" <div class=\"widget-header\">\r\n");
out.write(" <h4 class=\"widget-title\"><span class=\"fa fa-folder-o\"></span> \r\n");
out.write(" ");
if (_jspx_meth_c_choose_1(_jspx_page_context))
return;
out.write("\r\n");
out.write(" Perfil</h4>\r\n");
out.write(" </div>\r\n");
out.write("\r\n");
out.write(" <div class=\"widget-body\">\r\n");
out.write(" <div class=\"widget-main no-padding\">\r\n");
out.write(" <form action=\"ControllerServlet?acao=PerfilCU\" method=\"POST\">\r\n");
out.write(" <input type=\"hidden\" name=\"execucao\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" />\r\n");
out.write(" <input type=\"hidden\" name=\"pkPerfil\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${per.pkPerfil}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" />\r\n");
out.write(" <fieldset>\r\n");
out.write(" <div class=\"form-group\">\r\n");
out.write(" <label class=\"col-sm-3 control-label no-padding-right\" for=\"form-field-1\"> Tipo de Perfil </label>\r\n");
out.write(" <div class=\"col-sm-9 col-xs-12 control-label no-padding-right\" for=\"form-field-1\">\r\n");
out.write(" ");
if (_jspx_meth_c_choose_2(_jspx_page_context))
return;
out.write("\r\n");
out.write(" </div>\r\n");
out.write(" </div>\r\n");
out.write(" <br/><br/>\r\n");
out.write(" <div class=\"form-group\">\r\n");
out.write(" <label class=\"col-sm-3 control-label no-padding-right\" for=\"form-field-1\"> Descrição </label>\r\n");
out.write(" <div class=\"col-sm-9 col-xs-12 control-label no-padding-right\" for=\"form-field-1\">\r\n");
out.write(" ");
if (_jspx_meth_c_choose_3(_jspx_page_context))
return;
out.write("\r\n");
out.write(" </div>\r\n");
out.write(" </div>\r\n");
out.write(" \r\n");
out.write(" <br/><br/><br/>\r\n");
out.write(" <div class=\"form-group\"> \r\n");
out.write(" <label class=\"col-sm-4 control-label no-padding-right\" for=\"form-field-1\"> Permissão Leitura: </label>\r\n");
out.write(" <div class=\"col-sm-2 col-xs-12\">\r\n");
out.write(" ");
if (_jspx_meth_c_choose_4(_jspx_page_context))
return;
out.write(" \r\n");
out.write(" </div>\r\n");
out.write(" <label class=\"col-sm-3 control-label no-padding-right\" for=\"form-field-1\"> Permissão Gravar: </label>\r\n");
out.write(" <div class=\"col-sm-3 col-xs-12\">\r\n");
out.write(" ");
if (_jspx_meth_c_choose_6(_jspx_page_context))
return;
out.write(" \r\n");
out.write(" </div>\r\n");
out.write(" </div>\r\n");
out.write(" <br /><br />\r\n");
out.write(" <div class=\"form-group\"> \r\n");
out.write(" <label class=\"col-sm-4 control-label no-padding-right\" for=\"form-field-1\"> Permissão Alterar: </label>\r\n");
out.write(" <div class=\"col-sm-2 col-xs-12\">\r\n");
out.write(" ");
if (_jspx_meth_c_choose_8(_jspx_page_context))
return;
out.write(" \r\n");
out.write(" </div>\r\n");
out.write(" \r\n");
out.write(" <label class=\"col-sm-3 control-label no-padding-right\" for=\"form-field-1\"> Permissão Excluir: </label>\r\n");
out.write(" <div class=\"col-sm-3 col-xs-12\">\r\n");
out.write(" ");
if (_jspx_meth_c_choose_10(_jspx_page_context))
return;
out.write(" \r\n");
out.write(" </div>\r\n");
out.write(" </div> \r\n");
out.write(" <div class=\"form-group\"> \r\n");
out.write(" <br /><br />\r\n");
out.write(" \r\n");
out.write(" <label class=\"col-sm-4 control-label no-padding-right\" for=\"form-field-1\"> Permissão Gerenciar: </label>\r\n");
out.write(" <div class=\"col-sm-2 col-xs-12\">\r\n");
out.write(" ");
if (_jspx_meth_c_choose_12(_jspx_page_context))
return;
out.write(" \r\n");
out.write(" </div>\r\n");
out.write(" </div>\r\n");
out.write(" </fieldset>\r\n");
out.write("\r\n");
out.write(" <div class=\"form-actions center\">\r\n");
out.write(" <button class=\"btn btn-yellow\" type=\"reset\" onclick=\" location.href='ControllerServlet?acao=PerfilLista';\">\r\n");
out.write(" <i class=\"ace-icon fa fa-undo bigger-110\"></i>\r\n");
out.write(" Voltar\r\n");
out.write(" </button>\r\n");
out.write(" ");
if (_jspx_meth_c_if_0(_jspx_page_context))
return;
out.write("\r\n");
out.write(" </div>\r\n");
out.write(" </form>\r\n");
out.write(" <div id=\"msg\">\r\n");
out.write(" <div class=\"alert alert-block alert-success\" id=\"up\">\r\n");
out.write(" <strong><i class=\"ace-icon fa fa-check\"></i>Sucesso!</strong>\r\n");
out.write(" A(s) alteração(ões) foi(ram) realizada(s)\r\n");
out.write(" </div>\r\n");
out.write(" <div class=\" alert alert-success\" id=\"ok\">\r\n");
out.write(" <strong><i class=\"ace-icon fa fa-check\"></i>Sucesso!</strong> \r\n");
out.write(" Cadastro realizado.</div> \r\n");
out.write(" </div>\r\n");
out.write(" </div>\r\n");
out.write(" </div>\r\n");
out.write(" ");
if (request.getAttribute("msg") == "gravou") {
out.write("\r\n");
out.write(" <style>\r\n");
out.write(" #msg{visibility: visible;}\r\n");
out.write(" #ok{visibility: visible;} \r\n");
out.write(" #up{visibility: hidden;}\r\n");
out.write(" </style>\r\n");
out.write(" ");
}else if (request.getAttribute("msg") == "alterou"){
out.write("\r\n");
out.write(" <style>\r\n");
out.write(" #msg{visibility: visible;}\r\n");
out.write(" #ok{visibility: hidden;} \r\n");
out.write(" #up{visibility: visible;}\r\n");
out.write(" </style>\r\n");
out.write(" ");
} else {
out.write("\r\n");
out.write(" <style>\r\n");
out.write(" #msg{visibility: hidden;}\r\n");
out.write(" </style>\r\n");
out.write(" ");
}
out.write("\r\n");
out.write(" </div>\r\n");
out.write(" </div>\r\n");
out.write(" </div>\r\n");
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "include/footer.jsp", out, false);
out.write("\r\n");
out.write(" </div><!-- /.main-container --> \r\n");
out.write(" </body>\r\n");
out.write("</html>\r\n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
private boolean _jspx_meth_c_set_0(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_0 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_0.setPageContext(_jspx_page_context);
_jspx_th_c_set_0.setParent(null);
_jspx_th_c_set_0.setVar("acessoPerfil");
_jspx_th_c_set_0.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${sessionPerfil}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_0 = _jspx_th_c_set_0.doStartTag();
if (_jspx_th_c_set_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_0);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_0);
return false;
}
private boolean _jspx_meth_c_choose_0(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_0 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_0.setPageContext(_jspx_page_context);
_jspx_th_c_choose_0.setParent(null);
int _jspx_eval_c_choose_0 = _jspx_th_c_choose_0.doStartTag();
if (_jspx_eval_c_choose_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_when_0((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_0, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_when_1((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_0, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_when_2((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_0, _jspx_page_context))
return true;
out.write('\r');
out.write('\n');
int evalDoAfterBody = _jspx_th_c_choose_0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_0);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_0);
return false;
}
private boolean _jspx_meth_c_when_0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_0, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_0 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_0.setPageContext(_jspx_page_context);
_jspx_th_c_when_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_0);
_jspx_th_c_when_0.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${sessionLogin == '' || sessionLogin == null}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_0 = _jspx_th_c_when_0.doStartTag();
if (_jspx_eval_c_when_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_redirect_0((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_0, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_0);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_0);
return false;
}
private boolean _jspx_meth_c_redirect_0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_0, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:redirect
org.apache.taglibs.standard.tag.rt.core.RedirectTag _jspx_th_c_redirect_0 = (org.apache.taglibs.standard.tag.rt.core.RedirectTag) _jspx_tagPool_c_redirect_url_nobody.get(org.apache.taglibs.standard.tag.rt.core.RedirectTag.class);
_jspx_th_c_redirect_0.setPageContext(_jspx_page_context);
_jspx_th_c_redirect_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_0);
_jspx_th_c_redirect_0.setUrl("/AcessoNegado.jsp");
int _jspx_eval_c_redirect_0 = _jspx_th_c_redirect_0.doStartTag();
if (_jspx_th_c_redirect_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_redirect_url_nobody.reuse(_jspx_th_c_redirect_0);
return true;
}
_jspx_tagPool_c_redirect_url_nobody.reuse(_jspx_th_c_redirect_0);
return false;
}
private boolean _jspx_meth_c_when_1(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_0, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_1 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_1.setPageContext(_jspx_page_context);
_jspx_th_c_when_1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_0);
_jspx_th_c_when_1.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${sessionPerfil != acessoPerfil}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_1 = _jspx_th_c_when_1.doStartTag();
if (_jspx_eval_c_when_1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_set_1((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_1, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_redirect_1((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_1, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_1.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_1);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_1);
return false;
}
private boolean _jspx_meth_c_set_1(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_1, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_1 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_scope_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_1.setPageContext(_jspx_page_context);
_jspx_th_c_set_1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_1);
_jspx_th_c_set_1.setVar("msg3");
_jspx_th_c_set_1.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${true}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
_jspx_th_c_set_1.setScope("session");
int _jspx_eval_c_set_1 = _jspx_th_c_set_1.doStartTag();
if (_jspx_th_c_set_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_scope_nobody.reuse(_jspx_th_c_set_1);
return true;
}
_jspx_tagPool_c_set_var_value_scope_nobody.reuse(_jspx_th_c_set_1);
return false;
}
private boolean _jspx_meth_c_redirect_1(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_1, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:redirect
org.apache.taglibs.standard.tag.rt.core.RedirectTag _jspx_th_c_redirect_1 = (org.apache.taglibs.standard.tag.rt.core.RedirectTag) _jspx_tagPool_c_redirect_url_nobody.get(org.apache.taglibs.standard.tag.rt.core.RedirectTag.class);
_jspx_th_c_redirect_1.setPageContext(_jspx_page_context);
_jspx_th_c_redirect_1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_1);
_jspx_th_c_redirect_1.setUrl("/AcessoNegado.jsp");
int _jspx_eval_c_redirect_1 = _jspx_th_c_redirect_1.doStartTag();
if (_jspx_th_c_redirect_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_redirect_url_nobody.reuse(_jspx_th_c_redirect_1);
return true;
}
_jspx_tagPool_c_redirect_url_nobody.reuse(_jspx_th_c_redirect_1);
return false;
}
private boolean _jspx_meth_c_when_2(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_0, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_2 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_2.setPageContext(_jspx_page_context);
_jspx_th_c_when_2.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_0);
_jspx_th_c_when_2.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${sessionStatus == 0}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_2 = _jspx_th_c_when_2.doStartTag();
if (_jspx_eval_c_when_2 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_set_2((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_2, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_redirect_2((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_2, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_2.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_2);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_2);
return false;
}
private boolean _jspx_meth_c_set_2(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_2, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_2 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_scope_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_2.setPageContext(_jspx_page_context);
_jspx_th_c_set_2.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_2);
_jspx_th_c_set_2.setVar("msg");
_jspx_th_c_set_2.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${true}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
_jspx_th_c_set_2.setScope("session");
int _jspx_eval_c_set_2 = _jspx_th_c_set_2.doStartTag();
if (_jspx_th_c_set_2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_scope_nobody.reuse(_jspx_th_c_set_2);
return true;
}
_jspx_tagPool_c_set_var_value_scope_nobody.reuse(_jspx_th_c_set_2);
return false;
}
private boolean _jspx_meth_c_redirect_2(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_2, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:redirect
org.apache.taglibs.standard.tag.rt.core.RedirectTag _jspx_th_c_redirect_2 = (org.apache.taglibs.standard.tag.rt.core.RedirectTag) _jspx_tagPool_c_redirect_url_nobody.get(org.apache.taglibs.standard.tag.rt.core.RedirectTag.class);
_jspx_th_c_redirect_2.setPageContext(_jspx_page_context);
_jspx_th_c_redirect_2.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_2);
_jspx_th_c_redirect_2.setUrl("/AcessoNegado.jsp");
int _jspx_eval_c_redirect_2 = _jspx_th_c_redirect_2.doStartTag();
if (_jspx_th_c_redirect_2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_redirect_url_nobody.reuse(_jspx_th_c_redirect_2);
return true;
}
_jspx_tagPool_c_redirect_url_nobody.reuse(_jspx_th_c_redirect_2);
return false;
}
private boolean _jspx_meth_c_set_3(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_3 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_3.setPageContext(_jspx_page_context);
_jspx_th_c_set_3.setParent(null);
_jspx_th_c_set_3.setVar("pg");
_jspx_th_c_set_3.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${param.pg}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_3 = _jspx_th_c_set_3.doStartTag();
if (_jspx_th_c_set_3.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_3);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_3);
return false;
}
private boolean _jspx_meth_c_set_4(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_4 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_4.setPageContext(_jspx_page_context);
_jspx_th_c_set_4.setParent(null);
_jspx_th_c_set_4.setVar("pf");
_jspx_th_c_set_4.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${param.pf}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_4 = _jspx_th_c_set_4.doStartTag();
if (_jspx_th_c_set_4.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_4);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_4);
return false;
}
private boolean _jspx_meth_c_set_5(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_5 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_5.setPageContext(_jspx_page_context);
_jspx_th_c_set_5.setParent(null);
_jspx_th_c_set_5.setVar("pi");
_jspx_th_c_set_5.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${param.pi}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_5 = _jspx_th_c_set_5.doStartTag();
if (_jspx_th_c_set_5.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_5);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_5);
return false;
}
private boolean _jspx_meth_c_set_6(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_6 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_6.setPageContext(_jspx_page_context);
_jspx_th_c_set_6.setParent(null);
_jspx_th_c_set_6.setVar("q");
_jspx_th_c_set_6.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${param.q}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_6 = _jspx_th_c_set_6.doStartTag();
if (_jspx_th_c_set_6.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_6);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_6);
return false;
}
private boolean _jspx_meth_c_set_7(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_7 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_7.setPageContext(_jspx_page_context);
_jspx_th_c_set_7.setParent(null);
_jspx_th_c_set_7.setVar("execucao");
_jspx_th_c_set_7.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${param.execucao}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_7 = _jspx_th_c_set_7.doStartTag();
if (_jspx_th_c_set_7.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_7);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_7);
return false;
}
private boolean _jspx_meth_c_choose_1(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_1 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_1.setPageContext(_jspx_page_context);
_jspx_th_c_choose_1.setParent(null);
int _jspx_eval_c_choose_1 = _jspx_th_c_choose_1.doStartTag();
if (_jspx_eval_c_choose_1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_when_3((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_1, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_when_4((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_1, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_otherwise_0((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_1, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_1.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_1);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_1);
return false;
}
private boolean _jspx_meth_c_when_3(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_1, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_3 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_3.setPageContext(_jspx_page_context);
_jspx_th_c_when_3.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_1);
_jspx_th_c_when_3.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao=='insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_3 = _jspx_th_c_when_3.doStartTag();
if (_jspx_eval_c_when_3 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" Cadastro de\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_3.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_3.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_3);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_3);
return false;
}
private boolean _jspx_meth_c_when_4(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_1, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_4 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_4.setPageContext(_jspx_page_context);
_jspx_th_c_when_4.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_1);
_jspx_th_c_when_4.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao=='edit'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_4 = _jspx_th_c_when_4.doStartTag();
if (_jspx_eval_c_when_4 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" Alterar dados do\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_4.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_4.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_4);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_4);
return false;
}
private boolean _jspx_meth_c_otherwise_0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_1, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_0 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_0.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_1);
int _jspx_eval_c_otherwise_0 = _jspx_th_c_otherwise_0.doStartTag();
if (_jspx_eval_c_otherwise_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" Detalhes do\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_0);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_0);
return false;
}
private boolean _jspx_meth_c_choose_2(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_2 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_2.setPageContext(_jspx_page_context);
_jspx_th_c_choose_2.setParent(null);
int _jspx_eval_c_choose_2 = _jspx_th_c_choose_2.doStartTag();
if (_jspx_eval_c_choose_2 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_when_5((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_2, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_when_6((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_2, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_otherwise_1((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_2, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_2.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_2);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_2);
return false;
}
private boolean _jspx_meth_c_when_5(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_2, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_5 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_5.setPageContext(_jspx_page_context);
_jspx_th_c_when_5.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_2);
_jspx_th_c_when_5.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao=='insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_5 = _jspx_th_c_when_5.doStartTag();
if (_jspx_eval_c_when_5 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" <input type=\"text\" name=\"perfil\" placeholder=\"Nome do perfil\" id=\"sigla\" onblur=\"alertSigla(this)\" onfocus=\"alertSiglaClear()\" class=\"col-sm-7 col-sm-12\" required=\"required\" maxlength=\"51\">\r\n");
out.write(" <span id=\"alertSigla\"></span>\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_5.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_5.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_5);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_5);
return false;
}
private boolean _jspx_meth_c_when_6(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_2, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_6 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_6.setPageContext(_jspx_page_context);
_jspx_th_c_when_6.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_2);
_jspx_th_c_when_6.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao=='edit'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_6 = _jspx_th_c_when_6.doStartTag();
if (_jspx_eval_c_when_6 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" <input type=\"text\" name=\"perfil\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${per.nmPerfil}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" id=\"sigla\" onblur=\"alertSigla(this)\" onfocus=\"alertSiglaClear()\" class=\"col-sm-7 col-sm-12\" required=\"required\" maxlength=\"51\">\r\n");
out.write(" <span id=\"alertSigla\"></span>\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_6.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_6.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_6);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_6);
return false;
}
private boolean _jspx_meth_c_otherwise_1(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_2, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_1 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_1.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_2);
int _jspx_eval_c_otherwise_1 = _jspx_th_c_otherwise_1.doStartTag();
if (_jspx_eval_c_otherwise_1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" <label class=\"lead\">");
if (_jspx_meth_c_out_0((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_otherwise_1, _jspx_page_context))
return true;
out.write("</label >\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_1.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_1);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_1);
return false;
}
private boolean _jspx_meth_c_out_0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_otherwise_1, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:out
org.apache.taglibs.standard.tag.rt.core.OutTag _jspx_th_c_out_0 = (org.apache.taglibs.standard.tag.rt.core.OutTag) _jspx_tagPool_c_out_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.OutTag.class);
_jspx_th_c_out_0.setPageContext(_jspx_page_context);
_jspx_th_c_out_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_otherwise_1);
_jspx_th_c_out_0.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${per.nmPerfil}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_out_0 = _jspx_th_c_out_0.doStartTag();
if (_jspx_th_c_out_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_0);
return true;
}
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_0);
return false;
}
private boolean _jspx_meth_c_choose_3(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_3 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_3.setPageContext(_jspx_page_context);
_jspx_th_c_choose_3.setParent(null);
int _jspx_eval_c_choose_3 = _jspx_th_c_choose_3.doStartTag();
if (_jspx_eval_c_choose_3 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_when_7((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_3, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_when_8((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_3, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_otherwise_2((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_3, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_3.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_3.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_3);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_3);
return false;
}
private boolean _jspx_meth_c_when_7(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_3, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_7 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_7.setPageContext(_jspx_page_context);
_jspx_th_c_when_7.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_3);
_jspx_th_c_when_7.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao=='insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_7 = _jspx_th_c_when_7.doStartTag();
if (_jspx_eval_c_when_7 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" <textarea class=\"form-control\" id=\"form-field-8\" name=\"descricao\" placeholder=\"Resumo do perfil\" required=\"required\"></textarea>\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_7.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_7.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_7);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_7);
return false;
}
private boolean _jspx_meth_c_when_8(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_3, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_8 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_8.setPageContext(_jspx_page_context);
_jspx_th_c_when_8.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_3);
_jspx_th_c_when_8.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao=='edit'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_8 = _jspx_th_c_when_8.doStartTag();
if (_jspx_eval_c_when_8 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" <textarea class=\"form-control\" id=\"form-field-8\" name=\"descricao\" placeholder=\"Resumo do perfil\" required=\"required\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${per.dsPerfil}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</textarea>\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_8.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_8.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_8);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_8);
return false;
}
private boolean _jspx_meth_c_otherwise_2(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_3, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_2 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_2.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_2.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_3);
int _jspx_eval_c_otherwise_2 = _jspx_th_c_otherwise_2.doStartTag();
if (_jspx_eval_c_otherwise_2 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" <textarea class=\"form-control\" id=\"form-field-8\" name=\"descricao\" placeholder=\"Resumo do perfil\" readonly=\"readonly\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${per.dsPerfil}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</textarea>\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_2.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_2);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_2);
return false;
}
private boolean _jspx_meth_c_choose_4(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_4 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_4.setPageContext(_jspx_page_context);
_jspx_th_c_choose_4.setParent(null);
int _jspx_eval_c_choose_4 = _jspx_th_c_choose_4.doStartTag();
if (_jspx_eval_c_choose_4 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_when_9((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_4, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_otherwise_3((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_4, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_4.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_4.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_4);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_4);
return false;
}
private boolean _jspx_meth_c_when_9(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_4, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_9 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_9.setPageContext(_jspx_page_context);
_jspx_th_c_when_9.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_4);
_jspx_th_c_when_9.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao=='insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_9 = _jspx_th_c_when_9.doStartTag();
if (_jspx_eval_c_when_9 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" <label class=\"pull-left inline\">\r\n");
out.write(" <input id=\"id-button-borders\" type=\"checkbox\" id=\"\" name=\"ler\" value=\"1\" class=\"ace ace-switch ace-switch-5\" >\r\n");
out.write(" <span class=\"lbl middle\"></span>\r\n");
out.write(" </label> \r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_9.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_9.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_9);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_9);
return false;
}
private boolean _jspx_meth_c_otherwise_3(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_4, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_3 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_3.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_3.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_4);
int _jspx_eval_c_otherwise_3 = _jspx_th_c_otherwise_3.doStartTag();
if (_jspx_eval_c_otherwise_3 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write(" \r\n");
out.write(" ");
if (_jspx_meth_c_choose_5((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_otherwise_3, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_3.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_3.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_3);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_3);
return false;
}
private boolean _jspx_meth_c_choose_5(javax.servlet.jsp.tagext.JspTag _jspx_th_c_otherwise_3, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_5 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_5.setPageContext(_jspx_page_context);
_jspx_th_c_choose_5.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_otherwise_3);
int _jspx_eval_c_choose_5 = _jspx_th_c_choose_5.doStartTag();
if (_jspx_eval_c_choose_5 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_when_10((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_5, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_otherwise_4((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_5, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_5.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_5.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_5);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_5);
return false;
}
private boolean _jspx_meth_c_when_10(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_5, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_10 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_10.setPageContext(_jspx_page_context);
_jspx_th_c_when_10.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_5);
_jspx_th_c_when_10.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${per.nrLer != 1}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_10 = _jspx_th_c_when_10.doStartTag();
if (_jspx_eval_c_when_10 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" <label class=\"pull-left inline\">\r\n");
out.write(" <input id=\"id-button-borders\" type=\"checkbox\" id=\"\" name=\"ler\" value=\"1\" class=\"ace ace-switch ace-switch-5\" >\r\n");
out.write(" <span class=\"lbl middle\"></span>\r\n");
out.write(" </label> \r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_10.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_10.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_10);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_10);
return false;
}
private boolean _jspx_meth_c_otherwise_4(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_5, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_4 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_4.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_4.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_5);
int _jspx_eval_c_otherwise_4 = _jspx_th_c_otherwise_4.doStartTag();
if (_jspx_eval_c_otherwise_4 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" <label class=\"pull-left inline\">\r\n");
out.write(" <input id=\"id-button-borders\" checked=\"checked\" id=\"\" name=\"ler\" value=\"1\" type=\"checkbox\" class=\"ace ace-switch ace-switch-5\" >\r\n");
out.write(" <span class=\"lbl middle\"></span>\r\n");
out.write(" </label> \r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_4.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_4.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_4);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_4);
return false;
}
private boolean _jspx_meth_c_choose_6(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_6 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_6.setPageContext(_jspx_page_context);
_jspx_th_c_choose_6.setParent(null);
int _jspx_eval_c_choose_6 = _jspx_th_c_choose_6.doStartTag();
if (_jspx_eval_c_choose_6 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_when_11((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_6, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_otherwise_5((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_6, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_6.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_6.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_6);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_6);
return false;
}
private boolean _jspx_meth_c_when_11(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_6, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_11 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_11.setPageContext(_jspx_page_context);
_jspx_th_c_when_11.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_6);
_jspx_th_c_when_11.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao=='insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_11 = _jspx_th_c_when_11.doStartTag();
if (_jspx_eval_c_when_11 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" <label class=\"pull-left inline\">\r\n");
out.write(" <input id=\"id-button-borders\" type=\"checkbox\" id=\"\" name=\"inserir\" value=\"1\" class=\"ace ace-switch ace-switch-5\" >\r\n");
out.write(" <span class=\"lbl middle\"></span>\r\n");
out.write(" </label> \r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_11.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_11.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_11);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_11);
return false;
}
private boolean _jspx_meth_c_otherwise_5(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_6, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_5 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_5.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_5.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_6);
int _jspx_eval_c_otherwise_5 = _jspx_th_c_otherwise_5.doStartTag();
if (_jspx_eval_c_otherwise_5 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write(" \r\n");
out.write(" ");
if (_jspx_meth_c_choose_7((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_otherwise_5, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_5.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_5.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_5);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_5);
return false;
}
private boolean _jspx_meth_c_choose_7(javax.servlet.jsp.tagext.JspTag _jspx_th_c_otherwise_5, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_7 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_7.setPageContext(_jspx_page_context);
_jspx_th_c_choose_7.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_otherwise_5);
int _jspx_eval_c_choose_7 = _jspx_th_c_choose_7.doStartTag();
if (_jspx_eval_c_choose_7 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_when_12((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_7, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_otherwise_6((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_7, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_7.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_7.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_7);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_7);
return false;
}
private boolean _jspx_meth_c_when_12(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_7, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_12 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_12.setPageContext(_jspx_page_context);
_jspx_th_c_when_12.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_7);
_jspx_th_c_when_12.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${per.nrInserir != 1}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_12 = _jspx_th_c_when_12.doStartTag();
if (_jspx_eval_c_when_12 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" <label class=\"pull-left inline\">\r\n");
out.write(" <input id=\"id-button-borders\" type=\"checkbox\" id=\"\" name=\"inserir\" value=\"1\" class=\"ace ace-switch ace-switch-5\" >\r\n");
out.write(" <span class=\"lbl middle\"></span>\r\n");
out.write(" </label> \r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_12.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_12.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_12);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_12);
return false;
}
private boolean _jspx_meth_c_otherwise_6(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_7, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_6 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_6.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_6.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_7);
int _jspx_eval_c_otherwise_6 = _jspx_th_c_otherwise_6.doStartTag();
if (_jspx_eval_c_otherwise_6 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" <label class=\"pull-left inline\">\r\n");
out.write(" <input id=\"id-button-borders\" checked=\"checked\" id=\"\" name=\"inserir\" value=\"1\" type=\"checkbox\" class=\"ace ace-switch ace-switch-5\" >\r\n");
out.write(" <span class=\"lbl middle\"></span>\r\n");
out.write(" </label> \r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_6.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_6.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_6);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_6);
return false;
}
private boolean _jspx_meth_c_choose_8(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_8 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_8.setPageContext(_jspx_page_context);
_jspx_th_c_choose_8.setParent(null);
int _jspx_eval_c_choose_8 = _jspx_th_c_choose_8.doStartTag();
if (_jspx_eval_c_choose_8 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_when_13((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_8, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_otherwise_7((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_8, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_8.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_8.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_8);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_8);
return false;
}
private boolean _jspx_meth_c_when_13(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_8, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_13 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_13.setPageContext(_jspx_page_context);
_jspx_th_c_when_13.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_8);
_jspx_th_c_when_13.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao=='insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_13 = _jspx_th_c_when_13.doStartTag();
if (_jspx_eval_c_when_13 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" <label class=\"pull-left inline\">\r\n");
out.write(" <input id=\"id-button-borders\" type=\"checkbox\" id=\"\" name=\"editar\" value=\"1\" class=\"ace ace-switch ace-switch-5\" >\r\n");
out.write(" <span class=\"lbl middle\"></span>\r\n");
out.write(" </label> \r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_13.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_13.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_13);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_13);
return false;
}
private boolean _jspx_meth_c_otherwise_7(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_8, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_7 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_7.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_7.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_8);
int _jspx_eval_c_otherwise_7 = _jspx_th_c_otherwise_7.doStartTag();
if (_jspx_eval_c_otherwise_7 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write(" \r\n");
out.write(" ");
if (_jspx_meth_c_choose_9((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_otherwise_7, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_7.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_7.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_7);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_7);
return false;
}
private boolean _jspx_meth_c_choose_9(javax.servlet.jsp.tagext.JspTag _jspx_th_c_otherwise_7, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_9 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_9.setPageContext(_jspx_page_context);
_jspx_th_c_choose_9.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_otherwise_7);
int _jspx_eval_c_choose_9 = _jspx_th_c_choose_9.doStartTag();
if (_jspx_eval_c_choose_9 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_when_14((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_9, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_otherwise_8((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_9, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_9.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_9.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_9);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_9);
return false;
}
private boolean _jspx_meth_c_when_14(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_9, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_14 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_14.setPageContext(_jspx_page_context);
_jspx_th_c_when_14.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_9);
_jspx_th_c_when_14.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${per.nrEditar != 1}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_14 = _jspx_th_c_when_14.doStartTag();
if (_jspx_eval_c_when_14 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" <label class=\"pull-left inline\">\r\n");
out.write(" <input id=\"id-button-borders\" type=\"checkbox\" id=\"\" name=\"editar\" value=\"1\" class=\"ace ace-switch ace-switch-5\" >\r\n");
out.write(" <span class=\"lbl middle\"></span>\r\n");
out.write(" </label> \r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_14.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_14.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_14);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_14);
return false;
}
private boolean _jspx_meth_c_otherwise_8(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_9, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_8 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_8.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_8.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_9);
int _jspx_eval_c_otherwise_8 = _jspx_th_c_otherwise_8.doStartTag();
if (_jspx_eval_c_otherwise_8 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" <label class=\"pull-left inline\">\r\n");
out.write(" <input id=\"id-button-borders\" checked=\"checked\" id=\"\" name=\"editar\" value=\"1\" type=\"checkbox\" class=\"ace ace-switch ace-switch-5\" >\r\n");
out.write(" <span class=\"lbl middle\"></span>\r\n");
out.write(" </label> \r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_8.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_8.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_8);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_8);
return false;
}
private boolean _jspx_meth_c_choose_10(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_10 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_10.setPageContext(_jspx_page_context);
_jspx_th_c_choose_10.setParent(null);
int _jspx_eval_c_choose_10 = _jspx_th_c_choose_10.doStartTag();
if (_jspx_eval_c_choose_10 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_when_15((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_10, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_otherwise_9((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_10, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_10.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_10.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_10);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_10);
return false;
}
private boolean _jspx_meth_c_when_15(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_10, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_15 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_15.setPageContext(_jspx_page_context);
_jspx_th_c_when_15.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_10);
_jspx_th_c_when_15.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao=='insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_15 = _jspx_th_c_when_15.doStartTag();
if (_jspx_eval_c_when_15 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" <label class=\"pull-left inline\">\r\n");
out.write(" <input id=\"id-button-borders\" type=\"checkbox\" id=\"\" name=\"excluir\" value=\"1\" class=\"ace ace-switch ace-switch-5\" >\r\n");
out.write(" <span class=\"lbl middle\"></span>\r\n");
out.write(" </label> \r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_15.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_15.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_15);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_15);
return false;
}
private boolean _jspx_meth_c_otherwise_9(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_10, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_9 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_9.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_9.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_10);
int _jspx_eval_c_otherwise_9 = _jspx_th_c_otherwise_9.doStartTag();
if (_jspx_eval_c_otherwise_9 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write(" \r\n");
out.write(" ");
if (_jspx_meth_c_choose_11((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_otherwise_9, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_9.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_9.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_9);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_9);
return false;
}
private boolean _jspx_meth_c_choose_11(javax.servlet.jsp.tagext.JspTag _jspx_th_c_otherwise_9, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_11 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_11.setPageContext(_jspx_page_context);
_jspx_th_c_choose_11.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_otherwise_9);
int _jspx_eval_c_choose_11 = _jspx_th_c_choose_11.doStartTag();
if (_jspx_eval_c_choose_11 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_when_16((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_11, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_otherwise_10((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_11, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_11.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_11.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_11);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_11);
return false;
}
private boolean _jspx_meth_c_when_16(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_11, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_16 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_16.setPageContext(_jspx_page_context);
_jspx_th_c_when_16.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_11);
_jspx_th_c_when_16.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${per.nrExcluir != 1}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_16 = _jspx_th_c_when_16.doStartTag();
if (_jspx_eval_c_when_16 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" <label class=\"pull-left inline\">\r\n");
out.write(" <input id=\"id-button-borders\" type=\"checkbox\" id=\"\" name=\"excluir\" value=\"1\" class=\"ace ace-switch ace-switch-5\" >\r\n");
out.write(" <span class=\"lbl middle\"></span>\r\n");
out.write(" </label> \r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_16.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_16.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_16);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_16);
return false;
}
private boolean _jspx_meth_c_otherwise_10(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_11, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_10 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_10.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_10.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_11);
int _jspx_eval_c_otherwise_10 = _jspx_th_c_otherwise_10.doStartTag();
if (_jspx_eval_c_otherwise_10 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" <label class=\"pull-left inline\">\r\n");
out.write(" <input id=\"id-button-borders\" checked=\"checked\" id=\"\" name=\"excluir\" value=\"1\" type=\"checkbox\" class=\"ace ace-switch ace-switch-5\" >\r\n");
out.write(" <span class=\"lbl middle\"></span>\r\n");
out.write(" </label> \r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_10.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_10.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_10);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_10);
return false;
}
private boolean _jspx_meth_c_choose_12(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_12 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_12.setPageContext(_jspx_page_context);
_jspx_th_c_choose_12.setParent(null);
int _jspx_eval_c_choose_12 = _jspx_th_c_choose_12.doStartTag();
if (_jspx_eval_c_choose_12 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_when_17((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_12, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_otherwise_11((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_12, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_12.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_12.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_12);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_12);
return false;
}
private boolean _jspx_meth_c_when_17(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_12, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_17 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_17.setPageContext(_jspx_page_context);
_jspx_th_c_when_17.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_12);
_jspx_th_c_when_17.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao=='insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_17 = _jspx_th_c_when_17.doStartTag();
if (_jspx_eval_c_when_17 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" <label class=\"pull-left inline\">\r\n");
out.write(" <input id=\"id-button-borders\" type=\"checkbox\" id=\"\" name=\"gerenciar\" value=\"1\" class=\"ace ace-switch ace-switch-5\" >\r\n");
out.write(" <span class=\"lbl middle\"></span>\r\n");
out.write(" </label> \r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_17.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_17.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_17);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_17);
return false;
}
private boolean _jspx_meth_c_otherwise_11(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_12, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_11 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_11.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_11.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_12);
int _jspx_eval_c_otherwise_11 = _jspx_th_c_otherwise_11.doStartTag();
if (_jspx_eval_c_otherwise_11 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write(" \r\n");
out.write(" ");
if (_jspx_meth_c_choose_13((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_otherwise_11, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_11.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_11.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_11);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_11);
return false;
}
private boolean _jspx_meth_c_choose_13(javax.servlet.jsp.tagext.JspTag _jspx_th_c_otherwise_11, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_13 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_13.setPageContext(_jspx_page_context);
_jspx_th_c_choose_13.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_otherwise_11);
int _jspx_eval_c_choose_13 = _jspx_th_c_choose_13.doStartTag();
if (_jspx_eval_c_choose_13 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_when_18((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_13, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_otherwise_12((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_13, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_13.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_13.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_13);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_13);
return false;
}
private boolean _jspx_meth_c_when_18(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_13, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_18 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_18.setPageContext(_jspx_page_context);
_jspx_th_c_when_18.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_13);
_jspx_th_c_when_18.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${per.nrGerenciar != 1}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_18 = _jspx_th_c_when_18.doStartTag();
if (_jspx_eval_c_when_18 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" <label class=\"pull-left inline\">\r\n");
out.write(" <input id=\"id-button-borders\" type=\"checkbox\" id=\"\" name=\"gerenciar\" value=\"1\" class=\"ace ace-switch ace-switch-5\" >\r\n");
out.write(" <span class=\"lbl middle\"></span>\r\n");
out.write(" </label> \r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_18.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_18.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_18);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_18);
return false;
}
private boolean _jspx_meth_c_otherwise_12(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_13, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_12 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_12.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_12.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_13);
int _jspx_eval_c_otherwise_12 = _jspx_th_c_otherwise_12.doStartTag();
if (_jspx_eval_c_otherwise_12 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" <label class=\"pull-left inline\">\r\n");
out.write(" <input id=\"id-button-borders\" checked=\"checked\" id=\"\" name=\"gerenciar\" value=\"1\" type=\"checkbox\" class=\"ace ace-switch ace-switch-5\" >\r\n");
out.write(" <span class=\"lbl middle\"></span>\r\n");
out.write(" </label> \r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_12.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_12.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_12);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_12);
return false;
}
private boolean _jspx_meth_c_if_0(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_0 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_0.setPageContext(_jspx_page_context);
_jspx_th_c_if_0.setParent(null);
_jspx_th_c_if_0.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao=='edit' || execucao =='insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_0 = _jspx_th_c_if_0.doStartTag();
if (_jspx_eval_c_if_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" <button class=\"btn btn-success\" type=\"submit\" id=\"salvar\">\r\n");
out.write(" <i class=\"ace-icon fa fa-save bigger-110\"></i>\r\n");
out.write(" Salvar\r\n");
out.write(" </button>\r\n");
out.write(" \r\n");
out.write(" <button class=\"btn\" type=\"reset\">\r\n");
out.write(" <i class=\"ace-icon fa fa-eraser bigger-110\"></i>\r\n");
out.write(" Limpar\r\n");
out.write(" </button>\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_if_0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_0);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_0);
return false;
}
}
<file_sep>/src/java/br/com/Modelo/DispositivoLegal.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.Modelo;
/**
*
* @author d732229
*/
public class DispositivoLegal {
private int pkDisplegal, fkAutoCessao, fkTipoDisplegal;
private String nrDisp, nmTitulo, dtDisp, nmLogin, dthr_atualicacao;
private TipoDispositivoLegal tipoDispositivo;
public DispositivoLegal() {
}
public DispositivoLegal( int fkAutoCessao, int fkTipoDisplegal, String nrDisp, String dtDisp, String nmLogin) {
this.fkAutoCessao = fkAutoCessao;
this.fkTipoDisplegal = fkTipoDisplegal;
this.nrDisp = nrDisp;
this.dtDisp = dtDisp;
this.nmLogin = nmLogin;
}
public int getPkDisplegal() {
return pkDisplegal;
}
public void setPkDisplegal(int pkDisplegal) {
this.pkDisplegal = pkDisplegal;
}
public int getFkTipoDisplegal() {
return fkTipoDisplegal;
}
public void setFkTipoDisplegal(int fkTipoDisplegal) {
this.fkTipoDisplegal = fkTipoDisplegal;
}
public int getFkAutoCessao() {
return fkAutoCessao;
}
public void setFkAutoCessao(int fkAutoCessao) {
this.fkAutoCessao = fkAutoCessao;
}
public String getNrDisp() {
return nrDisp;
}
public void setNrDisp(String nrDisp) {
this.nrDisp = nrDisp;
}
public String getNmTitulo() {
return nmTitulo;
}
public void setNmTitulo(String nmTitulo) {
this.nmTitulo = nmTitulo;
}
public String getDtDisp() {
return dtDisp;
}
public void setDtDisp(String dtDisp) {
this.dtDisp = dtDisp;
}
public String getNmLogin() {
return nmLogin;
}
public void setNmLogin(String nmLogin) {
this.nmLogin = nmLogin;
}
public String getDthr_atualicacao() {
return dthr_atualicacao;
}
public void setDthr_atualicacao(String dthr_atualicacao) {
this.dthr_atualicacao = dthr_atualicacao;
}
public TipoDispositivoLegal getTipoDispositivo() {
return tipoDispositivo;
}
public void setTipoDispositivo(TipoDispositivoLegal tipoDispositivo) {
this.tipoDispositivo = tipoDispositivo;
}
}
<file_sep>/src/java/br/com/Modelo/CatAutoCessao.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.Modelo;
/**
*
* @author d732229
*/
public class CatAutoCessao {
private int pkCatAutoCessao;
private String sgCatAutoCessao, nmCatAutoCessao, nmLogin, dthrAtualizacao;
//Construtores
public CatAutoCessao(){
}
public CatAutoCessao(String sgCatAutoCessao, String nmCatAutoCessao, String nmLogin) {
this.sgCatAutoCessao = sgCatAutoCessao;
this.nmCatAutoCessao = nmCatAutoCessao;
this.nmLogin = nmLogin;
this.dthrAtualizacao = dthrAtualizacao;
}
public CatAutoCessao(int pkCatAutoCessao, String sgCatAutoCessao, String nmCatAutoCessao, String nmLogin) {
this (sgCatAutoCessao, nmCatAutoCessao, nmLogin);
this.pkCatAutoCessao = pkCatAutoCessao;
}
//Getters e Setters
public int getPkCatAutoCessao() {
return pkCatAutoCessao;
}
public void setPkCatAutoCessao(int pkCatAutoCessao) {
this.pkCatAutoCessao = pkCatAutoCessao;
}
public String getSgCatAutoCessao() {
return sgCatAutoCessao;
}
public void setSgCatAutoCessao(String sgCatAutoCessao) {
this.sgCatAutoCessao = sgCatAutoCessao;
}
public String getNmCatAutoCessao() {
return nmCatAutoCessao;
}
public void setNmCatAutoCessao(String nmCatAutoCessao) {
this.nmCatAutoCessao = nmCatAutoCessao;
}
public String getNmLogin() {
return nmLogin;
}
public void setNmLogin(String nmLogin) {
this.nmLogin = nmLogin;
}
public String getDthrAtualizacao() {
return dthrAtualizacao;
}
public void setDthrAtualizacao(String dthrAtualizacao) {
this.dthrAtualizacao = dthrAtualizacao;
}
}
<file_sep>/src/java/br/com/Controle/AutoCessaoUploadArquivo.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.Controle;
import br.com.Modelo.Logica;
import br.com.Modelo.Arquivo;
import br.com.Modelo.ArquivoDAO;
import br.com.Modelo.AutoCessaoDAO;
import br.com.Utilitario.Transformar;
import br.com.Utilitario.Upload;
import java.io.File;
import java.io.InputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
/**java servlet pathinfo
*
* @author d732229
*/
public class AutoCessaoUploadArquivo implements Logica{
@Override
public String executa(HttpServletRequest req,
HttpServletResponse res) throws Exception {
Upload up = new Upload();
AutoCessaoDAO autoDAO = new AutoCessaoDAO();
ArquivoDAO arDAO = new ArquivoDAO();
Arquivo ar = new Arquivo();
HttpSession session = req.getSession();
int pkAutoCessao, retiRati=0;
InputStream arquivoCarregado;
String nomeDoArquivo, retiRatificacao, extensaoArquivo, caminhoArquivo, tipoArquivo, nmNomeclatura, execucao, loginSessio, pastaArquivar, sistemaOperacional;
tipoArquivo = req.getParameter("tipoArquivo");
nmNomeclatura = req.getParameter("nmNomeclatura");
pkAutoCessao = Integer.parseInt(req.getParameter("pkAutoCessao"));
retiRatificacao = req.getParameter("retiRatificacao");
execucao = req.getParameter("execucao");
loginSessio =(String) session.getAttribute("sessionLogin");
sistemaOperacional = System.getProperty("os.name");
if(null != retiRatificacao){
retiRati = Integer.parseInt(retiRatificacao);
}
if (sistemaOperacional.equals("Linux")) {
File diretorio = new File("/opt/SGPatri/Arquivo/"+tipoArquivo);
boolean existente = diretorio.exists();
if (!existente) {
diretorio.mkdirs();
}
pastaArquivar = File.separator+"opt"+File.separator+"SGPatri"+File.separator+"Arquivo"+File.separator+tipoArquivo;
} else {
File diretorio = new File("C:/SGPatri/Arquivo/"+tipoArquivo);
boolean existente = diretorio.exists();
if (!existente) {
diretorio.mkdirs();
}
pastaArquivar = "C:"+File.separator+"SGPatri"+File.separator+"Arquivo"+File.separator+tipoArquivo;
}
int qtdRepetidos = arDAO.qtdRepetidos(pkAutoCessao, tipoArquivo);
Part ArquivoUpload = req.getPart("ArquivoUpload");
extensaoArquivo = Transformar.getFileExtension(ArquivoUpload.getSubmittedFileName());
nomeDoArquivo = "idAC-"+String.valueOf(pkAutoCessao)+"-"+tipoArquivo+extensaoArquivo;
if(qtdRepetidos > 0){
qtdRepetidos = qtdRepetidos-1;
nomeDoArquivo = String.valueOf(pkAutoCessao)+"-"+tipoArquivo+"-ratificacao-"+qtdRepetidos+extensaoArquivo;
retiRati = 1;
}
// nomeDoArquivo = Transformar.getSubstituiEspacoHifen(Transformar.getRetiraEspacosDuplicados(Transformar.getRemoveAccents(ArquivoUpload.getSubmittedFileName())));
arquivoCarregado = ArquivoUpload.getInputStream();
caminhoArquivo = up.upload(pastaArquivar, nomeDoArquivo, arquivoCarregado);
ar = new Arquivo(pkAutoCessao, retiRati, tipoArquivo, nomeDoArquivo, extensaoArquivo, caminhoArquivo, nmNomeclatura, loginSessio);
arDAO.cArquivo(ar);
if("Planta".equals(tipoArquivo)){
autoDAO.upAutoCessaoVerificadoArquivoPlanta(pkAutoCessao, 1);
}else{
autoDAO.upAutoCessaoVerificadoArquivoAc(pkAutoCessao, 1);
}
req.setAttribute("msg", "true");
req.setAttribute("tipoAler", "success");
req.setAttribute("alert", "Sucesso! ");
// if( pkAutoCessao > 4675){
// req.setAttribute("txtAlert", "Finalizado os cadastro do Auto Cessão");
// return "ControllerServlet?acao=AutoCessaoDetalhe&pkAutoStage="+pkAutoCessao+"&execucao=view";
// }else{
req.setAttribute("txtAlert", "O arquivo "+tipoArquivo+" foi incluido corretamente.");
// return "ControllerServlet?acao=AutoCessaoDetalhe&pkAutoStage="+pkAutoCessao+"&execucao="+execucao;
// }
// } else{
//
// req.setAttribute("msg", "true");
// req.setAttribute("tipoAler", "danger");
// req.setAttribute("alert", "Duplicidade ! ");
// req.setAttribute("txtAlert", "Excluir o arquivo para anexar um novo arquipo do tipo "+tipoArquivo+".");
// return"ControllerServlet?acao=AutoCessaoDetalhe&pkAutoCessao="+pkAutoCessao+"&execucao="+execucao;
// }
return "ControllerServlet?acao=AutoCessaoDetalhe&pkAutoStage="+pkAutoCessao+"&execucao="+execucao;
}
}
<file_sep>/lib/nblibraries.properties
libs.CopyLibs.classpath=\
${base}/CopyLibs/org-netbeans-modules-java-j2seproject-copylibstask.jar
libs.CopyLibs.displayName=Tarefa CopyLibs
libs.CopyLibs.prop-version=2.0
libs.javaee-endorsed-api-7.0.classpath=\
${base}/javaee-endorsed-api-7.0/javax.annotation-api.jar;\
${base}/javaee-endorsed-api-7.0/javax.xml.soap-api.jar;\
${base}/javaee-endorsed-api-7.0/jaxb-api-osgi.jar;\
${base}/javaee-endorsed-api-7.0/jaxws-api.jar;\
${base}/javaee-endorsed-api-7.0/jsr181-api.jar
libs.javaee-endorsed-api-7.0.displayName=Biblioteca de API Java EE 7 Endossada
libs.javaee-endorsed-api-7.0.javadoc=\
${base}/javaee-endorsed-api-7.0/javaee-doc-api.jar
libs.jsp-compilation-syscp.classpath=\
${base}/jsp-compilation-syscp/ant.jar;\
${base}/jsp-compilation-syscp/servlet3.1-jsp2.3-api.jar;\
${base}/jsp-compilation-syscp/glassfish-jspparser-4.0.jar;\
${base}/jsp-compilation-syscp/jstl-impl.jar;\
${base}/jsp-compilation-syscp/javax.faces.jar
libs.jsp-compilation-syscp.displayName=Sysclasspath da Compila\u00e7\u00e3o JSP
libs.jsp-compilation.classpath=\
${base}/jsp-compilation/ant.jar;\
${base}/jsp-compilation/servlet3.1-jsp2.3-api.jar;\
${base}/jsp-compilation/glassfish-jspparser-4.0.jar;\
${base}/jsp-compilation/javax.faces.jar;\
${base}/jsp-compilation/jstl-api.jar;\
${base}/jsp-compilation/ant-launcher.jar
libs.jsp-compilation.displayName=Compila\u00e7\u00e3o JSP
libs.jsp-compiler.classpath=\
${base}/jsp-compiler/jspcompile.jar
libs.jsp-compiler.displayName=Compilador JSP
libs.jstl.classpath=\
${base}/jstl/jstl-impl.jar;\
${base}/jstl/jstl-api.jar
libs.jstl.displayName=JSTL 1.2.1
libs.jstl.javadoc=\
${base}/jstl/javaee-doc-api.jar
libs.jstl.prop-maven-dependencies=\n javax.servlet.jsp.jstl:javax.servlet.jsp.jstl-api:1.2.1:jar\n org.glassfish.web:javax.servlet.jsp.jstl:1.2.2:jar\n
libs.PostgreSQLDriver.classpath=\
${base}/PostgreSQLDriver/postgresql-9.4.1209.jar
libs.PostgreSQLDriver.displayName=Driver JDBC do PostgreSQL
libs.PostgreSQLDriver.prop-maven-dependencies=org.postgresql:postgresql:9.4.1209:jar
<file_sep>/src/java/br/com/Controle/CatSubFinalidadeCU.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.Controle;
import br.com.Modelo.CatSubFinalidade;
import br.com.Modelo.CatSubFinalidadeDAO;
import br.com.Modelo.Logica;
import br.com.Utilitario.Transformar;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author d732229
*/
public class CatSubFinalidadeCU implements Logica{
@Override
public String executa(HttpServletRequest req,
HttpServletResponse res) throws Exception{
CatSubFinalidade catSub = new CatSubFinalidade();
CatSubFinalidadeDAO catSubDAO = new CatSubFinalidadeDAO();
HttpSession session = req.getSession();
//Atributo
int pkCatSubFinalidade, fkCategoria;
String sigla, catSubFinalidade, loginSessio, execucao;
//Carregando os atributos com as informações do formulário
execucao = req.getParameter("execucao");
fkCategoria = Integer.parseInt(req.getParameter("fkCategoria"));
sigla = req.getParameter("sigla").toUpperCase();
catSubFinalidade = Transformar.getRemoveAccents(req.getParameter("catSubFinalidade")).toUpperCase().trim();
loginSessio =(String) session.getAttribute("sessionLogin");
//Tratando para executar o inserir ou alterar, populando o objeto e gravando no banco
if ("edit".equals(execucao)){
pkCatSubFinalidade = Integer.parseInt(req.getParameter("pkCatSubFinalidade"));
catSub = new CatSubFinalidade(pkCatSubFinalidade, fkCategoria, sigla, catSubFinalidade, loginSessio);
catSubDAO.upCatSubFinalidade(catSub);
req.setAttribute("msg","alterou");
}else if ("insert".equals(execucao)) {
catSub = new CatSubFinalidade(fkCategoria, sigla, catSubFinalidade, loginSessio);
catSubDAO.cCatSubFinalidade(catSub);
req.setAttribute("msg","gravou");
}
return "ControllerServlet?acao=CatSubFinalidadeLista";
}
}
<file_sep>/src/java/br/com/Modelo/TipoAutoCessaoDAO.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.Modelo;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author d732229
*/
public class TipoAutoCessaoDAO extends FabricaConexao {
private Connection connection = getConnetion();
//Construtor
public TipoAutoCessaoDAO() {
this.connection = new FabricaConexao().getConnetion();
}
//Metodo de quantidade de linhas
public int qdTipoCessao (String q) throws SQLException{
PreparedStatement stmt = null;
ResultSet rs = null;
int total = 0;
String sql = ("SELECT COUNT(*) as total "
+ "FROM tbl_tipocessao "
+ "WHERE nm_tipocessao ILIKE ? ");
try{
stmt = connection.prepareStatement(sql);
stmt.setString(1, '%'+q+'%');
rs = stmt.executeQuery();
if(rs.next()){
total = rs.getInt("total");
}
stmt.execute();
return total;
}catch (SQLException e){
throw new RuntimeException(e);
}finally{
rs.close();
stmt.close();
connection.close();
}
}
//METODO lista os Tipos de Auto de Cessão das pesquisas e paginada
public List<TipoAutoCessao> listTpCessao (int qtLinha, int offset, String q ) throws SQLException{
PreparedStatement stmt = null;
ResultSet rs = null;
List<TipoAutoCessao> lisTpCessao = new ArrayList<TipoAutoCessao>();
String sql = ("SELECT id_tipocessao, fk_categoriauto, sg_categoriauto, nm_categoriaauto, nm_tipocessao, "
+ "nm_tipocessao, nm_login, dthr_atualizacao "
+ "FROM vw_tipocessaocompleto "
+ "WHERE nm_tipocessao ILIKE ? "
+ "ORDER BY nm_tipocessao "
+ "LIMIT ? OFFSET ? ");
try{
stmt = connection.prepareStatement(sql);
stmt.setString(1,'%'+q+'%');
stmt.setInt(2, qtLinha);
stmt.setInt(3, offset);
rs = stmt.executeQuery();
while (rs.next()){
TipoAutoCessao tpCessao = new TipoAutoCessao();
tpCessao.setPkTipoAutoCessao(rs.getInt("id_tipocessao"));
tpCessao.setFkCatAutoCessao(rs.getInt("fk_categoriauto"));
tpCessao.setSgCatAutoCessao(rs.getString("sg_categoriauto"));
tpCessao.setNmCatAutoCessao(rs.getString("nm_categoriaauto"));
tpCessao.setNmTipoAutoCessao(rs.getString("nm_tipocessao"));
tpCessao.setNmLogin(rs.getString("nm_login"));
tpCessao.setDthrAtualizacao(rs.getString("dthr_atualizacao"));
lisTpCessao.add(tpCessao);
}
return lisTpCessao;
}catch (SQLException e){
throw new RuntimeException(e);
}finally{
rs.close();
stmt.close();
connection.close();
}
}
//METODO utilizado para retornar as informação de um Tipo de Auto Cessão
public TipoAutoCessao detalheTpCessao(int pkTipoAutoCessao) throws SQLException{
PreparedStatement stmt = null;
ResultSet rs = null;
TipoAutoCessao tpCessao = new TipoAutoCessao();
String sql = "SELECT id_tipocessao, fk_categoriauto, sg_categoriauto, nm_categoriaauto, nm_tipocessao, nm_login, dthr_atualizacao "
+ "FROM vw_tipocessaocompleto "
+ "WHERE id_tipocessao = ?";
try{
stmt = connection.prepareStatement(sql);
stmt.setInt(1, pkTipoAutoCessao);
rs = stmt.executeQuery();
if(rs.next()){
tpCessao.setPkTipoAutoCessao(rs.getInt("id_tipocessao"));
tpCessao.setFkCatAutoCessao(rs.getInt("fk_categoriauto"));
tpCessao.setSgCatAutoCessao(rs.getString("sg_categoriauto"));
tpCessao.setNmCatAutoCessao(rs.getString("nm_categoriaauto"));
tpCessao.setNmTipoAutoCessao(rs.getString("nm_tipocessao"));
tpCessao.setNmLogin(rs.getString("nm_login"));
tpCessao.setDthrAtualizacao(rs.getString("dthr_atualizacao"));
}
return tpCessao;
}catch (SQLException e){
throw new RuntimeException(e);
}finally{
rs.close();
stmt.close();
// connection.close();
}
}
//METODO utilizado para inserir uma novo Tipo de Auto de Cessao no BANCO
public void cTipoCessao(TipoAutoCessao tpCessao) throws SQLException{
PreparedStatement stmt = null;
String sql = "INSERT INTO tbl_tipocessao "
+ "(fk_categoriauto, nm_tipocessao, nm_login, dthr_atualizacao ) "
+ "VALUES (?,?,?,? )";
try{
stmt = connection.prepareStatement(sql);
stmt.setInt(1, tpCessao.getFkCatAutoCessao());
stmt.setString(2, tpCessao.getNmTipoAutoCessao());
stmt.setString(3, tpCessao.getNmLogin());
stmt.setTimestamp(4,java.sql.Timestamp.valueOf(java.time.LocalDateTime.now()));
stmt.execute();
}catch (SQLException e){
throw new RuntimeException(e);
}finally{
stmt.close();
connection.close();
}
}
//MEDOTO utilizado para realizar a alteração das informações de um Tipo de Auto de Cessão
public void upTipoCessao(TipoAutoCessao tpCessao) throws SQLException{
PreparedStatement stmt = null;
String sql = "UPDATE tbl_tipocessao "
+"SET fk_categoriauto=?, nm_tipocessao=?, nm_login=?, dthr_atualizacao=? "
+"WHERE id_tipocessao = ?";
try{
stmt = connection.prepareStatement(sql);
stmt.setInt(1, tpCessao.getFkCatAutoCessao());
stmt.setString(2, tpCessao.getNmTipoAutoCessao());
stmt.setString(3, tpCessao.getNmLogin() );
stmt.setTimestamp(4,java.sql.Timestamp.valueOf(java.time.LocalDateTime.now()));
stmt.setInt(5, tpCessao.getPkTipoAutoCessao());
stmt.execute();
}catch (SQLException e){
throw new RuntimeException(e);
}finally{
stmt.close();
connection.close();
}
}
//METODO lista os Tipo de Auto Cessão para campo select
public List<TipoAutoCessao> listSelectTpCessao() throws SQLException {
PreparedStatement stmt = null;
ResultSet rs = null;
List<TipoAutoCessao> lisTpCessao = new ArrayList<TipoAutoCessao>();
String sql = "SELECT id_tipocessao, fk_categoriauto, sg_categoriauto, nm_categoriaauto, "
+ "nm_tipocessao, nm_login, dthr_atualizacao "
+ "FROM vw_tipocessaocompleto "
+ "ORDER BY nm_tipocessao ";
try {
stmt = connection.prepareStatement(sql);
rs = stmt.executeQuery();
while (rs.next()){
TipoAutoCessao tpCessao = new TipoAutoCessao();
tpCessao.setPkTipoAutoCessao(rs.getInt("id_tipocessao"));
tpCessao.setFkCatAutoCessao(rs.getInt("fk_categoriauto"));
tpCessao.setSgCatAutoCessao(rs.getString("sg_categoriauto"));
tpCessao.setNmCatAutoCessao(rs.getString("nm_categoriaauto"));
tpCessao.setNmTipoAutoCessao(rs.getString("nm_tipocessao"));
tpCessao.setNmLogin(rs.getString("nm_login"));
tpCessao.setDthrAtualizacao(rs.getString("dthr_atualizacao"));
lisTpCessao.add(tpCessao);
}
stmt.execute();
return lisTpCessao;
} catch (SQLException e) {
throw new RuntimeException(e);
}finally{
rs.close();
stmt.close();
connection.close();
}
}
}
<file_sep>/build/generated/src/org/apache/jsp/AutoCessaoCRU_jsp.java
package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class AutoCessaoCRU_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.List<String> _jspx_dependants;
static {
_jspx_dependants = new java.util.ArrayList<String>(1);
_jspx_dependants.add("/include/ControleAcesso.jsp");
}
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_forEach_var_items;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_set_var_value_nobody;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_redirect_url_nobody;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_set_var_value_scope_nobody;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_out_value_nobody;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_fmt_formatDate_var_value_pattern_nobody;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_choose;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_if_test;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_fmt_parseDate_var_value_pattern_nobody;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_otherwise;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_when_test;
private org.glassfish.jsp.api.ResourceInjector _jspx_resourceInjector;
public java.util.List<String> getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_jspx_tagPool_c_forEach_var_items = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_c_set_var_value_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_c_redirect_url_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_c_set_var_value_scope_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_c_out_value_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_fmt_formatDate_var_value_pattern_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_c_choose = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_c_if_test = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_fmt_parseDate_var_value_pattern_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_c_otherwise = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_c_when_test = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
}
public void _jspDestroy() {
_jspx_tagPool_c_forEach_var_items.release();
_jspx_tagPool_c_set_var_value_nobody.release();
_jspx_tagPool_c_redirect_url_nobody.release();
_jspx_tagPool_c_set_var_value_scope_nobody.release();
_jspx_tagPool_c_out_value_nobody.release();
_jspx_tagPool_fmt_formatDate_var_value_pattern_nobody.release();
_jspx_tagPool_c_choose.release();
_jspx_tagPool_c_if_test.release();
_jspx_tagPool_fmt_parseDate_var_value_pattern_nobody.release();
_jspx_tagPool_c_otherwise.release();
_jspx_tagPool_c_when_test.release();
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html charset=UTF-8;");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
_jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("<!DOCTYPE html>\n");
out.write("<html>\n");
out.write(" \n");
out.write(" ");
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "include/head.jsp", out, false);
out.write("\n");
out.write(" \n");
out.write(" <body class=\"no-skin\">\n");
out.write(" ");
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "include/top.jsp", out, false);
out.write("\n");
out.write(" <div class=\"main-container ace-save-state\" id=\"main-container\">\n");
out.write(" ");
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "include/nav.jsp", out, false);
out.write("\n");
out.write(" ");
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "include/adicionarCampo.jsp", out, false);
out.write("\n");
out.write(" ");
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "javaScritp/ajaxSelectSubFinalidade.html", out, false);
out.write("\n");
out.write(" ");
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "javaScritp/AutoCessaoValidacao.html", out, false);
out.write("\n");
out.write(" ");
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "javaScritp/maskProcesso.html", out, false);
out.write("\n");
out.write(" ");
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "javaScritp/somenteNum.html", out, false);
out.write("\n");
out.write(" \n");
out.write(" \n");
out.write("\n");
out.write("<!--Verificação de acesso -->\n");
out.write(" ");
if (_jspx_meth_c_set_0(_jspx_page_context))
return;
out.write("\n");
out.write(" ");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
if (_jspx_meth_c_choose_0(_jspx_page_context))
return;
out.write("\n");
out.write(" \n");
out.write(" \n");
out.write(" \n");
out.write(" ");
br.com.Modelo.TipoAutoCessaoDAO TpCessao = null;
synchronized (_jspx_page_context) {
TpCessao = (br.com.Modelo.TipoAutoCessaoDAO) _jspx_page_context.getAttribute("TpCessao", PageContext.PAGE_SCOPE);
if (TpCessao == null){
TpCessao = new br.com.Modelo.TipoAutoCessaoDAO();
_jspx_page_context.setAttribute("TpCessao", TpCessao, PageContext.PAGE_SCOPE);
}
}
out.write("\n");
out.write(" ");
br.com.Modelo.CatFinalidadeDAO CatFin = null;
synchronized (_jspx_page_context) {
CatFin = (br.com.Modelo.CatFinalidadeDAO) _jspx_page_context.getAttribute("CatFin", PageContext.PAGE_SCOPE);
if (CatFin == null){
CatFin = new br.com.Modelo.CatFinalidadeDAO();
_jspx_page_context.setAttribute("CatFin", CatFin, PageContext.PAGE_SCOPE);
}
}
out.write("\n");
out.write(" ");
br.com.Modelo.CatSubFinalidadeDAO CatSubFin = null;
synchronized (_jspx_page_context) {
CatSubFin = (br.com.Modelo.CatSubFinalidadeDAO) _jspx_page_context.getAttribute("CatSubFin", PageContext.PAGE_SCOPE);
if (CatSubFin == null){
CatSubFin = new br.com.Modelo.CatSubFinalidadeDAO();
_jspx_page_context.setAttribute("CatSubFin", CatSubFin, PageContext.PAGE_SCOPE);
}
}
out.write("\n");
out.write(" ");
br.com.Modelo.CatAutoCessaoDAO CatAuto = null;
synchronized (_jspx_page_context) {
CatAuto = (br.com.Modelo.CatAutoCessaoDAO) _jspx_page_context.getAttribute("CatAuto", PageContext.PAGE_SCOPE);
if (CatAuto == null){
CatAuto = new br.com.Modelo.CatAutoCessaoDAO();
_jspx_page_context.setAttribute("CatAuto", CatAuto, PageContext.PAGE_SCOPE);
}
}
out.write("\n");
out.write(" ");
br.com.Modelo.CatContrapartidaDAO CatContra = null;
synchronized (_jspx_page_context) {
CatContra = (br.com.Modelo.CatContrapartidaDAO) _jspx_page_context.getAttribute("CatContra", PageContext.PAGE_SCOPE);
if (CatContra == null){
CatContra = new br.com.Modelo.CatContrapartidaDAO();
_jspx_page_context.setAttribute("CatContra", CatContra, PageContext.PAGE_SCOPE);
}
}
out.write("\n");
out.write(" ");
br.com.Modelo.TipoDispositivoLegalDAO TpDis = null;
synchronized (_jspx_page_context) {
TpDis = (br.com.Modelo.TipoDispositivoLegalDAO) _jspx_page_context.getAttribute("TpDis", PageContext.PAGE_SCOPE);
if (TpDis == null){
TpDis = new br.com.Modelo.TipoDispositivoLegalDAO();
_jspx_page_context.setAttribute("TpDis", TpDis, PageContext.PAGE_SCOPE);
}
}
out.write("\n");
out.write(" ");
br.com.Modelo.SubPrefeituraDAO subPref = null;
synchronized (_jspx_page_context) {
subPref = (br.com.Modelo.SubPrefeituraDAO) _jspx_page_context.getAttribute("subPref", PageContext.PAGE_SCOPE);
if (subPref == null){
subPref = new br.com.Modelo.SubPrefeituraDAO();
_jspx_page_context.setAttribute("subPref", subPref, PageContext.PAGE_SCOPE);
}
}
out.write("\n");
out.write(" ");
br.com.Modelo.DispositivoLegalDAO Disp = null;
synchronized (_jspx_page_context) {
Disp = (br.com.Modelo.DispositivoLegalDAO) _jspx_page_context.getAttribute("Disp", PageContext.PAGE_SCOPE);
if (Disp == null){
Disp = new br.com.Modelo.DispositivoLegalDAO();
_jspx_page_context.setAttribute("Disp", Disp, PageContext.PAGE_SCOPE);
}
}
out.write("\n");
out.write(" ");
br.com.Modelo.ArquivoDAO Arquivo = null;
synchronized (_jspx_page_context) {
Arquivo = (br.com.Modelo.ArquivoDAO) _jspx_page_context.getAttribute("Arquivo", PageContext.PAGE_SCOPE);
if (Arquivo == null){
Arquivo = new br.com.Modelo.ArquivoDAO();
_jspx_page_context.setAttribute("Arquivo", Arquivo, PageContext.PAGE_SCOPE);
}
}
out.write("\n");
out.write(" ");
br.com.Modelo.NivelAdministracaoDAO NivelAdm = null;
synchronized (_jspx_page_context) {
NivelAdm = (br.com.Modelo.NivelAdministracaoDAO) _jspx_page_context.getAttribute("NivelAdm", PageContext.PAGE_SCOPE);
if (NivelAdm == null){
NivelAdm = new br.com.Modelo.NivelAdministracaoDAO();
_jspx_page_context.setAttribute("NivelAdm", NivelAdm, PageContext.PAGE_SCOPE);
}
}
out.write("\n");
out.write(" ");
br.com.Modelo.CatEntidadeDAO CatEnt = null;
synchronized (_jspx_page_context) {
CatEnt = (br.com.Modelo.CatEntidadeDAO) _jspx_page_context.getAttribute("CatEnt", PageContext.PAGE_SCOPE);
if (CatEnt == null){
CatEnt = new br.com.Modelo.CatEntidadeDAO();
_jspx_page_context.setAttribute("CatEnt", CatEnt, PageContext.PAGE_SCOPE);
}
}
out.write("\n");
out.write(" ");
br.com.Modelo.DivisaoDAO Divisao = null;
synchronized (_jspx_page_context) {
Divisao = (br.com.Modelo.DivisaoDAO) _jspx_page_context.getAttribute("Divisao", PageContext.PAGE_SCOPE);
if (Divisao == null){
Divisao = new br.com.Modelo.DivisaoDAO();
_jspx_page_context.setAttribute("Divisao", Divisao, PageContext.PAGE_SCOPE);
}
}
out.write("\n");
out.write(" ");
br.com.Modelo.ValidacaoDAO Val = null;
synchronized (_jspx_page_context) {
Val = (br.com.Modelo.ValidacaoDAO) _jspx_page_context.getAttribute("Val", PageContext.PAGE_SCOPE);
if (Val == null){
Val = new br.com.Modelo.ValidacaoDAO();
_jspx_page_context.setAttribute("Val", Val, PageContext.PAGE_SCOPE);
}
}
out.write("\n");
out.write(" ");
br.com.Modelo.UsuarioDAO Usuario = null;
synchronized (_jspx_page_context) {
Usuario = (br.com.Modelo.UsuarioDAO) _jspx_page_context.getAttribute("Usuario", PageContext.PAGE_SCOPE);
if (Usuario == null){
Usuario = new br.com.Modelo.UsuarioDAO();
_jspx_page_context.setAttribute("Usuario", Usuario, PageContext.PAGE_SCOPE);
}
}
out.write("\n");
out.write(" \n");
out.write(" ");
if (_jspx_meth_c_set_3(_jspx_page_context))
return;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_set_4(_jspx_page_context))
return;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_set_5(_jspx_page_context))
return;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_set_6(_jspx_page_context))
return;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_set_7(_jspx_page_context))
return;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_set_8(_jspx_page_context))
return;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_set_9(_jspx_page_context))
return;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_set_10(_jspx_page_context))
return;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_set_11(_jspx_page_context))
return;
out.write("\n");
out.write(" \n");
out.write(" \n");
out.write(" ");
if (_jspx_meth_c_set_12(_jspx_page_context))
return;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_set_13(_jspx_page_context))
return;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_set_14(_jspx_page_context))
return;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_set_15(_jspx_page_context))
return;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_set_16(_jspx_page_context))
return;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_set_17(_jspx_page_context))
return;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_set_18(_jspx_page_context))
return;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_set_19(_jspx_page_context))
return;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_set_20(_jspx_page_context))
return;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_set_21(_jspx_page_context))
return;
out.write("\n");
out.write(" \n");
out.write(" <div class=\"breadcrumbs ace-save-state\" id=\"breadcrumbs\">\n");
out.write(" <ul class=\"breadcrumb\">\n");
out.write(" <li><i class=\"ace-icon fa fa-list\"></i> Auto de Cessão </li>\n");
out.write(" </ul>\n");
out.write(" </div> \n");
out.write(" <div class=\"page-content\" >\n");
out.write(" <div id=\"\" class=\"specific-block\"></div> \n");
out.write(" <div class=\"row\">\n");
out.write(" <div class=\"col-xs-12\">\n");
out.write(" \n");
out.write(" \n");
out.write(" <div class=\"col-sm-offset-1 col-sm-10\">\n");
out.write(" <h2>Auto de Cessão</h2>\n");
out.write(" <div class=\"space-14\"></div>\n");
out.write(" <div class=\"form-horizontal\">\n");
out.write(" <div class=\"tabbable\">\n");
out.write(" <ul class=\"nav nav-tabs padding-0\">\n");
out.write(" <li class=\"active\">\n");
out.write(" <a data-toggle=\"tab\" href=\"#auto-cessao\" aria-expanded=\"true\">\n");
out.write(" Auto de Cessão \n");
out.write(" ");
if (_jspx_meth_c_if_0(_jspx_page_context))
return;
out.write("\n");
out.write(" </a>\n");
out.write(" </li>\n");
out.write(" <li class=\"\">\n");
out.write(" <a data-toggle=\"tab\" href=\"#contrapartida\" aria-expanded=\"true\">\n");
out.write(" Contrapartida\n");
out.write(" ");
if (_jspx_meth_c_if_1(_jspx_page_context))
return;
out.write("\n");
out.write(" </a>\n");
out.write(" </li>\n");
out.write(" <li class=\"\">\n");
out.write(" <a data-toggle=\"tab\" href=\"#disp-legal\" aria-expanded=\"true\">\n");
out.write(" Dispositivo Legal\n");
out.write(" ");
if (_jspx_meth_c_if_2(_jspx_page_context))
return;
out.write("\n");
out.write(" </a>\n");
out.write(" </li>\n");
out.write(" <li class=\"\">\n");
out.write(" <a data-toggle=\"tab\" href=\"#anexar-doc\" aria-expanded=\"true\">\n");
out.write(" Anexar documento\n");
out.write(" ");
if (_jspx_meth_c_if_3(_jspx_page_context))
return;
out.write("\n");
out.write(" </a>\n");
out.write(" </li>\n");
out.write(" <li class=\"\">\n");
out.write(" <a data-toggle=\"tab\" href=\"#vistoria\" aria-expanded=\"true\">\n");
out.write(" Vistoria\n");
out.write(" ");
if (_jspx_meth_c_if_4(_jspx_page_context))
return;
out.write("\n");
out.write(" </a>\n");
out.write(" </li>\n");
out.write(" <li class=\"\">\n");
out.write(" <a data-toggle=\"tab\" href=\"#validacao\" aria-expanded=\"true\">\n");
out.write(" Validação\n");
out.write(" ");
if (_jspx_meth_c_if_5(_jspx_page_context))
return;
out.write("\n");
out.write(" </a>\n");
out.write(" </li>\n");
out.write(" </ul>\n");
out.write(" <div class=\"tab-content profile-edit-tab-content\">\n");
out.write(" <div id=\"auto-cessao\" class=\"tab-pane in active\">\n");
out.write(" <h5 class=\"header smaller lbl\"><strong>Auto de Cessão</strong></h5>\n");
out.write(" <form action=\"ControllerServlet?acao=AutoCessoValidacaoUC\" method=\"POST\" >\n");
out.write(" <div class=\"space-10\"></div>\n");
out.write(" \n");
out.write(" <input type=\"hidden\" name=\"pkAutoStage\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.pkAutoStage}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" />\n");
out.write(" <input type=\"hidden\" name=\"nrVerAc\" value=\"1\" />\n");
out.write(" <input type=\"hidden\" name=\"nmStatus\" value=\"EmConferencia\" />\n");
out.write(" <input type=\"hidden\" name=\"execucao\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" />\n");
out.write(" <input type=\"hidden\" name=\"pgValidacao\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pgValidacao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" />\n");
out.write("\n");
out.write(" <div class=\"form-group\">\n");
out.write(" <div class=\"inline col-md-2 col-xs-12\">\n");
out.write(" <span class=\"lbl\"><strong>Nº AC:</strong></span>\n");
out.write(" </div>\n");
out.write(" <label class=\"inline col-md-3 col-xs-12\">\n");
out.write(" ");
if (_jspx_meth_c_choose_1(_jspx_page_context))
return;
out.write("\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-3 col-xs-12\">\n");
out.write(" <span class=\"lbl\">\n");
out.write(" <strong>Categoria</strong>\n");
out.write(" </span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\">\n");
out.write(" ");
if (_jspx_meth_c_choose_2(_jspx_page_context))
return;
out.write("\n");
out.write(" </label>\n");
out.write(" </div>\n");
out.write(" <div class=\"form-group\">\n");
out.write(" <div class=\"inline col-md-2 col-xs-12\">\n");
out.write(" <span class=\"lbl\"><strong>Data Lavratura:</strong></span>\n");
out.write(" </div>\n");
out.write(" <label class=\"inline col-md-3 col-xs-12 \">\n");
out.write(" ");
if (_jspx_meth_c_choose_3(_jspx_page_context))
return;
out.write("\n");
out.write("\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-3 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Nível Administração:</strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-3 col-xs-12\">\n");
out.write(" ");
if (_jspx_meth_c_choose_4(_jspx_page_context))
return;
out.write("\n");
out.write("\n");
out.write(" </label>\n");
out.write("\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"space-1\"></div> \n");
out.write("\n");
out.write(" <div class=\"form-group\">\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Tipo de Cessão:</strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-6 col-xs-12\">\n");
out.write(" ");
if (_jspx_meth_c_choose_5(_jspx_page_context))
return;
out.write("\n");
out.write("\n");
out.write(" </label>\n");
out.write(" </div> \n");
out.write(" <div class=\"form-group\">\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\">\n");
out.write(" <span class=\"lbl\"><strong>Nº Processo:</strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-3 col-xs-12\">\n");
out.write(" ");
if (_jspx_meth_c_choose_6(_jspx_page_context))
return;
out.write("\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-4 col-xs-12\">\n");
out.write(" <div class=\"radio inline col-md-3\">\n");
out.write(" <label>\n");
out.write(" <input name=\"tpProcesso\" id=\"sei\" value=\"SEI\" type=\"radio\" class=\"ace\" onclick=\"maskProcesso();\">\n");
out.write(" <span class=\"lbl\"><strong> SEI</strong></span>\n");
out.write(" </label>\n");
out.write(" </div>\n");
out.write(" <div class=\"radio inline col-md-3\">\n");
out.write(" <label>\n");
out.write(" <input name=\"tpProcesso\" id=\"pa\" value=\"PA\" type=\"radio\" class=\"ace\" onclick=\"maskProcesso();\">\n");
out.write(" <span class=\"lbl\"><strong> P.A.</strong></span>\n");
out.write(" </label>\n");
out.write(" </div>\n");
out.write(" <div class=\"radio inline col-md-3\">\n");
out.write(" <label>\n");
out.write(" <input name=\"tpProcesso\" id=\"tid\" value=\"TID\" type=\"radio\" class=\"ace\" onclick=\"maskProcesso();\">\n");
out.write(" <span class=\"lbl\"><strong> TID</strong></span>\n");
out.write(" </label>\n");
out.write(" </div>\n");
out.write(" <div class=\"radio inline col-md-3\">\n");
out.write(" <label>\n");
out.write(" <input name=\"tpProcesso\" id=\"cid\" value=\"CID\" type=\"radio\" class=\"ace\" onclick=\"maskProcesso();\">\n");
out.write(" <span class=\"lbl\"><strong> CID</strong></span>\n");
out.write(" </label>\n");
out.write(" </div>\n");
out.write(" </label>\n");
out.write(" <!--<lable id=\"msgProcesso\"></lable>-->\n");
out.write(" <span id=\"msgProcesso\"></span>\n");
out.write(" </div> \n");
out.write("\n");
out.write(" <div class=\"space-1\"></div>\n");
out.write("\n");
out.write(" <div class=\"form-group\">\n");
out.write("\n");
out.write(" </div> \n");
out.write("\n");
out.write(" <div class=\"form-group\">\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\n");
out.write(" <span class=\"lbl\">\n");
out.write(" <strong>Cessionário/Cedente:</strong>\n");
out.write(" </span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-9 col-xs-12\">\n");
out.write(" ");
if (_jspx_meth_c_choose_7(_jspx_page_context))
return;
out.write("\n");
out.write("\n");
out.write(" </label>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"space-2\"></div>\n");
out.write(" <div class=\"form-group\">\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Categoria Entidade:</strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-6 col-xs-12\">\n");
out.write(" ");
if (_jspx_meth_c_choose_8(_jspx_page_context))
return;
out.write("\n");
out.write("\n");
out.write(" </label>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"space-2\"></div>\n");
out.write("\n");
out.write(" <div class=\"form-group\">\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Categoria da finalidade:</strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-3 col-xs-12\">\n");
out.write(" ");
if (_jspx_meth_c_choose_9(_jspx_page_context))
return;
out.write("\n");
out.write("\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Finalidade:</strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-4 col-xs-12\">\n");
out.write(" ");
if (_jspx_meth_c_choose_10(_jspx_page_context))
return;
out.write("\n");
out.write("\n");
out.write(" </label>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"space-1\"></div> \n");
out.write("\n");
out.write(" <div class=\"form-group\">\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\n");
out.write(" <span class=\"lbl\">\n");
out.write(" <strong>Detalhamento da Finalidade</strong>\n");
out.write(" </span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-8 col-xs-12\">\n");
out.write(" ");
if (_jspx_meth_c_choose_11(_jspx_page_context))
return;
out.write("\n");
out.write(" </label>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"space-1\"></div>\n");
out.write("\n");
out.write(" <div class=\"form-group\">\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Planta:</strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\">\n");
out.write(" ");
if (_jspx_meth_c_choose_12(_jspx_page_context))
return;
out.write("\n");
out.write("\n");
out.write(" </label>\n");
out.write("\n");
out.write(" <label class=\"inline col-md-1 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Croqui:</strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\">\n");
out.write(" ");
if (_jspx_meth_c_choose_13(_jspx_page_context))
return;
out.write("\n");
out.write("\n");
out.write(" </label>\n");
out.write("\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Área do croqui:</strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\">\n");
out.write(" ");
if (_jspx_meth_c_choose_14(_jspx_page_context))
return;
out.write("\n");
out.write("\n");
out.write(" </label>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"space-1\"></div>\n");
out.write("\n");
out.write(" <div class=\"form-group\">\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Setor:</strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\">\n");
out.write(" ");
if (_jspx_meth_c_choose_15(_jspx_page_context))
return;
out.write("\n");
out.write("\n");
out.write(" </label>\n");
out.write("\n");
out.write(" <label class=\"inline col-md-1 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Quadra:</strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\">\n");
out.write(" ");
if (_jspx_meth_c_choose_16(_jspx_page_context))
return;
out.write("\n");
out.write("\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-1 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Lote:</strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\">\n");
out.write(" ");
if (_jspx_meth_c_choose_17(_jspx_page_context))
return;
out.write("\n");
out.write(" </label>\n");
out.write(" </div>\n");
out.write(" <div class=\"space-1\"></div>\n");
out.write("\n");
out.write(" <div class=\"form-group\">\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>CAP:</strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\">\n");
out.write(" ");
if (_jspx_meth_c_choose_18(_jspx_page_context))
return;
out.write("\n");
out.write("\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Metragem oficial:</strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\">\n");
out.write(" ");
if (_jspx_meth_c_choose_19(_jspx_page_context))
return;
out.write("\n");
out.write("\n");
out.write(" </label>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"space-1\"></div>\n");
out.write("\n");
out.write(" <div class=\"form-group\">\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Subprefituras: </strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-4 col-xs-12\" >\n");
out.write(" ");
if (_jspx_meth_c_choose_20(_jspx_page_context))
return;
out.write("\n");
out.write("\n");
out.write(" </label>\n");
out.write("\n");
out.write(" <!--<label class=\"inline col-md-2 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>CEP:</strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" placeholder=\"00000-000\" name=\"\" >\n");
out.write(" </label>-->\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"space-1\"></div>\n");
out.write("\n");
out.write(" <div class=\"form-group\">\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Tipo endereço:</strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-3 col-xs-12\">\n");
out.write(" ");
if (_jspx_meth_c_choose_21(_jspx_page_context))
return;
out.write("\n");
out.write("\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Título do endereço:</strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-4 col-xs-12\" >\n");
out.write(" ");
if (_jspx_meth_c_choose_22(_jspx_page_context))
return;
out.write("\n");
out.write("\n");
out.write("\n");
out.write(" </label>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"space-1\"></div>\n");
out.write("\n");
out.write(" <div class=\"form-group\">\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Endereço:</strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-6 col-xs-12\" >\n");
out.write(" ");
if (_jspx_meth_c_choose_23(_jspx_page_context))
return;
out.write("\n");
out.write("\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-1 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>número:</strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\n");
out.write(" ");
if (_jspx_meth_c_choose_24(_jspx_page_context))
return;
out.write("\n");
out.write("\n");
out.write(" </label>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"space-1\"></div>\n");
out.write("\n");
out.write(" <div class=\"form-group\">\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Complemento:</strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-3 col-xs-12\" >\n");
out.write(" ");
if (_jspx_meth_c_choose_25(_jspx_page_context))
return;
out.write("\n");
out.write("\n");
out.write(" </label>\n");
out.write("\n");
out.write(" </div>\n");
out.write(" <div class=\"form-group\">\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" > \n");
out.write(" <span class=\"lbl\"><strong>Referência:</strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-8 col-xs-12\" >\n");
out.write(" ");
if (_jspx_meth_c_choose_26(_jspx_page_context))
return;
out.write("\n");
out.write("\n");
out.write(" </label>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"space-1\"></div>\n");
out.write("\n");
out.write(" <div class=\"form-group\">\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Prazo:</strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-3 col-xs-12\">\n");
out.write(" ");
if (_jspx_meth_c_choose_27(_jspx_page_context))
return;
out.write("\n");
out.write(" </label>\n");
out.write(" ");
if (_jspx_meth_c_choose_30(_jspx_page_context))
return;
out.write("\n");
out.write("\n");
out.write("\n");
out.write(" ");
if (_jspx_meth_c_choose_31(_jspx_page_context))
return;
out.write("\n");
out.write(" </div>\n");
out.write(" ");
if (_jspx_meth_c_if_14(_jspx_page_context))
return;
out.write(" \n");
out.write(" <div class=\"space-2\"></div>\n");
out.write("\n");
out.write(" <div class=\"form-group\">\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\">\n");
out.write(" <span class=\"lbl\"><strong>Em vigor:</strong></span>\n");
out.write(" </label>\n");
out.write(" ");
if (_jspx_meth_c_choose_32(_jspx_page_context))
return;
out.write("\n");
out.write(" </div>\n");
out.write(" <div class=\"space-1\"></div>\n");
out.write("\n");
out.write(" <div class=\"form-group\">\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Observação:</strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-10 col-xs-12\">\n");
out.write(" ");
if (_jspx_meth_c_choose_35(_jspx_page_context))
return;
out.write("\n");
out.write(" </label>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"space-2\"></div>\n");
out.write("\n");
out.write(" <div class=\"form-actions center\">\n");
out.write(" ");
if (_jspx_meth_c_choose_36(_jspx_page_context))
return;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_if_15(_jspx_page_context))
return;
out.write(" \n");
out.write(" </div>\n");
out.write("\n");
out.write(" </form>\n");
out.write(" </div>\n");
out.write(" \n");
out.write("<!--Inicio da tab-pane Contrapartida--> \n");
out.write(" <div id=\"contrapartida\" class=\"tab-pane \n");
out.write(" ");
if (_jspx_meth_c_if_16(_jspx_page_context))
return;
out.write("\n");
out.write(" \">\n");
out.write(" <h5 class=\"header smaller lbl \"><strong>Contrapartida</strong></h5>\n");
out.write(" <div class=\"form-group\">\n");
out.write(" <label class=\"inline col-md-3 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Categoria da contrapartida:</strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-6 col-xs-12\">\n");
out.write(" ");
if (_jspx_meth_c_choose_37(_jspx_page_context))
return;
out.write("\n");
out.write("\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-3 col-xs-12\">\n");
out.write(" <a href=\"#\" class=\"add_field_button\" title=\"Adicionar outro categoria\" title=\"Adicionar campos\"><span class=\"label label-success arrowed\"><i class=\" glyphicon glyphicon-plus-sign\"></i></span></a>\n");
out.write(" </label>\n");
out.write(" </div>\n");
out.write(" <div class=\"space-1\"></div>\n");
out.write("\n");
out.write(" <div class=\"form-group\">\n");
out.write(" <label class=\"inline col-md-3 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Contrapartida <font size=\"-2\"> (Descrição Simplificada):</font></strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-9 col-xs-12\">\n");
out.write(" ");
if (_jspx_meth_c_choose_38(_jspx_page_context))
return;
out.write("\n");
out.write(" </label>\n");
out.write(" </div>\n");
out.write(" <div class=\"space-2\"></div>\n");
out.write(" <div class=\"form-actions center\">\n");
out.write(" <button class=\"btn btn-success\" type=\"submit\">\n");
out.write(" <i class=\"ace-icon fa fa-save bigger-110\"></i>\n");
out.write(" Salvar\n");
out.write(" </button>\n");
out.write(" </div> \n");
out.write(" </div>\n");
out.write(" \n");
out.write(" \n");
out.write(" \n");
out.write(" \n");
out.write("<!--Inicio da tab-pane Dispositvo Legal--> \n");
out.write(" <div id=\"disp-legal\" class=\"tab-pane \n");
out.write(" ");
if (_jspx_meth_c_if_17(_jspx_page_context))
return;
out.write(" \n");
out.write(" \"> \n");
out.write(" <h5 class=\"header smaller lbl \"><strong>Dispositivo Legal</strong></h5>\n");
out.write(" ");
if (_jspx_meth_c_if_18(_jspx_page_context))
return;
out.write("\n");
out.write(" <!--Lista dos Dispositivo no banco-->\n");
out.write(" ");
if (_jspx_meth_c_forEach_15(_jspx_page_context))
return;
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write(" </div>\n");
out.write("\n");
out.write("<!--Inicico da tab-pane Anexer Documento -->\n");
out.write(" <div id=\"anexar-doc\" class=\"tab-pane \n");
out.write(" ");
if (_jspx_meth_c_if_21(_jspx_page_context))
return;
out.write(" \n");
out.write(" \">\n");
out.write(" <h5 class=\"header smaller lbl\"><strong>Anexar documento</strong></h5>\n");
out.write(" <div class=\"form-group\">\n");
out.write(" <form action=\"ControllerServlet?acao=ArquivoUpload\" enctype=\"multipart/form-data\" method=\"POST\" >\n");
out.write(" <input type=\"hidden\" name=\"pkAutoStage\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.pkAutoStage}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" />\n");
out.write(" <input type=\"hidden\" name=\"tipoArquivo\" value=\"planta\" />\n");
out.write(" <input type=\"hidden\" name=\"Origem\" value=\"AutoCessao\" />\n");
out.write(" <input type=\"hidden\" name=\"nrVerArqPlanta\" value=\"1\" />\n");
out.write(" <input type=\"hidden\" name=\"execucao\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" />\n");
out.write(" <input type=\"hidden\" name=\"pgValidacao\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pgValidacao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" />\n");
out.write(" ");
if (_jspx_meth_c_set_23(_jspx_page_context))
return;
out.write("\n");
out.write(" <input type=\"hidden\" name=\"pkArquivo\" value=\"");
if (_jspx_meth_c_out_0(_jspx_page_context))
return;
out.write("\" /> \n");
out.write(" ");
if (_jspx_meth_c_if_22(_jspx_page_context))
return;
out.write("\n");
out.write("\n");
out.write("\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\"><strong>Planta:</strong></label>\n");
out.write(" <label class=\"col-md-1 col-xs-12\">\n");
out.write(" ");
if (_jspx_meth_c_forEach_16(_jspx_page_context))
return;
out.write("\n");
out.write(" </label>\n");
out.write(" ");
if (_jspx_meth_c_if_24(_jspx_page_context))
return;
out.write(" \n");
out.write(" </form>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"space-2\"></div>\n");
out.write("\n");
out.write(" <div class=\"form-group\"> \n");
out.write(" <form action=\"ControllerServlet?acao=ArquivoUpload\" method=\"POST\" enctype=\"multipart/form-data\">\n");
out.write(" <input type=\"hidden\" name=\"pkAutoStage\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.pkAutoStage}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" />\n");
out.write(" <input type=\"hidden\" name=\"tipoArquivo\" value=\"AC\" />\n");
out.write(" <input type=\"hidden\" name=\"Origem\" value=\"AutoCessao\" />\n");
out.write(" <input type=\"hidden\" name=\"nrVerArqAc\" value=\"1\" />\n");
out.write(" <input type=\"hidden\" name=\"execucao\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" />\n");
out.write(" <input type=\"hidden\" name=\"pgValidacao\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pgValidacao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" />\n");
out.write(" ");
if (_jspx_meth_c_set_25(_jspx_page_context))
return;
out.write("\n");
out.write(" <input type=\"hidden\" name=\"pkArquivo\" value=\"");
if (_jspx_meth_c_out_2(_jspx_page_context))
return;
out.write("\" />\n");
out.write(" ");
if (_jspx_meth_c_if_25(_jspx_page_context))
return;
out.write("\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\"><strong>Auto Cessão:</strong></label>\n");
out.write(" <label class=\"col-md-1 col-xs-12\">\n");
out.write(" ");
if (_jspx_meth_c_forEach_17(_jspx_page_context))
return;
out.write("\n");
out.write(" </label>\n");
out.write(" ");
if (_jspx_meth_c_if_27(_jspx_page_context))
return;
out.write(" \n");
out.write(" </form>\n");
out.write("\n");
out.write(" </div>\n");
out.write("\n");
out.write(" </div>\n");
out.write(" \n");
out.write("<!--Inicio da tab-pane Vistoria -->\n");
out.write(" <div id=\"vistoria\" class=\"tab-pane \n");
out.write(" ");
if (_jspx_meth_c_if_28(_jspx_page_context))
return;
out.write("\n");
out.write(" \">\n");
out.write(" <h5 class=\"header smaller lbl\"><strong>Vistoria</strong></h5>\n");
out.write("\n");
out.write(" </div>\n");
out.write(" \n");
out.write("<!-- Inicio do formulario Validação --> \n");
out.write(" <div id=\"validacao\" class=\"tab-pane \n");
out.write(" ");
if (_jspx_meth_c_if_29(_jspx_page_context))
return;
out.write(" \n");
out.write(" \">\n");
out.write(" <h5 class=\"header smaller lbl\"><strong>Validação</strong></h5>\n");
out.write(" ");
if (_jspx_meth_c_if_30(_jspx_page_context))
return;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_forEach_19(_jspx_page_context))
return;
out.write("\n");
out.write(" </div>\n");
out.write(" \n");
out.write(" \n");
out.write(" \n");
out.write(" \n");
out.write(" \n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" </div> \n");
out.write(" </div> \n");
out.write(" \n");
out.write(" \n");
out.write(" ");
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "include/footer.jsp", out, false);
out.write("\n");
out.write(" ");
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "javaScritp/carregado.html", out, false);
out.write("\n");
out.write(" \n");
out.write(" </div><!-- /.main-container -->\n");
out.write(" <div id=\"dialog-planta\"style=\"display:none;\">\n");
out.write(" \n");
out.write(" </div>\n");
out.write(" \n");
out.write(" <div id=\"dialog-auto-cessao\"style=\"display:none;\">\n");
out.write(" \n");
out.write(" </div>\n");
out.write(" \n");
out.write(" \n");
out.write(" </body>\n");
out.write("</html>\n");
out.write("\n");
out.write("\n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
private boolean _jspx_meth_c_set_0(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_0 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_0.setPageContext(_jspx_page_context);
_jspx_th_c_set_0.setParent(null);
_jspx_th_c_set_0.setVar("acessoPerfil");
_jspx_th_c_set_0.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${sessionPerfil}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_0 = _jspx_th_c_set_0.doStartTag();
if (_jspx_th_c_set_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_0);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_0);
return false;
}
private boolean _jspx_meth_c_choose_0(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_0 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_0.setPageContext(_jspx_page_context);
_jspx_th_c_choose_0.setParent(null);
int _jspx_eval_c_choose_0 = _jspx_th_c_choose_0.doStartTag();
if (_jspx_eval_c_choose_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_when_0((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_0, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_when_1((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_0, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_when_2((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_0, _jspx_page_context))
return true;
out.write('\r');
out.write('\n');
int evalDoAfterBody = _jspx_th_c_choose_0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_0);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_0);
return false;
}
private boolean _jspx_meth_c_when_0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_0, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_0 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_0.setPageContext(_jspx_page_context);
_jspx_th_c_when_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_0);
_jspx_th_c_when_0.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${sessionLogin == '' || sessionLogin == null}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_0 = _jspx_th_c_when_0.doStartTag();
if (_jspx_eval_c_when_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_redirect_0((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_0, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_0);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_0);
return false;
}
private boolean _jspx_meth_c_redirect_0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_0, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:redirect
org.apache.taglibs.standard.tag.rt.core.RedirectTag _jspx_th_c_redirect_0 = (org.apache.taglibs.standard.tag.rt.core.RedirectTag) _jspx_tagPool_c_redirect_url_nobody.get(org.apache.taglibs.standard.tag.rt.core.RedirectTag.class);
_jspx_th_c_redirect_0.setPageContext(_jspx_page_context);
_jspx_th_c_redirect_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_0);
_jspx_th_c_redirect_0.setUrl("/AcessoNegado.jsp");
int _jspx_eval_c_redirect_0 = _jspx_th_c_redirect_0.doStartTag();
if (_jspx_th_c_redirect_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_redirect_url_nobody.reuse(_jspx_th_c_redirect_0);
return true;
}
_jspx_tagPool_c_redirect_url_nobody.reuse(_jspx_th_c_redirect_0);
return false;
}
private boolean _jspx_meth_c_when_1(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_0, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_1 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_1.setPageContext(_jspx_page_context);
_jspx_th_c_when_1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_0);
_jspx_th_c_when_1.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${sessionPerfil != acessoPerfil}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_1 = _jspx_th_c_when_1.doStartTag();
if (_jspx_eval_c_when_1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_set_1((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_1, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_redirect_1((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_1, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_1.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_1);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_1);
return false;
}
private boolean _jspx_meth_c_set_1(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_1, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_1 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_scope_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_1.setPageContext(_jspx_page_context);
_jspx_th_c_set_1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_1);
_jspx_th_c_set_1.setVar("msg3");
_jspx_th_c_set_1.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${true}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
_jspx_th_c_set_1.setScope("session");
int _jspx_eval_c_set_1 = _jspx_th_c_set_1.doStartTag();
if (_jspx_th_c_set_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_scope_nobody.reuse(_jspx_th_c_set_1);
return true;
}
_jspx_tagPool_c_set_var_value_scope_nobody.reuse(_jspx_th_c_set_1);
return false;
}
private boolean _jspx_meth_c_redirect_1(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_1, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:redirect
org.apache.taglibs.standard.tag.rt.core.RedirectTag _jspx_th_c_redirect_1 = (org.apache.taglibs.standard.tag.rt.core.RedirectTag) _jspx_tagPool_c_redirect_url_nobody.get(org.apache.taglibs.standard.tag.rt.core.RedirectTag.class);
_jspx_th_c_redirect_1.setPageContext(_jspx_page_context);
_jspx_th_c_redirect_1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_1);
_jspx_th_c_redirect_1.setUrl("/AcessoNegado.jsp");
int _jspx_eval_c_redirect_1 = _jspx_th_c_redirect_1.doStartTag();
if (_jspx_th_c_redirect_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_redirect_url_nobody.reuse(_jspx_th_c_redirect_1);
return true;
}
_jspx_tagPool_c_redirect_url_nobody.reuse(_jspx_th_c_redirect_1);
return false;
}
private boolean _jspx_meth_c_when_2(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_0, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_2 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_2.setPageContext(_jspx_page_context);
_jspx_th_c_when_2.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_0);
_jspx_th_c_when_2.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${sessionStatus == 0}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_2 = _jspx_th_c_when_2.doStartTag();
if (_jspx_eval_c_when_2 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_set_2((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_2, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_redirect_2((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_2, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_2.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_2);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_2);
return false;
}
private boolean _jspx_meth_c_set_2(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_2, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_2 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_scope_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_2.setPageContext(_jspx_page_context);
_jspx_th_c_set_2.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_2);
_jspx_th_c_set_2.setVar("msg");
_jspx_th_c_set_2.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${true}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
_jspx_th_c_set_2.setScope("session");
int _jspx_eval_c_set_2 = _jspx_th_c_set_2.doStartTag();
if (_jspx_th_c_set_2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_scope_nobody.reuse(_jspx_th_c_set_2);
return true;
}
_jspx_tagPool_c_set_var_value_scope_nobody.reuse(_jspx_th_c_set_2);
return false;
}
private boolean _jspx_meth_c_redirect_2(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_2, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:redirect
org.apache.taglibs.standard.tag.rt.core.RedirectTag _jspx_th_c_redirect_2 = (org.apache.taglibs.standard.tag.rt.core.RedirectTag) _jspx_tagPool_c_redirect_url_nobody.get(org.apache.taglibs.standard.tag.rt.core.RedirectTag.class);
_jspx_th_c_redirect_2.setPageContext(_jspx_page_context);
_jspx_th_c_redirect_2.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_2);
_jspx_th_c_redirect_2.setUrl("/AcessoNegado.jsp");
int _jspx_eval_c_redirect_2 = _jspx_th_c_redirect_2.doStartTag();
if (_jspx_th_c_redirect_2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_redirect_url_nobody.reuse(_jspx_th_c_redirect_2);
return true;
}
_jspx_tagPool_c_redirect_url_nobody.reuse(_jspx_th_c_redirect_2);
return false;
}
private boolean _jspx_meth_c_set_3(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_3 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_3.setPageContext(_jspx_page_context);
_jspx_th_c_set_3.setParent(null);
_jspx_th_c_set_3.setVar("selTpCessao");
_jspx_th_c_set_3.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${TpCessao.detalheTpCessao(auto.fkTipoCessaoStage)}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_3 = _jspx_th_c_set_3.doStartTag();
if (_jspx_th_c_set_3.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_3);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_3);
return false;
}
private boolean _jspx_meth_c_set_4(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_4 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_4.setPageContext(_jspx_page_context);
_jspx_th_c_set_4.setParent(null);
_jspx_th_c_set_4.setVar("selCatAuto");
_jspx_th_c_set_4.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${CatAuto.detalheCatAuto(auto.fkCatAutoStage)}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_4 = _jspx_th_c_set_4.doStartTag();
if (_jspx_th_c_set_4.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_4);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_4);
return false;
}
private boolean _jspx_meth_c_set_5(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_5 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_5.setPageContext(_jspx_page_context);
_jspx_th_c_set_5.setParent(null);
_jspx_th_c_set_5.setVar("selCatFin");
_jspx_th_c_set_5.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${CatFin.detalheCatFinalidade(auto.fkCatFinalidadeStage)}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_5 = _jspx_th_c_set_5.doStartTag();
if (_jspx_th_c_set_5.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_5);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_5);
return false;
}
private boolean _jspx_meth_c_set_6(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_6 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_6.setPageContext(_jspx_page_context);
_jspx_th_c_set_6.setParent(null);
_jspx_th_c_set_6.setVar("selNvAdm");
_jspx_th_c_set_6.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${NivelAdm.detalheNivelAdm(auto.fkNivelAdm)}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_6 = _jspx_th_c_set_6.doStartTag();
if (_jspx_th_c_set_6.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_6);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_6);
return false;
}
private boolean _jspx_meth_c_set_7(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_7 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_7.setPageContext(_jspx_page_context);
_jspx_th_c_set_7.setParent(null);
_jspx_th_c_set_7.setVar("selCatEnt");
_jspx_th_c_set_7.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${CatEnt.detalheCatEnt(auto.fkCatEntidadeStage)}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_7 = _jspx_th_c_set_7.doStartTag();
if (_jspx_th_c_set_7.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_7);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_7);
return false;
}
private boolean _jspx_meth_c_set_8(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_8 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_8.setPageContext(_jspx_page_context);
_jspx_th_c_set_8.setParent(null);
_jspx_th_c_set_8.setVar("selSubPref");
_jspx_th_c_set_8.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${subPref.detalheSubPref(auto.fkSubpref)}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_8 = _jspx_th_c_set_8.doStartTag();
if (_jspx_th_c_set_8.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_8);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_8);
return false;
}
private boolean _jspx_meth_c_set_9(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_9 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_9.setPageContext(_jspx_page_context);
_jspx_th_c_set_9.setParent(null);
_jspx_th_c_set_9.setVar("selCatContra");
_jspx_th_c_set_9.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${CatContra.detalheCatContra(auto.fkCatContrapartida)}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_9 = _jspx_th_c_set_9.doStartTag();
if (_jspx_th_c_set_9.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_9);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_9);
return false;
}
private boolean _jspx_meth_c_set_10(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_10 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_10.setPageContext(_jspx_page_context);
_jspx_th_c_set_10.setParent(null);
_jspx_th_c_set_10.setVar("selCatSubFin");
_jspx_th_c_set_10.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${CatSubFin.detalheCatSubFinalidade(auto.fkSubcatfinalidade)}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_10 = _jspx_th_c_set_10.doStartTag();
if (_jspx_th_c_set_10.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_10);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_10);
return false;
}
private boolean _jspx_meth_c_set_11(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_11 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_11.setPageContext(_jspx_page_context);
_jspx_th_c_set_11.setParent(null);
_jspx_th_c_set_11.setVar("selVal");
_jspx_th_c_set_11.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${Val.detalheValidacaoAutoCessao(auto.pkAutoStage)}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_11 = _jspx_th_c_set_11.doStartTag();
if (_jspx_th_c_set_11.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_11);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_11);
return false;
}
private boolean _jspx_meth_c_set_12(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_12 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_12.setPageContext(_jspx_page_context);
_jspx_th_c_set_12.setParent(null);
_jspx_th_c_set_12.setVar("qAC");
_jspx_th_c_set_12.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${param.qAC}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_12 = _jspx_th_c_set_12.doStartTag();
if (_jspx_th_c_set_12.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_12);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_12);
return false;
}
private boolean _jspx_meth_c_set_13(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_13 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_13.setPageContext(_jspx_page_context);
_jspx_th_c_set_13.setParent(null);
_jspx_th_c_set_13.setVar("qProcesso");
_jspx_th_c_set_13.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${param.qProcesso}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_13 = _jspx_th_c_set_13.doStartTag();
if (_jspx_th_c_set_13.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_13);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_13);
return false;
}
private boolean _jspx_meth_c_set_14(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_14 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_14.setPageContext(_jspx_page_context);
_jspx_th_c_set_14.setParent(null);
_jspx_th_c_set_14.setVar("qVigor");
_jspx_th_c_set_14.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${param.qVigor}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_14 = _jspx_th_c_set_14.doStartTag();
if (_jspx_th_c_set_14.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_14);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_14);
return false;
}
private boolean _jspx_meth_c_set_15(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_15 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_15.setPageContext(_jspx_page_context);
_jspx_th_c_set_15.setParent(null);
_jspx_th_c_set_15.setVar("qStatus");
_jspx_th_c_set_15.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${param.qStatus}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_15 = _jspx_th_c_set_15.doStartTag();
if (_jspx_th_c_set_15.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_15);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_15);
return false;
}
private boolean _jspx_meth_c_set_16(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_16 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_16.setPageContext(_jspx_page_context);
_jspx_th_c_set_16.setParent(null);
_jspx_th_c_set_16.setVar("pg");
_jspx_th_c_set_16.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${param.pg}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_16 = _jspx_th_c_set_16.doStartTag();
if (_jspx_th_c_set_16.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_16);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_16);
return false;
}
private boolean _jspx_meth_c_set_17(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_17 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_17.setPageContext(_jspx_page_context);
_jspx_th_c_set_17.setParent(null);
_jspx_th_c_set_17.setVar("pf");
_jspx_th_c_set_17.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${param.pf}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_17 = _jspx_th_c_set_17.doStartTag();
if (_jspx_th_c_set_17.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_17);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_17);
return false;
}
private boolean _jspx_meth_c_set_18(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_18 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_18.setPageContext(_jspx_page_context);
_jspx_th_c_set_18.setParent(null);
_jspx_th_c_set_18.setVar("pi");
_jspx_th_c_set_18.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${param.pi}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_18 = _jspx_th_c_set_18.doStartTag();
if (_jspx_th_c_set_18.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_18);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_18);
return false;
}
private boolean _jspx_meth_c_set_19(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_19 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_19.setPageContext(_jspx_page_context);
_jspx_th_c_set_19.setParent(null);
_jspx_th_c_set_19.setVar("execucao");
_jspx_th_c_set_19.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${param.execucao}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_19 = _jspx_th_c_set_19.doStartTag();
if (_jspx_th_c_set_19.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_19);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_19);
return false;
}
private boolean _jspx_meth_c_set_20(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_20 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_20.setPageContext(_jspx_page_context);
_jspx_th_c_set_20.setParent(null);
_jspx_th_c_set_20.setVar("novo");
_jspx_th_c_set_20.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${param.novo}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_20 = _jspx_th_c_set_20.doStartTag();
if (_jspx_th_c_set_20.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_20);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_20);
return false;
}
private boolean _jspx_meth_c_set_21(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_21 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_21.setPageContext(_jspx_page_context);
_jspx_th_c_set_21.setParent(null);
_jspx_th_c_set_21.setVar("pgValidacao");
_jspx_th_c_set_21.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${param.pgValidacao}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_21 = _jspx_th_c_set_21.doStartTag();
if (_jspx_th_c_set_21.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_21);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_21);
return false;
}
private boolean _jspx_meth_c_if_0(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_0 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_0.setPageContext(_jspx_page_context);
_jspx_th_c_if_0.setParent(null);
_jspx_th_c_if_0.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nrVerAc == '1'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_0 = _jspx_th_c_if_0.doStartTag();
if (_jspx_eval_c_if_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"badge badge-transparent\" title=\"Ok\"><i class=\"ace-icon fa fa-check-square-o green bigger-130\"></i></span>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_if_0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_0);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_0);
return false;
}
private boolean _jspx_meth_c_if_1(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_1 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_1.setPageContext(_jspx_page_context);
_jspx_th_c_if_1.setParent(null);
_jspx_th_c_if_1.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nrVerContrapartida == '1'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_1 = _jspx_th_c_if_1.doStartTag();
if (_jspx_eval_c_if_1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"badge badge-transparent\" title=\"OK\"><i class=\"ace-icon fa fa-check-square-o green bigger-130\"></i></span>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_if_1.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_1);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_1);
return false;
}
private boolean _jspx_meth_c_if_2(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_2 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_2.setPageContext(_jspx_page_context);
_jspx_th_c_if_2.setParent(null);
_jspx_th_c_if_2.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nrVerDispLegal == '1'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_2 = _jspx_th_c_if_2.doStartTag();
if (_jspx_eval_c_if_2 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"badge badge-transparent\" title=\"Ok\"><i class=\"ace-icon fa fa-check-square-o green bigger-130\"></i></span>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_if_2.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_2);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_2);
return false;
}
private boolean _jspx_meth_c_if_3(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_3 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_3.setPageContext(_jspx_page_context);
_jspx_th_c_if_3.setParent(null);
_jspx_th_c_if_3.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${ (auto.nrVerArqAc == '1' && auto.nrVerArqPlanta == '1') }", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_3 = _jspx_th_c_if_3.doStartTag();
if (_jspx_eval_c_if_3 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"badge badge-transparent\" title=\"Ok\"><i class=\"ace-icon fa fa-check-square-o green bigger-130\"></i></span>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_if_3.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_3.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_3);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_3);
return false;
}
private boolean _jspx_meth_c_if_4(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_4 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_4.setPageContext(_jspx_page_context);
_jspx_th_c_if_4.setParent(null);
_jspx_th_c_if_4.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${ (auto.nrVerVitoria == '1' && auto.nrVerArqPlanta == '1') }", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_4 = _jspx_th_c_if_4.doStartTag();
if (_jspx_eval_c_if_4 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"badge badge-transparent\" title=\"OK\"><i class=\"ace-icon fa fa-check-square-o green bigger-130\"></i></span>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_if_4.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_4.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_4);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_4);
return false;
}
private boolean _jspx_meth_c_if_5(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_5 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_5.setPageContext(_jspx_page_context);
_jspx_th_c_if_5.setParent(null);
_jspx_th_c_if_5.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nrVerValidacao == '1'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_5 = _jspx_th_c_if_5.doStartTag();
if (_jspx_eval_c_if_5 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"badge badge-transparent\" title=\"OK\"><i class=\"ace-icon fa fa-check-square-o green bigger-130\"></i></span>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_if_5.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_5.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_5);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_5);
return false;
}
private boolean _jspx_meth_c_choose_1(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_1 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_1.setPageContext(_jspx_page_context);
_jspx_th_c_choose_1.setParent(null);
int _jspx_eval_c_choose_1 = _jspx_th_c_choose_1.doStartTag();
if (_jspx_eval_c_choose_1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_3((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_1, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_4((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_1, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_0((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_1, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_1.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_1);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_1);
return false;
}
private boolean _jspx_meth_c_when_3(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_1, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_3 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_3.setPageContext(_jspx_page_context);
_jspx_th_c_when_3.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_1);
_jspx_th_c_when_3.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'edit'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_3 = _jspx_th_c_when_3.doStartTag();
if (_jspx_eval_c_when_3 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" name=\"codAC\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nmCodAc}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" placeholder=\"nº do AC\" required=\"required\">\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_3.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_3.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_3);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_3);
return false;
}
private boolean _jspx_meth_c_when_4(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_1, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_4 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_4.setPageContext(_jspx_page_context);
_jspx_th_c_when_4.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_1);
_jspx_th_c_when_4.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_4 = _jspx_th_c_when_4.doStartTag();
if (_jspx_eval_c_when_4 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" name=\"codAC\" placeholder=\"nº do AC\" required=\"required\" >\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_4.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_4.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_4);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_4);
return false;
}
private boolean _jspx_meth_c_otherwise_0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_1, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_0 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_0.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_1);
int _jspx_eval_c_otherwise_0 = _jspx_th_c_otherwise_0.doStartTag();
if (_jspx_eval_c_otherwise_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nmCodAc}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_0);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_0);
return false;
}
private boolean _jspx_meth_c_choose_2(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_2 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_2.setPageContext(_jspx_page_context);
_jspx_th_c_choose_2.setParent(null);
int _jspx_eval_c_choose_2 = _jspx_th_c_choose_2.doStartTag();
if (_jspx_eval_c_choose_2 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_5((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_2, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_6((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_2, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_1((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_2, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_2.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_2);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_2);
return false;
}
private boolean _jspx_meth_c_when_5(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_2, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_5 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_5.setPageContext(_jspx_page_context);
_jspx_th_c_when_5.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_2);
_jspx_th_c_when_5.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'edit'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_5 = _jspx_th_c_when_5.doStartTag();
if (_jspx_eval_c_when_5 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <select class=\"col-md-12 col-xs-12\" name=\"pkCatAutoCessao\" required=\"required\">\n");
out.write(" <option value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${selCatAuto.pkCatAutoCessao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write('"');
out.write('>');
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${selCatAuto.nmCatAutoCessao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</option>\n");
out.write(" <option></option>\n");
out.write(" ");
if (_jspx_meth_c_forEach_0((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_5, _jspx_page_context))
return true;
out.write("\n");
out.write(" </select>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_5.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_5.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_5);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_5);
return false;
}
private boolean _jspx_meth_c_forEach_0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_5, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:forEach
org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_forEach_0 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _jspx_tagPool_c_forEach_var_items.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class);
_jspx_th_c_forEach_0.setPageContext(_jspx_page_context);
_jspx_th_c_forEach_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_5);
_jspx_th_c_forEach_0.setVar("CatAuto");
_jspx_th_c_forEach_0.setItems((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${CatAuto.listSelectCatAutoCessao()}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int[] _jspx_push_body_count_c_forEach_0 = new int[] { 0 };
try {
int _jspx_eval_c_forEach_0 = _jspx_th_c_forEach_0.doStartTag();
if (_jspx_eval_c_forEach_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_if_6((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_forEach_0, _jspx_page_context, _jspx_push_body_count_c_forEach_0))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_forEach_0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_forEach_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_c_forEach_0[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_c_forEach_0.doCatch(_jspx_exception);
} finally {
_jspx_th_c_forEach_0.doFinally();
_jspx_tagPool_c_forEach_var_items.reuse(_jspx_th_c_forEach_0);
}
return false;
}
private boolean _jspx_meth_c_if_6(javax.servlet.jsp.tagext.JspTag _jspx_th_c_forEach_0, PageContext _jspx_page_context, int[] _jspx_push_body_count_c_forEach_0)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_6 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_6.setPageContext(_jspx_page_context);
_jspx_th_c_if_6.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_forEach_0);
_jspx_th_c_if_6.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${CatAuto.nmCatAutoCessao != 'Informação não cadastrada'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_6 = _jspx_th_c_if_6.doStartTag();
if (_jspx_eval_c_if_6 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <option value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${CatAuto.pkCatAutoCessao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" title=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${CatAuto.nmCatAutoCessao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write('"');
out.write('>');
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${CatAuto.nmCatAutoCessao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</option> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_if_6.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_6.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_6);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_6);
return false;
}
private boolean _jspx_meth_c_when_6(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_2, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_6 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_6.setPageContext(_jspx_page_context);
_jspx_th_c_when_6.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_2);
_jspx_th_c_when_6.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_6 = _jspx_th_c_when_6.doStartTag();
if (_jspx_eval_c_when_6 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <select class=\"col-md-12 col-xs-12\" name=\"pkCatAutoCessao\" required=\"required\">\n");
out.write(" <option></option>\n");
out.write(" ");
if (_jspx_meth_c_forEach_1((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_6, _jspx_page_context))
return true;
out.write("\n");
out.write(" </select>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_6.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_6.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_6);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_6);
return false;
}
private boolean _jspx_meth_c_forEach_1(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_6, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:forEach
org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_forEach_1 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _jspx_tagPool_c_forEach_var_items.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class);
_jspx_th_c_forEach_1.setPageContext(_jspx_page_context);
_jspx_th_c_forEach_1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_6);
_jspx_th_c_forEach_1.setVar("CatAuto");
_jspx_th_c_forEach_1.setItems((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${CatAuto.listSelectCatAutoCessao()}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int[] _jspx_push_body_count_c_forEach_1 = new int[] { 0 };
try {
int _jspx_eval_c_forEach_1 = _jspx_th_c_forEach_1.doStartTag();
if (_jspx_eval_c_forEach_1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_if_7((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_forEach_1, _jspx_page_context, _jspx_push_body_count_c_forEach_1))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_forEach_1.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_forEach_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_c_forEach_1[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_c_forEach_1.doCatch(_jspx_exception);
} finally {
_jspx_th_c_forEach_1.doFinally();
_jspx_tagPool_c_forEach_var_items.reuse(_jspx_th_c_forEach_1);
}
return false;
}
private boolean _jspx_meth_c_if_7(javax.servlet.jsp.tagext.JspTag _jspx_th_c_forEach_1, PageContext _jspx_page_context, int[] _jspx_push_body_count_c_forEach_1)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_7 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_7.setPageContext(_jspx_page_context);
_jspx_th_c_if_7.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_forEach_1);
_jspx_th_c_if_7.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${CatAuto.nmCatAutoCessao != 'Informação não cadastrada'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_7 = _jspx_th_c_if_7.doStartTag();
if (_jspx_eval_c_if_7 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <option value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${CatAuto.pkCatAutoCessao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" title=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${CatAuto.nmCatAutoCessao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write('"');
out.write('>');
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${CatAuto.nmCatAutoCessao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</option> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_if_7.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_7.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_7);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_7);
return false;
}
private boolean _jspx_meth_c_otherwise_1(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_2, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_1 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_1.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_2);
int _jspx_eval_c_otherwise_1 = _jspx_th_c_otherwise_1.doStartTag();
if (_jspx_eval_c_otherwise_1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${selCatAuto.nmCatAutoCessao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_1.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_1);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_1);
return false;
}
private boolean _jspx_meth_c_choose_3(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_3 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_3.setPageContext(_jspx_page_context);
_jspx_th_c_choose_3.setParent(null);
int _jspx_eval_c_choose_3 = _jspx_th_c_choose_3.doStartTag();
if (_jspx_eval_c_choose_3 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_7((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_3, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_8((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_3, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_2((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_3, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_3.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_3.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_3);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_3);
return false;
}
private boolean _jspx_meth_c_when_7(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_3, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_7 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_7.setPageContext(_jspx_page_context);
_jspx_th_c_when_7.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_3);
_jspx_th_c_when_7.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'edit'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_7 = _jspx_th_c_when_7.doStartTag();
if (_jspx_eval_c_when_7 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <div class=\"input-group\">\n");
out.write(" <input class=\"form-control date-picker\" id=\"id-date-picker-1\" name=\"dtlavratura\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.dtLavratura}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" type=\"text\" placeholder=\"dd/mm/aaaa\" data-date-format=\"dd/mm/yyyy\" required=\"required\">\n");
out.write(" <span class=\"input-group-addon\">\n");
out.write(" <i class=\"fa fa-calendar bigger-110\"></i>\n");
out.write(" </span>\n");
out.write(" </div>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_7.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_7.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_7);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_7);
return false;
}
private boolean _jspx_meth_c_when_8(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_3, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_8 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_8.setPageContext(_jspx_page_context);
_jspx_th_c_when_8.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_3);
_jspx_th_c_when_8.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_8 = _jspx_th_c_when_8.doStartTag();
if (_jspx_eval_c_when_8 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <div class=\"input-group\">\n");
out.write(" <input class=\"form-control date-picker\" id=\"id-date-picker-1\" name=\"dtlavratura\" type=\"text\" placeholder=\"dd/mm/aaaa\" data-date-format=\"dd/mm/yyyy\" required=\"required\">\n");
out.write(" <span class=\"input-group-addon\">\n");
out.write(" <i class=\"fa fa-calendar bigger-110\"></i>\n");
out.write(" </span>\n");
out.write(" </div>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_8.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_8.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_8);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_8);
return false;
}
private boolean _jspx_meth_c_otherwise_2(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_3, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_2 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_2.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_2.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_3);
int _jspx_eval_c_otherwise_2 = _jspx_th_c_otherwise_2.doStartTag();
if (_jspx_eval_c_otherwise_2 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.dtLavratura}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_2.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_2);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_2);
return false;
}
private boolean _jspx_meth_c_choose_4(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_4 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_4.setPageContext(_jspx_page_context);
_jspx_th_c_choose_4.setParent(null);
int _jspx_eval_c_choose_4 = _jspx_th_c_choose_4.doStartTag();
if (_jspx_eval_c_choose_4 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_9((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_4, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_10((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_4, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_3((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_4, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_4.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_4.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_4);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_4);
return false;
}
private boolean _jspx_meth_c_when_9(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_4, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_9 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_9.setPageContext(_jspx_page_context);
_jspx_th_c_when_9.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_4);
_jspx_th_c_when_9.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'edit'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_9 = _jspx_th_c_when_9.doStartTag();
if (_jspx_eval_c_when_9 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <select class=\"col-md-12 col-xs-12\" name=\"pkNivelAdm\" required=\"required\">\n");
out.write(" <option value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${selNvAdm.pkAdm}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write('"');
out.write('>');
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${selNvAdm.nmAdm}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</option>\n");
out.write(" <option value=\"\"></option> \n");
out.write(" ");
if (_jspx_meth_c_forEach_2((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_9, _jspx_page_context))
return true;
out.write("\n");
out.write(" </select> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_9.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_9.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_9);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_9);
return false;
}
private boolean _jspx_meth_c_forEach_2(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_9, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:forEach
org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_forEach_2 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _jspx_tagPool_c_forEach_var_items.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class);
_jspx_th_c_forEach_2.setPageContext(_jspx_page_context);
_jspx_th_c_forEach_2.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_9);
_jspx_th_c_forEach_2.setVar("nv");
_jspx_th_c_forEach_2.setItems((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${NivelAdm.listNivelAdm()}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int[] _jspx_push_body_count_c_forEach_2 = new int[] { 0 };
try {
int _jspx_eval_c_forEach_2 = _jspx_th_c_forEach_2.doStartTag();
if (_jspx_eval_c_forEach_2 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_if_8((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_forEach_2, _jspx_page_context, _jspx_push_body_count_c_forEach_2))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_forEach_2.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_forEach_2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_c_forEach_2[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_c_forEach_2.doCatch(_jspx_exception);
} finally {
_jspx_th_c_forEach_2.doFinally();
_jspx_tagPool_c_forEach_var_items.reuse(_jspx_th_c_forEach_2);
}
return false;
}
private boolean _jspx_meth_c_if_8(javax.servlet.jsp.tagext.JspTag _jspx_th_c_forEach_2, PageContext _jspx_page_context, int[] _jspx_push_body_count_c_forEach_2)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_8 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_8.setPageContext(_jspx_page_context);
_jspx_th_c_if_8.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_forEach_2);
_jspx_th_c_if_8.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${nv.nmAdm != 'Informação não cadastrada'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_8 = _jspx_th_c_if_8.doStartTag();
if (_jspx_eval_c_if_8 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <option value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${nv.pkAdm}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" title=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${nv.nmAdm}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write('"');
out.write('>');
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${nv.nmAdm}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</option> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_if_8.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_8.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_8);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_8);
return false;
}
private boolean _jspx_meth_c_when_10(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_4, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_10 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_10.setPageContext(_jspx_page_context);
_jspx_th_c_when_10.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_4);
_jspx_th_c_when_10.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_10 = _jspx_th_c_when_10.doStartTag();
if (_jspx_eval_c_when_10 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <select class=\"col-md-12 col-xs-12\" name=\"pkNivelAdm\" required=\"required\">\n");
out.write(" <option value=\"\"></option> \n");
out.write(" ");
if (_jspx_meth_c_forEach_3((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_10, _jspx_page_context))
return true;
out.write("\n");
out.write(" </select> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_10.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_10.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_10);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_10);
return false;
}
private boolean _jspx_meth_c_forEach_3(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_10, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:forEach
org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_forEach_3 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _jspx_tagPool_c_forEach_var_items.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class);
_jspx_th_c_forEach_3.setPageContext(_jspx_page_context);
_jspx_th_c_forEach_3.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_10);
_jspx_th_c_forEach_3.setVar("nv");
_jspx_th_c_forEach_3.setItems((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${NivelAdm.listNivelAdm()}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int[] _jspx_push_body_count_c_forEach_3 = new int[] { 0 };
try {
int _jspx_eval_c_forEach_3 = _jspx_th_c_forEach_3.doStartTag();
if (_jspx_eval_c_forEach_3 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_if_9((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_forEach_3, _jspx_page_context, _jspx_push_body_count_c_forEach_3))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_forEach_3.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_forEach_3.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_c_forEach_3[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_c_forEach_3.doCatch(_jspx_exception);
} finally {
_jspx_th_c_forEach_3.doFinally();
_jspx_tagPool_c_forEach_var_items.reuse(_jspx_th_c_forEach_3);
}
return false;
}
private boolean _jspx_meth_c_if_9(javax.servlet.jsp.tagext.JspTag _jspx_th_c_forEach_3, PageContext _jspx_page_context, int[] _jspx_push_body_count_c_forEach_3)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_9 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_9.setPageContext(_jspx_page_context);
_jspx_th_c_if_9.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_forEach_3);
_jspx_th_c_if_9.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${nv.nmAdm != 'Informação não cadastrada'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_9 = _jspx_th_c_if_9.doStartTag();
if (_jspx_eval_c_if_9 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <option value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${nv.pkAdm}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" title=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${nv.nmAdm}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write('"');
out.write('>');
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${nv.nmAdm}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</option> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_if_9.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_9.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_9);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_9);
return false;
}
private boolean _jspx_meth_c_otherwise_3(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_4, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_3 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_3.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_3.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_4);
int _jspx_eval_c_otherwise_3 = _jspx_th_c_otherwise_3.doStartTag();
if (_jspx_eval_c_otherwise_3 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${selNvAdm.nmAdm}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_3.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_3.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_3);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_3);
return false;
}
private boolean _jspx_meth_c_choose_5(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_5 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_5.setPageContext(_jspx_page_context);
_jspx_th_c_choose_5.setParent(null);
int _jspx_eval_c_choose_5 = _jspx_th_c_choose_5.doStartTag();
if (_jspx_eval_c_choose_5 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_11((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_5, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_12((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_5, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_4((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_5, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_5.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_5.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_5);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_5);
return false;
}
private boolean _jspx_meth_c_when_11(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_5, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_11 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_11.setPageContext(_jspx_page_context);
_jspx_th_c_when_11.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_5);
_jspx_th_c_when_11.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'edit'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_11 = _jspx_th_c_when_11.doStartTag();
if (_jspx_eval_c_when_11 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <select class=\"col-md-12 col-xs-12\" name=\"pkTpcessao\" required=\"required\">\n");
out.write(" <option value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${selTpCessao.pkTipoAutoCessao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write('"');
out.write('>');
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${selTpCessao.nmTipoAutoCessao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</option>\n");
out.write(" <option value=\"\"></option> \n");
out.write(" ");
if (_jspx_meth_c_forEach_4((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_11, _jspx_page_context))
return true;
out.write("\n");
out.write(" </select>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_11.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_11.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_11);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_11);
return false;
}
private boolean _jspx_meth_c_forEach_4(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_11, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:forEach
org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_forEach_4 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _jspx_tagPool_c_forEach_var_items.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class);
_jspx_th_c_forEach_4.setPageContext(_jspx_page_context);
_jspx_th_c_forEach_4.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_11);
_jspx_th_c_forEach_4.setVar("cat");
_jspx_th_c_forEach_4.setItems((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${TpCessao.listSelectTpCessao()}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int[] _jspx_push_body_count_c_forEach_4 = new int[] { 0 };
try {
int _jspx_eval_c_forEach_4 = _jspx_th_c_forEach_4.doStartTag();
if (_jspx_eval_c_forEach_4 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <option value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${cat.pkTipoAutoCessao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" title=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${cat.nmTipoAutoCessao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write('"');
out.write('>');
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${cat.nmTipoAutoCessao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</option> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_forEach_4.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_forEach_4.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_c_forEach_4[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_c_forEach_4.doCatch(_jspx_exception);
} finally {
_jspx_th_c_forEach_4.doFinally();
_jspx_tagPool_c_forEach_var_items.reuse(_jspx_th_c_forEach_4);
}
return false;
}
private boolean _jspx_meth_c_when_12(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_5, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_12 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_12.setPageContext(_jspx_page_context);
_jspx_th_c_when_12.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_5);
_jspx_th_c_when_12.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_12 = _jspx_th_c_when_12.doStartTag();
if (_jspx_eval_c_when_12 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <select class=\"col-md-12 col-xs-12\" name=\"pkTpcessao\" required=\"required\">\n");
out.write(" <option value=\"\"></option> \n");
out.write(" ");
if (_jspx_meth_c_forEach_5((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_12, _jspx_page_context))
return true;
out.write("\n");
out.write(" </select>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_12.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_12.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_12);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_12);
return false;
}
private boolean _jspx_meth_c_forEach_5(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_12, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:forEach
org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_forEach_5 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _jspx_tagPool_c_forEach_var_items.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class);
_jspx_th_c_forEach_5.setPageContext(_jspx_page_context);
_jspx_th_c_forEach_5.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_12);
_jspx_th_c_forEach_5.setVar("cat");
_jspx_th_c_forEach_5.setItems((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${TpCessao.listSelectTpCessao()}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int[] _jspx_push_body_count_c_forEach_5 = new int[] { 0 };
try {
int _jspx_eval_c_forEach_5 = _jspx_th_c_forEach_5.doStartTag();
if (_jspx_eval_c_forEach_5 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <option value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${cat.pkTipoAutoCessao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" title=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${cat.nmTipoAutoCessao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write('"');
out.write('>');
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${cat.nmTipoAutoCessao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</option> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_forEach_5.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_forEach_5.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_c_forEach_5[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_c_forEach_5.doCatch(_jspx_exception);
} finally {
_jspx_th_c_forEach_5.doFinally();
_jspx_tagPool_c_forEach_var_items.reuse(_jspx_th_c_forEach_5);
}
return false;
}
private boolean _jspx_meth_c_otherwise_4(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_5, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_4 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_4.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_4.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_5);
int _jspx_eval_c_otherwise_4 = _jspx_th_c_otherwise_4.doStartTag();
if (_jspx_eval_c_otherwise_4 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${selTpCessao.nmTipoAutoCessao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_4.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_4.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_4);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_4);
return false;
}
private boolean _jspx_meth_c_choose_6(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_6 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_6.setPageContext(_jspx_page_context);
_jspx_th_c_choose_6.setParent(null);
int _jspx_eval_c_choose_6 = _jspx_th_c_choose_6.doStartTag();
if (_jspx_eval_c_choose_6 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_13((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_6, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_14((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_6, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_5((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_6, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_6.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_6.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_6);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_6);
return false;
}
private boolean _jspx_meth_c_when_13(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_6, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_13 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_13.setPageContext(_jspx_page_context);
_jspx_th_c_when_13.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_6);
_jspx_th_c_when_13.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'edit'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_13 = _jspx_th_c_when_13.doStartTag();
if (_jspx_eval_c_when_13 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <input type=\"text\" class=\"col-xs-12 col-md-12\" name=\"nrprocesso\" id=\"nrprocesso\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nmProcesso}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" placeholder=\"nº do processo\" required=\"required\" onKeyPress=\"return somenteNum(event);\" >\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_13.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_13.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_13);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_13);
return false;
}
private boolean _jspx_meth_c_when_14(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_6, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_14 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_14.setPageContext(_jspx_page_context);
_jspx_th_c_when_14.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_6);
_jspx_th_c_when_14.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_14 = _jspx_th_c_when_14.doStartTag();
if (_jspx_eval_c_when_14 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <input type=\"text\" class=\"col-xs-12 col-md-12\" name=\"nrprocesso\" id=\"nrprocesso\" placeholder=\"nº do processo\" required=\"required\" onKeyPress=\"return somenteNum(event);\" >\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_14.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_14.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_14);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_14);
return false;
}
private boolean _jspx_meth_c_otherwise_5(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_6, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_5 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_5.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_5.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_6);
int _jspx_eval_c_otherwise_5 = _jspx_th_c_otherwise_5.doStartTag();
if (_jspx_eval_c_otherwise_5 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nmProcesso}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_5.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_5.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_5);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_5);
return false;
}
private boolean _jspx_meth_c_choose_7(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_7 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_7.setPageContext(_jspx_page_context);
_jspx_th_c_choose_7.setParent(null);
int _jspx_eval_c_choose_7 = _jspx_th_c_choose_7.doStartTag();
if (_jspx_eval_c_choose_7 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_15((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_7, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_16((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_7, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_6((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_7, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_7.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_7.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_7);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_7);
return false;
}
private boolean _jspx_meth_c_when_15(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_7, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_15 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_15.setPageContext(_jspx_page_context);
_jspx_th_c_when_15.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_7);
_jspx_th_c_when_15.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'edit'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_15 = _jspx_th_c_when_15.doStartTag();
if (_jspx_eval_c_when_15 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" name=\"nmcessionario\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nmCessionario}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" placeholder=\"nome do cessionário\" required=\"required\" >\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_15.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_15.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_15);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_15);
return false;
}
private boolean _jspx_meth_c_when_16(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_7, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_16 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_16.setPageContext(_jspx_page_context);
_jspx_th_c_when_16.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_7);
_jspx_th_c_when_16.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_16 = _jspx_th_c_when_16.doStartTag();
if (_jspx_eval_c_when_16 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" name=\"nmcessionario\" placeholder=\"nome do cessionário\" required=\"required\" >\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_16.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_16.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_16);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_16);
return false;
}
private boolean _jspx_meth_c_otherwise_6(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_7, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_6 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_6.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_6.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_7);
int _jspx_eval_c_otherwise_6 = _jspx_th_c_otherwise_6.doStartTag();
if (_jspx_eval_c_otherwise_6 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nmCessionario}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_6.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_6.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_6);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_6);
return false;
}
private boolean _jspx_meth_c_choose_8(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_8 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_8.setPageContext(_jspx_page_context);
_jspx_th_c_choose_8.setParent(null);
int _jspx_eval_c_choose_8 = _jspx_th_c_choose_8.doStartTag();
if (_jspx_eval_c_choose_8 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_17((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_8, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_18((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_8, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_7((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_8, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_8.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_8.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_8);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_8);
return false;
}
private boolean _jspx_meth_c_when_17(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_8, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_17 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_17.setPageContext(_jspx_page_context);
_jspx_th_c_when_17.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_8);
_jspx_th_c_when_17.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'edit'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_17 = _jspx_th_c_when_17.doStartTag();
if (_jspx_eval_c_when_17 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <select class=\"col-md-12 col-xs-12\" name=\"pkCatEntidade\" required=\"required\">\n");
out.write(" <option value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${selCatEnt.pkCatEntidade}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write('"');
out.write('>');
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${selCatEnt.nmCatEntidade}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</option>\n");
out.write(" <option value=\"\"></option> \n");
out.write(" ");
if (_jspx_meth_c_forEach_6((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_17, _jspx_page_context))
return true;
out.write("\n");
out.write(" </select>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_17.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_17.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_17);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_17);
return false;
}
private boolean _jspx_meth_c_forEach_6(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_17, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:forEach
org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_forEach_6 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _jspx_tagPool_c_forEach_var_items.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class);
_jspx_th_c_forEach_6.setPageContext(_jspx_page_context);
_jspx_th_c_forEach_6.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_17);
_jspx_th_c_forEach_6.setVar("ent");
_jspx_th_c_forEach_6.setItems((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${CatEnt.listCatEnt()}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int[] _jspx_push_body_count_c_forEach_6 = new int[] { 0 };
try {
int _jspx_eval_c_forEach_6 = _jspx_th_c_forEach_6.doStartTag();
if (_jspx_eval_c_forEach_6 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_if_10((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_forEach_6, _jspx_page_context, _jspx_push_body_count_c_forEach_6))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_forEach_6.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_forEach_6.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_c_forEach_6[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_c_forEach_6.doCatch(_jspx_exception);
} finally {
_jspx_th_c_forEach_6.doFinally();
_jspx_tagPool_c_forEach_var_items.reuse(_jspx_th_c_forEach_6);
}
return false;
}
private boolean _jspx_meth_c_if_10(javax.servlet.jsp.tagext.JspTag _jspx_th_c_forEach_6, PageContext _jspx_page_context, int[] _jspx_push_body_count_c_forEach_6)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_10 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_10.setPageContext(_jspx_page_context);
_jspx_th_c_if_10.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_forEach_6);
_jspx_th_c_if_10.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${ent.nmCatEntidade != 'Informação não cadastrada'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_10 = _jspx_th_c_if_10.doStartTag();
if (_jspx_eval_c_if_10 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <option value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${ent.pkCatEntidade}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" title=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${ent.nmCatEntidade}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write('"');
out.write('>');
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${ent.nmCatEntidade}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</option> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_if_10.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_10.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_10);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_10);
return false;
}
private boolean _jspx_meth_c_when_18(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_8, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_18 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_18.setPageContext(_jspx_page_context);
_jspx_th_c_when_18.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_8);
_jspx_th_c_when_18.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_18 = _jspx_th_c_when_18.doStartTag();
if (_jspx_eval_c_when_18 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <select class=\"col-md-12 col-xs-12\" name=\"pkCatEntidade\" required=\"required\">\n");
out.write(" <option value=\"\"></option> \n");
out.write(" ");
if (_jspx_meth_c_forEach_7((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_18, _jspx_page_context))
return true;
out.write("\n");
out.write(" </select>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_18.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_18.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_18);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_18);
return false;
}
private boolean _jspx_meth_c_forEach_7(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_18, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:forEach
org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_forEach_7 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _jspx_tagPool_c_forEach_var_items.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class);
_jspx_th_c_forEach_7.setPageContext(_jspx_page_context);
_jspx_th_c_forEach_7.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_18);
_jspx_th_c_forEach_7.setVar("ent");
_jspx_th_c_forEach_7.setItems((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${CatEnt.listCatEnt()}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int[] _jspx_push_body_count_c_forEach_7 = new int[] { 0 };
try {
int _jspx_eval_c_forEach_7 = _jspx_th_c_forEach_7.doStartTag();
if (_jspx_eval_c_forEach_7 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_if_11((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_forEach_7, _jspx_page_context, _jspx_push_body_count_c_forEach_7))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_forEach_7.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_forEach_7.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_c_forEach_7[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_c_forEach_7.doCatch(_jspx_exception);
} finally {
_jspx_th_c_forEach_7.doFinally();
_jspx_tagPool_c_forEach_var_items.reuse(_jspx_th_c_forEach_7);
}
return false;
}
private boolean _jspx_meth_c_if_11(javax.servlet.jsp.tagext.JspTag _jspx_th_c_forEach_7, PageContext _jspx_page_context, int[] _jspx_push_body_count_c_forEach_7)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_11 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_11.setPageContext(_jspx_page_context);
_jspx_th_c_if_11.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_forEach_7);
_jspx_th_c_if_11.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${ent.nmCatEntidade != 'Informação não cadastrada'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_11 = _jspx_th_c_if_11.doStartTag();
if (_jspx_eval_c_if_11 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <option value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${ent.pkCatEntidade}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" title=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${ent.nmCatEntidade}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write('"');
out.write('>');
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${ent.nmCatEntidade}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</option> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_if_11.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_11.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_11);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_11);
return false;
}
private boolean _jspx_meth_c_otherwise_7(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_8, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_7 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_7.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_7.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_8);
int _jspx_eval_c_otherwise_7 = _jspx_th_c_otherwise_7.doStartTag();
if (_jspx_eval_c_otherwise_7 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${selCatEnt.nmCatEntidade}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_7.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_7.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_7);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_7);
return false;
}
private boolean _jspx_meth_c_choose_9(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_9 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_9.setPageContext(_jspx_page_context);
_jspx_th_c_choose_9.setParent(null);
int _jspx_eval_c_choose_9 = _jspx_th_c_choose_9.doStartTag();
if (_jspx_eval_c_choose_9 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_19((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_9, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_20((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_9, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_8((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_9, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_9.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_9.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_9);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_9);
return false;
}
private boolean _jspx_meth_c_when_19(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_9, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_19 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_19.setPageContext(_jspx_page_context);
_jspx_th_c_when_19.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_9);
_jspx_th_c_when_19.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'edit'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_19 = _jspx_th_c_when_19.doStartTag();
if (_jspx_eval_c_when_19 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <select class=\"col-md-12 col-xs-12\" name=\"pkCatFinalidade\" id=\"pkCatFinalidade\" onChange=\"pkCatFin(this)\" required=\"required\">\n");
out.write(" <option value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${selCatFin.pkCatFinalidade}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write('"');
out.write('>');
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${selCatFin.nmCatFinalidade}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</option>\n");
out.write(" <option></option> \n");
out.write(" ");
if (_jspx_meth_c_forEach_8((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_19, _jspx_page_context))
return true;
out.write("\n");
out.write(" </select>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_19.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_19.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_19);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_19);
return false;
}
private boolean _jspx_meth_c_forEach_8(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_19, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:forEach
org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_forEach_8 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _jspx_tagPool_c_forEach_var_items.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class);
_jspx_th_c_forEach_8.setPageContext(_jspx_page_context);
_jspx_th_c_forEach_8.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_19);
_jspx_th_c_forEach_8.setVar("catFin");
_jspx_th_c_forEach_8.setItems((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${CatFin.listSelectCatFinalidade()}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int[] _jspx_push_body_count_c_forEach_8 = new int[] { 0 };
try {
int _jspx_eval_c_forEach_8 = _jspx_th_c_forEach_8.doStartTag();
if (_jspx_eval_c_forEach_8 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_if_12((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_forEach_8, _jspx_page_context, _jspx_push_body_count_c_forEach_8))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_forEach_8.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_forEach_8.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_c_forEach_8[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_c_forEach_8.doCatch(_jspx_exception);
} finally {
_jspx_th_c_forEach_8.doFinally();
_jspx_tagPool_c_forEach_var_items.reuse(_jspx_th_c_forEach_8);
}
return false;
}
private boolean _jspx_meth_c_if_12(javax.servlet.jsp.tagext.JspTag _jspx_th_c_forEach_8, PageContext _jspx_page_context, int[] _jspx_push_body_count_c_forEach_8)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_12 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_12.setPageContext(_jspx_page_context);
_jspx_th_c_if_12.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_forEach_8);
_jspx_th_c_if_12.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${catFin.nmCatFinalidade != 'Informação não cadastrada'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_12 = _jspx_th_c_if_12.doStartTag();
if (_jspx_eval_c_if_12 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <option value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${catFin.pkCatFinalidade}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" title=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${catFin.nmCatFinalidade}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write('"');
out.write('>');
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${catFin.nmCatFinalidade}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</option> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_if_12.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_12.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_12);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_12);
return false;
}
private boolean _jspx_meth_c_when_20(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_9, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_20 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_20.setPageContext(_jspx_page_context);
_jspx_th_c_when_20.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_9);
_jspx_th_c_when_20.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_20 = _jspx_th_c_when_20.doStartTag();
if (_jspx_eval_c_when_20 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <select class=\"col-md-12 col-xs-12\" name=\"pkCatFinalidade\" id=\"pkCatFinalidade\" onChange=\"pkCatFin(this)\" required=\"required\">\n");
out.write(" <option></option> \n");
out.write(" ");
if (_jspx_meth_c_forEach_9((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_20, _jspx_page_context))
return true;
out.write("\n");
out.write(" </select>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_20.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_20.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_20);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_20);
return false;
}
private boolean _jspx_meth_c_forEach_9(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_20, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:forEach
org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_forEach_9 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _jspx_tagPool_c_forEach_var_items.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class);
_jspx_th_c_forEach_9.setPageContext(_jspx_page_context);
_jspx_th_c_forEach_9.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_20);
_jspx_th_c_forEach_9.setVar("catFin");
_jspx_th_c_forEach_9.setItems((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${CatFin.listSelectCatFinalidade()}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int[] _jspx_push_body_count_c_forEach_9 = new int[] { 0 };
try {
int _jspx_eval_c_forEach_9 = _jspx_th_c_forEach_9.doStartTag();
if (_jspx_eval_c_forEach_9 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_if_13((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_forEach_9, _jspx_page_context, _jspx_push_body_count_c_forEach_9))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_forEach_9.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_forEach_9.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_c_forEach_9[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_c_forEach_9.doCatch(_jspx_exception);
} finally {
_jspx_th_c_forEach_9.doFinally();
_jspx_tagPool_c_forEach_var_items.reuse(_jspx_th_c_forEach_9);
}
return false;
}
private boolean _jspx_meth_c_if_13(javax.servlet.jsp.tagext.JspTag _jspx_th_c_forEach_9, PageContext _jspx_page_context, int[] _jspx_push_body_count_c_forEach_9)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_13 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_13.setPageContext(_jspx_page_context);
_jspx_th_c_if_13.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_forEach_9);
_jspx_th_c_if_13.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${catFin.nmCatFinalidade != 'Informação não cadastrada'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_13 = _jspx_th_c_if_13.doStartTag();
if (_jspx_eval_c_if_13 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <option value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${catFin.pkCatFinalidade}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" title=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${catFin.nmCatFinalidade}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write('"');
out.write('>');
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${catFin.nmCatFinalidade}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</option> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_if_13.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_13.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_13);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_13);
return false;
}
private boolean _jspx_meth_c_otherwise_8(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_9, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_8 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_8.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_8.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_9);
int _jspx_eval_c_otherwise_8 = _jspx_th_c_otherwise_8.doStartTag();
if (_jspx_eval_c_otherwise_8 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${selCatFin.nmCatFinalidade}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_8.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_8.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_8);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_8);
return false;
}
private boolean _jspx_meth_c_choose_10(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_10 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_10.setPageContext(_jspx_page_context);
_jspx_th_c_choose_10.setParent(null);
int _jspx_eval_c_choose_10 = _jspx_th_c_choose_10.doStartTag();
if (_jspx_eval_c_choose_10 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_21((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_10, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_22((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_10, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_9((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_10, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_10.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_10.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_10);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_10);
return false;
}
private boolean _jspx_meth_c_when_21(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_10, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_21 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_21.setPageContext(_jspx_page_context);
_jspx_th_c_when_21.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_10);
_jspx_th_c_when_21.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'edit'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_21 = _jspx_th_c_when_21.doStartTag();
if (_jspx_eval_c_when_21 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <select class=\"col-md-12 col-xs-12\" name=\"pkSubCatFinalidade\" id=\"selectSubFinalidade\" required=\"required\" >\n");
out.write(" <option value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${selCatSubFin.pkCatSubFinalidade}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" title=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${selCatSubFin.nmCatSubFinalidade}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write('"');
out.write('>');
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${selCatSubFin.sgCatSubFinalidade}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</option>\n");
out.write(" </select>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_21.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_21.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_21);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_21);
return false;
}
private boolean _jspx_meth_c_when_22(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_10, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_22 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_22.setPageContext(_jspx_page_context);
_jspx_th_c_when_22.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_10);
_jspx_th_c_when_22.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_22 = _jspx_th_c_when_22.doStartTag();
if (_jspx_eval_c_when_22 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <select class=\"col-md-12 col-xs-12\" name=\"pkSubCatFinalidade\" id=\"selectSubFinalidade\" required=\"required\" >\n");
out.write(" </select>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_22.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_22.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_22);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_22);
return false;
}
private boolean _jspx_meth_c_otherwise_9(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_10, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_9 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_9.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_9.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_10);
int _jspx_eval_c_otherwise_9 = _jspx_th_c_otherwise_9.doStartTag();
if (_jspx_eval_c_otherwise_9 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${selCatSubFin.nmCatSubFinalidade}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_9.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_9.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_9);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_9);
return false;
}
private boolean _jspx_meth_c_choose_11(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_11 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_11.setPageContext(_jspx_page_context);
_jspx_th_c_choose_11.setParent(null);
int _jspx_eval_c_choose_11 = _jspx_th_c_choose_11.doStartTag();
if (_jspx_eval_c_choose_11 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_23((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_11, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_24((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_11, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_10((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_11, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_11.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_11.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_11);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_11);
return false;
}
private boolean _jspx_meth_c_when_23(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_11, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_23 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_23.setPageContext(_jspx_page_context);
_jspx_th_c_when_23.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_11);
_jspx_th_c_when_23.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'edit'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_23 = _jspx_th_c_when_23.doStartTag();
if (_jspx_eval_c_when_23 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <textarea class=\"form-control\" id=\"form-field-8\" name=\"dsFinalidade\" placeholder=\"Descreve a finalidade ex: Instalação do 75º Distrito Policial-PM\" style=\"margin: 0px 102.656px 0px 0px; width: 600px; height: 50px;\" required=\"required\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.dsFinalidade}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</textarea>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_23.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_23.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_23);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_23);
return false;
}
private boolean _jspx_meth_c_when_24(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_11, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_24 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_24.setPageContext(_jspx_page_context);
_jspx_th_c_when_24.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_11);
_jspx_th_c_when_24.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_24 = _jspx_th_c_when_24.doStartTag();
if (_jspx_eval_c_when_24 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <textarea class=\"form-control\" id=\"form-field-8\" name=\"dsFinalidade\" placeholder=\"Descreve a finalidade ex: Instalação do 75º Distrito Policial-PM\" style=\"margin: 0px 102.656px 0px 0px; width: 600px; height: 50px;\" required=\"required\"></textarea>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_24.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_24.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_24);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_24);
return false;
}
private boolean _jspx_meth_c_otherwise_10(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_11, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_10 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_10.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_10.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_11);
int _jspx_eval_c_otherwise_10 = _jspx_th_c_otherwise_10.doStartTag();
if (_jspx_eval_c_otherwise_10 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.dsFinalidade}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_10.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_10.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_10);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_10);
return false;
}
private boolean _jspx_meth_c_choose_12(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_12 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_12.setPageContext(_jspx_page_context);
_jspx_th_c_choose_12.setParent(null);
int _jspx_eval_c_choose_12 = _jspx_th_c_choose_12.doStartTag();
if (_jspx_eval_c_choose_12 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_25((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_12, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_26((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_12, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_11((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_12, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_12.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_12.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_12);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_12);
return false;
}
private boolean _jspx_meth_c_when_25(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_12, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_25 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_25.setPageContext(_jspx_page_context);
_jspx_th_c_when_25.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_12);
_jspx_th_c_when_25.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'edit'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_25 = _jspx_th_c_when_25.doStartTag();
if (_jspx_eval_c_when_25 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" name=\"nmplanta\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nmPlanta}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" placeholder=\"nº da planta\" required=\"required\" >\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_25.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_25.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_25);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_25);
return false;
}
private boolean _jspx_meth_c_when_26(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_12, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_26 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_26.setPageContext(_jspx_page_context);
_jspx_th_c_when_26.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_12);
_jspx_th_c_when_26.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_26 = _jspx_th_c_when_26.doStartTag();
if (_jspx_eval_c_when_26 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" name=\"nmplanta\" placeholder=\"nº da planta\" >\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_26.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_26.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_26);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_26);
return false;
}
private boolean _jspx_meth_c_otherwise_11(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_12, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_11 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_11.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_11.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_12);
int _jspx_eval_c_otherwise_11 = _jspx_th_c_otherwise_11.doStartTag();
if (_jspx_eval_c_otherwise_11 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nmPlanta}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_11.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_11.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_11);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_11);
return false;
}
private boolean _jspx_meth_c_choose_13(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_13 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_13.setPageContext(_jspx_page_context);
_jspx_th_c_choose_13.setParent(null);
int _jspx_eval_c_choose_13 = _jspx_th_c_choose_13.doStartTag();
if (_jspx_eval_c_choose_13 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_27((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_13, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_28((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_13, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_12((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_13, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_13.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_13.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_13);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_13);
return false;
}
private boolean _jspx_meth_c_when_27(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_13, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_27 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_27.setPageContext(_jspx_page_context);
_jspx_th_c_when_27.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_13);
_jspx_th_c_when_27.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'edit'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_27 = _jspx_th_c_when_27.doStartTag();
if (_jspx_eval_c_when_27 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" name=\"nmcroqui\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nmCroqui}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" placeholder=\"nº croqui\" required=\"required\" >\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_27.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_27.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_27);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_27);
return false;
}
private boolean _jspx_meth_c_when_28(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_13, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_28 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_28.setPageContext(_jspx_page_context);
_jspx_th_c_when_28.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_13);
_jspx_th_c_when_28.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_28 = _jspx_th_c_when_28.doStartTag();
if (_jspx_eval_c_when_28 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" name=\"nmcroqui\" placeholder=\"nº croqui\" >\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_28.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_28.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_28);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_28);
return false;
}
private boolean _jspx_meth_c_otherwise_12(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_13, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_12 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_12.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_12.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_13);
int _jspx_eval_c_otherwise_12 = _jspx_th_c_otherwise_12.doStartTag();
if (_jspx_eval_c_otherwise_12 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nmCroqui}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_12.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_12.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_12);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_12);
return false;
}
private boolean _jspx_meth_c_choose_14(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_14 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_14.setPageContext(_jspx_page_context);
_jspx_th_c_choose_14.setParent(null);
int _jspx_eval_c_choose_14 = _jspx_th_c_choose_14.doStartTag();
if (_jspx_eval_c_choose_14 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_29((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_14, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_30((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_14, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_13((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_14, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_14.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_14.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_14);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_14);
return false;
}
private boolean _jspx_meth_c_when_29(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_14, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_29 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_29.setPageContext(_jspx_page_context);
_jspx_th_c_when_29.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_14);
_jspx_th_c_when_29.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'edit'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_29 = _jspx_th_c_when_29.doStartTag();
if (_jspx_eval_c_when_29 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" name=\"nrarea\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nrArea}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" placeholder=\"\" required=\"required\" >\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_29.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_29.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_29);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_29);
return false;
}
private boolean _jspx_meth_c_when_30(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_14, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_30 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_30.setPageContext(_jspx_page_context);
_jspx_th_c_when_30.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_14);
_jspx_th_c_when_30.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_30 = _jspx_th_c_when_30.doStartTag();
if (_jspx_eval_c_when_30 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" name=\"nrarea\" placeholder=\"\" required=\"required\">\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_30.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_30.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_30);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_30);
return false;
}
private boolean _jspx_meth_c_otherwise_13(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_14, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_13 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_13.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_13.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_14);
int _jspx_eval_c_otherwise_13 = _jspx_th_c_otherwise_13.doStartTag();
if (_jspx_eval_c_otherwise_13 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nrArea}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_13.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_13.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_13);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_13);
return false;
}
private boolean _jspx_meth_c_choose_15(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_15 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_15.setPageContext(_jspx_page_context);
_jspx_th_c_choose_15.setParent(null);
int _jspx_eval_c_choose_15 = _jspx_th_c_choose_15.doStartTag();
if (_jspx_eval_c_choose_15 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_31((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_15, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_32((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_15, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_14((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_15, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_15.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_15.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_15);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_15);
return false;
}
private boolean _jspx_meth_c_when_31(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_15, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_31 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_31.setPageContext(_jspx_page_context);
_jspx_th_c_when_31.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_15);
_jspx_th_c_when_31.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'edit'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_31 = _jspx_th_c_when_31.doStartTag();
if (_jspx_eval_c_when_31 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" name=\"nrsetor\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nrSetor}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" placeholder=\"nº do setor²\" required=\"required\" >\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_31.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_31.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_31);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_31);
return false;
}
private boolean _jspx_meth_c_when_32(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_15, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_32 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_32.setPageContext(_jspx_page_context);
_jspx_th_c_when_32.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_15);
_jspx_th_c_when_32.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_32 = _jspx_th_c_when_32.doStartTag();
if (_jspx_eval_c_when_32 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" name=\"nrsetor\" placeholder=\"nº do setor\" required=\"required\" >\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_32.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_32.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_32);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_32);
return false;
}
private boolean _jspx_meth_c_otherwise_14(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_15, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_14 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_14.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_14.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_15);
int _jspx_eval_c_otherwise_14 = _jspx_th_c_otherwise_14.doStartTag();
if (_jspx_eval_c_otherwise_14 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nrSetor}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_14.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_14.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_14);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_14);
return false;
}
private boolean _jspx_meth_c_choose_16(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_16 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_16.setPageContext(_jspx_page_context);
_jspx_th_c_choose_16.setParent(null);
int _jspx_eval_c_choose_16 = _jspx_th_c_choose_16.doStartTag();
if (_jspx_eval_c_choose_16 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_33((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_16, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_34((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_16, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_15((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_16, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_16.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_16.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_16);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_16);
return false;
}
private boolean _jspx_meth_c_when_33(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_16, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_33 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_33.setPageContext(_jspx_page_context);
_jspx_th_c_when_33.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_16);
_jspx_th_c_when_33.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'edit'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_33 = _jspx_th_c_when_33.doStartTag();
if (_jspx_eval_c_when_33 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" name=\"nrquadra\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nrQuadra}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" placeholder=\"nº da quadra\" required=\"required\">\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_33.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_33.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_33);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_33);
return false;
}
private boolean _jspx_meth_c_when_34(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_16, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_34 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_34.setPageContext(_jspx_page_context);
_jspx_th_c_when_34.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_16);
_jspx_th_c_when_34.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_34 = _jspx_th_c_when_34.doStartTag();
if (_jspx_eval_c_when_34 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" name=\"nrquadra\" placeholder=\"nº da quadra\" required=\"required\">\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_34.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_34.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_34);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_34);
return false;
}
private boolean _jspx_meth_c_otherwise_15(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_16, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_15 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_15.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_15.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_16);
int _jspx_eval_c_otherwise_15 = _jspx_th_c_otherwise_15.doStartTag();
if (_jspx_eval_c_otherwise_15 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nrQuadra}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_15.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_15.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_15);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_15);
return false;
}
private boolean _jspx_meth_c_choose_17(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_17 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_17.setPageContext(_jspx_page_context);
_jspx_th_c_choose_17.setParent(null);
int _jspx_eval_c_choose_17 = _jspx_th_c_choose_17.doStartTag();
if (_jspx_eval_c_choose_17 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_35((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_17, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_36((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_17, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_16((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_17, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_17.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_17.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_17);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_17);
return false;
}
private boolean _jspx_meth_c_when_35(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_17, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_35 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_35.setPageContext(_jspx_page_context);
_jspx_th_c_when_35.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_17);
_jspx_th_c_when_35.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'edit'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_35 = _jspx_th_c_when_35.doStartTag();
if (_jspx_eval_c_when_35 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" name=\"nrlote\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nrLote}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" placeholder=\"nº do lote\" required=\"required\">\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_35.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_35.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_35);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_35);
return false;
}
private boolean _jspx_meth_c_when_36(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_17, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_36 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_36.setPageContext(_jspx_page_context);
_jspx_th_c_when_36.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_17);
_jspx_th_c_when_36.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_36 = _jspx_th_c_when_36.doStartTag();
if (_jspx_eval_c_when_36 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" name=\"nrlote\" placeholder=\"nº do lote\" required=\"required\">\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_36.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_36.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_36);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_36);
return false;
}
private boolean _jspx_meth_c_otherwise_16(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_17, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_16 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_16.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_16.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_17);
int _jspx_eval_c_otherwise_16 = _jspx_th_c_otherwise_16.doStartTag();
if (_jspx_eval_c_otherwise_16 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nrLote}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_16.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_16.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_16);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_16);
return false;
}
private boolean _jspx_meth_c_choose_18(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_18 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_18.setPageContext(_jspx_page_context);
_jspx_th_c_choose_18.setParent(null);
int _jspx_eval_c_choose_18 = _jspx_th_c_choose_18.doStartTag();
if (_jspx_eval_c_choose_18 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_37((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_18, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_38((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_18, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_17((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_18, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_18.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_18.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_18);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_18);
return false;
}
private boolean _jspx_meth_c_when_37(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_18, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_37 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_37.setPageContext(_jspx_page_context);
_jspx_th_c_when_37.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_18);
_jspx_th_c_when_37.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'edit'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_37 = _jspx_th_c_when_37.doStartTag();
if (_jspx_eval_c_when_37 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" name=\"nmcap\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nrCap}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" placeholder=\"nº do cap\" required=\"required\">\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_37.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_37.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_37);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_37);
return false;
}
private boolean _jspx_meth_c_when_38(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_18, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_38 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_38.setPageContext(_jspx_page_context);
_jspx_th_c_when_38.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_18);
_jspx_th_c_when_38.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_38 = _jspx_th_c_when_38.doStartTag();
if (_jspx_eval_c_when_38 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" name=\"nmcap\" placeholder=\"nº do cap\" required=\"required\">\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_38.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_38.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_38);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_38);
return false;
}
private boolean _jspx_meth_c_otherwise_17(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_18, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_17 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_17.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_17.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_18);
int _jspx_eval_c_otherwise_17 = _jspx_th_c_otherwise_17.doStartTag();
if (_jspx_eval_c_otherwise_17 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nrCap}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_17.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_17.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_17);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_17);
return false;
}
private boolean _jspx_meth_c_choose_19(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_19 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_19.setPageContext(_jspx_page_context);
_jspx_th_c_choose_19.setParent(null);
int _jspx_eval_c_choose_19 = _jspx_th_c_choose_19.doStartTag();
if (_jspx_eval_c_choose_19 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_39((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_19, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_40((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_19, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_18((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_19, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_19.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_19.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_19);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_19);
return false;
}
private boolean _jspx_meth_c_when_39(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_19, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_39 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_39.setPageContext(_jspx_page_context);
_jspx_th_c_when_39.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_19);
_jspx_th_c_when_39.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'edit'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_39 = _jspx_th_c_when_39.doStartTag();
if (_jspx_eval_c_when_39 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" name=\"nmMetragemOficial\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nmMetragem}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" placeholder=\"Área m²\" required=\"required\">\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_39.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_39.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_39);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_39);
return false;
}
private boolean _jspx_meth_c_when_40(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_19, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_40 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_40.setPageContext(_jspx_page_context);
_jspx_th_c_when_40.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_19);
_jspx_th_c_when_40.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_40 = _jspx_th_c_when_40.doStartTag();
if (_jspx_eval_c_when_40 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" name=\"nmMetragemOficial\" placeholder=\"Área m²\" required=\"required\">\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_40.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_40.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_40);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_40);
return false;
}
private boolean _jspx_meth_c_otherwise_18(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_19, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_18 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_18.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_18.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_19);
int _jspx_eval_c_otherwise_18 = _jspx_th_c_otherwise_18.doStartTag();
if (_jspx_eval_c_otherwise_18 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nmMetragem}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_18.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_18.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_18);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_18);
return false;
}
private boolean _jspx_meth_c_choose_20(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_20 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_20.setPageContext(_jspx_page_context);
_jspx_th_c_choose_20.setParent(null);
int _jspx_eval_c_choose_20 = _jspx_th_c_choose_20.doStartTag();
if (_jspx_eval_c_choose_20 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_41((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_20, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_42((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_20, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_19((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_20, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_20.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_20.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_20);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_20);
return false;
}
private boolean _jspx_meth_c_when_41(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_20, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_41 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_41.setPageContext(_jspx_page_context);
_jspx_th_c_when_41.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_20);
_jspx_th_c_when_41.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'edit'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_41 = _jspx_th_c_when_41.doStartTag();
if (_jspx_eval_c_when_41 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <select class=\"col-md-12 col-xs-12\" name=\"pkSubPref\" id=\"\" required=\"required\">\n");
out.write(" <option value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${selSubPref.pkSubPrefeitura}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" title=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${selSubPref.nmSubPrefeitura}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write('"');
out.write('>');
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${selSubPref.nmSubPrefeitura}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</option>\n");
out.write(" <option></option> \n");
out.write(" ");
if (_jspx_meth_c_forEach_10((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_41, _jspx_page_context))
return true;
out.write("\n");
out.write(" </select>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_41.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_41.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_41);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_41);
return false;
}
private boolean _jspx_meth_c_forEach_10(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_41, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:forEach
org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_forEach_10 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _jspx_tagPool_c_forEach_var_items.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class);
_jspx_th_c_forEach_10.setPageContext(_jspx_page_context);
_jspx_th_c_forEach_10.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_41);
_jspx_th_c_forEach_10.setVar("subPref");
_jspx_th_c_forEach_10.setItems((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${subPref.listSelectSubPref()}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int[] _jspx_push_body_count_c_forEach_10 = new int[] { 0 };
try {
int _jspx_eval_c_forEach_10 = _jspx_th_c_forEach_10.doStartTag();
if (_jspx_eval_c_forEach_10 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <option value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${subPref.pkSubPrefeitura}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" title=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${subPref.nmSubPrefeitura}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write('"');
out.write('>');
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${subPref.nmSubPrefeitura}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</option> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_forEach_10.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_forEach_10.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_c_forEach_10[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_c_forEach_10.doCatch(_jspx_exception);
} finally {
_jspx_th_c_forEach_10.doFinally();
_jspx_tagPool_c_forEach_var_items.reuse(_jspx_th_c_forEach_10);
}
return false;
}
private boolean _jspx_meth_c_when_42(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_20, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_42 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_42.setPageContext(_jspx_page_context);
_jspx_th_c_when_42.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_20);
_jspx_th_c_when_42.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_42 = _jspx_th_c_when_42.doStartTag();
if (_jspx_eval_c_when_42 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <select class=\"col-md-12 col-xs-12\" name=\"pkSubPref\" id=\"\" required=\"required\">\n");
out.write(" <option></option> \n");
out.write(" ");
if (_jspx_meth_c_forEach_11((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_42, _jspx_page_context))
return true;
out.write("\n");
out.write(" </select>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_42.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_42.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_42);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_42);
return false;
}
private boolean _jspx_meth_c_forEach_11(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_42, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:forEach
org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_forEach_11 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _jspx_tagPool_c_forEach_var_items.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class);
_jspx_th_c_forEach_11.setPageContext(_jspx_page_context);
_jspx_th_c_forEach_11.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_42);
_jspx_th_c_forEach_11.setVar("subPref");
_jspx_th_c_forEach_11.setItems((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${subPref.listSelectSubPref()}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int[] _jspx_push_body_count_c_forEach_11 = new int[] { 0 };
try {
int _jspx_eval_c_forEach_11 = _jspx_th_c_forEach_11.doStartTag();
if (_jspx_eval_c_forEach_11 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <option value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${subPref.pkSubPrefeitura}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" title=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${subPref.nmSubPrefeitura}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write('"');
out.write('>');
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${subPref.nmSubPrefeitura}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</option> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_forEach_11.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_forEach_11.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_c_forEach_11[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_c_forEach_11.doCatch(_jspx_exception);
} finally {
_jspx_th_c_forEach_11.doFinally();
_jspx_tagPool_c_forEach_var_items.reuse(_jspx_th_c_forEach_11);
}
return false;
}
private boolean _jspx_meth_c_otherwise_19(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_20, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_19 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_19.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_19.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_20);
int _jspx_eval_c_otherwise_19 = _jspx_th_c_otherwise_19.doStartTag();
if (_jspx_eval_c_otherwise_19 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${selSubPref.nmSubPrefeitura}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_19.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_19.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_19);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_19);
return false;
}
private boolean _jspx_meth_c_choose_21(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_21 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_21.setPageContext(_jspx_page_context);
_jspx_th_c_choose_21.setParent(null);
int _jspx_eval_c_choose_21 = _jspx_th_c_choose_21.doStartTag();
if (_jspx_eval_c_choose_21 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_43((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_21, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_44((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_21, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_20((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_21, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_21.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_21.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_21);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_21);
return false;
}
private boolean _jspx_meth_c_when_43(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_21, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_43 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_43.setPageContext(_jspx_page_context);
_jspx_th_c_when_43.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_21);
_jspx_th_c_when_43.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'edit'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_43 = _jspx_th_c_when_43.doStartTag();
if (_jspx_eval_c_when_43 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <select class=\"col-md-12 col-xs-12\" name=\"tipoEndereco\" title=\"Rua / Avenida / Praça / etc\" required=\"required\">\n");
out.write(" <option value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nmTipoEndereco}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write('"');
out.write('>');
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nmTipoEndereco}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</option>\n");
out.write(" <option></option>\n");
out.write(" <option>ACESSO</option>\n");
out.write(" <option>ALAMEDA</option>\n");
out.write(" <option>AV. PROJETADA</option>\n");
out.write(" <option>AVENIDA</option>\n");
out.write(" <option>BALAO RETORNO</option>\n");
out.write(" <option>BECO</option>\n");
out.write(" <option>CAMINHO</option>\n");
out.write(" <option>CAMINHO PART</option>\n");
out.write(" <option>CAMINHO PEDEST</option>\n");
out.write(" <option>COMPLEXO VIARIO</option>\n");
out.write(" <option>DESVIO</option>\n");
out.write(" <option>DIV</option>\n");
out.write(" <option>ENT</option>\n");
out.write(" <option>ES. PROJETADA</option>\n");
out.write(" <option>ESC</option>\n");
out.write(" <option>ESPACO LIVRE</option>\n");
out.write(" <option>ESPLANADA</option>\n");
out.write(" <option>EST. DE RODAGEM</option>\n");
out.write(" <option>ESTACIONAMENTO</option>\n");
out.write(" <option>ESTR. DE FERRO</option>\n");
out.write(" <option>ESTRADA</option>\n");
out.write(" <option>ESTRADA PART</option>\n");
out.write(" <option>GALERIA</option>\n");
out.write(" <option>JARDIM</option>\n");
out.write(" <option>LADEIRA</option>\n");
out.write(" <option>LARGO</option>\n");
out.write(" <option>PARQUE</option>\n");
out.write(" <option>PASSAGEM</option>\n");
out.write(" <option>PASSAGEM PART</option>\n");
out.write(" <option>PASSARELA</option>\n");
out.write(" <option>PATIO</option>\n");
out.write(" <option>PONTE</option>\n");
out.write(" <option>PONTILHAO</option>\n");
out.write(" <option>PQE</option>\n");
out.write(" <option>PQL</option>\n");
out.write(" <option>PQM</option>\n");
out.write(" <option>PRACA</option>\n");
out.write(" <option>PRACA MANOBRA</option>\n");
out.write(" <option>PRACA PROJETADA</option>\n");
out.write(" <option>PRACA RETORNO</option>\n");
out.write(" <option>PRO</option>\n");
out.write(" <option>PS PROJETADA</option>\n");
out.write(" <option>PS. DE PEDESTRE</option>\n");
out.write(" <option>PS. SUBTERRANEA</option>\n");
out.write(" <option>RODOVIA</option>\n");
out.write(" <option>RUA</option>\n");
out.write(" <option>RUA PART</option>\n");
out.write(" <option>RUA PROJETADA</option>\n");
out.write(" <option>SERVIDAO</option>\n");
out.write(" <option>TRAVESSA</option>\n");
out.write(" <option>TRAVESSA PART</option>\n");
out.write(" <option>TUNEL</option>\n");
out.write(" <option>TV PROJETADA</option>\n");
out.write(" <option>VEREDA</option>\n");
out.write(" <option>VIA</option>\n");
out.write(" <option>VIA CIRC PEDEST</option>\n");
out.write(" <option>VIA DE PEDESTRE</option>\n");
out.write(" <option>VIA ELEVADA</option>\n");
out.write(" <option>VIADUTO</option>\n");
out.write(" <option>VIELA</option>\n");
out.write(" <option>VIELA PART</option>\n");
out.write(" <option>VIELA PROJETADA</option>\n");
out.write(" <option><NAME></option>\n");
out.write(" <option>VILA</option>\n");
out.write(" <option>VLP</option>\n");
out.write(" </select>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_43.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_43.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_43);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_43);
return false;
}
private boolean _jspx_meth_c_when_44(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_21, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_44 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_44.setPageContext(_jspx_page_context);
_jspx_th_c_when_44.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_21);
_jspx_th_c_when_44.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_44 = _jspx_th_c_when_44.doStartTag();
if (_jspx_eval_c_when_44 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <select class=\"col-md-12 col-xs-12\" name=\"tipoEndereco\" title=\"Rua / Avenida / Praça / etc\" required=\"required\">\n");
out.write(" <option></option>\n");
out.write(" <option>ACESSO</option>\n");
out.write(" <option>ALAMEDA</option>\n");
out.write(" <option>AV. PROJETADA</option>\n");
out.write(" <option>AVENIDA</option>\n");
out.write(" <option><NAME></option>\n");
out.write(" <option>BECO</option>\n");
out.write(" <option>CAMINHO</option>\n");
out.write(" <option>CAMINHO PART</option>\n");
out.write(" <option>CAMINHO PEDEST</option>\n");
out.write(" <option>COMPLEXO VIARIO</option>\n");
out.write(" <option>DESVIO</option>\n");
out.write(" <option>DIV</option>\n");
out.write(" <option>ENT</option>\n");
out.write(" <option>ES. PROJETADA</option>\n");
out.write(" <option>ESC</option>\n");
out.write(" <option>ESPACO LIVRE</option>\n");
out.write(" <option>ESPLANADA</option>\n");
out.write(" <option>EST. DE RODAGEM</option>\n");
out.write(" <option>ESTACIONAMENTO</option>\n");
out.write(" <option>ESTR. DE FERRO</option>\n");
out.write(" <option>ESTRADA</option>\n");
out.write(" <option>ESTRADA PART</option>\n");
out.write(" <option>GALERIA</option>\n");
out.write(" <option>JARDIM</option>\n");
out.write(" <option>LADEIRA</option>\n");
out.write(" <option>LARGO</option>\n");
out.write(" <option>PARQUE</option>\n");
out.write(" <option>PASSAGEM</option>\n");
out.write(" <option>PASSAGEM PART</option>\n");
out.write(" <option>PASSARELA</option>\n");
out.write(" <option>PATIO</option>\n");
out.write(" <option>PONTE</option>\n");
out.write(" <option>PONTILHAO</option>\n");
out.write(" <option>PQE</option>\n");
out.write(" <option>PQL</option>\n");
out.write(" <option>PQM</option>\n");
out.write(" <option>PRACA</option>\n");
out.write(" <option>PRACA MANOBRA</option>\n");
out.write(" <option>PRACA PROJETADA</option>\n");
out.write(" <option>PRACA RETORNO</option>\n");
out.write(" <option>PRO</option>\n");
out.write(" <option>PS PROJETADA</option>\n");
out.write(" <option>PS. DE PEDESTRE</option>\n");
out.write(" <option>PS. SUBTERRANEA</option>\n");
out.write(" <option>RODOVIA</option>\n");
out.write(" <option>RUA</option>\n");
out.write(" <option>RUA PART</option>\n");
out.write(" <option>RUA PROJETADA</option>\n");
out.write(" <option>SERVIDAO</option>\n");
out.write(" <option>TRAVESSA</option>\n");
out.write(" <option>TRAVESSA PART</option>\n");
out.write(" <option>TUNEL</option>\n");
out.write(" <option>TV PROJETADA</option>\n");
out.write(" <option>VEREDA</option>\n");
out.write(" <option>VIA</option>\n");
out.write(" <option>VIA CIRC PEDEST</option>\n");
out.write(" <option>VIA DE PEDESTRE</option>\n");
out.write(" <option>VIA ELEVADA</option>\n");
out.write(" <option>VIADUTO</option>\n");
out.write(" <option>VIELA</option>\n");
out.write(" <option>VIELA PART</option>\n");
out.write(" <option>VIELA PROJETADA</option>\n");
out.write(" <option>VIELA SANITARIA</option>\n");
out.write(" <option>VILA</option>\n");
out.write(" <option>VLP</option>\n");
out.write(" </select>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_44.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_44.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_44);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_44);
return false;
}
private boolean _jspx_meth_c_otherwise_20(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_21, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_20 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_20.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_20.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_21);
int _jspx_eval_c_otherwise_20 = _jspx_th_c_otherwise_20.doStartTag();
if (_jspx_eval_c_otherwise_20 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nmTipoEndereco}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_20.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_20.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_20);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_20);
return false;
}
private boolean _jspx_meth_c_choose_22(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_22 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_22.setPageContext(_jspx_page_context);
_jspx_th_c_choose_22.setParent(null);
int _jspx_eval_c_choose_22 = _jspx_th_c_choose_22.doStartTag();
if (_jspx_eval_c_choose_22 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_45((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_22, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_46((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_22, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_21((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_22, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_22.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_22.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_22);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_22);
return false;
}
private boolean _jspx_meth_c_when_45(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_22, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_45 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_45.setPageContext(_jspx_page_context);
_jspx_th_c_when_45.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_22);
_jspx_th_c_when_45.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'edit'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_45 = _jspx_th_c_when_45.doStartTag();
if (_jspx_eval_c_when_45 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <select class=\"col-md-12 col-xs-12\" name=\"tituloEndereco\" title=\"Capitão / Doutor / Dom / etc\">\n");
out.write(" <option>");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nmTituloEndereco}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</option>\n");
out.write(" <option></option>\n");
out.write(" <option>ABADE</option>\n");
out.write(" <option>ACADEMICO</option>\n");
out.write(" <option>ADVOGADO</option>\n");
out.write(" <option>AGENTE</option>\n");
out.write(" <option>AGRIC</option>\n");
out.write(" <option>AGRIMENSOR</option>\n");
out.write(" <option>AJUDANTE</option>\n");
out.write(" <option>ALFERES</option>\n");
out.write(" <option>ALMIRANTE</option>\n");
out.write(" <option>APOSTOLO</option>\n");
out.write(" <option>ARCEBISPO</option>\n");
out.write(" <option>ARCIP</option>\n");
out.write(" <option>ARCJO</option>\n");
out.write(" <option>ARQUITETA</option>\n");
out.write(" <option>ARQUITETO</option>\n");
out.write(" <option>ARQUITETO PROFESSOR</option>\n");
out.write(" <option>ASPIRANTE</option>\n");
out.write(" <option>AVENIDA</option>\n");
out.write(" <option>AVIADOR</option>\n");
out.write(" <option>AVIADORA</option>\n");
out.write(" <option>BACHAREL</option>\n");
out.write(" <option>BANDEIRANTE</option>\n");
out.write(" <option>BANQUEIRO</option>\n");
out.write(" <option>BARAO</option>\n");
out.write(" <option>BARONESA</option>\n");
out.write(" <option>BEATO PADRE</option>\n");
out.write(" <option>BEM AVENTURADO</option>\n");
out.write(" <option>BENEMERITO</option>\n");
out.write(" <option>BISPO</option>\n");
out.write(" <option>BRIGADEIRO</option>\n");
out.write(" <option>CABO</option>\n");
out.write(" <option>CABO PM</option>\n");
out.write(" <option>CADETE</option>\n");
out.write(" <option>CAMPEADOR</option>\n");
out.write(" <option>CAPITAO</option>\n");
out.write(" <option>CAPITAO ALMIRANTE</option>\n");
out.write(" <option>CAPITAO DE FRAGATA</option>\n");
out.write(" <option>CAPITAO DE MAR E GUERRA</option>\n");
out.write(" <option>CAPITAO GENERAL</option>\n");
out.write(" <option>CAPITAO MOR</option>\n");
out.write(" <option>CAPITAO PM</option>\n");
out.write(" <option>CAPITAO TENENTE</option>\n");
out.write(" <option>CAR</option>\n");
out.write(" <option>CARDEAL</option>\n");
out.write(" <option>CATEQUISTA</option>\n");
out.write(" <option>CAVALEIRO</option>\n");
out.write(" <option>CAVALHEIRO</option>\n");
out.write(" <option>CINEASTA</option>\n");
out.write(" <option>COMANDANTE</option>\n");
out.write(" <option>COMEDIANTE</option>\n");
out.write(" <option>COMENDADOR</option>\n");
out.write(" <option>COMISSARIA</option>\n");
out.write(" <option>COMISSARIO</option>\n");
out.write(" <option>COMPOSITOR</option>\n");
out.write(" <option>CONDE</option>\n");
out.write(" <option>CONDESSA</option>\n");
out.write(" <option>CONEGO</option>\n");
out.write(" <option>CONFRADE</option>\n");
out.write(" <option>CONSELHEIRO</option>\n");
out.write(" <option>CONSUL</option>\n");
out.write(" <option>CORONEL</option>\n");
out.write(" <option>CORONEL PM</option>\n");
out.write(" <option>CORREGEDOR</option>>\n");
out.write(" <option>DEPUTADA</option>\n");
out.write(" <option>DELEGADO</option>\n");
out.write(" <option>DENTISTA</option\n");
out.write(" <option>DEPUTADO</option>\n");
out.write(" <option>DEPUTADO DOUTOR</option>\n");
out.write(" <option>DESEMBARGADOR</option>\n");
out.write(" <option>DIACO</option>\n");
out.write(" <option>DOM</option>\n");
out.write(" <option>DONA</option>\n");
out.write(" <option>DOUTOR</option>\n");
out.write(" <option>DOUTORA</option>\n");
out.write(" <option>DUQUE</option>\n");
out.write(" <option>DUQUESA</option>\n");
out.write(" <option>EDITOR</option>\n");
out.write(" <option>EDUCADOR</option>\n");
out.write(" <option>EDUCADORA</option>\n");
out.write(" <option>EMBAIXADOR</option>\n");
out.write(" <option>EMBAIXADORA</option>\n");
out.write(" <option>EMP</option>\n");
out.write(" <option>ENGENHEIRA</option>\n");
out.write(" <option>ENGENHEIRO</option>\n");
out.write(" <option>ESCOTEIRO</option>\n");
out.write(" <option>ESCRAVO</option>\n");
out.write(" <option>ESCRITOR</option>\n");
out.write(" <option>EXPEDICIONARIO</option>\n");
out.write(" <option>FISICO</option>\n");
out.write(" <option>FREI</option>\n");
out.write(" <option>GENERAL</option>\n");
out.write(" <option>GOVERNADOR</option>\n");
out.write(" <option>GRUMETE</option>\n");
out.write(" <option>GUARDA CIVIL METROPOLITANO</option>\n");
out.write(" <option>IMACULADA</option>\n");
out.write(" <option>IMPERADOR</option>\n");
out.write(" <option>IMPERATRIZ</option>\n");
out.write(" <option>INFANTE</option>\n");
out.write(" <option>INSPETOR</option>\n");
out.write(" <option>IRMA</option>\n");
out.write(" <option>IRMAO</option>\n");
out.write(" <option>IRMAOS</option>\n");
out.write(" <option>IRMAS</option>\n");
out.write(" <option>JORNALISTA</option>\n");
out.write(" <option>LIBERTADOR</option>\n");
out.write(" <option>LIDCO</option>\n");
out.write(" <option>LIVREIRO</option>\n");
out.write(" <option>LORDE</option>\n");
out.write(" <option>MADAME</option>\n");
out.write(" <option>MADRE</option>\n");
out.write(" <option>MAESTRO</option>\n");
out.write(" <option>MAJOR</option>\n");
out.write(" <option>MAJOR AVIADOR</option>\n");
out.write(" <option>MAJOR BRIGADEIRO</option>\n");
out.write(" <option>MAQUINISTA</option>\n");
out.write(" <option>MARECHAL</option>\n");
out.write(" <option>MARECHAL DO AR</option>\n");
out.write(" <option>MARQUES</option>\n");
out.write(" <option>MARQUESA</option>\n");
out.write(" <option>MERE</option>\n");
out.write(" <option>MESTRAS</option>\n");
out.write(" <option>MESTRE</option>\n");
out.write(" <option>MESTRES</option>\n");
out.write(" <option>MILITANTE</option>\n");
out.write(" <option>MINISTRO</option>\n");
out.write(" <option>MISSIONARIA</option>\n");
out.write(" <option>MISSIONARIO</option>\n");
out.write(" <option>MONGE</option>\n");
out.write(" <option>MONSENHOR</option>\n");
out.write(" <option>MUNIC</option>\n");
out.write(" <option>MUSICO</option>\n");
out.write(" <option>NOSSA SENHORA</option>\n");
out.write(" <option>NOSSO SENHOR</option>\n");
out.write(" <option>OUVIDOR</option>\n");
out.write(" <option>PADRE</option>\n");
out.write(" <option>PADRES</option>\n");
out.write(" <option>PAI</option>\n");
out.write(" <option>PAPA</option>\n");
out.write(" <option>PASTOR</option>\n");
out.write(" <option>PATRIARCA</option>\n");
out.write(" <option>POETA</option>\n");
out.write(" <option>POETISA</option>\n");
out.write(" <option>PREFEITO</option>\n");
out.write(" <option>PRESIDENTE</option>\n");
out.write(" <option>PRESIDENTE DA ACAD.BRAS.LETRAS</option>\n");
out.write(" <option>PREVR</option>\n");
out.write(" <option>PRIMEIRO SARGENTO</option>\n");
out.write(" <option>PRIMEIRO SARGENTO PM</option>\n");
out.write(" <option>PRIMEIRO TENENTE</option>\n");
out.write(" <option>PRIMEIRO TENENTE PM</option>\n");
out.write(" <option>PRINCESA</option>\n");
out.write(" <option>PRINCIPE</option>\n");
out.write(" <option>PROCURADOR</option>\n");
out.write(" <option>PROFESSOR</option>\n");
out.write(" <option>PROFESSOR DOUTOR</option>\n");
out.write(" <option>PROFESSOR ENGENHEIRO</option>\n");
out.write(" <option>PROFESSORA</option>\n");
out.write(" <option>PROFETA</option>\n");
out.write(" <option>PROMOTOR</option>\n");
out.write(" <option>PROVEDOR</option>\n");
out.write(" <option>PROVEDOR MOR</option>\n");
out.write(" <option>RABINO</option>\n");
out.write(" <option>RADIALISTA</option>\n");
out.write(" <option>RAINHA</option>\n");
out.write(" <option>REGENTE</option>\n");
out.write(" <option>REI</option>\n");
out.write(" <option>REVERENDO</option>\n");
out.write(" <option>RUA</option>\n");
out.write(" <option>SACERDOTE</option>\n");
out.write(" <option>SANTA</option>\n");
out.write(" <option>SANTO</option>\n");
out.write(" <option>SAO</option>\n");
out.write(" <option>SARGENTO</option>\n");
out.write(" <option>SARGENTO MOR</option>\n");
out.write(" <option>SARGENTO PM</option>\n");
out.write(" <option>SEGUNDO SARGENTO</option>\n");
out.write(" <option>SEGUNDO SARGENTO PM</option>\n");
out.write(" <option>SEGUNDO TENENTE</option>\n");
out.write(" <option>SENADOR</option>\n");
out.write(" <option>SENHOR</option>\n");
out.write(" <option>SENHORA</option>\n");
out.write(" <option>SERTANISTA</option>\n");
out.write(" <option>SINHA</option>\n");
out.write(" <option>SIR</option>\n");
out.write(" <option>SOCIOLOGO</option>\n");
out.write(" <option>SOLDADO</option>\n");
out.write(" <option>SOLDADO PM</option>\n");
out.write(" <option>SOROR</option>\n");
out.write(" <option>SUB TENENTE</option>\n");
out.write(" <option>TENENTE</option>\n");
out.write(" <option>TENENTE AVIADOR</option>\n");
out.write(" <option>TENENTE BRIGADEIRO</option>\n");
out.write(" <option>TENENTE CORONEL</option>\n");
out.write(" <option>TENENTE CORONEL PM</option>\n");
out.write(" <option>TEOLOGO</option>\n");
out.write(" <option>TERCEIRO SARGENTO</option>\n");
out.write(" <option>TERCEIRO SARGENTO PM</option>\n");
out.write(" <option>TIA</option>\n");
out.write(" <option>VEREADOR</option>\n");
out.write(" <option>VICE ALMIRANTE</option>\n");
out.write(" <option>VICE REI</option>\n");
out.write(" <option>VIGARIO</option>\n");
out.write(" <option>VISCONDE</option>\n");
out.write(" <option>VISCONDESSA</option>\n");
out.write(" <option>VOLUNTARIO</option>\n");
out.write(" </select>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_45.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_45.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_45);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_45);
return false;
}
private boolean _jspx_meth_c_when_46(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_22, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_46 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_46.setPageContext(_jspx_page_context);
_jspx_th_c_when_46.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_22);
_jspx_th_c_when_46.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_46 = _jspx_th_c_when_46.doStartTag();
if (_jspx_eval_c_when_46 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <select class=\"col-md-12 col-xs-12\" name=\"tituloEndereco\" title=\"Capitão / Doutor / Dom / etc\">\n");
out.write(" <option></option>\n");
out.write(" <option>ABADE</option>\n");
out.write(" <option>ACADEMICO</option>\n");
out.write(" <option>ADVOGADO</option>\n");
out.write(" <option>AGENTE</option>\n");
out.write(" <option>AGRIC</option>\n");
out.write(" <option>AGRIMENSOR</option>\n");
out.write(" <option>AJUDANTE</option>\n");
out.write(" <option>ALFERES</option>\n");
out.write(" <option>ALMIRANTE</option>\n");
out.write(" <option>APOSTOLO</option>\n");
out.write(" <option>ARCEBISPO</option>\n");
out.write(" <option>ARCIP</option>\n");
out.write(" <option>ARCJO</option>\n");
out.write(" <option>ARQUITETA</option>\n");
out.write(" <option>ARQUITETO</option>\n");
out.write(" <option>ARQUITETO PROFESSOR</option>\n");
out.write(" <option>ASPIRANTE</option>\n");
out.write(" <option>AVENIDA</option>\n");
out.write(" <option>AVIADOR</option>\n");
out.write(" <option>AVIADORA</option>\n");
out.write(" <option>BACHAREL</option>\n");
out.write(" <option>BANDEIRANTE</option>\n");
out.write(" <option>BANQUEIRO</option>\n");
out.write(" <option>BARAO</option>\n");
out.write(" <option>BARONESA</option>\n");
out.write(" <option>BEATO PADRE</option>\n");
out.write(" <option>BEM AVENTURADO</option>\n");
out.write(" <option>BENEMERITO</option>\n");
out.write(" <option>BISPO</option>\n");
out.write(" <option>BRIGADEIRO</option>\n");
out.write(" <option>CABO</option>\n");
out.write(" <option>CABO PM</option>\n");
out.write(" <option>CADETE</option>\n");
out.write(" <option>CAMPEADOR</option>\n");
out.write(" <option>CAPITAO</option>\n");
out.write(" <option>CAPITAO ALMIRANTE</option>\n");
out.write(" <option>CAPITAO DE FRAGATA</option>\n");
out.write(" <option>CAPITAO DE MAR E GUERRA</option>\n");
out.write(" <option>CAPITAO GENERAL</option>\n");
out.write(" <option>CAPITAO MOR</option>\n");
out.write(" <option>CAPITAO PM</option>\n");
out.write(" <option>CAPITAO TENENTE</option>\n");
out.write(" <option>CAR</option>\n");
out.write(" <option>CARDEAL</option>\n");
out.write(" <option>CATEQUISTA</option>\n");
out.write(" <option>CAVALEIRO</option>\n");
out.write(" <option>CAVALHEIRO</option>\n");
out.write(" <option>CINEASTA</option>\n");
out.write(" <option>COMANDANTE</option>\n");
out.write(" <option>COMEDIANTE</option>\n");
out.write(" <option>COMENDADOR</option>\n");
out.write(" <option>COMISSARIA</option>\n");
out.write(" <option>COMISSARIO</option>\n");
out.write(" <option>COMPOSITOR</option>\n");
out.write(" <option>CONDE</option>\n");
out.write(" <option>CONDESSA</option>\n");
out.write(" <option>CONEGO</option>\n");
out.write(" <option>CONFRADE</option>\n");
out.write(" <option>CONSELHEIRO</option>\n");
out.write(" <option>CONSUL</option>\n");
out.write(" <option>CORONEL</option>\n");
out.write(" <option>CORONEL PM</option>\n");
out.write(" <option>CORREGEDOR</option>>\n");
out.write(" <option>DEPUTADA</option>\n");
out.write(" <option>DELEGADO</option>\n");
out.write(" <option>DENTISTA</option\n");
out.write(" <option>DEPUTADO</option>\n");
out.write(" <option>DEPUTADO DOUTOR</option>\n");
out.write(" <option>DESEMBARGADOR</option>\n");
out.write(" <option>DIACO</option>\n");
out.write(" <option>DOM</option>\n");
out.write(" <option>DONA</option>\n");
out.write(" <option>DOUTOR</option>\n");
out.write(" <option>DOUTORA</option>\n");
out.write(" <option>DUQUE</option>\n");
out.write(" <option>DUQUESA</option>\n");
out.write(" <option>EDITOR</option>\n");
out.write(" <option>EDUCADOR</option>\n");
out.write(" <option>EDUCADORA</option>\n");
out.write(" <option>EMBAIXADOR</option>\n");
out.write(" <option>EMBAIXADORA</option>\n");
out.write(" <option>EMP</option>\n");
out.write(" <option>ENGENHEIRA</option>\n");
out.write(" <option>ENGENHEIRO</option>\n");
out.write(" <option>ESCOTEIRO</option>\n");
out.write(" <option>ESCRAVO</option>\n");
out.write(" <option>ESCRITOR</option>\n");
out.write(" <option>EXPEDICIONARIO</option>\n");
out.write(" <option>FISICO</option>\n");
out.write(" <option>FREI</option>\n");
out.write(" <option>GENERAL</option>\n");
out.write(" <option>GOVERNADOR</option>\n");
out.write(" <option>GRUMETE</option>\n");
out.write(" <option>GUARDA CIVIL METROPOLITANO</option>\n");
out.write(" <option>IMACULADA</option>\n");
out.write(" <option>IMPERADOR</option>\n");
out.write(" <option>IMPERATRIZ</option>\n");
out.write(" <option>INFANTE</option>\n");
out.write(" <option>INSPETOR</option>\n");
out.write(" <option>IRMA</option>\n");
out.write(" <option>IRMAO</option>\n");
out.write(" <option>IRMAOS</option>\n");
out.write(" <option>IRMAS</option>\n");
out.write(" <option>JORNALISTA</option>\n");
out.write(" <option>LIBERTADOR</option>\n");
out.write(" <option>LIDCO</option>\n");
out.write(" <option>LIVREIRO</option>\n");
out.write(" <option>LORDE</option>\n");
out.write(" <option>MADAME</option>\n");
out.write(" <option>MADRE</option>\n");
out.write(" <option>MAESTRO</option>\n");
out.write(" <option>MAJOR</option>\n");
out.write(" <option>MAJOR AVIADOR</option>\n");
out.write(" <option>MAJOR BRIGADEIRO</option>\n");
out.write(" <option>MAQUINISTA</option>\n");
out.write(" <option>MARECHAL</option>\n");
out.write(" <option>MARECHAL DO AR</option>\n");
out.write(" <option>MARQUES</option>\n");
out.write(" <option>MARQUESA</option>\n");
out.write(" <option>MERE</option>\n");
out.write(" <option>MESTRAS</option>\n");
out.write(" <option>MESTRE</option>\n");
out.write(" <option>MESTRES</option>\n");
out.write(" <option>MILITANTE</option>\n");
out.write(" <option>MINISTRO</option>\n");
out.write(" <option>MISSIONARIA</option>\n");
out.write(" <option>MISSIONARIO</option>\n");
out.write(" <option>MONGE</option>\n");
out.write(" <option>MONSENHOR</option>\n");
out.write(" <option>MUNIC</option>\n");
out.write(" <option>MUSICO</option>\n");
out.write(" <option>NOSSA SENHORA</option>\n");
out.write(" <option>NOSSO SENHOR</option>\n");
out.write(" <option>OUVIDOR</option>\n");
out.write(" <option>PADRE</option>\n");
out.write(" <option>PADRES</option>\n");
out.write(" <option>PAI</option>\n");
out.write(" <option>PAPA</option>\n");
out.write(" <option>PASTOR</option>\n");
out.write(" <option>PATRIARCA</option>\n");
out.write(" <option>POETA</option>\n");
out.write(" <option>POETISA</option>\n");
out.write(" <option>PREFEITO</option>\n");
out.write(" <option>PRESIDENTE</option>\n");
out.write(" <option>PRESIDENTE DA ACAD.BRAS.LETRAS</option>\n");
out.write(" <option>PREVR</option>\n");
out.write(" <option>PRIMEIRO SARGENTO</option>\n");
out.write(" <option>PRIMEIRO SARGENTO PM</option>\n");
out.write(" <option>PRIMEIRO TENENTE</option>\n");
out.write(" <option>PRIMEIRO TENENTE PM</option>\n");
out.write(" <option>PRINCESA</option>\n");
out.write(" <option>PRINCIPE</option>\n");
out.write(" <option>PROCURADOR</option>\n");
out.write(" <option>PROFESSOR</option>\n");
out.write(" <option>PROFESSOR DOUTOR</option>\n");
out.write(" <option>PROFESSOR ENGENHEIRO</option>\n");
out.write(" <option>PROFESSORA</option>\n");
out.write(" <option>PROFETA</option>\n");
out.write(" <option>PROMOTOR</option>\n");
out.write(" <option>PROVEDOR</option>\n");
out.write(" <option>PROVEDOR MOR</option>\n");
out.write(" <option>RABINO</option>\n");
out.write(" <option>RADIALISTA</option>\n");
out.write(" <option>RAINHA</option>\n");
out.write(" <option>REGENTE</option>\n");
out.write(" <option>REI</option>\n");
out.write(" <option>REVERENDO</option>\n");
out.write(" <option>RUA</option>\n");
out.write(" <option>SACERDOTE</option>\n");
out.write(" <option>SANTA</option>\n");
out.write(" <option>SANTO</option>\n");
out.write(" <option>SAO</option>\n");
out.write(" <option>SARGENTO</option>\n");
out.write(" <option>SARGENTO MOR</option>\n");
out.write(" <option>SARGENTO PM</option>\n");
out.write(" <option>SEGUNDO SARGENTO</option>\n");
out.write(" <option>SEGUNDO SARGENTO PM</option>\n");
out.write(" <option>SEGUNDO TENENTE</option>\n");
out.write(" <option>SENADOR</option>\n");
out.write(" <option>SENHOR</option>\n");
out.write(" <option>SENHORA</option>\n");
out.write(" <option>SERTANISTA</option>\n");
out.write(" <option>SINHA</option>\n");
out.write(" <option>SIR</option>\n");
out.write(" <option>SOCIOLOGO</option>\n");
out.write(" <option>SOLDADO</option>\n");
out.write(" <option>SOLDADO PM</option>\n");
out.write(" <option>SOROR</option>\n");
out.write(" <option>SUB TENENTE</option>\n");
out.write(" <option>TENENTE</option>\n");
out.write(" <option>TENENTE AVIADOR</option>\n");
out.write(" <option>TENENTE BRIGADEIRO</option>\n");
out.write(" <option>TENENTE CORONEL</option>\n");
out.write(" <option>TENENTE CORONEL PM</option>\n");
out.write(" <option>TEOLOGO</option>\n");
out.write(" <option>TERCEIRO SARGENTO</option>\n");
out.write(" <option>TERCEIRO SARGENTO PM</option>\n");
out.write(" <option>TIA</option>\n");
out.write(" <option>VEREADOR</option>\n");
out.write(" <option>VICE ALMIRANTE</option>\n");
out.write(" <option>VICE REI</option>\n");
out.write(" <option>VIGARIO</option>\n");
out.write(" <option>VISCONDE</option>\n");
out.write(" <option>VISCONDESSA</option>\n");
out.write(" <option>VOLUNTARIO</option>\n");
out.write(" </select>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_46.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_46.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_46);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_46);
return false;
}
private boolean _jspx_meth_c_otherwise_21(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_22, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_21 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_21.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_21.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_22);
int _jspx_eval_c_otherwise_21 = _jspx_th_c_otherwise_21.doStartTag();
if (_jspx_eval_c_otherwise_21 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nmTituloEndereco}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_21.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_21.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_21);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_21);
return false;
}
private boolean _jspx_meth_c_choose_23(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_23 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_23.setPageContext(_jspx_page_context);
_jspx_th_c_choose_23.setParent(null);
int _jspx_eval_c_choose_23 = _jspx_th_c_choose_23.doStartTag();
if (_jspx_eval_c_choose_23 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_47((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_23, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_48((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_23, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_22((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_23, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_23.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_23.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_23);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_23);
return false;
}
private boolean _jspx_meth_c_when_47(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_23, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_47 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_47.setPageContext(_jspx_page_context);
_jspx_th_c_when_47.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_23);
_jspx_th_c_when_47.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'edit'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_47 = _jspx_th_c_when_47.doStartTag();
if (_jspx_eval_c_when_47 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" name=\"nmendereco\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nmEndereco}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" placeholder=\"nome do endereço\" required=\"required\">\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_47.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_47.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_47);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_47);
return false;
}
private boolean _jspx_meth_c_when_48(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_23, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_48 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_48.setPageContext(_jspx_page_context);
_jspx_th_c_when_48.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_23);
_jspx_th_c_when_48.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_48 = _jspx_th_c_when_48.doStartTag();
if (_jspx_eval_c_when_48 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" name=\"nmendereco\" placeholder=\"nome do endereço\" required=\"required\">\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_48.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_48.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_48);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_48);
return false;
}
private boolean _jspx_meth_c_otherwise_22(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_23, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_22 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_22.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_22.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_23);
int _jspx_eval_c_otherwise_22 = _jspx_th_c_otherwise_22.doStartTag();
if (_jspx_eval_c_otherwise_22 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nmEndereco}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_22.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_22.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_22);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_22);
return false;
}
private boolean _jspx_meth_c_choose_24(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_24 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_24.setPageContext(_jspx_page_context);
_jspx_th_c_choose_24.setParent(null);
int _jspx_eval_c_choose_24 = _jspx_th_c_choose_24.doStartTag();
if (_jspx_eval_c_choose_24 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_49((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_24, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_50((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_24, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_23((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_24, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_24.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_24.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_24);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_24);
return false;
}
private boolean _jspx_meth_c_when_49(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_24, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_49 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_49.setPageContext(_jspx_page_context);
_jspx_th_c_when_49.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_24);
_jspx_th_c_when_49.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'edit'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_49 = _jspx_th_c_when_49.doStartTag();
if (_jspx_eval_c_when_49 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" name=\"nrnumeroend\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nrEndereco}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" placeholder=\"nº\">\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_49.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_49.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_49);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_49);
return false;
}
private boolean _jspx_meth_c_when_50(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_24, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_50 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_50.setPageContext(_jspx_page_context);
_jspx_th_c_when_50.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_24);
_jspx_th_c_when_50.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_50 = _jspx_th_c_when_50.doStartTag();
if (_jspx_eval_c_when_50 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" name=\"nrnumeroend\" placeholder=\"nº\">\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_50.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_50.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_50);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_50);
return false;
}
private boolean _jspx_meth_c_otherwise_23(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_24, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_23 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_23.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_23.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_24);
int _jspx_eval_c_otherwise_23 = _jspx_th_c_otherwise_23.doStartTag();
if (_jspx_eval_c_otherwise_23 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nrEndereco}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_23.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_23.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_23);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_23);
return false;
}
private boolean _jspx_meth_c_choose_25(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_25 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_25.setPageContext(_jspx_page_context);
_jspx_th_c_choose_25.setParent(null);
int _jspx_eval_c_choose_25 = _jspx_th_c_choose_25.doStartTag();
if (_jspx_eval_c_choose_25 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_51((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_25, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_52((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_25, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_24((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_25, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_25.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_25.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_25);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_25);
return false;
}
private boolean _jspx_meth_c_when_51(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_25, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_51 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_51.setPageContext(_jspx_page_context);
_jspx_th_c_when_51.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_25);
_jspx_th_c_when_51.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'edit'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_51 = _jspx_th_c_when_51.doStartTag();
if (_jspx_eval_c_when_51 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" name=\"nmcomplementoend\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nmComplementoEndereco}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" placeholder=\"complemento do endereço\" >\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_51.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_51.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_51);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_51);
return false;
}
private boolean _jspx_meth_c_when_52(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_25, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_52 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_52.setPageContext(_jspx_page_context);
_jspx_th_c_when_52.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_25);
_jspx_th_c_when_52.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_52 = _jspx_th_c_when_52.doStartTag();
if (_jspx_eval_c_when_52 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" name=\"nmcomplementoend\" placeholder=\"complemento do endereço\" >\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_52.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_52.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_52);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_52);
return false;
}
private boolean _jspx_meth_c_otherwise_24(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_25, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_24 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_24.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_24.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_25);
int _jspx_eval_c_otherwise_24 = _jspx_th_c_otherwise_24.doStartTag();
if (_jspx_eval_c_otherwise_24 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nmComplementoEndereco}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_24.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_24.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_24);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_24);
return false;
}
private boolean _jspx_meth_c_choose_26(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_26 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_26.setPageContext(_jspx_page_context);
_jspx_th_c_choose_26.setParent(null);
int _jspx_eval_c_choose_26 = _jspx_th_c_choose_26.doStartTag();
if (_jspx_eval_c_choose_26 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_53((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_26, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_54((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_26, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_25((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_26, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_26.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_26.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_26);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_26);
return false;
}
private boolean _jspx_meth_c_when_53(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_26, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_53 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_53.setPageContext(_jspx_page_context);
_jspx_th_c_when_53.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_26);
_jspx_th_c_when_53.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'edit'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_53 = _jspx_th_c_when_53.doStartTag();
if (_jspx_eval_c_when_53 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" name=\"nmreferenciaend\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nmReferencialEndereco}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" placeholder=\"referencia do endereço\" >\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_53.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_53.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_53);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_53);
return false;
}
private boolean _jspx_meth_c_when_54(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_26, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_54 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_54.setPageContext(_jspx_page_context);
_jspx_th_c_when_54.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_26);
_jspx_th_c_when_54.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_54 = _jspx_th_c_when_54.doStartTag();
if (_jspx_eval_c_when_54 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" name=\"nmreferenciaend\" placeholder=\"referencia do endereço\" >\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_54.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_54.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_54);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_54);
return false;
}
private boolean _jspx_meth_c_otherwise_25(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_26, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_25 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_25.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_25.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_26);
int _jspx_eval_c_otherwise_25 = _jspx_th_c_otherwise_25.doStartTag();
if (_jspx_eval_c_otherwise_25 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nmReferencialEndereco}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_25.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_25.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_25);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_25);
return false;
}
private boolean _jspx_meth_c_choose_27(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_27 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_27.setPageContext(_jspx_page_context);
_jspx_th_c_choose_27.setParent(null);
int _jspx_eval_c_choose_27 = _jspx_th_c_choose_27.doStartTag();
if (_jspx_eval_c_choose_27 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_55((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_27, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_57((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_27, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_28((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_27, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_27.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_27.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_27);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_27);
return false;
}
private boolean _jspx_meth_c_when_55(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_27, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_55 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_55.setPageContext(_jspx_page_context);
_jspx_th_c_when_55.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_27);
_jspx_th_c_when_55.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'edit'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_55 = _jspx_th_c_when_55.doStartTag();
if (_jspx_eval_c_when_55 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <div class=\"checkbox\">\n");
out.write(" ");
if (_jspx_meth_c_choose_28((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_55, _jspx_page_context))
return true;
out.write("\n");
out.write(" </div>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_55.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_55.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_55);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_55);
return false;
}
private boolean _jspx_meth_c_choose_28(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_55, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_28 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_28.setPageContext(_jspx_page_context);
_jspx_th_c_choose_28.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_55);
int _jspx_eval_c_choose_28 = _jspx_th_c_choose_28.doStartTag();
if (_jspx_eval_c_choose_28 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_56((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_28, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_26((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_28, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_28.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_28.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_28);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_28);
return false;
}
private boolean _jspx_meth_c_when_56(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_28, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_56 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_56.setPageContext(_jspx_page_context);
_jspx_th_c_when_56.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_28);
_jspx_th_c_when_56.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nrPrazo == 'Indeterminado'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_56 = _jspx_th_c_when_56.doStartTag();
if (_jspx_eval_c_when_56 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <label>\n");
out.write(" <input class=\"ace ace-switch ace-switch-6\" type=\"checkbox\" name=\"nmprazo\" checked value=\"Indeterminado\">\n");
out.write(" <span class=\"lbl\"> <label>Indeterminado</label></span>\n");
out.write(" </label>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_56.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_56.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_56);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_56);
return false;
}
private boolean _jspx_meth_c_otherwise_26(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_28, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_26 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_26.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_26.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_28);
int _jspx_eval_c_otherwise_26 = _jspx_th_c_otherwise_26.doStartTag();
if (_jspx_eval_c_otherwise_26 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <label>\n");
out.write(" <input class=\"ace ace-switch ace-switch-6\" type=\"checkbox\" name=\"nmprazo\" value=\"Indeterminado\">\n");
out.write(" <span class=\"lbl\"> <label>Indeterminado</label></span>\n");
out.write(" </label>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_26.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_26.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_26);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_26);
return false;
}
private boolean _jspx_meth_c_when_57(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_27, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_57 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_57.setPageContext(_jspx_page_context);
_jspx_th_c_when_57.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_27);
_jspx_th_c_when_57.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_57 = _jspx_th_c_when_57.doStartTag();
if (_jspx_eval_c_when_57 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <div class=\"checkbox\">\n");
out.write(" ");
if (_jspx_meth_c_choose_29((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_57, _jspx_page_context))
return true;
out.write("\n");
out.write(" </div>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_57.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_57.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_57);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_57);
return false;
}
private boolean _jspx_meth_c_choose_29(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_57, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_29 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_29.setPageContext(_jspx_page_context);
_jspx_th_c_choose_29.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_57);
int _jspx_eval_c_choose_29 = _jspx_th_c_choose_29.doStartTag();
if (_jspx_eval_c_choose_29 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_58((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_29, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_27((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_29, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_29.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_29.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_29);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_29);
return false;
}
private boolean _jspx_meth_c_when_58(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_29, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_58 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_58.setPageContext(_jspx_page_context);
_jspx_th_c_when_58.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_29);
_jspx_th_c_when_58.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nrPrazo == 'Indeterminado'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_58 = _jspx_th_c_when_58.doStartTag();
if (_jspx_eval_c_when_58 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <label>\n");
out.write(" <input class=\"ace ace-switch ace-switch-6\" type=\"checkbox\" name=\"nmprazo\" checked value=\"Indeterminado\">\n");
out.write(" <span class=\"lbl\"> <label>Indeterminado</label></span>\n");
out.write(" </label>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_58.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_58.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_58);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_58);
return false;
}
private boolean _jspx_meth_c_otherwise_27(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_29, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_27 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_27.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_27.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_29);
int _jspx_eval_c_otherwise_27 = _jspx_th_c_otherwise_27.doStartTag();
if (_jspx_eval_c_otherwise_27 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <label>\n");
out.write(" <input class=\"ace ace-switch ace-switch-6\" type=\"checkbox\" name=\"nmprazo\" value=\"Indeterminado\">\n");
out.write(" <span class=\"lbl\"> <label>Indeterminado</label></span>\n");
out.write(" </label>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_27.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_27.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_27);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_27);
return false;
}
private boolean _jspx_meth_c_otherwise_28(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_27, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_28 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_28.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_28.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_27);
int _jspx_eval_c_otherwise_28 = _jspx_th_c_otherwise_28.doStartTag();
if (_jspx_eval_c_otherwise_28 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nrPrazo}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write(" </span>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_28.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_28.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_28);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_28);
return false;
}
private boolean _jspx_meth_c_choose_30(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_30 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_30.setPageContext(_jspx_page_context);
_jspx_th_c_choose_30.setParent(null);
int _jspx_eval_c_choose_30 = _jspx_th_c_choose_30.doStartTag();
if (_jspx_eval_c_choose_30 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_59((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_30, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_60((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_30, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_30.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_30.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_30);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_30);
return false;
}
private boolean _jspx_meth_c_when_59(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_30, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_59 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_59.setPageContext(_jspx_page_context);
_jspx_th_c_when_59.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_30);
_jspx_th_c_when_59.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'edit'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_59 = _jspx_th_c_when_59.doStartTag();
if (_jspx_eval_c_when_59 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\">\n");
out.write(" <input type=\"number\" min=\"0\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" name=\"nrprazoAno\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nrPrazoAno}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" placeholder=\"\">\n");
out.write(" </label> \n");
out.write(" <label class=\"inline col-md-1 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Ano(s)</strong></span>\n");
out.write(" </label>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_59.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_59.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_59);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_59);
return false;
}
private boolean _jspx_meth_c_when_60(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_30, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_60 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_60.setPageContext(_jspx_page_context);
_jspx_th_c_when_60.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_30);
_jspx_th_c_when_60.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_60 = _jspx_th_c_when_60.doStartTag();
if (_jspx_eval_c_when_60 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\">\n");
out.write(" <input type=\"number\" min=\"0\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" name=\"nrprazoAno\" placeholder=\"\" >\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-1 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Ano(s)</strong></span>\n");
out.write(" </label>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_60.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_60.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_60);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_60);
return false;
}
private boolean _jspx_meth_c_choose_31(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_31 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_31.setPageContext(_jspx_page_context);
_jspx_th_c_choose_31.setParent(null);
int _jspx_eval_c_choose_31 = _jspx_th_c_choose_31.doStartTag();
if (_jspx_eval_c_choose_31 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_61((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_31, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_62((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_31, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_31.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_31.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_31);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_31);
return false;
}
private boolean _jspx_meth_c_when_61(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_31, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_61 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_61.setPageContext(_jspx_page_context);
_jspx_th_c_when_61.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_31);
_jspx_th_c_when_61.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'edit'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_61 = _jspx_th_c_when_61.doStartTag();
if (_jspx_eval_c_when_61 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <label class=\"inline col-md-1 col-xs-12\">\n");
out.write(" <input type=\"number\" min=\"0\" max=\"12\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" name=\"nrprazoMes\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nrPrazoMes}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" placeholder=\"\">\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Mese(s)</strong></span>\n");
out.write(" </label>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_61.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_61.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_61);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_61);
return false;
}
private boolean _jspx_meth_c_when_62(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_31, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_62 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_62.setPageContext(_jspx_page_context);
_jspx_th_c_when_62.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_31);
_jspx_th_c_when_62.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_62 = _jspx_th_c_when_62.doStartTag();
if (_jspx_eval_c_when_62 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <label class=\"inline col-md-1 col-xs-12\">\n");
out.write(" <input type=\"number\" min=\"0\" max=\"12\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" name=\"nrprazoMes\" placeholder=\"\" >\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-1 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Mese(s)</strong></span>\n");
out.write(" </label>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_62.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_62.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_62);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_62);
return false;
}
private boolean _jspx_meth_c_if_14(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_14 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_14.setPageContext(_jspx_page_context);
_jspx_th_c_if_14.setParent(null);
_jspx_th_c_if_14.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao !='edit' && execucao !='insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_14 = _jspx_th_c_if_14.doStartTag();
if (_jspx_eval_c_if_14 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <div class=\"form-group\">\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Vencimento:</strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-3 col-xs-12\">\n");
out.write(" <span>");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.dtVencimento}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span>\n");
out.write(" </label>\n");
out.write(" </div>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_if_14.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_14.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_14);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_14);
return false;
}
private boolean _jspx_meth_c_choose_32(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_32 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_32.setPageContext(_jspx_page_context);
_jspx_th_c_choose_32.setParent(null);
int _jspx_eval_c_choose_32 = _jspx_th_c_choose_32.doStartTag();
if (_jspx_eval_c_choose_32 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_63((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_32, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_65((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_32, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_30((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_32, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_32.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_32.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_32);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_32);
return false;
}
private boolean _jspx_meth_c_when_63(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_32, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_63 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_63.setPageContext(_jspx_page_context);
_jspx_th_c_when_63.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_32);
_jspx_th_c_when_63.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'edit'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_63 = _jspx_th_c_when_63.doStartTag();
if (_jspx_eval_c_when_63 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_choose_33((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_63, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_63.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_63.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_63);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_63);
return false;
}
private boolean _jspx_meth_c_choose_33(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_63, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_33 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_33.setPageContext(_jspx_page_context);
_jspx_th_c_choose_33.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_63);
int _jspx_eval_c_choose_33 = _jspx_th_c_choose_33.doStartTag();
if (_jspx_eval_c_choose_33 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_64((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_33, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_29((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_33, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_33.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_33.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_33);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_33);
return false;
}
private boolean _jspx_meth_c_when_64(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_33, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_64 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_64.setPageContext(_jspx_page_context);
_jspx_th_c_when_64.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_33);
_jspx_th_c_when_64.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nrVigor != 'true'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_64 = _jspx_th_c_when_64.doStartTag();
if (_jspx_eval_c_when_64 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <label class=\"pull-left inline\">\n");
out.write(" <input id=\"id-button-borders\" type=\"checkbox\" id=\"\" name=\"nrvigor\" value=\"true\" class=\"ace ace-switch ace-switch-5\" >\n");
out.write(" <span class=\"lbl middle\"></span>\n");
out.write(" </label>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_64.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_64.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_64);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_64);
return false;
}
private boolean _jspx_meth_c_otherwise_29(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_33, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_29 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_29.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_29.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_33);
int _jspx_eval_c_otherwise_29 = _jspx_th_c_otherwise_29.doStartTag();
if (_jspx_eval_c_otherwise_29 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <label class=\"pull-left inline\">\n");
out.write(" <input id=\"id-button-borders\" type=\"checkbox\" id=\"\" name=\"nrvigor\" value=\"true\" checked=\"\" class=\"ace ace-switch ace-switch-5\" >\n");
out.write(" <span class=\"lbl middle\"></span>\n");
out.write(" </label>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_29.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_29.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_29);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_29);
return false;
}
private boolean _jspx_meth_c_when_65(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_32, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_65 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_65.setPageContext(_jspx_page_context);
_jspx_th_c_when_65.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_32);
_jspx_th_c_when_65.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_65 = _jspx_th_c_when_65.doStartTag();
if (_jspx_eval_c_when_65 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <label class=\"pull-left inline\">\n");
out.write(" <input id=\"id-button-borders\" type=\"checkbox\" id=\"\" name=\"nrvigor\" value=\"true\" class=\"ace ace-switch ace-switch-5\" >\n");
out.write(" <span class=\"lbl middle\"></span>\n");
out.write(" </label>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_65.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_65.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_65);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_65);
return false;
}
private boolean _jspx_meth_c_otherwise_30(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_32, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_30 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_30.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_30.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_32);
int _jspx_eval_c_otherwise_30 = _jspx_th_c_otherwise_30.doStartTag();
if (_jspx_eval_c_otherwise_30 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_choose_34((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_otherwise_30, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_30.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_30.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_30);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_30);
return false;
}
private boolean _jspx_meth_c_choose_34(javax.servlet.jsp.tagext.JspTag _jspx_th_c_otherwise_30, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_34 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_34.setPageContext(_jspx_page_context);
_jspx_th_c_choose_34.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_otherwise_30);
int _jspx_eval_c_choose_34 = _jspx_th_c_choose_34.doStartTag();
if (_jspx_eval_c_choose_34 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_66((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_34, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_31((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_34, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_34.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_34.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_34);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_34);
return false;
}
private boolean _jspx_meth_c_when_66(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_34, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_66 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_66.setPageContext(_jspx_page_context);
_jspx_th_c_when_66.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_34);
_jspx_th_c_when_66.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${'true' == auto.nrVigor}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_66 = _jspx_th_c_when_66.doStartTag();
if (_jspx_eval_c_when_66 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"label label-success arrowed\" title=\"SIM\">\n");
out.write(" <i class=\"ace-icon fa fa-check bigger-120\"></i>\n");
out.write(" Sim\n");
out.write(" </span>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_66.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_66.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_66);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_66);
return false;
}
private boolean _jspx_meth_c_otherwise_31(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_34, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_31 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_31.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_31.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_34);
int _jspx_eval_c_otherwise_31 = _jspx_th_c_otherwise_31.doStartTag();
if (_jspx_eval_c_otherwise_31 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"label label-danger arrowed\" title=\"NÃO\">\n");
out.write(" <i class=\"ace-icon fa fa-ban bigger-120\"></i>\n");
out.write(" Não\n");
out.write(" </span>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_31.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_31.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_31);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_31);
return false;
}
private boolean _jspx_meth_c_choose_35(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_35 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_35.setPageContext(_jspx_page_context);
_jspx_th_c_choose_35.setParent(null);
int _jspx_eval_c_choose_35 = _jspx_th_c_choose_35.doStartTag();
if (_jspx_eval_c_choose_35 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_67((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_35, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_68((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_35, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_32((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_35, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_35.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_35.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_35);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_35);
return false;
}
private boolean _jspx_meth_c_when_67(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_35, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_67 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_67.setPageContext(_jspx_page_context);
_jspx_th_c_when_67.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_35);
_jspx_th_c_when_67.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'edit'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_67 = _jspx_th_c_when_67.doStartTag();
if (_jspx_eval_c_when_67 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <textarea class=\"form-control\" id=\"form-field-8\" name=\"dsObservacao\" placeholder=\"\" style=\"margin: 0px 102.656px 0px 0px; width: 600px; height: 90px;\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.dsObservacao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</textarea>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_67.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_67.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_67);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_67);
return false;
}
private boolean _jspx_meth_c_when_68(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_35, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_68 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_68.setPageContext(_jspx_page_context);
_jspx_th_c_when_68.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_35);
_jspx_th_c_when_68.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_68 = _jspx_th_c_when_68.doStartTag();
if (_jspx_eval_c_when_68 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <textarea class=\"form-control\" id=\"form-field-8\" name=\"dsObservacao\" placeholder=\"\" style=\"margin: 0px 102.656px 0px 0px; width: 600px; height: 90px;\"></textarea>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_68.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_68.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_68);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_68);
return false;
}
private boolean _jspx_meth_c_otherwise_32(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_35, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_32 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_32.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_32.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_35);
int _jspx_eval_c_otherwise_32 = _jspx_th_c_otherwise_32.doStartTag();
if (_jspx_eval_c_otherwise_32 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.dsObservacao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_32.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_32.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_32);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_32);
return false;
}
private boolean _jspx_meth_c_choose_36(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_36 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_36.setPageContext(_jspx_page_context);
_jspx_th_c_choose_36.setParent(null);
int _jspx_eval_c_choose_36 = _jspx_th_c_choose_36.doStartTag();
if (_jspx_eval_c_choose_36 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_69((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_36, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_33((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_36, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_36.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_36.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_36);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_36);
return false;
}
private boolean _jspx_meth_c_when_69(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_36, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_69 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_69.setPageContext(_jspx_page_context);
_jspx_th_c_when_69.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_36);
_jspx_th_c_when_69.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pgValidacao=='pgValidacao'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_69 = _jspx_th_c_when_69.doStartTag();
if (_jspx_eval_c_when_69 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <button class=\"btn btn-yellow other-block preview\" type=\"reset\" onclick=\"location.href='ControllerServlet?acao=AutoCessaoValidacaoLista';\" >\n");
out.write(" <i class=\"ace-icon fa fa-undo bigger-110\"></i>\n");
out.write(" Voltar\n");
out.write(" </button>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_69.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_69.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_69);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_69);
return false;
}
private boolean _jspx_meth_c_otherwise_33(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_36, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_33 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_33.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_33.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_36);
int _jspx_eval_c_otherwise_33 = _jspx_th_c_otherwise_33.doStartTag();
if (_jspx_eval_c_otherwise_33 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <button class=\"btn btn-yellow other-block preview\" type=\"reset\" onclick=\" location.href='ControllerServlet?acao=AutoCessaoListaPagFiltro&ter=");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${ter}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("';\">\n");
out.write(" <i class=\"ace-icon fa fa-undo bigger-110\"></i>\n");
out.write(" Voltar\n");
out.write(" </button>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_33.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_33.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_33);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_33);
return false;
}
private boolean _jspx_meth_c_if_15(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_15 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_15.setPageContext(_jspx_page_context);
_jspx_th_c_if_15.setParent(null);
_jspx_th_c_if_15.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao=='insert' || execucao=='edit' && (sessionSgDivisao == 'DDPI' && sessionSgSetor == 'SCL')}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_15 = _jspx_th_c_if_15.doStartTag();
if (_jspx_eval_c_if_15 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <button class=\"btn btn-success\" type=\"submit\">\n");
out.write(" <i class=\"ace-icon fa fa-save bigger-110\"></i>\n");
out.write(" Salvar\n");
out.write(" </button>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_if_15.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_15.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_15);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_15);
return false;
}
private boolean _jspx_meth_c_if_16(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_16 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_16.setPageContext(_jspx_page_context);
_jspx_th_c_if_16.setParent(null);
_jspx_th_c_if_16.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.pkAutoStage ==1}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_16 = _jspx_th_c_if_16.doStartTag();
if (_jspx_eval_c_if_16 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" disabled-li-menu \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_if_16.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_16.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_16);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_16);
return false;
}
private boolean _jspx_meth_c_choose_37(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_37 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_37.setPageContext(_jspx_page_context);
_jspx_th_c_choose_37.setParent(null);
int _jspx_eval_c_choose_37 = _jspx_th_c_choose_37.doStartTag();
if (_jspx_eval_c_choose_37 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_70((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_37, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_71((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_37, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_34((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_37, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_37.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_37.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_37);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_37);
return false;
}
private boolean _jspx_meth_c_when_70(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_37, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_70 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_70.setPageContext(_jspx_page_context);
_jspx_th_c_when_70.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_37);
_jspx_th_c_when_70.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'edit'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_70 = _jspx_th_c_when_70.doStartTag();
if (_jspx_eval_c_when_70 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <select class=\"col-md-8 col-xs-12\" name=\"pkCatContrapartida\">\n");
out.write(" <option value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${selCatContra.pkCatContrapartida}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" title=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${selCatContra.nmCatContrapartida}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write('"');
out.write('>');
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${selCatContra.nmCatContrapartida}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</option>\n");
out.write(" <option></option>\n");
out.write(" ");
if (_jspx_meth_c_forEach_12((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_70, _jspx_page_context))
return true;
out.write("\n");
out.write(" </select>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_70.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_70.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_70);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_70);
return false;
}
private boolean _jspx_meth_c_forEach_12(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_70, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:forEach
org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_forEach_12 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _jspx_tagPool_c_forEach_var_items.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class);
_jspx_th_c_forEach_12.setPageContext(_jspx_page_context);
_jspx_th_c_forEach_12.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_70);
_jspx_th_c_forEach_12.setVar("catContra");
_jspx_th_c_forEach_12.setItems((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${CatContra.listSelectCatContra()}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int[] _jspx_push_body_count_c_forEach_12 = new int[] { 0 };
try {
int _jspx_eval_c_forEach_12 = _jspx_th_c_forEach_12.doStartTag();
if (_jspx_eval_c_forEach_12 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <option value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${catContra.pkCatContrapartida}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" title=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${catContra.nmCatContrapartida}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write('"');
out.write('>');
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${catContra.nmCatContrapartida}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</option> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_forEach_12.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_forEach_12.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_c_forEach_12[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_c_forEach_12.doCatch(_jspx_exception);
} finally {
_jspx_th_c_forEach_12.doFinally();
_jspx_tagPool_c_forEach_var_items.reuse(_jspx_th_c_forEach_12);
}
return false;
}
private boolean _jspx_meth_c_when_71(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_37, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_71 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_71.setPageContext(_jspx_page_context);
_jspx_th_c_when_71.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_37);
_jspx_th_c_when_71.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_71 = _jspx_th_c_when_71.doStartTag();
if (_jspx_eval_c_when_71 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <select class=\"col-md-8 col-xs-12\" name=\"pkCatContrapartida\" required=\"required\">\n");
out.write(" <option></option>\n");
out.write(" ");
if (_jspx_meth_c_forEach_13((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_71, _jspx_page_context))
return true;
out.write("\n");
out.write(" </select>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_71.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_71.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_71);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_71);
return false;
}
private boolean _jspx_meth_c_forEach_13(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_71, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:forEach
org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_forEach_13 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _jspx_tagPool_c_forEach_var_items.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class);
_jspx_th_c_forEach_13.setPageContext(_jspx_page_context);
_jspx_th_c_forEach_13.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_71);
_jspx_th_c_forEach_13.setVar("catContra");
_jspx_th_c_forEach_13.setItems((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${CatContra.listSelectCatContra()}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int[] _jspx_push_body_count_c_forEach_13 = new int[] { 0 };
try {
int _jspx_eval_c_forEach_13 = _jspx_th_c_forEach_13.doStartTag();
if (_jspx_eval_c_forEach_13 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <option value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${catContra.pkCatContrapartida}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" title=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${catContra.nmCatContrapartida}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write('"');
out.write('>');
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${catContra.nmCatContrapartida}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</option> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_forEach_13.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_forEach_13.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_c_forEach_13[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_c_forEach_13.doCatch(_jspx_exception);
} finally {
_jspx_th_c_forEach_13.doFinally();
_jspx_tagPool_c_forEach_var_items.reuse(_jspx_th_c_forEach_13);
}
return false;
}
private boolean _jspx_meth_c_otherwise_34(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_37, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_34 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_34.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_34.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_37);
int _jspx_eval_c_otherwise_34 = _jspx_th_c_otherwise_34.doStartTag();
if (_jspx_eval_c_otherwise_34 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${selCatContra.nmCatContrapartida}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_34.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_34.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_34);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_34);
return false;
}
private boolean _jspx_meth_c_choose_38(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_38 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_38.setPageContext(_jspx_page_context);
_jspx_th_c_choose_38.setParent(null);
int _jspx_eval_c_choose_38 = _jspx_th_c_choose_38.doStartTag();
if (_jspx_eval_c_choose_38 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_72((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_38, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_73((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_38, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_35((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_38, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_38.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_38.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_38);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_38);
return false;
}
private boolean _jspx_meth_c_when_72(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_38, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_72 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_72.setPageContext(_jspx_page_context);
_jspx_th_c_when_72.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_38);
_jspx_th_c_when_72.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'edit'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_72 = _jspx_th_c_when_72.doStartTag();
if (_jspx_eval_c_when_72 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <textarea class=\"form-control\" id=\"form-field-8\" name=\"dsContrapartida\" placeholder=\"\" style=\"margin: 0px 102.656px 0px 0px; width: 600px; height: 90px;\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.dsContrapartida}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</textarea>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_72.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_72.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_72);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_72);
return false;
}
private boolean _jspx_meth_c_when_73(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_38, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_73 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_73.setPageContext(_jspx_page_context);
_jspx_th_c_when_73.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_38);
_jspx_th_c_when_73.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao == 'insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_73 = _jspx_th_c_when_73.doStartTag();
if (_jspx_eval_c_when_73 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <textarea class=\"form-control\" id=\"form-field-8\" name=\"dsContrapartida\" placeholder=\"\" style=\"margin: 0px 102.656px 0px 0px; width: 600px; height: 90px;\"></textarea>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_73.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_73.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_73);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_73);
return false;
}
private boolean _jspx_meth_c_otherwise_35(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_38, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_35 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_35.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_35.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_38);
int _jspx_eval_c_otherwise_35 = _jspx_th_c_otherwise_35.doStartTag();
if (_jspx_eval_c_otherwise_35 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.dsContrapartida}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_35.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_35.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_35);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_35);
return false;
}
private boolean _jspx_meth_c_if_17(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_17 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_17.setPageContext(_jspx_page_context);
_jspx_th_c_if_17.setParent(null);
_jspx_th_c_if_17.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.pkAutoStage ==1}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_17 = _jspx_th_c_if_17.doStartTag();
if (_jspx_eval_c_if_17 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" disabled-li-menu \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_if_17.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_17.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_17);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_17);
return false;
}
private boolean _jspx_meth_c_if_18(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_18 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_18.setPageContext(_jspx_page_context);
_jspx_th_c_if_18.setParent(null);
_jspx_th_c_if_18.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${(sessionSgDivisao == 'DDPI' && sessionSgSetor == 'SCL') && (execucao=='insert' || execucao=='edit')}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_18 = _jspx_th_c_if_18.doStartTag();
if (_jspx_eval_c_if_18 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <form action=\"ControllerServlet?acao=AutoCessaoValidacaoDispLegalUC\" method=\"POST\" >\n");
out.write(" <input type=\"hidden\" name=\"pkAutoStage\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.pkAutoStage}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" />\n");
out.write(" <input type=\"hidden\" name=\"nrVerDisplegal\" value=\"1\" />\n");
out.write(" <input type=\"hidden\" name=\"execucao\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${execucao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" />\n");
out.write(" <input type=\"hidden\" name=\"pgValidacao\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pgValidacao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" />\n");
out.write(" <div class=\"input_fields_wrap\">\n");
out.write(" <div class=\"form-group\">\n");
out.write(" <label class=\"inline col-md-1 col-xs-12\" >\n");
out.write(" <span class=\"lbl\">\n");
out.write(" <strong>Tipo:</strong>\n");
out.write(" </span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-3 col-xs-12\">\n");
out.write(" <select class=\"col-md-12 col-xs-12\" name=\"tpDispositivo\" required=\"required\">\n");
out.write(" <option></option>\n");
out.write(" ");
if (_jspx_meth_c_forEach_14((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_if_18, _jspx_page_context))
return true;
out.write("\n");
out.write(" </select>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-1 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Número:</strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-3 col-xs-12\">\n");
out.write(" <input type=\"number\" min=\"1\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" placeholder=\"numero\" name=\"numDispositivo\" >\n");
out.write(" </label>\n");
out.write("\n");
out.write(" <label class=\"inline col-md-1 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Data:</strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-1 col-xs-12\">\n");
out.write(" <div class=\"input-group\">\n");
out.write(" <input class=\"form-control\" name=\"dtDispositivo\" type=\"date\" placeholder=\"dd/mm/aaaa\" data-date-format=\"dd/mm/yyyy\">\n");
out.write(" <a href=\"#\" class=\"add_field_button\" title=\"Adicionar dispositivos\" title=\"Adicionar campos\"><span class=\"label label-success\"><i class=\" glyphicon glyphicon-plus-sign\"></i></span></a>\n");
out.write(" </div>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-offset-1 col-md-2 col-xs-12\">\n");
out.write(" \n");
out.write(" </label>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" <div class=\"space-2\"></div>\n");
out.write(" <div class=\"form-actions center\">\n");
out.write(" <button class=\"btn btn-success\" type=\"submit\">\n");
out.write(" <i class=\"ace-icon fa fa-save bigger-110\"></i>\n");
out.write(" Salvar\n");
out.write(" </button>\n");
out.write(" </div>\n");
out.write(" </form>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_if_18.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_18.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_18);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_18);
return false;
}
private boolean _jspx_meth_c_forEach_14(javax.servlet.jsp.tagext.JspTag _jspx_th_c_if_18, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:forEach
org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_forEach_14 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _jspx_tagPool_c_forEach_var_items.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class);
_jspx_th_c_forEach_14.setPageContext(_jspx_page_context);
_jspx_th_c_forEach_14.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_if_18);
_jspx_th_c_forEach_14.setVar("tpdis");
_jspx_th_c_forEach_14.setItems((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${TpDis.listSelectTipoDisp()}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int[] _jspx_push_body_count_c_forEach_14 = new int[] { 0 };
try {
int _jspx_eval_c_forEach_14 = _jspx_th_c_forEach_14.doStartTag();
if (_jspx_eval_c_forEach_14 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_if_19((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_forEach_14, _jspx_page_context, _jspx_push_body_count_c_forEach_14))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_forEach_14.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_forEach_14.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_c_forEach_14[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_c_forEach_14.doCatch(_jspx_exception);
} finally {
_jspx_th_c_forEach_14.doFinally();
_jspx_tagPool_c_forEach_var_items.reuse(_jspx_th_c_forEach_14);
}
return false;
}
private boolean _jspx_meth_c_if_19(javax.servlet.jsp.tagext.JspTag _jspx_th_c_forEach_14, PageContext _jspx_page_context, int[] _jspx_push_body_count_c_forEach_14)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_19 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_19.setPageContext(_jspx_page_context);
_jspx_th_c_if_19.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_forEach_14);
_jspx_th_c_if_19.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${tpdis.nmTipoDispLegal != 'Informacao nao cadastrada'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_19 = _jspx_th_c_if_19.doStartTag();
if (_jspx_eval_c_if_19 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <option value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${tpdis.pkTipoDispLegal}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" title=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${tpdis.nmTipoDispLegal}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write('"');
out.write('>');
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${tpdis.nmTipoDispLegal}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</option> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_if_19.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_19.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_19);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_19);
return false;
}
private boolean _jspx_meth_c_forEach_15(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:forEach
org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_forEach_15 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _jspx_tagPool_c_forEach_var_items.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class);
_jspx_th_c_forEach_15.setPageContext(_jspx_page_context);
_jspx_th_c_forEach_15.setParent(null);
_jspx_th_c_forEach_15.setVar("di");
_jspx_th_c_forEach_15.setItems((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${Disp.listDispositivo(auto.pkAutoStage)}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int[] _jspx_push_body_count_c_forEach_15 = new int[] { 0 };
try {
int _jspx_eval_c_forEach_15 = _jspx_th_c_forEach_15.doStartTag();
if (_jspx_eval_c_forEach_15 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_set_22((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_forEach_15, _jspx_page_context, _jspx_push_body_count_c_forEach_15))
return true;
out.write("\n");
out.write(" <div class=\"form-group\">\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\n");
out.write(" <span class=\"lbl\">\n");
out.write(" <strong>Tipo de Dispositivo:</strong>\n");
out.write(" </span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-3 col-xs-12\">\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${TpDisp.nmTipoDispLegal}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-1 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Número:</strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\">\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${di.nrDisp}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-1 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Data:</strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\">\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${di.dtDisp}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span>\n");
out.write(" </label>\n");
out.write(" ");
if (_jspx_meth_c_if_20((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_forEach_15, _jspx_page_context, _jspx_push_body_count_c_forEach_15))
return true;
out.write("\n");
out.write(" </div>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_forEach_15.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_forEach_15.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_c_forEach_15[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_c_forEach_15.doCatch(_jspx_exception);
} finally {
_jspx_th_c_forEach_15.doFinally();
_jspx_tagPool_c_forEach_var_items.reuse(_jspx_th_c_forEach_15);
}
return false;
}
private boolean _jspx_meth_c_set_22(javax.servlet.jsp.tagext.JspTag _jspx_th_c_forEach_15, PageContext _jspx_page_context, int[] _jspx_push_body_count_c_forEach_15)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_22 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_22.setPageContext(_jspx_page_context);
_jspx_th_c_set_22.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_forEach_15);
_jspx_th_c_set_22.setVar("TpDisp");
_jspx_th_c_set_22.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${TpDis.detalheTpDisp(di.fkTipoDisplegal)}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_22 = _jspx_th_c_set_22.doStartTag();
if (_jspx_th_c_set_22.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_22);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_22);
return false;
}
private boolean _jspx_meth_c_if_20(javax.servlet.jsp.tagext.JspTag _jspx_th_c_forEach_15, PageContext _jspx_page_context, int[] _jspx_push_body_count_c_forEach_15)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_20 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_20.setPageContext(_jspx_page_context);
_jspx_th_c_if_20.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_forEach_15);
_jspx_th_c_if_20.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nmStatus != 'Validado' && (sessionSgDivisao == 'DDPI' && sessionSgSetor == 'SCL')}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_20 = _jspx_th_c_if_20.doStartTag();
if (_jspx_eval_c_if_20 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <a href=\"ControllerServlet?acao=DispositivoLegalDelete&pkDispLegal=");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${di.pkDisplegal}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("&pkAutoStage=");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.pkAutoStage}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" class=\"red remove_field\" title=\"Excluir Dispositivo\"><i class=\"ace-icon glyphicon glyphicon-trash bigger-130\"></i></a>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_if_20.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_20.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_20);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_20);
return false;
}
private boolean _jspx_meth_c_if_21(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_21 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_21.setPageContext(_jspx_page_context);
_jspx_th_c_if_21.setParent(null);
_jspx_th_c_if_21.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.pkAutoStage ==null}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_21 = _jspx_th_c_if_21.doStartTag();
if (_jspx_eval_c_if_21 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" disabled-li-menu \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_if_21.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_21.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_21);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_21);
return false;
}
private boolean _jspx_meth_c_set_23(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_23 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_23.setPageContext(_jspx_page_context);
_jspx_th_c_set_23.setParent(null);
_jspx_th_c_set_23.setVar("arPlanta");
_jspx_th_c_set_23.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${Arquivo.pkArquivo(auto.pkAutoStage,'AutoCessao', 'planta')}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_23 = _jspx_th_c_set_23.doStartTag();
if (_jspx_th_c_set_23.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_23);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_23);
return false;
}
private boolean _jspx_meth_c_out_0(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:out
org.apache.taglibs.standard.tag.rt.core.OutTag _jspx_th_c_out_0 = (org.apache.taglibs.standard.tag.rt.core.OutTag) _jspx_tagPool_c_out_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.OutTag.class);
_jspx_th_c_out_0.setPageContext(_jspx_page_context);
_jspx_th_c_out_0.setParent(null);
_jspx_th_c_out_0.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${arPlanta.pkArquivo}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_out_0 = _jspx_th_c_out_0.doStartTag();
if (_jspx_th_c_out_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_0);
return true;
}
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_0);
return false;
}
private boolean _jspx_meth_c_if_22(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_22 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_22.setPageContext(_jspx_page_context);
_jspx_th_c_if_22.setParent(null);
_jspx_th_c_if_22.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nrVerArqAc=='1' && execucao=='insert' }", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_22 = _jspx_th_c_if_22.doStartTag();
if (_jspx_eval_c_if_22 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <input type=\"hidden\" name=\"finalizar\" value=\"1\" />\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_if_22.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_22.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_22);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_22);
return false;
}
private boolean _jspx_meth_c_forEach_16(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:forEach
org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_forEach_16 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _jspx_tagPool_c_forEach_var_items.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class);
_jspx_th_c_forEach_16.setPageContext(_jspx_page_context);
_jspx_th_c_forEach_16.setParent(null);
_jspx_th_c_forEach_16.setVar("ar");
_jspx_th_c_forEach_16.setItems((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${Arquivo.listArquivo(auto.pkAutoStage, 'AutoCessao')}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int[] _jspx_push_body_count_c_forEach_16 = new int[] { 0 };
try {
int _jspx_eval_c_forEach_16 = _jspx_th_c_forEach_16.doStartTag();
if (_jspx_eval_c_forEach_16 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_if_23((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_forEach_16, _jspx_page_context, _jspx_push_body_count_c_forEach_16))
return true;
out.write(" \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_forEach_16.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_forEach_16.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_c_forEach_16[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_c_forEach_16.doCatch(_jspx_exception);
} finally {
_jspx_th_c_forEach_16.doFinally();
_jspx_tagPool_c_forEach_var_items.reuse(_jspx_th_c_forEach_16);
}
return false;
}
private boolean _jspx_meth_c_if_23(javax.servlet.jsp.tagext.JspTag _jspx_th_c_forEach_16, PageContext _jspx_page_context, int[] _jspx_push_body_count_c_forEach_16)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_23 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_23.setPageContext(_jspx_page_context);
_jspx_th_c_if_23.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_forEach_16);
_jspx_th_c_if_23.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${ar.nmTipo == 'planta'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_23 = _jspx_th_c_if_23.doStartTag();
if (_jspx_eval_c_if_23 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <a href=\"");
if (_jspx_meth_c_out_1((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_if_23, _jspx_page_context, _jspx_push_body_count_c_forEach_16))
return true;
out.write("/Arquivo/Planta/");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${ar.nmNomeArquivo}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" target=\"_blank\"><img src=\"img/img-planta.png\" title=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${ar.nmNome}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" width=\"60%\" height=\"60%\"/></a>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_if_23.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_23.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_23);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_23);
return false;
}
private boolean _jspx_meth_c_out_1(javax.servlet.jsp.tagext.JspTag _jspx_th_c_if_23, PageContext _jspx_page_context, int[] _jspx_push_body_count_c_forEach_16)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:out
org.apache.taglibs.standard.tag.rt.core.OutTag _jspx_th_c_out_1 = (org.apache.taglibs.standard.tag.rt.core.OutTag) _jspx_tagPool_c_out_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.OutTag.class);
_jspx_th_c_out_1.setPageContext(_jspx_page_context);
_jspx_th_c_out_1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_if_23);
_jspx_th_c_out_1.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.servletContext.contextPath}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_out_1 = _jspx_th_c_out_1.doStartTag();
if (_jspx_th_c_out_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_1);
return true;
}
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_1);
return false;
}
private boolean _jspx_meth_c_if_24(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_24 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_24.setPageContext(_jspx_page_context);
_jspx_th_c_if_24.setParent(null);
_jspx_th_c_if_24.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${(sessionSgDivisao == 'DDPI' &&sessionSgSetor == 'SCL') && (execucao=='insert' || execucao=='edit')}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_24 = _jspx_th_c_if_24.doStartTag();
if (_jspx_eval_c_if_24 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <label class=\"inline col-md-3\">\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" name=\"nmNome\" placeholder=\"Nome da Planta\" required=\"required\" >\n");
out.write(" </label>\n");
out.write("\n");
out.write(" <label class=\"inline col-md-3 col-xs-12\">\n");
out.write(" <input type=\"file\" id=\"id-input-file-2\" name=\"UploadPlanta\" required=\"required\"><span class=\"ace-file-container\" data-title=\"Choose\"><span class=\"ace-file-name\" data-title=\"No File ...\"></span></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\">\n");
out.write(" ");
if (_jspx_meth_c_set_24((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_if_24, _jspx_page_context))
return true;
out.write(" \n");
out.write(" ");
if (_jspx_meth_c_choose_39((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_if_24, _jspx_page_context))
return true;
out.write("\n");
out.write(" </label> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_if_24.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_24.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_24);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_24);
return false;
}
private boolean _jspx_meth_c_set_24(javax.servlet.jsp.tagext.JspTag _jspx_th_c_if_24, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_24 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_24.setPageContext(_jspx_page_context);
_jspx_th_c_set_24.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_if_24);
_jspx_th_c_set_24.setVar("idPlanta");
_jspx_th_c_set_24.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${Arquivo.pkArquivo(auto.pkAutoStage,'AutoCessao', 'planta')}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_24 = _jspx_th_c_set_24.doStartTag();
if (_jspx_th_c_set_24.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_24);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_24);
return false;
}
private boolean _jspx_meth_c_choose_39(javax.servlet.jsp.tagext.JspTag _jspx_th_c_if_24, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_39 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_39.setPageContext(_jspx_page_context);
_jspx_th_c_choose_39.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_if_24);
int _jspx_eval_c_choose_39 = _jspx_th_c_choose_39.doStartTag();
if (_jspx_eval_c_choose_39 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_74((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_39, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_36((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_39, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_39.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_39.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_39);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_39);
return false;
}
private boolean _jspx_meth_c_when_74(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_39, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_74 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_74.setPageContext(_jspx_page_context);
_jspx_th_c_when_74.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_39);
_jspx_th_c_when_74.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${ idPlanta.pkArquivo != '0'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_74 = _jspx_th_c_when_74.doStartTag();
if (_jspx_eval_c_when_74 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <button class=\"btn btn-yellow\" type=\"submit\">\n");
out.write(" <i class=\"ace-icon fa fa-save bigger-110\"></i>\n");
out.write(" Substituir\n");
out.write(" </button>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_74.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_74.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_74);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_74);
return false;
}
private boolean _jspx_meth_c_otherwise_36(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_39, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_36 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_36.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_36.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_39);
int _jspx_eval_c_otherwise_36 = _jspx_th_c_otherwise_36.doStartTag();
if (_jspx_eval_c_otherwise_36 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <button class=\"btn btn-success\" type=\"submit\">\n");
out.write(" <i class=\"ace-icon fa fa-save bigger-110\"></i>\n");
out.write(" Salvar\n");
out.write(" </button>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_36.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_36.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_36);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_36);
return false;
}
private boolean _jspx_meth_c_set_25(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_25 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_25.setPageContext(_jspx_page_context);
_jspx_th_c_set_25.setParent(null);
_jspx_th_c_set_25.setVar("arAC");
_jspx_th_c_set_25.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${Arquivo.pkArquivo(auto.pkAutoStage,'AutoCessao', 'AC')}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_25 = _jspx_th_c_set_25.doStartTag();
if (_jspx_th_c_set_25.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_25);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_25);
return false;
}
private boolean _jspx_meth_c_out_2(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:out
org.apache.taglibs.standard.tag.rt.core.OutTag _jspx_th_c_out_2 = (org.apache.taglibs.standard.tag.rt.core.OutTag) _jspx_tagPool_c_out_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.OutTag.class);
_jspx_th_c_out_2.setPageContext(_jspx_page_context);
_jspx_th_c_out_2.setParent(null);
_jspx_th_c_out_2.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${arAC.pkArquivo}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_out_2 = _jspx_th_c_out_2.doStartTag();
if (_jspx_th_c_out_2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_2);
return true;
}
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_2);
return false;
}
private boolean _jspx_meth_c_if_25(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_25 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_25.setPageContext(_jspx_page_context);
_jspx_th_c_if_25.setParent(null);
_jspx_th_c_if_25.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nrVerArqPlanta=='1' && execucao=='insert'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_25 = _jspx_th_c_if_25.doStartTag();
if (_jspx_eval_c_if_25 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <input type=\"hidden\" name=\"finalizar\" value=\"1\" />\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_if_25.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_25.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_25);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_25);
return false;
}
private boolean _jspx_meth_c_forEach_17(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:forEach
org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_forEach_17 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _jspx_tagPool_c_forEach_var_items.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class);
_jspx_th_c_forEach_17.setPageContext(_jspx_page_context);
_jspx_th_c_forEach_17.setParent(null);
_jspx_th_c_forEach_17.setVar("ar");
_jspx_th_c_forEach_17.setItems((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${Arquivo.listArquivo(auto.pkAutoStage, 'AutoCessao')}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int[] _jspx_push_body_count_c_forEach_17 = new int[] { 0 };
try {
int _jspx_eval_c_forEach_17 = _jspx_th_c_forEach_17.doStartTag();
if (_jspx_eval_c_forEach_17 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_if_26((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_forEach_17, _jspx_page_context, _jspx_push_body_count_c_forEach_17))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_forEach_17.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_forEach_17.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_c_forEach_17[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_c_forEach_17.doCatch(_jspx_exception);
} finally {
_jspx_th_c_forEach_17.doFinally();
_jspx_tagPool_c_forEach_var_items.reuse(_jspx_th_c_forEach_17);
}
return false;
}
private boolean _jspx_meth_c_if_26(javax.servlet.jsp.tagext.JspTag _jspx_th_c_forEach_17, PageContext _jspx_page_context, int[] _jspx_push_body_count_c_forEach_17)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_26 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_26.setPageContext(_jspx_page_context);
_jspx_th_c_if_26.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_forEach_17);
_jspx_th_c_if_26.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${ar.nmTipo == 'AC'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_26 = _jspx_th_c_if_26.doStartTag();
if (_jspx_eval_c_if_26 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <a href=\"");
if (_jspx_meth_c_out_3((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_if_26, _jspx_page_context, _jspx_push_body_count_c_forEach_17))
return true;
out.write("/Arquivo/AC/");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${ar.nmNomeArquivo}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" target=\"_blank\"><img src=\"img/img-arquivo.png\" title=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${ar.nmNome}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" width=\"50%\" height=\"50%\"/></a>\n");
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_if_26.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_26.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_26);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_26);
return false;
}
private boolean _jspx_meth_c_out_3(javax.servlet.jsp.tagext.JspTag _jspx_th_c_if_26, PageContext _jspx_page_context, int[] _jspx_push_body_count_c_forEach_17)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:out
org.apache.taglibs.standard.tag.rt.core.OutTag _jspx_th_c_out_3 = (org.apache.taglibs.standard.tag.rt.core.OutTag) _jspx_tagPool_c_out_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.OutTag.class);
_jspx_th_c_out_3.setPageContext(_jspx_page_context);
_jspx_th_c_out_3.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_if_26);
_jspx_th_c_out_3.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.servletContext.contextPath}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_out_3 = _jspx_th_c_out_3.doStartTag();
if (_jspx_th_c_out_3.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_3);
return true;
}
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_3);
return false;
}
private boolean _jspx_meth_c_if_27(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_27 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_27.setPageContext(_jspx_page_context);
_jspx_th_c_if_27.setParent(null);
_jspx_th_c_if_27.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${(sessionSgDivisao == 'DDPI' && sessionSgSetor == 'SCL') && (execucao=='insert' || execucao=='edit')}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_27 = _jspx_th_c_if_27.doStartTag();
if (_jspx_eval_c_if_27 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <label class=\"inline col-md-3\">\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" name=\"nmNome\" placeholder=\"Nome do Auto de Cessão\" required=\"required\" >\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-3 col-xs-12\">\n");
out.write(" <input type=\"file\" id=\"id-input-file-2\" name=\"UploadAC\" required=\"required\" ><span class=\"ace-file-container\" data-title=\"Choose\"><span class=\"ace-file-name\" data-title=\"No File ...\"></span></span>\n");
out.write(" </label>\n");
out.write("\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\">\n");
out.write(" ");
if (_jspx_meth_c_set_26((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_if_27, _jspx_page_context))
return true;
out.write(" \n");
out.write(" ");
if (_jspx_meth_c_choose_40((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_if_27, _jspx_page_context))
return true;
out.write("\n");
out.write(" </label>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_if_27.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_27.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_27);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_27);
return false;
}
private boolean _jspx_meth_c_set_26(javax.servlet.jsp.tagext.JspTag _jspx_th_c_if_27, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_26 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_26.setPageContext(_jspx_page_context);
_jspx_th_c_set_26.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_if_27);
_jspx_th_c_set_26.setVar("idAC");
_jspx_th_c_set_26.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${Arquivo.pkArquivo(auto.pkAutoStage,'AutoCessao', 'AC')}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_26 = _jspx_th_c_set_26.doStartTag();
if (_jspx_th_c_set_26.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_26);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_26);
return false;
}
private boolean _jspx_meth_c_choose_40(javax.servlet.jsp.tagext.JspTag _jspx_th_c_if_27, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_40 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_40.setPageContext(_jspx_page_context);
_jspx_th_c_choose_40.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_if_27);
int _jspx_eval_c_choose_40 = _jspx_th_c_choose_40.doStartTag();
if (_jspx_eval_c_choose_40 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_75((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_40, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_37((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_40, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_40.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_40.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_40);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_40);
return false;
}
private boolean _jspx_meth_c_when_75(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_40, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_75 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_75.setPageContext(_jspx_page_context);
_jspx_th_c_when_75.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_40);
_jspx_th_c_when_75.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${idAC.pkArquivo != '0'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_75 = _jspx_th_c_when_75.doStartTag();
if (_jspx_eval_c_when_75 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <button class=\"btn btn-yellow\" type=\"submit\">\n");
out.write(" <i class=\"ace-icon fa fa-save bigger-110\"></i>\n");
out.write(" Substituir\n");
out.write(" </button>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_75.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_75.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_75);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_75);
return false;
}
private boolean _jspx_meth_c_otherwise_37(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_40, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_37 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_37.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_37.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_40);
int _jspx_eval_c_otherwise_37 = _jspx_th_c_otherwise_37.doStartTag();
if (_jspx_eval_c_otherwise_37 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <button class=\"btn btn-success\" type=\"submit\">\n");
out.write(" <i class=\"ace-icon fa fa-save bigger-110\"></i>\n");
out.write(" Salvar\n");
out.write(" </button>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_37.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_37.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_37);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_37);
return false;
}
private boolean _jspx_meth_c_if_28(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_28 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_28.setPageContext(_jspx_page_context);
_jspx_th_c_if_28.setParent(null);
_jspx_th_c_if_28.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.pkAutoStage ==null}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_28 = _jspx_th_c_if_28.doStartTag();
if (_jspx_eval_c_if_28 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" disabled-li-menu \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_if_28.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_28.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_28);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_28);
return false;
}
private boolean _jspx_meth_c_if_29(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_29 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_29.setPageContext(_jspx_page_context);
_jspx_th_c_if_29.setParent(null);
_jspx_th_c_if_29.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.pkAutoStage ==null}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_29 = _jspx_th_c_if_29.doStartTag();
if (_jspx_eval_c_if_29 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" disabled-li-menu \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_if_29.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_29.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_29);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_29);
return false;
}
private boolean _jspx_meth_c_if_30(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_30 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_30.setPageContext(_jspx_page_context);
_jspx_th_c_if_30.setParent(null);
_jspx_th_c_if_30.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${sessionSgDivisao == 'DDPI' && sessionSgSetor == 'SCL' && execucao == 'Validado'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_30 = _jspx_th_c_if_30.doStartTag();
if (_jspx_eval_c_if_30 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <form action=\"ControllerServlet?acao=ValidacaoUC\" method=\"POST\">\n");
out.write(" <input type=\"hidden\" name=\"pkAutoStage\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.pkAutoStage}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" />\n");
out.write(" <input type=\"hidden\" name=\"pkValidacao\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.fkValidacao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" />\n");
out.write(" <input type=\"hidden\" name=\"execucao\" value=\"insert\" />\n");
out.write(" <input type=\"hidden\" name=\"pgValidacao\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pgValidacao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" />\n");
out.write(" <input type=\"hidden\" name=\"nrVerValidacao\" value=\"1\" />\n");
out.write(" <input type=\"hidden\" name=\"qAC\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${auto.nmCodAc}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" />\n");
out.write("\n");
out.write(" <div class=\"form-group\">\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\n");
out.write(" <span class=\"lbl\">\n");
out.write(" <strong>Situação:</strong>\n");
out.write(" </span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-10 col-xs-12\">\n");
out.write(" <select class=\"col-md-3 col-xs-12\" name=\"nmstatus\" required=\"required\" onChange=\"AutoCessaoValidacao(this)\">\n");
out.write(" <option></option>\n");
out.write(" <option value=\"Corrigir\">Corrigir</option>\n");
out.write(" <option value=\"Validado\">Validado</option>\n");
out.write(" </select>\n");
out.write(" </label>\n");
out.write(" </div> \n");
out.write(" <div class=\"form-group\">\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Tipo de Problema:</strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-4 col-xs-12\">\n");
out.write(" <select class=\"col-md-10 col-xs-12\" name=\"nmProblema\" id=\"Problema\" >\n");
out.write(" <option></option>\n");
out.write(" <option>Documento do Auto Cessão</option>\n");
out.write(" <option>Planta</option>\n");
out.write(" <option>Georreferenciamento</option>\n");
out.write(" <option>Dificuldade na localização</option>\n");
out.write(" </select>\n");
out.write(" </label>\n");
out.write("\n");
out.write(" <label class=\"inline col-md-3 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Divisão responsável:</strong></span>\n");
out.write(" </label>\n");
out.write("\n");
out.write(" <label class=\"inline col-md-3 col-xs-12\">\n");
out.write(" <select class=\"\" name=\"fkDivisao\" id=\"Divisao\">\n");
out.write(" <option></option>\n");
out.write(" ");
if (_jspx_meth_c_forEach_18((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_if_30, _jspx_page_context))
return true;
out.write("\n");
out.write(" </select>\n");
out.write(" </label>\n");
out.write(" </div>\n");
out.write(" <div class=\"form-group\">\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Tarefa p/ solução:</strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-4 col-xs-12\">\n");
out.write(" <select class=\"col-md-10 col-xs-12\" name=\"nmTarefa\" id=\"Tarefa\">\n");
out.write(" <option></option>\n");
out.write(" <option>Refazer polígono</option>\n");
out.write(" <option>Refazer planta</option>\n");
out.write(" <option>Chamar processo</option>\n");
out.write(" <option>Vistória no local</option>\n");
out.write(" </select>\n");
out.write(" </label>\n");
out.write(" </div>\n");
out.write(" <div class=\"form-group\">\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Notas:</strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-10 col-xs-12\">\n");
out.write(" <textarea id=\"form-field-11\" class=\"autosize-transition form-control\" name=\"dsObsservacao\" style=\"margin: 0px 102.656px 0px 0px; width: 600px; height: 50px;\"></textarea>\n");
out.write(" </label> \n");
out.write(" </div>\n");
out.write(" <div class=\"space-2\"></div>\n");
out.write(" <div class=\"form-actions center\">\n");
out.write(" <button class=\"btn btn-yellow other-block preview\" type=\"reset\" onclick=\"history.go(-1);\">\n");
out.write(" <i class=\"ace-icon fa fa-undo bigger-110\"></i>\n");
out.write(" Voltar \n");
out.write(" </button>\n");
out.write(" <button class=\"btn btn-success\" type=\"submit\">\n");
out.write(" <i class=\"ace-icon fa fa-save bigger-110\"></i>\n");
out.write(" Concluir \n");
out.write(" </button>\n");
out.write(" </div>\n");
out.write(" </form>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_if_30.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_30.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_30);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_30);
return false;
}
private boolean _jspx_meth_c_forEach_18(javax.servlet.jsp.tagext.JspTag _jspx_th_c_if_30, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:forEach
org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_forEach_18 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _jspx_tagPool_c_forEach_var_items.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class);
_jspx_th_c_forEach_18.setPageContext(_jspx_page_context);
_jspx_th_c_forEach_18.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_if_30);
_jspx_th_c_forEach_18.setVar("dv");
_jspx_th_c_forEach_18.setItems((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${Divisao.selectLisDivisao()}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int[] _jspx_push_body_count_c_forEach_18 = new int[] { 0 };
try {
int _jspx_eval_c_forEach_18 = _jspx_th_c_forEach_18.doStartTag();
if (_jspx_eval_c_forEach_18 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_if_31((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_forEach_18, _jspx_page_context, _jspx_push_body_count_c_forEach_18))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_forEach_18.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_forEach_18.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_c_forEach_18[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_c_forEach_18.doCatch(_jspx_exception);
} finally {
_jspx_th_c_forEach_18.doFinally();
_jspx_tagPool_c_forEach_var_items.reuse(_jspx_th_c_forEach_18);
}
return false;
}
private boolean _jspx_meth_c_if_31(javax.servlet.jsp.tagext.JspTag _jspx_th_c_forEach_18, PageContext _jspx_page_context, int[] _jspx_push_body_count_c_forEach_18)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_31 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_31.setPageContext(_jspx_page_context);
_jspx_th_c_if_31.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_forEach_18);
_jspx_th_c_if_31.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${dv.sgDivisao != 'OUTRO DEPTO'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_31 = _jspx_th_c_if_31.doStartTag();
if (_jspx_eval_c_if_31 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <option value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${dv.pkDivisao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\"> ");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${dv.sgDivisao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</option>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_if_31.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_31.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_31);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_31);
return false;
}
private boolean _jspx_meth_c_forEach_19(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:forEach
org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_forEach_19 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _jspx_tagPool_c_forEach_var_items.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class);
_jspx_th_c_forEach_19.setPageContext(_jspx_page_context);
_jspx_th_c_forEach_19.setParent(null);
_jspx_th_c_forEach_19.setVar("va");
_jspx_th_c_forEach_19.setItems((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${Val.lisValidacao(auto.pkAutoStage)}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int[] _jspx_push_body_count_c_forEach_19 = new int[] { 0 };
try {
int _jspx_eval_c_forEach_19 = _jspx_th_c_forEach_19.doStartTag();
if (_jspx_eval_c_forEach_19 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_set_27((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_forEach_19, _jspx_page_context, _jspx_push_body_count_c_forEach_19))
return true;
out.write("\n");
out.write(" <div class=\"form-group\">\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Situação:</strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-10 col-xs-12\">\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${va.nmStatus}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span>\n");
out.write(" </label>\n");
out.write(" </div> \n");
out.write(" ");
if (_jspx_meth_c_if_32((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_forEach_19, _jspx_page_context, _jspx_push_body_count_c_forEach_19))
return true;
out.write("\n");
out.write(" <div class=\"form-group\">\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Notas:</strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-10 col-xs-12\">\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${va.dsObsservacao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span>\n");
out.write(" </label> \n");
out.write(" </div>\n");
out.write(" <div class=\"form-group\">\n");
out.write(" ");
if (_jspx_meth_c_set_28((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_forEach_19, _jspx_page_context, _jspx_push_body_count_c_forEach_19))
return true;
out.write("\n");
out.write("\n");
out.write(" ");
if (_jspx_meth_c_set_29((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_forEach_19, _jspx_page_context, _jspx_push_body_count_c_forEach_19))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_fmt_parseDate_0((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_forEach_19, _jspx_page_context, _jspx_push_body_count_c_forEach_19))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_fmt_formatDate_0((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_forEach_19, _jspx_page_context, _jspx_push_body_count_c_forEach_19))
return true;
out.write("\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Realizado por:</strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-4 col-xs-12\">\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${usValidacao.nmNome}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span>\n");
out.write(" </label> \n");
out.write(" <label class=\"inline col-md-4 col-xs-12\">\n");
out.write(" <span class=\"lbl\"><strong>em: </strong></span>\n");
out.write(" <span class=\"lbl\"> ");
if (_jspx_meth_c_out_4((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_forEach_19, _jspx_page_context, _jspx_push_body_count_c_forEach_19))
return true;
out.write("</span>\n");
out.write(" </label> \n");
out.write(" </div>\n");
out.write(" <hr style=\"background-color: black\">\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_forEach_19.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_forEach_19.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_c_forEach_19[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_c_forEach_19.doCatch(_jspx_exception);
} finally {
_jspx_th_c_forEach_19.doFinally();
_jspx_tagPool_c_forEach_var_items.reuse(_jspx_th_c_forEach_19);
}
return false;
}
private boolean _jspx_meth_c_set_27(javax.servlet.jsp.tagext.JspTag _jspx_th_c_forEach_19, PageContext _jspx_page_context, int[] _jspx_push_body_count_c_forEach_19)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_27 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_27.setPageContext(_jspx_page_context);
_jspx_th_c_set_27.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_forEach_19);
_jspx_th_c_set_27.setVar("selDivisao");
_jspx_th_c_set_27.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${Divisao.detalheDivisao(va.fkDivisao)}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_27 = _jspx_th_c_set_27.doStartTag();
if (_jspx_th_c_set_27.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_27);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_27);
return false;
}
private boolean _jspx_meth_c_if_32(javax.servlet.jsp.tagext.JspTag _jspx_th_c_forEach_19, PageContext _jspx_page_context, int[] _jspx_push_body_count_c_forEach_19)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_32 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_32.setPageContext(_jspx_page_context);
_jspx_th_c_if_32.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_forEach_19);
_jspx_th_c_if_32.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${va.nmStatus !='Validado'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_32 = _jspx_th_c_if_32.doStartTag();
if (_jspx_eval_c_if_32 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <div class=\"form-group\">\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Tipo de Problema:</strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-4 col-xs-12\">\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${va.nmProblema}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span>\n");
out.write(" </label>\n");
out.write("\n");
out.write(" <label class=\"inline col-md-3 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Divisão responsável:</strong></span>\n");
out.write(" </label>\n");
out.write("\n");
out.write(" <label class=\"inline col-md-3 col-xs-12\">\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${selDivisao.sgDivisao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span>\n");
out.write(" </label>\n");
out.write(" </div>\n");
out.write(" <div class=\"form-group\">\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\n");
out.write(" <span class=\"lbl\"><strong>Tarefa p/ solução:</strong></span>\n");
out.write(" </label>\n");
out.write(" <label class=\"inline col-md-4 col-xs-12\">\n");
out.write(" <span class=\"lbl\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${va.nmTarefa}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</span>\n");
out.write(" </label>\n");
out.write(" </div>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_if_32.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_32.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_32);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_32);
return false;
}
private boolean _jspx_meth_c_set_28(javax.servlet.jsp.tagext.JspTag _jspx_th_c_forEach_19, PageContext _jspx_page_context, int[] _jspx_push_body_count_c_forEach_19)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_28 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_28.setPageContext(_jspx_page_context);
_jspx_th_c_set_28.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_forEach_19);
_jspx_th_c_set_28.setVar("usValidacao");
_jspx_th_c_set_28.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${Usuario.nomeUsuario(va.nmLogin)}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_28 = _jspx_th_c_set_28.doStartTag();
if (_jspx_th_c_set_28.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_28);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_28);
return false;
}
private boolean _jspx_meth_c_set_29(javax.servlet.jsp.tagext.JspTag _jspx_th_c_forEach_19, PageContext _jspx_page_context, int[] _jspx_push_body_count_c_forEach_19)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_29 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_29.setPageContext(_jspx_page_context);
_jspx_th_c_set_29.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_forEach_19);
_jspx_th_c_set_29.setVar("dt");
_jspx_th_c_set_29.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${va.dthrAtualizacao}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_29 = _jspx_th_c_set_29.doStartTag();
if (_jspx_th_c_set_29.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_29);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_29);
return false;
}
private boolean _jspx_meth_fmt_parseDate_0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_forEach_19, PageContext _jspx_page_context, int[] _jspx_push_body_count_c_forEach_19)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// fmt:parseDate
org.apache.taglibs.standard.tag.rt.fmt.ParseDateTag _jspx_th_fmt_parseDate_0 = (org.apache.taglibs.standard.tag.rt.fmt.ParseDateTag) _jspx_tagPool_fmt_parseDate_var_value_pattern_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.ParseDateTag.class);
_jspx_th_fmt_parseDate_0.setPageContext(_jspx_page_context);
_jspx_th_fmt_parseDate_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_forEach_19);
_jspx_th_fmt_parseDate_0.setVar("converteData");
_jspx_th_fmt_parseDate_0.setValue((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${dt}", java.lang.String.class, (PageContext)_jspx_page_context, null));
_jspx_th_fmt_parseDate_0.setPattern("yyyy-MM-dd HH:mm:ss");
int _jspx_eval_fmt_parseDate_0 = _jspx_th_fmt_parseDate_0.doStartTag();
if (_jspx_th_fmt_parseDate_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_fmt_parseDate_var_value_pattern_nobody.reuse(_jspx_th_fmt_parseDate_0);
return true;
}
_jspx_tagPool_fmt_parseDate_var_value_pattern_nobody.reuse(_jspx_th_fmt_parseDate_0);
return false;
}
private boolean _jspx_meth_fmt_formatDate_0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_forEach_19, PageContext _jspx_page_context, int[] _jspx_push_body_count_c_forEach_19)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// fmt:formatDate
org.apache.taglibs.standard.tag.rt.fmt.FormatDateTag _jspx_th_fmt_formatDate_0 = (org.apache.taglibs.standard.tag.rt.fmt.FormatDateTag) _jspx_tagPool_fmt_formatDate_var_value_pattern_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.FormatDateTag.class);
_jspx_th_fmt_formatDate_0.setPageContext(_jspx_page_context);
_jspx_th_fmt_formatDate_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_forEach_19);
_jspx_th_fmt_formatDate_0.setValue((java.util.Date) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${converteData}", java.util.Date.class, (PageContext)_jspx_page_context, null));
_jspx_th_fmt_formatDate_0.setVar("dtHrAtualizacao");
_jspx_th_fmt_formatDate_0.setPattern("dd/MM/yyyy - HH:mm:ss");
int _jspx_eval_fmt_formatDate_0 = _jspx_th_fmt_formatDate_0.doStartTag();
if (_jspx_th_fmt_formatDate_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_fmt_formatDate_var_value_pattern_nobody.reuse(_jspx_th_fmt_formatDate_0);
return true;
}
_jspx_tagPool_fmt_formatDate_var_value_pattern_nobody.reuse(_jspx_th_fmt_formatDate_0);
return false;
}
private boolean _jspx_meth_c_out_4(javax.servlet.jsp.tagext.JspTag _jspx_th_c_forEach_19, PageContext _jspx_page_context, int[] _jspx_push_body_count_c_forEach_19)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:out
org.apache.taglibs.standard.tag.rt.core.OutTag _jspx_th_c_out_4 = (org.apache.taglibs.standard.tag.rt.core.OutTag) _jspx_tagPool_c_out_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.OutTag.class);
_jspx_th_c_out_4.setPageContext(_jspx_page_context);
_jspx_th_c_out_4.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_forEach_19);
_jspx_th_c_out_4.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${dtHrAtualizacao}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_out_4 = _jspx_th_c_out_4.doStartTag();
if (_jspx_th_c_out_4.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_4);
return true;
}
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_4);
return false;
}
}
<file_sep>/src/java/br/com/Controle/AutoCessaoListaValidacao.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.Controle;
import br.com.Modelo.AutoCessao;
import br.com.Modelo.AutoCessaoDAO;
import br.com.Modelo.Logica;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author d732229
*/
public class AutoCessaoListaValidacao implements Logica {
@Override
public String executa(HttpServletRequest req,
HttpServletResponse res) throws Exception {
AutoCessaoDAO autoVaDAO = new AutoCessaoDAO();
/**
* Atributos:
* pg = número da página atual
* pi = número da página inicial
* pf = número da página final
* qtdRegistro = quantidade de registro geral
* qtdPg = número de quantidade de páginas
* qtdLinha = número de quantidade de linhas por página
* maxPg = quantidade de paginação a ser exibida (1, 2 , 3 ...)
* sobraMaxPg = auxiliar para o calculdo da quantidade de pagina
* */
int pg, pi, pf, qtdRegistro, qtdPg, sobraMaxPg=0, offset;
int qtdLinha = 6;
int maxPg = 10;
String pgS, piS, pfS;
String qAC, qProcesso, qTpProcesso, qVigor, qStatus;
//Carregando atributos com a informações do formlário.
pgS = req.getParameter("pg");
piS = req.getParameter("pi");
pfS = req.getParameter("pf");
qProcesso = req.getParameter("qProcesso");
qTpProcesso = req.getParameter("qTpProcesso");
qAC = req.getParameter("qAC");
qVigor = req.getParameter("qVigor");
qStatus = req.getParameter("qStatus");
//Validação dos atributos carregdos com as informações do formulário.
if (qAC == null){
qAC ="";
}
if (qProcesso == null){
qProcesso ="";
}
if (qVigor == null){
qVigor="";
}
if (qStatus == null){
qStatus="";
}
if (pgS == null) {
pg = 0;
} else {
pg = Integer.parseInt(pgS);
}
if (piS == null) {
pi = 0;
} else {
pi = Integer.parseInt(piS);
}
if (pfS == null) {
pf = 0;
} else {
pf = Integer.parseInt(pfS);
}
//Carregando a quantidade de registro para calculdo da quantidade de paginas
qtdRegistro = autoVaDAO.qtdAutoCessaoPesquisa(qAC, qProcesso, qVigor, qStatus);
qtdPg = qtdRegistro / qtdLinha;
//Logica da paginação
if ((qtdRegistro % qtdLinha) != 0) {
qtdPg = qtdPg+1;
}
if (qtdPg < maxPg) {
maxPg = qtdPg;
}
if (qtdPg > maxPg) {
sobraMaxPg = qtdPg - maxPg;
if (sobraMaxPg > maxPg){
sobraMaxPg = maxPg;
}
}
if (pg == 0) {
pg = 1;
}
if (pf == 0) {
pf = maxPg;
}
if (pg == pf && pf != qtdPg && pf < qtdPg) {
pi = pf;
pf = pf + sobraMaxPg;
} else if (pg == pi){
pi = pi - maxPg;
pf = pf - sobraMaxPg;
pg = pg - 1;
}
offset = ((pg * qtdLinha)- qtdLinha);
//Populando o objeto lista
List<AutoCessao> listAuto = new AutoCessaoDAO().listPagFiltro(qAC, qProcesso, qVigor, qStatus, qtdLinha, offset);
req.setAttribute("listAuto", listAuto);
req.setAttribute("qAC", qAC);
req.setAttribute("qProcesso", qProcesso);
req.setAttribute("qTpProcesso", qTpProcesso);
req.setAttribute("qVigor", qVigor);
req.setAttribute("qStatus", qStatus);
return "AutoCessaoListaValidacao.jsp?pg="+pg+"&pi="+pi+"&pf="+pf+"&qtdPg="+qtdPg+"&totalRes="+qtdRegistro;
}
}
<file_sep>/src/java/br/com/Modelo/ValidacaoDAO.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.Modelo;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author d732229
*/
public class ValidacaoDAO {
private final Connection connection;
public ValidacaoDAO(){
this.connection = new FabricaConexao().getConnetion();
}
//METODO utilizado para retornar as informação de um Validação
public Validacao detalheValidacaoAutoCessao(int fkAutoCessao) throws SQLException {
PreparedStatement stmt =null;
ResultSet rs = null;
Validacao val = new Validacao();
String sql = "SELECT id_validacao_autocessao, fk_autocessao, fk_divisao, nm_status, "
+ "nm_problema, nm_tarefa, ds_obs, nm_login, dthr_atualizacao "
+ "FROM tbl_validacao_autocessao "
+ "WHERE fk_autocessao = ? ";
try{
stmt = connection.prepareStatement(sql);
stmt.setInt(1, fkAutoCessao);
rs = stmt.executeQuery();
if(rs.next()){
val.setPkValidacao(rs.getInt("id_validacao_autocessao"));
val.setFkAutoCessao(rs.getInt("fk_autocessao"));
val.setFkDivisao(rs.getInt("fk_divisao"));
val.setNmStatus(rs.getString("nm_status"));
val.setNmProblema(rs.getString("nm_problema"));
val.setNmTarefa(rs.getString("nm_tarefa"));
val.setDsObsservacao(rs.getString("ds_obs"));
val.setNmLogin(rs.getString("nm_login"));
val.setDthrAtualizacao(rs.getString("dthr_atualizacao"));
}
return val;
}catch (SQLException e){
throw new RuntimeException(e);
}finally{
rs.close();
stmt.close();
// connection.close();
}
}
//METODO utilizado para inserir uma nova Validação no BANCO
public int cValidacao(Validacao val) throws SQLException{
int pkValidacao = 0;
PreparedStatement stmt =null;
ResultSet rs = null;
String sql = "INSERT INTO tbl_validacao_autocessao (fk_autocessao, fk_divisao, nm_status, "
+ "nm_problema, nm_tarefa, ds_obs, nm_login, dthr_atualizacao) "
+ "VALUES (?,?,?,?,?,?,?,?)";
try{
stmt = connection.prepareStatement(sql,PreparedStatement.RETURN_GENERATED_KEYS);
stmt.setInt(1, val.getFkAutoCessao());
stmt.setInt(2, val.getFkDivisao());
stmt.setString(3, val.getNmStatus());
stmt.setString(4, val.getNmProblema());
stmt.setString(5, val.getNmTarefa());
stmt.setString(6, val.getDsObsservacao());
stmt.setString(7, val.getNmLogin());
stmt.setTimestamp(8,java.sql.Timestamp.valueOf(java.time.LocalDateTime.now()));
stmt.executeUpdate();
rs = stmt.getGeneratedKeys();
if(rs.next()){
pkValidacao = rs.getInt("id_validacao_autocessao");
}
}catch (SQLException e){
throw new RuntimeException(e);
}finally{
rs.close();
stmt.close();
}
return pkValidacao;
}
//MEDOTO utilizado para realizar a alteração das informações da Validação
public void upValidacao(Validacao val) throws SQLException {
PreparedStatement stmt = null;
String sql = "UPDATE tbl_validacao_autocessao SET fk_autocessao=?, fk_divisao=?, nm_status=?, "
+ "nm_problema=?, nm_tarefa=?, ds_obs=?, nm_login=?, dthr_atualizacao=? "
+ "WHERE id_validacao_autocessao = ?";
try{
stmt = connection.prepareStatement(sql);
stmt.setInt(1, val.getFkAutoCessao());
stmt.setInt(2, val.getFkDivisao());
stmt.setString(3, val.getNmStatus());
stmt.setString(4, val.getNmProblema());
stmt.setString(5, val.getNmTarefa());
stmt.setString(6, val.getDsObsservacao());
stmt.setString(7, val.getNmLogin());
stmt.setTimestamp(8,java.sql.Timestamp.valueOf(java.time.LocalDateTime.now()));
stmt.setInt(9, val.getPkValidacao());
stmt.execute();
}catch (SQLException e){
throw new RuntimeException(e);
}finally {
stmt.close();
connection.close();
}
}
//METODO lista os setor de um Divisão, utilizado no o select da pagina cadastro e alteração de ususário
public List<Validacao> lisValidacao(int pkAutoCessao) throws SQLException {
PreparedStatement stmt = null;
ResultSet rs = null;
List<Validacao> listValidacao = new ArrayList<Validacao>();
String sql = ("SELECT id_validacao_autocessao, fk_autocessao, fk_divisao, nm_status, "
+ " nm_tarefa, nm_problema, ds_obs, nm_login, dthr_atualizacao "
+ "FROM tbl_validacao_autocessao "
+ "WHERE fk_autocessao = ? "
+ "ORDER BY id_validacao_autocessao DESC");
try {
stmt = connection.prepareStatement(sql);
stmt.setInt(1, pkAutoCessao);
rs = stmt.executeQuery();
while (rs.next()){
Validacao va = new Validacao();
va.setPkValidacao(rs.getInt("id_validacao_autocessao"));
va.setFkAutoCessao(rs.getInt("fk_autocessao"));
va.setFkDivisao(rs.getInt("fk_divisao"));
va.setNmStatus(rs.getString("nm_status"));
va.setNmTarefa(rs.getString("nm_tarefa"));
va.setNmProblema(rs.getString("nm_problema"));
va.setDsObsservacao(rs.getString("ds_obs"));
va.setNmLogin(rs.getString("nm_login"));
va.setDthrAtualizacao(rs.getString("dthr_atualizacao"));
listValidacao.add(va);
}
return listValidacao;
} catch (SQLException e) {
throw new RuntimeException(e);
}finally{
stmt.close();
connection.close();
}
}
}
<file_sep>/src/java/br/com/Controle/ValidacaoUC.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.Controle;
import br.com.Modelo.AutoCessaoDAO;
import br.com.Modelo.Logica;
import br.com.Modelo.Validacao;
import br.com.Modelo.ValidacaoDAO;
import br.com.Utilitario.Transformar;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author d732229
*/
public class ValidacaoUC implements Logica {
@Override
public String executa(HttpServletRequest req,
HttpServletResponse res) throws Exception{
Validacao va = new Validacao();
ValidacaoDAO vaDAO = new ValidacaoDAO();
AutoCessaoDAO autoDAO = new AutoCessaoDAO();
HttpSession session = req.getSession();
//Atributo
int pkValidacao, pkAutoCessao, fkDivisao;
String divisao, nmstatus, nmProblema, nmTarefa, dsObsservacao, loginSessio;
//Carregando os atributos com as informações do formulário
pkAutoCessao = Integer.parseInt(req.getParameter("pkAutoCessao"));
nmstatus = req.getParameter("nmstatus");
nmProblema = req.getParameter("nmProblema");
nmTarefa = req.getParameter("nmTarefa");
dsObsservacao = req.getParameter("dsObsservacao");
divisao = req.getParameter("fkDivisao");
loginSessio =(String) session.getAttribute("sessionLogin");
if(divisao == null || divisao.equals("")){
fkDivisao=0;
}else{
fkDivisao = Integer.parseInt(divisao);
}
if(null == dsObsservacao || !dsObsservacao.equals("")){
dsObsservacao = Transformar.getRemoveAccents(dsObsservacao).toUpperCase().trim();
}
va = new Validacao(pkAutoCessao, fkDivisao, nmProblema, nmTarefa, nmstatus, dsObsservacao, loginSessio);
pkValidacao = vaDAO.cValidacao(va);
req.setAttribute("msg", "true");
req.setAttribute("tipoAler", "success");
req.setAttribute("alert", "Sucesso! ");
if("Validado".equals(nmstatus)){
req.setAttribute("txtAlert", "Finalizado o processo de validação do Auto Cessão");
autoDAO.upAutoCessaoVerificadoValidacao(pkValidacao, 1, pkAutoCessao, nmstatus);
}else{
req.setAttribute("txtAlert", "A(s) informação(ões) foi(ram) salva(s).");
autoDAO.upAutoCessaoVerificadoValidacao(pkValidacao, 0, pkAutoCessao, nmstatus);
}
return "ControllerServlet?acao=AutoCessaoDetalhe&pkAutoCessao="+pkAutoCessao+"&execucao=view";
}
}
<file_sep>/src/java/br/com/Controle/UsuarioLogoff.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.Controle;
import br.com.Modelo.Logica;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author d732229
*/
public class UsuarioLogoff implements Logica{
@Override
public String executa(HttpServletRequest req,
HttpServletResponse res) throws Exception {
// remover os atributos das session!
HttpSession session = req.getSession();
session.removeAttribute("sessionPkUs");
session.removeAttribute("sessionLogin");
session.removeAttribute("sessionNome");
session.removeAttribute("sessionPkDivisao");
session.removeAttribute("sessionSgDivisao");
session.removeAttribute("sessionNmDivisao");
session.removeAttribute("sessionPkSetor");
session.removeAttribute("sessionSgSetor");
session.removeAttribute("sessionNmSetor");
session.removeAttribute("sessionPerfil");
session.removeAttribute("sessionCargo");
session.removeAttribute("sessionFoto");
session.removeAttribute("sessionStatus");
session.removeAttribute("sessionLer");
session.removeAttribute("sessionInserir");
session.removeAttribute("sessionEditar");
session.removeAttribute("sessionExcluir");
session.removeAttribute("sessionPainel");
session.removeAttribute("sessionDesPerfil");
session.invalidate();
return "Login.jsp";
}
}
<file_sep>/src/java/br/com/Utilitario/Transformar.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.Utilitario;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.Normalizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* @author d732229
*/
public class Transformar {
//Converte String para o padrão UTF8
public static String getUFT8(String s) {
String out;
try {
// out = new String(s.getBytes("ISO-8859-1"), "UTF-8");
out = new String(s.getBytes("UTF-8"), "UTF-8");
} catch (java.io.UnsupportedEncodingException e) {
return null;
}
return out;
}
//Converte padronização o texto para a Primeira Letra da frase em Maiuscula
public static String getPriMaiuscula(String value) {
value = value.toLowerCase();
String result = "";
String[] nomes = value.split("\\s+");
for(String palavra : nomes)
result = result +" "+ palavra.replaceFirst(palavra.substring(0, 1), palavra.substring(0, 1).toUpperCase());
return result.trim();
}
//Criptografia o texto para o padrão MD5 (Message-Digest algorithm 5)
public static String getMD5(String senha){
String sen = "";
MessageDigest md = null;
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
BigInteger hash = new BigInteger(1, md.digest(senha.getBytes()));
sen = hash.toString(16);
return sen;
}
public static String getRemoveAccents(String str) {
str = Normalizer.normalize(str, Normalizer.Form.NFD);
str = str.replaceAll("[^\\p{ASCII}]", "");
return str;
}
public static String getSubstituiEspacoHifen(String str){
str = str.replaceAll("\\s+","-");
return str;
}
public static String getRetiraEspacosDuplicados(String str) {
String patternStr = "\\s+";
String replaceStr = " ";
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(str);
str = matcher.replaceAll(replaceStr);
return str;
}
public static String getFileExtension(String filename) {
if (filename.contains("."))
// return filename.substring(filename.lastIndexOf(".") + 1);
return filename.substring(filename.lastIndexOf("."));
else
return "";
}
}
<file_sep>/src/java/br/com/Modelo/Perfil.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.Modelo;
/**
*
* @author d732229
*/
public class Perfil {
//Atributo
private int pkPerfil, nrLer, nrInserir, nrEditar, nrExcluir, nrGerenciar;
private String nmPerfil, dsPerfil, nmLogin, dthrAtualizacao;
//Construtor
public Perfil() {
}
public Perfil(int nrLer, int nrInserir, int nrEditar, int nrExcluir, int nrGerenciar, String nmPerfil, String dsPerfil, String nmLogin) {
this.nrLer = nrLer;
this.nrInserir = nrInserir;
this.nrEditar = nrEditar;
this.nrExcluir = nrExcluir;
this.nrGerenciar = nrGerenciar;
this.nmPerfil = nmPerfil;
this.dsPerfil = dsPerfil;
this.nmLogin = nmLogin;
}
public Perfil(int pkPerfil, int nrLer, int nrInserir, int nrEditar, int nrExcluir, int nrGerenciar, String nmPerfil, String dsPerfil, String nmLogin) {
this(nrLer, nrInserir, nrEditar, nrExcluir, nrGerenciar, nmPerfil, dsPerfil, nmLogin) ;
this.pkPerfil = pkPerfil;
}
//Getters e Setters
public int getPkPerfil() {
return pkPerfil;
}
public void setPkPerfil(int pkPerfil) {
this.pkPerfil = pkPerfil;
}
public int getNrLer() {
return nrLer;
}
public void setNrLer(int nrLer) {
this.nrLer = nrLer;
}
public int getNrInserir() {
return nrInserir;
}
public void setNrInserir(int nrInserir) {
this.nrInserir = nrInserir;
}
public int getNrEditar() {
return nrEditar;
}
public void setNrEditar(int nrEditar) {
this.nrEditar = nrEditar;
}
public int getNrExcluir() {
return nrExcluir;
}
public void setNrExcluir(int nrExcluir) {
this.nrExcluir = nrExcluir;
}
public int getNrGerenciar() {
return nrGerenciar;
}
public void setNrGerenciar(int nrGerenciar) {
this.nrGerenciar = nrGerenciar;
}
public String getNmPerfil() {
return nmPerfil;
}
public void setNmPerfil(String nmPerfil) {
this.nmPerfil = nmPerfil;
}
public String getDsPerfil() {
return dsPerfil;
}
public void setDsPerfil(String dsPerfil) {
this.dsPerfil = dsPerfil;
}
public String getNmLogin() {
return nmLogin;
}
public void setNmLogin(String nmLogin) {
this.nmLogin = nmLogin;
}
public String getDthrAtualizacao() {
return dthrAtualizacao;
}
public void setDthrAtualizacao(String dthrAtualizacao) {
this.dthrAtualizacao = dthrAtualizacao;
}
}
<file_sep>/build/generated/src/org/apache/jsp/UsuarioRU_jsp.java
package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class UsuarioRU_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.List<String> _jspx_dependants;
static {
_jspx_dependants = new java.util.ArrayList<String>(1);
_jspx_dependants.add("/include/ControleAcesso.jsp");
}
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_forEach_var_items;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_set_var_value_nobody;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_redirect_url_nobody;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_set_var_value_scope_nobody;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_out_value_nobody;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_choose;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_if_test;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_fmt_parseDate_var_value_pattern_nobody;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_otherwise;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_fmt_formatDate_var_value_type_nobody;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_when_test;
private org.glassfish.jsp.api.ResourceInjector _jspx_resourceInjector;
public java.util.List<String> getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_jspx_tagPool_c_forEach_var_items = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_c_set_var_value_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_c_redirect_url_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_c_set_var_value_scope_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_c_out_value_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_c_choose = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_c_if_test = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_fmt_parseDate_var_value_pattern_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_c_otherwise = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_fmt_formatDate_var_value_type_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_c_when_test = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
}
public void _jspDestroy() {
_jspx_tagPool_c_forEach_var_items.release();
_jspx_tagPool_c_set_var_value_nobody.release();
_jspx_tagPool_c_redirect_url_nobody.release();
_jspx_tagPool_c_set_var_value_scope_nobody.release();
_jspx_tagPool_c_out_value_nobody.release();
_jspx_tagPool_c_choose.release();
_jspx_tagPool_c_if_test.release();
_jspx_tagPool_fmt_parseDate_var_value_pattern_nobody.release();
_jspx_tagPool_c_otherwise.release();
_jspx_tagPool_fmt_formatDate_var_value_type_nobody.release();
_jspx_tagPool_c_when_test.release();
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html charset=UTF-8;");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
_jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("<!DOCTYPE html>\n");
out.write("<html>\n");
out.write(" \n");
out.write(" ");
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "include/head.jsp", out, false);
out.write("\n");
out.write(" \n");
out.write(" \n");
out.write(" <body class=\"no-skin\">\n");
out.write(" ");
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "include/top.jsp", out, false);
out.write("\n");
out.write(" <div class=\"main-container ace-save-state\" id=\"main-container\">\n");
out.write(" ");
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "include/nav.jsp", out, false);
out.write("\n");
out.write(" ");
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "javaScritp/ajaxSelectSetorAlterar.html", out, false);
out.write("\n");
out.write("\n");
out.write("<!--Verificação de acesso --> \n");
out.write(" ");
if (_jspx_meth_c_set_0(_jspx_page_context))
return;
out.write("\n");
out.write(" ");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
if (_jspx_meth_c_choose_0(_jspx_page_context))
return;
out.write("\n");
out.write("\n");
out.write("<!-- parametro para paginação e pesquisa --> \n");
out.write(" ");
if (_jspx_meth_c_set_3(_jspx_page_context))
return;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_set_4(_jspx_page_context))
return;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_set_5(_jspx_page_context))
return;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_set_6(_jspx_page_context))
return;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_set_7(_jspx_page_context))
return;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_set_8(_jspx_page_context))
return;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_set_9(_jspx_page_context))
return;
out.write("\n");
out.write("\n");
out.write(" <div class=\"breadcrumbs ace-save-state\" id=\"breadcrumbs\">\n");
out.write(" <ul class=\"breadcrumb\">\n");
out.write(" <li><i class=\"ace-icon fa fa-user\"></i> Usuário</li>\n");
out.write(" </ul>\n");
out.write(" </div> \n");
out.write(" <div class=\"page-content\">\n");
out.write(" <div class=\"row\">\n");
out.write(" <div class=\"col-xs-12\">\n");
out.write(" \n");
out.write(" \n");
out.write(" <div class=\"col-sm-offset-1 col-sm-10\">\n");
out.write(" <div id=\"user-profile-2\" class=\"user-profile\">\n");
out.write(" <div class=\"tabbable\">\n");
out.write(" <ul class=\"nav nav-tabs padding-18\">\n");
out.write(" <li class=\"active\">\n");
out.write(" <a data-toggle=\"tab\" href=\"#home\" aria-expanded=\"true\">\n");
out.write(" <i class=\" ace-icon fa fa-user bigger-120\"></i>\n");
out.write(" Prefil\n");
out.write(" </a>\n");
out.write(" </li>\n");
out.write("\n");
out.write(" <!-- <li class=\"\">\n");
out.write(" <a data-toggle=\"tab\" href=\"#escolaridade\" aria-expanded=\"false\">\n");
out.write(" <i class=\"ace-icon fa fa-briefcase bigger-120\"></i>\n");
out.write(" Escolaridade\n");
out.write(" </a>\n");
out.write(" </li>\n");
out.write("\n");
out.write(" <li class=\"\">\n");
out.write(" <a data-toggle=\"tab\" href=\"#friends\" aria-expanded=\"false\">\n");
out.write(" <i class=\"ace-icon fa fa-road bigger-120\"></i>\n");
out.write(" Carreira profissional\n");
out.write(" </a>\n");
out.write(" </li>\n");
out.write("\n");
out.write(" <li class=\"\">\n");
out.write(" <a data-toggle=\"tab\" href=\"#pictures\" aria-expanded=\"false\">\n");
out.write(" <i class=\"ace-icon fa fa-road bigger-120\"></i>\n");
out.write(" Histórico \n");
out.write(" </a>\n");
out.write(" </li>\n");
out.write("-->\n");
out.write(" </ul>\n");
out.write("\n");
out.write(" <div class=\"tab-content no-border padding-24\">\n");
out.write(" <div id=\"home\" class=\"tab-pane active\">\n");
out.write(" <div class=\"row\">\n");
out.write(" <div class=\"col-xs-12 col-sm-2 center\">\n");
out.write(" <span class=\"profile-picture\">\n");
out.write(" <img class=\"editable img-responsive\" title=\"\" alt=\"\" id=\"avatar1\" src=\"img/foto/user.jpg\">\n");
out.write(" </span>\n");
out.write("\n");
out.write(" <div class=\"space space-4\"></div>\n");
out.write("\n");
out.write(" <a href=\"#\" class=\"btn btn-sm btn-block btn-success\">\n");
out.write(" <i class=\"ace-icon fa fa-refresh\"></i>\n");
out.write(" <span class=\"bigger-110\"></span> Atualizar foto\n");
out.write(" </a>\n");
out.write(" \n");
out.write(" </div><!-- /.col -->\n");
out.write(" <form action=\"ControllerServlet?acao=UsuarioAlterar\" method=\"POST\" >\n");
out.write(" <input type=\"hidden\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${us.pkUsuario}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" name=\"pkUsuario\" />\n");
out.write(" <input type=\"hidden\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pg}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" name=\"pg\" />\n");
out.write(" <input type=\"hidden\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pf}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" name=\"pf\" />\n");
out.write(" <input type=\"hidden\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pi}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" name=\"pi\"/>\n");
out.write(" <input type=\"hidden\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${q}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" name=\"q\"/>\n");
out.write(" \n");
out.write(" <div class=\"col-xs-12 col-sm-9\">\n");
out.write(" <h4 class=\"blue\">\n");
out.write(" ");
if (_jspx_meth_c_choose_1(_jspx_page_context))
return;
out.write("\n");
out.write(" </h4>\n");
out.write("\n");
out.write(" <div class=\"profile-user-info\">\n");
out.write(" <div class=\"profile-info-row\">\n");
out.write(" <div class=\"profile-info-name\"> Login</div>\n");
out.write("\n");
out.write(" <div class=\"profile-info-value\">\n");
out.write(" ");
if (_jspx_meth_c_choose_2(_jspx_page_context))
return;
out.write("\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" <div class=\"profile-info-row\">\n");
out.write(" <div class=\"profile-info-name\"> R.F.</div>\n");
out.write("\n");
out.write(" <div class=\"profile-info-value\">\n");
out.write(" ");
if (_jspx_meth_c_choose_3(_jspx_page_context))
return;
out.write("\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" <div class=\"profile-info-row\">\n");
out.write(" <div class=\"profile-info-name\"> E-mail</div>\n");
out.write("\n");
out.write(" <div class=\"profile-info-value\">\n");
out.write(" ");
if (_jspx_meth_c_choose_4(_jspx_page_context))
return;
out.write(" \n");
out.write(" </div>\n");
out.write(" </div> \n");
out.write("\n");
out.write(" <div class=\"profile-info-row\">\n");
out.write(" <div class=\"profile-info-name\"> Divisão</div>\n");
out.write("\n");
out.write(" <div class=\"profile-info-value\">\n");
out.write(" ");
if (_jspx_meth_c_choose_5(_jspx_page_context))
return;
out.write("\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" <div class=\"profile-info-row\" >\n");
out.write(" <div class=\"profile-info-name\"> Núcleo</div>\n");
out.write(" <div class=\"profile-info-value\">\n");
out.write(" ");
if (_jspx_meth_c_choose_6(_jspx_page_context))
return;
out.write(" \n");
out.write(" </div>\n");
out.write(" </div> \n");
out.write(" <div class=\"profile-info-row\">\n");
out.write(" <div class=\"profile-info-name\"> Cargo</div>\n");
out.write("\n");
out.write(" <div class=\"profile-info-value\">\n");
out.write(" ");
if (_jspx_meth_c_choose_7(_jspx_page_context))
return;
out.write("\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"profile-info-row\">\n");
out.write(" <div class=\"profile-info-name\"> Perfil</div>\n");
out.write("\n");
out.write(" <div class=\"profile-info-value\">\n");
out.write(" ");
if (_jspx_meth_c_choose_8(_jspx_page_context))
return;
out.write(" \n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" <div class=\"profile-info-row\">\n");
out.write(" <div class=\"profile-info-name\"> Status</div>\n");
out.write("\n");
out.write(" <div class=\"profile-info-value\">\n");
out.write(" ");
if (_jspx_meth_c_choose_9(_jspx_page_context))
return;
out.write("\n");
out.write(" \n");
out.write(" \n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" \n");
out.write(" <div class=\"profile-info-row\">\n");
out.write(" <div class=\"profile-info-name\"> Atualização</div>\n");
out.write("\n");
out.write(" <div class=\"profile-info-value\">\n");
out.write(" <span>\n");
out.write(" ");
if (_jspx_meth_c_set_10(_jspx_page_context))
return;
out.write("\n");
out.write(" ");
if (_jspx_meth_fmt_parseDate_0(_jspx_page_context))
return;
out.write("\n");
out.write(" ");
if (_jspx_meth_fmt_formatDate_0(_jspx_page_context))
return;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_out_10(_jspx_page_context))
return;
out.write("\n");
out.write(" \n");
out.write(" </span>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" <br />\n");
out.write(" <button class=\"btn btn-yellow\" type=\"reset\" onclick=\" location.href='ControllerServlet?acao=UsuarioListaPaginada&pg=");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pg}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("&pi=");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pi}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("&pf=");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pf}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("&q=");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${q}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("&sgDivisao=");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${sgDivisao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("';\">\n");
out.write(" <i class=\"ace-icon fa fa-undo bigger-110\"></i>\n");
out.write(" Voltar\n");
out.write(" </button>\n");
out.write(" ");
if (_jspx_meth_c_if_1(_jspx_page_context))
return;
out.write("\n");
out.write(" <div class=\"col-sm-12 col-xs-12\" id=\"msg\">\n");
out.write(" <div class=\"alert alert-success\" id=\"ok\">\n");
out.write(" <strong>Sucesso!</strong> A(s) alteração(ôes) foi(ram) realizada(as). \n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" \n");
out.write(" </div><!-- /.col -->\n");
out.write(" \n");
out.write(" </form>\n");
out.write(" </div><!-- /.row -->\n");
out.write("\n");
out.write(" <div class=\"space-20\"></div>\n");
out.write("\n");
out.write(" \n");
out.write(" </div><!-- /#home -->\n");
out.write("\n");
out.write(" <!-- Inicio da Aba Escolaridade--> \n");
out.write(" <div id=\"escolaridade\" class=\"tab-pane\">\n");
out.write(" <div class=\"profile-feed row\">\n");
out.write(" <div class=\"col-sm-6\">\n");
out.write(" <div class=\"profile-activity clearfix\">\n");
out.write(" <div>\n");
out.write(" <img class=\"pull-left\" alt=\"<NAME>'s avatar\" src=\"assets/images/avatars/avatar5.png\">\n");
out.write(" <a class=\"user\" href=\"#\"> <NAME> </a>\n");
out.write(" changed his profile photo.\n");
out.write(" <a href=\"#\">Take a look</a>\n");
out.write("\n");
out.write(" <div class=\"time\">\n");
out.write(" <i class=\"ace-icon fa fa-clock-o bigger-110\"></i>\n");
out.write(" an hour ago\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"tools action-buttons\">\n");
out.write(" <a href=\"#\" class=\"blue\">\n");
out.write(" <i class=\"ace-icon fa fa-pencil bigger-125\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\" class=\"red\">\n");
out.write(" <i class=\"ace-icon fa fa-times bigger-125\"></i>\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"profile-activity clearfix\">\n");
out.write(" <div>\n");
out.write(" <img class=\"pull-left\" alt=\"<NAME>'s avatar\" src=\"assets/images/avatars/avatar1.png\">\n");
out.write(" <a class=\"user\" href=\"#\"> <NAME> </a>\n");
out.write("\n");
out.write(" is now friends with <NAME>.\n");
out.write(" <div class=\"time\">\n");
out.write(" <i class=\"ace-icon fa fa-clock-o bigger-110\"></i>\n");
out.write(" 2 hours ago\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"tools action-buttons\">\n");
out.write(" <a href=\"#\" class=\"blue\">\n");
out.write(" <i class=\"ace-icon fa fa-pencil bigger-125\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\" class=\"red\">\n");
out.write(" <i class=\"ace-icon fa fa-times bigger-125\"></i>\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"profile-activity clearfix\">\n");
out.write(" <div>\n");
out.write(" <i class=\"pull-left thumbicon fa fa-check btn-success no-hover\"></i>\n");
out.write(" <a class=\"user\" href=\"#\"> <NAME> </a>\n");
out.write(" joined\n");
out.write(" <a href=\"#\">Country Music</a>\n");
out.write("\n");
out.write(" group.\n");
out.write(" <div class=\"time\">\n");
out.write(" <i class=\"ace-icon fa fa-clock-o bigger-110\"></i>\n");
out.write(" 5 hours ago\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"tools action-buttons\">\n");
out.write(" <a href=\"#\" class=\"blue\">\n");
out.write(" <i class=\"ace-icon fa fa-pencil bigger-125\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\" class=\"red\">\n");
out.write(" <i class=\"ace-icon fa fa-times bigger-125\"></i>\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"profile-activity clearfix\">\n");
out.write(" <div>\n");
out.write(" <i class=\"pull-left thumbicon fa fa-picture-o btn-info no-hover\"></i>\n");
out.write(" <a class=\"user\" href=\"#\"> <NAME> </a>\n");
out.write(" uploaded a new photo.\n");
out.write(" <a href=\"#\">Take a look</a>\n");
out.write("\n");
out.write(" <div class=\"time\">\n");
out.write(" <i class=\"ace-icon fa fa-clock-o bigger-110\"></i>\n");
out.write(" 5 hours ago\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"tools action-buttons\">\n");
out.write(" <a href=\"#\" class=\"blue\">\n");
out.write(" <i class=\"ace-icon fa fa-pencil bigger-125\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\" class=\"red\">\n");
out.write(" <i class=\"ace-icon fa fa-times bigger-125\"></i>\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"profile-activity clearfix\">\n");
out.write(" <div>\n");
out.write(" <img class=\"pull-left\" alt=\"<NAME>'s avatar\" src=\"assets/images/avatars/avatar4.png\">\n");
out.write(" <a class=\"user\" href=\"#\"> <NAME> </a>\n");
out.write("\n");
out.write(" left a comment on Alex's wall.\n");
out.write(" <div class=\"time\">\n");
out.write(" <i class=\"ace-icon fa fa-clock-o bigger-110\"></i>\n");
out.write(" 8 hours ago\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"tools action-buttons\">\n");
out.write(" <a href=\"#\" class=\"blue\">\n");
out.write(" <i class=\"ace-icon fa fa-pencil bigger-125\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\" class=\"red\">\n");
out.write(" <i class=\"ace-icon fa fa-times bigger-125\"></i>\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" </div><!-- /.col -->\n");
out.write("\n");
out.write(" <div class=\"col-sm-6\">\n");
out.write(" <div class=\"profile-activity clearfix\">\n");
out.write(" <div>\n");
out.write(" <i class=\"pull-left thumbicon fa fa-pencil-square-o btn-pink no-hover\"></i>\n");
out.write(" <a class=\"user\" href=\"#\"> <NAME> </a>\n");
out.write(" published a new blog post.\n");
out.write(" <a href=\"#\">Read now</a>\n");
out.write("\n");
out.write(" <div class=\"time\">\n");
out.write(" <i class=\"ace-icon fa fa-clock-o bigger-110\"></i>\n");
out.write(" 11 hours ago\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"tools action-buttons\">\n");
out.write(" <a href=\"#\" class=\"blue\">\n");
out.write(" <i class=\"ace-icon fa fa-pencil bigger-125\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\" class=\"red\">\n");
out.write(" <i class=\"ace-icon fa fa-times bigger-125\"></i>\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"profile-activity clearfix\">\n");
out.write(" <div>\n");
out.write(" <img class=\"pull-left\" alt=\"<NAME> avatar\" src=\"assets/images/avatars/avatar5.png\">\n");
out.write(" <a class=\"user\" href=\"#\"> <NAME> </a>\n");
out.write("\n");
out.write(" upgraded his skills.\n");
out.write(" <div class=\"time\">\n");
out.write(" <i class=\"ace-icon fa fa-clock-o bigger-110\"></i>\n");
out.write(" 12 hours ago\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"tools action-buttons\">\n");
out.write(" <a href=\"#\" class=\"blue\">\n");
out.write(" <i class=\"ace-icon fa fa-pencil bigger-125\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\" class=\"red\">\n");
out.write(" <i class=\"ace-icon fa fa-times bigger-125\"></i>\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"profile-activity clearfix\">\n");
out.write(" <div>\n");
out.write(" <i class=\"pull-left thumbicon fa fa-key btn-info no-hover\"></i>\n");
out.write(" <a class=\"user\" href=\"#\"> <NAME> </a>\n");
out.write("\n");
out.write(" logged in.\n");
out.write(" <div class=\"time\">\n");
out.write(" <i class=\"ace-icon fa fa-clock-o bigger-110\"></i>\n");
out.write(" 12 hours ago\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"tools action-buttons\">\n");
out.write(" <a href=\"#\" class=\"blue\">\n");
out.write(" <i class=\"ace-icon fa fa-pencil bigger-125\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\" class=\"red\">\n");
out.write(" <i class=\"ace-icon fa fa-times bigger-125\"></i>\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"profile-activity clearfix\">\n");
out.write(" <div>\n");
out.write(" <i class=\"pull-left thumbicon fa fa-power-off btn-inverse no-hover\"></i>\n");
out.write(" <a class=\"user\" href=\"#\"> <NAME> </a>\n");
out.write("\n");
out.write(" logged out.\n");
out.write(" <div class=\"time\">\n");
out.write(" <i class=\"ace-icon fa fa-clock-o bigger-110\"></i>\n");
out.write(" 16 hours ago\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"tools action-buttons\">\n");
out.write(" <a href=\"#\" class=\"blue\">\n");
out.write(" <i class=\"ace-icon fa fa-pencil bigger-125\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\" class=\"red\">\n");
out.write(" <i class=\"ace-icon fa fa-times bigger-125\"></i>\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"profile-activity clearfix\">\n");
out.write(" <div>\n");
out.write(" <i class=\"pull-left thumbicon fa fa-key btn-info no-hover\"></i>\n");
out.write(" <a class=\"user\" href=\"#\"> <NAME> </a>\n");
out.write("\n");
out.write(" logged in.\n");
out.write(" <div class=\"time\">\n");
out.write(" <i class=\"ace-icon fa fa-clock-o bigger-110\"></i>\n");
out.write(" 16 hours ago\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"tools action-buttons\">\n");
out.write(" <a href=\"#\" class=\"blue\">\n");
out.write(" <i class=\"ace-icon fa fa-pencil bigger-125\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\" class=\"red\">\n");
out.write(" <i class=\"ace-icon fa fa-times bigger-125\"></i>\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" </div><!-- /.col -->\n");
out.write(" </div><!-- /.row -->\n");
out.write("\n");
out.write(" <div class=\"space-12\"></div>\n");
out.write("\n");
out.write(" <div class=\"center\">\n");
out.write(" <button type=\"button\" class=\"btn btn-sm btn-primary btn-white btn-round\">\n");
out.write(" <i class=\"ace-icon fa fa-rss bigger-150 middle orange2\"></i>\n");
out.write(" <span class=\"bigger-110\">View more activities</span>\n");
out.write("\n");
out.write(" <i class=\"icon-on-right ace-icon fa fa-arrow-right\"></i>\n");
out.write(" </button>\n");
out.write(" </div>\n");
out.write(" </div><!-- /#feed -->\n");
out.write("\n");
out.write(" <div id=\"friends\" class=\"tab-pane\">\n");
out.write(" <div class=\"profile-users clearfix\">\n");
out.write(" <div class=\"itemdiv memberdiv\">\n");
out.write(" <div class=\"inline pos-rel\">\n");
out.write(" <div class=\"user\">\n");
out.write(" <a href=\"#\">\n");
out.write(" <img src=\"assets/images/avatars/avatar4.png\" alt=\"<NAME>'s avatar\">\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"body\">\n");
out.write(" <div class=\"name\">\n");
out.write(" <a href=\"#\">\n");
out.write(" <span class=\"user-status status-online\"></span>\n");
out.write(" <NAME>\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"popover\">\n");
out.write(" <div class=\"arrow\"></div>\n");
out.write("\n");
out.write(" <div class=\"popover-content\">\n");
out.write(" <div class=\"bolder\">Content Editor</div>\n");
out.write("\n");
out.write(" <div class=\"time\">\n");
out.write(" <i class=\"ace-icon fa fa-clock-o middle bigger-120 orange\"></i>\n");
out.write(" <span class=\"green\"> 20 mins ago </span>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"hr dotted hr-8\"></div>\n");
out.write("\n");
out.write(" <div class=\"tools action-buttons\">\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-facebook-square blue bigger-150\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-twitter-square light-blue bigger-150\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-google-plus-square red bigger-150\"></i>\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"itemdiv memberdiv\">\n");
out.write(" <div class=\"inline pos-rel\">\n");
out.write(" <div class=\"user\">\n");
out.write(" <a href=\"#\">\n");
out.write(" <img src=\"assets/images/avatars/avatar1.png\" alt=\"<NAME>'s avatar\">\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"body\">\n");
out.write(" <div class=\"name\">\n");
out.write(" <a href=\"#\">\n");
out.write(" <span class=\"user-status status-offline\"></span>\n");
out.write(" <NAME>\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"popover\">\n");
out.write(" <div class=\"arrow\"></div>\n");
out.write("\n");
out.write(" <div class=\"popover-content\">\n");
out.write(" <div class=\"bolder\">Graphic Designer</div>\n");
out.write("\n");
out.write(" <div class=\"time\">\n");
out.write(" <i class=\"ace-icon fa fa-clock-o middle bigger-120 grey\"></i>\n");
out.write(" <span class=\"grey\"> 30 min ago </span>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"hr dotted hr-8\"></div>\n");
out.write("\n");
out.write(" <div class=\"tools action-buttons\">\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-facebook-square blue bigger-150\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-twitter-square light-blue bigger-150\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-google-plus-square red bigger-150\"></i>\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"itemdiv memberdiv\">\n");
out.write(" <div class=\"inline pos-rel\">\n");
out.write(" <div class=\"user\">\n");
out.write(" <a href=\"#\">\n");
out.write(" <img src=\"assets/images/avatars/avatar.png\" alt=\"<NAME> avatar\">\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"body\">\n");
out.write(" <div class=\"name\">\n");
out.write(" <a href=\"#\">\n");
out.write(" <span class=\"user-status status-busy\"></span>\n");
out.write(" <NAME>\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"popover\">\n");
out.write(" <div class=\"arrow\"></div>\n");
out.write("\n");
out.write(" <div class=\"popover-content\">\n");
out.write(" <div class=\"bolder\">SEO & Advertising</div>\n");
out.write("\n");
out.write(" <div class=\"time\">\n");
out.write(" <i class=\"ace-icon fa fa-clock-o middle bigger-120 red\"></i>\n");
out.write(" <span class=\"grey\"> 1 hour ago </span>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"hr dotted hr-8\"></div>\n");
out.write("\n");
out.write(" <div class=\"tools action-buttons\">\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-facebook-square blue bigger-150\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-twitter-square light-blue bigger-150\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-google-plus-square red bigger-150\"></i>\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"itemdiv memberdiv\">\n");
out.write(" <div class=\"inline pos-rel\">\n");
out.write(" <div class=\"user\">\n");
out.write(" <a href=\"#\">\n");
out.write(" <img src=\"assets/images/avatars/avatar5.png\" alt=\"<NAME> avatar\">\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"body\">\n");
out.write(" <div class=\"name\">\n");
out.write(" <a href=\"#\">\n");
out.write(" <span class=\"user-status status-idle\"></span>\n");
out.write(" <NAME>\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"popover\">\n");
out.write(" <div class=\"arrow\"></div>\n");
out.write("\n");
out.write(" <div class=\"popover-content\">\n");
out.write(" <div class=\"bolder\">Marketing</div>\n");
out.write("\n");
out.write(" <div class=\"time\">\n");
out.write(" <i class=\"ace-icon fa fa-clock-o middle bigger-120 orange\"></i>\n");
out.write(" <span class=\"\"> 40 minutes idle </span>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"hr dotted hr-8\"></div>\n");
out.write("\n");
out.write(" <div class=\"tools action-buttons\">\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-facebook-square blue bigger-150\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-twitter-square light-blue bigger-150\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-google-plus-square red bigger-150\"></i>\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"itemdiv memberdiv\">\n");
out.write(" <div class=\"inline pos-rel\">\n");
out.write(" <div class=\"user\">\n");
out.write(" <a href=\"#\">\n");
out.write(" <img src=\"assets/images/avatars/avatar2.png\" alt=\"<NAME> avatar\">\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"body\">\n");
out.write(" <div class=\"name\">\n");
out.write(" <a href=\"#\">\n");
out.write(" <span class=\"user-status status-online\"></span>\n");
out.write(" <NAME>\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"popover\">\n");
out.write(" <div class=\"arrow\"></div>\n");
out.write("\n");
out.write(" <div class=\"popover-content\">\n");
out.write(" <div class=\"bolder\">Public Relations</div>\n");
out.write("\n");
out.write(" <div class=\"time\">\n");
out.write(" <i class=\"ace-icon fa fa-clock-o middle bigger-120 orange\"></i>\n");
out.write(" <span class=\"green\"> 2 hours ago </span>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"hr dotted hr-8\"></div>\n");
out.write("\n");
out.write(" <div class=\"tools action-buttons\">\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-facebook-square blue bigger-150\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-twitter-square light-blue bigger-150\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-google-plus-square red bigger-150\"></i>\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"itemdiv memberdiv\">\n");
out.write(" <div class=\"inline pos-rel\">\n");
out.write(" <div class=\"user\">\n");
out.write(" <a href=\"#\">\n");
out.write(" <img src=\"assets/images/avatars/avatar3.png\" alt=\"<NAME> avatar\">\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"body\">\n");
out.write(" <div class=\"name\">\n");
out.write(" <a href=\"#\">\n");
out.write(" <span class=\"user-status status-online\"></span>\n");
out.write(" <NAME>\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"popover\">\n");
out.write(" <div class=\"arrow\"></div>\n");
out.write("\n");
out.write(" <div class=\"popover-content\">\n");
out.write(" <div class=\"bolder\">HR Management</div>\n");
out.write("\n");
out.write(" <div class=\"time\">\n");
out.write(" <i class=\"ace-icon fa fa-clock-o middle bigger-120 orange\"></i>\n");
out.write(" <span class=\"green\"> 20 mins ago </span>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"hr dotted hr-8\"></div>\n");
out.write("\n");
out.write(" <div class=\"tools action-buttons\">\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-facebook-square blue bigger-150\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-twitter-square light-blue bigger-150\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-google-plus-square red bigger-150\"></i>\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"itemdiv memberdiv\">\n");
out.write(" <div class=\"inline pos-rel\">\n");
out.write(" <div class=\"user\">\n");
out.write(" <a href=\"#\">\n");
out.write(" <img src=\"assets/images/avatars/avatar1.png\" alt=\"<NAME> avatar\">\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"body\">\n");
out.write(" <div class=\"name\">\n");
out.write(" <a href=\"#\">\n");
out.write(" <span class=\"user-status status-offline\"></span>\n");
out.write(" <NAME>\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"popover\">\n");
out.write(" <div class=\"arrow\"></div>\n");
out.write("\n");
out.write(" <div class=\"popover-content\">\n");
out.write(" <div class=\"bolder\">Graphic Designer</div>\n");
out.write("\n");
out.write(" <div class=\"time\">\n");
out.write(" <i class=\"ace-icon fa fa-clock-o middle bigger-120 grey\"></i>\n");
out.write(" <span class=\"grey\"> 2 hours ago </span>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"hr dotted hr-8\"></div>\n");
out.write("\n");
out.write(" <div class=\"tools action-buttons\">\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-facebook-square blue bigger-150\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-twitter-square light-blue bigger-150\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-google-plus-square red bigger-150\"></i>\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"itemdiv memberdiv\">\n");
out.write(" <div class=\"inline pos-rel\">\n");
out.write(" <div class=\"user\">\n");
out.write(" <a href=\"#\">\n");
out.write(" <img src=\"assets/images/avatars/avatar3.png\" alt=\"<NAME> avatar\">\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"body\">\n");
out.write(" <div class=\"name\">\n");
out.write(" <a href=\"#\">\n");
out.write(" <span class=\"user-status status-offline\"></span>\n");
out.write(" <NAME>\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"popover\">\n");
out.write(" <div class=\"arrow\"></div>\n");
out.write("\n");
out.write(" <div class=\"popover-content\">\n");
out.write(" <div class=\"bolder\">Accounting</div>\n");
out.write("\n");
out.write(" <div class=\"time\">\n");
out.write(" <i class=\"ace-icon fa fa-clock-o middle bigger-120 grey\"></i>\n");
out.write(" <span class=\"grey\"> 4 hours ago </span>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"hr dotted hr-8\"></div>\n");
out.write("\n");
out.write(" <div class=\"tools action-buttons\">\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-facebook-square blue bigger-150\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-twitter-square light-blue bigger-150\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-google-plus-square red bigger-150\"></i>\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"hr hr10 hr-double\"></div>\n");
out.write("\n");
out.write(" <ul class=\"pager pull-right\">\n");
out.write(" <li class=\"previous disabled\">\n");
out.write(" <a href=\"#\">? Prev</a>\n");
out.write(" </li>\n");
out.write("\n");
out.write(" <li class=\"next\">\n");
out.write(" <a href=\"#\">Next ?</a>\n");
out.write(" </li>\n");
out.write(" </ul>\n");
out.write(" </div><!-- /#friends -->\n");
out.write("\n");
out.write(" <div id=\"pictures\" class=\"tab-pane\">\n");
out.write(" <ul class=\"ace-thumbnails\">\n");
out.write(" <li>\n");
out.write(" <a href=\"#\" data-rel=\"colorbox\">\n");
out.write(" <img alt=\"150x150\" src=\"assets/images/gallery/thumb-1.jpg\">\n");
out.write(" <div class=\"text\">\n");
out.write(" <div class=\"inner\">Sample Caption on Hover</div>\n");
out.write(" </div>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <div class=\"tools tools-bottom\">\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-link\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-paperclip\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-pencil\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-times red\"></i>\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write(" </li>\n");
out.write("\n");
out.write(" <li>\n");
out.write(" <a href=\"#\" data-rel=\"colorbox\">\n");
out.write(" <img alt=\"150x150\" src=\"assets/images/gallery/thumb-2.jpg\">\n");
out.write(" <div class=\"text\">\n");
out.write(" <div class=\"inner\">Sample Caption on Hover</div>\n");
out.write(" </div>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <div class=\"tools tools-bottom\">\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-link\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-paperclip\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-pencil\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-times red\"></i>\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write(" </li>\n");
out.write("\n");
out.write(" <li>\n");
out.write(" <a href=\"#\" data-rel=\"colorbox\">\n");
out.write(" <img alt=\"150x150\" src=\"assets/images/gallery/thumb-3.jpg\">\n");
out.write(" <div class=\"text\">\n");
out.write(" <div class=\"inner\">Sample Caption on Hover</div>\n");
out.write(" </div>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <div class=\"tools tools-bottom\">\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-link\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-paperclip\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-pencil\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-times red\"></i>\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write(" </li>\n");
out.write("\n");
out.write(" <li>\n");
out.write(" <a href=\"#\" data-rel=\"colorbox\">\n");
out.write(" <img alt=\"150x150\" src=\"assets/images/gallery/thumb-4.jpg\">\n");
out.write(" <div class=\"text\">\n");
out.write(" <div class=\"inner\">Sample Caption on Hover</div>\n");
out.write(" </div>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <div class=\"tools tools-bottom\">\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-link\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-paperclip\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-pencil\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-times red\"></i>\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write(" </li>\n");
out.write("\n");
out.write(" <li>\n");
out.write(" <a href=\"#\" data-rel=\"colorbox\">\n");
out.write(" <img alt=\"150x150\" src=\"assets/images/gallery/thumb-5.jpg\">\n");
out.write(" <div class=\"text\">\n");
out.write(" <div class=\"inner\">Sample Caption on Hover</div>\n");
out.write(" </div>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <div class=\"tools tools-bottom\">\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-link\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-paperclip\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-pencil\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-times red\"></i>\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write(" </li>\n");
out.write("\n");
out.write(" <li>\n");
out.write(" <a href=\"#\" data-rel=\"colorbox\">\n");
out.write(" <img alt=\"150x150\" src=\"assets/images/gallery/thumb-6.jpg\">\n");
out.write(" <div class=\"text\">\n");
out.write(" <div class=\"inner\">Sample Caption on Hover</div>\n");
out.write(" </div>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <div class=\"tools tools-bottom\">\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-link\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-paperclip\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-pencil\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-times red\"></i>\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write(" </li>\n");
out.write("\n");
out.write(" <li>\n");
out.write(" <a href=\"#\" data-rel=\"colorbox\">\n");
out.write(" <img alt=\"150x150\" src=\"assets/images/gallery/thumb-1.jpg\">\n");
out.write(" <div class=\"text\">\n");
out.write(" <div class=\"inner\">Sample Caption on Hover</div>\n");
out.write(" </div>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <div class=\"tools tools-bottom\">\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-link\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-paperclip\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-pencil\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-times red\"></i>\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write(" </li>\n");
out.write("\n");
out.write(" <li>\n");
out.write(" <a href=\"#\" data-rel=\"colorbox\">\n");
out.write(" <img alt=\"150x150\" src=\"assets/images/gallery/thumb-2.jpg\">\n");
out.write(" <div class=\"text\">\n");
out.write(" <div class=\"inner\">Sample Caption on Hover</div>\n");
out.write(" </div>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <div class=\"tools tools-bottom\">\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-link\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-paperclip\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-pencil\"></i>\n");
out.write(" </a>\n");
out.write("\n");
out.write(" <a href=\"#\">\n");
out.write(" <i class=\"ace-icon fa fa-times red\"></i>\n");
out.write(" </a>\n");
out.write(" </div>\n");
out.write(" </li>\n");
out.write(" </ul>\n");
out.write(" </div><!-- /#pictures -->\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" <!-- Botão coloca aqui todos a tab visualização -->\n");
out.write(" </div>\n");
if (request.getAttribute("msg") == "gravou") {
out.write("\n");
out.write(" <style>\n");
out.write(" #msg{visibility: visible;}\n");
out.write(" #ok{visibility: visible;} \n");
out.write(" #erro{visibility: hidden;}\n");
out.write(" </style>\n");
} else {
out.write("\n");
out.write(" <style>\n");
out.write(" #msg{visibility: hidden;}\n");
out.write(" </style>\n");
out.write("\n");
}
out.write("\n");
out.write(" \n");
out.write(" \n");
out.write(" \n");
out.write(" \n");
out.write(" \n");
out.write(" ");
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "include/footer.jsp", out, false);
out.write("\n");
out.write(" </div><!-- /.main-container --> \n");
out.write(" </body>\n");
out.write("</html>\n");
out.write("\n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
private boolean _jspx_meth_c_set_0(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_0 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_0.setPageContext(_jspx_page_context);
_jspx_th_c_set_0.setParent(null);
_jspx_th_c_set_0.setVar("acessoPerfil");
_jspx_th_c_set_0.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${sessionPerfil}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_0 = _jspx_th_c_set_0.doStartTag();
if (_jspx_th_c_set_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_0);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_0);
return false;
}
private boolean _jspx_meth_c_choose_0(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_0 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_0.setPageContext(_jspx_page_context);
_jspx_th_c_choose_0.setParent(null);
int _jspx_eval_c_choose_0 = _jspx_th_c_choose_0.doStartTag();
if (_jspx_eval_c_choose_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_when_0((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_0, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_when_1((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_0, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_when_2((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_0, _jspx_page_context))
return true;
out.write('\r');
out.write('\n');
int evalDoAfterBody = _jspx_th_c_choose_0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_0);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_0);
return false;
}
private boolean _jspx_meth_c_when_0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_0, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_0 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_0.setPageContext(_jspx_page_context);
_jspx_th_c_when_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_0);
_jspx_th_c_when_0.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${sessionLogin == '' || sessionLogin == null}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_0 = _jspx_th_c_when_0.doStartTag();
if (_jspx_eval_c_when_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_redirect_0((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_0, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_0);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_0);
return false;
}
private boolean _jspx_meth_c_redirect_0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_0, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:redirect
org.apache.taglibs.standard.tag.rt.core.RedirectTag _jspx_th_c_redirect_0 = (org.apache.taglibs.standard.tag.rt.core.RedirectTag) _jspx_tagPool_c_redirect_url_nobody.get(org.apache.taglibs.standard.tag.rt.core.RedirectTag.class);
_jspx_th_c_redirect_0.setPageContext(_jspx_page_context);
_jspx_th_c_redirect_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_0);
_jspx_th_c_redirect_0.setUrl("/AcessoNegado.jsp");
int _jspx_eval_c_redirect_0 = _jspx_th_c_redirect_0.doStartTag();
if (_jspx_th_c_redirect_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_redirect_url_nobody.reuse(_jspx_th_c_redirect_0);
return true;
}
_jspx_tagPool_c_redirect_url_nobody.reuse(_jspx_th_c_redirect_0);
return false;
}
private boolean _jspx_meth_c_when_1(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_0, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_1 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_1.setPageContext(_jspx_page_context);
_jspx_th_c_when_1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_0);
_jspx_th_c_when_1.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${sessionPerfil != acessoPerfil}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_1 = _jspx_th_c_when_1.doStartTag();
if (_jspx_eval_c_when_1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_set_1((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_1, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_redirect_1((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_1, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_1.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_1);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_1);
return false;
}
private boolean _jspx_meth_c_set_1(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_1, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_1 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_scope_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_1.setPageContext(_jspx_page_context);
_jspx_th_c_set_1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_1);
_jspx_th_c_set_1.setVar("msg3");
_jspx_th_c_set_1.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${true}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
_jspx_th_c_set_1.setScope("session");
int _jspx_eval_c_set_1 = _jspx_th_c_set_1.doStartTag();
if (_jspx_th_c_set_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_scope_nobody.reuse(_jspx_th_c_set_1);
return true;
}
_jspx_tagPool_c_set_var_value_scope_nobody.reuse(_jspx_th_c_set_1);
return false;
}
private boolean _jspx_meth_c_redirect_1(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_1, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:redirect
org.apache.taglibs.standard.tag.rt.core.RedirectTag _jspx_th_c_redirect_1 = (org.apache.taglibs.standard.tag.rt.core.RedirectTag) _jspx_tagPool_c_redirect_url_nobody.get(org.apache.taglibs.standard.tag.rt.core.RedirectTag.class);
_jspx_th_c_redirect_1.setPageContext(_jspx_page_context);
_jspx_th_c_redirect_1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_1);
_jspx_th_c_redirect_1.setUrl("/AcessoNegado.jsp");
int _jspx_eval_c_redirect_1 = _jspx_th_c_redirect_1.doStartTag();
if (_jspx_th_c_redirect_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_redirect_url_nobody.reuse(_jspx_th_c_redirect_1);
return true;
}
_jspx_tagPool_c_redirect_url_nobody.reuse(_jspx_th_c_redirect_1);
return false;
}
private boolean _jspx_meth_c_when_2(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_0, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_2 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_2.setPageContext(_jspx_page_context);
_jspx_th_c_when_2.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_0);
_jspx_th_c_when_2.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${sessionStatus == 0}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_2 = _jspx_th_c_when_2.doStartTag();
if (_jspx_eval_c_when_2 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_set_2((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_2, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_redirect_2((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_2, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_2.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_2);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_2);
return false;
}
private boolean _jspx_meth_c_set_2(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_2, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_2 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_scope_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_2.setPageContext(_jspx_page_context);
_jspx_th_c_set_2.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_2);
_jspx_th_c_set_2.setVar("msg");
_jspx_th_c_set_2.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${true}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
_jspx_th_c_set_2.setScope("session");
int _jspx_eval_c_set_2 = _jspx_th_c_set_2.doStartTag();
if (_jspx_th_c_set_2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_scope_nobody.reuse(_jspx_th_c_set_2);
return true;
}
_jspx_tagPool_c_set_var_value_scope_nobody.reuse(_jspx_th_c_set_2);
return false;
}
private boolean _jspx_meth_c_redirect_2(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_2, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:redirect
org.apache.taglibs.standard.tag.rt.core.RedirectTag _jspx_th_c_redirect_2 = (org.apache.taglibs.standard.tag.rt.core.RedirectTag) _jspx_tagPool_c_redirect_url_nobody.get(org.apache.taglibs.standard.tag.rt.core.RedirectTag.class);
_jspx_th_c_redirect_2.setPageContext(_jspx_page_context);
_jspx_th_c_redirect_2.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_2);
_jspx_th_c_redirect_2.setUrl("/AcessoNegado.jsp");
int _jspx_eval_c_redirect_2 = _jspx_th_c_redirect_2.doStartTag();
if (_jspx_th_c_redirect_2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_redirect_url_nobody.reuse(_jspx_th_c_redirect_2);
return true;
}
_jspx_tagPool_c_redirect_url_nobody.reuse(_jspx_th_c_redirect_2);
return false;
}
private boolean _jspx_meth_c_set_3(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_3 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_3.setPageContext(_jspx_page_context);
_jspx_th_c_set_3.setParent(null);
_jspx_th_c_set_3.setVar("pg");
_jspx_th_c_set_3.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${param.pg}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_3 = _jspx_th_c_set_3.doStartTag();
if (_jspx_th_c_set_3.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_3);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_3);
return false;
}
private boolean _jspx_meth_c_set_4(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_4 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_4.setPageContext(_jspx_page_context);
_jspx_th_c_set_4.setParent(null);
_jspx_th_c_set_4.setVar("pf");
_jspx_th_c_set_4.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${param.pf}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_4 = _jspx_th_c_set_4.doStartTag();
if (_jspx_th_c_set_4.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_4);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_4);
return false;
}
private boolean _jspx_meth_c_set_5(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_5 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_5.setPageContext(_jspx_page_context);
_jspx_th_c_set_5.setParent(null);
_jspx_th_c_set_5.setVar("pi");
_jspx_th_c_set_5.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${param.pi}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_5 = _jspx_th_c_set_5.doStartTag();
if (_jspx_th_c_set_5.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_5);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_5);
return false;
}
private boolean _jspx_meth_c_set_6(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_6 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_6.setPageContext(_jspx_page_context);
_jspx_th_c_set_6.setParent(null);
_jspx_th_c_set_6.setVar("q");
_jspx_th_c_set_6.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${param.q}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_6 = _jspx_th_c_set_6.doStartTag();
if (_jspx_th_c_set_6.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_6);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_6);
return false;
}
private boolean _jspx_meth_c_set_7(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_7 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_7.setPageContext(_jspx_page_context);
_jspx_th_c_set_7.setParent(null);
_jspx_th_c_set_7.setVar("sgDivisao");
_jspx_th_c_set_7.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${param.sgDivisao}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_7 = _jspx_th_c_set_7.doStartTag();
if (_jspx_th_c_set_7.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_7);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_7);
return false;
}
private boolean _jspx_meth_c_set_8(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_8 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_8.setPageContext(_jspx_page_context);
_jspx_th_c_set_8.setParent(null);
_jspx_th_c_set_8.setVar("alt");
_jspx_th_c_set_8.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${param.alt}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_8 = _jspx_th_c_set_8.doStartTag();
if (_jspx_th_c_set_8.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_8);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_8);
return false;
}
private boolean _jspx_meth_c_set_9(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_9 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_9.setPageContext(_jspx_page_context);
_jspx_th_c_set_9.setParent(null);
_jspx_th_c_set_9.setVar("idDivisaoCombo");
_jspx_th_c_set_9.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${param.idDivisaoCombo}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_9 = _jspx_th_c_set_9.doStartTag();
if (_jspx_th_c_set_9.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_9);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_9);
return false;
}
private boolean _jspx_meth_c_choose_1(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_1 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_1.setPageContext(_jspx_page_context);
_jspx_th_c_choose_1.setParent(null);
int _jspx_eval_c_choose_1 = _jspx_th_c_choose_1.doStartTag();
if (_jspx_eval_c_choose_1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_3((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_1, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_0((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_1, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_1.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_1);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_1);
return false;
}
private boolean _jspx_meth_c_when_3(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_1, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_3 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_3.setPageContext(_jspx_page_context);
_jspx_th_c_when_3.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_1);
_jspx_th_c_when_3.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${alt == 'alt'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_3 = _jspx_th_c_when_3.doStartTag();
if (_jspx_eval_c_when_3 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <input type=\"text\" id=\"form-field-1\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${us.nmNome}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" name=\"nome\" placeholder=\"Nome completo\" class=\"col-xs-12 col-sm-12\" required=\"required\">\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_3.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_3.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_3);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_3);
return false;
}
private boolean _jspx_meth_c_otherwise_0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_1, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_0 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_0.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_1);
int _jspx_eval_c_otherwise_0 = _jspx_th_c_otherwise_0.doStartTag();
if (_jspx_eval_c_otherwise_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"middle\">");
if (_jspx_meth_c_out_0((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_otherwise_0, _jspx_page_context))
return true;
out.write("</span>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_0);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_0);
return false;
}
private boolean _jspx_meth_c_out_0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_otherwise_0, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:out
org.apache.taglibs.standard.tag.rt.core.OutTag _jspx_th_c_out_0 = (org.apache.taglibs.standard.tag.rt.core.OutTag) _jspx_tagPool_c_out_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.OutTag.class);
_jspx_th_c_out_0.setPageContext(_jspx_page_context);
_jspx_th_c_out_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_otherwise_0);
_jspx_th_c_out_0.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${us.nmNome}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_out_0 = _jspx_th_c_out_0.doStartTag();
if (_jspx_th_c_out_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_0);
return true;
}
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_0);
return false;
}
private boolean _jspx_meth_c_choose_2(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_2 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_2.setPageContext(_jspx_page_context);
_jspx_th_c_choose_2.setParent(null);
int _jspx_eval_c_choose_2 = _jspx_th_c_choose_2.doStartTag();
if (_jspx_eval_c_choose_2 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_4((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_2, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_1((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_2, _jspx_page_context))
return true;
out.write(" \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_2.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_2);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_2);
return false;
}
private boolean _jspx_meth_c_when_4(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_2, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_4 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_4.setPageContext(_jspx_page_context);
_jspx_th_c_when_4.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_2);
_jspx_th_c_when_4.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${alt == 'alt'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_4 = _jspx_th_c_when_4.doStartTag();
if (_jspx_eval_c_when_4 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <input type=\"text\" id=\"form-field-1\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${us.nmLogin}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" name=\"login\" placeholder=\"d00000 ou x00000\" class=\"col-xs-10 col-sm-12\" required=\"required\">\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_4.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_4.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_4);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_4);
return false;
}
private boolean _jspx_meth_c_otherwise_1(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_2, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_1 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_1.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_2);
int _jspx_eval_c_otherwise_1 = _jspx_th_c_otherwise_1.doStartTag();
if (_jspx_eval_c_otherwise_1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span>");
if (_jspx_meth_c_out_1((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_otherwise_1, _jspx_page_context))
return true;
out.write("</span>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_1.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_1);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_1);
return false;
}
private boolean _jspx_meth_c_out_1(javax.servlet.jsp.tagext.JspTag _jspx_th_c_otherwise_1, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:out
org.apache.taglibs.standard.tag.rt.core.OutTag _jspx_th_c_out_1 = (org.apache.taglibs.standard.tag.rt.core.OutTag) _jspx_tagPool_c_out_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.OutTag.class);
_jspx_th_c_out_1.setPageContext(_jspx_page_context);
_jspx_th_c_out_1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_otherwise_1);
_jspx_th_c_out_1.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${us.nmLogin}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_out_1 = _jspx_th_c_out_1.doStartTag();
if (_jspx_th_c_out_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_1);
return true;
}
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_1);
return false;
}
private boolean _jspx_meth_c_choose_3(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_3 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_3.setPageContext(_jspx_page_context);
_jspx_th_c_choose_3.setParent(null);
int _jspx_eval_c_choose_3 = _jspx_th_c_choose_3.doStartTag();
if (_jspx_eval_c_choose_3 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_5((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_3, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_2((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_3, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_3.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_3.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_3);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_3);
return false;
}
private boolean _jspx_meth_c_when_5(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_3, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_5 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_5.setPageContext(_jspx_page_context);
_jspx_th_c_when_5.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_3);
_jspx_th_c_when_5.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${alt == 'alt'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_5 = _jspx_th_c_when_5.doStartTag();
if (_jspx_eval_c_when_5 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <input type=\"text\" id=\"form-field-1\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${us.nmRf}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" name=\"rf\" placeholder=\"000.000.0\" class=\"col-xs-10 col-sm-12\" required=\"required\">\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_5.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_5.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_5);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_5);
return false;
}
private boolean _jspx_meth_c_otherwise_2(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_3, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_2 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_2.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_2.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_3);
int _jspx_eval_c_otherwise_2 = _jspx_th_c_otherwise_2.doStartTag();
if (_jspx_eval_c_otherwise_2 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span>");
if (_jspx_meth_c_out_2((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_otherwise_2, _jspx_page_context))
return true;
out.write("</span>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_2.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_2);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_2);
return false;
}
private boolean _jspx_meth_c_out_2(javax.servlet.jsp.tagext.JspTag _jspx_th_c_otherwise_2, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:out
org.apache.taglibs.standard.tag.rt.core.OutTag _jspx_th_c_out_2 = (org.apache.taglibs.standard.tag.rt.core.OutTag) _jspx_tagPool_c_out_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.OutTag.class);
_jspx_th_c_out_2.setPageContext(_jspx_page_context);
_jspx_th_c_out_2.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_otherwise_2);
_jspx_th_c_out_2.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${us.nmRf}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_out_2 = _jspx_th_c_out_2.doStartTag();
if (_jspx_th_c_out_2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_2);
return true;
}
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_2);
return false;
}
private boolean _jspx_meth_c_choose_4(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_4 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_4.setPageContext(_jspx_page_context);
_jspx_th_c_choose_4.setParent(null);
int _jspx_eval_c_choose_4 = _jspx_th_c_choose_4.doStartTag();
if (_jspx_eval_c_choose_4 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_6((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_4, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_3((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_4, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_4.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_4.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_4);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_4);
return false;
}
private boolean _jspx_meth_c_when_6(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_4, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_6 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_6.setPageContext(_jspx_page_context);
_jspx_th_c_when_6.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_4);
_jspx_th_c_when_6.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${alt == 'alt'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_6 = _jspx_th_c_when_6.doStartTag();
if (_jspx_eval_c_when_6 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <input type=\"email\" id=\"form-field-1\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${us.nmEmail}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" name=\"email\" placeholder=\"e-mail\" class=\"col-xs-12 col-sm-12\" required=\"required\">\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_6.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_6.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_6);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_6);
return false;
}
private boolean _jspx_meth_c_otherwise_3(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_4, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_3 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_3.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_3.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_4);
int _jspx_eval_c_otherwise_3 = _jspx_th_c_otherwise_3.doStartTag();
if (_jspx_eval_c_otherwise_3 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span>");
if (_jspx_meth_c_out_3((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_otherwise_3, _jspx_page_context))
return true;
out.write("</span>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_3.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_3.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_3);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_3);
return false;
}
private boolean _jspx_meth_c_out_3(javax.servlet.jsp.tagext.JspTag _jspx_th_c_otherwise_3, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:out
org.apache.taglibs.standard.tag.rt.core.OutTag _jspx_th_c_out_3 = (org.apache.taglibs.standard.tag.rt.core.OutTag) _jspx_tagPool_c_out_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.OutTag.class);
_jspx_th_c_out_3.setPageContext(_jspx_page_context);
_jspx_th_c_out_3.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_otherwise_3);
_jspx_th_c_out_3.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${us.nmEmail}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_out_3 = _jspx_th_c_out_3.doStartTag();
if (_jspx_th_c_out_3.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_3);
return true;
}
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_3);
return false;
}
private boolean _jspx_meth_c_choose_5(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_5 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_5.setPageContext(_jspx_page_context);
_jspx_th_c_choose_5.setParent(null);
int _jspx_eval_c_choose_5 = _jspx_th_c_choose_5.doStartTag();
if (_jspx_eval_c_choose_5 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_7((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_5, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_4((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_5, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_5.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_5.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_5);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_5);
return false;
}
private boolean _jspx_meth_c_when_7(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_5, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_7 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_7.setPageContext(_jspx_page_context);
_jspx_th_c_when_7.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_5);
_jspx_th_c_when_7.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${alt == 'alt' && sessionPerfil == 'Administrador'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_7 = _jspx_th_c_when_7.doStartTag();
if (_jspx_eval_c_when_7 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <select class=\"form-control col-xs-12 col-sm-12\" id=\"form-field-select-1\" name=\"divisao\" onChange=\"pkDivisao(this)\" required=\"required\">\n");
out.write(" <option value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${us.pkDivisao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" title=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${us.nmDivisao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" selected=\"selected\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${us.sgDivisao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write(" - ");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${us.nmDivisao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</option>\n");
out.write(" <option></option>\n");
out.write(" ");
if (_jspx_meth_c_forEach_0((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_7, _jspx_page_context))
return true;
out.write("\n");
out.write(" </select>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_7.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_7.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_7);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_7);
return false;
}
private boolean _jspx_meth_c_forEach_0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_7, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:forEach
org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_forEach_0 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _jspx_tagPool_c_forEach_var_items.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class);
_jspx_th_c_forEach_0.setPageContext(_jspx_page_context);
_jspx_th_c_forEach_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_7);
_jspx_th_c_forEach_0.setVar("d");
_jspx_th_c_forEach_0.setItems((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${listDivisao}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int[] _jspx_push_body_count_c_forEach_0 = new int[] { 0 };
try {
int _jspx_eval_c_forEach_0 = _jspx_th_c_forEach_0.doStartTag();
if (_jspx_eval_c_forEach_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <option value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${d.pkDivisao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" title=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${d.nmDivisao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write('"');
out.write('>');
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${d.sgDivisao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write(" - ");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${d.nmDivisao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</option> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_forEach_0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_forEach_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_c_forEach_0[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_c_forEach_0.doCatch(_jspx_exception);
} finally {
_jspx_th_c_forEach_0.doFinally();
_jspx_tagPool_c_forEach_var_items.reuse(_jspx_th_c_forEach_0);
}
return false;
}
private boolean _jspx_meth_c_otherwise_4(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_5, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_4 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_4.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_4.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_5);
int _jspx_eval_c_otherwise_4 = _jspx_th_c_otherwise_4.doStartTag();
if (_jspx_eval_c_otherwise_4 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <input type=\"hidden\" name=\"divisao\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${us.pkDivisao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" />\n");
out.write(" <span>");
if (_jspx_meth_c_out_4((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_otherwise_4, _jspx_page_context))
return true;
out.write("</span>\n");
out.write(" <span> ");
if (_jspx_meth_c_out_5((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_otherwise_4, _jspx_page_context))
return true;
out.write("</span>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_4.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_4.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_4);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_4);
return false;
}
private boolean _jspx_meth_c_out_4(javax.servlet.jsp.tagext.JspTag _jspx_th_c_otherwise_4, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:out
org.apache.taglibs.standard.tag.rt.core.OutTag _jspx_th_c_out_4 = (org.apache.taglibs.standard.tag.rt.core.OutTag) _jspx_tagPool_c_out_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.OutTag.class);
_jspx_th_c_out_4.setPageContext(_jspx_page_context);
_jspx_th_c_out_4.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_otherwise_4);
_jspx_th_c_out_4.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${us.sgDivisao}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_out_4 = _jspx_th_c_out_4.doStartTag();
if (_jspx_th_c_out_4.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_4);
return true;
}
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_4);
return false;
}
private boolean _jspx_meth_c_out_5(javax.servlet.jsp.tagext.JspTag _jspx_th_c_otherwise_4, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:out
org.apache.taglibs.standard.tag.rt.core.OutTag _jspx_th_c_out_5 = (org.apache.taglibs.standard.tag.rt.core.OutTag) _jspx_tagPool_c_out_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.OutTag.class);
_jspx_th_c_out_5.setPageContext(_jspx_page_context);
_jspx_th_c_out_5.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_otherwise_4);
_jspx_th_c_out_5.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${us.nmDivisao}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_out_5 = _jspx_th_c_out_5.doStartTag();
if (_jspx_th_c_out_5.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_5);
return true;
}
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_5);
return false;
}
private boolean _jspx_meth_c_choose_6(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_6 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_6.setPageContext(_jspx_page_context);
_jspx_th_c_choose_6.setParent(null);
int _jspx_eval_c_choose_6 = _jspx_th_c_choose_6.doStartTag();
if (_jspx_eval_c_choose_6 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_8((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_6, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_5((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_6, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_6.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_6.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_6);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_6);
return false;
}
private boolean _jspx_meth_c_when_8(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_6, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_8 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_8.setPageContext(_jspx_page_context);
_jspx_th_c_when_8.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_6);
_jspx_th_c_when_8.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${alt == 'alt'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_8 = _jspx_th_c_when_8.doStartTag();
if (_jspx_eval_c_when_8 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <div id=\"selectSetor\" >\n");
out.write(" <select class=\"form-control col-xs-12 col-sm-12\" name=\"setor\" required=\"required\">\n");
out.write(" <option value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${us.pkSetor}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" title=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${us.nmSetor}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" selected=\"selected\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${us.sgSetor}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write(" - ");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${us.nmSetor}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</option>\n");
out.write(" ");
if (_jspx_meth_c_forEach_1((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_8, _jspx_page_context))
return true;
out.write("\n");
out.write(" </select>\n");
out.write(" </div>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_8.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_8.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_8);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_8);
return false;
}
private boolean _jspx_meth_c_forEach_1(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_8, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:forEach
org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_forEach_1 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _jspx_tagPool_c_forEach_var_items.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class);
_jspx_th_c_forEach_1.setPageContext(_jspx_page_context);
_jspx_th_c_forEach_1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_8);
_jspx_th_c_forEach_1.setVar("s");
_jspx_th_c_forEach_1.setItems((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${listSetor}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int[] _jspx_push_body_count_c_forEach_1 = new int[] { 0 };
try {
int _jspx_eval_c_forEach_1 = _jspx_th_c_forEach_1.doStartTag();
if (_jspx_eval_c_forEach_1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <option value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${s.pkSetor}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" title=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${s.nmSetor}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write('"');
out.write('>');
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${s.sgSetor}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write(" - ");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${s.nmSetor}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</option> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_forEach_1.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_forEach_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_c_forEach_1[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_c_forEach_1.doCatch(_jspx_exception);
} finally {
_jspx_th_c_forEach_1.doFinally();
_jspx_tagPool_c_forEach_var_items.reuse(_jspx_th_c_forEach_1);
}
return false;
}
private boolean _jspx_meth_c_otherwise_5(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_6, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_5 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_5.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_5.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_6);
int _jspx_eval_c_otherwise_5 = _jspx_th_c_otherwise_5.doStartTag();
if (_jspx_eval_c_otherwise_5 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span>\n");
out.write(" ");
if (_jspx_meth_c_if_0((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_otherwise_5, _jspx_page_context))
return true;
out.write("\n");
out.write(" </span>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_5.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_5.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_5);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_5);
return false;
}
private boolean _jspx_meth_c_if_0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_otherwise_5, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_0 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_0.setPageContext(_jspx_page_context);
_jspx_th_c_if_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_otherwise_5);
_jspx_th_c_if_0.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${not empty us.nmSetor}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_0 = _jspx_th_c_if_0.doStartTag();
if (_jspx_eval_c_if_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_out_6((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_if_0, _jspx_page_context))
return true;
out.write(" - ");
if (_jspx_meth_c_out_7((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_if_0, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_if_0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_0);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_0);
return false;
}
private boolean _jspx_meth_c_out_6(javax.servlet.jsp.tagext.JspTag _jspx_th_c_if_0, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:out
org.apache.taglibs.standard.tag.rt.core.OutTag _jspx_th_c_out_6 = (org.apache.taglibs.standard.tag.rt.core.OutTag) _jspx_tagPool_c_out_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.OutTag.class);
_jspx_th_c_out_6.setPageContext(_jspx_page_context);
_jspx_th_c_out_6.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_if_0);
_jspx_th_c_out_6.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${us.sgSetor}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_out_6 = _jspx_th_c_out_6.doStartTag();
if (_jspx_th_c_out_6.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_6);
return true;
}
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_6);
return false;
}
private boolean _jspx_meth_c_out_7(javax.servlet.jsp.tagext.JspTag _jspx_th_c_if_0, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:out
org.apache.taglibs.standard.tag.rt.core.OutTag _jspx_th_c_out_7 = (org.apache.taglibs.standard.tag.rt.core.OutTag) _jspx_tagPool_c_out_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.OutTag.class);
_jspx_th_c_out_7.setPageContext(_jspx_page_context);
_jspx_th_c_out_7.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_if_0);
_jspx_th_c_out_7.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${us.nmSetor}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_out_7 = _jspx_th_c_out_7.doStartTag();
if (_jspx_th_c_out_7.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_7);
return true;
}
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_7);
return false;
}
private boolean _jspx_meth_c_choose_7(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_7 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_7.setPageContext(_jspx_page_context);
_jspx_th_c_choose_7.setParent(null);
int _jspx_eval_c_choose_7 = _jspx_th_c_choose_7.doStartTag();
if (_jspx_eval_c_choose_7 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_9((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_7, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_6((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_7, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_7.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_7.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_7);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_7);
return false;
}
private boolean _jspx_meth_c_when_9(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_7, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_9 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_9.setPageContext(_jspx_page_context);
_jspx_th_c_when_9.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_7);
_jspx_th_c_when_9.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${alt == 'alt'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_9 = _jspx_th_c_when_9.doStartTag();
if (_jspx_eval_c_when_9 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <select class=\"form-control col-xs-12 col-sm-12\" id=\"form-field-select-1\" name=\"cargo\" required=\"required\">\n");
out.write(" <option value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${us.pkCargo}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write('"');
out.write('>');
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${us.nmCargo}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</option>\n");
out.write(" <option></option>\n");
out.write(" ");
if (_jspx_meth_c_forEach_2((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_9, _jspx_page_context))
return true;
out.write("\n");
out.write(" </select>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_9.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_9.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_9);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_9);
return false;
}
private boolean _jspx_meth_c_forEach_2(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_9, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:forEach
org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_forEach_2 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _jspx_tagPool_c_forEach_var_items.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class);
_jspx_th_c_forEach_2.setPageContext(_jspx_page_context);
_jspx_th_c_forEach_2.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_9);
_jspx_th_c_forEach_2.setVar("c");
_jspx_th_c_forEach_2.setItems((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${listCargo}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int[] _jspx_push_body_count_c_forEach_2 = new int[] { 0 };
try {
int _jspx_eval_c_forEach_2 = _jspx_th_c_forEach_2.doStartTag();
if (_jspx_eval_c_forEach_2 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <option value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${c.pkCargo}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" title=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${c.dsCargo}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write('"');
out.write('>');
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${c.nmCargo}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</option> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_forEach_2.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_forEach_2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_c_forEach_2[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_c_forEach_2.doCatch(_jspx_exception);
} finally {
_jspx_th_c_forEach_2.doFinally();
_jspx_tagPool_c_forEach_var_items.reuse(_jspx_th_c_forEach_2);
}
return false;
}
private boolean _jspx_meth_c_otherwise_6(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_7, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_6 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_6.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_6.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_7);
int _jspx_eval_c_otherwise_6 = _jspx_th_c_otherwise_6.doStartTag();
if (_jspx_eval_c_otherwise_6 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span>");
if (_jspx_meth_c_out_8((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_otherwise_6, _jspx_page_context))
return true;
out.write("</span>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_6.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_6.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_6);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_6);
return false;
}
private boolean _jspx_meth_c_out_8(javax.servlet.jsp.tagext.JspTag _jspx_th_c_otherwise_6, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:out
org.apache.taglibs.standard.tag.rt.core.OutTag _jspx_th_c_out_8 = (org.apache.taglibs.standard.tag.rt.core.OutTag) _jspx_tagPool_c_out_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.OutTag.class);
_jspx_th_c_out_8.setPageContext(_jspx_page_context);
_jspx_th_c_out_8.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_otherwise_6);
_jspx_th_c_out_8.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${us.nmCargo}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_out_8 = _jspx_th_c_out_8.doStartTag();
if (_jspx_th_c_out_8.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_8);
return true;
}
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_8);
return false;
}
private boolean _jspx_meth_c_choose_8(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_8 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_8.setPageContext(_jspx_page_context);
_jspx_th_c_choose_8.setParent(null);
int _jspx_eval_c_choose_8 = _jspx_th_c_choose_8.doStartTag();
if (_jspx_eval_c_choose_8 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_10((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_8, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_7((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_8, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_8.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_8.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_8);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_8);
return false;
}
private boolean _jspx_meth_c_when_10(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_8, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_10 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_10.setPageContext(_jspx_page_context);
_jspx_th_c_when_10.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_8);
_jspx_th_c_when_10.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${alt == 'alt'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_10 = _jspx_th_c_when_10.doStartTag();
if (_jspx_eval_c_when_10 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <select class=\"form-control col-xs-12 col-sm-12\" id=\"form-field-select-1\" name=\"perfil\" required=\"required\">\n");
out.write(" <option value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${us.pkPerfil}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write('"');
out.write('>');
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${us.nmPerfil}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</option>\n");
out.write(" <option></option>\n");
out.write(" ");
if (_jspx_meth_c_forEach_3((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_10, _jspx_page_context))
return true;
out.write("\n");
out.write(" </select>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_10.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_10.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_10);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_10);
return false;
}
private boolean _jspx_meth_c_forEach_3(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_10, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:forEach
org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_forEach_3 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _jspx_tagPool_c_forEach_var_items.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class);
_jspx_th_c_forEach_3.setPageContext(_jspx_page_context);
_jspx_th_c_forEach_3.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_10);
_jspx_th_c_forEach_3.setVar("p");
_jspx_th_c_forEach_3.setItems((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${listPerfil}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int[] _jspx_push_body_count_c_forEach_3 = new int[] { 0 };
try {
int _jspx_eval_c_forEach_3 = _jspx_th_c_forEach_3.doStartTag();
if (_jspx_eval_c_forEach_3 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <option value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${p.pkPerfil}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" title=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${p.dsPerfil}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write('"');
out.write('>');
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${p.nmPerfil}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</option> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_forEach_3.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_forEach_3.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_c_forEach_3[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_c_forEach_3.doCatch(_jspx_exception);
} finally {
_jspx_th_c_forEach_3.doFinally();
_jspx_tagPool_c_forEach_var_items.reuse(_jspx_th_c_forEach_3);
}
return false;
}
private boolean _jspx_meth_c_otherwise_7(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_8, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_7 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_7.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_7.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_8);
int _jspx_eval_c_otherwise_7 = _jspx_th_c_otherwise_7.doStartTag();
if (_jspx_eval_c_otherwise_7 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span>");
if (_jspx_meth_c_out_9((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_otherwise_7, _jspx_page_context))
return true;
out.write("</span>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_7.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_7.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_7);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_7);
return false;
}
private boolean _jspx_meth_c_out_9(javax.servlet.jsp.tagext.JspTag _jspx_th_c_otherwise_7, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:out
org.apache.taglibs.standard.tag.rt.core.OutTag _jspx_th_c_out_9 = (org.apache.taglibs.standard.tag.rt.core.OutTag) _jspx_tagPool_c_out_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.OutTag.class);
_jspx_th_c_out_9.setPageContext(_jspx_page_context);
_jspx_th_c_out_9.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_otherwise_7);
_jspx_th_c_out_9.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${us.nmPerfil}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_out_9 = _jspx_th_c_out_9.doStartTag();
if (_jspx_th_c_out_9.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_9);
return true;
}
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_9);
return false;
}
private boolean _jspx_meth_c_choose_9(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_9 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_9.setPageContext(_jspx_page_context);
_jspx_th_c_choose_9.setParent(null);
int _jspx_eval_c_choose_9 = _jspx_th_c_choose_9.doStartTag();
if (_jspx_eval_c_choose_9 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_11((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_9, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_9((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_9, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_9.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_9.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_9);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_9);
return false;
}
private boolean _jspx_meth_c_when_11(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_9, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_11 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_11.setPageContext(_jspx_page_context);
_jspx_th_c_when_11.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_9);
_jspx_th_c_when_11.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${alt == 'alt'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_11 = _jspx_th_c_when_11.doStartTag();
if (_jspx_eval_c_when_11 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" \n");
out.write(" ");
if (_jspx_meth_c_choose_10((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_11, _jspx_page_context))
return true;
out.write("\n");
out.write(" \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_11.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_11.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_11);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_11);
return false;
}
private boolean _jspx_meth_c_choose_10(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_11, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_10 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_10.setPageContext(_jspx_page_context);
_jspx_th_c_choose_10.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_11);
int _jspx_eval_c_choose_10 = _jspx_th_c_choose_10.doStartTag();
if (_jspx_eval_c_choose_10 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_12((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_10, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_8((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_10, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_10.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_10.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_10);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_10);
return false;
}
private boolean _jspx_meth_c_when_12(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_10, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_12 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_12.setPageContext(_jspx_page_context);
_jspx_th_c_when_12.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_10);
_jspx_th_c_when_12.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${'0' == us.nrAtivo}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_12 = _jspx_th_c_when_12.doStartTag();
if (_jspx_eval_c_when_12 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <label class=\"pull-left inline\">\n");
out.write(" <input id=\"id-button-borders\" type=\"checkbox\" id=\"\" name=\"ativo\" value=\"1\" class=\"ace ace-switch ace-switch-5\" >\n");
out.write(" <span class=\"lbl middle\"></span>\n");
out.write(" </label> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_12.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_12.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_12);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_12);
return false;
}
private boolean _jspx_meth_c_otherwise_8(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_10, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_8 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_8.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_8.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_10);
int _jspx_eval_c_otherwise_8 = _jspx_th_c_otherwise_8.doStartTag();
if (_jspx_eval_c_otherwise_8 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <label class=\"pull-left inline\">\n");
out.write(" <small class=\"muted smaller-90\">Ativar:</small>\n");
out.write(" <input id=\"id-button-borders\" checked=\"checked\" type=\"checkbox\" class=\"ace ace-switch ace-switch-5\" id=\"\" name=\"ativo\" value=\"1\" >\n");
out.write(" <span class=\"lbl middle\"></span>\n");
out.write(" </label> \n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_8.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_8.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_8);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_8);
return false;
}
private boolean _jspx_meth_c_otherwise_9(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_9, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_9 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_9.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_9.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_9);
int _jspx_eval_c_otherwise_9 = _jspx_th_c_otherwise_9.doStartTag();
if (_jspx_eval_c_otherwise_9 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_choose_11((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_otherwise_9, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_9.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_9.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_9);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_9);
return false;
}
private boolean _jspx_meth_c_choose_11(javax.servlet.jsp.tagext.JspTag _jspx_th_c_otherwise_9, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_11 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_11.setPageContext(_jspx_page_context);
_jspx_th_c_choose_11.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_otherwise_9);
int _jspx_eval_c_choose_11 = _jspx_th_c_choose_11.doStartTag();
if (_jspx_eval_c_choose_11 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" ");
if (_jspx_meth_c_when_13((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_11, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
if (_jspx_meth_c_otherwise_10((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_11, _jspx_page_context))
return true;
out.write("\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_11.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_11.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_11);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_11);
return false;
}
private boolean _jspx_meth_c_when_13(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_11, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_13 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_13.setPageContext(_jspx_page_context);
_jspx_th_c_when_13.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_11);
_jspx_th_c_when_13.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${'1' == us.nrAtivo}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_13 = _jspx_th_c_when_13.doStartTag();
if (_jspx_eval_c_when_13 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"label label-sm label-success\">Ativo</span>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_13.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_13.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_13);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_13);
return false;
}
private boolean _jspx_meth_c_otherwise_10(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_11, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_10 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_10.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_10.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_11);
int _jspx_eval_c_otherwise_10 = _jspx_th_c_otherwise_10.doStartTag();
if (_jspx_eval_c_otherwise_10 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <span class=\"label label-sm label-danger\">Desativado</span>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_10.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_10.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_10);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_10);
return false;
}
private boolean _jspx_meth_c_set_10(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_10 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_10.setPageContext(_jspx_page_context);
_jspx_th_c_set_10.setParent(null);
_jspx_th_c_set_10.setVar("dt");
_jspx_th_c_set_10.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${us.dthrAtualizacao}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_10 = _jspx_th_c_set_10.doStartTag();
if (_jspx_th_c_set_10.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_10);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_10);
return false;
}
private boolean _jspx_meth_fmt_parseDate_0(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// fmt:parseDate
org.apache.taglibs.standard.tag.rt.fmt.ParseDateTag _jspx_th_fmt_parseDate_0 = (org.apache.taglibs.standard.tag.rt.fmt.ParseDateTag) _jspx_tagPool_fmt_parseDate_var_value_pattern_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.ParseDateTag.class);
_jspx_th_fmt_parseDate_0.setPageContext(_jspx_page_context);
_jspx_th_fmt_parseDate_0.setParent(null);
_jspx_th_fmt_parseDate_0.setValue((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${dt}", java.lang.String.class, (PageContext)_jspx_page_context, null));
_jspx_th_fmt_parseDate_0.setVar("converteDT");
_jspx_th_fmt_parseDate_0.setPattern("yyyy-MM-dd HH:mm");
int _jspx_eval_fmt_parseDate_0 = _jspx_th_fmt_parseDate_0.doStartTag();
if (_jspx_th_fmt_parseDate_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_fmt_parseDate_var_value_pattern_nobody.reuse(_jspx_th_fmt_parseDate_0);
return true;
}
_jspx_tagPool_fmt_parseDate_var_value_pattern_nobody.reuse(_jspx_th_fmt_parseDate_0);
return false;
}
private boolean _jspx_meth_fmt_formatDate_0(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// fmt:formatDate
org.apache.taglibs.standard.tag.rt.fmt.FormatDateTag _jspx_th_fmt_formatDate_0 = (org.apache.taglibs.standard.tag.rt.fmt.FormatDateTag) _jspx_tagPool_fmt_formatDate_var_value_type_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.FormatDateTag.class);
_jspx_th_fmt_formatDate_0.setPageContext(_jspx_page_context);
_jspx_th_fmt_formatDate_0.setParent(null);
_jspx_th_fmt_formatDate_0.setType("both");
_jspx_th_fmt_formatDate_0.setValue((java.util.Date) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${converteDT}", java.util.Date.class, (PageContext)_jspx_page_context, null));
_jspx_th_fmt_formatDate_0.setVar("dtAtu");
int _jspx_eval_fmt_formatDate_0 = _jspx_th_fmt_formatDate_0.doStartTag();
if (_jspx_th_fmt_formatDate_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_fmt_formatDate_var_value_type_nobody.reuse(_jspx_th_fmt_formatDate_0);
return true;
}
_jspx_tagPool_fmt_formatDate_var_value_type_nobody.reuse(_jspx_th_fmt_formatDate_0);
return false;
}
private boolean _jspx_meth_c_out_10(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:out
org.apache.taglibs.standard.tag.rt.core.OutTag _jspx_th_c_out_10 = (org.apache.taglibs.standard.tag.rt.core.OutTag) _jspx_tagPool_c_out_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.OutTag.class);
_jspx_th_c_out_10.setPageContext(_jspx_page_context);
_jspx_th_c_out_10.setParent(null);
_jspx_th_c_out_10.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${dtAtu}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_out_10 = _jspx_th_c_out_10.doStartTag();
if (_jspx_th_c_out_10.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_10);
return true;
}
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_10);
return false;
}
private boolean _jspx_meth_c_if_1(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_1 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_1.setPageContext(_jspx_page_context);
_jspx_th_c_if_1.setParent(null);
_jspx_th_c_if_1.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${alt == 'alt'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_1 = _jspx_th_c_if_1.doStartTag();
if (_jspx_eval_c_if_1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <button class=\"btn btn-success\" type=\"submit\">\n");
out.write(" <i class=\"ace-icon fa fa-save bigger-110\"></i>\n");
out.write(" Salvar\n");
out.write(" </button>\n");
out.write(" <button class=\"btn\" type=\"reset\">\n");
out.write(" <i class=\"ace-icon fa fa-eraser bigger-110\"></i>\n");
out.write(" Limpar\n");
out.write(" </button>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_if_1.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_1);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_1);
return false;
}
}
<file_sep>/build/generated/src/org/apache/jsp/Erro_jsp.java
package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class Erro_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.List<String> _jspx_dependants;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_set_var_value_nobody;
private org.glassfish.jsp.api.ResourceInjector _jspx_resourceInjector;
public java.util.List<String> getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_jspx_tagPool_c_set_var_value_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
}
public void _jspDestroy() {
_jspx_tagPool_c_set_var_value_nobody.release();
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
Throwable exception = org.apache.jasper.runtime.JspRuntimeLibrary.getThrowable(request);
if (exception != null) {
response.setStatus((Integer)request.getAttribute("javax.servlet.error.status_code"));
}
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html charset=UTF-8;");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
_jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("<!DOCTYPE html>\r\n");
out.write("<html>\r\n");
out.write(" ");
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "include/head.jsp", out, false);
out.write("\r\n");
out.write(" <body class=\"no-skin\">\r\n");
out.write(" <div id=\"navbar\" class=\"navbar navbar-default ace-save-state\">\r\n");
out.write(" <div class=\"navbar-container ace-save-state\" id=\"navbar-container\">\r\n");
out.write(" <button type=\"button\" class=\"navbar-toggle menu-toggler pull-left\" id=\"menu-toggler\" data-target=\"#sidebar\">\r\n");
out.write(" <span class=\"sr-only\">Toggle sidebar</span>\r\n");
out.write(" <span class=\"icon-bar\"></span>\r\n");
out.write(" <span class=\"icon-bar\"></span>\r\n");
out.write(" <span class=\"icon-bar\"></span>\r\n");
out.write(" </button>\r\n");
out.write(" <div class=\"navbar-header pull-left\">\r\n");
out.write(" <a href=\"Index.jsp\" class=\"navbar-brand\">\r\n");
out.write(" <small><img src=\"img/logo.png\" height=\"6%\" width=\"6%\" title=\"CGPatri - Gerador de Indicadores\"> SG-PATRI - Sistema de Gestão das Áreas Públicas</small>\r\n");
out.write(" </a>\r\n");
out.write(" </div>\r\n");
out.write(" <!-- <div class=\"navbar-buttons navbar-header pull-right\" role=\"navigation\">\r\n");
out.write(" <ul class=\"nav ace-nav\">\r\n");
out.write(" <li class=\"light-blue dropdown-modal\">\r\n");
out.write(" <a data-toggle=\"dropdown\" href=\"#\" class=\"dropdown-toggle\">\r\n");
out.write(" <img class=\"nav-user-photo\" src=\"img/foto/user.jpg\" alt=\"\" title=\"foto \" />\r\n");
out.write(" <span class=\"user-info\">\r\n");
out.write(" <small>Bem vindo,</small>\r\n");
out.write(" </span>\r\n");
out.write(" <i class=\"ace-icon fa fa-caret-down\"></i>\r\n");
out.write(" </a>\r\n");
out.write(" <ul class=\"user-menu dropdown-menu-right dropdown-menu dropdown-yellow dropdown-caret dropdown-close\">\r\n");
out.write(" \r\n");
out.write(" <li>\r\n");
out.write(" <a href=\"Config.jsp\">\r\n");
out.write(" <i class=\"ace-icon fa fa-cog\"></i>\r\n");
out.write(" Configuração\r\n");
out.write(" </a>\r\n");
out.write(" </li>\r\n");
out.write(" \r\n");
out.write(" <li>\r\n");
out.write(" <a href=\"#\">\r\n");
out.write(" <i class=\"ace-icon fa fa-user\"></i>\r\n");
out.write(" Prefil\r\n");
out.write(" </a>\r\n");
out.write(" </li>\r\n");
out.write(" <li class=\"divider\"></li>\r\n");
out.write(" <li>\r\n");
out.write(" <a href=\"ControllerServlet?acao=UsuarioLogoff\">\r\n");
out.write(" <i class=\"ace-icon fa fa-power-off\"></i>\r\n");
out.write(" Logof\r\n");
out.write(" </a>\r\n");
out.write(" </li>\r\n");
out.write(" </ul>\r\n");
out.write(" </li>\r\n");
out.write(" </ul>\r\n");
out.write(" </div>-->\r\n");
out.write(" </div><!-- /.navbar-container -->\r\n");
out.write(" </div>\r\n");
out.write(" <div class=\"main-container ace-save-state\" id=\"main-container\">\r\n");
out.write(" \r\n");
out.write(" <!--<div class=\"breadcrumbs ace-save-state\" id=\"breadcrumbs\">\r\n");
out.write(" <ul class=\"breadcrumb\">\r\n");
out.write(" <li><i class=\"ace-icon fa fa-random\"></i> Erro</li>\r\n");
out.write(" </ul>\r\n");
out.write(" </div>-->\r\n");
out.write(" \r\n");
out.write(" <div class=\"page-content\">\r\n");
out.write(" <div class=\"row\">\r\n");
out.write(" <div class=\"col-xs-12\">\r\n");
out.write(" ");
if (_jspx_meth_c_set_0(_jspx_page_context))
return;
out.write("\r\n");
out.write(" <div class=\"well\">\r\n");
out.write(" <h1 class=\"grey lighter smaller\">\r\n");
out.write(" <span class=\"blue bigger-125\">\r\n");
out.write(" <i class=\"ace-icon fa fa-random\"></i>\r\n");
out.write(" Erro \r\n");
out.write(" </span>\r\n");
out.write(" inesperado no sistema!\r\n");
out.write(" </h1>\r\n");
out.write("\r\n");
out.write(" <hr>\r\n");
out.write(" <h3 class=\"lighter smaller\">\r\n");
out.write(" Iremos trabalhar \r\n");
out.write(" <i class=\"ace-icon fa fa-wrench icon-animated-wrench bigger-125\"></i>\r\n");
out.write(" para corrigir !\r\n");
out.write(" </h3>\r\n");
out.write("\r\n");
out.write(" <div class=\"space\"></div>\r\n");
out.write("\r\n");
out.write(" <div>\r\n");
out.write(" <h4 class=\"lighter smaller\">Por gentileza, nos ajude encaminhando o erro abaixo para o e-mail:</h4>\r\n");
out.write(" <ul class=\"list-unstyled spaced inline bigger-110 margin-15\">\r\n");
out.write(" <li>\r\n");
out.write(" <i class=\"ace-icon fa fa-envelope blue\"></i>\r\n");
out.write(" <a href=\"mailto:<EMAIL>?subject=Erro no SISGI\">Administrador do sistema.</a>\r\n");
out.write(" </li>\r\n");
out.write(" </ul>\r\n");
out.write(" </div>\r\n");
out.write(" <div class=\"col-sm-12 \">\r\n");
out.write(" <button class=\"btn btn-yellow right\" type=\"reset\" onclick=\" location.href='javascript:history.back()';\" title=\"Tela ínicial\">\r\n");
out.write(" <span class=\" fa fa-undo bigger-110\"></span>\r\n");
out.write(" </button> \r\n");
out.write(" </div>\r\n");
out.write(" <hr>\r\n");
out.write(" <div class=\"text-capitalize\">\r\n");
out.write(" ");
exception.printStackTrace(new java.io.PrintWriter(out));
out.write("\r\n");
out.write(" </div>\r\n");
out.write(" </div>\r\n");
out.write(" \r\n");
out.write(" \r\n");
out.write(" ");
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "include/footer.jsp", out, false);
out.write("\r\n");
out.write(" </div><!-- /.main-container --> \r\n");
out.write(" </body>\r\n");
out.write("</html>\r\n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
private boolean _jspx_meth_c_set_0(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_0 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_0.setPageContext(_jspx_page_context);
_jspx_th_c_set_0.setParent(null);
_jspx_th_c_set_0.setVar("exception");
_jspx_th_c_set_0.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${requestScope['javax.servlet.error.exception']}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_0 = _jspx_th_c_set_0.doStartTag();
if (_jspx_th_c_set_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_0);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_0);
return false;
}
}
<file_sep>/src/java/br/com/Controle/AutoCessaoLista.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.Controle;
import br.com.Modelo.AutoCessao;
import br.com.Modelo.AutoCessaoDAO;
import br.com.Modelo.Logica;
import br.com.Modelo.TipoAutoCessao;
import br.com.Modelo.TipoAutoCessaoDAO;
import br.com.Utilitario.Transformar;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author d732229
*/
public class AutoCessaoLista implements Logica{
@Override
public String executa(HttpServletRequest req,
HttpServletResponse res) throws Exception {
AutoCessaoDAO autoDAO = new AutoCessaoDAO();
TipoAutoCessaoDAO tpDAO = new TipoAutoCessaoDAO();
/**
* Atributos:
* pg = número da página atual
* pi = número da página inicial
* pf = número da página final
* qtdRegistro = quantidade de registro geral
* qtdPg = número de quantidade de páginas
* qtdLinha = número de quantidade de linhas por página
* maxPg = quantidade de paginação a ser exibida (1, 2 , 3 ...)
* sobraMaxPg = auxiliar para o calculdo da quantidade de pagina
* */
int pg, pi, pf, qtdRegistro, qtdPg, sobraMaxPg=0, offset, tpCessao=0;
int qtdLinha = 6;
int maxPg = 10;
String pgS, piS, pfS, ter;
String qTpcessao, qAC, qProcesso, qCessionario, qCedente, qEndereco, qCroqui, qVigor;
//Carregando atributos com a informações do formlário.
pgS = req.getParameter("pg");
piS = req.getParameter("pi");
pfS = req.getParameter("pf");
qTpcessao = req.getParameter("qTpcessao");
qProcesso = req.getParameter("qProcesso");
qAC = req.getParameter("qAC");
qCessionario = req.getParameter("qCessionario");
qCedente = req.getParameter("qCedente");
qEndereco = req.getParameter("qEndereco");
qCroqui = req.getParameter("qCroqui");
qVigor = req.getParameter("qVigor");
ter = req.getParameter("ter");
//Validação dos atributos carregdos com as informações do formulário.
if (qTpcessao == null || qTpcessao.equals("")){
qTpcessao ="";
}else{
tpCessao = Integer.parseInt(qTpcessao);
}
if (qAC == null){
qAC ="";
}
if (qProcesso == null){
qProcesso ="";
}
if (null == qCessionario || qCessionario.equals("") ){
qCessionario ="";
}
else{
qCessionario = Transformar.getRemoveAccents(Transformar.getUFT8(qCessionario)).toUpperCase().trim();
}
if (null == qCedente || qCedente.equals("") ){
qCedente ="";
}
else{
qCedente = Transformar.getRemoveAccents(Transformar.getUFT8(qCedente)).toUpperCase().trim();
}
if (null == qEndereco || qEndereco.equals("") ){
qEndereco ="";
}
else{
qEndereco = Transformar.getRemoveAccents(Transformar.getUFT8(qEndereco)).toUpperCase().trim();
}
if (null == qCroqui || qCroqui.equals("") ){
qCroqui ="";
}
else{
qCroqui = Transformar.getRemoveAccents(qCroqui).toUpperCase().trim();
}
if (qVigor == null){
qVigor="";
}
if (pgS == null) {
pg = 0;
} else {
pg = Integer.parseInt(pgS);
}
if (piS == null) {
pi = 0;
} else {
pi = Integer.parseInt(piS);
}
if (pfS == null) {
pf = 0;
} else {
pf = Integer.parseInt(pfS);
}
//Carregando a quantidade de registro para calculdo da quantidade de paginas
qtdRegistro = autoDAO.qtdAutoPesquisa(qTpcessao, qAC, qProcesso, qCessionario, qCedente, qEndereco, qCroqui, qVigor);
qtdPg = qtdRegistro / qtdLinha;
if ((qtdRegistro % qtdLinha) != 0) {
qtdPg = qtdPg+1;
}
if (qtdPg < maxPg) {
maxPg = qtdPg;
}
if (qtdPg > maxPg) {
sobraMaxPg = qtdPg - maxPg;
if (sobraMaxPg > maxPg){
sobraMaxPg = maxPg;
}
}
if (pg == 0) {
pg = 1;
}
if (pf == 0) {
pf = maxPg;
}
if (pg == pf && pf != qtdPg && pf < qtdPg) {
pi = pf;
pf = pf + sobraMaxPg;
} else if (pg == pi){
pi = pi - maxPg;
pf = pf - sobraMaxPg;
pg = pg - 1;
}
offset = ((pg * qtdLinha)- qtdLinha);
//Populando o objeto lista
List<AutoCessao> listAuto = new AutoCessaoDAO().listPagFiltroPesquisa(qTpcessao, qAC, qProcesso, qCessionario, qCedente, qEndereco, qCroqui, qVigor, qtdLinha, offset);
List<TipoAutoCessao> lisTpAuto = tpDAO.listSelectTpCessao();
// qCessionario = URLEncoder.encode(qCessionario,"UTF-8");
// qCedente = URLEncoder.encode(qCedente,"UTF-8");
// qEndereco = URLEncoder.encode(qEndereco,"UTF-8");
req.setAttribute("listAuto", listAuto);
req.setAttribute("lisTpAuto", lisTpAuto);
return "AutoCessaoLista.jsp?"
+"pg="+pg
+"&pi="+pi
+"&pf="+pf
+"&qtdPg="+qtdPg
+"&totalRes="+qtdRegistro
+"&qTpcessao="+qTpcessao
+"&qAC="+qAC
+"&qProcesso="+qProcesso
+"&qCessionario="+qCessionario
+"&qCedente="+qCedente
+"&qEndereco="+qEndereco
+"&qVigor="+qVigor
+"&qCroqui="+qCroqui
+"&ter"+ter;
}
}
<file_sep>/build/generated/src/org/apache/jsp/include/grafico_jsp.java
package org.apache.jsp.include;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class grafico_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.List<String> _jspx_dependants;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_set_var_value_nobody;
private org.glassfish.jsp.api.ResourceInjector _jspx_resourceInjector;
public java.util.List<String> getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_jspx_tagPool_c_set_var_value_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
}
public void _jspDestroy() {
_jspx_tagPool_c_set_var_value_nobody.release();
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html charset=UTF-8;");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
_jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
if (_jspx_meth_c_set_0(_jspx_page_context))
return;
out.write("\r\n");
out.write("\r\n");
out.write(" <script type=\"text/javascript\" src=\"https://www.gstatic.com/charts/loader.js\"></script>\r\n");
out.write(" <script type=\"text/javascript\" src=\"https://www.google.com/jsapi\"></script>\r\n");
out.write(" <script type=\"text/javascript\">\r\n");
out.write(" google.charts.load('current', {'packages':['corechart']});\r\n");
out.write(" google.charts.setOnLoadCallback(drawVisualization);\r\n");
out.write("\r\n");
out.write(" function drawVisualization() {\r\n");
out.write(" // Some raw data (not necessarily accurate)\r\n");
out.write(" var data = google.visualization.arrayToDataTable([\r\n");
out.write(" ['Month', 'Mar/18', 'Abr/2018', 'Mai/2018', 'Jun/2018'],\r\n");
out.write(" ['Total', 21, 21, 31, 32],\r\n");
out.write(" ['Herança', 6, 0, 0, 0],\r\n");
out.write(" ['Nesgas', 1, 0, 0, 0],\r\n");
out.write(" ['Locação', 4, 11, 4, 3],\r\n");
out.write(" ['Outros', 10, 10, 27, 29]\r\n");
out.write(" ]);\r\n");
out.write("\r\n");
out.write(" var options = {\r\n");
out.write(" title: 'Avaliação (DEAPI - Guilherme)',\r\n");
out.write(" chartArea: {width:'60%'},\r\n");
out.write(" vAxis: {title: '', minValue: 0,textStyle:{fontSize:10}},\r\n");
out.write(" hAxis: {title: ''},\r\n");
out.write(" seriesType: 'bars',\r\n");
out.write(" series: {5: {type: 'line'},},\r\n");
out.write(" legend: { position: \"\"},\r\n");
out.write(" height:300,\r\n");
out.write(" \r\n");
out.write(" };\r\n");
out.write("\r\n");
out.write(" var chart = new google.visualization.ComboChart(document.getElementById('avaliaca'));\r\n");
out.write(" chart.draw(data, options);\r\n");
out.write(" }\r\n");
out.write(" </script>\r\n");
out.write(" \r\n");
out.write(" <script>\r\n");
out.write(" google.charts.load('current', {'packages':['corechart']});\r\n");
out.write(" google.charts.setOnLoadCallback(drawChart);\r\n");
out.write("\r\n");
out.write(" function drawChart() {\r\n");
out.write(" var data = google.visualization.arrayToDataTable([\r\n");
out.write(" ['Quantidade de processo por Divisão', 'Quantidade'],\r\n");
out.write(" ['DDPI', 20],\r\n");
out.write(" ['DIPI', 41],\r\n");
out.write(" ['DEAPI', 44],\r\n");
out.write(" ['AVALICAO', 10],\r\n");
out.write(" ['GABINETE', 15]\r\n");
out.write(" ]);\r\n");
out.write("\r\n");
out.write(" var options = {\r\n");
out.write(" title: 'Auto Cessão',\r\n");
out.write(" chartArea:{left:'5%',top:'13%',width:'95%',height:'80%'},\r\n");
out.write(" pieSliceText: 'value',\r\n");
out.write(" //legend: { position: \"left\"},\r\n");
out.write(" height:300,\r\n");
out.write(" \r\n");
out.write(" };\r\n");
out.write("\r\n");
out.write(" var chart = new google.visualization.PieChart(document.getElementById('divisao'));\r\n");
out.write(" chart.draw(data, options);\r\n");
out.write(" }\r\n");
out.write(" </script>\r\n");
out.write(" \r\n");
out.write(" <script type=\"text/javascript\">\r\n");
out.write("\tgoogle.load('visualization', '1', {packages: ['corechart', 'bar']});\r\n");
out.write("\tgoogle.setOnLoadCallback(drawAnnotations);\r\n");
out.write(" \r\n");
out.write(" function drawAnnotations() {\r\n");
out.write(" \r\n");
out.write(" var data = google.visualization.arrayToDataTable([\r\n");
out.write(" ['Auto de Cessao', '', {type: 'string', role: 'annotation'}],\r\n");
out.write(" ['Transferência de Administração', 1243,'1243'],\r\n");
out.write(" ['Permissão de Uso', 475,'475'],\r\n");
out.write(" ['Áreas Recebidas em Cessão', 63,'63'],\r\n");
out.write(" ['Concessão Administração de Uso', 62,'62'],\r\n");
out.write(" ['Permissão de Uso a Título Percário e Oneroso', 33,'33']\r\n");
out.write(" ]);\r\n");
out.write("\tvar options = {\r\n");
out.write(" title: 'Auto de Cessão',\r\n");
out.write(" chartArea:{left:'25%',top:'10%',width:'80%',height:'80%'},\r\n");
out.write(" annotations: {alwaysOutside: true,\r\n");
out.write(" textStyle: {fontSize: 10 , auraColor: 'none', color:'#555'},\r\n");
out.write(" boxStyle: { stroke: '#ccc', strokeWidth: 1, \r\n");
out.write("\t\t gradient: { color1: '#f3e5f5', color2: '#f3e5f5', x1: '0%', y1: '0%', x2: '100%', y2: '100%' } } },\r\n");
out.write(" hAxis: {title: '', minValue: 0,textStyle:{fontSize:12} },\r\n");
out.write(" vAxis: { title: '' },\r\n");
out.write("\t\tfontSize: 10\r\n");
out.write("\t\t\r\n");
out.write("\t\t};\r\n");
out.write(" var chart = new google.visualization.BarChart(document.getElementById('autoCessao'));\r\n");
out.write(" chart.draw(data, options);\r\n");
out.write("\r\n");
out.write(" }\r\n");
out.write(" </script>\r\n");
out.write("\r\n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
private boolean _jspx_meth_c_set_0(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_0 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_0.setPageContext(_jspx_page_context);
_jspx_th_c_set_0.setParent(null);
_jspx_th_c_set_0.setVar("ter");
_jspx_th_c_set_0.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${param.ter}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_0 = _jspx_th_c_set_0.doStartTag();
if (_jspx_th_c_set_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_0);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_0);
return false;
}
}
<file_sep>/src/java/br/com/Controle/PerfilCU.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.Controle;
import br.com.Utilitario.Transformar;
import br.com.Modelo.Logica;
import br.com.Modelo.Perfil;
import br.com.Modelo.PerfilDAO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author d732229
*/
public class PerfilCU implements Logica{
@Override
public String executa(HttpServletRequest req,
HttpServletResponse res) throws Exception{
Perfil perf = new Perfil();
PerfilDAO perfDAO = new PerfilDAO();
HttpSession session = req.getSession();
//Atributo
int pkPerfil, ler=0, inserir=0, editar=0, excluir=0, gerenciar=0;
String perfil, descricao, loginSessio, execucao;
//Carregando os atributos com as informações do formulário
execucao = req.getParameter("execucao");
perfil = Transformar.getPriMaiuscula(req.getParameter("perfil"));
descricao = Transformar.getRemoveAccents(req.getParameter("descricao")).toUpperCase().trim();
loginSessio =(String) session.getAttribute("sessionLogin");
//Validação dos atributos carregdos com as informações do formulário.
if("1".equals(req.getParameter("ler")) ){
ler = 1;
}
if("1".equals(req.getParameter("inserir")) ){
inserir = 1;
}
if("1".equals(req.getParameter("editar")) ){
editar = 1;
}
if("1".equals(req.getParameter("excluir")) ){
excluir = 1;
}
if("1".equals(req.getParameter("gerenciar")) ){
gerenciar = 1;
}
//Tratando para executar o inserir ou alterar, populando o objeto e gravando no banco
if ("edit".equals(execucao)){
pkPerfil = Integer.parseInt(req.getParameter("pkPerfil"));
perf = new Perfil(pkPerfil, ler, inserir, editar, excluir, gerenciar, perfil, descricao, loginSessio);
perfDAO.upPerfil(perf);
req.setAttribute("msg","alterou");
}else if ("insert".equals(execucao)) {
perf = new Perfil(ler, inserir, editar, excluir, gerenciar, perfil, descricao, loginSessio);
perfDAO.cPerfil(perf);
req.setAttribute("msg","gravou");
}
return "ControllerServlet?acao=PerfilLista";
}
}<file_sep>/build/generated/src/org/apache/jsp/Login_jsp.java
package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class Login_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.List<String> _jspx_dependants;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_set_var_value_nobody;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_out_value_nobody;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_if_test;
private org.glassfish.jsp.api.ResourceInjector _jspx_resourceInjector;
public java.util.List<String> getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_jspx_tagPool_c_set_var_value_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_c_out_value_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_c_if_test = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
}
public void _jspDestroy() {
_jspx_tagPool_c_set_var_value_nobody.release();
_jspx_tagPool_c_out_value_nobody.release();
_jspx_tagPool_c_if_test.release();
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html charset=UTF-8;");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
_jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
if (_jspx_meth_c_set_0(_jspx_page_context))
return;
out.write("\r\n");
out.write("<!DOCTYPE html>\r\n");
out.write("<html>\r\n");
out.write(" ");
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "include/head.jsp", out, false);
out.write("\r\n");
out.write(" <body class=\"login-layout light-login\">\r\n");
out.write(" <div class=\"main-container\">\r\n");
out.write(" <div class=\"main-content\">\r\n");
out.write(" <div class=\"row\">\r\n");
out.write(" <div class=\"col-sm-10 col-sm-offset-1\">\r\n");
out.write(" <div class=\"login-container\">\r\n");
out.write(" <div class=\"center\">\r\n");
out.write(" <h1>\r\n");
out.write(" <img src=\"img/logo_c.png\" height=\"35%\" width=\"35%\" title=\"CGPatri - Gerador de Indicadores\">\r\n");
out.write(" </h1>\r\n");
out.write(" \r\n");
out.write(" </div>\r\n");
out.write("\r\n");
out.write(" <div class=\"space-6\"></div>\r\n");
out.write("\r\n");
out.write(" <div class=\"position-relative\">\r\n");
out.write(" <div id=\"login-box\" class=\"login-box visible widget-box no-border \">\r\n");
out.write(" <div class=\"widget-body \">\r\n");
out.write(" <div class=\"widget-main \">\r\n");
out.write(" <h4 class=\"header blue lighter bigger\">\r\n");
out.write(" <span class=\"red\">SG-PATRI</span><br />\r\n");
out.write(" <span class=\"grey\">Sistema de Gestão das Áreas Públicas</span>\r\n");
out.write(" </h4>\r\n");
out.write("\r\n");
out.write(" <div class=\"space-6\"></div>\r\n");
out.write("\r\n");
out.write(" <form action=\"ControllerServlet?acao=UsuarioLogin\" method=\"POST\">\r\n");
out.write(" <fieldset>\r\n");
out.write(" <label class=\"block clearfix col-sm-8 col-sm-offset-2\">\r\n");
out.write(" <span class=\"block input-icon input-icon-right\">\r\n");
out.write(" <input type=\"text\" name=\"Login\" class=\"form-control\" placeholder=\"Login\" title=\"Informar o mesmo login de rede ex.: (d000000 ou x000000)\" required=\"required\">\r\n");
out.write(" <i class=\"ace-icon fa fa-user\"></i>\r\n");
out.write(" </span>\r\n");
out.write(" </label>\r\n");
out.write("\r\n");
out.write(" <label class=\"block clearfix col-sm-8 col-sm-offset-2\">\r\n");
out.write(" <span class=\"block input-icon input-icon-right\">\r\n");
out.write(" <input type=\"password\" name=\"senha\" class=\"form-control\" placeholder=\"Senha\" title=\"Utilizar a mesma senha de rede\" required=\"required\">\r\n");
out.write(" <i class=\"ace-icon fa fa-lock\"></i>\r\n");
out.write(" </span>\r\n");
out.write(" </label>\r\n");
out.write("\r\n");
out.write(" <div class=\"space\"></div>\r\n");
out.write("\r\n");
out.write(" <div class=\"clearfix center\">\r\n");
out.write(" <button type=\"submit\" class=\"width-35 btn btn-sm btn-primary\">\r\n");
out.write(" <i class=\"ace-icon fa fa-key\"></i>\r\n");
out.write(" <span class=\"bigger-110\">Login</span>\r\n");
out.write(" </button>\r\n");
out.write(" </div>\r\n");
out.write("\r\n");
out.write(" <div class=\"space-4\"></div>\r\n");
out.write(" </fieldset>\r\n");
out.write(" </form>\r\n");
out.write("\r\n");
out.write(" <div class=\"social-or-login center\">\r\n");
out.write(" <span class=\"bigger-110\">-</span>\r\n");
out.write(" </div>\r\n");
out.write(" ");
if (_jspx_meth_c_if_0(_jspx_page_context))
return;
out.write("\r\n");
out.write(" <div class=\"space-6\"></div>\r\n");
out.write(" </div><!-- /.widget-main -->\r\n");
out.write("\r\n");
out.write(" <div class=\"toolbar clearfix\">\r\n");
out.write(" <div>\r\n");
out.write(" <!-- <a href=\"#\" data-target=\"#forgot-box\" class=\"forgot-password-link\">\r\n");
out.write(" <i class=\"ace-icon fa fa-arrow-left\"></i>\r\n");
out.write(" Esqueceu a senha.\r\n");
out.write(" </a> -->\r\n");
out.write(" <div class=\"space-8\"></div>\r\n");
out.write(" </div>\r\n");
out.write(" <div>\r\n");
out.write(" <!-- <a href=\"#\" data-target=\"#signup-box\" class=\"user-signup-link\">\r\n");
out.write(" Solicitar acesso\r\n");
out.write(" <i class=\"ace-icon fa fa-arrow-right\"></i>\r\n");
out.write(" </a>-->\r\n");
out.write(" <div class=\"space-8\"></div>\r\n");
out.write(" </div>\r\n");
out.write(" </div>\r\n");
out.write(" </div><!-- /.widget-body -->\r\n");
out.write(" </div><!-- /.login-box -->\r\n");
out.write(" \r\n");
out.write(" \r\n");
out.write(" \r\n");
out.write(" <!-- <div id=\"forgot-box\" class=\"forgot-box widget-box no-border\">\r\n");
out.write(" <div class=\"widget-body\">\r\n");
out.write(" <div class=\"widget-main\">\r\n");
out.write(" <h4 class=\"header red lighter bigger\">\r\n");
out.write(" <i class=\"ace-icon fa fa-key\"></i>\r\n");
out.write(" Esqueceu sua senha?\r\n");
out.write(" </h4>\r\n");
out.write("\r\n");
out.write(" <div class=\"space-6\"></div>\r\n");
out.write(" <p>\r\n");
out.write(" Por favor, insira seu endereço de e-mail. Um e-mail será enviado a você, para que possa escolher uma nova senha.\r\n");
out.write(" </p>\r\n");
out.write("\r\n");
out.write(" <form>\r\n");
out.write(" <fieldset>\r\n");
out.write(" <label class=\"block clearfix\">\r\n");
out.write(" <span class=\"block input-icon input-icon-right\">\r\n");
out.write(" <input type=\"email\" class=\"form-control\" placeholder=\"Email\">\r\n");
out.write(" <i class=\"ace-icon fa fa-envelope\"></i>\r\n");
out.write(" </span>\r\n");
out.write(" </label>\r\n");
out.write("\r\n");
out.write(" <div class=\"clearfix\">\r\n");
out.write(" <button type=\"button\" class=\"width-35 pull-right btn btn-sm btn-danger\">\r\n");
out.write(" <i class=\"ace-icon fa fa-lightbulb-o\"></i>\r\n");
out.write(" <span class=\"bigger-110\">Enviar</span>\r\n");
out.write(" </button>\r\n");
out.write(" </div>\r\n");
out.write(" </fieldset>\r\n");
out.write(" </form>\r\n");
out.write(" </div><!-- /.widget-main -->\r\n");
out.write(" \r\n");
out.write(" <!-- <div class=\"toolbar center\">\r\n");
out.write(" <a href=\"#\" data-target=\"#login-box\" class=\"back-to-login-link\">\r\n");
out.write(" Back to login\r\n");
out.write(" <i class=\"ace-icon fa fa-arrow-right\"></i>\r\n");
out.write(" </a>\r\n");
out.write(" </div>\r\n");
out.write(" </div>\r\n");
out.write(" \r\n");
out.write(" </div> -->\r\n");
out.write(" <!-- /.widget-body -->\r\n");
out.write(" <!-- /.forgot-box -->\r\n");
out.write("\r\n");
out.write(" <div id=\"signup-box\" class=\"signup-box widget-box no-border\">\r\n");
out.write(" <div class=\"widget-body\">\r\n");
out.write(" <div class=\"widget-main\">\r\n");
out.write(" <h4 class=\"header blue lighter bigger\">\r\n");
out.write(" <span class=\"red\">SISGI</span><br />\r\n");
out.write(" <span class=\"grey\" id=\"id-text2\">Cadastro de solicitação de acesso</span>\r\n");
out.write(" </h4>\r\n");
out.write("\r\n");
out.write(" <div class=\"space-6\"></div>\r\n");
out.write(" <p> Preenchar o formulário: </p>\r\n");
out.write("\r\n");
out.write(" <form action=\"#\" method=\"POST\">\r\n");
out.write(" <fieldset>\r\n");
out.write(" <label class=\"block clearfix\">\r\n");
out.write(" <span class=\"block input-icon input-icon-right\">\r\n");
out.write(" <input type=\"text\" class=\"form-control\" placeholder=\"Login: d00000\">\r\n");
out.write(" <i class=\"ace-icon fa fa-info-circle\"></i>\r\n");
out.write(" </span>\r\n");
out.write(" </label>\r\n");
out.write("\r\n");
out.write(" <label class=\"block clearfix\">\r\n");
out.write(" <span class=\"block input-icon input-icon-right\">\r\n");
out.write(" <input type=\"text\" class=\"form-control\" placeholder=\"<NAME>\">\r\n");
out.write(" <i class=\"ace-icon fa fa-user\"></i>\r\n");
out.write(" </span>\r\n");
out.write(" </label>\r\n");
out.write("\r\n");
out.write(" <label class=\"block clearfix\">\r\n");
out.write(" <span class=\"block input-icon input-icon-right\">\r\n");
out.write(" <input type=\"email\" class=\"form-control\" placeholder=\"Email\">\r\n");
out.write(" <i class=\"ace-icon fa fa-envelope\"></i>\r\n");
out.write(" </span>\r\n");
out.write(" </label> \r\n");
out.write(" \r\n");
out.write(" <label class=\"block clearfix\">\r\n");
out.write(" <span class=\"block input-icon input-icon-right\">\r\n");
out.write(" <input type=\"text\" class=\"form-control\" placeholder=\"Secretária/Prefitura Reginal\">\r\n");
out.write(" <i class=\"ace-icon glyphicon glyphicon-home\"></i>\r\n");
out.write(" </span>\r\n");
out.write(" </label> \r\n");
out.write(" <label class=\"block clearfix\">\r\n");
out.write(" <span class=\"block input-icon input-icon-right\">\r\n");
out.write(" <input type=\"email\" class=\"form-control\" placeholder=\"Divisão/Setor/Local\">\r\n");
out.write(" <i class=\"ace-icon glyphicon glyphicon-home\"></i>\r\n");
out.write(" </span>\r\n");
out.write(" </label> \r\n");
out.write(" \r\n");
out.write("\r\n");
out.write(" <label class=\"block\">\r\n");
out.write(" <input type=\"checkbox\" class=\"ace\">\r\n");
out.write(" <span class=\"lbl\">\r\n");
out.write(" Eu aceito a\r\n");
out.write(" <a href=\"#\">condições de uso.</a>\r\n");
out.write(" </span>\r\n");
out.write(" </label>\r\n");
out.write("\r\n");
out.write(" <div class=\"space-24\"></div>\r\n");
out.write("\r\n");
out.write(" <div class=\"clearfix\">\r\n");
out.write(" <button type=\"reset\" class=\"width-30 pull-left btn btn-sm\">\r\n");
out.write(" <i class=\"ace-icon fa fa-refresh\"></i>\r\n");
out.write(" <span class=\"bigger-110\">Limpar</span>\r\n");
out.write(" </button>\r\n");
out.write("\r\n");
out.write(" <button type=\"submit\" class=\"width-30 col-sm-offset-3 btn btn-sm btn-success\">\r\n");
out.write(" <span class=\"bigger-110\">Solicitar</span>\r\n");
out.write("\r\n");
out.write(" <i class=\"ace-icon fa fa-arrow-right icon-on-right\"></i>\r\n");
out.write(" </button>\r\n");
out.write(" </div>\r\n");
out.write(" </fieldset>\r\n");
out.write(" </form>\r\n");
out.write(" </div>\r\n");
out.write("\r\n");
out.write(" <div class=\"toolbar\">\r\n");
out.write(" <div>\r\n");
out.write(" <a href=\"#\" data-target=\"#login-box\" class=\"back-to-login-link\">\r\n");
out.write(" <i class=\"ace-icon fa fa-arrow-left\"></i>\r\n");
out.write(" voltar tela de Login.\r\n");
out.write(" </a>\r\n");
out.write(" </div>\r\n");
out.write(" \r\n");
out.write(" </div>\r\n");
out.write(" </div><!-- /.widget-body -->\r\n");
out.write(" </div><!-- /.signup-box -->\r\n");
out.write(" </div><!-- /.position-relative -->\r\n");
out.write("\r\n");
out.write(" </div>\r\n");
out.write(" </div><!-- /.col -->\r\n");
out.write(" </div><!-- /.row -->\r\n");
out.write(" </div><!-- /.main-content -->\r\n");
out.write(" </div><!-- /.main-container -->\r\n");
out.write("\r\n");
out.write(" <!-- basic scripts -->\r\n");
out.write("\r\n");
out.write(" <!--[if !IE]> -->\r\n");
out.write(" <script src=\"assets/js/jquery-2.1.4.min.js\"></script>\r\n");
out.write("\r\n");
out.write(" <!-- <![endif]-->\r\n");
out.write("\r\n");
out.write(" <!--[if IE]>\r\n");
out.write("<script src=\"assets/js/jquery-1.11.3.min.js\"></script>\r\n");
out.write("<![endif]-->\r\n");
out.write(" <script type=\"text/javascript\">\r\n");
out.write(" if('ontouchstart' in document.documentElement) document.write(\"<script src='assets/js/jquery.mobile.custom.min.js'>\"+\"<\"+\"/script>\");\r\n");
out.write(" </script>\r\n");
out.write("\r\n");
out.write(" <!-- inline scripts related to this page -->\r\n");
out.write(" <script type=\"text/javascript\">\r\n");
out.write(" jQuery(function ($) {\r\n");
out.write(" $(document).on('click', '.toolbar a[data-target]', function (e) {\r\n");
out.write(" e.preventDefault();\r\n");
out.write(" var target = $(this).data('target');\r\n");
out.write(" $('.widget-box.visible').removeClass('visible');//hide others\r\n");
out.write(" $(target).addClass('visible');//show target\r\n");
out.write(" });\r\n");
out.write(" });\r\n");
out.write(" </script>\r\n");
out.write("\r\n");
out.write("\r\n");
out.write(" </body>\r\n");
out.write("</html>\r\n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
private boolean _jspx_meth_c_set_0(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_0 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_0.setPageContext(_jspx_page_context);
_jspx_th_c_set_0.setParent(null);
_jspx_th_c_set_0.setVar("msg");
_jspx_th_c_set_0.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${requestScope.msg}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_0 = _jspx_th_c_set_0.doStartTag();
if (_jspx_th_c_set_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_0);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_0);
return false;
}
private boolean _jspx_meth_c_if_0(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_0 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_0.setPageContext(_jspx_page_context);
_jspx_th_c_if_0.setParent(null);
_jspx_th_c_if_0.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${not empty msg || msg != null}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_0 = _jspx_th_c_if_0.doStartTag();
if (_jspx_eval_c_if_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" <div class=\"alert alert-danger\">\r\n");
out.write(" <span class=\"text-danger\" >\r\n");
out.write(" ");
if (_jspx_meth_c_out_0((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_if_0, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" </span>\r\n");
out.write(" </div>\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_if_0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_0);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_0);
return false;
}
private boolean _jspx_meth_c_out_0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_if_0, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:out
org.apache.taglibs.standard.tag.rt.core.OutTag _jspx_th_c_out_0 = (org.apache.taglibs.standard.tag.rt.core.OutTag) _jspx_tagPool_c_out_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.OutTag.class);
_jspx_th_c_out_0.setPageContext(_jspx_page_context);
_jspx_th_c_out_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_if_0);
_jspx_th_c_out_0.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${msg}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_out_0 = _jspx_th_c_out_0.doStartTag();
if (_jspx_th_c_out_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_0);
return true;
}
_jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_0);
return false;
}
}
<file_sep>/src/java/br/com/Controle/PerfilLista.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.Controle;
import br.com.Modelo.*;
import br.com.Modelo.Logica;
import br.com.Modelo.Perfil;
import br.com.Modelo.PerfilDAO;
import br.com.Utilitario.Transformar;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author d732229
*/
public class PerfilLista implements Logica{
@Override
public String executa(HttpServletRequest req,
HttpServletResponse res) throws Exception {
PerfilDAO pfDAO = new PerfilDAO();
/**
* Atributos:
* pg = número da página atual
* pi = número da página inicial
* pf = número da página final
* qtdRegistro = quantidade de registro geral
* qtdPg = número de quantidade de páginas
* qtdLinha = número de quantidade de linhas por página
* maxPg = quantidade de paginação a ser exibida (1, 2 , 3 ...)
* sobraMaxPg = auxiliar para o calculdo da quantidade de pagina
* */
int pg, pi, pf, qtdRegistro, qtdPg, offset;
String q, pgS, piS, pfS;
int qtdLinha = 8;
int maxPg = 10;
int sobraMaxPg = 0;
//Carregando atributos com a informações do formlário.
pgS = req.getParameter("pg");
piS = req.getParameter("pi");
pfS = req.getParameter("pf");
q = req.getParameter("q");
//Validação dos atributos carregdos com as informações do formulário.
if (q == null){
q = "";
}else if(!"".equals(q)) {
q = Transformar.getPriMaiuscula(q);
}
if (pgS == null) {
pg = 0;
} else {
pg = Integer.parseInt(pgS);
}
if (piS == null) {
pi = 0;
} else {
pi = Integer.parseInt(piS);
}
if (pfS == null) {
pf = 0;
} else {
pf = Integer.parseInt(pfS);
}
//Carregando a quantidade de registro para calculdo da quantidade de paginas
qtdRegistro = pfDAO.qdPerfil(q);
qtdPg = qtdRegistro / qtdLinha;
//Logica da paginação
if ((qtdRegistro % qtdLinha) != 0) {
qtdPg = qtdPg+1;
}
if (qtdPg < maxPg) {
maxPg = qtdPg;
}
if (qtdPg > maxPg) {
sobraMaxPg = qtdPg - maxPg;
if (sobraMaxPg > maxPg){
sobraMaxPg = maxPg;
}
}
if (pg == 0) {
pg = 1;
}
if (pf == 0) {
pf = maxPg;
}
if (pg == pf && pf != qtdPg && pf < qtdPg) {
pi = pf;
pf = pf + sobraMaxPg;
} else if (pg == pi){
pi = pi - maxPg;
pf = pf - sobraMaxPg;
pg = pg - 1;
}
offset = ((pg * qtdLinha)- qtdLinha);
//Populando o objeto lista
List<Perfil> lisPerfil = new PerfilDAO().lisPerfil(qtdLinha, offset, q);
req.setAttribute("lisPerfil", lisPerfil);
return "PerfilLista.jsp?pg="+pg+"&pi="+pi+"&pf="+pf+"&qtdPg="+qtdPg+"&totalRes="+qtdRegistro+"&q="+q;
}
}
<file_sep>/build/generated/src/org/apache/jsp/include/footer_jsp.java
package org.apache.jsp.include;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class footer_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.List<String> _jspx_dependants;
private org.glassfish.jsp.api.ResourceInjector _jspx_resourceInjector;
public java.util.List<String> getDependants() {
return _jspx_dependants;
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
_jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");
out.write("\r\n");
out.write("\r\n");
out.write("<!--Fim DIV do body -->\r\n");
out.write("</div><!-- /.col -->\r\n");
out.write("</div><!-- /.row -->\r\n");
out.write("</div><!-- /.page-content -->\r\n");
out.write("</div>\r\n");
out.write("</div><!-- /.main-content -->\r\n");
out.write("<div class=\"footer\">\r\n");
out.write(" <div class=\"footer-inner\">\r\n");
out.write(" <div class=\"footer-content\">\r\n");
out.write(" <span class=\"bigger-120\">\r\n");
out.write(" <span class=\"bolder\">SGPatri</span> - Sistema de Gestão das Áreas Públicas\r\n");
out.write(" </span>\r\n");
out.write(" </div>\r\n");
out.write(" </div>\r\n");
out.write("</div>\r\n");
out.write("\r\n");
out.write("<a href=\"#\" id=\"btn-scroll-up\" class=\"btn-scroll-up btn btn-sm btn-inverse\">\r\n");
out.write(" <i class=\"ace-icon fa fa-angle-double-up icon-only bigger-110\"></i>\r\n");
out.write("</a>\r\n");
out.write("\r\n");
out.write("<!-- basic scripts -->\r\n");
out.write("<!--[if !IE]> -->\r\n");
out.write("<script src=\"assets/js/jquery-2.1.4.min.js\"></script>\r\n");
out.write("<!-- <![endif]-->\r\n");
out.write("<!--[if IE]>\r\n");
out.write("<script src=\"assets/js/jquery-1.11.3.min.js\"></script>\r\n");
out.write("<![endif]-->\r\n");
out.write("<script type=\"text/javascript\">\r\n");
out.write(" if('ontouchstart' in document.documentElement) document.write(\"<script src='assets/js/jquery.mobile.custom.min.js'>\"+\"<\"+\"/script>\");\r\n");
out.write("</script>\r\n");
out.write("\r\n");
out.write("<!-- page specific plugin scripts -->\r\n");
out.write("<script src=\"assets/js/bootstrap.min.js\"></script>\r\n");
out.write("<script src=\"assets/js/bootstrap-datepicker.min.js\"></script>\r\n");
out.write("<script src=\"assets/js/grid.locale-en.js\"></script>\r\n");
out.write("<script src=\"assets/js/jquery.jqGrid.min.js\"></script>\r\n");
out.write("<script src=\"assets/js/jquery-ui.custom.min.js\"></script>\r\n");
out.write("<script src=\"assets/js/jquery.inputlimiter.min.js\"></script>\r\n");
out.write("<script src=\"assets/js/jquery.maskedinput.min.js\"></script>\r\n");
out.write("<script src=\"assets/js/jquery-ui.min.js\"></script>\r\n");
out.write("<script src=\"assets/js/jquery.ui.touch-punch.min.js\"></script> \r\n");
out.write("\r\n");
out.write("\r\n");
out.write("<script src=\"assets/js/bootstrap-datepicker.min.js\"></script>\r\n");
out.write("<script src=\"assets/js/autosize.min.js\"></script>\r\n");
out.write("\r\n");
out.write("<!-- ace scripts -->\r\n");
out.write("<script src=\"assets/js/ace-elements.min.js\"></script>\r\n");
out.write("<script src=\"assets/js/ace.min.js\"></script>\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("<!-- inline scripts related to this page -->\r\n");
out.write("<script type=\"text/javascript\">\r\n");
out.write(" \r\n");
out.write(" jQuery(function($) {\r\n");
out.write(" $('[data-rel=tooltip]').tooltip({container:'body'});\r\n");
out.write(" $('[data-rel=popover]').popover({container:'body'});\r\n");
out.write("\r\n");
out.write(" autosize($('textarea[class*=autosize]'));\r\n");
out.write("\r\n");
out.write(" $('textarea.limited').inputlimiter({\r\n");
out.write(" remText: '%n character%s remaining...',\r\n");
out.write(" limitText: 'max allowed : %n.'\r\n");
out.write(" });\r\n");
out.write("\r\n");
out.write(" $.mask.definitions['~']='[+-]';\r\n");
out.write(" $('.input-mask-date').mask('99/99/9999');\r\n");
out.write(" $('.input-mask-phone').mask('(999) 999-9999');\r\n");
out.write(" $('.input-mask-eyescript').mask('~9.99 ~9.99 999');\r\n");
out.write(" $(\".input-mask-product\").mask(\"a*-999-a999\",{placeholder:\" \",completed:function(){alert(\"You typed the following: \"+this.val());}});\r\n");
out.write("\r\n");
out.write("\r\n");
out.write(" //\"jQuery UI Slider\"\r\n");
out.write(" //range slider tooltip example\r\n");
out.write(" $(\"#slider-eq > span.ui-slider-purple\").slider('disable');//disable third item\r\n");
out.write("\r\n");
out.write(" //pre-show a file name, for example a previously selected file\r\n");
out.write(" //$('#id-input-file-1').ace_file_input('show_file_list', ['myfile.txt'])\r\n");
out.write(" \r\n");
out.write(" //Funcionalidade do botão Upload de arquivo\r\n");
out.write(" $('#id-input-file-1 , #id-input-file-2').ace_file_input({\r\n");
out.write(" no_file:'Sem arquivo ...',\r\n");
out.write(" btn_choose:'Escolher',\r\n");
out.write(" btn_change:'Alterar',\r\n");
out.write(" droppable:false,\r\n");
out.write(" onchange:null,\r\n");
out.write(" thumbnail:false //| true | large\r\n");
out.write(" //whitelist:'gif|png|jpg|jpeg'\r\n");
out.write(" //blacklist:'exe|php'\r\n");
out.write(" //onchange:''\r\n");
out.write(" //\r\n");
out.write(" });\r\n");
out.write(" \r\n");
out.write(" //Funcionalidade do botão Modal\r\n");
out.write(" //override dialog's title function to allow for HTML titles\r\n");
out.write(" $.widget(\"ui.dialog\", $.extend({}, $.ui.dialog.prototype, {\r\n");
out.write(" _title: function(title) {\r\n");
out.write(" var $title = this.options.title || ' '\r\n");
out.write(" if( (\"title_html\" in this.options) && this.options.title_html == true )\r\n");
out.write(" title.html($title);\r\n");
out.write(" else title.text($title);\r\n");
out.write(" }\r\n");
out.write(" }));\r\n");
out.write("\r\n");
out.write(" $(\"#id-btn-dialog1\" ).on('click', function(e) {\r\n");
out.write(" e.preventDefault();\r\n");
out.write(" $( \"#dialog-planta\" ).removeClass('hide').dialog({\r\n");
out.write(" resizable: true,\r\n");
out.write(" width: '700',\r\n");
out.write(" modal: true,\r\n");
out.write(" title: \"<div class='widget-header widget-header-small'><h4 class='smaller'><i class='ace-icon fa fa-upload'></i> Anexar Planta</h4></div>\",\r\n");
out.write(" title_html: true,\r\n");
out.write(" buttons:[{\r\n");
out.write(" html: \"<i class='ace-icon fa fa-undo bigger-110'></i> Voltar\",\r\n");
out.write(" \"class\" : \"btn btn-yellow\",\r\n");
out.write(" click: function() {\r\n");
out.write(" $( this ).dialog( \"close\" );\r\n");
out.write(" }\r\n");
out.write(" }]\r\n");
out.write(" });\r\n");
out.write(" });\r\n");
out.write("\r\n");
out.write(" $( \"#id-btn-dialog2\" ).on('click', function(e) {\r\n");
out.write(" e.preventDefault();\r\n");
out.write(" $( \"#dialog-auto-cessao\" ).removeClass('hide').dialog({\r\n");
out.write(" resizable: true,\r\n");
out.write(" width: '500',\r\n");
out.write(" modal: true,\r\n");
out.write(" title: \"<div class='widget-header widget-header-small'><h4 class='smaller'><i class='ace-icon fa fa-upload'></i> Anexar Auto Cessão</h4></div>\",\r\n");
out.write(" title_html: true,\r\n");
out.write(" buttons:[{\r\n");
out.write(" html: \"<i class='ace-icon fa fa-undo bigger-110'></i> Voltar\",\r\n");
out.write(" \"class\" : \"btn btn-yellow\",\r\n");
out.write(" click: function() {\r\n");
out.write(" $( this ).dialog( \"close\" );\r\n");
out.write(" }\r\n");
out.write(" }]\r\n");
out.write(" });\r\n");
out.write(" });\r\n");
out.write(" \r\n");
out.write("\r\n");
out.write(" //dynamically change allowed formats by changing allowExt && allowMime function\r\n");
out.write(" $('#id-file-format').removeAttr('checked').on('change', function () {\r\n");
out.write(" var whitelist_ext, whitelist_mime;\r\n");
out.write(" var btn_choose\r\n");
out.write(" var no_icon\r\n");
out.write(" if (this.checked) {\r\n");
out.write(" btn_choose = \"Drop images here or click to choose\";\r\n");
out.write(" no_icon = \"ace-icon fa fa-picture-o\";\r\n");
out.write("\r\n");
out.write(" whitelist_ext = [\"jpeg\", \"jpg\", \"png\", \"gif\", \"bmp\"];\r\n");
out.write(" whitelist_mime = [\"image/jpg\", \"image/jpeg\", \"image/png\", \"image/gif\", \"image/bmp\"];\r\n");
out.write(" } else {\r\n");
out.write(" btn_choose = \"Drop files here or click to choose\";\r\n");
out.write(" no_icon = \"ace-icon fa fa-cloud-upload\";\r\n");
out.write("\r\n");
out.write(" whitelist_ext = null;//all extensions are acceptable\r\n");
out.write(" whitelist_mime = null;//all mimes are acceptable\r\n");
out.write(" }\r\n");
out.write(" var file_input = $('#id-input-file-3');\r\n");
out.write(" file_input\r\n");
out.write(" .ace_file_input('update_settings',\r\n");
out.write(" {\r\n");
out.write(" 'btn_choose': btn_choose,\r\n");
out.write(" 'no_icon': no_icon,\r\n");
out.write(" 'allowExt': whitelist_ext,\r\n");
out.write(" 'allowMime': whitelist_mime\r\n");
out.write(" })\r\n");
out.write(" file_input.ace_file_input('reset_input');\r\n");
out.write("\r\n");
out.write(" file_input\r\n");
out.write(" .off('file.error.ace')\r\n");
out.write(" .on('file.error.ace', function (e, info) {\r\n");
out.write(" //console.log(info.file_count);//number of selected files\r\n");
out.write(" //console.log(info.invalid_count);//number of invalid files\r\n");
out.write(" //console.log(info.error_list);//a list of errors in the following format\r\n");
out.write("\r\n");
out.write(" //info.error_count['ext']\r\n");
out.write(" //info.error_count['mime']\r\n");
out.write(" //info.error_count['size']\r\n");
out.write("\r\n");
out.write(" //info.error_list['ext'] = [list of file names with invalid extension]\r\n");
out.write(" //info.error_list['mime'] = [list of file names with invalid mimetype]\r\n");
out.write(" //info.error_list['size'] = [list of file names with invalid size]\r\n");
out.write("\r\n");
out.write("\r\n");
out.write(" /**\r\n");
out.write(" if( !info.dropped ) {\r\n");
out.write(" //perhapse reset file field if files have been selected, and there are invalid files among them\r\n");
out.write(" //when files are dropped, only valid files will be added to our file array\r\n");
out.write(" e.preventDefault();//it will rest input\r\n");
out.write(" }\r\n");
out.write(" */\r\n");
out.write("\r\n");
out.write("\r\n");
out.write(" //if files have been selected (not dropped), you can choose to reset input\r\n");
out.write(" //because browser keeps all selected files anyway and this cannot be changed\r\n");
out.write(" //we can only reset file field to become empty again\r\n");
out.write(" //on any case you still should check files with your server side script\r\n");
out.write(" //because any arbitrary file can be uploaded by user and it's not safe to rely on browser-side measures\r\n");
out.write(" });\r\n");
out.write("\r\n");
out.write("\r\n");
out.write(" /**\r\n");
out.write(" file_input\r\n");
out.write(" .off('file.preview.ace')\r\n");
out.write(" .on('file.preview.ace', function(e, info) {\r\n");
out.write(" console.log(info.file.width);\r\n");
out.write(" console.log(info.file.height);\r\n");
out.write(" e.preventDefault();//to prevent preview\r\n");
out.write(" });\r\n");
out.write(" */\r\n");
out.write("\r\n");
out.write(" });\r\n");
out.write("\r\n");
out.write(" $('#spinner1').ace_spinner({value: 0, min: 0, max: 200, step: 10, btn_up_class: 'btn-info', btn_down_class: 'btn-info'})\r\n");
out.write(" .closest('.ace-spinner')\r\n");
out.write(" .on('changed.fu.spinbox', function () {\r\n");
out.write(" //console.log($('#spinner1').val())\r\n");
out.write(" });\r\n");
out.write(" $('#spinner2').ace_spinner({value: 0, min: 0, max: 10000, step: 100, touch_spinner: true, icon_up: 'ace-icon fa fa-caret-up bigger-110', icon_down: 'ace-icon fa fa-caret-down bigger-110'});\r\n");
out.write(" $('#spinner3').ace_spinner({value: 0, min: -100, max: 100, step: 10, on_sides: true, icon_up: 'ace-icon fa fa-plus bigger-110', icon_down: 'ace-icon fa fa-minus bigger-110', btn_up_class: 'btn-success', btn_down_class: 'btn-danger'});\r\n");
out.write(" $('#spinner4').ace_spinner({value: 0, min: -100, max: 100, step: 10, on_sides: true, icon_up: 'ace-icon fa fa-plus', icon_down: 'ace-icon fa fa-minus', btn_up_class: 'btn-purple', btn_down_class: 'btn-purple'});\r\n");
out.write("\r\n");
out.write(" //$('#spinner1').ace_spinner('disable').ace_spinner('value', 11);\r\n");
out.write(" //or\r\n");
out.write(" //$('#spinner1').closest('.ace-spinner').spinner('disable').spinner('enable').spinner('value', 11);//disable, enable or change value\r\n");
out.write(" //$('#spinner1').closest('.ace-spinner').spinner('value', 0);//reset to 0\r\n");
out.write("\r\n");
out.write("\r\n");
out.write(" //datepicker plugin\r\n");
out.write(" //link\r\n");
out.write(" $('.date-picker').datepicker({\r\n");
out.write(" autoclose: true,\r\n");
out.write(" todayHighlight: true\r\n");
out.write(" })\r\n");
out.write(" //show datepicker when clicking on the icon\r\n");
out.write(" .next().on(ace.click_event, function () {\r\n");
out.write(" $(this).prev().focus();\r\n");
out.write(" });\r\n");
out.write("\r\n");
out.write(" //or change it into a date range picker\r\n");
out.write(" $('.input-daterange').datepicker({autoclose: true});\r\n");
out.write("\r\n");
out.write("\r\n");
out.write(" //to translate the daterange picker, please copy the \"examples/daterange-fr.js\" contents here before initialization\r\n");
out.write(" $('input[name=date-range-picker]').daterangepicker({\r\n");
out.write(" 'applyClass': 'btn-sm btn-success',\r\n");
out.write(" 'cancelClass': 'btn-sm btn-default',\r\n");
out.write(" locale: {\r\n");
out.write(" applyLabel: 'Apply',\r\n");
out.write(" cancelLabel: 'Cancel',\r\n");
out.write(" }\r\n");
out.write(" })\r\n");
out.write(" .prev().on(ace.click_event, function () {\r\n");
out.write(" $(this).next().focus();\r\n");
out.write(" });\r\n");
out.write("\r\n");
out.write("\r\n");
out.write(" $('#timepicker1').timepicker({\r\n");
out.write(" minuteStep: 1,\r\n");
out.write(" showSeconds: true,\r\n");
out.write(" showMeridian: false,\r\n");
out.write(" disableFocus: true,\r\n");
out.write(" icons: {\r\n");
out.write(" up: 'fa fa-chevron-up',\r\n");
out.write(" down: 'fa fa-chevron-down'\r\n");
out.write(" }\r\n");
out.write(" }).on('focus', function () {\r\n");
out.write(" $('#timepicker1').timepicker('showWidget');\r\n");
out.write(" }).next().on(ace.click_event, function () {\r\n");
out.write(" $(this).prev().focus();\r\n");
out.write(" });\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write(" if (!ace.vars['old_ie'])\r\n");
out.write(" $('#date-timepicker1').datetimepicker({\r\n");
out.write(" //format: 'MM/DD/YYYY h:mm:ss A',//use this option to display seconds\r\n");
out.write(" icons: {\r\n");
out.write(" time: 'fa fa-clock-o',\r\n");
out.write(" date: 'fa fa-calendar',\r\n");
out.write(" up: 'fa fa-chevron-up',\r\n");
out.write(" down: 'fa fa-chevron-down',\r\n");
out.write(" previous: 'fa fa-chevron-left',\r\n");
out.write(" next: 'fa fa-chevron-right',\r\n");
out.write(" today: 'fa fa-arrows ',\r\n");
out.write(" clear: 'fa fa-trash',\r\n");
out.write(" close: 'fa fa-times'\r\n");
out.write(" }\r\n");
out.write(" }).next().on(ace.click_event, function () {\r\n");
out.write(" $(this).prev().focus();\r\n");
out.write(" });\r\n");
out.write("\r\n");
out.write("\r\n");
out.write(" $('#colorpicker1').colorpicker();\r\n");
out.write(" //$('.colorpicker').last().css('z-index', 2000);//if colorpicker is inside a modal, its z-index should be higher than modal'safe\r\n");
out.write("\r\n");
out.write(" $('#simple-colorpicker-1').ace_colorpicker();\r\n");
out.write(" //$('#simple-colorpicker-1').ace_colorpicker('pick', 2);//select 2nd color\r\n");
out.write(" //$('#simple-colorpicker-1').ace_colorpicker('pick', '#fbe983');//select #fbe983 color\r\n");
out.write(" //var picker = $('#simple-colorpicker-1').data('ace_colorpicker')\r\n");
out.write(" //picker.pick('red', true);//insert the color if it doesn't exist\r\n");
out.write("\r\n");
out.write("\r\n");
out.write(" $(\".knob\").knob();\r\n");
out.write("\r\n");
out.write("\r\n");
out.write(" var tag_input = $('#form-field-tags');\r\n");
out.write(" try {\r\n");
out.write(" tag_input.tag(\r\n");
out.write(" {\r\n");
out.write(" placeholder: tag_input.attr('placeholder'),\r\n");
out.write(" //enable typeahead by specifying the source array\r\n");
out.write(" source: ace.vars['US_STATES'], //defined in ace.js >> ace.enable_search_ahead\r\n");
out.write(" /**\r\n");
out.write(" //or fetch data from database, fetch those that match \"query\"\r\n");
out.write(" source: function(query, process) {\r\n");
out.write(" $.ajax({url: 'remote_source.php?q='+encodeURIComponent(query)})\r\n");
out.write(" .done(function(result_items){\r\n");
out.write(" process(result_items);\r\n");
out.write(" });\r\n");
out.write(" }\r\n");
out.write(" */\r\n");
out.write(" }\r\n");
out.write(" )\r\n");
out.write("\r\n");
out.write(" //programmatically add/remove a tag\r\n");
out.write(" var $tag_obj = $('#form-field-tags').data('tag');\r\n");
out.write(" $tag_obj.add('Programmatically Added');\r\n");
out.write("\r\n");
out.write(" var index = $tag_obj.inValues('some tag');\r\n");
out.write(" $tag_obj.remove(index);\r\n");
out.write(" } catch (e) {\r\n");
out.write(" //display a textarea for old IE, because it doesn't support this plugin or another one I tried!\r\n");
out.write(" tag_input.after('<textarea id=\"' + tag_input.attr('id') + '\" name=\"' + tag_input.attr('name') + '\" rows=\"3\">' + tag_input.val() + '</textarea>').remove();\r\n");
out.write(" //autosize($('#form-field-tags'));\r\n");
out.write(" }\r\n");
out.write("\r\n");
out.write("\r\n");
out.write(" /////////\r\n");
out.write(" $('#modal-form input[type=file]').ace_file_input({\r\n");
out.write(" style: 'well',\r\n");
out.write(" btn_choose: 'Drop files here or click to choose',\r\n");
out.write(" btn_change: null,\r\n");
out.write(" no_icon: 'ace-icon fa fa-cloud-upload',\r\n");
out.write(" droppable: true,\r\n");
out.write(" thumbnail: 'large'\r\n");
out.write(" })\r\n");
out.write("\r\n");
out.write(" //chosen plugin inside a modal will have a zero width because the select element is originally hidden\r\n");
out.write(" //and its width cannot be determined.\r\n");
out.write(" //so we set the width after modal is show\r\n");
out.write(" $('#modal-form').on('shown.bs.modal', function () {\r\n");
out.write(" if (!ace.vars['touch']) {\r\n");
out.write(" $(this).find('.chosen-container').each(function () {\r\n");
out.write(" $(this).find('a:first-child').css('width', '210px');\r\n");
out.write(" $(this).find('.chosen-drop').css('width', '210px');\r\n");
out.write(" $(this).find('.chosen-search input').css('width', '200px');\r\n");
out.write(" });\r\n");
out.write(" }\r\n");
out.write(" })\r\n");
out.write(" /**\r\n");
out.write(" //or you can activate the chosen plugin after modal is shown\r\n");
out.write(" //this way select element becomes visible with dimensions and chosen works as expected\r\n");
out.write(" $('#modal-form').on('shown', function () {\r\n");
out.write(" $(this).find('.modal-chosen').chosen();\r\n");
out.write(" })\r\n");
out.write(" */\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write(" $(document).one('ajaxloadstart.page', function (e) {\r\n");
out.write(" autosize.destroy('textarea[class*=autosize]')\r\n");
out.write("\r\n");
out.write(" $('.limiterBox,.autosizejs').remove();\r\n");
out.write(" $('.daterangepicker.dropdown-menu,.colorpicker.dropdown-menu,.bootstrap-datetimepicker-widget.dropdown-menu').remove();\r\n");
out.write(" });\r\n");
out.write("\r\n");
out.write(" });\r\n");
out.write("</script>\r\n");
out.write("\r\n");
out.write("<script type=\"text/javascript\">\r\n");
out.write("var grid_data = \r\n");
out.write("[ \r\n");
out.write(" {id:\"1\",name:\"Desktop Computer\",note:\"note\",stock:\"Yes\",ship:\"FedEx\", sdate:\"2007-12-03\"},\r\n");
out.write(" {id:\"2\",name:\"Laptop\",note:\"Long text \",stock:\"Yes\",ship:\"InTime\",sdate:\"2007-12-03\"},\r\n");
out.write(" {id:\"3\",name:\"LCD Monitor\",note:\"note3\",stock:\"Yes\",ship:\"TNT\",sdate:\"2007-12-03\"},\r\n");
out.write(" {id:\"4\",name:\"Speakers\",note:\"note\",stock:\"No\",ship:\"ARAMEX\",sdate:\"2007-12-03\"},\r\n");
out.write(" {id:\"5\",name:\"Laser Printer\",note:\"note2\",stock:\"Yes\",ship:\"FedEx\",sdate:\"2007-12-03\"},\r\n");
out.write(" {id:\"6\",name:\"Play Station\",note:\"note3\",stock:\"No\", ship:\"FedEx\",sdate:\"2007-12-03\"},\r\n");
out.write(" {id:\"7\",name:\"Mobile Telephone\",note:\"note\",stock:\"Yes\",ship:\"ARAMEX\",sdate:\"2007-12-03\"},\r\n");
out.write(" {id:\"8\",name:\"Server\",note: \"note2\", stock: \"Yes\", ship: \"TNT\", sdate: \"2007-12-03\"},\r\n");
out.write(" {id: \"9\", name: \"Matrix Printer\", note: \"note3\", stock: \"No\", ship: \"FedEx\", sdate: \"2007-12-03\"},\r\n");
out.write(" {id: \"10\", name: \"Desktop Computer\", note: \"note\", stock: \"Yes\", ship: \"FedEx\", sdate: \"2007-12-03\"},\r\n");
out.write(" {id: \"11\", name: \"Laptop\", note: \"Long text \", stock: \"Yes\", ship: \"InTime\", sdate: \"2007-12-03\"},\r\n");
out.write(" {id: \"12\", name: \"LCD Monitor\", note: \"note3\", stock: \"Yes\", ship: \"TNT\", sdate: \"2007-12-03\"},\r\n");
out.write(" {id: \"13\", name: \"Speakers\", note: \"note\", stock: \"No\", ship: \"ARAMEX\", sdate: \"2007-12-03\"},\r\n");
out.write(" {id: \"14\", name: \"Laser Printer\", note: \"note2\", stock: \"Yes\", ship: \"FedEx\", sdate: \"2007-12-03\"},\r\n");
out.write(" {id: \"15\", name: \"Play Station\", note: \"note3\", stock: \"No\", ship: \"FedEx\", sdate: \"2007-12-03\"},\r\n");
out.write(" {id: \"16\", name: \"Mobile Telephone\", note: \"note\", stock: \"Yes\", ship: \"ARAMEX\", sdate: \"2007-12-03\"},\r\n");
out.write(" {id: \"17\", name: \"Server\", note: \"note2\", stock: \"Yes\", ship: \"TNT\", sdate: \"2007-12-03\"},\r\n");
out.write(" {id: \"18\", name: \"Matrix Printer\", note: \"note3\", stock: \"No\", ship: \"FedEx\", sdate: \"2007-12-03\"},\r\n");
out.write(" {id: \"19\", name: \"Matrix Printer\", note: \"note3\", stock: \"No\", ship: \"FedEx\", sdate: \"2007-12-03\"},\r\n");
out.write(" {id: \"20\", name: \"Desktop Computer\", note: \"note\", stock: \"Yes\", ship: \"FedEx\", sdate: \"2007-12-03\"},\r\n");
out.write(" {id: \"21\", name: \"Laptop\", note: \"Long text \", stock: \"Yes\", ship: \"InTime\", sdate: \"2007-12-03\"},\r\n");
out.write(" {id: \"22\", name: \"LCD Monitor\", note: \"note3\", stock: \"Yes\", ship: \"TNT\", sdate: \"2007-12-03\"},\r\n");
out.write(" {id: \"23\", name: \"Speakers\", note: \"note\", stock: \"No\", ship: \"ARAMEX\", sdate: \"2007-12-03\"}\r\n");
out.write(" ];\r\n");
out.write("\r\n");
out.write(" var subgrid_data =\r\n");
out.write(" [\r\n");
out.write(" {id: \"1\", name: \"sub grid item 1\", qty: 11},\r\n");
out.write(" {id: \"2\", name: \"sub grid item 2\", qty: 3},\r\n");
out.write(" {id: \"3\", name: \"sub grid item 3\", qty: 12},\r\n");
out.write(" {id: \"4\", name: \"sub grid item 4\", qty: 5},\r\n");
out.write(" {id: \"5\", name: \"sub grid item 5\", qty: 2},\r\n");
out.write(" {id: \"6\", name: \"sub grid item 6\", qty: 9},\r\n");
out.write(" {id: \"7\", name: \"sub grid item 7\", qty: 3},\r\n");
out.write(" {id: \"8\", name: \"sub grid item 8\", qty: 8}\r\n");
out.write(" ];\r\n");
out.write("\r\n");
out.write(" jQuery(function ($) {\r\n");
out.write(" var grid_selector = \"#grid-table\";\r\n");
out.write(" var pager_selector = \"#grid-pager\";\r\n");
out.write("\r\n");
out.write(" var parent_column = $(grid_selector).closest('[class*=\"col-\"]');\r\n");
out.write(" //resize to fit page size\r\n");
out.write(" $(window).on('resize.jqGrid', function () {\r\n");
out.write(" $(grid_selector).jqGrid('setGridWidth', parent_column.width());\r\n");
out.write(" })\r\n");
out.write("\r\n");
out.write(" //resize on sidebar collapse/expand\r\n");
out.write(" $(document).on('settings.ace.jqGrid', function (ev, event_name, collapsed) {\r\n");
out.write(" if (event_name === 'sidebar_collapsed' || event_name === 'main_container_fixed') {\r\n");
out.write(" //setTimeout is for webkit only to give time for DOM changes and then redraw!!!\r\n");
out.write(" setTimeout(function () {\r\n");
out.write(" $(grid_selector).jqGrid('setGridWidth', parent_column.width());\r\n");
out.write(" }, 20);\r\n");
out.write(" }\r\n");
out.write(" })\r\n");
out.write("\r\n");
out.write(" //if your grid is inside another element, for example a tab pane, you should use its parent's width:\r\n");
out.write(" /**\r\n");
out.write(" $(window).on('resize.jqGrid', function () {\r\n");
out.write(" var parent_width = $(grid_selector).closest('.tab-pane').width();\r\n");
out.write(" $(grid_selector).jqGrid( 'setGridWidth', parent_width );\r\n");
out.write(" })\r\n");
out.write(" //and also set width when tab pane becomes visible\r\n");
out.write(" $('#myTab a[data-toggle=\"tab\"]').on('shown.bs.tab', function (e) {\r\n");
out.write(" if($(e.target).attr('href') == '#mygrid') {\r\n");
out.write(" var parent_width = $(grid_selector).closest('.tab-pane').width();\r\n");
out.write(" $(grid_selector).jqGrid( 'setGridWidth', parent_width );\r\n");
out.write(" }\r\n");
out.write(" })\r\n");
out.write(" */\r\n");
out.write("\r\n");
out.write(" jQuery(grid_selector).jqGrid({\r\n");
out.write(" //direction: \"rtl\",\r\n");
out.write("\r\n");
out.write(" //subgrid options\r\n");
out.write(" subGrid: true,\r\n");
out.write(" //subGridModel: [{ name : ['No','Item Name','Qty'], width : [55,200,80] }],\r\n");
out.write(" //datatype: \"xml\",\r\n");
out.write(" subGridOptions: {\r\n");
out.write(" plusicon: \"ace-icon fa fa-plus center bigger-110 blue\",\r\n");
out.write(" minusicon: \"ace-icon fa fa-minus center bigger-110 blue\",\r\n");
out.write(" openicon: \"ace-icon fa fa-chevron-right center orange\"\r\n");
out.write(" },\r\n");
out.write(" //for this example we are using local data\r\n");
out.write(" subGridRowExpanded: function (subgridDivId, rowId) {\r\n");
out.write(" var subgridTableId = subgridDivId + \"_t\";\r\n");
out.write(" $(\"#\" + subgridDivId).html(\"<table id='\" + subgridTableId + \"'></table>\");\r\n");
out.write(" $(\"#\" + subgridTableId).jqGrid({\r\n");
out.write(" datatype: 'local',\r\n");
out.write(" data: subgrid_data,\r\n");
out.write(" colNames: ['No', 'Item Name', 'Qty'],\r\n");
out.write(" colModel: [\r\n");
out.write(" {name: 'id', width: 50},\r\n");
out.write(" {name: 'name', width: 150},\r\n");
out.write(" {name: 'qty', width: 50}\r\n");
out.write(" ]\r\n");
out.write(" });\r\n");
out.write(" },\r\n");
out.write("\r\n");
out.write(" data: grid_data,\r\n");
out.write(" datatype: \"local\",\r\n");
out.write(" height: 250,\r\n");
out.write(" colNames: [' ', 'ID', 'Last Sales', 'Name', 'Stock', 'Ship via', 'Notes'],\r\n");
out.write(" colModel: [\r\n");
out.write(" {name: 'myac', index: '', width: 80, fixed: true, sortable: false, resize: false,\r\n");
out.write(" formatter: 'actions',\r\n");
out.write(" formatoptions: {\r\n");
out.write(" keys: true,\r\n");
out.write(" //delbutton: false,//disable delete button\r\n");
out.write("\r\n");
out.write(" delOptions: {recreateForm: true, beforeShowForm: beforeDeleteCallback},\r\n");
out.write(" //editformbutton:true, editOptions:{recreateForm: true, beforeShowForm:beforeEditCallback}\r\n");
out.write(" }\r\n");
out.write(" },\r\n");
out.write(" {name: 'id', index: 'id', width: 60, sorttype: \"int\", editable: true},\r\n");
out.write(" {name: 'sdate', index: 'sdate', width: 90, editable: true, sorttype: \"date\", unformat: pickDate},\r\n");
out.write(" {name: 'name', index: 'name', width: 150, editable: true, editoptions: {size: \"20\", maxlength: \"30\"}},\r\n");
out.write(" {name: 'stock', index: 'stock', width: 70, editable: true, edittype: \"checkbox\", editoptions: {value: \"Yes:No\"}, unformat: aceSwitch},\r\n");
out.write(" {name: 'ship', index: 'ship', width: 90, editable: true, edittype: \"select\", editoptions: {value: \"FE:FedEx;IN:InTime;TN:TNT;AR:ARAMEX\"}},\r\n");
out.write(" {name: 'note', index: 'note', width: 150, sortable: false, editable: true, edittype: \"textarea\", editoptions: {rows: \"2\", cols: \"10\"}}\r\n");
out.write(" ],\r\n");
out.write("\r\n");
out.write(" viewrecords: true,\r\n");
out.write(" rowNum: 10,\r\n");
out.write(" rowList: [10, 20, 30],\r\n");
out.write(" pager: pager_selector,\r\n");
out.write(" altRows: true,\r\n");
out.write(" //toppager: true,\r\n");
out.write("\r\n");
out.write(" multiselect: true,\r\n");
out.write(" //multikey: \"ctrlKey\",\r\n");
out.write(" multiboxonly: true,\r\n");
out.write("\r\n");
out.write(" loadComplete: function () {\r\n");
out.write(" var table = this;\r\n");
out.write(" setTimeout(function () {\r\n");
out.write(" styleCheckbox(table);\r\n");
out.write("\r\n");
out.write(" updateActionIcons(table);\r\n");
out.write(" updatePagerIcons(table);\r\n");
out.write(" enableTooltips(table);\r\n");
out.write(" }, 0);\r\n");
out.write(" },\r\n");
out.write("\r\n");
out.write(" editurl: \"./dummy.php\", //nothing is saved\r\n");
out.write(" caption: \"jqGrid with inline editing\"\r\n");
out.write("\r\n");
out.write(" //,autowidth: true,\r\n");
out.write("\r\n");
out.write("\r\n");
out.write(" /**\r\n");
out.write(" ,\r\n");
out.write(" grouping:true, \r\n");
out.write(" groupingView : { \r\n");
out.write(" groupField : ['name'],\r\n");
out.write(" groupDataSorted : true,\r\n");
out.write(" plusicon : 'fa fa-chevron-down bigger-110',\r\n");
out.write(" minusicon : 'fa fa-chevron-up bigger-110'\r\n");
out.write(" },\r\n");
out.write(" caption: \"Grouping\"\r\n");
out.write(" */\r\n");
out.write("\r\n");
out.write(" });\r\n");
out.write(" $(window).triggerHandler('resize.jqGrid');//trigger window resize to make the grid get the correct size\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write(" //enable search/filter toolbar\r\n");
out.write(" //jQuery(grid_selector).jqGrid('filterToolbar',{defaultSearch:true,stringResult:true})\r\n");
out.write(" //jQuery(grid_selector).filterToolbar({});\r\n");
out.write("\r\n");
out.write("\r\n");
out.write(" //switch element when editing inline\r\n");
out.write(" function aceSwitch(cellvalue, options, cell) {\r\n");
out.write(" setTimeout(function () {\r\n");
out.write(" $(cell).find('input[type=checkbox]')\r\n");
out.write(" .addClass('ace ace-switch ace-switch-5')\r\n");
out.write(" .after('<span class=\"lbl\"></span>');\r\n");
out.write(" }, 0);\r\n");
out.write(" }\r\n");
out.write(" //enable datepicker\r\n");
out.write(" function pickDate(cellvalue, options, cell) {\r\n");
out.write(" setTimeout(function () {\r\n");
out.write(" $(cell).find('input[type=text]')\r\n");
out.write(" .datepicker({format: 'yyyy-mm-dd', autoclose: true});\r\n");
out.write(" }, 0);\r\n");
out.write(" }\r\n");
out.write("\r\n");
out.write(" //navButtons\r\n");
out.write(" jQuery(grid_selector).jqGrid('navGrid', pager_selector,\r\n");
out.write(" {//navbar options\r\n");
out.write(" edit: true,\r\n");
out.write(" editicon: 'ace-icon fa fa-pencil blue',\r\n");
out.write(" add: true,\r\n");
out.write(" addicon: 'ace-icon fa fa-plus-circle purple',\r\n");
out.write(" del: true,\r\n");
out.write(" delicon: 'ace-icon fa fa-trash-o red',\r\n");
out.write(" search: true,\r\n");
out.write(" searchicon: 'ace-icon fa fa-search orange',\r\n");
out.write(" refresh: true,\r\n");
out.write(" refreshicon: 'ace-icon fa fa-refresh green',\r\n");
out.write(" view: true,\r\n");
out.write(" viewicon: 'ace-icon fa fa-search-plus grey',\r\n");
out.write(" },\r\n");
out.write(" {\r\n");
out.write(" //edit record form\r\n");
out.write(" //closeAfterEdit: true,\r\n");
out.write(" //width: 700,\r\n");
out.write(" recreateForm: true,\r\n");
out.write(" beforeShowForm: function (e) {\r\n");
out.write(" var form = $(e[0]);\r\n");
out.write(" form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class=\"widget-header\" />')\r\n");
out.write(" style_edit_form(form);\r\n");
out.write(" }\r\n");
out.write(" },\r\n");
out.write(" {\r\n");
out.write(" //new record form\r\n");
out.write(" //width: 700,\r\n");
out.write(" closeAfterAdd: true,\r\n");
out.write(" recreateForm: true,\r\n");
out.write(" viewPagerButtons: false,\r\n");
out.write(" beforeShowForm: function (e) {\r\n");
out.write(" var form = $(e[0]);\r\n");
out.write(" form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar')\r\n");
out.write(" .wrapInner('<div class=\"widget-header\" />')\r\n");
out.write(" style_edit_form(form);\r\n");
out.write(" }\r\n");
out.write(" },\r\n");
out.write(" {\r\n");
out.write(" //delete record form\r\n");
out.write(" recreateForm: true,\r\n");
out.write(" beforeShowForm: function (e) {\r\n");
out.write(" var form = $(e[0]);\r\n");
out.write(" if (form.data('styled'))\r\n");
out.write(" return false;\r\n");
out.write("\r\n");
out.write(" form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class=\"widget-header\" />')\r\n");
out.write(" style_delete_form(form);\r\n");
out.write("\r\n");
out.write(" form.data('styled', true);\r\n");
out.write(" },\r\n");
out.write(" onClick: function (e) {\r\n");
out.write(" //alert(1);\r\n");
out.write(" }\r\n");
out.write(" },\r\n");
out.write(" {\r\n");
out.write(" //search form\r\n");
out.write(" recreateForm: true,\r\n");
out.write(" afterShowSearch: function (e) {\r\n");
out.write(" var form = $(e[0]);\r\n");
out.write(" form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class=\"widget-header\" />')\r\n");
out.write(" style_search_form(form);\r\n");
out.write(" },\r\n");
out.write(" afterRedraw: function () {\r\n");
out.write(" style_search_filters($(this));\r\n");
out.write(" }\r\n");
out.write(" ,\r\n");
out.write(" multipleSearch: true,\r\n");
out.write(" /**\r\n");
out.write(" multipleGroup:true,\r\n");
out.write(" showQuery: true\r\n");
out.write(" */\r\n");
out.write(" },\r\n");
out.write(" {\r\n");
out.write(" //view record form\r\n");
out.write(" recreateForm: true,\r\n");
out.write(" beforeShowForm: function (e) {\r\n");
out.write(" var form = $(e[0]);\r\n");
out.write(" form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class=\"widget-header\" />')\r\n");
out.write(" }\r\n");
out.write(" }\r\n");
out.write(" )\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write(" function style_edit_form(form) {\r\n");
out.write(" //enable datepicker on \"sdate\" field and switches for \"stock\" field\r\n");
out.write(" form.find('input[name=sdate]').datepicker({format: 'yyyy-mm-dd', autoclose: true})\r\n");
out.write("\r\n");
out.write(" form.find('input[name=stock]').addClass('ace ace-switch ace-switch-5').after('<span class=\"lbl\"></span>');\r\n");
out.write(" //don't wrap inside a label element, the checkbox value won't be submitted (POST'ed)\r\n");
out.write(" //.addClass('ace ace-switch ace-switch-5').wrap('<label class=\"inline\" />').after('<span class=\"lbl\"></span>');\r\n");
out.write("\r\n");
out.write("\r\n");
out.write(" //update buttons classes\r\n");
out.write(" var buttons = form.next().find('.EditButton .fm-button');\r\n");
out.write(" buttons.addClass('btn btn-sm').find('[class*=\"-icon\"]').hide();//ui-icon, s-icon\r\n");
out.write(" buttons.eq(0).addClass('btn-primary').prepend('<i class=\"ace-icon fa fa-check\"></i>');\r\n");
out.write(" buttons.eq(1).prepend('<i class=\"ace-icon fa fa-times\"></i>')\r\n");
out.write("\r\n");
out.write(" buttons = form.next().find('.navButton a');\r\n");
out.write(" buttons.find('.ui-icon').hide();\r\n");
out.write(" buttons.eq(0).append('<i class=\"ace-icon fa fa-chevron-left\"></i>');\r\n");
out.write(" buttons.eq(1).append('<i class=\"ace-icon fa fa-chevron-right\"></i>');\r\n");
out.write(" }\r\n");
out.write("\r\n");
out.write(" function style_delete_form(form) {\r\n");
out.write(" var buttons = form.next().find('.EditButton .fm-button');\r\n");
out.write(" buttons.addClass('btn btn-sm btn-white btn-round').find('[class*=\"-icon\"]').hide();//ui-icon, s-icon\r\n");
out.write(" buttons.eq(0).addClass('btn-danger').prepend('<i class=\"ace-icon fa fa-trash-o\"></i>');\r\n");
out.write(" buttons.eq(1).addClass('btn-default').prepend('<i class=\"ace-icon fa fa-times\"></i>')\r\n");
out.write(" }\r\n");
out.write("\r\n");
out.write(" function style_search_filters(form) {\r\n");
out.write(" form.find('.delete-rule').val('X');\r\n");
out.write(" form.find('.add-rule').addClass('btn btn-xs btn-primary');\r\n");
out.write(" form.find('.add-group').addClass('btn btn-xs btn-success');\r\n");
out.write(" form.find('.delete-group').addClass('btn btn-xs btn-danger');\r\n");
out.write(" }\r\n");
out.write(" function style_search_form(form) {\r\n");
out.write(" var dialog = form.closest('.ui-jqdialog');\r\n");
out.write(" var buttons = dialog.find('.EditTable')\r\n");
out.write(" buttons.find('.EditButton a[id*=\"_reset\"]').addClass('btn btn-sm btn-info').find('.ui-icon').attr('class', 'ace-icon fa fa-retweet');\r\n");
out.write(" buttons.find('.EditButton a[id*=\"_query\"]').addClass('btn btn-sm btn-inverse').find('.ui-icon').attr('class', 'ace-icon fa fa-comment-o');\r\n");
out.write(" buttons.find('.EditButton a[id*=\"_search\"]').addClass('btn btn-sm btn-purple').find('.ui-icon').attr('class', 'ace-icon fa fa-search');\r\n");
out.write(" }\r\n");
out.write("\r\n");
out.write(" function beforeDeleteCallback(e) {\r\n");
out.write(" var form = $(e[0]);\r\n");
out.write(" if (form.data('styled'))\r\n");
out.write(" return false;\r\n");
out.write("\r\n");
out.write(" form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class=\"widget-header\" />')\r\n");
out.write(" style_delete_form(form);\r\n");
out.write("\r\n");
out.write(" form.data('styled', true);\r\n");
out.write(" }\r\n");
out.write("\r\n");
out.write(" function beforeEditCallback(e) {\r\n");
out.write(" var form = $(e[0]);\r\n");
out.write(" form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class=\"widget-header\" />')\r\n");
out.write(" style_edit_form(form);\r\n");
out.write(" }\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write(" //it causes some flicker when reloading or navigating grid\r\n");
out.write(" //it may be possible to have some custom formatter to do this as the grid is being created to prevent this\r\n");
out.write(" //or go back to default browser checkbox styles for the grid\r\n");
out.write(" function styleCheckbox(table) {\r\n");
out.write(" /**\r\n");
out.write(" $(table).find('input:checkbox').addClass('ace')\r\n");
out.write(" .wrap('<label />')\r\n");
out.write(" .after('<span class=\"lbl align-top\" />')\r\n");
out.write(" \r\n");
out.write(" \r\n");
out.write(" $('.ui-jqgrid-labels th[id*=\"_cb\"]:first-child')\r\n");
out.write(" .find('input.cbox[type=checkbox]').addClass('ace')\r\n");
out.write(" .wrap('<label />').after('<span class=\"lbl align-top\" />');\r\n");
out.write(" */\r\n");
out.write(" }\r\n");
out.write("\r\n");
out.write("\r\n");
out.write(" //unlike navButtons icons, action icons in rows seem to be hard-coded\r\n");
out.write(" //you can change them like this in here if you want\r\n");
out.write(" function updateActionIcons(table) {\r\n");
out.write(" /**\r\n");
out.write(" var replacement = \r\n");
out.write(" {\r\n");
out.write(" 'ui-ace-icon fa fa-pencil' : 'ace-icon fa fa-pencil blue',\r\n");
out.write(" 'ui-ace-icon fa fa-trash-o' : 'ace-icon fa fa-trash-o red',\r\n");
out.write(" 'ui-icon-disk' : 'ace-icon fa fa-check green',\r\n");
out.write(" 'ui-icon-cancel' : 'ace-icon fa fa-times red'\r\n");
out.write(" };\r\n");
out.write(" $(table).find('.ui-pg-div span.ui-icon').each(function(){\r\n");
out.write(" var icon = $(this);\r\n");
out.write(" var $class = $.trim(icon.attr('class').replace('ui-icon', ''));\r\n");
out.write(" if($class in replacement) icon.attr('class', 'ui-icon '+replacement[$class]);\r\n");
out.write(" })\r\n");
out.write(" */\r\n");
out.write(" }\r\n");
out.write("\r\n");
out.write(" //replace icons with FontAwesome icons like above\r\n");
out.write(" function updatePagerIcons(table) {\r\n");
out.write(" var replacement =\r\n");
out.write(" {\r\n");
out.write(" 'ui-icon-seek-first': 'ace-icon fa fa-angle-double-left bigger-140',\r\n");
out.write(" 'ui-icon-seek-prev': 'ace-icon fa fa-angle-left bigger-140',\r\n");
out.write(" 'ui-icon-seek-next': 'ace-icon fa fa-angle-right bigger-140',\r\n");
out.write(" 'ui-icon-seek-end': 'ace-icon fa fa-angle-double-right bigger-140'\r\n");
out.write(" };\r\n");
out.write(" $('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function () {\r\n");
out.write(" var icon = $(this);\r\n");
out.write(" var $class = $.trim(icon.attr('class').replace('ui-icon', ''));\r\n");
out.write("\r\n");
out.write(" if ($class in replacement)\r\n");
out.write(" icon.attr('class', 'ui-icon ' + replacement[$class]);\r\n");
out.write(" })\r\n");
out.write(" }\r\n");
out.write("\r\n");
out.write(" function enableTooltips(table) {\r\n");
out.write(" $('.navtable .ui-pg-button').tooltip({container: 'body'});\r\n");
out.write(" $(table).find('.ui-pg-div').tooltip({container: 'body'});\r\n");
out.write(" }\r\n");
out.write("\r\n");
out.write(" //var selr = jQuery(grid_selector).jqGrid('getGridParam','selrow');\r\n");
out.write("\r\n");
out.write(" $(document).one('ajaxloadstart.page', function (e) {\r\n");
out.write(" $.jgrid.gridDestroy(grid_selector);\r\n");
out.write(" $('.ui-jqdialog').remove();\r\n");
out.write(" });\r\n");
out.write(" });\r\n");
out.write("</script>\r\n");
out.write("\r\n");
out.write("<div id=\"goog-gt-tt\" class=\"skiptranslate\" dir=\"ltr\"><div style=\"padding: 8px;\"><div><div class=\"logo\"><img src=\"https://www.gstatic.com/images/branding/product/1x/translate_24dp.png\" width=\"20\" height=\"20\" alt=\"Google Tradutor\"></div></div></div><div class=\"top\" style=\"padding: 8px; float: left; width: 100%;\"><h1 class=\"title gray\">Texto original</h1></div><div class=\"middle\" style=\"padding: 8px;\"><div class=\"original-text\"></div></div><div class=\"bottom\" style=\"padding: 8px;\"><div class=\"activity-links\"><span class=\"activity-link\">Sugerir uma tradução melhor</span><span class=\"activity-link\"></span></div><div class=\"started-activity-container\"><hr style=\"color: #CCC; background-color: #CCC; height: 1px; border: none;\"><div class=\"activity-root\"></div></div></div><div class=\"status-message\" style=\"display: none;\"></div></div>\r\n");
out.write("\r\n");
out.write("<div class=\"ui-jqdialog ui-widget ui-widget-content ui-corner-all\" id=\"alertmod_grid-table\" dir=\"ltr\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"alerthd_grid-table\" aria-hidden=\"true\" style=\"width: 200px; height: auto; z-index: 950; overflow: hidden; top: 358.5px; left: 620px;\"><div class=\"ui-jqdialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix\" id=\"alerthd_grid-table\" style=\"cursor: move;\"><span class=\"ui-jqdialog-title\" style=\"float: left;\">Warning</span><a class=\"ui-jqdialog-titlebar-close ui-corner-all\" style=\"right: 0.3em;\"><span class=\"ui-icon ui-icon-closethick\"></span></a></div><div class=\"ui-jqdialog-content ui-widget-content\" id=\"alertcnt_grid-table\"><div>Please, select row</div><span tabindex=\"0\"><span tabindex=\"-1\" id=\"jqg_alrt\"></span></span></div><div class=\"jqResize ui-resizable-handle ui-resizable-se ui-icon ui-icon-gripsmall-diagonal-se\"></div></div>\r\n");
out.write("<div class=\"goog-te-spinner-pos\"><div class=\"goog-te-spinner-animation\"><svg xmlns=\"http://www.w3.org/2000/svg\" class=\"goog-te-spinner\" width=\"96px\" height=\"96px\" viewBox=\"0 0 66 66\"><circle class=\"goog-te-spinner-path\" fill=\"none\" stroke-width=\"6\" stroke-linecap=\"round\" cx=\"33\" cy=\"33\" r=\"30\"></circle></svg></div></div>");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
<file_sep>/src/java/br/com/Modelo/NivelAdministracao.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.Modelo;
/**
*
* @author d732229
*/
public class NivelAdministracao {
//Atributos
private int pkAdm;
private String sgAdm, nmAdm, nmLogin, dthrAtualizacao;
public int getPkAdm() {
return pkAdm;
}
public void setPkAdm(int pkAdm) {
this.pkAdm = pkAdm;
}
public String getSgAdm() {
return sgAdm;
}
public void setSgAdm(String sgAdm) {
this.sgAdm = sgAdm;
}
public String getNmAdm() {
return nmAdm;
}
public void setNmAdm(String nmAdm) {
this.nmAdm = nmAdm;
}
public String getNmLogin() {
return nmLogin;
}
public void setNmLogin(String nmLogin) {
this.nmLogin = nmLogin;
}
public String getDthrAtualizacao() {
return dthrAtualizacao;
}
public void setDthrAtualizacao(String dthrAtualizacao) {
this.dthrAtualizacao = dthrAtualizacao;
}
}
<file_sep>/src/java/br/com/Controle/ControllerServlet.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.Controle;
import br.com.Modelo.Logica;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author d732229
*/
@MultipartConfig
public class ControllerServlet extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String acao = request.getParameter("acao");
String ClasseAcao = "br.com.Controle." + acao;
try {
Class classe = Class.forName(ClasseAcao);
Logica logica = (Logica) classe.newInstance();
String pagina = logica.executa(request, response);
request.getRequestDispatcher(pagina).forward(request, response);
} catch (Exception e) {
throw new ServletException(
"\nA lógica de negócios causou uma exceção", e);
}
}
}
<file_sep>/src/java/br/com/Controle/CatAutoCessaoCU.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.Controle;
import br.com.Modelo.CatAutoCessao;
import br.com.Modelo.CatAutoCessaoDAO;
import br.com.Modelo.Logica;
import br.com.Utilitario.Transformar;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author d732229
*/
public class CatAutoCessaoCU implements Logica {
@Override
public String executa(HttpServletRequest req,
HttpServletResponse res) throws Exception{
CatAutoCessao catauto = new CatAutoCessao();
CatAutoCessaoDAO catautoDAO = new CatAutoCessaoDAO();
HttpSession session = req.getSession();
//Atributo
int pkCatAutoCessao;
String sigla, catautocessao, loginSessio, execucao;
//Carregando os atributos com as informações do formulário
execucao = req.getParameter("execucao");
sigla = req.getParameter("sigla").toUpperCase();
catautocessao = Transformar.getRemoveAccents(req.getParameter("catautocessao")).toUpperCase().trim();
loginSessio =(String) session.getAttribute("sessionLogin");
//Tratando para executar o inserir ou alterar, populando o objeto e gravando no banco
if ("edit".equals(execucao)){
pkCatAutoCessao = Integer.parseInt(req.getParameter("pkCatAutoCessao"));
catauto = new CatAutoCessao(pkCatAutoCessao, sigla, catautocessao, loginSessio);
catautoDAO.upCatAutoCessao(catauto);
req.setAttribute("msg","alterou");
}else if ("insert".equals(execucao)) {
catauto = new CatAutoCessao(sigla, catautocessao, loginSessio);
catautoDAO.cCatAutoCessao(catauto);
req.setAttribute("msg","gravou");
}
return "ControllerServlet?acao=CatAutoCessaoLista";
}
}
<file_sep>/src/java/br/com/Controle/DivisaoDetalhe.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.Controle;
import br.com.Modelo.*;
import br.com.Modelo.Divisao;
import br.com.Modelo.DivisaoDAO;
import br.com.Modelo.Logica;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author d732229
*/
public class DivisaoDetalhe implements Logica{
@Override
public String executa(HttpServletRequest req,
HttpServletResponse res) throws Exception {
//Atributo
int pkDivisao;
String execucao;
//Carregando os atributos com as informações do formulário
pkDivisao = Integer.parseInt(req.getParameter("pkDivisao"));
execucao = req.getParameter("execucao");
//Consulta no banco e populando o objeto
DivisaoDAO dvDAO = new DivisaoDAO();
Divisao dv = dvDAO.detalheDivisao(pkDivisao);
req.setAttribute("dv", dv);
req.setAttribute("execucao", execucao);
return "DivisaoCRU.jsp";
}
}
<file_sep>/src/java/br/com/Controle/CatFinalidadeDetalhe.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.Controle;
import br.com.Modelo.CatFinalidade;
import br.com.Modelo.CatFinalidadeDAO;
import br.com.Modelo.Logica;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author d732229
*/
public class CatFinalidadeDetalhe implements Logica {
@Override
public String executa(HttpServletRequest req,
HttpServletResponse res) throws Exception {
//Atributo
int pkCatFinalidade;
String execucao;
//Carregando os atributos com as informações do formulário
pkCatFinalidade = Integer.parseInt(req.getParameter("pkCatFinalidade"));
execucao = req.getParameter("execucao");
//Consulta no banco e populando o objeto
CatFinalidadeDAO catFinDAO = new CatFinalidadeDAO();
CatFinalidade catFin = catFinDAO.detalheCatFinalidade(pkCatFinalidade);
req.setAttribute("catFin", catFin);
req.setAttribute("execucao", execucao);
return "CatFinalidadeCRU.jsp";
}
}
<file_sep>/src/java/br/com/Controle/AutoCessaoDispLegalUC.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.Controle;
import br.com.Modelo.AutoCessaoDAO;
import br.com.Modelo.DispositivoLegal;
import br.com.Modelo.DispositivoLegalDAO;
import br.com.Modelo.Logica;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author d732229
*/
public class AutoCessaoDispLegalUC implements Logica {
@Override
public String executa(HttpServletRequest req,
HttpServletResponse res) throws Exception {
HttpSession session = req.getSession();
DispositivoLegalDAO dispDAO = new DispositivoLegalDAO();
AutoCessaoDAO autoDAO = new AutoCessaoDAO();
List<DispositivoLegal> lisDis = new ArrayList<DispositivoLegal>();
String[] tpDispositivo;
String[] nrDispositivo;
String[] dtDispositivo;
String execucao,loginSessio;
int pkAutoStage, cont, nrVerDisplegal;
execucao = req.getParameter("execucao");
tpDispositivo = req.getParameterValues("tpDispositivo");
nrDispositivo = req.getParameterValues("numDispositivo");
dtDispositivo = req.getParameterValues("dtDispositivo");
pkAutoStage = Integer.parseInt(req.getParameter("pkAutoCessao"));
loginSessio = (String) session.getAttribute("sessionLogin");
nrVerDisplegal = Integer.parseInt(req.getParameter("nrVerDisplegal"));
cont = tpDispositivo.length;
for (int i=0; i<cont; i++){
DispositivoLegal disp = new DispositivoLegal();
disp.setFkAutoCessao(pkAutoStage);
disp.setFkTipoDisplegal(Integer.parseInt(tpDispositivo[i]));
disp.setNrDisp(nrDispositivo[i]);
disp.setDtDisp(dtDispositivo[i]);
disp.setNmLogin(loginSessio);
lisDis.add(disp);
}
for(DispositivoLegal d : lisDis){
dispDAO.cDisLegal(d);
}
autoDAO.upAutoCessaoVerificadoDisLegal(pkAutoStage, nrVerDisplegal);
req.setAttribute("msg", "true");
req.setAttribute("tipoAler", "success");
req.setAttribute("alert", "Sucesso! ");
req.setAttribute("txtAlert", "O(s) dispositivo(s) legal(is) foi(ram) salvo(s)");
return "ControllerServlet?acao=AutoCessaoDetalhe&pkAutoStage="+pkAutoStage+"&execucao="+execucao;
}
}
<file_sep>/src/java/br/com/Controle/AutoCessaoDeleteArquivo.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.Controle;
import br.com.Modelo.Arquivo;
import br.com.Modelo.ArquivoDAO;
import br.com.Modelo.AutoCessaoDAO;
import br.com.Modelo.Logica;
import br.com.Utilitario.Upload;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author d732229
*/
public class AutoCessaoDeleteArquivo implements Logica {
@Override
public String executa(HttpServletRequest req,
HttpServletResponse res) throws Exception {
Upload up = new Upload();
ArquivoDAO arDAO = new ArquivoDAO();
AutoCessaoDAO autoDAO = new AutoCessaoDAO();
Arquivo ar = new Arquivo();
int pkArquivo =0, pkAutoCessao;
String execucao, diretorio, nmTipo;
boolean deletado;
pkArquivo = Integer.parseInt(req.getParameter("pkArquivo"));
pkAutoCessao = Integer.parseInt(req.getParameter("pkAutoCessao"));
diretorio = req.getParameter("diretorio");
nmTipo = req.getParameter("nmTipo");
execucao = req.getParameter("execucao");
// ar = arDAO.pkArquivo(pkArquivo);
deletado = up.deltar(diretorio);
if(deletado){
arDAO.deleteArquvio(pkArquivo);
if ("Planta".equals(nmTipo)) {
autoDAO.upAutoCessaoVerificadoArquivoPlanta(pkAutoCessao, 0);
} else {
autoDAO.upAutoCessaoVerificadoArquivoAc(pkAutoCessao, 0);
}
req.setAttribute("msg", "true");
req.setAttribute("tipoAler", "success");
req.setAttribute("alert", "Sucesso! ");
req.setAttribute("txtAlert", "O arquivo "+nmTipo+" foi excluído com sucesso.");
return "ControllerServlet?acao=AutoCessaoDetalhe&pkAutoCessao="+pkAutoCessao+"&execucao="+execucao;
}
req.setAttribute("msg", "true");
req.setAttribute("tipoAler", "danger");
req.setAttribute("alert", "Erro! ");
req.setAttribute("txtAlert", "Não foi possível excluír o arquivo, por favor contate o administrado do sistema! ");
return "ControllerServlet?acao=AutoCessaoDetalhe&pkAutoCessao="+pkAutoCessao+"&execucao="+execucao;
}
}
<file_sep>/src/java/br/com/Modelo/NivelAdministracaoDAO.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.Modelo;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author d732229
*/
public class NivelAdministracaoDAO {
//Atrituto
private final Connection connection;
//Construtor
public NivelAdministracaoDAO() {
this.connection = new FabricaConexao().getConnetion();
}
//METODO lista os NivelAdm select
public List<NivelAdministracao> listNivelAdm() throws SQLException {
PreparedStatement stmt = null;
ResultSet rs = null;
List<NivelAdministracao> lisNivelAdm = new ArrayList<>();
String sql = ("SELECT id_niveladministracao, sg_administracao, nm_administracao, nm_login, dthr_atualizacao "
+ "FROM tbl_niveladministracao "
+ "ORDER BY nm_administracao");
try {
stmt = connection.prepareStatement(sql);
rs = stmt.executeQuery();
while (rs.next()){
NivelAdministracao nvadm = new NivelAdministracao();
nvadm.setPkAdm(rs.getInt("id_niveladministracao"));
nvadm.setSgAdm(rs.getString("sg_administracao"));
nvadm.setNmAdm(rs.getString("nm_administracao"));
nvadm.setNmLogin(rs.getString("nm_login"));
nvadm.setDthrAtualizacao(rs.getString("dthr_atualizacao"));
lisNivelAdm.add(nvadm);
}
stmt.execute();
return lisNivelAdm;
} catch (SQLException e) {
throw new RuntimeException(e);
}finally{
rs.close();
stmt.close();
connection.close();
}
}
//METODO utilizado para retornar as informação de um Nivel Administração
public NivelAdministracao detalheNivelAdm(int pkNivelAdm) throws SQLException{
PreparedStatement stmt = null;
ResultSet rs = null;
NivelAdministracao nvadm = new NivelAdministracao();
String sql = "SELECT id_niveladministracao, sg_administracao, nm_administracao, nm_login, dthr_atualizacao "
+ "FROM tbl_niveladministracao "
+ "WHERE id_niveladministracao = ?";
try{
stmt = connection.prepareStatement(sql);
stmt.setInt(1, pkNivelAdm);
rs = stmt.executeQuery();
if(rs.next()){
nvadm.setPkAdm(rs.getInt("id_niveladministracao"));
nvadm.setSgAdm(rs.getString("sg_administracao"));
nvadm.setNmAdm(rs.getString("nm_administracao"));
nvadm.setNmLogin(rs.getString("nm_login"));
nvadm.setDthrAtualizacao(rs.getString("dthr_atualizacao"));
}
return nvadm;
}catch (SQLException e){
throw new RuntimeException(e);
}finally{
rs.close();
stmt.close();
// connection.close();
}
}
}
<file_sep>/src/java/br/com/Modelo/CatFinalidadeDAO.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.Modelo;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author d732229
*/
public class CatFinalidadeDAO {
private final Connection connection;
//Construtor
public CatFinalidadeDAO() {
this.connection = new FabricaConexao().getConnetion();
}
//Metodo de quantidade de linhas
public int qdCatFinalidade (String q) throws SQLException{
PreparedStatement stmt = null;
ResultSet rs = null;
int total = 0;
String sql = ("SELECT COUNT(*) as total "
+ "FROM tbl_categoriafinalidade "
+ "WHERE (sg_categoriafinalidade ILIKE ? or nm_categoriafinalidade ILIKE ? ) ");
try{
stmt = connection.prepareStatement(sql);
stmt.setString(1, '%'+q+'%');
stmt.setString(2, '%'+q+'%');
rs = stmt.executeQuery();
if(rs.next()){
total = rs.getInt("total");
}
return total;
}catch (SQLException e){
throw new RuntimeException(e);
}finally{
rs.close();
stmt.close();
connection.close();
}
}
//METODO lista as Categoria Finalidade das pesquisas e paginada
public List<CatFinalidade> listCatFinalidade (int qtLinha, int offset, String q ) throws SQLException{
PreparedStatement stmt = null;
ResultSet rs = null;
List<CatFinalidade> lisCatFin = new ArrayList<CatFinalidade>();
String sql = ("SELECT id_categoriafinalidade, sg_categoriafinalidade, nm_categoriafinalidade, nm_login, dthr_atualizacao "
+ "FROM tbl_categoriafinalidade "
+ "WHERE (sg_categoriafinalidade ILIKE ? or nm_categoriafinalidade ILIKE ? ) "
+ "ORDER BY nm_categoriafinalidade "
+ "LIMIT ? OFFSET ? ");
try{
stmt = connection.prepareStatement(sql);
stmt.setString(1,'%'+q+'%');
stmt.setString(2,'%'+q+'%');
stmt.setInt(3, qtLinha);
stmt.setInt(4, offset);
rs = stmt.executeQuery();
while (rs.next()){
CatFinalidade catFin = new CatFinalidade();
catFin.setPkCatFinalidade(rs.getInt("id_categoriafinalidade"));
catFin.setSgCatFinalidade(rs.getString("sg_categoriafinalidade"));
catFin.setNmCatFinalidade(rs.getString("nm_categoriafinalidade"));
catFin.setNmLogin(rs.getString("nm_login"));
catFin.setDthrAtualizacao(rs.getString("dthr_atualizacao"));
lisCatFin.add(catFin);
}
return lisCatFin;
}catch (SQLException e){
throw new RuntimeException(e);
}finally{
rs.close();
stmt.close();
connection.close();
}
}
//METODO utilizado para retornar as informação de um Categoria Finalidade
public CatFinalidade detalheCatFinalidade(int pkCatFinalidade) throws SQLException{
PreparedStatement stmt = null;
ResultSet rs = null;
CatFinalidade catFin = new CatFinalidade();
String sql = "SELECT id_categoriafinalidade, sg_categoriafinalidade, nm_categoriafinalidade, nm_login, dthr_atualizacao "
+ "FROM tbl_categoriafinalidade "
+ "WHERE id_categoriafinalidade = ?";
try{
stmt = connection.prepareStatement(sql);
stmt.setInt(1, pkCatFinalidade);
rs = stmt.executeQuery();
if(rs.next()){
catFin.setPkCatFinalidade(rs.getInt("id_categoriafinalidade"));
catFin.setSgCatFinalidade(rs.getString("sg_categoriafinalidade"));
catFin.setNmCatFinalidade(rs.getString("nm_categoriafinalidade"));
catFin.setNmLogin(rs.getString("nm_login"));
catFin.setDthrAtualizacao(rs.getString("dthr_atualizacao"));
}
return catFin;
}catch (SQLException e){
throw new RuntimeException(e);
}finally{
rs.close();
stmt.close();
// connection.close();
}
}
//METODO utilizado para inserir uma nova Categoria Finalidade no BANCO
public void cCatFinalidade(CatFinalidade catFin) throws SQLException{
PreparedStatement stmt = null;
String sql = "INSERT INTO tbl_categoriafinalidade "
+ "(sg_categoriafinalidade, nm_categoriafinalidade, nm_login, dthr_atualizacao) "
+ "VALUES (?,?,?,? )";
try{
stmt = connection.prepareStatement(sql);
stmt.setString(1, catFin.getSgCatFinalidade());
stmt.setString(2, catFin.getNmCatFinalidade());
stmt.setString(3, catFin.getNmLogin());
stmt.setTimestamp(4,java.sql.Timestamp.valueOf(java.time.LocalDateTime.now()));
stmt.execute();
}catch (SQLException e){
throw new RuntimeException(e);
}finally{
stmt.close();
connection.close();
}
}
//MEDOTO utilizado para realizar a alteração das informações de um Categoria Finalidade
public void upCatFinalidade(CatFinalidade catFin) throws SQLException{
PreparedStatement stmt = null;
String sql = "UPDATE tbl_categoriafinalidade SET "
+ "sg_categoriafinalidade=?, nm_categoriafinalidade=?, nm_login=?, dthr_atualizacao=? "
+ "WHERE id_categoriafinalidade = ?";
try{
stmt = connection.prepareStatement(sql);
stmt.setString(1, catFin.getSgCatFinalidade() );
stmt.setString(2, catFin.getNmCatFinalidade() );
stmt.setString(3, catFin.getNmLogin() );
stmt.setTimestamp(4,java.sql.Timestamp.valueOf(java.time.LocalDateTime.now()));
stmt.setInt(5, catFin.getPkCatFinalidade());
stmt.execute();
}catch (SQLException e){
throw new RuntimeException(e);
}finally{
stmt.close();
connection.close();
}
}
//METODO lista a Categoria Finalidade para campo select
public List<CatFinalidade> listSelectCatFinalidade() throws SQLException {
PreparedStatement stmt = null;
ResultSet rs = null;
List<CatFinalidade> lisCatFin = new ArrayList<CatFinalidade>();
String sql = "SELECT id_categoriafinalidade, sg_categoriafinalidade, nm_categoriafinalidade, nm_login, dthr_atualizacao "
+ "FROM tbl_categoriafinalidade "
+ "ORDER BY nm_categoriafinalidade";
try {
stmt = connection.prepareStatement(sql);
rs = stmt.executeQuery();
while (rs.next()){
CatFinalidade catFin = new CatFinalidade();
catFin.setPkCatFinalidade(rs.getInt("id_categoriafinalidade"));
catFin.setSgCatFinalidade(rs.getString("sg_categoriafinalidade"));
catFin.setNmCatFinalidade(rs.getString("nm_categoriafinalidade"));
catFin.setNmLogin(rs.getString("nm_login"));
catFin.setDthrAtualizacao(rs.getString("dthr_atualizacao"));
lisCatFin.add(catFin);
}
return lisCatFin;
} catch (SQLException e) {
throw new RuntimeException(e);
}finally{
rs.close();
stmt.close();
connection.close();
}
}
}
<file_sep>/test/teste/utilitarios/ExemploPropridade.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package teste.utilitarios;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author d732229
*/
@WebServlet(name = "NewServlet", urlPatterns = {"/NewServlet"})
public class ExemploPropridade extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
// List list = new ArrayList();
// System.out.println("Obtendo Informacões da Rede:");
//
// InetAddress addr = InetAddress.getLocalHost();
// byte[] ipAddr = addr.getAddress();
// String hostname = addr.getHostName();
// System.out.println("Nome do Computador completo: " + hostname);
//
// InetAddress localHost = Inet4Address.getLocalHost();
// NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localHost);
// System.out.println("Placa: " + networkInterface.getDisplayName());
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet NewServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet NewServlet at " + request.getContextPath() + "</h1>");
// List list = new ArrayList();
// out.println("Obtendo Informacões da Rede:");
//
// InetAddress addr = InetAddress.getLocalHost();
// byte[] ipAddr = addr.getAddress();
//
// String hostname = addr.getHostName();
// out.println("<br />Nome do Computador completo: " + hostname);
//
// InetAddress localHost = Inet4Address.getLocalHost();
// NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localHost);
// out.println("<br />Placa: " + networkInterface.getDisplayName()+"<br />");
Properties p = System.getProperties();
p.list(System.out);
out.println("<br /> Login user: "+p.getProperty("user.name")+"<br />");
// Enumeration ifaces = NetworkInterface.getNetworkInterfaces();
// while (ifaces.hasMoreElements()) {
// NetworkInterface iface = (NetworkInterface)ifaces.nextElement();
// out.println("<br />Obtendo Informacões da interface: " + iface.getName());
// for (InterfaceAddress address : iface.getInterfaceAddresses()){
// out.println("<br />IP........: " + address.getAddress().toString());
// Object bc = address.getBroadcast();
// out.println("<br />Broadcast.: " + bc);
// out.println("<br />Máscara...: " + address.getNetworkPrefixLength()+"<br />");
// }
// }
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
<file_sep>/test/teste/utilitarios/CalcPrazoVencimento.java
package teste.utilitarios;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import br.com.Modelo.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
/**
*
* @author d732229
*/
public class CalcPrazoVencimento {
public static void main(String args[]) throws ParseException {
// public Date somaDiasMesAno(Date data, int dias, int mes, int ano) {
Calendar cal = new GregorianCalendar();
String hoje = "21/11/2018";
DateFormat converter =new SimpleDateFormat("dd/MM/yyyy",Locale.getDefault());
Date data = converter.parse(hoje);
int dias=0, mes=0, ano=0;
int altD=0, aldM=0, altAno=0;
cal.setTime(data);
cal.add(Calendar.DAY_OF_MONTH, +dias);
cal.add(Calendar.MONTH, +mes+1);// No calendário do java Janeiro = 0, Fevereiro=1, etc.
cal.add(Calendar.YEAR, +ano);
System.out.println("Data: "+data);
System.out.println("\nData: "+cal.getTime());
//cal.setTime(cal.getTime());
altD = cal.get(Calendar.DAY_OF_MONTH);
aldM = cal.get(Calendar.MONTH);
altAno = cal.get(Calendar.YEAR);
System.out.println("\nDia alt "+altD);
System.out.println("\nMês alt "+aldM);
System.out.println("\nAno alt "+altAno);
//
// return cal.getTime();
}
}
<file_sep>/build/generated/src/org/apache/jsp/AutoCessaoInserir_jsp.java
package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class AutoCessaoInserir_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.List<String> _jspx_dependants;
static {
_jspx_dependants = new java.util.ArrayList<String>(1);
_jspx_dependants.add("/include/ControleAcesso.jsp");
}
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_forEach_var_items;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_set_var_value_nobody;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_redirect_url_nobody;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_set_var_value_scope_nobody;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_choose;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_if_test;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_otherwise;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_when_test;
private org.glassfish.jsp.api.ResourceInjector _jspx_resourceInjector;
public java.util.List<String> getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_jspx_tagPool_c_forEach_var_items = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_c_set_var_value_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_c_redirect_url_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_c_set_var_value_scope_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_c_choose = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_c_if_test = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_c_otherwise = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_jspx_tagPool_c_when_test = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
}
public void _jspDestroy() {
_jspx_tagPool_c_forEach_var_items.release();
_jspx_tagPool_c_set_var_value_nobody.release();
_jspx_tagPool_c_redirect_url_nobody.release();
_jspx_tagPool_c_set_var_value_scope_nobody.release();
_jspx_tagPool_c_choose.release();
_jspx_tagPool_c_if_test.release();
_jspx_tagPool_c_otherwise.release();
_jspx_tagPool_c_when_test.release();
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html charset=UTF-8;");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
_jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("<!DOCTYPE html>\r\n");
out.write("<html>\r\n");
out.write(" \r\n");
out.write(" ");
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "include/head.jsp", out, false);
out.write("\r\n");
out.write(" <body class=\"no-skin\">\r\n");
out.write(" ");
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "include/top.jsp", out, false);
out.write("\r\n");
out.write(" <div class=\"main-container ace-save-state\" id=\"main-container\">\r\n");
out.write(" ");
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "include/nav.jsp", out, false);
out.write("\r\n");
out.write("\r\n");
out.write("<!--Verificação de acesso -->\r\n");
out.write(" ");
if (_jspx_meth_c_set_0(_jspx_page_context))
return;
out.write("\r\n");
out.write(" ");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
if (_jspx_meth_c_choose_0(_jspx_page_context))
return;
out.write("\r\n");
out.write(" \r\n");
out.write(" \r\n");
out.write(" \r\n");
out.write(" ");
br.com.Modelo.TipoAutoCessaoDAO TpCessao = null;
synchronized (_jspx_page_context) {
TpCessao = (br.com.Modelo.TipoAutoCessaoDAO) _jspx_page_context.getAttribute("TpCessao", PageContext.PAGE_SCOPE);
if (TpCessao == null){
TpCessao = new br.com.Modelo.TipoAutoCessaoDAO();
_jspx_page_context.setAttribute("TpCessao", TpCessao, PageContext.PAGE_SCOPE);
}
}
out.write("\r\n");
out.write(" ");
br.com.Modelo.CatFinalidadeDAO CatFin = null;
synchronized (_jspx_page_context) {
CatFin = (br.com.Modelo.CatFinalidadeDAO) _jspx_page_context.getAttribute("CatFin", PageContext.PAGE_SCOPE);
if (CatFin == null){
CatFin = new br.com.Modelo.CatFinalidadeDAO();
_jspx_page_context.setAttribute("CatFin", CatFin, PageContext.PAGE_SCOPE);
}
}
out.write("\r\n");
out.write(" ");
br.com.Modelo.CatAutoCessaoDAO CatAuto = null;
synchronized (_jspx_page_context) {
CatAuto = (br.com.Modelo.CatAutoCessaoDAO) _jspx_page_context.getAttribute("CatAuto", PageContext.PAGE_SCOPE);
if (CatAuto == null){
CatAuto = new br.com.Modelo.CatAutoCessaoDAO();
_jspx_page_context.setAttribute("CatAuto", CatAuto, PageContext.PAGE_SCOPE);
}
}
out.write("\r\n");
out.write(" ");
br.com.Modelo.CatContrapartidaDAO CatContra = null;
synchronized (_jspx_page_context) {
CatContra = (br.com.Modelo.CatContrapartidaDAO) _jspx_page_context.getAttribute("CatContra", PageContext.PAGE_SCOPE);
if (CatContra == null){
CatContra = new br.com.Modelo.CatContrapartidaDAO();
_jspx_page_context.setAttribute("CatContra", CatContra, PageContext.PAGE_SCOPE);
}
}
out.write("\r\n");
out.write(" ");
br.com.Modelo.TipoDispositivoLegalDAO TpDis = null;
synchronized (_jspx_page_context) {
TpDis = (br.com.Modelo.TipoDispositivoLegalDAO) _jspx_page_context.getAttribute("TpDis", PageContext.PAGE_SCOPE);
if (TpDis == null){
TpDis = new br.com.Modelo.TipoDispositivoLegalDAO();
_jspx_page_context.setAttribute("TpDis", TpDis, PageContext.PAGE_SCOPE);
}
}
out.write("\r\n");
out.write(" ");
br.com.Modelo.SubPrefeituraDAO subPref = null;
synchronized (_jspx_page_context) {
subPref = (br.com.Modelo.SubPrefeituraDAO) _jspx_page_context.getAttribute("subPref", PageContext.PAGE_SCOPE);
if (subPref == null){
subPref = new br.com.Modelo.SubPrefeituraDAO();
_jspx_page_context.setAttribute("subPref", subPref, PageContext.PAGE_SCOPE);
}
}
out.write("\r\n");
out.write(" ");
br.com.Modelo.DispositivoLegalDAO Disp = null;
synchronized (_jspx_page_context) {
Disp = (br.com.Modelo.DispositivoLegalDAO) _jspx_page_context.getAttribute("Disp", PageContext.PAGE_SCOPE);
if (Disp == null){
Disp = new br.com.Modelo.DispositivoLegalDAO();
_jspx_page_context.setAttribute("Disp", Disp, PageContext.PAGE_SCOPE);
}
}
out.write("\r\n");
out.write(" ");
br.com.Modelo.ArquivoDAO Arquivo = null;
synchronized (_jspx_page_context) {
Arquivo = (br.com.Modelo.ArquivoDAO) _jspx_page_context.getAttribute("Arquivo", PageContext.PAGE_SCOPE);
if (Arquivo == null){
Arquivo = new br.com.Modelo.ArquivoDAO();
_jspx_page_context.setAttribute("Arquivo", Arquivo, PageContext.PAGE_SCOPE);
}
}
out.write("\r\n");
out.write(" \r\n");
out.write(" ");
if (_jspx_meth_c_set_3(_jspx_page_context))
return;
out.write(" \r\n");
out.write(" \r\n");
out.write(" <div class=\"breadcrumbs ace-save-state\" id=\"breadcrumbs\">\r\n");
out.write(" <ul class=\"breadcrumb\">\r\n");
out.write(" <li><i class=\"ace-icon fa fa-list\"></i> Auto de Cessão ");
if (_jspx_meth_c_if_0(_jspx_page_context))
return;
out.write("</li>\r\n");
out.write(" </ul>\r\n");
out.write(" </div> \r\n");
out.write(" <div class=\"page-content\">\r\n");
out.write(" <div class=\"row\">\r\n");
out.write(" <div class=\"col-xs-12\">\r\n");
out.write(" \r\n");
out.write(" \r\n");
out.write(" <div class=\"col-sm-offset-1 col-sm-10\">\r\n");
out.write(" <h2>Cadastro de Auto de Cessão ");
if (_jspx_meth_c_if_1(_jspx_page_context))
return;
out.write("</h2>\r\n");
out.write(" <div class=\"space-14\"></div>\r\n");
out.write(" <div class=\"form-horizontal\">\r\n");
out.write(" <div class=\"tabbable\">\r\n");
out.write(" <ul class=\"nav nav-tabs padding-0\">\r\n");
out.write(" <li class=\"active\">\r\n");
out.write(" <a data-toggle=\"tab\" href=\"#auto-cessao\" aria-expanded=\"true\">\r\n");
out.write(" \r\n");
out.write(" Auto Cessão ");
if (_jspx_meth_c_if_2(_jspx_page_context))
return;
out.write("</h2>\r\n");
out.write(" </a>\r\n");
out.write(" </li>\r\n");
out.write(" </ul>\r\n");
out.write("\r\n");
out.write(" <div class=\"tab-content profile-edit-tab-content\">\r\n");
out.write(" <div id=\"auto-cessao\" class=\"tab-pane in active\">\r\n");
out.write(" <form \r\n");
out.write(" ");
if (_jspx_meth_c_choose_1(_jspx_page_context))
return;
out.write("\r\n");
out.write(" method=\"POST\" >\r\n");
out.write(" <div class=\"space-4\"></div>\r\n");
out.write(" <div class=\"space-2\"></div>\r\n");
out.write("\r\n");
out.write(" <div class=\"form-group\">\r\n");
out.write(" <div class=\"inline col-md-2 col-xs-12\">\r\n");
out.write(" <span class=\"lbl\"><strong>Data Lavratura:</strong></span>\r\n");
out.write(" </div>\r\n");
out.write(" <label class=\"inline col-md-3 col-xs-12 \">\r\n");
out.write(" <div class=\"input-group\">\r\n");
out.write(" <input class=\"form-control date-picker\" id=\"id-date-picker-1\" name=\"dtlavratura\" type=\"text\" placeholder=\"dd/mm/aaaa\" data-date-format=\"dd/mm/yyyy\">\r\n");
out.write(" <span class=\"input-group-addon\">\r\n");
out.write(" <i class=\"fa fa-calendar bigger-110\"></i>\r\n");
out.write(" </span>\r\n");
out.write(" </div>\r\n");
out.write(" </label>\r\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\">\r\n");
out.write(" <span class=\"lbl\"><strong>Nº Processo:</strong></span>\r\n");
out.write(" </label>\r\n");
out.write(" <label class=\"inline col-md-4 col-xs-12\">\r\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" name=\"nrprocesso\" placeholder=\"nº do processo\" >\r\n");
out.write(" </label>\r\n");
out.write(" </div>\r\n");
out.write("\r\n");
out.write(" <div class=\"space-1\"></div> \r\n");
out.write("\r\n");
out.write(" <div class=\"form-group\">\r\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\r\n");
out.write(" <span class=\"lbl\"><strong>Tipo de Cessão:</strong></span>\r\n");
out.write(" </label>\r\n");
out.write(" <label class=\"inline col-md-3 col-xs-12\">\r\n");
out.write(" <select class=\"col-md-12 col-xs-12\" name=\"qTpcessao\">\r\n");
out.write(" <option value=\"\"></option> \r\n");
out.write(" ");
if (_jspx_meth_c_forEach_0(_jspx_page_context))
return;
out.write("\r\n");
out.write(" </select> \r\n");
out.write(" </label>\r\n");
out.write("\r\n");
out.write(" <label class=\"inline col-md-3 col-xs-12\">\r\n");
out.write(" <span class=\"lbl\">\r\n");
out.write(" <strong>Categoria\r\n");
out.write(" ");
if (_jspx_meth_c_choose_2(_jspx_page_context))
return;
out.write("\r\n");
out.write(" </strong>\r\n");
out.write(" </span>\r\n");
out.write(" </label>\r\n");
out.write(" <label class=\"inline col-md-3 col-xs-12\">\r\n");
out.write(" <select class=\"col-md-12 col-xs-12\" name=\"nmNvAdm\">\r\n");
out.write(" <option></option>\r\n");
out.write(" ");
if (_jspx_meth_c_forEach_1(_jspx_page_context))
return;
out.write("\r\n");
out.write("\r\n");
out.write(" </select>\r\n");
out.write(" </label>\r\n");
out.write(" </div> \r\n");
out.write("\r\n");
out.write(" <div class=\"space-1\"></div>\r\n");
out.write("\r\n");
out.write(" <div class=\"form-group\">\r\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\r\n");
out.write(" <span class=\"lbl\">\r\n");
out.write(" <strong>\r\n");
out.write(" ");
if (_jspx_meth_c_choose_4(_jspx_page_context))
return;
out.write("\r\n");
out.write(" </strong>\r\n");
out.write(" </span>\r\n");
out.write(" </label>\r\n");
out.write(" <label class=\"inline col-md-9 col-xs-12\">\r\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" placeholder=\"<NAME> cessionário\" name=\"nmcessionario\" >\r\n");
out.write(" </label>\r\n");
out.write(" </div>\r\n");
out.write("\r\n");
out.write(" <div class=\"space-2\"></div> \r\n");
out.write("\r\n");
out.write(" <div class=\"form-group\">\r\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\r\n");
out.write(" <span class=\"lbl\"><strong>Categoria da finalidade:</strong></span>\r\n");
out.write(" </label>\r\n");
out.write(" <label class=\"inline col-md-3 col-xs-12\">\r\n");
out.write(" <select class=\"col-md-12 col-xs-12\" name=\"\">\r\n");
out.write(" <option></option> \r\n");
out.write(" <option>Educação</option>\r\n");
out.write(" <option>Esporte</option>\r\n");
out.write(" <option>Saúde</option>\r\n");
out.write(" </select>\r\n");
out.write(" </label>\r\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\r\n");
out.write(" <span class=\"lbl\"><strong>Finalidade:</strong></span>\r\n");
out.write(" </label>\r\n");
out.write(" <label class=\"inline col-md-4 col-xs-12\">\r\n");
out.write(" <select class=\"col-md-12 col-xs-12\" name=\"\">\r\n");
out.write(" <option></option>\r\n");
out.write(" <option>Creche</option>\r\n");
out.write(" <option>Escola</option>\r\n");
out.write(" <option>Biblioteca</option>\r\n");
out.write(" <option>Faculdade</option>\r\n");
out.write(" </select>\r\n");
out.write(" </label>\r\n");
out.write(" \r\n");
out.write(" </div>\r\n");
out.write("\r\n");
out.write(" <div class=\"space-1\"></div> \r\n");
out.write(" \r\n");
out.write(" <div class=\"form-group\">\r\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\r\n");
out.write(" <span class=\"lbl\">\r\n");
out.write(" <strong>Detalhamento da Finalidade</strong>\r\n");
out.write(" </span>\r\n");
out.write(" </label>\r\n");
out.write(" <label class=\"inline col-md-8 col-xs-12\">\r\n");
out.write(" <textarea id=\"form-field-11\" class=\"autosize-transition form-control\" name=\"\" style=\"height:200px; margin-left: 0px; width: 670px;\"></textarea>\r\n");
out.write(" </label>\r\n");
out.write(" </div>\r\n");
out.write(" \r\n");
out.write(" <div class=\"space-1\"></div>\r\n");
out.write(" \r\n");
out.write("\r\n");
out.write(" <div class=\"form-group\">\r\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\r\n");
out.write(" <span class=\"lbl\"><strong>Planta:</strong></span>\r\n");
out.write(" </label>\r\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\">\r\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" placeholder=\"nº da planta\" name=\"nmplanta\" >\r\n");
out.write(" </label>\r\n");
out.write("\r\n");
out.write(" <label class=\"inline col-md-1 col-xs-12\" >\r\n");
out.write(" <span class=\"lbl\"><strong>Croqui:</strong></span>\r\n");
out.write(" </label>\r\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\">\r\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" placeholder=\"nº croqui\" name=\"nmcroqui\" >\r\n");
out.write(" </label>\r\n");
out.write("\r\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\r\n");
out.write(" <span class=\"lbl\"><strong>Área do croqui:</strong></span>\r\n");
out.write(" </label>\r\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\">\r\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" placeholder=\"\" name=\"nmarea\" >\r\n");
out.write(" </label>\r\n");
out.write(" </div>\r\n");
out.write("\r\n");
out.write(" <div class=\"space-1\"></div>\r\n");
out.write("\r\n");
out.write(" <div class=\"form-group\">\r\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\r\n");
out.write(" <span class=\"lbl\"><strong>Setor:</strong></span>\r\n");
out.write(" </label>\r\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\">\r\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" placeholder=\"nº do setor²\" name=\"nmSetor\" >\r\n");
out.write(" </label>\r\n");
out.write("\r\n");
out.write(" <label class=\"inline col-md-1 col-xs-12\" >\r\n");
out.write(" <span class=\"lbl\"><strong>Quadra:</strong></span>\r\n");
out.write(" </label>\r\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\">\r\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" placeholder=\"nº da quadra\" name=\"nmquadra\" >\r\n");
out.write(" </label>\r\n");
out.write(" </div>\r\n");
out.write(" <div class=\"space-1\"></div>\r\n");
out.write(" \r\n");
out.write(" <div class=\"form-group\">\r\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\r\n");
out.write(" <span class=\"lbl\"><strong>CAP:</strong></span>\r\n");
out.write(" </label>\r\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\">\r\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" placeholder=\"nº do cap\" name=\"nmcap\" >\r\n");
out.write(" </label>\r\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\r\n");
out.write(" <span class=\"lbl\"><strong>Metragem oficial:</strong></span>\r\n");
out.write(" </label>\r\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\">\r\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" placeholder=\"Área m²\" name=\"\" >\r\n");
out.write(" </label>\r\n");
out.write(" \r\n");
out.write(" </div>\r\n");
out.write("\r\n");
out.write(" <div class=\"space-1\"></div>\r\n");
out.write("\r\n");
out.write(" <div class=\"form-group\">\r\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\r\n");
out.write(" <span class=\"lbl\"><strong>Tipo endereço:</strong></span>\r\n");
out.write(" </label>\r\n");
out.write(" <label class=\"inline col-md-3 col-xs-12\">\r\n");
out.write(" <select class=\"col-md-12 col-xs-12\" name=\"\" title=\"Rua / Avenida / Praça / etc\">\r\n");
out.write(" <option></option>\r\n");
out.write(" <option value=\"AC\">ACESSO</option>\r\n");
out.write(" <option value=\"AL\">ALAMEDA</option>\r\n");
out.write(" <option value=\"AVJ\">AV. PROJETADA</option>\r\n");
out.write(" <option value=\"AV\">AVENIDA</option>\r\n");
out.write(" <option value=\"BLR\">BALAO RETORNO</option>\r\n");
out.write(" <option value=\"BC\">BECO</option>\r\n");
out.write(" <option value=\"CM\">CAMINHO</option>\r\n");
out.write(" <option value=\"CMP\">CAMINHO PART</option>\r\n");
out.write(" <option value=\"CP\">CAMINHO PEDEST</option>\r\n");
out.write(" <option value=\"CV\">COMPLEXO VIARIO</option>\r\n");
out.write(" <option value=\"DV\">DESVIO</option>\r\n");
out.write(" <option value=\"DIV\">DIV</option>\r\n");
out.write(" <option value=\"ENT\">ENT</option>\r\n");
out.write(" <option value=\"ESJ\">ES. PROJETADA</option>\r\n");
out.write(" <option value=\"ESC\">ESC</option>\r\n");
out.write(" <option value=\"EL\">ESPACO LIVRE</option>\r\n");
out.write(" <option value=\"EPL\">ESPLANADA</option>\r\n");
out.write(" <option value=\"ER\">EST. DE RODAGEM</option>\r\n");
out.write(" <option value=\"EST\">ESTACIONAMENTO</option>\r\n");
out.write(" <option value=\"EF\">ESTR. DE FERRO</option>\r\n");
out.write(" <option value=\"ES\">ESTRADA</option>\r\n");
out.write(" <option value=\"ESP\">ESTRADA PART</option>\r\n");
out.write(" <option value=\"GL\">GALERIA</option>\r\n");
out.write(" <option value=\"JD\">JARDIM</option>\r\n");
out.write(" <option value=\"LD\">LADEIRA</option>\r\n");
out.write(" <option value=\"LG\">LARGO</option>\r\n");
out.write(" <option value=\"PQ\">PARQUE</option>\r\n");
out.write(" <option value=\"PS\">PASSAGEM</option>\r\n");
out.write(" <option value=\"PSP\">PASSAGEM PART</option>\r\n");
out.write(" <option value=\"PA\">PASSARELA</option>\r\n");
out.write(" <option value=\"PT\">PATIO</option>\r\n");
out.write(" <option value=\"PTE\">PONTE</option>\r\n");
out.write(" <option value=\"PTL\">PONTILHAO</option>\r\n");
out.write(" <option value=\"PQE\">PQE</option>\r\n");
out.write(" <option value=\"PQL\">PQL</option>\r\n");
out.write(" <option value=\"PQM\">PQM</option>\r\n");
out.write(" <option value=\"PC\">PRACA</option>\r\n");
out.write(" <option value=\"PCM\">PRACA MANOBRA</option>\r\n");
out.write(" <option value=\"PCJ\">PRACA PROJETADA</option>\r\n");
out.write(" <option value=\"PCR\">PRACA RETORNO</option>\r\n");
out.write(" <option value=\"PRO\">PRO</option>\r\n");
out.write(" <option value=\"PSJ\">PS PROJETADA</option>\r\n");
out.write(" <option value=\"PP\">PS. DE PEDESTRE</option>\r\n");
out.write(" <option value=\"PSS\">PS. SUBTERRANEA</option>\r\n");
out.write(" <option value=\"RV\">RODOVIA</option>\r\n");
out.write(" <option value=\"R\">RUA</option>\r\n");
out.write(" <option value=\"RP\">RUA PART</option>\r\n");
out.write(" <option value=\"RPJ\">RUA PROJETADA</option>\r\n");
out.write(" <option value=\"SV\">SERVIDAO</option>\r\n");
out.write(" <option value=\"TV\">TRAVESSA</option>\r\n");
out.write(" <option value=\"TVP\">TRAVESSA PART</option>\r\n");
out.write(" <option value=\"TN\">TUNEL</option>\r\n");
out.write(" <option value=\"TPJ\">TV PROJETADA</option>\r\n");
out.write(" <option value=\"VER\">VEREDA</option>\r\n");
out.write(" <option value=\"VIA\">VIA</option>\r\n");
out.write(" <option value=\"VCP\">VIA CIRC PEDEST</option>\r\n");
out.write(" <option value=\"VP\">VIA DE PEDESTRE</option>\r\n");
out.write(" <option value=\"VEL\">VIA ELEVADA</option>\r\n");
out.write(" <option value=\"VD\">VIADUTO</option>\r\n");
out.write(" <option value=\"VE\">VIELA</option>\r\n");
out.write(" <option value=\"VEP\">VIELA PART</option>\r\n");
out.write(" <option value=\"VEJ\">VIELA PROJETADA</option>\r\n");
out.write(" <option value=\"VES\">VIELA SANITARIA</option>\r\n");
out.write(" <option value=\"VL\">VILA</option>\r\n");
out.write(" <option value=\"VLP\">VLP</option>\r\n");
out.write(" </select>\r\n");
out.write(" </label>\r\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\r\n");
out.write(" <span class=\"lbl\"><strong>Título do endereço:</strong></span>\r\n");
out.write(" </label>\r\n");
out.write(" <label class=\"inline col-md-4 col-xs-12\" >\r\n");
out.write(" <select class=\"col-md-12 col-xs-12\" name=\"\" title=\"Capitão / Doutor / Dom / etc\">\r\n");
out.write(" <option></option>\r\n");
out.write(" <option value=\"ABADE\">ABADE</option>\r\n");
out.write(" <option value=\"ACD\">ACADEMICO</option>\r\n");
out.write(" <option value=\"ADV\">ADVOGADO</option>\r\n");
out.write(" <option value=\"AGTE\">AGENTE</option>\r\n");
out.write(" <option value=\"AGRIC\">AGRIC</option>\r\n");
out.write(" <option value=\"AGRIM\">AGRIMENSOR</option>\r\n");
out.write(" <option value=\"AJUD\">AJUDANTE</option>\r\n");
out.write(" <option value=\"ALF\">ALFERES</option>\r\n");
out.write(" <option value=\"ALM\">ALMIRANTE</option>\r\n");
out.write(" <option value=\"APOST\">APOSTOLO</option>\r\n");
out.write(" <option value=\"ARC\">ARCEBISPO</option>\r\n");
out.write(" <option value=\"ARCIP\">ARCIP</option>\r\n");
out.write(" <option value=\"ARCJO\">ARCJO</option>\r\n");
out.write(" <option value=\"ARQA\">ARQUITETA</option>\r\n");
out.write(" <option value=\"ARQ\">ARQUITETO</option>\r\n");
out.write(" <option value=\"ARQPR\">ARQUITETO PROFESSOR</option>\r\n");
out.write(" <option value=\"ASP\">ASPIRANTE</option>\r\n");
out.write(" <option value=\"AV\">AVENIDA</option>\r\n");
out.write(" <option value=\"AVI\">AVIADOR</option>\r\n");
out.write(" <option value=\"AVIA\">AVIADORA</option>\r\n");
out.write(" <option value=\"BEL\">BACHAREL</option>\r\n");
out.write(" <option value=\"BAND\">BANDEIRANTE</option>\r\n");
out.write(" <option value=\"BANQ\">BANQUEIRO</option>\r\n");
out.write(" <option value=\"BR\">BARAO</option>\r\n");
out.write(" <option value=\"BRA\">BARONESA</option>\r\n");
out.write(" <option value=\"BEPDE\">BEATO PADRE</option>\r\n");
out.write(" <option value=\"BEMAV\">BEM AVENTURADO</option>\r\n");
out.write(" <option value=\"BNTO\">BENEMERITO</option>\r\n");
out.write(" <option value=\"BISP\">BISPO</option>\r\n");
out.write(" <option value=\"BRIG\">BRIGADEIRO</option>\r\n");
out.write(" <option value=\"CABO\">CABO</option>\r\n");
out.write(" <option value=\"CABPM\">CABO PM</option>\r\n");
out.write(" <option value=\"CAD\">CADETE</option>\r\n");
out.write(" <option value=\"CAMP\">CAMPEADOR</option>\r\n");
out.write(" <option value=\"CAP\">CAPITAO</option>\r\n");
out.write(" <option value=\"CPALM\">CAPITAO ALMIRANTE</option>\r\n");
out.write(" <option value=\"CAPFR\">CAPITAO DE FRAGATA</option>\r\n");
out.write(" <option value=\"CAPMG\">CAPITAO DE MAR E GUERRA</option>\r\n");
out.write(" <option value=\"CAPG\">CAPITAO GENERAL</option>\r\n");
out.write(" <option value=\"CAPM\">CAPITAO MOR</option>\r\n");
out.write(" <option value=\"CAPPM\">CAPITAO PM</option>\r\n");
out.write(" <option value=\"CAPT\">CAPITAO TENENTE</option>\r\n");
out.write(" <option value=\"CAR\">CAR</option>\r\n");
out.write(" <option value=\"CARD\">CARDEAL</option>\r\n");
out.write(" <option value=\"CAT\">CATEQUISTA</option>\r\n");
out.write(" <option value=\"CAV\">CAVALEIRO</option>\r\n");
out.write(" <option value=\"CAVLH\">CAVALHEIRO</option>\r\n");
out.write(" <option value=\"CIN\">CINEASTA</option>\r\n");
out.write(" <option value=\"COMTE\">COMANDANTE</option>\r\n");
out.write(" <option value=\"COMED\">COMEDIANTE</option>\r\n");
out.write(" <option value=\"COMEN\">COMENDADOR</option>\r\n");
out.write(" <option value=\"COMIA\">COMISSARIA</option>\r\n");
out.write(" <option value=\"COMIS\">COMISSARIO</option>\r\n");
out.write(" <option value=\"COMP\">COMPOSITOR</option>\r\n");
out.write(" <option value=\"CD\">CONDE</option>\r\n");
out.write(" <option value=\"CDSSA\">CONDESSA</option>\r\n");
out.write(" <option value=\"CON\">CONEGO</option>\r\n");
out.write(" <option value=\"CONF\">CONFRADE</option>\r\n");
out.write(" <option value=\"CONS\">CONSELHEIRO</option>\r\n");
out.write(" <option value=\"CONSU\">CONSUL</option>\r\n");
out.write(" <option value=\"CEL\">CORONEL</option>\r\n");
out.write(" <option value=\"CELPM\">CORONEL PM</option>\r\n");
out.write(" <option value=\"CRG\">CORREGEDOR</option>\r\n");
out.write(" <option value=\"DEL\">DELEGADO</option>\r\n");
out.write(" <option value=\"DENT\">DENTISTA</option>\r\n");
out.write(" <option value=\"DEPA\">DEPUTADA</option>\r\n");
out.write(" <option value=\"DEP\">DEPUTADO</option>\r\n");
out.write(" <option value=\"DEPDR\">DEPUTADO DOUTOR</option>\r\n");
out.write(" <option value=\"DESEM\">DESEMBARGADOR</option>\r\n");
out.write(" <option value=\"DIACO\">DIACO</option>\r\n");
out.write(" <option value=\"DOM\">DOM</option>\r\n");
out.write(" <option value=\"DONA\">DONA</option>\r\n");
out.write(" <option value=\"DR\">DOUTOR</option>\r\n");
out.write(" <option value=\"DRA\">DOUTORA</option>\r\n");
out.write(" <option value=\"DUQ\">DUQUE</option>\r\n");
out.write(" <option value=\"DUQSA\">DUQUESA</option>\r\n");
out.write(" <option value=\"EDIT\">EDITOR</option>\r\n");
out.write(" <option value=\"EDUC\">EDUCADOR</option>\r\n");
out.write(" <option value=\"EDUCA\">EDUCADORA</option>\r\n");
out.write(" <option value=\"EMB\">EMBAIXADOR</option>\r\n");
out.write(" <option value=\"EMBA\">EMBAIXADORA</option>\r\n");
out.write(" <option value=\"EMP\">EMP</option>\r\n");
out.write(" <option value=\"ENGA\">ENGENHEIRA</option>\r\n");
out.write(" <option value=\"ENG\">ENGENHEIRO</option>\r\n");
out.write(" <option value=\"ESCOT\">ESCOTEIRO</option>\r\n");
out.write(" <option value=\"ESC\">ESCRAVO</option>\r\n");
out.write(" <option value=\"ESCR\">ESCRITOR</option>\r\n");
out.write(" <option value=\"EXP\">EXPEDICIONARIO</option>\r\n");
out.write(" <option value=\"FIS\">FISICO</option>\r\n");
out.write(" <option value=\"FREI\">FREI</option>\r\n");
out.write(" <option value=\"GAL\">GENERAL</option>\r\n");
out.write(" <option value=\"GOV\">GOVERNADOR</option>\r\n");
out.write(" <option value=\"GRUM\">GRUMETE</option>\r\n");
out.write(" <option value=\"GCM\">GUARDA CIVIL METROPOLITANO</option>\r\n");
out.write(" <option value=\"IMAC\">IMACULADA</option>\r\n");
out.write(" <option value=\"IMPD\">IMPERADOR</option>\r\n");
out.write(" <option value=\"IMP\">IMPERATRIZ</option>\r\n");
out.write(" <option value=\"INF\">INFANTE</option>\r\n");
out.write(" <option value=\"INSP\">INSPETOR</option>\r\n");
out.write(" <option value=\"IRMA\">IRMA</option>\r\n");
out.write(" <option value=\"IRMAO\">IRMAO</option>\r\n");
out.write(" <option value=\"IRMOS\">IRMAOS</option>\r\n");
out.write(" <option value=\"IRMAS\">IRMAS</option>\r\n");
out.write(" <option value=\"JORN\">JORNALISTA</option>\r\n");
out.write(" <option value=\"LIB\">LIBERTADOR</option>\r\n");
out.write(" <option value=\"LIDCO\">LIDCO</option>\r\n");
out.write(" <option value=\"LIVR\">LIVREIRO</option>\r\n");
out.write(" <option value=\"LORD\">LORDE</option>\r\n");
out.write(" <option value=\"MME\">MADAME</option>\r\n");
out.write(" <option value=\"MADRE\">MADRE</option>\r\n");
out.write(" <option value=\"MAEST\">MAESTRO</option>\r\n");
out.write(" <option value=\"MAJ\">MAJOR</option>\r\n");
out.write(" <option value=\"MJAVI\">MAJOR AVIADOR</option>\r\n");
out.write(" <option value=\"MJBRI\">MAJOR BRIGADEIRO</option>\r\n");
out.write(" <option value=\"MAQ\">MAQUINISTA</option>\r\n");
out.write(" <option value=\"MAL\">MARECHAL</option>\r\n");
out.write(" <option value=\"MALAR\">MARECHAL DO AR</option>\r\n");
out.write(" <option value=\"MARQ\">MARQUES</option>\r\n");
out.write(" <option value=\"MARQA\">MARQUESA</option>\r\n");
out.write(" <option value=\"MERE\">MERE</option>\r\n");
out.write(" <option value=\"MTRAS\">MESTRAS</option>\r\n");
out.write(" <option value=\"MEST\">MESTRE</option>\r\n");
out.write(" <option value=\"MTRES\">MESTRES</option>\r\n");
out.write(" <option value=\"MIL\">MILITANTE</option>\r\n");
out.write(" <option value=\"MIN\">MINISTRO</option>\r\n");
out.write(" <option value=\"MISSA\">MISSIONARIA</option>\r\n");
out.write(" <option value=\"MISSO\">MISSIONARIO</option>\r\n");
out.write(" <option value=\"MONGE\">MONGE</option>\r\n");
out.write(" <option value=\"MONS\">MONSENHOR</option>\r\n");
out.write(" <option value=\"MUNIC\">MUNIC</option>\r\n");
out.write(" <option value=\"MUS\">MUSICO</option>\r\n");
out.write(" <option value=\"NSRA\">NOSSA SENHORA</option>\r\n");
out.write(" <option value=\"NS\">NOSSO SENHOR</option>\r\n");
out.write(" <option value=\"OUVID\">OUVIDOR</option>\r\n");
out.write(" <option value=\"PDE\">PADRE</option>\r\n");
out.write(" <option value=\"PDES\">PADRES</option>\r\n");
out.write(" <option value=\"PAI\">PAI</option>\r\n");
out.write(" <option value=\"PAPA\">PAPA</option>\r\n");
out.write(" <option value=\"PAST\">PASTOR</option>\r\n");
out.write(" <option value=\"PATR\">PATRIARCA</option>\r\n");
out.write(" <option value=\"POETA\">POETA</option>\r\n");
out.write(" <option value=\"POTSA\">POETISA</option>\r\n");
out.write(" <option value=\"PREF\">PREFEITO</option>\r\n");
out.write(" <option value=\"PRES\">PRESIDENTE</option>\r\n");
out.write(" <option value=\"PABL\">PRESIDENTE DA ACAD.BRAS.LETRAS</option>\r\n");
out.write(" <option value=\"PREVR\">PREVR</option>\r\n");
out.write(" <option value=\"PSARG\">PRIMEIRO SARGENTO</option>\r\n");
out.write(" <option value=\"PSGPM\">PRIMEIRO SARGENTO PM</option>\r\n");
out.write(" <option value=\"PTTE\">PRIMEIRO TENENTE</option>\r\n");
out.write(" <option value=\"PTEPM\">PRIMEIRO TENENTE PM</option>\r\n");
out.write(" <option value=\"PRSA\">PRINCESA</option>\r\n");
out.write(" <option value=\"PRINC\">PRINCIPE</option>\r\n");
out.write(" <option value=\"PROC\">PROCURADOR</option>\r\n");
out.write(" <option value=\"PROF\">PROFESSOR</option>\r\n");
out.write(" <option value=\"PRODR\">PROFESSOR DOUTOR</option>\r\n");
out.write(" <option value=\"PROEN\">PROFESSOR ENGENHEIRO</option>\r\n");
out.write(" <option value=\"PROFA\">PROFESSORA</option>\r\n");
out.write(" <option value=\"PROTA\">PROFETA</option>\r\n");
out.write(" <option value=\"PROM\">PROMOTOR</option>\r\n");
out.write(" <option value=\"PROV\">PROVEDOR</option>\r\n");
out.write(" <option value=\"PRVM\">PROVEDOR MOR</option>\r\n");
out.write(" <option value=\"RAB\">RABINO</option>\r\n");
out.write(" <option value=\"RADTA\">RADIALISTA</option>\r\n");
out.write(" <option value=\"RAINH\">RAINHA</option>\r\n");
out.write(" <option value=\"REG\">REGENTE</option>\r\n");
out.write(" <option value=\"REI\">REI</option>\r\n");
out.write(" <option value=\"REV\">REVERENDO</option>\r\n");
out.write(" <option value=\"R\">RUA</option>\r\n");
out.write(" <option value=\"SCT\">SACERDOTE</option>\r\n");
out.write(" <option value=\"STA\">SANTA</option>\r\n");
out.write(" <option value=\"STO\">SANTO</option>\r\n");
out.write(" <option value=\"S\">SAO</option>\r\n");
out.write(" <option value=\"SARG\">SARGENTO</option>\r\n");
out.write(" <option value=\"SARGM\">SARGENTO MOR</option>\r\n");
out.write(" <option value=\"SGPM\">SARGENTO PM</option>\r\n");
out.write(" <option value=\"SSARG\">SEGUNDO SARGENTO</option>\r\n");
out.write(" <option value=\"SSGPM\">SEGUNDO SARGENTO PM</option>\r\n");
out.write(" <option value=\"STTE\">SEGUNDO TENENTE</option>\r\n");
out.write(" <option value=\"SEN\">SENADOR</option>\r\n");
out.write(" <option value=\"SR\">SENHOR</option>\r\n");
out.write(" <option value=\"SRA\">SENHORA</option>\r\n");
out.write(" <option value=\"SERT\">SERTANISTA</option>\r\n");
out.write(" <option value=\"SIN\">SINHA</option>\r\n");
out.write(" <option value=\"SIR\">SIR</option>\r\n");
out.write(" <option value=\"SOCIO\">SOCIOLOGO</option>\r\n");
out.write(" <option value=\"SOLD\">SOLDADO</option>\r\n");
out.write(" <option value=\"SDPM\">SOLDADO PM</option>\r\n");
out.write(" <option value=\"SOROR\">SOROR</option>\r\n");
out.write(" <option value=\"SBTTE\">SUB TENENTE</option>\r\n");
out.write(" <option value=\"TTE\">TENENTE</option>\r\n");
out.write(" <option value=\"TTAVI\">TENENTE AVIADOR</option>\r\n");
out.write(" <option value=\"TTBRI\">TENENTE BRIGADEIRO</option>\r\n");
out.write(" <option value=\"TTCEL\">TENENTE CORONEL</option>\r\n");
out.write(" <option value=\"TTCPM\">TENENTE CORONEL PM</option>\r\n");
out.write(" <option value=\"TEO\">TEOLOGO</option>\r\n");
out.write(" <option value=\"TSARG\">TERCEIRO SARGENTO</option>\r\n");
out.write(" <option value=\"TSGPM\">TERCEIRO SARGENTO PM</option>\r\n");
out.write(" <option value=\"TIA\">TIA</option>\r\n");
out.write(" <option value=\"VER\">VEREADOR</option>\r\n");
out.write(" <option value=\"VALM\">VICE ALMIRANTE</option>\r\n");
out.write(" <option value=\"VREI\">VICE REI</option>\r\n");
out.write(" <option value=\"VIG\">VIGARIO</option>\r\n");
out.write(" <option value=\"VISC\">VISCONDE</option>\r\n");
out.write(" <option value=\"VISCA\">VISCONDESSA</option>\r\n");
out.write(" <option value=\"VOL\">VOLUNTARIO</option>\r\n");
out.write(" </select>\r\n");
out.write("\r\n");
out.write(" </label>\r\n");
out.write(" </div>\r\n");
out.write("\r\n");
out.write(" <div class=\"space-1\"></div>\r\n");
out.write("\r\n");
out.write(" <div class=\"form-group\">\r\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\r\n");
out.write(" <span class=\"lbl\"><strong>Endereço:</strong></span>\r\n");
out.write(" </label>\r\n");
out.write(" <label class=\"inline col-md-6 col-xs-12\" >\r\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" placeholder=\"nome do endereço\" name=\"nmendereco\" >\r\n");
out.write(" </label>\r\n");
out.write(" <label class=\"inline col-md-1 col-xs-12\" >\r\n");
out.write(" <span class=\"lbl\"><strong>número:</strong></span>\r\n");
out.write(" </label>\r\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\r\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" placeholder=\"nº\" name=\"nmendereco\" >\r\n");
out.write(" </label>\r\n");
out.write(" </div>\r\n");
out.write("\r\n");
out.write(" <div class=\"space-1\"></div>\r\n");
out.write("\r\n");
out.write(" <div class=\"form-group\">\r\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\r\n");
out.write(" <span class=\"lbl\"><strong>Complemento:</strong></span>\r\n");
out.write(" </label>\r\n");
out.write(" <label class=\"inline col-md-3 col-xs-12\" >\r\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" placeholder=\"complemento do endereço\" name=\"nmcompelnt\" >\r\n");
out.write(" </label>\r\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\r\n");
out.write(" <span class=\"lbl\"><strong>Referência:</strong></span>\r\n");
out.write(" </label>\r\n");
out.write(" <label class=\"inline col-md-4 col-xs-12\" >\r\n");
out.write(" <input type=\"text\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" placeholder=\"referencia do endereço\" name=\"nmfinalidade\" >\r\n");
out.write(" </label>\r\n");
out.write(" </div>\r\n");
out.write(" \r\n");
out.write(" <div class=\"space-1\"></div>\r\n");
out.write("\r\n");
out.write(" <div class=\"form-group\">\r\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\r\n");
out.write(" <span class=\"lbl\"><strong>Prazo:</strong></span>\r\n");
out.write(" </label>\r\n");
out.write(" <label class=\"inline col-md-1 col-xs-12\">\r\n");
out.write(" <input type=\"number\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" placeholder=\"\" name=\"nrprazo\" >\r\n");
out.write(" </label>\r\n");
out.write(" <label class=\"inline col-md-1 col-xs-12\" >\r\n");
out.write(" <span class=\"lbl\"><strong>Ano</strong></span>\r\n");
out.write(" </label>\r\n");
out.write(" <label class=\"inline col-md-1 col-xs-12\">\r\n");
out.write(" <input type=\"number\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" placeholder=\"\" name=\"nrprazo\" >\r\n");
out.write(" </label>\r\n");
out.write(" <label class=\"inline col-md-1 col-xs-12\" >\r\n");
out.write(" <span class=\"lbl\"><strong>Meses</strong></span>\r\n");
out.write(" </label>\r\n");
out.write(" </div> \r\n");
out.write("\r\n");
out.write(" <div class=\"space-1\"></div>\r\n");
out.write(" \r\n");
out.write(" <div class=\"form-group\">\r\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\r\n");
out.write(" <span class=\"lbl\"><strong>Categoria da contrapartida:</strong></span>\r\n");
out.write(" </label>\r\n");
out.write(" <label class=\"inline col-md-3 col-xs-12\">\r\n");
out.write(" <select class=\"col-md-12 col-xs-12\" name=\"tpDispLegal\">\r\n");
out.write(" <option></option>\r\n");
out.write(" <option>Serviço</option>\r\n");
out.write(" <option>Pecuniária</option>\r\n");
out.write(" </select>\r\n");
out.write(" </label>\r\n");
out.write(" </div>\r\n");
out.write(" <div class=\"space-1\"></div>\r\n");
out.write(" \r\n");
out.write(" <div class=\"form-group\">\r\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\r\n");
out.write(" <span class=\"lbl\"><strong>Contrapartida <font size=\"-2\"> (Descrição Simplificada):</font></strong></span>\r\n");
out.write(" </label>\r\n");
out.write(" <label class=\"inline col-md-9 col-xs-12\">\r\n");
out.write(" <textarea id=\"form-field-11\" class=\"autosize-transition form-control\" name=\"contraSimplificada\" style=\"height:200px; margin-left: 0px; width: 650px;\"></textarea>\r\n");
out.write(" </label>\r\n");
out.write(" </div>\r\n");
out.write(" <div class=\"space-1\"></div>\r\n");
out.write("\r\n");
out.write(" <div class=\"form-group\">\r\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\r\n");
out.write(" <span class=\"lbl\"><strong>Observação:</strong></span>\r\n");
out.write(" </label>\r\n");
out.write(" <label class=\"inline col-md-10 col-xs-12\">\r\n");
out.write(" <textarea id=\"form-field-11\" class=\"autosize-transition form-control\" name=\"observacao\" style=\"height:200px; margin-left: 0px; width: 650px;\"></textarea>\r\n");
out.write(" </label>\r\n");
out.write(" </div>\r\n");
out.write(" \r\n");
out.write(" <h5 class=\"header smaller lbl\"><strong>Dispositivos Legais</strong></h5>\r\n");
out.write(" <div class=\"form-group\">\r\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\" >\r\n");
out.write(" <span class=\"lbl\">\r\n");
out.write(" <strong>Tipo de Dispositivo:</strong>\r\n");
out.write(" </span>\r\n");
out.write(" </label>\r\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\">\r\n");
out.write(" <select class=\"col-md-12 col-xs-12\" name=\"tpDispLegal\">\r\n");
out.write(" <option></option>\r\n");
out.write(" ");
if (_jspx_meth_c_forEach_2(_jspx_page_context))
return;
out.write("\r\n");
out.write(" </select>\r\n");
out.write(" </label>\r\n");
out.write(" <label class=\"inline col-md-1 col-xs-12\" >\r\n");
out.write(" <span class=\"lbl\"><strong>Número:</strong></span>\r\n");
out.write(" </label>\r\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\">\r\n");
out.write(" <input type=\"number\" id=\"form-field-1\" class=\"col-xs-12 col-md-12\" placeholder=\"numero\" name=\"subprefeitura\" >\r\n");
out.write(" </label>\r\n");
out.write("\r\n");
out.write(" <label class=\"inline col-md-1 col-xs-12\" >\r\n");
out.write(" <span class=\"lbl\"><strong>Data:</strong></span>\r\n");
out.write(" </label>\r\n");
out.write(" <label class=\"inline col-md-2 col-xs-12\">\r\n");
out.write(" <div class=\"input-group\">\r\n");
out.write(" <input class=\"form-control date-picker\" id=\"id-date-picker-1\" name=\"dtDispositivo\" type=\"text\" placeholder=\"dd/mm/aaaa\" data-date-format=\"dd/mm/yyyy\">\r\n");
out.write(" <span class=\"input-group-addon\">\r\n");
out.write(" <i class=\"fa fa-calendar bigger-110\"></i>\r\n");
out.write(" </span>\r\n");
out.write("\r\n");
out.write(" </div>\r\n");
out.write(" </label>\r\n");
out.write(" <div class=\"\">\r\n");
out.write(" <i class=\"fa fa-plus-circle\"></i>\r\n");
out.write(" </div>\r\n");
out.write(" \r\n");
out.write(" </div> \r\n");
out.write(" \r\n");
out.write(" <div class=\"form-actions center\">\r\n");
out.write(" <button class=\"btn btn-yellow\" type=\"reset\" onclick=\"location.href='AutoCessao.jsp?ter=");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${ter}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("';\">\r\n");
out.write(" <i class=\"ace-icon fa fa-undo bigger-110\"></i>\r\n");
out.write(" Voltar\r\n");
out.write(" </button>\r\n");
out.write(" <button class=\"btn btn-success\" type=\"submit\">\r\n");
out.write(" <i class=\"ace-icon fa fa-save bigger-110\"></i>\r\n");
out.write(" Salvar\r\n");
out.write(" </button>\r\n");
out.write(" </div>\r\n");
out.write(" </form>\r\n");
out.write(" </div>\r\n");
out.write("\r\n");
out.write("<!--Inicio da tab-pane Auto Cessão Terceiros--> \r\n");
out.write(" <div id=\"auto-cessao-terceiro\" class=\"tab-pane ");
if (_jspx_meth_c_if_4(_jspx_page_context))
return;
out.write("\">\r\n");
out.write(" \r\n");
out.write(" </div>\r\n");
out.write(" </div>\r\n");
out.write(" </div>\r\n");
out.write(" </div> \r\n");
out.write(" </div> \r\n");
out.write(" \r\n");
out.write(" \r\n");
out.write(" ");
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "include/footer.jsp", out, false);
out.write("\r\n");
out.write(" </div><!-- /.main-container --> \r\n");
out.write(" </body>\r\n");
out.write("</html>\r\n");
out.write("\r\n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
private boolean _jspx_meth_c_set_0(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_0 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_0.setPageContext(_jspx_page_context);
_jspx_th_c_set_0.setParent(null);
_jspx_th_c_set_0.setVar("acessoPerfil");
_jspx_th_c_set_0.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${sessionPerfil}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_0 = _jspx_th_c_set_0.doStartTag();
if (_jspx_th_c_set_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_0);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_0);
return false;
}
private boolean _jspx_meth_c_choose_0(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_0 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_0.setPageContext(_jspx_page_context);
_jspx_th_c_choose_0.setParent(null);
int _jspx_eval_c_choose_0 = _jspx_th_c_choose_0.doStartTag();
if (_jspx_eval_c_choose_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_when_0((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_0, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_when_1((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_0, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_when_2((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_0, _jspx_page_context))
return true;
out.write('\r');
out.write('\n');
int evalDoAfterBody = _jspx_th_c_choose_0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_0);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_0);
return false;
}
private boolean _jspx_meth_c_when_0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_0, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_0 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_0.setPageContext(_jspx_page_context);
_jspx_th_c_when_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_0);
_jspx_th_c_when_0.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${sessionLogin == '' || sessionLogin == null}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_0 = _jspx_th_c_when_0.doStartTag();
if (_jspx_eval_c_when_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_redirect_0((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_0, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_0);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_0);
return false;
}
private boolean _jspx_meth_c_redirect_0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_0, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:redirect
org.apache.taglibs.standard.tag.rt.core.RedirectTag _jspx_th_c_redirect_0 = (org.apache.taglibs.standard.tag.rt.core.RedirectTag) _jspx_tagPool_c_redirect_url_nobody.get(org.apache.taglibs.standard.tag.rt.core.RedirectTag.class);
_jspx_th_c_redirect_0.setPageContext(_jspx_page_context);
_jspx_th_c_redirect_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_0);
_jspx_th_c_redirect_0.setUrl("/AcessoNegado.jsp");
int _jspx_eval_c_redirect_0 = _jspx_th_c_redirect_0.doStartTag();
if (_jspx_th_c_redirect_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_redirect_url_nobody.reuse(_jspx_th_c_redirect_0);
return true;
}
_jspx_tagPool_c_redirect_url_nobody.reuse(_jspx_th_c_redirect_0);
return false;
}
private boolean _jspx_meth_c_when_1(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_0, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_1 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_1.setPageContext(_jspx_page_context);
_jspx_th_c_when_1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_0);
_jspx_th_c_when_1.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${sessionPerfil != acessoPerfil}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_1 = _jspx_th_c_when_1.doStartTag();
if (_jspx_eval_c_when_1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_set_1((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_1, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_redirect_1((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_1, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_1.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_1);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_1);
return false;
}
private boolean _jspx_meth_c_set_1(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_1, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_1 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_scope_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_1.setPageContext(_jspx_page_context);
_jspx_th_c_set_1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_1);
_jspx_th_c_set_1.setVar("msg3");
_jspx_th_c_set_1.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${true}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
_jspx_th_c_set_1.setScope("session");
int _jspx_eval_c_set_1 = _jspx_th_c_set_1.doStartTag();
if (_jspx_th_c_set_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_scope_nobody.reuse(_jspx_th_c_set_1);
return true;
}
_jspx_tagPool_c_set_var_value_scope_nobody.reuse(_jspx_th_c_set_1);
return false;
}
private boolean _jspx_meth_c_redirect_1(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_1, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:redirect
org.apache.taglibs.standard.tag.rt.core.RedirectTag _jspx_th_c_redirect_1 = (org.apache.taglibs.standard.tag.rt.core.RedirectTag) _jspx_tagPool_c_redirect_url_nobody.get(org.apache.taglibs.standard.tag.rt.core.RedirectTag.class);
_jspx_th_c_redirect_1.setPageContext(_jspx_page_context);
_jspx_th_c_redirect_1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_1);
_jspx_th_c_redirect_1.setUrl("/AcessoNegado.jsp");
int _jspx_eval_c_redirect_1 = _jspx_th_c_redirect_1.doStartTag();
if (_jspx_th_c_redirect_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_redirect_url_nobody.reuse(_jspx_th_c_redirect_1);
return true;
}
_jspx_tagPool_c_redirect_url_nobody.reuse(_jspx_th_c_redirect_1);
return false;
}
private boolean _jspx_meth_c_when_2(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_0, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_2 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_2.setPageContext(_jspx_page_context);
_jspx_th_c_when_2.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_0);
_jspx_th_c_when_2.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${sessionStatus == 0}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_2 = _jspx_th_c_when_2.doStartTag();
if (_jspx_eval_c_when_2 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_set_2((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_2, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_redirect_2((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_when_2, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_2.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_2);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_2);
return false;
}
private boolean _jspx_meth_c_set_2(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_2, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_2 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_scope_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_2.setPageContext(_jspx_page_context);
_jspx_th_c_set_2.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_2);
_jspx_th_c_set_2.setVar("msg");
_jspx_th_c_set_2.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${true}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
_jspx_th_c_set_2.setScope("session");
int _jspx_eval_c_set_2 = _jspx_th_c_set_2.doStartTag();
if (_jspx_th_c_set_2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_scope_nobody.reuse(_jspx_th_c_set_2);
return true;
}
_jspx_tagPool_c_set_var_value_scope_nobody.reuse(_jspx_th_c_set_2);
return false;
}
private boolean _jspx_meth_c_redirect_2(javax.servlet.jsp.tagext.JspTag _jspx_th_c_when_2, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:redirect
org.apache.taglibs.standard.tag.rt.core.RedirectTag _jspx_th_c_redirect_2 = (org.apache.taglibs.standard.tag.rt.core.RedirectTag) _jspx_tagPool_c_redirect_url_nobody.get(org.apache.taglibs.standard.tag.rt.core.RedirectTag.class);
_jspx_th_c_redirect_2.setPageContext(_jspx_page_context);
_jspx_th_c_redirect_2.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_when_2);
_jspx_th_c_redirect_2.setUrl("/AcessoNegado.jsp");
int _jspx_eval_c_redirect_2 = _jspx_th_c_redirect_2.doStartTag();
if (_jspx_th_c_redirect_2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_redirect_url_nobody.reuse(_jspx_th_c_redirect_2);
return true;
}
_jspx_tagPool_c_redirect_url_nobody.reuse(_jspx_th_c_redirect_2);
return false;
}
private boolean _jspx_meth_c_set_3(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_set_3 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _jspx_tagPool_c_set_var_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_set_3.setPageContext(_jspx_page_context);
_jspx_th_c_set_3.setParent(null);
_jspx_th_c_set_3.setVar("ter");
_jspx_th_c_set_3.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${param.ter}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int _jspx_eval_c_set_3 = _jspx_th_c_set_3.doStartTag();
if (_jspx_th_c_set_3.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_3);
return true;
}
_jspx_tagPool_c_set_var_value_nobody.reuse(_jspx_th_c_set_3);
return false;
}
private boolean _jspx_meth_c_if_0(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_0 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_0.setPageContext(_jspx_page_context);
_jspx_th_c_if_0.setParent(null);
_jspx_th_c_if_0.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${not empty ter}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_0 = _jspx_th_c_if_0.doStartTag();
if (_jspx_eval_c_if_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write(" Terceiro");
int evalDoAfterBody = _jspx_th_c_if_0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_0);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_0);
return false;
}
private boolean _jspx_meth_c_if_1(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_1 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_1.setPageContext(_jspx_page_context);
_jspx_th_c_if_1.setParent(null);
_jspx_th_c_if_1.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${not empty ter}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_1 = _jspx_th_c_if_1.doStartTag();
if (_jspx_eval_c_if_1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write(" Terceiro");
int evalDoAfterBody = _jspx_th_c_if_1.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_1);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_1);
return false;
}
private boolean _jspx_meth_c_if_2(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_2 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_2.setPageContext(_jspx_page_context);
_jspx_th_c_if_2.setParent(null);
_jspx_th_c_if_2.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${not empty ter}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_2 = _jspx_th_c_if_2.doStartTag();
if (_jspx_eval_c_if_2 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write(" Terceiro");
int evalDoAfterBody = _jspx_th_c_if_2.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_2);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_2);
return false;
}
private boolean _jspx_meth_c_choose_1(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_1 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_1.setPageContext(_jspx_page_context);
_jspx_th_c_choose_1.setParent(null);
int _jspx_eval_c_choose_1 = _jspx_th_c_choose_1.doStartTag();
if (_jspx_eval_c_choose_1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_when_3((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_1, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_otherwise_0((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_1, _jspx_page_context))
return true;
out.write(" \r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_1.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_1);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_1);
return false;
}
private boolean _jspx_meth_c_when_3(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_1, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_3 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_3.setPageContext(_jspx_page_context);
_jspx_th_c_when_3.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_1);
_jspx_th_c_when_3.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${not empty ter}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_3 = _jspx_th_c_when_3.doStartTag();
if (_jspx_eval_c_when_3 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" action=\"\" \r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_3.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_3.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_3);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_3);
return false;
}
private boolean _jspx_meth_c_otherwise_0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_1, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_0 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_0.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_1);
int _jspx_eval_c_otherwise_0 = _jspx_th_c_otherwise_0.doStartTag();
if (_jspx_eval_c_otherwise_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" action=\"\" \r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_0);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_0);
return false;
}
private boolean _jspx_meth_c_forEach_0(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:forEach
org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_forEach_0 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _jspx_tagPool_c_forEach_var_items.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class);
_jspx_th_c_forEach_0.setPageContext(_jspx_page_context);
_jspx_th_c_forEach_0.setParent(null);
_jspx_th_c_forEach_0.setVar("CatAuto");
_jspx_th_c_forEach_0.setItems((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${CatAuto.listSelectCatAutoCessao()}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int[] _jspx_push_body_count_c_forEach_0 = new int[] { 0 };
try {
int _jspx_eval_c_forEach_0 = _jspx_th_c_forEach_0.doStartTag();
if (_jspx_eval_c_forEach_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_if_3((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_forEach_0, _jspx_page_context, _jspx_push_body_count_c_forEach_0))
return true;
out.write("\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_forEach_0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_forEach_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_c_forEach_0[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_c_forEach_0.doCatch(_jspx_exception);
} finally {
_jspx_th_c_forEach_0.doFinally();
_jspx_tagPool_c_forEach_var_items.reuse(_jspx_th_c_forEach_0);
}
return false;
}
private boolean _jspx_meth_c_if_3(javax.servlet.jsp.tagext.JspTag _jspx_th_c_forEach_0, PageContext _jspx_page_context, int[] _jspx_push_body_count_c_forEach_0)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_3 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_3.setPageContext(_jspx_page_context);
_jspx_th_c_if_3.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_forEach_0);
_jspx_th_c_if_3.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${CatAuto.nmCatAutoCessao != 'Informação não cadastrada'}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_3 = _jspx_th_c_if_3.doStartTag();
if (_jspx_eval_c_if_3 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" <option value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${CatAuto.pkCatAutoCessao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" title=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${CatAuto.nmCatAutoCessao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write('"');
out.write('>');
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${CatAuto.nmCatAutoCessao}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("</option> \r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_if_3.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_3.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_3);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_3);
return false;
}
private boolean _jspx_meth_c_choose_2(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_2 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_2.setPageContext(_jspx_page_context);
_jspx_th_c_choose_2.setParent(null);
int _jspx_eval_c_choose_2 = _jspx_th_c_choose_2.doStartTag();
if (_jspx_eval_c_choose_2 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_when_4((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_2, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_otherwise_1((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_2, _jspx_page_context))
return true;
out.write(" \r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_2.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_2);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_2);
return false;
}
private boolean _jspx_meth_c_when_4(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_2, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_4 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_4.setPageContext(_jspx_page_context);
_jspx_th_c_when_4.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_2);
_jspx_th_c_when_4.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${not empty ter}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_4 = _jspx_th_c_when_4.doStartTag();
if (_jspx_eval_c_when_4 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" Cedente:\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_4.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_4.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_4);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_4);
return false;
}
private boolean _jspx_meth_c_otherwise_1(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_2, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_1 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_1.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_2);
int _jspx_eval_c_otherwise_1 = _jspx_th_c_otherwise_1.doStartTag();
if (_jspx_eval_c_otherwise_1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" Cessionário:\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_1.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_1);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_1);
return false;
}
private boolean _jspx_meth_c_forEach_1(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:forEach
org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_forEach_1 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _jspx_tagPool_c_forEach_var_items.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class);
_jspx_th_c_forEach_1.setPageContext(_jspx_page_context);
_jspx_th_c_forEach_1.setParent(null);
_jspx_th_c_forEach_1.setVar("nvadm");
_jspx_th_c_forEach_1.setItems((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${NvAdm.listNivelAdm()}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int[] _jspx_push_body_count_c_forEach_1 = new int[] { 0 };
try {
int _jspx_eval_c_forEach_1 = _jspx_th_c_forEach_1.doStartTag();
if (_jspx_eval_c_forEach_1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" <option value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${nvadm.pkNiveladm}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" title=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${nvadm.nnAdm}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\">\r\n");
out.write(" ");
if (_jspx_meth_c_choose_3((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_forEach_1, _jspx_page_context, _jspx_push_body_count_c_forEach_1))
return true;
out.write("\r\n");
out.write(" </option> \r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_forEach_1.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_forEach_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_c_forEach_1[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_c_forEach_1.doCatch(_jspx_exception);
} finally {
_jspx_th_c_forEach_1.doFinally();
_jspx_tagPool_c_forEach_var_items.reuse(_jspx_th_c_forEach_1);
}
return false;
}
private boolean _jspx_meth_c_choose_3(javax.servlet.jsp.tagext.JspTag _jspx_th_c_forEach_1, PageContext _jspx_page_context, int[] _jspx_push_body_count_c_forEach_1)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_3 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_3.setPageContext(_jspx_page_context);
_jspx_th_c_choose_3.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_forEach_1);
int _jspx_eval_c_choose_3 = _jspx_th_c_choose_3.doStartTag();
if (_jspx_eval_c_choose_3 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_when_5((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_3, _jspx_page_context, _jspx_push_body_count_c_forEach_1))
return true;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_otherwise_2((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_3, _jspx_page_context, _jspx_push_body_count_c_forEach_1))
return true;
out.write("\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_3.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_3.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_3);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_3);
return false;
}
private boolean _jspx_meth_c_when_5(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_3, PageContext _jspx_page_context, int[] _jspx_push_body_count_c_forEach_1)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_5 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_5.setPageContext(_jspx_page_context);
_jspx_th_c_when_5.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_3);
_jspx_th_c_when_5.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${nvadm.nnAdm.length() > 40 }", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_5 = _jspx_th_c_when_5.doStartTag();
if (_jspx_eval_c_when_5 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" ");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${nvadm.nnAdm.substring(0,40)}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_5.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_5.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_5);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_5);
return false;
}
private boolean _jspx_meth_c_otherwise_2(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_3, PageContext _jspx_page_context, int[] _jspx_push_body_count_c_forEach_1)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_2 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_2.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_2.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_3);
int _jspx_eval_c_otherwise_2 = _jspx_th_c_otherwise_2.doStartTag();
if (_jspx_eval_c_otherwise_2 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" ");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${nvadm.nnAdm}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_2.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_2);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_2);
return false;
}
private boolean _jspx_meth_c_choose_4(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:choose
org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_4 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class);
_jspx_th_c_choose_4.setPageContext(_jspx_page_context);
_jspx_th_c_choose_4.setParent(null);
int _jspx_eval_c_choose_4 = _jspx_th_c_choose_4.doStartTag();
if (_jspx_eval_c_choose_4 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_when_6((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_4, _jspx_page_context))
return true;
out.write("\r\n");
out.write(" ");
if (_jspx_meth_c_otherwise_3((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_4, _jspx_page_context))
return true;
out.write(" \r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_choose_4.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_choose_4.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_4);
return true;
}
_jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_4);
return false;
}
private boolean _jspx_meth_c_when_6(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_4, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_6 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_6.setPageContext(_jspx_page_context);
_jspx_th_c_when_6.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_4);
_jspx_th_c_when_6.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${not empty ter}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_6 = _jspx_th_c_when_6.doStartTag();
if (_jspx_eval_c_when_6 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" Cedente:\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_when_6.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_6.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_6);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_6);
return false;
}
private boolean _jspx_meth_c_otherwise_3(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_4, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:otherwise
org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_otherwise_3 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _jspx_tagPool_c_otherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class);
_jspx_th_c_otherwise_3.setPageContext(_jspx_page_context);
_jspx_th_c_otherwise_3.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_4);
int _jspx_eval_c_otherwise_3 = _jspx_th_c_otherwise_3.doStartTag();
if (_jspx_eval_c_otherwise_3 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" Cessionário:\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_otherwise_3.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_otherwise_3.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_3);
return true;
}
_jspx_tagPool_c_otherwise.reuse(_jspx_th_c_otherwise_3);
return false;
}
private boolean _jspx_meth_c_forEach_2(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:forEach
org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_forEach_2 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _jspx_tagPool_c_forEach_var_items.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class);
_jspx_th_c_forEach_2.setPageContext(_jspx_page_context);
_jspx_th_c_forEach_2.setParent(null);
_jspx_th_c_forEach_2.setVar("dplegal");
_jspx_th_c_forEach_2.setItems((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${dpLegal.listDispLegal()}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
int[] _jspx_push_body_count_c_forEach_2 = new int[] { 0 };
try {
int _jspx_eval_c_forEach_2 = _jspx_th_c_forEach_2.doStartTag();
if (_jspx_eval_c_forEach_2 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" <option value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${dplegal.pkDispositivoLegal}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" title=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${dplegal.nmDispLegal}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\">\r\n");
out.write(" ");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${dplegal.nmDispLegal}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\r\n");
out.write(" </option> \r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_forEach_2.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_forEach_2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_c_forEach_2[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_c_forEach_2.doCatch(_jspx_exception);
} finally {
_jspx_th_c_forEach_2.doFinally();
_jspx_tagPool_c_forEach_var_items.reuse(_jspx_th_c_forEach_2);
}
return false;
}
private boolean _jspx_meth_c_if_4(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:if
org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_if_4 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
_jspx_th_c_if_4.setPageContext(_jspx_page_context);
_jspx_th_c_if_4.setParent(null);
_jspx_th_c_if_4.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${not empty ter}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_if_4 = _jspx_th_c_if_4.doStartTag();
if (_jspx_eval_c_if_4 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write(" in active");
int evalDoAfterBody = _jspx_th_c_if_4.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_if_4.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_4);
return true;
}
_jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_4);
return false;
}
}
| 679261d7ae43081b23c5bfbb47134b31b7781a31 | [
"Java",
"INI"
] | 47 | Java | kleberfranklin/SGPatri | 2cd4dda89fc99a86e5306aeac600ea05ba10aff8 | fe63d291a9aa640574573463d0ed11124fe8fd03 |
refs/heads/master | <file_sep><html>
<head>
<meta charset="utf-8">
<title>Enviando requisição</title>
</head>
<body><h1>Aguarde um momento</h1></body>
<?php
require('../connect.php');
require('login-verification.php');
$id = mysql_real_escape_string($_GET['id']);
// Deletando imagem do servidor
$dados = mysql_query('SELECT * FROM imagem WHERE idNave = ' . $id, $con);
$row = mysql_fetch_assoc($dados);
unlink('../../images/ships/'.$row['nome']);
// Deletando nave do bd
mysql_query('DELETE FROM nave WHERE idNave = ' . $id, $con);
mysql_query('DELETE FROM imagem WHERE idNave = ' . $id, $con);
header('Location: ../../pages/internal-system/ship-manage.php');
exit();
?>
</html><file_sep><?php require("../../server/execs/login-verification.php"); ?>
<!doctype html>
<html lang="pt-br">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="../../../css/bulma.min.0.9.css">
<link rel="stylesheet" href="../../../css/form.css">
<title>Cadastro de Naves - Sistema Interno</title>
<link rel="shortcut icon" href="../../images/favicon-manage.png" type="image/x-icon" />
</head>
<body>
<?php include('../../model/navbar-internal-system.php');?>
<div class="container">
<form method="post" action="../../../server/execs/ship-registration-exec.php" enctype="multipart/form-data" autocomplete="off">
<div class="control">
<input name="nome" type="text" placeholder="Nome da nave" class="input is-info" required>
</div>
<div class="control">
<input name="universo" type="text" placeholder="Universo (filme/série de origem)" class="input is-info" required>
</div>
<div class="control">
<input name="capacidade" type="number" placeholder="Capacidade de pessoas a bordo" class="input is-info" required>
</div>
<div class="control">
<input name="descricao" type="text" placeholder="Descrição técnica" class="input is-info" required>
</div>
<div class="control">
<input name="valor" type="text" placeholder="Valor da nave" class="input is-info dinheiro" required>
</div>
<div class="control">
<input type="file" name="imagem" accept="image/png, image/jpeg, image/gif" required>
</div>
<button type="submit" class="button is-link">Cadastrar</button>
</form>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.1/js/all.min.js"></script>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<!-- Mascara de Valor -->
<script src="../../../js/mask-number-min.js"></script>
<script>
$('.dinheiro').mask('#.##0,00', { reverse: true });
</script>
</div>
</body>
</html><file_sep><?php
session_start();
require('../connect.php');
if(empty($_POST['user']) || empty($_POST['senha'])) {
header('Location: ../../pages/internal-system/login.php');
exit();
}
$usuario = mysql_real_escape_string($_POST['user']);
$senha = mysql_real_escape_string($_POST['senha']);
$query = "select user, nome from administrador where user = '{$usuario}' and senha = md5('{$senha}')";
$result = mysql_query($query, $con);
$row = mysql_num_rows($result);
if($row == 1) {
$_SESSION['usuario'] = $usuario;
$row = mysql_fetch_assoc($result);
$_SESSION['usuario_nome'] = $row['nome'];
header('Location: ../../pages/internal-system/ship-manage.php');
exit();
} else {
$_SESSION['nao_autenticado'] = true;
header('Location: ../../pages/internal-system/login.php');
exit();
}
?><file_sep><html>
<head>
<meta charset="utf-8">
<title>Enviando requisição</title>
</head>
<body><h1>Aguarde um momento</h1></body>
<?php
require('../connect.php');
require('login-verification.php');
$nome = mysql_real_escape_string($_POST['nome']);
$universo = mysql_real_escape_string($_POST['universo']);
$capacidade = mysql_real_escape_string($_POST['capacidade']);
$descricao = mysql_real_escape_string($_POST['descricao']);
$valor = mysql_real_escape_string($_POST['valor']);
$queryDados = " INSERT INTO `nave` (`nome`, `universo`, `capacidade`, `descricao`, `valor`)
VALUES ('$nome', '$universo', '$capacidade', '$descricao', '$valor')
";
// ************
// ** Imagem **
// ************
$arquivo_tmp = $_FILES[ 'imagem' ][ 'tmp_name' ];
$nome = $_FILES[ 'imagem' ][ 'name' ];
$extensao = pathinfo($nome, PATHINFO_EXTENSION);
$extensao = strtolower($extensao);
// Verificando tentativa de invasão pela imagem
$permitido = False;
$extensaoPermitida = array('png', 'jpg', 'jpeg', 'gif');
for ($i = 0; $i < count($extensaoPermitida); $i++){
if ($extensao == $extensaoPermitida[$i]){
$permitido = True;
}
}
if(!$permitido){
header('Location: ../../pages/internal-system/ship-registration.php');
exit();
}
// Enviando para o servidor
$novoNome = uniqid(time()) . '.' . $extensao;
$destino = '../../images/ships/' . $novoNome;
move_uploaded_file($arquivo_tmp, $destino);
// Enviando as informações para o servidor
mysql_query($queryDados, $con);
$ultimoId = mysql_insert_id();
$queryImg = " INSERT INTO `imagem` (`nome`, `idNave`)
VALUES ('$novoNome', '$ultimoId')
";
mysql_query($queryImg, $con);
header('Location: ../../pages/internal-system/ship-registration.php');
exit();
?>
</html><file_sep><?php
session_start();
?>
<!doctype html>
<html lang="pt-br">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="../../css/bulma.min.0.9.css">
<link rel="stylesheet" href="../../css/login.css">
<title>Login - Sistema Administrador</title>
<link rel="shortcut icon" href="../../images/favicon-manage.png" type="image/x-icon" />
</head>
<body>
<div class="painel">
<div class="painel-content">
<h1 class="title is-4">Sistema de Login</h1>
<?php
if(isset($_SESSION['nao_autenticado'])){
?>
<div class="error">
<i class="fas fa-exclamation-triangle error-title"></i>
<h1 class="error-title">Erro ao tentar efetuar o login!</h1>
</div>
<?php
}
unset($_SESSION['nao_autenticado']);
?>
<form method="post" action="../../../server/execs/login-admin-exec.php" autocomplete="off">
<div class="control">
<label class="label"><i class="fas fa-user"></i> User</label>
<input name="user" type="text" placeholder="Digite o usuário" class="input is-info is-rounded is-medium" required>
</div>
<div class="control">
<label class="label"><i class="fas fa-lock"></i> Senha</label>
<label class="label"></label>
<input name="senha" type="password" placeholder="Digite a senha" class="input is-info is-rounded is-medium" required>
</div>
<button type="submit" class="button is-outlined is-rounded is-large is-fullwidth is-link">Entrar</button>
</form>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.1/js/all.min.js"
integrity="<KEY>
crossorigin="anonymous"></script>
</body>
</html><file_sep>function confirmExclusion(nome){
return confirm(`Você realmente deseja deletar '${nome}'?\n(Essa ação é permanente)`);
}<file_sep><nav class="navbar" role="navigation" aria-label="main navigation" style="background-color: #3273dc; margin-bottom: 30px;">
<div class="navbar-brand">
<a class="navbar-item" href="#">
<img src="../../images/logo.png" width="112" height="28">
</a>
<a role="button" class="navbar-burger burger" aria-label="menu" aria-expanded="false"
data-target="navbarBasicExample">
<span aria-hidden="true"></span>
<span aria-hidden="true"></span>
<span aria-hidden="true"></span>
</a>
</div>
<div id="navbarBasicExample" class="navbar-menu">
<div class="navbar-start">
<a href="../../index.php" class="navbar-item">
Loja
</a>
<a href="ship-registration.php" class="navbar-item">
Cadastro
</a>
<a href="ship-edit.php" class="navbar-item">
Gerenciamento
</a>
</div>
<div class="navbar-end">
<div class="navbar-item">
<i class="fas fa-user" style="margin-right: 5px"></i>
<?php echo $_SESSION['usuario_nome'];?>
</div>
<a class="navbar-item" style="color: #F03A5F;" href="../../server/execs/logout.php">
<strong>Sair</strong>
<i class="fas fa-sign-out-alt" style="margin-left: 5px"></i>
</a>
</div>
</div>
</nav><file_sep><?php
require("../../server/connect.php");
require("../../server/execs/login-verification.php");
$dados = mysql_query('SELECT * FROM nave', $con) or die(mysql_error());
$row = mysql_fetch_assoc($dados);
$total = mysql_num_rows($dados);
?>
<!doctype html>
<html lang="pt-br">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="../../css/bulma.min.0.9.css">
<link rel="stylesheet" href="../../css/form.css">
<title>Gestão de Naves - Sistema Interno</title>
<link rel="shortcut icon" href="../../images/favicon-manage.png" type="image/x-icon" />
</head>
<body>
<?php include('../../model/navbar-internal-system.php');?>
<div class="container">
<center>
<table class="table">
<thead>
<tr>
<th><strong style="font-size: 19px;">#</strong></th>
<th>Imagem</th>
<th>Nome</th>
<th>Universo</th>
<th>Capacidade</th>
<th>Valor</th>
<th><strong>MODIFICAR</strong></th>
<th><strong>DELETAR</strong></th>
</tr>
</thead>
<tbody class="is-size-5">
<?php
if($total > 0) {
do {
?>
<tr>
<th><?=$row['idNave']?></th>
<?php
$id = $row['idNave'];
$imagemDados = mysql_query('SELECT * FROM imagem WHERE idNave = ' . $id, $con) or die(mysql_error());
$img = mysql_fetch_assoc($imagemDados)
?>
<td><img class="form-img" src="../../images/ships/<?=$img['nome']?>"></td>
<td><?=$row['nome']?></td>
<td><?=$row['universo']?></td>
<td><?=$row['capacidade']?></td>
<td><?=$row['valor']?></td>
<td><button class="button is-warning"
onclick="window.location.href='ship-edit.php?ship=<?=$row['idNave']?>'"><i
class="fas fa-cogs" style="color: #fff;"></i></button>
</td>
<td>
<a href="../../server/execs/ship-delete-exec.php?id=<?=$row['idNave']?>"
onclick="return confirmExclusion('<?=$row['nome']?>')">
<button class="button is-danger" style="color: #fff;"><i
class="fas fa-trash-alt"></i></button>
</a>
</td>
</tr>
<?php
}while($row = mysql_fetch_assoc($dados));
}
?>
</tbody>
</table>
</center>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.1/js/all.min.js"
integrity="<KEY>
crossorigin="anonymous"></script>
<script src="../../js/confim-exclusion.js"></script>
</body>
</html><file_sep>window.onload = initPage;
var inputNome = document.getElementById('nome');
var inputUniverso = document.getElementById('universo');
var inputCapacidade = document.getElementById('capacidade');
var inputDescricao = document.getElementById('descricao');
var inputValor = document.getElementById('valor');
function initPage(){
inputNome.value = nave.nome;
inputUniverso.value = nave.universo;
inputCapacidade.value = nave.capacidade;
inputDescricao.value = nave.descricao;
inputValor.value = nave.valor;
}
function ComparaDados(input, valor) {
if (input.value != valor) {
input.classList.remove('is-info');
input.classList.add('is-warning');
} else {
input.classList.remove('is-warning');
input.classList.add('is-info');
}
}
inputNome.addEventListener('keyup', event => {
ComparaDados(inputNome, nave.nome);
});
inputUniverso.addEventListener('keyup', event => {
ComparaDados(inputUniverso, nave.universo);
});
inputCapacidade.addEventListener('keyup', event => {
ComparaDados(inputCapacidade, nave.capacidade);
});
inputDescricao.addEventListener('keyup', event => {
ComparaDados(inputDescricao, nave.descricao);
});
inputValor.addEventListener('keyup', event => {
ComparaDados(inputValor, nave.valor);
});
<file_sep><?php
require('server/connect.php');
$dados = mysql_query('SELECT * FROM nave', $con) or die(mysql_error());
$row = mysql_fetch_assoc($dados);
$total = mysql_num_rows($dados);
?>
<!doctype html>
<html lang="pt-br">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="css/bulma.min.0.9.css">
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/default.css">
<title>Star Store - Home</title>
<link rel="shortcut icon" href="images/favicon.png" type="image/x-icon" />
</head>
<body>
<div class="painel">
<div class="painel-content">
<h1 class="title is-1" style="color: #161718">Bem-vindo a Star Store</h1>
<h2 class="subtitle is-2" style="color: #161718">O Universo precisa ser explorado, sua viagem começa aqui!</h2>
</div>
</div>
<?php include('model/navbar.html'); ?>
<div class="container" style="margin-top: 30px;">
<div class="columns is-multiline">
<?php
if($total > 0) {
do {
?>
<div class="column is-one-third">
<div class="card large">
<div class="card-image is-16by9">
<figure class="image">
<?php
$id = $row['idNave'];
$imagemDados = mysql_query('SELECT * FROM imagem WHERE idNave = ' . $id, $con) or die(mysql_error());
$img = mysql_fetch_assoc($imagemDados)
?>
<img src="images/ships/<?=$img['nome']?>">
</figure>
</div>
<div class="card-content">
<div class="content">
<div class="title"><?=$row['nome']?></div>
<div class="subtitle"><?=$row['universo']?></div>
<div class="description"><?=$row['descricao']?>.</div><br>
<div class="capacidade">Capacidade: <strong><?=$row['capacidade']?></strong></div>
<div class="value">Valor: R$ <strong><?=$row['valor']?></strong></div>
</div>
</div>
</div>
</div>
<?php
}while($row = mysql_fetch_assoc($dados));
}
?>
</div>
</div>
<?php include('model/footer.html'); ?>
</body>
</html><file_sep><?php
require('credentials.php');
$host = "localhost";
$db = "Store";
$con = mysql_pconnect($host, $user, $pass) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($db, $con);
$mysqli = new mysqli($host, $user, $pass, $db) or die(mysqli_error());
// Formatando em utf-8
mysql_query("SET NAMES 'utf8'");
mysql_query('SET character_set_connection=utf8');
mysql_query('SET character_set_client=utf8');
mysql_query('SET character_set_results=utf8');
?><file_sep><html>
<head>
<meta charset="utf-8">
<title>Enviando requisição</title>
</head>
<body><h1>Aguarde um momento</h1></body>
<?php
require('../connect.php');
require('login-verification.php');
$nome = mysql_real_escape_string($_POST['nome']);
$universo = mysql_real_escape_string($_POST['universo']);
$capacidade = mysql_real_escape_string($_POST['capacidade']);
$descricao = mysql_real_escape_string($_POST['descricao']);
$valor = mysql_real_escape_string($_POST['valor']);
$id = mysql_real_escape_string($_POST['id']);
$query = " UPDATE `nave`
SET nome = '$nome', universo = '$universo', capacidade = '$capacidade',
descricao ='$descricao', valor = '$valor'
WHERE idNave = '$id'
";
mysql_query($query, $con);
header('Location: ../../pages/internal-system/ship-edit.php?ship='.$id);
exit();
?>
</html><file_sep><html>
<head>
<meta charset="utf-8">
<title>Enviando requisição</title>
</head>
<body><h1>Aguarde um momento</h1></body>
<?php
require('../connect.php');
require('login-verification.php');
$idImagem = $_POST['idImagem'];
$idNave = $_POST['id'];
$arquivo_tmp = $_FILES[ 'imagem' ][ 'tmp_name' ];
$nome = $_FILES[ 'imagem' ][ 'name' ];
$extensao = pathinfo($nome, PATHINFO_EXTENSION);
$extensao = strtolower($extensao);
// Verificando tentativa de invasão pela imagem
$permitido = False;
$extensaoPermitida = array('png', 'jpg', 'jpeg', 'gif');
for ($i = 0; $i < count($extensaoPermitida); $i++){
if ($extensao == $extensaoPermitida[$i]){
$permitido = True;
}
}
if(!$permitido){
header('Location: ../../pages/internal-system/ship-registration.php');
exit();
}
// Deletando
$dados = mysql_query('SELECT * FROM imagem WHERE idImagem = ' . $idImagem, $con) or die(mysql_error());
$row = mysql_fetch_assoc($dados);
unlink('../../images/ships/'.$row['nome']);
// Enviando para o servidor
$novoNome = uniqid(time()) . '.' . $extensao;
$destino = '../../images/ships/' . $novoNome;
move_uploaded_file($arquivo_tmp, $destino);
// Enviando as informações para o servidor
$queryImg = " UPDATE `imagem` SET nome = '$novoNome' WHERE idImagem = $idImagem";
mysql_query($queryImg, $con);
header('Location: ../../pages/internal-system/ship-edit.php?ship='.$idNave);
exit();
?>
</html><file_sep><!doctype html>
<html lang="pt-br">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="../css/bulma.min.0.9.css">
<link rel="stylesheet" href="../css/style.css">
<link rel="stylesheet" href="../css/default.css">
<title>Star Store - Sobre nós</title>
<link rel="shortcut icon" href="../images/favicon.png" type="image/x-icon" />
</head>
<body>
<?php include('../model/navbar.html'); ?>
<div class="container is-fluid" style="margin-top: 30px;">
<div class="paragrafo">
<h1 class="title">Nosso time</h1>
<h2 class="subtitle">Elias Santos</h2>
Aluno da escola Etec Vasco Antônio Venchiarutti, que com muita dedicação se empenhou para ajudar no bem coletivo, e garantir o melhor para equipe. Com grande esforço obteve sucesso em seus ofícios escolares e com sua humildade beneficiou a todos ao seu redor.
</div>
<div class="paragrafo">
<h2 class="subtitle"><NAME></h2>
Aluno da escola Etec Vasco Antônio Venchiarutti, onde se dedicou completamente a criação de sites e programas de forma exitosa e com muita determinação conseguiu alcançar os seus objetivos. Sempre se esforçou para dar o seu melhor em todos requisitos escolares, alcançando assim notoriedade em todos os seus projetos.
</div>
<div class="paragrafo">
<h2 class="subtitle"><NAME></h2>
Aluno da escola Etec Vas<NAME>, que com muito esforço conseguiu, com mérito, se destacar em suas atividades escolares. Com seu carisma e simpatia conquistou a confiança de amigos e professores, tendo assim uma boa influência escolar.
</div>
<div class="paragrafo">
<h2 class="subtitle"><NAME></h2>
Aluno da escola Etec V<NAME>, que com sua autoconfiança conseguiu de uma forma gratificante alcançar o ápice de seus objetivos e ganhar certo destaque em suas áreas de maior habilidade. Conquistando assim o respeito e apresso de professores e colegas.
</div>
</div>
<?php include('../model/footer.html'); ?>
</body>
</html><file_sep><?php
require("../../server/connect.php");
require("../../server/execs/login-verification.php");
if(!isset($_GET["ship"])) {
header('Location: ship-manage.php');
exit();
} else {
$idNave = $_GET["ship"];
$dados = mysql_query('SELECT * FROM nave WHERE idNave = ' . $idNave, $con) or die(mysql_error());
$row = mysql_fetch_assoc($dados);
$total = mysql_num_rows($dados);
}
?>
<!doctype html>
<html lang="pt-br">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="../../../css/bulma.min.0.9.css">
<link rel="stylesheet" href="../../../css/form.css">
<title>Edição de Nave - Sistema Interno</title>
<link rel="shortcut icon" href="../../images/favicon-manage.png" type="image/x-icon" />
<!-- Passando dados para o JS -->
<script>
var nave = {
nome: "<?=$row['nome']?>",
universo: "<?=$row['universo']?>",
descricao: "<?=$row['descricao']?>",
capacidade: "<?=$row['capacidade']?>",
valor: "<?=$row['valor']?>"
}
</script>
</head>
<body>
<?php include('../../model/navbar-internal-system.php');?>
<div class="container">
<form method="post" action="../../../server/execs/ship-edit-exec.php" enctype="multipart/form-data" autocomplete="off">
<h3 class="title is-3">Dados</h3>
<div class="control">
<label>Nome</label>
<input name="nome" id="nome" type="text" class="input is-info">
</div>
<div class="control">
<label>Universo</label>
<input name="universo" id="universo" type="text" class="input is-info">
</div>
<div class="control">
<label>Capacidade</label>
<input name="capacidade" id="capacidade" type="number" class="input is-info">
</div>
<div class="control">
<label>Descrição</label>
<input name="descricao" id="descricao" type="text" class="input is-info">
</div>
<div class="control">
<label>Valor</label>
<input name="valor" id="valor" type="text" class="input is-info dinheiro">
</div>
<input type="hidden" name="id" value="<?=$row['idNave']?>" />
<button type="submit" class="button is-link">Salvar alterações!</button>
</form>
<hr style="border: 1px solid #4a4a4a;">
<form method="post" action="../../../server/execs/ship-image-edit.php" enctype="multipart/form-data" autocomplete="off">
<h3 class="title is-3">Imagem</h3>
<?php
$id = $row['idNave'];
$imagemDados = mysql_query('SELECT * FROM imagem WHERE idNave = ' . $id, $con) or die(mysql_error());
$img = mysql_fetch_assoc($imagemDados)
?>
<div style="display: flex; align-items: center;">
<img class="form-img" src="../../images/ships/<?=$img['nome']?>">
<input type="file" name="imagem" accept="image/png, image/jpeg, image/gif" required style="margin-left: 15px;">
</div>
<input type="hidden" name="idImagem" value="<?=$img['idImagem']?>" />
<input type="hidden" name="id" value="<?=$row['idNave']?>" />
<br>
<button type="submit" class="button is-info">Alterar imagem</button>
<br><br>
</form>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.1/js/all.min.js"></script>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<!-- Mascara de Valor -->
<script src="../../../js/mask-number-min.js"></script>
<script>
$('.dinheiro').mask('#.##0,00', { reverse: true });
</script>
<script src="../../../js/edit-script.js"></script>
</div>
</body>
</html> | ab1dc8d243552f3af152817ed9ba06c595903e74 | [
"JavaScript",
"PHP"
] | 15 | PHP | Lemon42/star-store | cd7283443ef02092b86f1b4475358893f30ce2f6 | e917c0b740c15115ef17f625deb04c311db14b9b |
refs/heads/main | <repo_name>david-alfaro/tarea4-Ejercicio1<file_sep>/src/alfaroviquez/david/bl/entidades/Prestamo.java
package alfaroviquez.david.bl.entidades;
import java.sql.Date;
import java.time.LocalDate;
import java.util.ArrayList;
public class Prestamo {
private Persona persona;
private Material material;
private Date fechaDevolucion;
private Date fechaPrestamo;
public Persona getPersona() {
return persona;
}
public void setPersona(Persona persona) {
this.persona = persona;
}
public Material getMaterial() {
return material;
}
public void setMaterial(Material material) {
this.material = material;
}
public Date getFechaDevolucion() {
return fechaDevolucion;
}
public void setFechaDevolucion(Date fechaDevolucion) {
this.fechaDevolucion = fechaDevolucion;
}
public Date getFechaPrestamo() {
return fechaPrestamo;
}
public void setFechaPrestamo(Date fechaPrestamo) {
this.fechaPrestamo = fechaPrestamo;
}
public Prestamo() {
}
public Prestamo(Persona persona, Material material, Date fechaDevolucion, Date fechaPrestamo) {
this.persona = persona;
this.material = material;
this.fechaDevolucion = fechaDevolucion;
this.fechaPrestamo = fechaPrestamo;
}
@Override
public String toString() {
return "Prestamo{" +
"persona=" + persona +
", material=" + material +
", fechaDevolucion=" + fechaDevolucion +
", fechaPrestamo=" + fechaPrestamo +
'}';
}
}
<file_sep>/src/alfaroviquez/david/iu/IU.java
package alfaroviquez.david.iu;
import java.io.PrintStream;
import java.util.Scanner;
public class IU {
private PrintStream output = new PrintStream(System.out);
private Scanner input = new Scanner(System.in).useDelimiter("\n");
public void imprimirMenu(){
output.println("*** BibliotecaU ***");
output.println("1.Registro de usuarios");
output.println("2.Registro de Materiales");
output.println("3.Listar Usuarios");
output.println("4.Listar Materiales de la Biblioteca");
output.println("5. Prestamos");
output.println("6. Salir");
}
public void imprimirMenu2(){
output.println("*** Registro de Usuarios ***");
output.println("1. Registrar Estudiantes");
output.println("2. Registrar Profesores");
output.println("3. Registrar Administrativo");
output.println("4. Volver");
}
public void imprimirMenu3(){
output.println("*** Registro de Materiales ***");
output.println("1. Registro de Material de Texto");
output.println("2. Registro de Material de Audio");
output.println("3. Registro de Material de Video");
output.println("4. Registro de Otro tipo de material");
output.println("5. Volver");
}
public String leerMensaje(){
return input.next();
}
public int leerNumero(){
return input.nextInt();
}
public void imprimirMensaje(String str){
output.println(str);
}
}
<file_sep>/src/alfaroviquez/david/bl/entidades/Profesor.java
package alfaroviquez.david.bl.entidades;
import alfaroviquez.david.bl.tipos.tipoContrato;
import java.sql.Date;
import java.time.LocalDate;
public class Profesor extends Persona {
private Date fechaContratacion;
private tipoContrato contrato;
public Date getFechaContratacion() {
return fechaContratacion;
}
public void setFechaContratacion(Date fechaContratacion) {
this.fechaContratacion = fechaContratacion;
}
public tipoContrato getContrato() {
return contrato;
}
public void setContrato(tipoContrato contrato) {
this.contrato = contrato;
}
public Profesor() {
}
public Profesor(String nombre, String apellido, String ID, Date fechaContratacion, tipoContrato contrato) {
super(nombre, apellido, ID);
this.fechaContratacion = fechaContratacion;
this.contrato = contrato;
}
@Override
public String toString() {
return "Profesor{" +
"fechaContratacion=" + fechaContratacion +
", contrato=" + contrato +
", nombre='" + nombre + '\'' +
", apellido='" + apellido + '\'' +
", ID='" + ID + '\'' +
"} ";
}
@Override
public String toCSVLine() {
return this.nombre+","+this.apellido+","+this.ID+","+this.contrato+","+this.fechaContratacion;
}
}
<file_sep>/src/alfaroviquez/david/controlador/Controlador.java
package alfaroviquez.david.controlador;
import alfaroviquez.david.bl.entidades.*;
import alfaroviquez.david.bl.logica.Gestor;
import alfaroviquez.david.iu.IU;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
public class Controlador {
private IU interfaz = new IU();
private Gestor gestor = new Gestor();
public void ejecutarPrograma() {
int opcion = 0;
do {
interfaz.imprimirMenu();
opcion = interfaz.leerNumero();
procesarOpcion(opcion);
} while (opcion != 6);
}
private void procesarOpcion(int opcion) {
switch (opcion) {
case 1:
int opcion2 = 0;
do {
interfaz.imprimirMenu2();
opcion2 = interfaz.leerNumero();
procesarOpcion2(opcion2);
} while (opcion2 != 4);
break;
case 2:
int opcion3 = 0;
do {
interfaz.imprimirMenu3();
opcion3 = interfaz.leerNumero();
procesarOpcion3(opcion3);
} while (opcion3 != 5);
break;
case 3:
interfaz.imprimirMensaje("*** Lista de Estudiantes ***");
listarEstudiantes();
interfaz.imprimirMensaje("*** Lista de Profesores ***");
listarProfesores();
interfaz.imprimirMensaje("*** Lista de Personal Administrativo ***");
listarAdministrativos();
break;
case 4:
interfaz.imprimirMensaje("*** Lista de Materiales de Texto ***");
listarTextos();
interfaz.imprimirMensaje("*** Lista Materiales de Audio ***");
listarAudios();
interfaz.imprimirMensaje("*** Lista de Materiales de Video ***");
listarVideos();
interfaz.imprimirMensaje("*** Otros ***");
listarOtroMaterial();
break;
case 5:
crearPrestamo();
break;
case 6:
break;
default:
interfaz.imprimirMensaje("Opcion invalida");
}
}
private void procesarOpcion3(int opcion3) {
switch (opcion3) {
case 1:
registrarTexto();
break;
case 2:
registrarAudio();
break;
case 3:
registrarVideo();
break;
case 4:
registrarOtroMaterial();
break;
case 5:
break;
default:
interfaz.imprimirMensaje("Opcion invalida");
}
}
private void procesarOpcion2(int opcion2) {
switch (opcion2) {
case 1:
registrarEstudiante();
break;
case 2:
registrarProfesor();
break;
case 3:
registrarAdministrativo();
break;
case 4:
break;
default:
interfaz.imprimirMensaje("Opcion invalida");
}
}
private void registrarEstudiante() {
interfaz.imprimirMensaje("REGISTRAR ESTUDIANTE");
interfaz.imprimirMensaje("Nombre del estudiante: ");
String nombre = interfaz.leerMensaje();
interfaz.imprimirMensaje("Apellido del estudiante: ");
String apellido = interfaz.leerMensaje();
interfaz.imprimirMensaje("Carnet: ");
String carne = interfaz.leerMensaje();
interfaz.imprimirMensaje("Carrera matriculada: ");
String carrera = interfaz.leerMensaje();
interfaz.imprimirMensaje("Creditos matriculados: ");
int creditos = interfaz.leerNumero();
gestor.crearEstudiante(nombre, apellido, carne, carrera, creditos);
interfaz.imprimirMensaje("Estudiante registrado con exito");
}
private void listarEstudiantes() {
for (Persona unEstudiante : gestor.listarEstudiantes()
) {
interfaz.imprimirMensaje(unEstudiante.toCSVLine());
}
}
private void registrarProfesor() {
interfaz.imprimirMensaje("REGISTRAR PROFESOR");
interfaz.imprimirMensaje("Nombre del profesor: ");
String nombre = interfaz.leerMensaje();
interfaz.imprimirMensaje("Apellido del profesor: ");
String apellido = interfaz.leerMensaje();
interfaz.imprimirMensaje("Cedula (ID): ");
String ID = interfaz.leerMensaje();
interfaz.imprimirMensaje("Fecha de contratacion (yyyy-MM-dd): ");
String fecha = interfaz.leerMensaje();
LocalDate fechaContratacion = obtenerFecha(fecha);
interfaz.imprimirMensaje("Tipo de contrato (TIEMPO_COMPLETO, MEDIO_TIEMPO): ");
String contrato = interfaz.leerMensaje();
gestor.crearProfesor(nombre, apellido, ID, Date.valueOf(fechaContratacion), contrato);
interfaz.imprimirMensaje("Profesor registrado con exito");
}
private void listarProfesores() {
for (Persona unProfesor : gestor.listarProfesores()
) {
interfaz.imprimirMensaje(unProfesor.toCSVLine());
}
}
private void registrarAdministrativo() {
interfaz.imprimirMensaje("REGISTRAR Administrativo");
interfaz.imprimirMensaje("Nombre: ");
String nombre = interfaz.leerMensaje();
interfaz.imprimirMensaje("Apellido: ");
String apellido = interfaz.leerMensaje();
interfaz.imprimirMensaje("Cedula (ID): ");
String ID = interfaz.leerMensaje();
interfaz.imprimirMensaje("Tipo de nombramiento (A,B,C): ");
String tipoNombramiento = interfaz.leerMensaje();
interfaz.imprimirMensaje("Horas semanales asignadas: ");
int cantHoras = interfaz.leerNumero();
gestor.crearAdministrativo(nombre, apellido, ID, tipoNombramiento, cantHoras);
interfaz.imprimirMensaje("Persona Administrativa registrada con exito");
}
private void listarAdministrativos() {
for (Persona unAdministrarivo : gestor.listarAdministrativos()
) {
interfaz.imprimirMensaje(unAdministrarivo.toCSVLine());
}
}
private void registrarTexto() {
interfaz.imprimirMensaje("REGISTRAR MATERIAL DE TEXTO");
interfaz.imprimirMensaje("Ingrese la signatura (ID): ");
int signatura = interfaz.leerNumero();
interfaz.imprimirMensaje("Material restringido ? (y/n): ");
String respuesta = interfaz.leerMensaje();
boolean restringido = false;
if (respuesta.equalsIgnoreCase("y")) {
restringido = true;
} else {
restringido = false;
}
interfaz.imprimirMensaje("Tema : ");
String tema = interfaz.leerMensaje();
interfaz.imprimirMensaje("Fecha de compra (yyyy-MM-dd): ");
String fecha = interfaz.leerMensaje();
LocalDate fechaCompra = obtenerFecha(fecha);
interfaz.imprimirMensaje("Titulo del texto: ");
String titulo = interfaz.leerMensaje();
interfaz.imprimirMensaje("Nombre del autor: ");
String autor = interfaz.leerMensaje();
interfaz.imprimirMensaje("Idioma: ");
String idioma = interfaz.leerMensaje();
interfaz.imprimirMensaje("Fecha de publicacion (yyyy-MM-dd): ");
String publicacion = interfaz.leerMensaje();
LocalDate fechapublicacion = obtenerFecha(publicacion);
interfaz.imprimirMensaje("Cantidad de paginas: ");
int paginas = interfaz.leerNumero();
gestor.crearMaterialTexto(signatura, restringido, tema, Date.valueOf(fechaCompra), titulo, autor, Date.valueOf(fechapublicacion), paginas, idioma);
interfaz.imprimirMensaje("Material registrado con exito");
}
private void listarTextos() {
for (Material unTexto : gestor.listarTextos()
) {
interfaz.imprimirMensaje(unTexto.toCSVLine());
}
}
private void registrarAudio() {
interfaz.imprimirMensaje("REGISTRAR MATERIAL DE AUDIO");
interfaz.imprimirMensaje("Ingrese la signatura (ID): ");
int signatura = interfaz.leerNumero();
interfaz.imprimirMensaje("Material restringido ? (y/n): ");
String respuesta = interfaz.leerMensaje();
boolean restringido = false;
if (respuesta.equalsIgnoreCase("y")) {
restringido = true;
} else {
restringido = false;
}
interfaz.imprimirMensaje("Tema : ");
String tema = interfaz.leerMensaje();
interfaz.imprimirMensaje("Fecha de compra (yyyy-MM-dd): ");
String fecha = interfaz.leerMensaje();
LocalDate fechaCompra = obtenerFecha(fecha);
interfaz.imprimirMensaje("Idioma: ");
String idioma = interfaz.leerMensaje();
interfaz.imprimirMensaje("Duracion: ");
int duracion = interfaz.leerNumero();
interfaz.imprimirMensaje("Formato (CASETE,CD,DVD): ");
String formato = interfaz.leerMensaje();
gestor.crearMaterialAudio(signatura, restringido, tema, Date.valueOf(fechaCompra), formato, duracion, idioma);
interfaz.imprimirMensaje("Material registrado con exito");
}
private void listarAudios() {
for (Material unAudio : gestor.listarAudios()
) {
interfaz.imprimirMensaje(unAudio.toCSVLine());
}
}
private void registrarVideo() {
interfaz.imprimirMensaje("REGISTRAR MATERIAL DE VIDEO");
interfaz.imprimirMensaje("Ingrese la signatura (ID): ");
int signatura = interfaz.leerNumero();
interfaz.imprimirMensaje("Material restringido ? (y/n): ");
String respuesta = interfaz.leerMensaje();
boolean restringido = false;
if (respuesta.equalsIgnoreCase("y")) {
restringido = true;
} else {
restringido = false;
}
interfaz.imprimirMensaje("Tema : ");
String tema = interfaz.leerMensaje();
interfaz.imprimirMensaje("Fecha de compra (yyyy-MM-dd): ");
String fecha = interfaz.leerMensaje();
LocalDate fechaCompra = obtenerFecha(fecha);
interfaz.imprimirMensaje("Idioma: ");
String idioma = interfaz.leerMensaje();
interfaz.imprimirMensaje("Duracion: ");
int duracion = interfaz.leerNumero();
interfaz.imprimirMensaje("Formato (VHS,VCD,DVD): ");
String formato = interfaz.leerMensaje();
interfaz.imprimirMensaje("Nombre del director: ");
String director = interfaz.leerMensaje();
gestor.crearMaterialVideo(signatura, restringido, tema, Date.valueOf(fechaCompra), formato, duracion, idioma, director);
interfaz.imprimirMensaje("Material registrado exitosamente");
}
private void listarVideos() {
for (Material unvideo : gestor.listarVideos()
) {
interfaz.imprimirMensaje(unvideo.toCSVLine());
}
}
private void registrarOtroMaterial() {
interfaz.imprimirMensaje("REGISTRAR OTRO TIPO DE MATERIAL");
interfaz.imprimirMensaje("Ingrese la signatura (ID): ");
int signatura = interfaz.leerNumero();
interfaz.imprimirMensaje("Material restringido ? (y/n): ");
String respuesta = interfaz.leerMensaje();
boolean restringido = false;
if (respuesta.equalsIgnoreCase("y")) {
restringido = true;
} else {
restringido = false;
}
interfaz.imprimirMensaje("Tema : ");
String tema = interfaz.leerMensaje();
interfaz.imprimirMensaje("Fecha de compra (yyyy-MM-dd): ");
String fecha = interfaz.leerMensaje();
LocalDate fechaCompra = obtenerFecha(fecha);
//Date fechaC = convertTOLocalDateViaSqlDate(fechaCompra);
interfaz.imprimirMensaje("Descripcion: ");
String descripcion = interfaz.leerMensaje();
gestor.crearOtroMaterial(signatura, restringido, tema, Date.valueOf(fechaCompra), descripcion);
interfaz.imprimirMensaje("Material registrado exitosamente");
}
private void listarOtroMaterial() {
for (Material unMaterial : gestor.listarOtros()
) {
interfaz.imprimirMensaje(unMaterial.toCSVLine());
}
}
private void crearPrestamo() {
interfaz.imprimirMensaje("RESGISTRAR PRESTAMO");
interfaz.imprimirMensaje("Lista de Estudiantes");
listarEstudiantes();
interfaz.imprimirMensaje("Lista de Profesores");
listarProfesores();
interfaz.imprimirMensaje("Lista de Administrativos");
listarAdministrativos();
interfaz.imprimirMensaje("---------------------------------");
interfaz.imprimirMensaje("Ingrese el ID de la persona: ");
String id = interfaz.leerMensaje();
Persona persona = gestor.buscarPersonaPorID(id);
interfaz.imprimirMensaje("*** LISTA DE MATERIALES ***");
interfaz.imprimirMensaje("*** Lista de Materiales de Texto ***");
listarTextos();
interfaz.imprimirMensaje("*** Lista Materiales de Audio ***");
listarAudios();
interfaz.imprimirMensaje("*** Lista de Materiales de Video ***");
listarVideos();
interfaz.imprimirMensaje("*** Otros ***");
listarOtroMaterial();
interfaz.imprimirMensaje("---------------------------------");
interfaz.imprimirMensaje("Ingrese la signatura del material");
int signatura = interfaz.leerNumero();
Material material = gestor.buscarMaterialPorSignatura(signatura);
interfaz.imprimirMensaje("Ingrese la fecha de devolucion (yyyy-MM-dd): ");
String fecha = interfaz.leerMensaje();
LocalDate fechaDevolucion = obtenerFecha(fecha);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date date = new java.util.Date();
String fechaPrestamo = formatter.format(date);
LocalDate fechaPres = obtenerFecha(fechaPrestamo);
gestor.registrarPrestamo(persona,material,Date.valueOf(fechaDevolucion),Date.valueOf(fechaPres));
interfaz.imprimirMensaje("Prestamo registrado");
}
private LocalDate obtenerFecha(String fecha) {
return LocalDate.parse(fecha);
}
public java.sql.Date convertTOLocalDateViaSqlDate(java.util.Date dateToConvert) {
return new java.sql.Date(dateToConvert.getTime());
}
}
<file_sep>/src/alfaroviquez/david/bl/interfaces/SerializacionCSV.java
package alfaroviquez.david.bl.interfaces;
public interface SerializacionCSV {
public String toCSVLine();
}
<file_sep>/src/alfaroviquez/david/persistencia/OtroDAO.java
package alfaroviquez.david.persistencia;
import alfaroviquez.david.bl.entidades.OtroMaterial;
import alfaroviquez.david.bl.entidades.Video;
import alfaroviquez.david.bl.tipos.formatoVideo;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class OtroDAO {
Connection con;
private final String TEMPLATE_INSERT = "insert into otrosMateriales (signatura,tema,fechaCompra,restringido,descripcion)" +
"values (?,?,?,?,?)";
private final String TEMPLATE_QRY = "select * from otrosMateriales";
private PreparedStatement cmdInsertar;
private PreparedStatement consulta;
public OtroDAO(Connection cnx){
this.con=cnx;
try{
this.cmdInsertar = con.prepareStatement(TEMPLATE_INSERT);
this.consulta = con.prepareStatement(TEMPLATE_QRY);
}catch (SQLException e){
e.printStackTrace();
}
}
public void guardar(OtroMaterial otro) throws SQLException {
if(this.cmdInsertar!=null){
this.cmdInsertar.setInt(1,otro.getSignatura());
this.cmdInsertar.setString(2, otro.getTema());
this.cmdInsertar.setDate(3,otro.getFechaCompra());
this.cmdInsertar.setBoolean(4, otro.getRestringido());
this.cmdInsertar.setString(5, otro.getDescripcion());
this.cmdInsertar.execute();
}
}
public List<OtroMaterial> obtenerOtros(){
ArrayList<OtroMaterial> listaOtros = new ArrayList<>();
try {
ResultSet resultSet = this.consulta.executeQuery();
while (resultSet.next()){
OtroMaterial otro = new OtroMaterial();
otro.setSignatura(resultSet.getInt("signatura"));
otro.setTema(resultSet.getString("tema"));
otro.setFechaCompra(resultSet.getDate("fechaCompra"));
otro.setRestringido(resultSet.getBoolean("restringido"));
otro.setDescripcion(resultSet.getString("descripcion"));
listaOtros.add(otro);
}
}catch (SQLException e){
e.printStackTrace();
}
return listaOtros;
}
}
<file_sep>/src/alfaroviquez/david/bl/logica/Gestor.java
package alfaroviquez.david.bl.logica;
import alfaroviquez.david.bl.entidades.*;
import alfaroviquez.david.bl.tipos.formatoAudio;
import alfaroviquez.david.bl.tipos.formatoVideo;
import alfaroviquez.david.bl.tipos.tipoContrato;
import alfaroviquez.david.bl.tipos.tipoNombramiento;
import alfaroviquez.david.persistencia.*;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Gestor {
private Connection connection;
private String URL = "jdbc:mysql://localhost:3306/biblioteca";
private String USER = "root";
private String PSW = "12345";
private EstudianteDAO estudianteDAO;
private ProfesorDAO profesorDAO;
private AdministrativoDAO adminDAO;
private AudioDAO audioDAO;
private TextoDAO textoDAO;
private VideoDAO videoDAO;
private OtroDAO otroDAO;
private PrestamoDAO prestamoDAO;
private ArrayList<Persona> listaPersonas = new ArrayList<>();
private ArrayList<Material> listaMateriales = new ArrayList<>();
public Gestor() {
try {
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
this.connection = DriverManager.getConnection(URL, USER, PSW);
this.estudianteDAO = new EstudianteDAO(this.connection);
this.profesorDAO = new ProfesorDAO(this.connection);
this.adminDAO = new AdministrativoDAO(this.connection);
this.audioDAO = new AudioDAO(this.connection);
this.textoDAO = new TextoDAO(this.connection);
this.videoDAO = new VideoDAO(this.connection);
this.otroDAO = new OtroDAO(this.connection);
this.prestamoDAO = new PrestamoDAO(this.connection);
} catch (Exception e) {
e.printStackTrace();
System.out.println("No se puede conectar a la base de datos");
}
}
public void crearEstudiante(String nombre, String apellido, String ID, String carrera, int creditos) {
Estudiante nuevoEstudiante = new Estudiante(nombre, apellido, ID, carrera, creditos);
try {
estudianteDAO.guardar(nuevoEstudiante);
} catch (SQLException e) {
e.printStackTrace();
}
listaPersonas.add(nuevoEstudiante);
}
public List<Estudiante> listarEstudiantes() {
return estudianteDAO.obtenerEstudiantes();
}
public void crearProfesor(String nombre, String apellido, String ID, Date fechaContratacion, String tipocontrato) {
tipoContrato contrato = tipoContrato.valueOf(tipocontrato);
Profesor nuevoProfesor = new Profesor(nombre, apellido, ID, fechaContratacion, contrato);
try {
profesorDAO.guardar(nuevoProfesor);
} catch (SQLException e) {
e.printStackTrace();
}
listaPersonas.add(nuevoProfesor);
}
public List<Profesor> listarProfesores() {
return profesorDAO.obtenerProfesores();
}
public void crearAdministrativo(String nombre, String apellido, String ID, String nombramiento, int horasAsignadas) {
tipoNombramiento tipoNombramiento = alfaroviquez.david.bl.tipos.tipoNombramiento.valueOf(nombramiento);
Administrativo nuevoAdministrativo = new Administrativo(nombre, apellido, ID, tipoNombramiento, horasAsignadas);
try {
adminDAO.guardar(nuevoAdministrativo);
} catch (SQLException e) {
e.printStackTrace();
}
listaPersonas.add(nuevoAdministrativo);
}
public List<Administrativo> listarAdministrativos() {
return adminDAO.obtenerAdministrativos();
}
public void crearMaterialTexto(int signatura, Boolean restringido, String tema, Date fechaCompra, String titulo, String nombreAutor, Date fechaPublicacion, int numeroPaginas, String idioma) {
Texto nuevoTexto = new Texto(signatura, restringido, tema, fechaCompra, titulo, nombreAutor, fechaPublicacion, numeroPaginas, idioma);
try {
textoDAO.guardar(nuevoTexto);
} catch (SQLException e) {
e.printStackTrace();
}
listaMateriales.add(nuevoTexto);
}
public List<Texto> listarTextos() {
return textoDAO.obtenerTextos();
}
public void crearMaterialAudio(int signatura, Boolean restringido, String tema, Date fechaCompra, String formato, int duracion, String idioma) {
formatoAudio tipoFormato = formatoAudio.valueOf(formato);
Audio nuevoAudio = new Audio(signatura, restringido, tema, fechaCompra, tipoFormato, duracion, idioma);
try {
audioDAO.guardar(nuevoAudio);
} catch (SQLException e) {
e.printStackTrace();
}
listaMateriales.add(nuevoAudio);
}
public List<Audio> listarAudios() {
return audioDAO.obtenerAudios();
}
public void crearMaterialVideo(int signatura, Boolean restringido, String tema, Date fechaCompra, String formato, int duracion, String idioma, String director) {
formatoVideo tipoFormato = formatoVideo.valueOf(formato);
Video nuevoVideo = new Video(signatura, restringido, tema, fechaCompra, tipoFormato, duracion, idioma, director);
try {
videoDAO.guardar(nuevoVideo);
} catch (SQLException e) {
e.printStackTrace();
}
listaMateriales.add(nuevoVideo);
}
public List<Video> listarVideos() {
return videoDAO.obtenerVideos();
}
public void crearOtroMaterial(int signatura, Boolean restringido, String tema, Date fechaCompra, String descripcion) {
OtroMaterial nuevoOtro = new OtroMaterial(signatura, restringido, tema, fechaCompra, descripcion);
try {
otroDAO.guardar(nuevoOtro);
} catch (SQLException e) {
e.printStackTrace();
}
listaMateriales.add(nuevoOtro);
}
public List<OtroMaterial> listarOtros() {
return otroDAO.obtenerOtros();
}
public void registrarPrestamo(Persona per, Material mat, Date fechaDevol, Date fechaPrestamo) {
Prestamo nuevoPrestamo = new Prestamo(per,mat,fechaDevol,fechaPrestamo);
try {
prestamoDAO.guardarPrestamo(nuevoPrestamo);
} catch (SQLException e) {
e.printStackTrace();
}
}
public Persona buscarPersonaPorID(String id) {
for (Persona unaPersona : this.listaPersonas) {
if (unaPersona.getID().equals(id)) {
return unaPersona;
}
}
return null;
}
public Material buscarMaterialPorSignatura(int signatura) {
for (Material unMaterial : this.listaMateriales
) {
if (unMaterial.getSignatura() == signatura) {
return unMaterial;
}
}
return null;
}
}
<file_sep>/src/alfaroviquez/david/bl/tipos/tipoContrato.java
package alfaroviquez.david.bl.tipos;
public enum tipoContrato {
TIEMPO_COMPLETO,
MEDIO_TIEMPO
}
<file_sep>/src/alfaroviquez/david/bl/entidades/Persona.java
package alfaroviquez.david.bl.entidades;
import alfaroviquez.david.bl.interfaces.SerializacionCSV;
import java.util.Objects;
public abstract class Persona implements SerializacionCSV {
protected String nombre;
protected String apellido;
protected String ID;
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getApellido() {
return apellido;
}
public void setApellido(String apellido) {
this.apellido = apellido;
}
public Persona() {
}
public Persona(String nombre, String apellido, String ID) {
this.nombre = nombre;
this.apellido = apellido;
this.ID = ID;
}
@Override
public String toString() {
return "Persona{" +
"nombre='" + nombre + '\'' +
", apellido='" + apellido + '\'' +
", ID='" + ID + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Persona persona = (Persona) o;
return Objects.equals(nombre, persona.nombre) &&
Objects.equals(apellido, persona.apellido) &&
Objects.equals(ID, persona.ID);
}
@Override
public int hashCode() {
return Objects.hash(nombre, apellido, ID);
}
}
<file_sep>/src/alfaroviquez/david/bl/entidades/Audio.java
package alfaroviquez.david.bl.entidades;
import alfaroviquez.david.bl.tipos.formatoAudio;
import java.sql.Date;
import java.time.LocalDate;
public class Audio extends Material {
private formatoAudio formato;
private int duracion;
private String idioma;
public formatoAudio getFormato() {
return formato;
}
public void setFormato(formatoAudio formato) {
this.formato = formato;
}
public int getDuracion() {
return duracion;
}
public void setDuracion(int duracion) {
this.duracion = duracion;
}
public String getIdioma() {
return idioma;
}
public void setIdioma(String idioma) {
this.idioma = idioma;
}
public Audio() {
}
public Audio(int signatura, Boolean restringido, String tema, Date fechaCompra, formatoAudio formato, int duracion, String idioma) {
super(signatura, restringido, tema, fechaCompra);
this.formato = formato;
this.duracion = duracion;
this.idioma = idioma;
}
@Override
public String toString() {
return "Audio{" +
"formato=" + formato +
", duracion=" + duracion +
", idioma='" + idioma + '\'' +
", signatura='" + signatura + '\'' +
", restringido=" + restringido +
", tema='" + tema + '\'' +
", fechaCompra=" + fechaCompra +
"} " + super.toString();
}
@Override
public String toCSVLine() {
return this.signatura+","+this.restringido+","+this.tema+","+this.fechaCompra+","+this.formato+","+this.duracion+","+this.idioma;
}
}
<file_sep>/src/alfaroviquez/david/bl/entidades/Administrativo.java
package alfaroviquez.david.bl.entidades;
import alfaroviquez.david.bl.tipos.tipoNombramiento;
public class Administrativo extends Persona {
private tipoNombramiento nombramiento;
private int horasAsignadas;
public tipoNombramiento getNombramiento() {
return nombramiento;
}
public void setNombramiento(tipoNombramiento nombramiento) {
this.nombramiento = nombramiento;
}
public int getHorasAsignadas() {
return horasAsignadas;
}
public void setHorasAsignadas(int horasAsignadas) {
this.horasAsignadas = horasAsignadas;
}
public Administrativo() {
}
public Administrativo(String nombre, String apellido, String ID, tipoNombramiento nombramiento, int horasAsignadas) {
super(nombre, apellido, ID);
this.nombramiento = nombramiento;
this.horasAsignadas = horasAsignadas;
}
@Override
public String toString() {
return "Administrativo{" +
"nombramiento=" + nombramiento +
", horasAsignadas=" + horasAsignadas +
", nombre='" + nombre + '\'' +
", apellido='" + apellido + '\'' +
", ID='" + ID + '\'' +
"} ";
}
@Override
public String toCSVLine() {
return this.nombre+","+this.apellido+","+this.ID+","+this.nombramiento+","+this.horasAsignadas;
}
}
<file_sep>/src/alfaroviquez/david/bl/tipos/formatoVideo.java
package alfaroviquez.david.bl.tipos;
public enum formatoVideo {
VHS,
VCD,
DVD
}
<file_sep>/src/alfaroviquez/david/persistencia/AudioDAO.java
package alfaroviquez.david.persistencia;
import alfaroviquez.david.bl.entidades.Audio;
import alfaroviquez.david.bl.tipos.formatoAudio;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class AudioDAO {
Connection cnx;
private final String TEMPLATE_INSERTAR = "insert into audio(signatura,tema,fechaCompra,restringido,formato,duracion,idioma)" +
"values(?,?,?,?,?,?,?)";
private final String TEMPLAT_QRY = "select * from audio";
private PreparedStatement cmdInsertar;
private PreparedStatement qryConsulta;
public AudioDAO(Connection cnx){
this.cnx=cnx;
try {
this.cmdInsertar=cnx.prepareStatement(TEMPLATE_INSERTAR);
this.qryConsulta= cnx.prepareStatement(TEMPLAT_QRY);
}catch (SQLException e){
e.printStackTrace();
}
}
public void guardar(Audio audio) throws SQLException {
if(this.cmdInsertar!=null){
this.cmdInsertar.setInt(1,audio.getSignatura());
this.cmdInsertar.setString(2,audio.getTema());
this.cmdInsertar.setDate(3, audio.getFechaCompra());
this.cmdInsertar.setBoolean(4,audio.getRestringido());
this.cmdInsertar.setString(5, String.valueOf(audio.getFormato()));
this.cmdInsertar.setInt(6,audio.getDuracion());
this.cmdInsertar.setString(7, audio.getIdioma());
this.cmdInsertar.execute();
}
}
public List<Audio> obtenerAudios(){
ArrayList<Audio> listaAudios = new ArrayList<>();
try{
ResultSet resultSet = this.qryConsulta.executeQuery();
while (resultSet.next()){
Audio audio = new Audio();
audio.setSignatura(resultSet.getInt("signatura"));
audio.setTema(resultSet.getString("tema"));
audio.setFechaCompra(resultSet.getDate("fechaCompra"));
audio.setRestringido(resultSet.getBoolean("restringido"));
audio.setFormato(formatoAudio.valueOf(resultSet.getString("formato")));
audio.setDuracion(resultSet.getInt("duracion"));
audio.setIdioma(resultSet.getString("idioma"));
listaAudios.add(audio);
}
}catch (SQLException e){
e.printStackTrace();
}
return listaAudios;
}
}
| b98159946a441a6ac5d7986411f3be8c3f0d9afb | [
"Java"
] | 13 | Java | david-alfaro/tarea4-Ejercicio1 | b5da06bfc6914d553c2055cdfee8e10f58a3cb58 | 0320a57bc9cbfba7b35048229c0280e0eaaf1f24 |
refs/heads/master | <file_sep>package com.juventudes.gestor.entities;
import javax.persistence.Entity;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class OrganoUnitario extends Organo {
@ManyToOne
@JoinColumn(name = "id_dependencia_territorial")
private DireccionUnitaria direccionUnitariaSuperior ;
public void setDireccionUnitariaSuperior(DireccionUnitaria direccionUnitaria) {
this.direccionUnitariaSuperior = direccionUnitaria;
}
public DireccionUnitaria getDireccionUnitariaSuperior() {
return direccionUnitariaSuperior;
}
}<file_sep>package com.juventudes.gestor.mysc;
public enum Contrato {
TEMPORAL, INDEFINIDO
}
<file_sep>package com.juventudes.gestor.entities;
import java.io.Serializable;
import javax.persistence.*;
@Embeddable
public class MilitanteFrenteIntervencionPK implements Serializable {
private static final long serialVersionUID = 1L;
@Column(name="id_militante")
private int idMilitante;
@Column(name="id_frente")
private int idFrente;
public MilitanteFrenteIntervencionPK() {
}
public MilitanteFrenteIntervencionPK(int idMilitante, int idFrente) {
super();
this.idMilitante = idMilitante;
this.idFrente = idFrente;
}
public int getIdMilitante() {
return this.idMilitante;
}
public void setIdMilitante(int idMilitante) {
this.idMilitante = idMilitante;
}
public int getIdFrente() {
return this.idFrente;
}
public void setIdFrente(int idTipoFrente) {
this.idFrente = idTipoFrente;
}
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof MilitanteFrenteIntervencionPK)) {
return false;
}
MilitanteFrenteIntervencionPK castOther = (MilitanteFrenteIntervencionPK)other;
return
(this.idMilitante == castOther.idMilitante)
&& (this.idFrente == castOther.idFrente);
}
public int hashCode() {
final int prime = 31;
int hash = 17;
hash = hash * prime + this.idMilitante;
hash = hash * prime + this.idFrente;
return hash;
}
}<file_sep>package com.juventudes.gestor.entities;
import java.io.Serializable;
import javax.persistence.*;
import java.util.List;
/**
* The persistent class for the tipo_frente database table.
*
*/
@Entity
@Table(name="tipos_frente")
public class TipoFrente implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(unique=true, nullable=false)
private int id;
@Column(length=45)
private String nombre;
@OneToMany(mappedBy="tipoFrente")
private List<FrenteIntervencion> frenteIntervencions;
public TipoFrente() {
}
public TipoFrente(String nombre) {
this.nombre = nombre;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getNombre() {
return this.nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public List<FrenteIntervencion> getFrenteIntervencions() {
return this.frenteIntervencions;
}
public void setFrenteIntervencions(List<FrenteIntervencion> frenteIntervencions) {
this.frenteIntervencions = frenteIntervencions;
}
public FrenteIntervencion addFrenteIntervencion(FrenteIntervencion frenteIntervencion) {
getFrenteIntervencions().add(frenteIntervencion);
frenteIntervencion.setTipoFrente(this);
return frenteIntervencion;
}
public FrenteIntervencion removeFrenteIntervencion(FrenteIntervencion frenteIntervencion) {
getFrenteIntervencions().remove(frenteIntervencion);
frenteIntervencion.setTipoFrente(null);
return frenteIntervencion;
}
}<file_sep>package repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import com.juventudes.gestor.entities.TipoFrente;
public interface TipoFrenteRepository extends JpaRepository<TipoFrente, Integer> {
}
<file_sep>package com.juventudes.gestor.entities;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "responsabilidades")
public class Responsabilidad implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
private ResponsabilidadPK id;
@Column(name = "email_corporativo", length = 50)
private String emailCorporativo;
@ManyToOne
@JoinColumn(name = "id_organo", unique = false, nullable = false, insertable = false, updatable = false)
private Organo organo;
@ManyToOne
@JoinColumn(name = "id_militante")
private Militante militante;
@ManyToOne
@JoinColumn(name = "id_tipo_reponsabilidad", unique = false, nullable = false, insertable = false, updatable = false)
private TipoResponsabilidad tipoResponsabilidad;
public Responsabilidad() {
}
public Responsabilidad(Organo organo, TipoResponsabilidad tipoResponsabilidad) {
this.id = new ResponsabilidadPK();
this.id.setIdTipoReponsabilidad(tipoResponsabilidad.getId());
this.id.setIdOrgano(organo.getId());
}
public ResponsabilidadPK getId() {
return this.id;
}
public void setId(ResponsabilidadPK id) {
this.id = id;
}
public String getEmailCorporativo() {
return this.emailCorporativo;
}
public void setEmailCorporativo(String emailCorporativo) {
this.emailCorporativo = emailCorporativo;
}
public Organo getOrgano() {
return this.organo;
}
public void setOrgano(Organo organo) {
this.organo = organo;
}
public Militante getMilitante() {
return this.militante;
}
public void setMilitante(Militante militante) {
this.militante = militante;
}
public TipoResponsabilidad getTipoResponsabilidad() {
return this.tipoResponsabilidad;
}
public void setTipoResponsabilidad(TipoResponsabilidad tipoResponsabilidad) {
this.tipoResponsabilidad = tipoResponsabilidad;
}
}<file_sep>package repositories;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import com.juventudes.gestor.entities.Responsabilidad;
public interface ResponsabilidadRepository extends JpaRepository<Responsabilidad, Integer> {
Optional<Responsabilidad> findByMilitante_IdAndOrgano_Id(int id_militante, int id_organo);
List<Responsabilidad> findByMilitante_Id(int id_militante);
}
<file_sep>package integration;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.test.annotation.Commit;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import context.TestContextConfig;
import com.juventudes.gestor.entities.Colectivo;
import com.juventudes.gestor.entities.DireccionSectorial;
import com.juventudes.gestor.entities.DireccionUnitaria;
import com.juventudes.gestor.entities.Militante;
import com.juventudes.gestor.entities.Organo;
import com.juventudes.gestor.entities.OrganoSectorial;
import com.juventudes.gestor.entities.Responsabilidad;
import entitiesgenerators.MilitanteGenerator;
import repositories.MilitanteRepository;
import repositories.OrganoRepository;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = TestContextConfig.class)
@EnableJpaRepositories(basePackages = "repositories")
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@ActiveProfiles("test")
public class JpaIntegrationOrganizationTest {
@Autowired
MilitanteRepository militanteRepo;
@Autowired
OrganoRepository organoRepo;
public static Colectivo colectivoDH1, colectivoDH2, colectivoSevillaV, colectivoSevillaE1, colectivoSevillaE2;
public static DireccionUnitaria comarcalDosHermanas, comarcalSevilla, provincialSevilla, regionalAndalucia;
public static DireccionSectorial sectorialEstudiantesSevilla, sectorialObrerosSevilla, sectorialObrerosAndalucia,
sectorialEstudiantesAndalucia, sectorialVecinalAndalucia;
public static List<Militante> militantes = new ArrayList<>();
public static List<Responsabilidad> responsabilidades = new ArrayList<>();
@BeforeClass
public static void beforeMethod() {
// ===================ORGANOS=====================
colectivoDH1 = new Colectivo();
colectivoDH1.setIdMunicipio(6145); // Dos Hermanas
colectivoDH1.setNombre("Colectivo Obrero de Dos Hermanas");
colectivoDH2 = new Colectivo();
colectivoDH2.setIdMunicipio(6145); // Dos Hermanas
colectivoDH2.setNombre("Colectivo Estudiantes de Dos Hermanas");
colectivoSevillaV = new Colectivo();
colectivoSevillaV.setIdMunicipio(6199); // Sevilla
colectivoSevillaV.setNombre("Colectivo Vecinal de Sevilla");
colectivoSevillaE1 = new Colectivo();
colectivoSevillaE1.setIdMunicipio(6199); // Sevilla
colectivoSevillaE1.setNombre("Colectivo Estudiantes de Sevilla 1");
colectivoSevillaE2 = new Colectivo();
colectivoSevillaE2.setIdMunicipio(6199); // Sevilla
colectivoSevillaE2.setNombre("Colectivo Estudiantes de Sevilla 2");
comarcalDosHermanas = new DireccionUnitaria();
comarcalDosHermanas.setNombre("Comisión Política comarcal de Dos Hermanas");
comarcalSevilla = new DireccionUnitaria();
comarcalSevilla.setNombre("Comisión Política comarcal de Sevilla");
provincialSevilla = new DireccionUnitaria();
provincialSevilla.setNombre("Comisión Política provincial de Sevilla");
sectorialEstudiantesSevilla = new DireccionSectorial();
sectorialEstudiantesSevilla.setNombre("Comisión Política Sectorial Provincial de Estudiantes de Sevilla");
sectorialObrerosSevilla = new DireccionSectorial();
sectorialObrerosSevilla.setNombre("Comisión Política Sectorial Provincial de Obreros de Sevilla");
sectorialObrerosAndalucia = new DireccionSectorial();
sectorialObrerosAndalucia.setNombre("Comisión Política Sectorial Regional de Obreros de Andalucía");
sectorialVecinalAndalucia = new DireccionSectorial();
sectorialVecinalAndalucia.setNombre("Comisión Política Sectorial Regional Vecinal de Andalucía");
sectorialEstudiantesAndalucia = new DireccionSectorial();
sectorialEstudiantesAndalucia.setNombre("Comisión Política Sectorial Regional de Estudiantes de Andalucía");
regionalAndalucia = new DireccionUnitaria();
regionalAndalucia.setNombre("Comisión Política Regional de Andalucía");
// ===================MILITANTES=======================
militantes = MilitanteGenerator.createMilitantes(30);
}
@Test
public void A_insertOrganosAndMilitantes() {
organoRepo.saveAndFlush(colectivoDH1);
organoRepo.saveAndFlush(colectivoDH2);
organoRepo.saveAndFlush(colectivoSevillaV);
organoRepo.saveAndFlush(colectivoSevillaE1);
organoRepo.saveAndFlush(colectivoSevillaE2);
organoRepo.saveAndFlush(comarcalDosHermanas);
organoRepo.saveAndFlush(comarcalSevilla);
organoRepo.saveAndFlush(provincialSevilla);
organoRepo.saveAndFlush(sectorialObrerosSevilla);
organoRepo.saveAndFlush(sectorialEstudiantesSevilla);
organoRepo.saveAndFlush(regionalAndalucia);
organoRepo.saveAndFlush(sectorialObrerosAndalucia);
organoRepo.saveAndFlush(sectorialVecinalAndalucia);
organoRepo.saveAndFlush(sectorialEstudiantesAndalucia);
militanteRepo.saveAll(militantes);
militanteRepo.flush();
assertEquals(14, organoRepo.count());
assertEquals(30, militanteRepo.count());
}
@Test
@Transactional
@Commit
public void B_linkOrganos() {
List<Organo> organos = new ArrayList<>();
Colectivo cvohermanaso = (Colectivo) organoRepo.findByNombre("Colectivo Obrero de Dos Hermanas").get();
Colectivo cvohermanase = (Colectivo) organoRepo.findByNombre("Colectivo Estudiantes de Dos Hermanas").get();
Colectivo cvosevillae1 = (Colectivo) organoRepo.findByNombre("Colectivo Estudiantes de Sevilla 1").get();
Colectivo cvosevillae2 = (Colectivo) organoRepo.findByNombre("Colectivo Estudiantes de Sevilla 2").get();
Colectivo cvosevillav = (Colectivo) organoRepo.findByNombre("Colectivo Vecinal de Sevilla").get();
DireccionUnitaria comarcalDH = (DireccionUnitaria) organoRepo
.findByNombre("Comisión Política comarcal de Dos Hermanas").get();
DireccionUnitaria comarcalSevilla = (DireccionUnitaria) organoRepo
.findByNombre("Comisión Política comarcal de Sevilla").get();
DireccionUnitaria provincialSevilla = (DireccionUnitaria) organoRepo
.findByNombre("Comisión Política provincial de Sevilla").get();
DireccionSectorial sectorialSevillae = (DireccionSectorial) organoRepo
.findByNombre("Comisión Política Sectorial Provincial de Estudiantes de Sevilla").get();
DireccionSectorial sectorialSevillao = (DireccionSectorial) organoRepo
.findByNombre("Comisión Política Sectorial Provincial de Obreros de Sevilla").get();
DireccionSectorial sectorialAndaluciao = (DireccionSectorial) organoRepo
.findByNombre("Comisión Política Sectorial Regional de Obreros de Andalucía").get();
DireccionSectorial sectorialAndaluciae = (DireccionSectorial) organoRepo
.findByNombre("Comisión Política Sectorial Regional de Estudiantes de Andalucía").get();
DireccionSectorial sectorialAndaluciav = (DireccionSectorial) organoRepo
.findByNombre("Comisión Política Sectorial Regional Vecinal de Andalucía").get();
DireccionUnitaria regionalAndalucia = (DireccionUnitaria) organoRepo
.findByNombre("Comisión Política Regional de Andalucía").get();
//Comarcales con cvos
comarcalDH.addOrganoSectorialDependiente(cvohermanaso);
comarcalDH.addOrganoSectorialDependiente(cvohermanase);
List<OrganoSectorial> cvos_sevilla = new ArrayList<>();
cvos_sevilla.add(cvosevillav);
cvos_sevilla.add(cvosevillae1);
cvos_sevilla.add(cvosevillae2);
comarcalSevilla.setOrganosSectorialesDependientes(cvos_sevilla);
//Provinciales con comarcales
provincialSevilla.addOrganoUnitarioDependiente(comarcalSevilla);
provincialSevilla.addOrganoUnitarioDependiente(comarcalDH);
//Regionales y provinciales
regionalAndalucia.addOrganoUnitarioDependiente(provincialSevilla);
sectorialSevillae.setDireccionUnitariaSuperior(provincialSevilla);
sectorialSevillao.setDireccionUnitariaSuperior(provincialSevilla);
sectorialAndaluciav.setDireccionUnitariaSuperior(regionalAndalucia);
sectorialAndaluciao.setDireccionUnitariaSuperior(regionalAndalucia);
sectorialAndaluciae.setDireccionUnitariaSuperior(regionalAndalucia);
//Rama sectorial
//cvos
cvohermanase.setDireccionSectorialSuperior(sectorialSevillae);
cvohermanaso.setDireccionSectorialSuperior(sectorialSevillao);
sectorialSevillae.addOrganoSectorialDependiente(cvosevillae1);
sectorialSevillae.addOrganoSectorialDependiente(cvosevillae2);
sectorialSevillao.addOrganoSectorialDependiente(cvohermanaso);
sectorialAndaluciav.addOrganoSectorialDependiente(cvosevillav);
//organos de direccion
sectorialAndaluciae.addOrganoSectorialDependiente(sectorialSevillae);
sectorialAndaluciao.addOrganoSectorialDependiente(sectorialSevillao);
organos.add(cvohermanase);
organos.add(cvohermanaso);
organos.add(cvosevillae1);
organos.add(cvosevillae2);
organos.add(cvosevillav);
organos.add(sectorialSevillae);
organos.add(sectorialSevillao);
organos.add(sectorialAndaluciae);
organos.add(sectorialAndaluciao);
organos.add(sectorialAndaluciav);
organoRepo.flush();
}
@Test
@Transactional
public void C_assertLink() {
Colectivo cvohermanase = (Colectivo) organoRepo.findByNombre("Colectivo Estudiantes de Dos Hermanas").get();
DireccionUnitaria comarcalDH = (DireccionUnitaria) organoRepo
.findByNombre("Comisión Política comarcal de Dos Hermanas").get();
DireccionUnitaria comarcalSevilla = (DireccionUnitaria) organoRepo
.findByNombre("Comisión Política comarcal de Sevilla").get();
DireccionUnitaria provincialSevilla = (DireccionUnitaria) organoRepo
.findByNombre("Comisión Política provincial de Sevilla").get();
DireccionSectorial sectorialSevillae = (DireccionSectorial) organoRepo
.findByNombre("Comisión Política Sectorial Provincial de Estudiantes de Sevilla").get();
DireccionSectorial sectorialSevillao = (DireccionSectorial) organoRepo
.findByNombre("Comisión Política Sectorial Provincial de Obreros de Sevilla").get();
DireccionSectorial sectorialAndaluciae = (DireccionSectorial) organoRepo
.findByNombre("Comisión Política Sectorial Regional de Estudiantes de Andalucía").get();
DireccionSectorial sectorialAndaluciav = (DireccionSectorial) organoRepo
.findByNombre("Comisión Política Sectorial Regional Vecinal de Andalucía").get();
DireccionUnitaria regionalAndalucia = (DireccionUnitaria) organoRepo
.findByNombre("Comisión Política Regional de Andalucía").get();
//Estructura Unitaria
assertEquals(2, comarcalDH.getOrganosSectorialesDependientes().size());
assertEquals(comarcalDH.getId(), cvohermanase.getDireccionUnitariaSuperior().getId());
assertEquals(provincialSevilla.getId(), comarcalSevilla.getDireccionUnitariaSuperior().getId());
assertEquals(provincialSevilla.getId(), sectorialSevillao.getDireccionUnitariaSuperior().getId());
assertEquals(regionalAndalucia.getId(), provincialSevilla.getDireccionUnitariaSuperior().getId());
//Estructura sectorial
assertEquals(sectorialSevillae.getId(), cvohermanase.getDireccionSectorialSuperior().getId());
assertEquals(sectorialAndaluciae.getId(), sectorialSevillae.getDireccionSectorialSuperior().getId());
assertEquals(1, sectorialAndaluciav.getOrganosSectorialesDependientes().size());
}
}<file_sep>package repositories;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import com.juventudes.gestor.entities.Militante;
public interface MilitanteRepository extends JpaRepository<Militante, Integer> {
Optional<List<Militante>> findByNombre (String nombre);
}
<file_sep>package com.juventudes.gestor.entities;
import java.io.Serializable;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Embeddable
public class MilitanteFormacionPK implements Serializable {
private static final long serialVersionUID = 1L;
@Column(name = "id_militante")
private int idMilitante;
@Column(name = "id_formacion")
private int idFormacion;
@Column(name = "fechaformacion")
private LocalDate fecha;
public MilitanteFormacionPK() {
}
public MilitanteFormacionPK(int idMilitante, int idFormacion) {
this(idMilitante, idFormacion, LocalDate.now());
}
public MilitanteFormacionPK(int idMilitante, int idFormacion, LocalDate fecha) {
super();
this.idMilitante = idMilitante;
this.idFormacion = idFormacion;
this.fecha = fecha;
}
public int getIdMilitante() {
return this.idMilitante;
}
public void setIdMilitante(int idMilitante) {
this.idMilitante = idMilitante;
}
public int getIdFormacion() {
return this.idFormacion;
}
public void setIdFormacion(int idFormacion) {
this.idFormacion = idFormacion;
}
public LocalDate getFecha() {
return fecha;
}
public void setFecha(LocalDate fecha) {
this.fecha = fecha;
}
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof MilitanteFormacionPK)) {
return false;
}
MilitanteFormacionPK castOther = (MilitanteFormacionPK) other;
return (this.idMilitante == castOther.getIdMilitante()) && (this.idFormacion == castOther.getIdFormacion())
&& (this.fecha.equals(castOther.getFecha()));
}
public int hashCode() {
final int prime = 31;
int hash = 17;
hash = hash * prime + this.idMilitante;
return hash;
}
}<file_sep>package entitiesgenerators;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.springframework.util.ResourceUtils;
import com.juventudes.gestor.entities.Militante;
public class MilitanteGenerator {
public static List<Militante> createMilitantes(int num_militanes) {
List<Militante> militantes = new ArrayList<Militante>();
List<String> randomNombres = getRandomNombre(num_militanes);
for (int i = 0; i < num_militanes; i++) {
Militante militante = new Militante().setNombre(randomNombres.get(i));
militante.setFechaIngreso(LocalDate.now());
militantes.add(militante);
}
return militantes;
}
private static List<String> getRandomNombre(int num){
//Cargamos todos los nombres en un array
ArrayList<String> names = new ArrayList<>();
try (BufferedReader br = new BufferedReader(
new FileReader(ResourceUtils.getFile("src/test/resources/listas/nombres.txt")))){
String line;
while((line = br.readLine()) != null)
names.add(line);
} catch (IOException e1) {
e1.printStackTrace();
}
//Seleccionamos al azar los nombres y los cargamos en la lista de retorno
List<String> randomNames = new ArrayList<>();
for (int i = 0; i<num; i++) {
Random random = new Random();
int randomNumber = random.nextInt(names.size());
randomNames.add(names.get(randomNumber));
}
return randomNames;
}
}
<file_sep>package com.juventudes.gestor.entities;
import java.io.Serializable;
import javax.persistence.*;
/**
* The persistent class for the traslado database table.
*
*/
@Entity
@Table(name="traslados")
@NamedQuery(name="Traslado.findAll", query="SELECT t FROM Traslado t")
public class Traslado implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
private TrasladoPK id;
@Column(name="motivo_traslado", length=1)
private String motivoTraslado;
@ManyToOne
@JoinColumn(name="colectivo_destino", nullable=false)
private Colectivo colectivo1;
@ManyToOne
@JoinColumn(name="colectivo_origen", nullable=false)
private Colectivo colectivo2;
@ManyToOne
@JoinColumn(name="id_militante", nullable=false, insertable=false, updatable=false)
private Militante militante;
public Traslado() {
}
public TrasladoPK getId() {
return this.id;
}
public void setId(TrasladoPK id) {
this.id = id;
}
public String getMotivoTraslado() {
return this.motivoTraslado;
}
public void setMotivoTraslado(String motivoTraslado) {
this.motivoTraslado = motivoTraslado;
}
public Colectivo getColectivo1() {
return this.colectivo1;
}
public void setColectivo1(Colectivo colectivo1) {
this.colectivo1 = colectivo1;
}
public Colectivo getColectivo2() {
return this.colectivo2;
}
public void setColectivo2(Colectivo colectivo2) {
this.colectivo2 = colectivo2;
}
public Militante getMilitante() {
return this.militante;
}
public void setMilitante(Militante militante) {
this.militante = militante;
}
}<file_sep>package repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import com.juventudes.gestor.entities.MilitanteIdioma;
public interface MilitanteIdiomaRepository extends JpaRepository<MilitanteIdioma, Integer> {
}
<file_sep>package com.juventudes.gestor.entities;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name="poblaciones")
public class Poblacion implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(unique=true, nullable=false)
private int id;
@Column(nullable=false, length=90)
private String nombre;
@Column(nullable=false)
private int postal;
@OneToMany(mappedBy="poblacion")
private List<Empleo> empleos;
@OneToMany(mappedBy="poblacion")
private List<Estudio> estudios;
@OneToMany(mappedBy="poblacion")
private List<Militante> militantes;
@ManyToOne
@JoinColumn(name="id_provincia", nullable=false)
private Provincia provincia;
public Poblacion() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getNombrePoblacion() {
return this.nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public int getPostal() {
return this.postal;
}
public void setPostal(int postal) {
this.postal = postal;
}
public List<Empleo> getEmpleos() {
return this.empleos;
}
public List<Estudio> getEstudios() {
return this.estudios;
}
public List<Militante> getMilitantes() {
return this.militantes;
}
public void setMilitantes(List<Militante> militantes) {
this.militantes = militantes;
}
public Provincia getProvincia() {
return this.provincia;
}
public void setProvincia(Provincia provincia) {
this.provincia = provincia;
}
}<file_sep>package com.juventudes.gestor.entities;
import java.io.Serializable;
import javax.persistence.*;
@Embeddable
public class ResponsabilidadPK implements Serializable {
private static final long serialVersionUID = 1L;
@Column(name="id_organo", insertable=false, updatable=false, nullable=false)
private int idOrgano;
@Column(name="id_tipo_reponsabilidad", insertable=false, updatable=false, nullable=false)
private int idTipoReponsabilidad;
public ResponsabilidadPK() {
}
public int getIdOrgano() {
return this.idOrgano;
}
public void setIdOrgano(int idOrgano) {
this.idOrgano = idOrgano;
}
public int getIdTipoReponsabilidad() {
return this.idTipoReponsabilidad;
}
public void setIdTipoReponsabilidad(int idTipoReponsabilidad) {
this.idTipoReponsabilidad = idTipoReponsabilidad;
}
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof ResponsabilidadPK)) {
return false;
}
ResponsabilidadPK castOther = (ResponsabilidadPK)other;
return
(this.idOrgano == castOther.idOrgano)
&& (this.idTipoReponsabilidad == castOther.idTipoReponsabilidad);
}
public int hashCode() {
final int prime = 31;
int hash = 17;
hash = hash * prime + this.idOrgano;
hash = hash * prime + this.idTipoReponsabilidad;
return hash;
}
}<file_sep>package com.juventudes.gestor.entities;
import java.io.Serializable;
import java.time.LocalDate;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name="militante_formaciones")
public class MilitanteFormacion implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
private MilitanteFormacionPK id;
@Column(name="capaz_impartir", nullable=false)
private boolean capazImpartir;
@ManyToOne
@JoinColumn(name="id_formacion", unique = false, nullable=false, insertable=false, updatable=false)
private Formacion formacion;
@ManyToOne
@JoinColumn(name="id_militante", unique = false, nullable=false, insertable=false, updatable=false)
private Militante militante;
public MilitanteFormacion(){
}
public MilitanteFormacion(Formacion formacion, Militante militante) {
id = new MilitanteFormacionPK(militante.getId(), formacion.getId());
}
public MilitanteFormacion(Formacion formacion, Militante militante, LocalDate localDate) {
id = new MilitanteFormacionPK(militante.getId(), formacion.getId(), localDate);
}
public MilitanteFormacionPK getId() {
return this.id;
}
public void setId(MilitanteFormacionPK id) {
this.id = id;
}
public boolean getCapazImpartir() {
return this.capazImpartir;
}
public void setCapazImpartir(boolean capazImpartir) {
this.capazImpartir = capazImpartir;
}
public Formacion getFormacion() {
return this.formacion;
}
public void setFormacion(Formacion formacion) {
this.formacion = formacion;
}
public Militante getMilitante() {
return this.militante;
}
public void setMilitante(Militante militante) {
this.militante = militante;
}
}<file_sep># ormdatabase
Source code from jar
<file_sep>package integration;
import static org.junit.Assert.assertEquals;
import java.time.LocalDate;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.test.annotation.Commit;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import context.TestContextConfig;
import com.juventudes.gestor.entities.ConocimientoTIC;
import com.juventudes.gestor.entities.Empleo;
import com.juventudes.gestor.entities.Estudio;
import com.juventudes.gestor.entities.Idioma;
import com.juventudes.gestor.entities.Militante;
import com.juventudes.gestor.entities.Poblacion;
import com.juventudes.gestor.entities.Provincia;
import com.juventudes.gestor.mysc.Contrato;
import com.juventudes.gestor.mysc.Nivel;
import repositories.EstudioRepository;
import repositories.IdiomaRepository;
import repositories.MilitanteRepository;
import repositories.PoblacionRepository;
import repositories.ProvinciaRepository;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = TestContextConfig.class)
@EnableJpaRepositories(basePackages = "repositories")
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@ActiveProfiles("test")
public class JpaIntegrationMilitanteDatosPersonalesTest {
@Autowired
MilitanteRepository militanteRepo;
@Autowired
ProvinciaRepository provinciaRepo;
@Autowired
IdiomaRepository idiomaRepo;
@Autowired
PoblacionRepository poblacionRepo;
@Autowired
EstudioRepository estudioRepo;
private static ConocimientoTIC conocimientoTIC1, conocimientoTIC2;
private static Militante militante;
private static Estudio estudio1;
private static Empleo empleo1;
private static Idioma idioma1;
private static Poblacion poblacion1;
private static Provincia provincia1;
@BeforeClass
public static void beforeClass() {
// ==============DATOSPERSONALES=====================
militante = new Militante().setNombre("Neuer");
militante.setFechaNacimiento(LocalDate.of(1992, 9, 18));
// ====POBLACION & PROVINCIA======================
poblacion1 = new Poblacion();
provincia1 = new Provincia();
poblacion1.setId(1);
poblacion1.setNombre("Bertamiráns");
provincia1.setId(1);
provincia1.setNombre("<NAME>");
poblacion1.setProvincia(provincia1);
// ====ESTUDIOS===============
estudio1 = new Estudio();
estudio1.setEstudiosActuales("Ingeniería Química");
estudio1.setPoblacion(poblacion1);
// ====EMPLEO==================
empleo1 = new Empleo();
empleo1.setCentroTrabajo("Tecnicolor S.A.");
empleo1.setPoblacion(poblacion1);
empleo1.setTipoContrato(Contrato.INDEFINIDO);
// ====IDIOMA================
idioma1 = new Idioma("Inglés");
// =======CONOCIMIENTO_TIC======
conocimientoTIC1 = new ConocimientoTIC("Diseño web", "Capacidad para crear páginas bien formadas");
conocimientoTIC2 = new ConocimientoTIC("Otra cosa");
}
@Test
public void A_insertions() {
militanteRepo.saveAndFlush(militante);
provinciaRepo.save(provincia1);
poblacionRepo.save(poblacion1);
idiomaRepo.saveAndFlush(idioma1);
}
@Test
@Commit
@Transactional
public void B_insertDatosMilitante() {
Militante militante = militanteRepo.findByNombre("Neuer").get().get(0);
// EMPLEO
militante.addEmpleo(empleo1);
// POBLACION
militante.setPoblacion(poblacion1);
// ESTUDIO
militante.setEstudio(estudio1);
// IDIOMAS
militante.addIdioma(idioma1, Nivel.BAJO);
// CONOCIMIENTOS TIC
militante.addConocimientoTics(conocimientoTIC1);
militante.addConocimientoTics(conocimientoTIC2);
// VARIOS
militante.setCarnetConducir(true);
}
@Test
@Commit
@Transactional
public void C_assertDatosMilitante() {
Militante militantenew = militanteRepo.findByNombre("Neuer").get().get(0);
assertEquals(LocalDate.of(1992, 9, 18), militante.getFechaNacimiento());
assertEquals(true, militantenew.getCarnetConducir());
assertEquals("Bertamiráns", militantenew.getEstudio().getPoblacion().getNombrePoblacion());
assertEquals(1, militantenew.getEmpleos().size());
assertEquals(1, militantenew.getPoblacion().getProvincia().getId());
assertEquals(2, militantenew.getConocimientoTics().size());
assertEquals(1, militantenew.getIdiomas().size());
}
@Test
@Commit
@Transactional
public void D_testingCascadeIdioma() {
Militante militantenew = militanteRepo.findByNombre("Neuer").get().get(0);
militantenew.removeIdioma(idioma1);
assertEquals(0, militantenew.getIdiomas().size());
}
@Test
@Commit
@Transactional
public void E_testingCascadeConocimientosTIC() {
Militante militantenew = militanteRepo.findByNombre("Neuer").get().get(0);
Militante militantenew2 = militantenew;
militantenew2.removeConocimientoTics(conocimientoTIC2);
assertEquals(1, militantenew2.getConocimientoTics().size());
}
}<file_sep>package repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import com.juventudes.gestor.entities.ConocimientoTIC;
public interface ConocimientoTICRepository extends JpaRepository<ConocimientoTIC, Integer> {
}
<file_sep>package com.juventudes.gestor.entities;
import java.io.Serializable;
import java.time.LocalDate;
import javax.persistence.Column;
import javax.persistence.Embeddable;
@Embeddable
public class TrasladoPK implements Serializable {
private static final long serialVersionUID = 1L;
@Column(name="id_militante", insertable=false, updatable=false, unique=true, nullable=false)
private int idMilitante;
@Column(name="fecha_peticion_traslado", unique=true, nullable=false)
private LocalDate fechaPeticionTraslado;
public TrasladoPK() {
}
public int getIdMilitante() {
return this.idMilitante;
}
public void setIdMilitante(int idMilitante) {
this.idMilitante = idMilitante;
}
public LocalDate getFechaPeticionTraslado() {
return this.fechaPeticionTraslado;
}
public void setFechaPeticionTraslado(LocalDate fechaPeticionTraslado) {
this.fechaPeticionTraslado = fechaPeticionTraslado;
}
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof TrasladoPK)) {
return false;
}
TrasladoPK castOther = (TrasladoPK)other;
return
(this.idMilitante == castOther.idMilitante)
&& this.fechaPeticionTraslado.equals(castOther.fechaPeticionTraslado);
}
public int hashCode() {
final int prime = 31;
int hash = 17;
hash = hash * prime + this.idMilitante;
hash = hash * prime + this.fechaPeticionTraslado.hashCode();
return hash;
}
}<file_sep>package com.juventudes.gestor.entities;
import java.io.Serializable;
import java.time.LocalDate;
import javax.persistence.Column;
import javax.persistence.Embeddable;
@Embeddable
public class EmpleoPK implements Serializable {
private static final long serialVersionUID = 1L;
@Column(name="id_militante", insertable=false, updatable=false, unique=true, nullable=false)
private int idMilitante;
@Column(name="fecha_inicio", unique=true, nullable=false)
private LocalDate fechaInicio;
public EmpleoPK() {
}
public EmpleoPK(int idMilitante, LocalDate fechaInicio) {
super();
this.idMilitante = idMilitante;
this.fechaInicio = fechaInicio;
}
public int getIdMilitante() {
return this.idMilitante;
}
public void setIdMilitante(int idMilitante) {
this.idMilitante = idMilitante;
}
public LocalDate getFechaInicio() {
return this.fechaInicio;
}
public void setFechaInicio(LocalDate fechaInicio) {
this.fechaInicio = fechaInicio;
}
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof EmpleoPK)) {
return false;
}
EmpleoPK castOther = (EmpleoPK)other;
return
(this.idMilitante == castOther.idMilitante)
&& this.fechaInicio.equals(castOther.fechaInicio);
}
public int hashCode() {
final int prime = 31;
int hash = 17;
hash = hash * prime + this.idMilitante;
return hash;
}
}<file_sep>package integration;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import javax.transaction.Transactional;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.test.annotation.Commit;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import com.juventudes.gestor.entities.FrenteIntervencion;
import com.juventudes.gestor.entities.Militante;
import com.juventudes.gestor.entities.TipoFrente;
import context.TestContextConfig;
import entitiesgenerators.MilitanteGenerator;
import repositories.FrenteIntervencionRepository;
import repositories.MilitanteRepository;
import repositories.TipoFrenteRepository;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = TestContextConfig.class)
@EnableJpaRepositories(basePackages = "repositories")
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@ActiveProfiles("test")
public class JpaIntegrationFrentesIntervencionTest {
@Autowired
private MilitanteRepository militanteRepo;
@Autowired
private TipoFrenteRepository tipoFrenteRepo;
@Autowired
private FrenteIntervencionRepository frenteIntervencionRepo;
private static List<TipoFrente> tiposFrente = new ArrayList<>();
private static List<FrenteIntervencion> frentes = new ArrayList<>();
private static List<Militante> militantes = new ArrayList<>();
@BeforeClass
public static void beforeClass() {
// ========================TIPO FRENTE=====================
tiposFrente.add(new TipoFrente("Vecinal"));
tiposFrente.add(new TipoFrente("Estudiantil"));
// ==================FRENTES DE INTERVENCION=====================
frentes.add(new FrenteIntervencion("Marchas de la Dignidad", tiposFrente.get(0)));
frentes.add(new FrenteIntervencion("Accion Universitaria", tiposFrente.get(1)));
// =========================MILITANTES========================
militantes = MilitanteGenerator.createMilitantes(3);
}
@Test
public void A_assertProperlyInsertedt() {
tipoFrenteRepo.saveAll(tiposFrente);
frenteIntervencionRepo.saveAll(frentes);
militanteRepo.saveAll(militantes);
assertEquals(2, tipoFrenteRepo.count());
assertEquals(2, frenteIntervencionRepo.count());
assertEquals(3, militanteRepo.count());
}
@Test
@Transactional
@Commit
public void B_linkMilitanteFrenteIntervecion() {
Militante militante = militanteRepo.findById(1).get();
assertEquals(2, frentes.size());
militante.addFrenteIntervencion(frentes.get(0));
assertEquals(1, militante.getFrentesIntervencion().size());
}
}
<file_sep>package com.juventudes.gestor.mysc;
public enum Nivel {
ALTO, MEDIO, BAJO
}
<file_sep>package repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import com.juventudes.gestor.entities.MilitanteFormacion;
public interface MilitanteFormacionRepository extends JpaRepository<MilitanteFormacion, Integer> {
}
<file_sep>package com.juventudes.gestor.entities;
import java.io.Serializable;
import javax.persistence.*;
import java.util.List;
/**
* The persistent class for the tematica_escuela database table.
*
*/
@Entity
@Table(name="tematicas_escuela")
@NamedQuery(name="TematicaEscuela.findAll", query="SELECT t FROM TematicaEscuela t")
public class TematicaEscuela implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(unique=true, nullable=false)
private int id;
@Column(nullable=false, length=50)
private String nombre;
//bi-directional many-to-one association to Escuela
@OneToMany(mappedBy="tematicaEscuela")
private List<Escuela> escuelas;
public TematicaEscuela() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getNombre() {
return this.nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public List<Escuela> getEscuelas() {
return this.escuelas;
}
public void setEscuelas(List<Escuela> escuelas) {
this.escuelas = escuelas;
}
public Escuela addEscuela(Escuela escuela) {
getEscuelas().add(escuela);
escuela.setTematicaEscuela(this);
return escuela;
}
public Escuela removeEscuela(Escuela escuela) {
getEscuelas().remove(escuela);
escuela.setTematicaEscuela(null);
return escuela;
}
}<file_sep>package com.juventudes.gestor.entities;
import java.util.List;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import com.juventudes.gestor.mysc.Nivel;
@Entity
@Table(name = "formaciones")
public class Formacion{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(unique = true, nullable = false)
private int id;
@Enumerated(EnumType.STRING)
private Nivel nivel;
@Column(nullable = false, length = 50)
private String titulo;
@ManyToMany(mappedBy = "formaciones")
@Cascade(CascadeType.SAVE_UPDATE)
private Set<Escuela> escuelas;
@OneToMany(mappedBy = "formacion")
private List<MilitanteFormacion> militanteFormaciones;
public Formacion() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public Nivel getNivel() {
return this.nivel;
}
public void setNivel(Nivel nivel) {
this.nivel = nivel;
}
public String getTitulo() {
return this.titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public Set<Escuela> getEscuelas() {
return this.escuelas;
}
public void setEscuelas(Set<Escuela> escuelas) {
this.escuelas = escuelas;
}
public List<MilitanteFormacion> getMilitanteFormacions() {
return this.militanteFormaciones;
}
public void setMilitanteFormaciones(List<MilitanteFormacion> militanteFormacions) {
this.militanteFormaciones = militanteFormacions;
}
public MilitanteFormacion addMilitanteFormacion(MilitanteFormacion militanteFormacion) {
getMilitanteFormacions().add(militanteFormacion);
militanteFormacion.setFormacion(this);
return militanteFormacion;
}
public MilitanteFormacion removeMilitanteFormacion(MilitanteFormacion militanteFormacion) {
getMilitanteFormacions().remove(militanteFormacion);
militanteFormacion.setFormacion(null);
return militanteFormacion;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Formacion) {
Formacion f = (Formacion) obj;
return (f.getTitulo().equals(this.titulo) && f.getNivel().equals(this.nivel));
} else
return false;
}
@Override
public int hashCode() {
return this.titulo.hashCode();
}
@Override
public String toString() {
return getTitulo() + "--> Nivel: " + getNivel();
}
}<file_sep>package repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import com.juventudes.gestor.entities.Idioma;
public interface IdiomaRepository extends JpaRepository<Idioma, Integer> {
}
<file_sep>package com.juventudes.gestor.entities;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name="frentes_intervencion")
public class FrenteIntervencion {
@Id
@GeneratedValue
@Column(unique=true, nullable=false)
private int id;
@Column(nullable=false, length=30)
private String nombre;
@ManyToOne
@JoinColumn(name="tipo")
private TipoFrente tipoFrente;
@OneToMany(mappedBy="frenteIntervencion")
private List<MilitanteFrenteIntervencion> militantesFrentesIntervenciones;
public FrenteIntervencion() {
}
public FrenteIntervencion(String nombre, TipoFrente tipoFrente) {
this.nombre = nombre;
this.tipoFrente = tipoFrente;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getNombre() {
return this.nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public TipoFrente getTipoFrente() {
return this.tipoFrente;
}
public void setTipoFrente(TipoFrente tipoFrente) {
this.tipoFrente = tipoFrente;
}
public List<MilitanteFrenteIntervencion> getMilitantesFrentesIntervenciones() {
return this.militantesFrentesIntervenciones;
}
public void setMilitanteFrentesIntervencions(List<MilitanteFrenteIntervencion> militantesFrentesIntervenciones) {
this.militantesFrentesIntervenciones = militantesFrentesIntervenciones;
}
public MilitanteFrenteIntervencion addMilitantesFrentesIntervencion(MilitanteFrenteIntervencion militanteFrenteIntervencion) {
getMilitantesFrentesIntervenciones().add(militanteFrenteIntervencion);
militanteFrenteIntervencion.setFrenteIntervencion(this);
return militanteFrenteIntervencion;
}
public MilitanteFrenteIntervencion removeMilitantesFrentesIntervencion(MilitanteFrenteIntervencion militanteFrenteIntervencion) {
getMilitantesFrentesIntervenciones().remove(militanteFrenteIntervencion);
militanteFrenteIntervencion.setFrenteIntervencion(null);
return militanteFrenteIntervencion;
}
}<file_sep>package com.juventudes.gestor.entities;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import com.juventudes.gestor.mysc.Nivel;
@Entity
@Table(name = "militantes")
public class Militante {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(unique = true, nullable = false)
private int id;
@Column(length = 30)
private String nombre;
@Column(length = 30)
private String apellido1;
@Column(length = 30)
private String apellido2;
@Column(name = "carnet_conducir")
private boolean carnetConducir;
@Column(length = 1)
private String compromiso;
@Column(length = 100)
private String direccion;
@Column(name = "dni_nie", length = 10)
private String dniNie;
@Column(length = 50)
private String email;
@Column(name = "fecha_baja")
private LocalDate fechaBaja;
@Column(name = "fecha_ingreso")
private LocalDate fechaIngreso;
@Column(name = "fecha_militancia")
private LocalDate fechaMilitancia;
@Column(name = "fecha_nacimiento")
private LocalDate fechaNacimiento;
@Column(length = 1)
private String genero;
@Column(name = "motivo_baja", length = 1)
private String motivoBaja;
@Column(length = 9)
private String telefono;
@Column(name = "tipo_cuota", length = 1)
private String tipoCuota;
@Column(name = "tipo_pago")
private byte tipoPago;
@Column(length = 1)
private String vehiculo;
@OneToOne(mappedBy = "militante")
@Cascade(CascadeType.ALL)
private DatosBancarios datosBancario;
@OneToMany(mappedBy = "militante", orphanRemoval = true)
@Cascade(CascadeType.ALL)
private List<Empleo> empleos = new ArrayList<>();
@OneToOne(fetch = FetchType.LAZY)
@Cascade(CascadeType.ALL)
@PrimaryKeyJoinColumn
private Estudio estudio;
@ManyToMany(mappedBy = "militantes")
@Cascade(CascadeType.ALL)
private Set<Organo> organos = new HashSet<Organo>();
@ManyToMany
@Cascade(CascadeType.ALL)
@JoinTable(name = "militante_conocimientoTIC", joinColumns = {
@JoinColumn(name = "id_militante", nullable = false) }, inverseJoinColumns = {
@JoinColumn(name = "id_conocimientotic", nullable = false) })
private Set<ConocimientoTIC> conocimientoTics = new HashSet<>();
@Cascade(CascadeType.SAVE_UPDATE)
@ManyToMany(mappedBy = "militantes")
private List<Escuela> escuelas;
@OneToMany(mappedBy = "militante", orphanRemoval = true)
@Cascade(CascadeType.SAVE_UPDATE)
private List<MilitanteFormacion> formaciones;
@OneToMany(mappedBy = "militante", orphanRemoval = true)
@Cascade(CascadeType.ALL)
private Set<MilitanteFrenteIntervencion> frentes;
@ManyToOne
@JoinColumn(name = "municipio_residencia")
private Poblacion poblacion;
@OneToMany(mappedBy = "militante", orphanRemoval = true)
@Cascade(CascadeType.ALL)
private List<MilitanteIdioma> idiomas;
@OneToMany(mappedBy = "militante", orphanRemoval = true)
private List<Responsabilidad> responsabilidades;
@OneToMany(mappedBy = "militante")
private List<Traslado> traslados;
@OneToOne(mappedBy = "militante", fetch = FetchType.LAZY)
@Cascade(CascadeType.ALL)
private Usuario usuario;
public Militante() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getApellido1() {
return this.apellido1;
}
public void setApellido1(String apellido1) {
this.apellido1 = apellido1;
}
public String getApellido2() {
return this.apellido2;
}
public void setApellido2(String apellido2) {
this.apellido2 = apellido2;
}
public boolean getCarnetConducir() {
return carnetConducir;
}
public void setCarnetConducir(boolean carnetConducir) {
this.carnetConducir = carnetConducir;
}
public String getCompromiso() {
return this.compromiso;
}
public void setCompromiso(String compromiso) {
this.compromiso = compromiso;
}
public String getDireccion() {
return this.direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
public String getDniNie() {
return this.dniNie;
}
public void setDniNie(String dniNie) {
this.dniNie = dniNie;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public LocalDate getFechaBaja() {
return this.fechaBaja;
}
public void setFechaBaja(LocalDate fechaBaja) {
this.fechaBaja = fechaBaja;
}
public LocalDate getFechaIngreso() {
return this.fechaIngreso;
}
public void setFechaIngreso(LocalDate fechaIngreso) {
this.fechaIngreso = fechaIngreso;
}
public LocalDate getFechaMilitancia() {
return this.fechaMilitancia;
}
public void setFechaMilitancia(LocalDate fechaMilitancia) {
this.fechaMilitancia = fechaMilitancia;
}
public LocalDate getFechaNacimiento() {
return this.fechaNacimiento;
}
public void setFechaNacimiento(LocalDate fechaNacimiento) {
this.fechaNacimiento = fechaNacimiento;
}
public String getGenero() {
return this.genero;
}
public void setGenero(String genero) {
this.genero = genero;
}
public String getMotivoBaja() {
return this.motivoBaja;
}
public void setMotivoBaja(String motivoBaja) {
this.motivoBaja = motivoBaja;
}
public String getNombre() {
return this.nombre;
}
public Militante setNombre(String nombre) {
this.nombre = nombre;
return this;
}
public String getTelefono() {
return this.telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public String getTipoCuota() {
return this.tipoCuota;
}
public void setTipoCuota(String tipoCuota) {
this.tipoCuota = tipoCuota;
}
public byte getTipoPago() {
return this.tipoPago;
}
public void setTipoPago(byte tipoPago) {
this.tipoPago = tipoPago;
}
public String getVehiculo() {
return this.vehiculo;
}
public void setVehiculo(String vehiculo) {
this.vehiculo = vehiculo;
}
public DatosBancarios getDatosBancario() {
return this.datosBancario;
}
public void setDatosBancario(DatosBancarios datosBancario) {
this.datosBancario = datosBancario;
}
public List<Empleo> getEmpleos() {
return this.empleos;
}
public void setEmpleos(List<Empleo> empleos) {
this.empleos = empleos;
}
public Empleo addEmpleo(Empleo empleo) {
empleo.setId(new EmpleoPK(this.id, LocalDate.now()));
getEmpleos().add(empleo);
empleo.setMilitante(this);
return empleo;
}
public Empleo removeEmpleo(Empleo empleo) {
getEmpleos().remove(empleo);
empleo.setMilitante(null);
return empleo;
}
public Estudio getEstudio() {
return this.estudio;
}
public void setEstudio(Estudio estudio) {
estudio.setMilitante(this);
this.estudio = estudio;
}
public Set<ConocimientoTIC> getConocimientoTics() {
return this.conocimientoTics;
}
public void setConocimientoTics(Set<ConocimientoTIC> conocimientoTics) {
this.conocimientoTics = conocimientoTics;
}
public boolean addConocimientoTics(ConocimientoTIC conocimientoTics) {
conocimientoTics.addMilitante(this);
return getConocimientoTics().add(conocimientoTics);
}
public boolean removeConocimientoTics(ConocimientoTIC conocimientoTics) {
return getConocimientoTics().remove(conocimientoTics);
}
public List<Escuela> getEscuelas() {
return this.escuelas;
}
public void setEscuelas(List<Escuela> escuelas) {
this.escuelas = escuelas;
}
public Poblacion getPoblacion() {
return this.poblacion;
}
public void setPoblacion(Poblacion poblacion) {
this.poblacion = poblacion;
}
public List<MilitanteIdioma> getIdiomas() {
return idiomas;
}
public void setMilitanteIdiomas(List<MilitanteIdioma> militanteIdiomas) {
this.idiomas = militanteIdiomas;
}
public void addIdioma(Idioma idioma) {
addIdioma(idioma, Nivel.MEDIO);
}
public void addIdioma(Idioma idioma, Nivel nivel) {
MilitanteIdioma militanteIdioma = new MilitanteIdioma();
militanteIdioma.setId(new MilitanteIdiomaPK(this.id, idioma.getId()));
militanteIdioma.setNivel(nivel);
getIdiomas().add(militanteIdioma);
}
public void removeIdioma(Idioma idioma) {
MilitanteIdioma idiomar = null;
for (MilitanteIdioma i : getIdiomas()) {
if (i.getIdioma().equals(idioma)) {
idiomar = i;
break;
}
}
getIdiomas().remove(idiomar);
}
public Set<Organo> getOrganos() {
return this.organos;
}
void setOrganos(Set<Organo> organos) {
this.organos = organos;
}
void addOrgano(Organo organo) {
getOrganos().add(organo);
}
void removeOrgano(Organo organo) {
getOrganos().remove(organo);
}
public List<Responsabilidad> getResponsabilidades() {
return this.responsabilidades;
}
public void setResponsabilidads(List<Responsabilidad> responsabilidads) {
this.responsabilidades = responsabilidads;
}
public Responsabilidad addResponsabilidad(Responsabilidad responsabilidad) {
responsabilidad.setMilitante(this);
getResponsabilidades().add(responsabilidad);
responsabilidad.setMilitante(this);
return responsabilidad;
}
public Responsabilidad removeResponsabilidad(Responsabilidad responsabilidad) {
getResponsabilidades().remove(responsabilidad);
responsabilidad.setMilitante(null);
return responsabilidad;
}
public List<Traslado> getTraslados() {
return this.traslados;
}
public void setTraslados(List<Traslado> traslados) {
this.traslados = traslados;
}
public Traslado addTraslado(Traslado traslado) {
getTraslados().add(traslado);
traslado.setMilitante(this);
return traslado;
}
public Traslado removeTraslado(Traslado traslado) {
getTraslados().remove(traslado);
traslado.setMilitante(null);
return traslado;
}
public Usuario getUsuario() {
return this.usuario;
}
public void setUsuarios(Usuario usuarios) {
this.usuario = usuarios;
}
public List<MilitanteFormacion> getFormaciones() {
return formaciones;
}
public MilitanteFormacion addFormacion(Formacion f) {
return addFormacion(f, LocalDate.now());
}
public MilitanteFormacion addFormacion(Formacion f, LocalDate fecha) {
return addFormacion(f, fecha, false);
}
public MilitanteFormacion addFormacion(Formacion f, LocalDate fecha, boolean capaz_impartir) {
MilitanteFormacion lineaFormacion = new MilitanteFormacion(f, this);
lineaFormacion.setCapazImpartir(false);
f.addMilitanteFormacion(lineaFormacion);
return lineaFormacion;
}
public List<MilitanteFormacion> removeFormacion(MilitanteFormacion f) {
getFormaciones().removeIf((mf) -> mf.equals(f));
return getFormaciones();
}
private Set<MilitanteFrenteIntervencion> getMilitanteFrentesIntervencion() {
return frentes;
}
public Set<FrenteIntervencion> getFrentesIntervencion() {
Set<FrenteIntervencion> hs = new HashSet<>();
for (MilitanteFrenteIntervencion mfi : getMilitanteFrentesIntervencion()) {
hs.add(mfi.getFrenteIntervencion());
}
return hs;
}
public void addFrenteIntervencion(FrenteIntervencion frente) {
addFrenteIntervencion(frente, false, "");
}
public void addFrenteIntervencion(FrenteIntervencion frente, boolean prioritario, String responsabilidad) {
MilitanteFrenteIntervencion militanteFrenteIntervencion = new MilitanteFrenteIntervencion(this.id, frente,
prioritario, responsabilidad);
getMilitanteFrentesIntervencion().add(militanteFrenteIntervencion);
}
public void removeFrenteIntervencion(MilitanteFrenteIntervencion f) {
getMilitanteFrentesIntervencion().removeIf((fi) -> fi.equals(f));
}
@Override
public int hashCode() {
final int prime = 31;
return prime * id;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Militante))
return false;
Militante other = (Militante) obj;
if (id != other.id)
return false;
return true;
}
}<file_sep>package com.juventudes.gestor.entities;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class Organo {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(unique = true)
private int id;
private boolean activo;
@Column(name = "convocatoria_email")
private boolean convocatoriaEmail;
@Column(unique = true, length = 100)
private String nombre;
@Column(name = "periodicidad_reuniones", length = 1)
private String periodicidadReuniones;
@Column(name = "uso_calendar")
private boolean usoCalendar;
@Column(name = "uso_drive")
private boolean usoDrive;
@ManyToMany
@JoinTable(name = "organo_militantes",
joinColumns = @JoinColumn(name = "id_organo", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "id_militante", referencedColumnName = "id"))
private Set<Militante> militantes = new HashSet<Militante>();
@OneToMany(mappedBy = "organo")
private List<Responsabilidad> responsabilidades;
@OneToMany(mappedBy = "organo_realizador")
private List<Escuela> escuelas;
public Organo() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public Set<Militante> getMilitantes() {
return this.militantes;
}
public void setMilitantes(Set<Militante> militantes) {
this.militantes = militantes;
}
public void addMilitante(Militante militante) {
getMilitantes().add(militante);
militante.addOrgano(this);
}
public boolean getActivo() {
return this.activo;
}
public void setActivo(boolean activo) {
this.activo = activo;
}
public boolean getConvocatoriaEmail() {
return this.convocatoriaEmail;
}
public void setConvocatoriaEmail(boolean convocatoriaEmail) {
this.convocatoriaEmail = convocatoriaEmail;
}
public String getNombre() {
return this.nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getPeriodicidadReuniones() {
return this.periodicidadReuniones;
}
public void setPeriodicidadReuniones(String periodicidadReuniones) {
this.periodicidadReuniones = periodicidadReuniones;
}
public boolean getUsoCalendar() {
return this.usoCalendar;
}
public void setUsoCalendar(boolean usoCalendar) {
this.usoCalendar = usoCalendar;
}
public boolean getUsoDrive() {
return this.usoDrive;
}
public void setUsoDrive(boolean usoDrive) {
this.usoDrive = usoDrive;
}
public List<Responsabilidad> getResponsabilidades() {
return this.responsabilidades;
}
public void setResponsabilidades(List<Responsabilidad> responsabilidades) {
this.responsabilidades = responsabilidades;
}
public Responsabilidad addResponsabilidad(Responsabilidad responsabilidad) {
getResponsabilidades().add(responsabilidad);
responsabilidad.setOrgano(this);
return responsabilidad;
}
public Responsabilidad removeResponsabilidad(Responsabilidad responsabilidad) {
getResponsabilidades().remove(responsabilidad);
responsabilidad.setOrgano(null);
return responsabilidad;
}
public List<Escuela> getEscuelasOrganizadas() {
return escuelas;
}
public void setEscuelasOrganizadas(List<Escuela> escuelas) {
this.escuelas = escuelas;
}
public void addEscuelaOrganizada(Escuela escuela) {
getEscuelasOrganizadas().add(escuela);
escuela.setOrganoOrganizador(this);
}
public void removeEscuelaOrganizada(Escuela escuela) {
getEscuelasOrganizadas().remove(escuela);
escuela.setOrganoOrganizador(null);
}
}
<file_sep>package com.juventudes.gestor.entities;
import java.io.Serializable;
import javax.persistence.*;
@Entity
@Table(name="militantes_frentes_intervencion")
public class MilitanteFrenteIntervencion implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
private MilitanteFrenteIntervencionPK id;
@Column
private boolean prioritario;
@Column(length=30)
private String responsabilidad;
@ManyToOne
@JoinColumn(name="id_frente", unique=false, nullable=false, insertable=false, updatable=false)
private FrenteIntervencion frenteIntervencion;
@ManyToOne
@JoinColumn(name="id_militante", unique=false, nullable=false, insertable=false, updatable=false)
private Militante militante;
public MilitanteFrenteIntervencion() {
}
public MilitanteFrenteIntervencion(int id_militante, FrenteIntervencion frente) {
this(id_militante, frente, false, "");
}
public MilitanteFrenteIntervencion(int id_militante, FrenteIntervencion frente, boolean prioritario, String responsabilidad) {
super();
this.id = new MilitanteFrenteIntervencionPK(id_militante, frente.getId());
this.prioritario = prioritario;
this.responsabilidad = responsabilidad;
}
public MilitanteFrenteIntervencionPK getId() {
return this.id;
}
public void setId(MilitanteFrenteIntervencionPK id) {
this.id = id;
}
public boolean isPrioritario() {
return this.prioritario;
}
public void setPrioritario(boolean prioritario) {
this.prioritario = prioritario;
}
public String getResponsabilidad() {
return this.responsabilidad;
}
public void setResponsabilidad(String responsabilidad) {
this.responsabilidad = responsabilidad;
}
public FrenteIntervencion getFrenteIntervencion() {
return this.frenteIntervencion;
}
public void setFrenteIntervencion(FrenteIntervencion frenteIntervencion) {
this.frenteIntervencion = frenteIntervencion;
}
public Militante getMilitante() {
return this.militante;
}
public void setMilitante(Militante militante) {
this.militante = militante;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((militante == null) ? 0 : militante.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || !(obj instanceof MilitanteFrenteIntervencion))
return false;
MilitanteFrenteIntervencion other = (MilitanteFrenteIntervencion) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (militante == null) {
if (other.militante != null)
return false;
} else if (!militante.equals(other.militante))
return false;
return true;
}
} | 628e3b2ce6894e5dbd23dd583a8df97cda4335bf | [
"Markdown",
"Java"
] | 31 | Java | DesarrolloUJCE/ormdatabase | 664b3facdbc1c580bbe477ad63745437fdc596a1 | 7b86172f3dbc00a86e20c82b6f52742c2c14ce92 |
refs/heads/master | <file_sep>from .fileparse import *
<file_sep>from .messages import *
from .embed import *<file_sep># Wiki
## Quickstart:
#### Install:
```
git clone https://github.com/Merubokkusu/Discord-S.C.U.M.git
cd Discord-S.C.U.M
python3 setup.py install
```
#### Initiate client
```discum.Client(email="none", password="<PASSWORD>", token="none", proxy_host=False, proxy_port=False, user_agent="random")```
```python
>>> import discum
>>> bot = discum.Client(email='<EMAIL>',password='<PASSWORD>')
'Randomly generated user agent: Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_4 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) CriOS/32.0.1700.20 Mobile/10B350 Safari/8536.25'
[+] (<discum.login.Login.Login->Connect) Post -> https://discord.com/api/v8/auth/login
[+] (<discum.login.Login.Login->Connect) {"email": "<EMAIL>", "password": "<PASSWORD>", "undelete": false, "captcha_key": null, "login_source": null, "gift_code_sku_id": null}
[+] (<discum.login.Login.Login->Connect) Response <- {"token": "<PASSWORD>", "user_settings": {"locale": "en-US", "theme": "dark"}}
'Retrieving Discord's build number...'
'Discord is currently on build number 68015'
```
## Commands
- [Read User Data](#read-user-data)
- [Messages](#Messages)
- [User Actions](#User-Actions)
- [Gateway Server](#Gateway-Server)
#### Read User Data:
\* this connects to discord's gateway server and returns your current session settings. It's recommended that you set update to False after you run a command since you can only connect so many times to the gateway until discord gets suspicious (maximum recommended connections per day is 1000)
```bot.read(update=True)```
```bot.getAnalyticsToken(update=True)```
```bot.getConnectedAccounts(update=True)```
```bot.getConsents(update=True)```
```bot.getExperiments(update=True)```
```bot.getFriendSuggestingCount(update=True)```
```bot.getGuildExperiments(update=True)```
```bot.getGuilds(update=True)```
```bot.getGuildIDs(update=True)```
```bot.getGuildData(guildID,update=True)```
```bot.getGuildOwner(guildID,update=True)```
```bot.getGuildBoostLvl(guildID,update=True)```
```bot.getGuildEmojis(guildID,update=True)```
```bot.getGuildBanner(guildID,update=True)```
```bot.getGuildDiscoverySplash(guildID,update=True)```
```bot.getGuildUserPresences(guildID,update=True)```
```bot.getGuildMsgNotificationSettings(guildID,update=True)```
```bot.getGuildRulesChannelID(guildID,update=True)```
```bot.getGuildVerificationLvl(guildID,update=True)```
```bot.getGuildFeatures(guildID,update=True)```
```bot.getGuildJoinTime(guildID,update=True)```
```bot.getGuildRegion(guildID,update=True)```
```bot.getGuildApplicationID(GuildID,update=True)```
```bot.getGuildAfkChannelID(guildID,update=True)```
```bot.getGuildIcon(guildID,update=True)```
```bot.getGuildName(guildID,update=True)```
```bot.getGuildMaxVideoChannelUsers(guildID,update=True)```
```bot.getGuildRoles(guildID,update=True)```
```bot.getGuildPublicUpdatesChannelID(guildID,update=True)```
```bot.getGuildSystemChannelFlags(guildID,update=True)```
```bot.getGuildMfaLvl(guildID,update=True)```
```bot.getGuildAfkTimeout(guildID,update=True)```
```bot.getGuildHashes(guildID,update=True)```
```bot.getGuildSystemChannelID(guildID,update=True)```
```bot.isGuildLazy(guildID,update=True)```
```bot.getGuildNumBoosts(guildID,update=True)```
```bot.isGuildLarge(guildID,update=True)```
```bot.getGuildExplicitContentFilter(guildID,update=True)```
```bot.getGuildSplashHash(guildID,update=True)```
```bot.getGuildVoiceStates(guildID,update=True)```
```bot.getGuildMemberCount(guildID,update=True)```
```bot.getGuildDescription(guildID,update=True)```
```bot.getGuildVanityUrlCode(guildID,update=True)```
```bot.getGuildPreferredLocale(guildID,update=True)```
```bot.getGuildAllChannels(guildID,update=True)```
```bot.getGuildCategories(guildID,update=True)```
```bot.getGuildCategoryIDs(guildID,update=True)```
```bot.getGuildCategoryData(guildID,categoryID,update=True)```
```bot.getGuildChannels(guildID,update=True)```
```bot.getGuildChannelIDs(guildID,update=True)```
```bot.getGuildChannelData(guildID,channelID,update=True)```
```bot.getGuildMembers(guildID,update=True)```
```bot.getGuildMemberIDs(guildID,update=True)```
```bot.getGuildMemberData(guildID,memberID,update=True)```
```bot.getNotes(update=True)```
```bot.getOnlineFriends(update=True)```
```bot.getDMs(update=True)```
```bot.getDMIDs(update=True)```
```bot.getDMData(DMID,update=True)```
```bot.getDMRecipients(DMID,update=True)```
```bot.getReadStates(update=True)```
```bot.getRelationships(update=True)```
| Relationship Type | description |
| ------ | ------ |
| 1 | friend |
| 2 | block |
| 3 | incoming friend request |
| 4 | outgoing friend request |
```bot.getRelationshipIDs(update=True)```
```bot.getRelationshipData(RelationshipID,update=True)```
```bot.getFriends(update=True)```
```bot.getFriendIDs(update=True)```
```bot.getBlocked(update=True)```
```bot.getBlockedIDs(update=True)```
```bot.getIncomingFriendRequests(update=True)```
```bot.getIncomingFriendRequestIDs(update=True)```
```bot.getOutgoingFriendRequests(update=True)```
```bot.getOutgoingFriendRequestIDs(update=True)```
```bot.getSessionID(update=True)```
```bot.getTutorial(update=True)```
```bot.getUserData(update=True)```
```bot.getUserGuildSettings(update=True,guildID=None)```
```bot.getUserSettings(update=True)```
```bot.getOptionsForUserSettings(update=True)```
```bot.getWebsocketVersion(update=True)```
#### Messages
##### get messages in a channel
```getRecentMessage(ChannelID,num=1,beforeDate=None)```
```python
bot.getRecentMessage("383003333751856129") #if beforeDate not given, then most recent message(s) will be returned
```
##### send text message
```sendMessage(ChannelID,message,embed='',tts=False)```
```python
bot.sendMessage("383003333751856129","Hello You :)")
```
* bold message: \*\*text\*\*
* italicized message: \*text\*
* strikethrough message: \~\~text\~\~
* quoted message: \> text
* code: \`text\`
* spoiler: \|\|text\|\|
##### send file
```sendFile(channelID,filelocation,isurl=False,message="")```
```python
bot.sendFile("383003333751856129","https://thiscatdoesnotexist.com/",True)
```
* spoiler images: rename image to SPOILER_imagename.jpg (or whatever extension it has)
##### send embed
```sendMessage(ChannelID,message,embed='',tts=False)```
```python
embed = discum.Embedder()
embed.Title("This is a test")
embed.image('https://cdn.dribbble.com/users/189524/screenshots/2105870/04-example_800x600_v4.gif')
embed.fields('Hello!',':yum:')
embed.fields(':smile:','Testing :)')
embed.author('Tester')
bot.sendMessage("383006063751856129","",embed.read())
```
##### search messages
(if only guildID is provided, this will return most recent messages in that guild). format 25 grouped results per page, ~4 messages in each group, target messages have key "hit" in them). If you'd like to filter searchMessages to only return the messages you searched for, use filterSearchResults
```searchMessages(guildID,channelID=None,userID=None,mentionsUserID=None,has=None,beforeDate=None,afterDate=None,textSearch=None,afterNumResults=None)```
```python
bot.searchMessages("267624335836053506",textSearch="hello")
```
* input types for the search feature:
* channelID,userID,mentionsUserID are lists of either ints or strings
* has is a list of strings
* beforeDate and afterDate are ints
* textSearch is a string
* afterNumResults is an int (multiples of 25)
##### filter search results
```filterSearchResults(searchResponse)```
```python
searchResponse = bot.searchMessages("267624335836053506",textSearch="hello")
bot.filterSearchResults(searchResponse)
```
##### send typing action
```typingAction(channelID)```
```python
bot.typingAction("267624335836053506")
```
##### delete message
```deleteMessage(channelID,messageID)```
```python
bot.deleteMessage("267624335836053506","711254483669352469")
```
##### edit message
```editMessage(channelID, messageID, newMessage)```
```python
bot.editMessage("267624335836053506","711254483669352469","hi")
```
##### pin message
```pinMessage(channelID,messageID)```
```python
bot.pinMessage("267624335836053506","711254483669352469")
```
##### un-pin message
```unPinMessage(channelID,messageID)```
```python
bot.unPinMessage("267624335836053506","711254483669352469")
```
##### get pinned messages
```getPins(channelID)```
```python
bot.getPins("267624335836053506")
```
#### User Actions
##### send friend request
```requestFriend(userID)```
```python
bot.requestFriend(ID)
```
##### accept friend request
```acceptFriend(userID)```
```python
bot.acceptFriend(ID)
```
##### remove friend / unblock user / delete outgoing friend request / reject incoming friend request
```removeRelationship(userID)```
```python
bot.removeRelationship(ID)
```
##### block user
```blockUser(userID)```
```python
bot.blockUser(ID)
```
##### change name
```changeName(name)```
```python
bot.changeName(email,password,name)
```
##### set status
```setStatus(status)```
```python
bot.setStatus(status)
```
##### set avatar
```setAvatar(imagePath)```
```python
bot.setAvatar(email,password,imagePath)
```
#### Gateway Server
```_Client__gateway_server.runIt(taskdata)```
```python
bot._Client__gateway_server.runIt({
1: {
"send": [{
"op": 14,
"d": {
"guild_id": GUILD_ID,
"channels": {
TEXT_CHANNEL_ID: [
[0, 99],
[100, 199]
]
}
}
}],
"receive": [{
"key": [('d', 'ops', 0, 'range'), ('d', 'ops', 1, 'range')],
"keyvalue": [(('d', 'ops', 0, 'op'), 'SYNC'), (('d', 'ops', 1, 'op'), 'SYNC')]
}]
}
})
```
the input consists of "send" and "receive" data:
```
{
1: {
"send": [{...}, {...}, {...}],
"receive": [{...}]
},
2: {
"send": [{...}],
"receive": [{...}, {...}]
}, ...
}
```
the "send" data is a list of what you send, op code and all.
the "receive" data is formatted like so:
```
[{
"key":(optional; type list of tuples of strings/ints),
"keyvalue": (optional; type list of tuples of key&value)
}]
```
and here's a closer look at the values in the "receive" data:
```
[{
"key": [("keys","in","nesting","order"),("keys2","in2","nesting2","order2"),...]
"keyvalue": [(("keys","in","nesting","order"),value_to_check_for2),(("keys2","in2","nesting2","order2"),value_to_check_for2),...]
}]
```
and to clear up any confusion, key looks for the existence of keys and keyvalue looks to see if a specific key has a specific value. Since you can check multiple keys and/or multiple key-value pairs per task, the possibilities are literally endless for what you can look for :)
simple example: here's the minimum amount of data a task can have (the command below simply connects to the gateway server and listens for messages from discord):
```python
bot._Client__gateway_server.runIt({
1: {
"send": [],
"receive": []
}
})
```
<file_sep>#influence for much of this code came from here: https://github.com/Gehock/discord-ws
import asyncio
import websockets
import json
from collections import Counter
class TaskCompleted(Exception):
pass
class GatewayServer():
class LogLevel:
SEND = '\033[94m'
RECEIVE = '\033[92m'
WARNING = '\033[93m'
DEFAULT = '\033[m'
class OPCODE: #https://discordapp.com/developers/docs/topics/opcodes-and-status-codes
# Name Code Client Action Description
DISPATCH = 0 # Receive dispatches an event
HEARTBEAT = 1 # Send/Receive used for ping checking
IDENTIFY = 2 # Send used for client handshake
STATUS_UPDATE = 3 # Send used to update the client status
VOICE_UPDATE = 4 # Send used to join/move/leave voice channels
# 5 # ??? ???
RESUME = 6 # Send used to resume a closed connection
RECONNECT = 7 # Receive used to tell clients to reconnect to the gateway
REQUEST_GUILD_MEMBERS = 8 # Send used to request guild members
INVALID_SESSION = 9 # Receive used to notify client they have an invalid session id
HELLO = 10 # Receive sent immediately after connecting, contains heartbeat and server debug information
HEARTBEAT_ACK = 11 # Sent immediately following a client heartbeat that was received
GUILD_SYNC = 12 # ??? ???
def __init__(self, websocketurl, token, ua_data, proxy_host, proxy_port):
self.websocketurl = websocketurl
self.token = token
self.ua_data = ua_data
self.proxy_host = proxy_host
self.proxy_port = proxy_port
self.interval = None
self.sequence = None
self.session_id = None
self.session_data = None
self.all_tasks = {} #just the task input. all of it
self.receiveData = [] #the receive value input
#self.response_data = [] #lists incoming batches of data
#as far as checklists go, allTasks variables have values looking like None or "complete" which subtasks have values looking like [None] or ["complete"]. The exception is in the mailSent subtask, which has a value of either True or False.
self.receiveChecklist = [] #acts as a checklist for receive, looks at the current task
self.mailSent = False #just checks whether or not data has finished sending, looks at the current task
self.allTasksChecklist = {} #checklist for all tasks
self.taskCompleted = False #is current task completed?
self.allTasksCompleted = False #are all tasks completed?, technically unnecessary, but it's here in case youre confused about how the code works
#self.taskCompleteConstant = {}
self.auth = {
"token": self.token,
"capabilities": 61,
"properties": {
"os": self.ua_data["os"],
"browser": self.ua_data["browser"],
"device": self.ua_data["device"],
"browser_user_agent": self.ua_data["browser_user_agent"],
"browser_version": self.ua_data["browser_version"],
"os_version": self.ua_data["os_version"],
"referrer": "",
"referring_domain": "",
"referrer_current": "",
"referring_domain_current": "",
"release_channel": "stable",
"client_build_number": 68015,
"client_event_source": None
},
"presence": {
"status": "online",
"since": 0,
"activities": [],
"afk": False
},
"compress": False,
"client_state": {
"guild_hashes": {},
"highest_last_message_id": "0",
"read_state_version": 0,
"user_guild_settings_version": -1
}
}
if 'build_num' in self.ua_data and self.ua_data['build_num']!=68015:
self.auth['properties']['client_build_number'] = self.ua_data['build_num']
self.loop = asyncio.get_event_loop()
#variables for calling
self.channelID = None
self.userID = None
self.media_token = None
self.call_endpoint = None
self.call_session_id = None
def key_checker(self, element, keys):
_element = element
for key in keys:
try:
_element = _element[key]
except (KeyError, TypeError) as e:
return False
return True
def value_checker(self, element, keys, valuetest):
_element = element
for index,key in enumerate(keys):
try:
_element = _element[key]
if index==len(keys)-1 and _element != valuetest:
return False
except (KeyError, TypeError) as e:
return False
return True
def NestedDictValues(self,d): #gets all values of a nested dict
for v in d.values():
if isinstance(v, dict):
yield from self.NestedDictValues(v)
else:
yield v
def runIt(self,tasks):
self.all_tasks = tasks
if self.all_tasks != 'get session data':
self.allTasksChecklist = {key: None for key in self.all_tasks.keys()} #looks like {1:None,2:None,etc}
else:
self.allTasksChecklist = {1:'get session data'}
try:
asyncio.run(self.main())
except TaskCompleted:
self.loop.stop()
async def taskManager(self):
if self.all_tasks != 'get session data':
self.taskCompleted = True #necessary for first task to begin
for index in self.all_tasks:
print('task num: '+str(index))
await self.addTask(self.all_tasks[index])
while self.taskCompleted == False:
await asyncio.sleep(1)
self.taskCompleted = False #reset
self.allTasksChecklist[index] = "complete"
print(self.allTasksChecklist)
else:
while self.session_data is None:
await asyncio.sleep(1)
self.allTasksChecklist[1] = "complete" #the index might seem wrong, but remember that the format of this dict is {1:value,2:value,etc}
async def main(self): # http_proxy_host=self.proxy_host, http_proxy_port=self.proxy_port
if self.proxy_host == None:
async with websockets.connect(
self.websocketurl, origin="https://discordapp.com") \
as self.websocket:
print("Connected to "+self.websocketurl)
await self.hello()
if self.interval is None:
print(self.LogLevel.WARNING + "Hello failed, exiting")
print(self.LogLevel.DEFAULT)
return
await asyncio.gather(self.heartbeat(), self.receive(),self.stopLoop(),self.taskManager())
else:
async with websockets.connect(
self.websocketurl, origin="https://discordapp.com", host=self.proxy_host, port=self.proxy_port) \
as self.websocket:
print("Connected to "+self.websocketurl)
await self.hello()
if self.interval is None:
print(self.LogLevel.WARNING + "Hello failed, exiting")
print(self.LogLevel.DEFAULT)
return
await asyncio.gather(self.heartbeat(), self.receive(),self.stopLoop(),self.taskManager())
async def receive(self):
print("Entering receive")
async for message in self.websocket:
print(self.LogLevel.RECEIVE + "<", message)
print(self.LogLevel.DEFAULT)
data = json.loads(message)
#the following lines are technically optional if youre using GatewayServer separately, I simply have them here for convenience
if data["op"] == self.OPCODE.DISPATCH:
self.sequence = int(data["s"]) #necessary
event_type = data["t"]
if event_type == "READY":
self.session_id = data["d"]["session_id"]
self.session_data = data
if event_type == "VOICE_SERVER_UPDATE":
if "token" in data["d"]:
self.media_token = data["d"]["token"]
if "endpoint" in data["d"]:
endpointdata = data["d"]["endpoint"].split(':')[:][0]
self.call_endpoint = "wss://{}/?v=5".format(endpointdata)
if event_type == "VOICE_STATE_UPDATE":
if "user_id" in data["d"]:
self.userID = data["d"]["user_id"]
if "session_id" in data["d"]:
self.call_session_id = data["d"]["session_id"]
#onto updating self.receiveChecklist
for checklistIndex in range(len(self.receiveChecklist)): #for each message, every receive is checked just in case
if self.receiveChecklist[checklistIndex] != ["complete"]:
if "key" in self.receiveChecklist[checklistIndex] and all([self.key_checker(data,i) for i in self.receiveData[checklistIndex]["key"]]): #just looping thru the tuples
self.receiveChecklist[checklistIndex]["key"] = ["complete"]
if "keyvalue" in self.receiveChecklist[checklistIndex] and all([self.value_checker(data,i[0],i[1]) for i in self.receiveData[checklistIndex]["keyvalue"]]): #just looping thru the tuples
self.receiveChecklist[checklistIndex]["keyvalue"] = ["complete"]
if all(value == ["complete"] for value in list(self.NestedDictValues(self.receiveChecklist[checklistIndex]))): # and self.mailSent check mail sent later...
self.receiveChecklist[checklistIndex] = ["complete"]
break #after first match is found, break
if len(self.receiveChecklist)>0 and all(item == ["complete"] for item in self.receiveChecklist) and self.mailSent:
self.taskCompleted = True #current task is completed
async def send(self, opcode, payload):
data = self.opcode(opcode, payload)
print(self.LogLevel.SEND + ">", data)
print(self.LogLevel.DEFAULT)
await self.websocket.send(data)
async def heartbeat(self):
print("Entering heartbeat")
while self.interval is not None:
print("Sending a heartbeat")
await self.send(self.OPCODE.HEARTBEAT, self.sequence)
await asyncio.sleep(self.interval)
async def hello(self):
await self.send(self.OPCODE.IDENTIFY, self.auth)
print(self.LogLevel.SEND + "hello > auth")
print(self.LogLevel.DEFAULT)
ret = await self.websocket.recv()
print("{}hello < {}".format(self.LogLevel.RECEIVE,ret))
print(self.LogLevel.DEFAULT)
data = json.loads(ret)
opcode = data["op"]
if opcode != 10:
print(self.LogLevel.WARNING + "Unexpected reply")
print(ret)
print(self.LogLevel.DEFAULT)
return
self.interval = (data["d"]["heartbeat_interval"] - 2000) / 1000
print("interval:", self.interval)
def opcode(self, opcode: int, payload) -> str:
data = {
"op": opcode,
"d": payload
}
return json.dumps(data)
async def addTask(self,data):
self.mailSent = False #reset
self.taskCompleted = False #reset
self.receiveChecklist = [] #reset
self.receiveData = data["receive"]
for searchIndex in range(len(self.receiveData)):
self.receiveChecklist.append({})
if "key" in self.receiveData[searchIndex]:
self.receiveChecklist[searchIndex]["key"] = [None]
if "keyvalue" in self.receiveData[searchIndex]:
self.receiveChecklist[searchIndex]["keyvalue"] = [None]
sendData = data["send"] #have to also check if all data has been sent.............
for mail in sendData: #send data if theres data to send
#if you want to make changes to mail make that here
await self.send(mail["op"],mail["d"])
self.mailSent = True
async def stopLoop(self):
while not all(value == "complete" for value in self.allTasksChecklist.values()):
await asyncio.sleep(1)
self.allTasksCompleted = True
raise TaskCompleted(self.all_tasks)
'''
# although calling is not supported yet on discum, you can still initial calls with this program (and send data if you get creative). below lies an example code for calling another user (just input your token and the channel id)
if __name__ == "__main__":
gateway = GatewayServer(your_token_here,None,None) #lol id accidently posted my token online. deleted that account
gateway.runIt(taskdata) #loop stops a few seconds after allTasksCompleted == True
#gateway.runIt('get session data')
#gateway.runIt({1:{"send":[],"receive":[]}})
'''
<file_sep>from .GatewayServer import *
<file_sep>from .messages.messages import Messages
from .messages.embed import Embedder
from .user.user import User
from .login.Login import *
from .gateway.GatewayServer import *
import time
import random
import re
import user_agents
class Settings:
def __init__(self, obj):
for k, v in obj.items():
if isinstance(v, dict):
setattr(self, k, Settings(v))
else:
setattr(self, k, v)
def __getitem__(self, val):
return self.__dict__[val]
def __repr__(self):
return '{%s}' % str(', '.join('%s : %s' % (k, repr(v)) for (k, v) in self.__dict__.items()))
class Client:
def convert(self, data):
if isinstance(data, bytes):
return data.decode()
if isinstance(data, dict):
return dict(map(self.convert, data.items()))
if isinstance(data, tuple):
return tuple(map(self.convert, data))
if isinstance(data, list):
return list(map(self.convert, data))
return data
def __init__(self, email="none", password="<PASSWORD>", token="<PASSWORD>", proxy_host=None, proxy_port=None, user_agent="random"): #not using None on email pass and token since that could get flagged by discord...
self.__user_token = token
self.__user_email = email
self.__user_password = <PASSWORD>
self.__proxy_host = proxy_host
self.__proxy_port = proxy_port
self.classsession_settings = {} #look at function read()
self.discord = 'https://discord.com/api/v8/'
self.websocketurl = 'wss://gateway.discord.gg/?encoding=json&v=8'
if user_agent != "random":
self.__user_agent = user_agent
else:
from random_user_agent.user_agent import UserAgent #only really want to import this if needed...which is why it's down here
self.__user_agent = UserAgent(limit=100).get_random_user_agent()
print('Randomly generated user agent: '+self.__user_agent)
parseduseragent = user_agents.parse(self.__user_agent)
self.ua_data = {'os':parseduseragent.os.family,'browser':parseduseragent.browser.family,'device':parseduseragent.device.family if parseduseragent.is_mobile else '','browser_user_agent':self.__user_agent,'browser_version':parseduseragent.browser.version_string,'os_version':parseduseragent.os.version_string}
if self.__user_token == "none": #assuming email and pass are given...
self.__login = Login(self.discord,self.__user_email,self.__user_password,self.__user_agent,self.__proxy_host,self.__proxy_port)
self.__user_token = self.__login.GetToken() #update token from "none" to true string value
time.sleep(1)
self.headers = {
"Host": "discord.com",
"User-Agent": self.__user_agent,
"Accept": "*/*",
"Accept-Language": "en-US",
"Authorization": self.__user_token,
"Connection": "keep-alive",
"keep-alive" : "timeout=10, max=1000",
"TE": "Trailers",
"Pragma": "no-cache",
"Cache-Control": "no-cache",
"Referer": "https://discord.com/channels/@me",
"Content-Type": "application/json"
}
self.s = requests.Session()
self.s.headers.update(self.headers)
if self.__proxy_host != None: #self.s.proxies defaults to {}
self.proxies = {
'http': self.__proxy_host+':'+self.__proxy_port,
'https': self.__proxy_host+':'+self.__proxy_port
}
self.s.proxies.update(proxies)
print("Retrieving Discord's build number...")
discord_login_page_exploration = self.s.get('https://discord.com/login').text
time.sleep(1)
try: #getting the build num is kinda experimental
file_with_build_num = 'https://discord.com/assets/'+re.compile(r'assets/+([a-z0-9]+)\.js').findall(discord_login_page_exploration)[-2]+'.js' #fastest solution I could find since the last js file is huge in comparison to 2nd from last
req_file_build = self.s.get(file_with_build_num).text
index_of_build_num = req_file_build.find('buildNumber')+14
self.discord_build_num = int(req_file_build[index_of_build_num:index_of_build_num+5])
self.ua_data['build_num'] = self.discord_build_num #putting this onto ua_data since getting the build num won't necessarily work
print('Discord is currently on build number '+str(self.discord_build_num))
except:
print('Could not retrieve discord build number.')
self.__gateway_server = GatewayServer(self.websocketurl,self.__user_token,self.ua_data,self.__proxy_host,self.__proxy_port)
'''
test connection (this function was originally in discum and was created by Merubokkusu)
'''
def connectionTest(self): #,proxy):
url=self.discord+'users/@me/affinities/users'
connection = self.s.get(url)
if(connection.status_code == 200):
print("Connected")
else:
print("Incorrect Token")
'''
discord snowflake to unix timestamp and back
'''
def snowflake_to_unixts(self,snowflake):
return int((snowflake/4194304+1420070400000)/1000)
def unixts_to_snowflake(self,unixts):
return int((unixts*1000-1420070400000)*4194304)
'''
(get) and/or read session settings/data
'''
def read(self,update=True): #returns a class, this is the main function, if you want ALL the session data (wall of data), then call this (or bot.read().__dict__). if update=False session_settings will not be updated
if update == False: #if read() hasnt been called yet this will just return an empty dict
return self.classsession_settings
self.__gateway_server.runIt('get session data')
session_settings = self._Client__gateway_server.session_data["d"]
strsession_settings = self.convert(session_settings)
self.classsession_settings = Settings(strsession_settings)
return self.classsession_settings
def getAnalyticsToken(self,update=True):
return self.read(update).analytics_token
def getConnectedAccounts(self,update=True):
return self.read(update).connected_accounts
def getConsents(self,update=True):
return self.read(update).consents
def getExperiments(self,update=True):
return self.read(update).experiments
def getFriendSuggestionCount(self,update=True): #no idea what this is but it's here so whatever
return self.read(update).friend_suggestion_count
def getGuildExperiments(self,update=True):
return self.read(update).guild_experiments
#All about guilds, oh geez this is a long one
def getGuilds(self,update=True): #returns all information about all guilds you're in...might be a little overwhelming so don't call unless you're ready to see a wall of text
return self.read(update).guilds
def getGuildIDs(self,update=True): #just get the guild ids, type list
getthatdata = self.read(update) #refreshes session settings if update is True
return [self.getGuilds(False)[i]['id'] for i in range(len(self.getGuilds(False)))]
## getting specific about a PARTICULAR guild
def getGuildData(self,guildID,update=True): #type dict, all data about a PARTICULAR guild, can be overwhelming
getthatdata = self.read(update) #refreshes session settings if update is True
for i in range(len(self.getGuilds(False))):
if self.getGuilds(False)[i]['id'] == guildID:
return self.getGuilds(False)[i]
return None #guild not found
def getGuildOwner(self,guildID,update=True):
getthatdata = self.read(update) #refreshes session settings if update is True
return self.getGuildData(guildID,False)['owner_id'] #returns type int
def getGuildBoostLvl(self,guildID,update=True):
getthatdata = self.read(update) #refreshes session settings if update is True
return self.getGuildData(guildID,False)['premium_tier']
def getGuildEmojis(self,guildID,update=True):
getthatdata = self.read(update) #refreshes session settings if update is True
return self.getGuildData(guildID,False)['emojis']
def getGuildBanner(self,guildID,update=True):
getthatdata = self.read(update) #refreshes session settings if update is True
return self.getGuildData(guildID,False)['banner'] #if returns 'nil' then there's no banner
def getGuildDiscoverySplash(self,guildID,update=True): #not sure what this is about, something about server discoverability i guess (https://discord.com/developers/docs/resources/guild)
getthatdata = self.read(update) #refreshes session settings if update is True
return self.getGuildData(guildID,False)['discovery_splash']
def getGuildUserPresences(self,guildID,update=True): #only returns presences of online, idle, or do-not-disturb users
getthatdata = self.read(update) #refreshes session settings if update is True
return self.getGuildData(guildID,False)['presences']
def getGuildMsgNotificationSettings(self,guildID,update=True): #returns an int, 0=all messages, 1=only mentions (https://discord.com/developers/docs/resources/guild#guild-object-default-message-notification-level)
getthatdata = self.read(update) #refreshes session settings if update is True
return self.getGuildData(guildID,False)['default_message_notifications']
def getGuildRulesChannelID(self,guildID,update=True): #nil if no rules channel id, idk if this always works so it might actually be more useful just to look for the word "rules" in channel names
getthatdata = self.read(update) #refreshes session settings if update is True
return self.getGuildData(guildID,False)['rules_channel_id']
def getGuildVerificationLvl(self,guildID,update=True): #returns an int, 0-4 (https://discord.com/developers/docs/resources/guild#guild-object-verification-level)
getthatdata = self.read(update) #refreshes session settings if update is True
return self.getGuildData(guildID,False)['verification_level']
def getGuildFeatures(self,guildID,update=True): #returns a list of strings (https://discord.com/developers/docs/resources/guild#guild-object-guild-features)
getthatdata = self.read(update) #refreshes session settings if update is True
return self.getGuildData(guildID,False)['features']
def getGuildJoinTime(self,guildID,update=True): #returns when you joined the server, type string
getthatdata = self.read(update) #refreshes session settings if update is True
return self.getGuildData(guildID,False)['joined_at']
def getGuildRegion(self,guildID,update=True):
getthatdata = self.read(update) #refreshes session settings if update is True
return self.getGuildData(guildID,False)['region']
def getGuildApplicationID(self,GuildID,update=True): #returns application id of the guild creator if it is bot-created (https://discord.com/developers/docs/resources/guild#guild-object-guild-features)
getthatdata = self.read(update) #refreshes session settings if update is True
return self.getGuildData(guildID,False)['application_id']
def getGuildAfkChannelID(self,guildID,update=True): #not sure what this is
getthatdata = self.read(update) #refreshes session settings if update is True
return self.getGuildData(guildID,False)['afk_channel_id']
def getGuildIcon(self,guildID,update=True): #https://discord.com/developers/docs/reference#image-formatting
getthatdata = self.read(update) #refreshes session settings if update is True
return self.getGuildData(guildID,False)['icon']
def getGuildName(self,guildID,update=True):
getthatdata = self.read(update) #refreshes session settings if update is True
return self.getGuildData(guildID,False)['name']
def getGuildMaxVideoChannelUsers(self,guildID,update=True):
getthatdata = self.read(update) #refreshes session settings if update is True
return self.getGuildData(guildID,False)['max_video_channel_users']
def getGuildRoles(self,guildID,update=True): #https://discord.com/developers/docs/topics/permissions#role-object
getthatdata = self.read(update) #refreshes session settings if update is True
return self.getGuildData(guildID,False)['roles']
def getGuildPublicUpdatesChannelID(self,guildID,update=True):
getthatdata = self.read(update) #refreshes session settings if update is True
return self.getGuildData(guildID,False)['public_updates_channel_id']
def getGuildSystemChannelFlags(self,guildID,update=True): #https://discord.com/developers/docs/resources/guild#guild-object-system-channel-flags
getthatdata = self.read(update) #refreshes session settings if update is True
return self.getGuildData(guildID,False)['system_channel_flags']
def getGuildMfaLvl(self,guildID,update=True): #https://discord.com/developers/docs/resources/guild#guild-object-mfa-level
getthatdata = self.read(update) #refreshes session settings if update is True
return self.getGuildData(guildID,False)['mfa_level']
def getGuildAfkTimeout(self,guildID,update=True): #returns type int, unit seconds, https://discord.com/developers/docs/resources/guild
getthatdata = self.read(update) #refreshes session settings if update is True
return self.getGuildData(guildID,False)['afk_timeout']
def getGuildHashes(self,guildID,update=True): #https://github.com/discord/discord-api-docs/issues/1642
getthatdata = self.read(update) #refreshes session settings if update is True
return self.getGuildData(guildID,False)['guild_hashes']
def getGuildSystemChannelID(self,guildID,update=True): #returns an int, the id of the channel where guild notices such as welcome messages and boost events are posted
getthatdata = self.read(update) #refreshes session settings if update is True
return self.getGuildData(guildID,False)['system_channel_id']
def isGuildLazy(self,guildID,update=True): #slightly different naming format since it returns a boolean (https://luna.gitlab.io/discord-unofficial-docs/lazy_guilds.html)
getthatdata = self.read(update) #refreshes session settings if update is True
if self.getGuildData(guildID,False)['lazy'] == 'true':
return True
else:
return False
def getGuildNumBoosts(self,guildID,update=True): #get number of boosts the server has gotten
getthatdata = self.read(update) #refreshes session settings if update is True
return self.getGuildData(guildID,False)['premium_subscription_count']
def isGuildLarge(self,guildID,update=True): #slightly different naming format since it returns a boolean, large if more than 250 members
getthatdata = self.read(update) #refreshes session settings if update is True
if self.getGuildData(guildID,False)['large'] == 'true':
return True
else:
return False
def getGuildExplicitContentFilter(self,guildID,update=True): #https://discord.com/developers/docs/resources/guild#guild-object-explicit-content-filter-level
getthatdata = self.read(update) #refreshes session settings if update is True
return self.getGuildData(guildID,False)['explicit_content_filter']
def getGuildSplashHash(self,guildID,update=True): #not sure what this is for
getthatdata = self.read(update) #refreshes session settings if update is True
return self.getGuildData(guildID,False)['splash']
def getGuildVoiceStates(self,guildID,update=True): #https://discord.com/developers/docs/resources/voice#voice-state-object
getthatdata = self.read(update) #refreshes session settings if update is True
return self.getGuildData(guildID,False)['voice_states']
def getGuildMemberCount(self,guildID,update=True):
getthatdata = self.read(update) #refreshes session settings if update is True
return self.getGuildData(guildID,False)['member_count']
def getGuildDescription(self,guildID,update=True):
getthatdata = self.read(update) #refreshes session settings if update is True
return self.getGuildData(guildID,False)['description']
def getGuildVanityUrlCode(self,guildID,update=True):
getthatdata = self.read(update) #refreshes session settings if update is True
return self.getGuildData(guildID,False)['vanity_url_code']
def getGuildPreferredLocale(self,guildID,update=True):
getthatdata = self.read(update) #refreshes session settings if update is True
return self.getGuildData(guildID,False)['preferred_locale']
def getGuildAllChannels(self,guildID,update=True): #returns all categories and all channels, all the data about that, wall of data so it can be a bit overwhelming, useful if you want to check how many channels your server has since discord counts categories as channels
getthatdata = self.read(update) #refreshes session settings if update is True
return self.getGuildData(guildID,False)['channels']
def getGuildCategories(self,guildID,update=True): #all data about all guild categories, can be overwhelming
getthatdata = self.read(update) #refreshes session settings if update is True
all_channels = self.getGuildData(guildID,False)['channels']
all_categories = []
for channel in all_channels: #https://discord.com/developers/docs/resources/channel#channel-object-channel-types
if channel['type'] == 4:
all_categories.append(channel)
return all_categories
def getGuildCategoryIDs(self,guildID,update=True):
getthatdata = self.read(update) #refreshes session settings if update is True
return [self.getGuildCategories(guildID,False)[i]['id'] for i in range(len(self.getGuildCategories(guildID,False)))]
def getGuildCategoryData(self,guildID,categoryID,update=True):
getthatdata = self.read(update) #refreshes session settings if update is True
if isinstance(categoryID,str):
categoryID = int(categoryID)
for i in range(len(self.getGuildCategories(guildID,False))):
if self.getGuildCategories(guildID,False)[i]['id'] == categoryID:
return self.getGuildCategories(guildID,False)[i]
return None #category not found
def getGuildChannels(self,guildID,update=True): #all data about all guild channels, can be overwhelming
getthatdata = self.read(update) #refreshes session settings if update is True
all_channels = self.getGuildData(guildID,False)['channels']
all_non_categories = []
for channel in all_channels: #https://discord.com/developers/docs/resources/channel#channel-object-channel-types
if channel['type'] != 4:
all_non_categories.append(channel)
return all_non_categories
def getGuildChannelIDs(self,guildID,update=True):
getthatdata = self.read(update) #refreshes session settings if update is True
return [self.getGuildChannels(guildID,False)[i]['id'] for i in range(len(self.getGuildChannels(guildID,False)))]
def getGuildChannelData(self,guildID,channelID,update=True):
getthatdata = self.read(update) #refreshes session settings if update is True
for i in range(len(self.getGuildChannels(guildID,False))):
if self.getGuildChannels(guildID,False)[i]['id'] == channelID:
return self.getGuildChannels(guildID,False)[i]
return None #channel not found
def getGuildMembers(self,guildID,update=True): #all data about all members, can be overwhelming....doesnt get all members for some reason...my guess is that it only gets most recently active members but idk
getthatdata = self.read(update) #refreshes session settings if update is True
return self.getGuildData(guildID,False)['members']
def getGuildMemberIDs(self,guildID,update=True):
getthatdata = self.read(update) #refreshes session settings if update is True
return [self.getGuildMembers(guildID,False)[i]['user']['id'] for i in range(len(self.getGuildMembers(guildID,False)))]
def getGuildMemberData(self,guildID,memberID,update=True):
getthatdata = self.read(update) #refreshes session settings if update is True
for i in range(len(self.getGuildMembers(guildID,False))):
if self.getGuildMembers(guildID,False)[i]['user']['id'] == memberID:
return self.getGuildMembers(guildID,False)[i]
return None #member not found, again I must state that getGuildMembers doesnt return all members, likely it only returns most recent members but who knows for now...
# end of guild stuff, now onto the other stuff
def getNotes(self,update=True):
return self.read(update).notes #returns a dict where the keys are user IDs and the values are the notes
def getOnlineFriends(self,update=True): #i saw no reason to make "sub functions" of this since it's only about online friends
getthatdata = self.read(update) #refreshes session settings if update is True
return self.read(False).presences
#all about DMs, aw geez this is gonna be a long one too i guess...
def getDMs(self,update=True):
getthatdata = self.read(update) #refreshes session settings if update is True
return self.read(False).private_channels
def getDMIDs(self,update=True): #discord sometimes calls these channel IDs...
getthatdata = self.read(update) #refreshes session settings if update is True
return [self.getDMs(False)[i]['id'] for i in range(len(self.getDMs(False)))]
def getDMData(self,DMID,update=True): #get data about a particular DM
getthatdata = self.read(update) #refreshes session settings if update is True
for i in range(len(self.getDMs(False))):
if self.getDMs(False)[i]['id'] == DMID:
return self.getDMs(False)[i]
return None
def getDMRecipients(self,DMID,update=True): #returns everyone in that DM except your user
getthatdata = self.read(update) #refreshes session settings if update is True
return self.getDMData(DMID,False)['recipients']
#end of DM stuff, heh that wasnt that bad, onto the rest of the stuff
def getReadStates(self,update=True): #another advantage of using websockets instead of requests (see https://github.com/discord/discord-api-docs/issues/13)
getthatdata = self.read(update) #refreshes session settings if update is True
return self.read(False).read_state
#all about relationships...on discord. note this includes all your friends AND all users youve blocked
def getRelationships(self,update=True):
getthatdata = self.read(update) #refreshes session settings if update is True
return self.read(False).relationships
def getRelationshipIDs(self,update=True): #gets userIDs that are in a "relationship" with your account
getthatdata = self.read(update) #refreshes session settings if update is True
return [self.getRelationships(False)[i]['id'] for i in range(len(self.getRelationships(False)))]
def getRelationshipData(self,RelationshipID,update=True):
getthatdata = self.read(update) #refreshes session settings if update is True
if isinstance(RelationshipID,str) and "#" in RelationshipID: #if in username discriminator format
for i in range(len(self.getRelationships(False))):
if self.getRelationships(False)[i]['user']['username'] == RelationshipID.split("#")[0] and self.getRelationships(False)[i]['user']['discriminator'] == RelationshipID.split("#")[1]:
return self.getRelationships(False)[i]
elif isinstance(RelationshipID,str): #if in ID format, but is a string instead of an int
RelationshipID = int(RelationshipID)
for i in range(len(self.getRelationships(False))):
if self.getRelationships(False)[i]['id'] == RelationshipID:
return self.getRelationships(False)[i]
return None
def getFriends(self,update=True): #yay, no this will not give you friends, it returns data about the users you have a friends
getthatdata = self.read(update) #refreshes session settings if update is True
friends = []
for i in range(len(self.getRelationships(False))):
if self.getRelationships(False)[i]['type'] == 1:
friends.append(self.getRelationships(False)[i])
return friends #wow and just like that you have friends.........................
def getFriendIDs(self,update=True):
getthatdata = self.read(update) #refreshes session settings if update is True
return [self.getFriends(False)[i]['id'] for i in range(len(self.getFriends(False)))]
def getBlocked(self,update=True): #nay
getthatdata = self.read(update) #refreshes session settings if update is True
blocked = []
for i in range(len(self.getRelationships(False))):
if self.getRelationships(False)[i]['type'] == 2:
blocked.append(self.getRelationships(False)[i])
return blocked
def getBlockedIDs(self,update=True):
getthatdata = self.read(update) #refreshes session settings if update is True
return [self.getBlocked(False)[i]['id'] for i in range(len(self.getBlocked(False)))]
def getIncomingFriendRequests(self,update=True): #returns data...
getthatdata = self.read(update) #refreshes session settings if update is True
ifr = []
for i in range(len(self.getRelationships(False))):
if self.getRelationships(False)[i]['type'] == 3:
ifr.append(self.getRelationships(False)[i])
return ifr
def getIncomingFriendRequestIDs(self,update=True):
getthatdata = self.read(update) #refreshes session settings if update is True
return [self.getIncomingFriendRequests(False)[i]['id'] for i in range(len(self.getIncomingFriendRequests(False)))]
def getOutgoingFriendRequests(self,update=True):
getthatdata = self.read(update) #refreshes session settings if update is True
ofr = []
for i in range(len(self.getRelationships(False))):
if self.getRelationships(False)[i]['type'] == 4:
ofr.append(self.getRelationships(False)[i])
return ofr
def getOutgoingFriendRequestIDs(self,update=True):
getthatdata = self.read(update) #refreshes session settings if update is True
return [self.getOutgoingFriendRequests(False)[i]['id'] for i in range(len(self.getOutgoingFriendRequests(False)))]
#end of relationship stuff
def getSessionID(self,update=True):
return self.read(update).session_id
def getTutorial(self,update=True): #tutorial on what? guess we'll never know...ask discord maybe?
return self.read(update).tutorial
def getUserData(self,update=True):
return self.read(update).user
def getUserGuildSettings(self,update=True,guildID=None): #personal settings for a server, like whether or not you want @everyone pings to show, formatting is weird cause you might not want to pass a guildID, hence it is at the end
getthatdata = self.read(update) #refreshes session settings if update is True
all_user_guild_settings = self.read(False).user_guild_settings
if guildID != None:
if isinstance(guildID,str):
guildID = int(guildID)
for i in range(len(all_user_guild_settings)):
if all_user_guild_settings[i]['guild_id'] == guildID:
return all_user_guild_settings[i]
else:
return all_user_guild_settings
def getUserSettings(self,update=True): #returns a class
return self.read(update).user_settings
def getOptionsForUserSettings(self,update=True): #bc i didnt feel like making a ton of sub functions for this, the data is there if you want to process it but rn it seems useless to me
return list(self.read(update).user_settings.__dict__.keys()) #since getUserSettings() returns a class, you can call subsettings using this format: getUserSettings().afk_timeout
def getWebsocketVersion(self,update=True):
return self.read(update).v
# oof end of reading session settings
'''
username to snowflake and back
'''
def username_to_userID(self,userdiscriminator): #userdiscriminator is "username#discriminator"
getthatdata = self.read() #might as well get current session settings
if type(self.getRelationshipData(userdiscriminator,False)).__name__ != 'NoneType': #testing our luck to see if user is in a "relationship" with our user
return self.getRelationshipData(userdiscriminator,False)['id'] #returns type int
User(self.discord,self.s).requestFriend(userdiscriminator) #this puts you in a "relationship" with that user
if type(self.getRelationshipData(userdiscriminator,True)).__name__ != 'NoneType': #if you sent a request to a bot or to yourself then this becomes False
User(self.discord,self.s).removeRelationship(self.getRelationshipData(userdiscriminator,False)['id'])
return self.getRelationshipData(userdiscriminator,False)['id'] #returns type int
return None #happens if other user is a bot, is yourself, does not exist, or something wrong with your account
def userID_to_username(self,userID): #userID aka snowflake
getthatdata = self.read() #might as well get current session settings
if type(self.getRelationshipData(userID,False)).__name__ != 'NoneType': #testing our luck to see if user is in a "relationship" with our user
userdiscriminator = self.getRelationshipData(userID,False)['user']['username'] + "#" + self.getRelationshipData(userID,False)['user']['discriminator']
return userdiscriminator
if isinstance(userID,int):
userID = str(userID)
User(self.discord,self.s).requestFriend(userID) #this puts you in a "relationship" with that user
if type(self.getRelationshipData(userID,True)).__name__ != 'NoneType': #if you sent a request to a bot or to yourself then this becomes False
User(self.discord,self.s).removeRelationship(userID)
userdiscriminator = self.getRelationshipData(userID,False)['user']['username'] + "#" + self.getRelationshipData(userID,False)['user']['discriminator']
return userdiscriminator
return None #happens if other user is a bot, is yourself, does not exist, or something wrong with your account
'''
Messages
'''
#get recent messages
def getMessages(self,channelID,num=1,beforeDate=None): # num <= 100, beforeDate is a snowflake
return Messages(self.discord,self.s).getMessages(channelID,num,beforeDate)
#send text or embed messages
def sendMessage(self,channelID,message,embed="",tts=False):
return Messages(self.discord,self.s).sendMessage(channelID,message,embed,tts)
#send files (local or link)
def sendFile(self,channelID,filelocation,isurl=False,message=""):
return Messages(self.discord,self.s).sendFile(channelID,filelocation,isurl,message)
#search messages
def searchMessages(self,guildID,channelID=None,userID=None,mentionsUserID=None,has=None,beforeDate=None,afterDate=None,textSearch=None,afterNumResults=None):
return Messages(self.discord,self.s).searchMessages(guildID,channelID,userID,mentionsUserID,has,beforeDate,afterDate,textSearch,afterNumResults)
#filter searchMessages, takes in the output of searchMessages (a requests response object) and outputs a list of target messages
def filterSearchResults(self,searchResponse):
return Messages(self.discord,self.s).filterSearchResults(searchResponse)
#sends the typing action for 10 seconds (or technically until you change the page)
def typingAction(self,channelID):
return Messages(self.discord,self.s).typingAction(channelID)
#delete message
def deleteMessage(self,channelID,messageID):
return Messages(self.discord,self.s).deleteMessage(channelID,messageID)
#edit message
def editMessage(self,channelID,messageID,newMessage):
return Messages(self.discord,self.s).editMessage(channelID, messageID, newMessage)
#pin message
def pinMessage(self,channelID,messageID):
return Messages(self.discord,self.s).pinMessage(channelID,messageID)
#un-pin message
def unPinMessage(self,channelID,messageID):
return Messages(self.discord,self.s).unPinMessage(channelID,messageID)
#get pinned messages
def getPins(self,channelID):
return Messages(self.discord,self.s).getPins(channelID)
'''
User relationships
'''
#create outgoing friend request
def requestFriend(self,user): #you can input a userID(snowflake) or a user discriminator
return User(self.discord,self.s).requestFriend(user)
#accept incoming friend request
def acceptFriend(self,userID):
return User(self.discord,self.s).acceptFriend(userID)
#remove friend OR unblock user
def removeRelationship(self,userID):
return User(self.discord,self.s).removeRelationship(userID)
#block user
def blockUser(self,userID):
return User(self.discord,self.s).blockUser(userID)
'''
Profile edits
'''
# change name
def changeName(self,name):
return User(self.discord,self.s).changeName(self.email,self.password,name)
# set status
def setStatus(self,status):
return User(self.discord,self.s).setStatus(status)
# set avatar
def setAvatar(self,imagePath):
return User(self.discord,self.s).setAvatar(self.email,self.password,imagePath)
<file_sep>import requests
import json
from ..fileparse.fileparse import Fileparse
from ..Logger import *
from urllib.parse import urlparse,quote_plus
from requests_toolbelt import MultipartEncoder
import random,string
import math
import os
import time
class Messages(object):
def __init__(self, discord, s): #s is the requests session object
self.discord = discord
self.s = s
#get Message
def getMessages(self,channelID,num,beforeDate): # 1 ≤ num ≤ 100, beforeDate is a snowflake
url = self.discord+"channels/"+channelID+"/messages?limit="+str(num)
if beforeDate != None:
url += "&before="+str(beforeDate)
Logger.LogMessage('Get -> {}'.format(url))
response = self.s.get(url)
Logger.LogMessage('Response <- {}'.format(response.text), log_level=LogLevel.OK)
return response
#text message
def sendMessage(self,channelID,message,embed,tts):
url = self.discord+"channels/"+channelID+"/messages"
body = {"content": message, "tts": tts,"embed":embed}
Logger.LogMessage('Post -> {}'.format(url))
Logger.LogMessage('{}'.format(str(body)))
response = self.s.post(url, data=json.dumps(body))
Logger.LogMessage('Response <- {}'.format(response.text), log_level=LogLevel.OK)
return response
#send file
def sendFile(self,channelID,filelocation,isurl,message):
mimetype, extensiontype, fd = Fileparse(self.s).parse(filelocation,isurl) #guess extension from file data
if mimetype == 'invalid': #error out
print('ERROR: File does not exist.')
return
if isurl: #get filename
a = urlparse(filelocation)
if len(os.path.basename(a.path))>0: #if everything is normal...
filename = os.path.basename(a.path)
else:
if mimetype == 'unsupported': #if filetype not detected and extension not given
filename = 'unknown'
else: #if filetype detected but extension not given
filename = 'unknown.'+extensiontype
else: #local file
filename = os.path.basename(os.path.normpath(filelocation))
#now time to post the file
url = self.discord+'channels/'+channelID+'/messages'
if isurl:
fields={"file":(filename,fd,mimetype),"file_id":"0", "content":message}
else:
fields={"file":(filename,open(filelocation,'rb').read(),mimetype),"file_id":"0", "content":message}
m=MultipartEncoder(fields=fields,boundary='----WebKitFormBoundary'+''.join(random.sample(string.ascii_letters+string.digits,16)))
self.s.headers.update({"Content-Type":m.content_type})
Logger.LogMessage('Post -> {}'.format(url))
Logger.LogMessage('{}'.format(str(MultipartEncoder(fields={"file":(filename,"<file data here>",mimetype),"file_id":"0", "content":message},boundary='----WebKitFormBoundary'+''.join(random.sample(string.ascii_letters+string.digits,16))))))
response = self.s.post(url, data=m)
Logger.LogMessage('Response <- {}'.format(response.text), log_level=LogLevel.OK)
return response
def searchMessages(self,guildID,channelID,userID,mentionsUserID,has,beforeDate,afterDate,textSearch,afterNumResults): #classic discord search function, results with key "hit" are the results you searched for, afterNumResults (aka offset) is multiples of 25 and indicates after which messages (type int), filterResults defaults to False
url = self.discord+"guilds/"+guildID+"/messages/search?"
queryparams = ""
if not all(v is None for v in [channelID,userID,mentionsUserID,has,beforeDate,afterDate,textSearch,afterNumResults]):
if channelID != None and isinstance(channelID,list):
for item in channelID:
if isinstance(item,int):
queryparams += "channel_id="+str(item)+"&"
elif isinstance(item,str) and len(item)>0:
queryparams += "channel_id="+item+"&"
if userID != None and isinstance(userID,list):
for item in userID:
if isinstance(item,int):
queryparams += "author_id="+str(item)+"&"
elif isinstance(item,str) and len(item)>0:
queryparams += "author_id="+item+"&"
if mentionsUserID != None and isinstance(mentionsUserID,list):
for item in mentionsUserID:
if isinstance(item,int):
queryparams += "mentions="+str(item)+"&"
elif isinstance(item,str) and len(item)>0:
queryparams += "mentions="+item+"&"
if has != None and isinstance(has,list):
for item in has:
if isinstance(item,str) and len(item)>0:
queryparams += "has="+item+"&"
if beforeDate != None and isinstance(beforeDate,int):
queryparams += "min_id="+str(beforeDate)+"&"
if afterDate != None and isinstance(afterDate,int):
queryparams += "max_id="+str(afterDate)+"&"
if textSearch != None and isinstance(textSearch,str): #textSearch can be len 0....ugh
queryparams += "content="+quote_plus(textSearch)+"&"
if afterNumResults != None and isinstance(afterNumResults,int):
queryparams += "offset="+str(afterNumResults)
url += queryparams
Logger.LogMessage('Get -> {}'.format(url))
response = self.s.get(url)
Logger.LogMessage('Response <- {}'.format(response.text), log_level=LogLevel.OK)
return response
Logger.LogMessage('Get -> {}'.format(url))
response = self.s.get(url)
Logger.LogMessage('Response <- {}'.format(response.text), log_level=LogLevel.OK)
return response
def filterSearchResults(self,searchResponse): #only input is the requests response object outputted from searchMessages, returns type list
jsonresponse = searchResponse.json()['messages']
filteredMessages = []
for group in jsonresponse:
for result in group:
if 'hit' in result:
filteredMessages.append(result)
return filteredMessages
def typingAction(self,channelID): #sends the typing action for 10 seconds (or until you change the page)
url = self.discord+"channels/"+channelID+"/typing"
Logger.LogMessage('Post -> {}'.format(url))
response = self.s.post(url)
Logger.LogMessage('Response <- {}'.format(response.text), log_level=LogLevel.OK)
return response
def editMessage(self,channelID,messageID,newMessage):
url = self.discord+"channels/"+channelID+"/messages/"+messageID
body = {"content": newMessage}
Logger.LogMessage('Patch -> {}'.format(url))
Logger.LogMessage('{}'.format(str(body)))
response = self.s.patch(url, data=json.dumps(body))
Logger.LogMessage('Response <- {}'.format(response.text), log_level=LogLevel.OK)
return response
def deleteMessage(self,channelID,messageID):
url = self.discord+"channels/"+channelID+"/messages/"+messageID
Logger.LogMessage('Delete -> {}'.format(url))
response = self.s.delete(url)
Logger.LogMessage('Response <- {}'.format(response.text), log_level=LogLevel.OK)
return response
def pinMessage(self,channelID,messageID):
url = self.discord+"channels/"+channelID+"/pins/"+messageID
Logger.LogMessage('Put -> {}'.format(url))
response = self.s.put(url)
Logger.LogMessage('Response <- {}'.format(response.text), log_level=LogLevel.OK)
return response
def unPinMessage(self,channelID,messageID):
url = self.discord+"channels/"+channelID+"/pins/"+messageID
Logger.LogMessage('Delete -> {}'.format(url))
response = self.s.delete(url)
Logger.LogMessage('Response <- {}'.format(response.text), log_level=LogLevel.OK)
return response
def getPins(self,channelID): #get pinned messages
url = self.discord+"channels/"+channelID+"/pins"
Logger.LogMessage('Get -> {}'.format(url))
response = self.s.get(url)
Logger.LogMessage('Response <- {}'.format(response.text), log_level=LogLevel.OK)
return response
<file_sep>from .discum import *
from .gateway.GatewayServer import *
from .Logger import *
from .login.Login import *
<file_sep> [](https://badge.fury.io/py/discum) [](https://pypi.org/project/discum/0.2.1/) [](https://pepy.tech/project/discum/month) [](https://gitter.im/discum/community)
### A Discord Selfbot Api Wrapper - discum

\* [changelog](https://github.com/Merubokkusu/Discord-S.C.U.M/blob/master/changelog.md)
## Info
Discum is a Discord selfbot api wrapper (in case you didn't know, selfbotting = automating a user account). Whenever you login to discord, your client communicates with Discord's servers using Discord's http api (http(s) requests) and gateway server (websockets). Discum allows you have this communication with Discord with python.
The main difference between Discum and other Discord api wrapper libraries (like discord.py) is that discum is written and maintained to work on user accounts (so, perfect for selfbots). We thoroughly test all code on here and develop discum to be readable, expandable, and useable.
Note, using a selfbot is against Discord's Terms of Service and you could get banned for using one if you're not careful. Also, this needs to be said: discum does not have rate limit handling. The main reasons for this are that discum is made to (1) be (relatively) simple and (2) give the developer/user freedom (generally I'd recommend a bit more than 1 second in between tasks of the same type, but if you'd like a longer or shorter wait time that's up to you). We (Merubokkusu and anewrandomaccount) do not take any responsibility for any consequences you might face while using discum. We also do not take any responsibility for any damage caused (to servers/channels) through the use of Discum. Discum is a tool; how you use this tool is on you.
## Install (installation should be the same on Mac, Linux, Windows, etc; just make sure you're using python 3.7 or 3.8)
from PyPI (this is probably outdated, installing from source is recommended):
```python
pip install discum
```
from source (this is up-to-date with recent changes)(currently on version 0.2.5):
```
git clone https://github.com/Merubokkusu/Discord-S.C.U.M.git
cd Discord-S.C.U.M
python3 setup.py install
```
# Usage
### [Read the Wiki](https://github.com/Merubokkusu/Discord-S.C.U.M/blob/master/wiki.md)
# Example
```python
import discum
bot = discum.Client(email=,password=) #note, this will not work if you have a MFA account
#bot = discum.Client(email=,password=,proxy_host=,proxy_port=,user_agent=)
#bot = discum.Client(email=,password=,token=) #works for all types of accounts
#bot = discum.Client(token=) #works for all types of accounts, no profile editing however
#bot = discum.Client(token=,proxy_host=,proxy_port=) #works for all types of accounts, no profile editing however
bot.read()
bot.read(update=False).__dict__
bot.getGuildIDs(update=False)
bot.sendMessage("383003333751856129","Hello You :)")
```
### bonus features:
convert username to userID and back:
```python
bot.username_to_userID(userdiscriminator) #input is "username#discriminator". you cannot input bot accounts or yourself
bot.userID_to_username(snowflake) #input is userID (aka snowflake). you cannot input bot accounts or yourself
```
convert unix timestamp to snowflake and back:
```python
bot.unixts_to_snowflake(unixts) #unixts is of type int
bot.snowflake_to_unixts(snowflake) #snowflake is of type int
```
# To Do
- [x] Sending basic text messages
- [X] Sending Images
- [x] Sending Embeds
- [X] Sending Requests (Friends etc)
- [X] Profile Editing (Name,Status,Avatar)
- [ ] Making phone calls, sending audio/video data thru those calls
- [ ] Everything
# list of all 103 functions (click thru these and github should show their location in discum.py)
```python
discum.Client(email="none", password="<PASSWORD>", token="<PASSWORD>", proxy_host=False, proxy_port=False, user_agent="random") #look at __init__
connectionTest()
snowflake_to_unixts(snowflake)
unixts_to_snowflake(unixts)
read(update=True)
getAnalyticsToken(update=True)
getConnectedAccounts(update=True)
getConsents(update=True)
getExperiments(update=True)
getFriendSuggestionCount(update=True)
getGuildExperiments(update=True)
getGuilds(update=True)
getGuildIDs(update=True)
getGuildData(guildID,update=True)
getGuildOwner(guildID,update=True)
getGuildBoostLvl(guildID,update=True)
getGuildEmojis(guildID,update=True)
getGuildBanner(guildID,update=True)
getGuildDiscoverySplash(guildID,update=True): #not sure what this is about, something about server discoverability i guess (https
getGuildUserPresences(guildID,update=True)
getGuildMsgNotificationSettings(guildID,update=True): #returns an int, 0=all messages, 1=only mentions (https
getGuildRulesChannelID(guildID,update=True)
getGuildVerificationLvl(guildID,update=True): #returns an int, 0-4 (https
getGuildFeatures(guildID,update=True): #returns a list of strings (https
getGuildJoinTime(guildID,update=True)
getGuildRegion(guildID,update=True)
getGuildApplicationID(GuildID,update=True): #returns application id of the guild creator if it is bot-created (https
getGuildAfkChannelID(guildID,update=True)
getGuildIcon(guildID,update=True): #https
getGuildName(guildID,update=True)
getGuildMaxVideoChannelUsers(guildID,update=True)
getGuildRoles(guildID,update=True): #https
getGuildPublicUpdatesChannelID(guildID,update=True)
getGuildSystemChannelFlags(guildID,update=True): #https
getGuildMfaLvl(guildID,update=True): #https
getGuildAfkTimeout(guildID,update=True): #returns type int, unit seconds, https
getGuildHashes(guildID,update=True): #https
getGuildSystemChannelID(guildID,update=True)
isGuildLazy(guildID,update=True): #slightly different naming format since it returns a boolean (https
getGuildNumBoosts(guildID,update=True)
isGuildLarge(guildID,update=True)
getGuildExplicitContentFilter(guildID,update=True): #https
getGuildSplashHash(guildID,update=True)
getGuildVoiceStates(guildID,update=True): #https
getGuildMemberCount(guildID,update=True)
getGuildDescription(guildID,update=True)
getGuildVanityUrlCode(guildID,update=True)
getGuildPreferredLocale(guildID,update=True)
getGuildAllChannels(guildID,update=True)
getGuildCategories(guildID,update=True)
getGuildCategoryIDs(guildID,update=True)
getGuildCategoryData(guildID,categoryID,update=True)
getGuildChannels(guildID,update=True)
getGuildChannelIDs(guildID,update=True)
getGuildChannelData(guildID,channelID,update=True)
getGuildMembers(guildID,update=True)
getGuildMemberIDs(guildID,update=True)
getGuildMemberData(guildID,memberID,update=True)
getNotes(update=True)
getOnlineFriends(update=True)
getDMs(update=True)
getDMIDs(update=True)
getDMData(DMID,update=True)
getDMRecipients(DMID,update=True)
getReadStates(update=True): #another advantage of using websockets instead of requests (see https
getRelationships(update=True)
getRelationshipIDs(update=True)
getRelationshipData(RelationshipID,update=True)
getFriends(update=True)
getFriendIDs(update=True)
getBlocked(update=True)
getBlockedIDs(update=True)
getIncomingFriendRequests(update=True)
getIncomingFriendRequestIDs(update=True)
getOutgoingFriendRequests(update=True)
getOutgoingFriendRequestIDs(update=True)
getSessionID(update=True)
getTutorial(update=True)
getUserData(update=True)
getUserGuildSettings(update=True,guildID=None)
getUserSettings(update=True)
getOptionsForUserSettings(update=True)
getWebsocketVersion(update=True)
username_to_userID(userdiscriminator)
userID_to_username(userID)
getMessages(channelID,num=1,beforeDate=None)
sendMessage(channelID,message,embed="",tts=False)
sendFile(channelID,filelocation,isurl=False,message="")
searchMessages(guildID,channelID=None,userID=None,mentionsUserID=None,has=None,beforeDate=None,afterDate=None,textSearch=None,afterNumResults=None)
filterSearchResults(searchResponse)
typingAction(channelID)
deleteMessage(channelID,messageID)
pinMessage(channelID,messageID)
unPinMessage(channelID,messageID)
getPins(channelID)
requestFriend(user)
acceptFriend(userID)
removeRelationship(userID)
blockUser(userID)
changeName(name)
setStatus(status)
setAvatar(imagePath)
getGuildPublicUpdatesChannelID(guildID,update=True)
getGuildSystemChannelFlags(guildID,update=True): #https
getGuildMfaLvl(guildID,update=True): #https
getGuildAfkTimeout(guildID,update=True): #returns type int, unit seconds, https
getGuildHashes(guildID,update=True): #https
getGuildSystemChannelID(guildID,update=True)
isGuildLazy(guildID,update=True): #slightly different naming format since it returns a boolean (https
getGuildNumBoosts(guildID,update=True)
isGuildLarge(guildID,update=True)
getGuildExplicitContentFilter(guildID,update=True): #https
getGuildSplashHash(guildID,update=True)
getGuildVoiceStates(guildID,update=True): #https
getGuildMemberCount(guildID,update=True)
getGuildDescription(guildID,update=True)
getGuildVanityUrlCode(guildID,update=True)
getGuildPreferredLocale(guildID,update=True)
getGuildAllChannels(guildID,update=True)
getGuildCategories(guildID,update=True)
getGuildCategoryIDs(guildID,update=True)
getGuildCategoryData(guildID,categoryID,update=True)
getGuildChannels(guildID,update=True)
getGuildChannelIDs(guildID,update=True)
getGuildChannelData(guildID,channelID,update=True)
getGuildMembers(guildID,update=True)
getGuildMemberIDs(guildID,update=True)
getGuildMemberData(guildID,memberID,update=True)
getNotes(update=True)
getOnlineFriends(update=True)
getDMs(update=True)
getDMIDs(update=True)
getDMData(DMID,update=True)
getDMRecipients(DMID,update=True)
getReadStates(update=True): #another advantage of using websockets instead of requests (see https
getRelationships(update=True)
getRelationshipIDs(update=True)
getRelationshipData(RelationshipID,update=True)
getFriends(update=True)
getFriendIDs(update=True)
getBlocked(update=True)
getBlockedIDs(update=True)
getIncomingFriendRequests(update=True)
getIncomingFriendRequestIDs(update=True)
getOutgoingFriendRequests(update=True)
getOutgoingFriendRequestIDs(update=True)
getSessionID(update=True)
getTutorial(update=True)
getUserData(update=True)
getUserGuildSettings(update=True,guildID=None)
getUserSettings(update=True)
getOptionsForUserSettings(update=True)
getWebsocketVersion(update=True)
username_to_userID(userdiscriminator)
userID_to_username(userID)
getMessages(guildID,channelID=None,userID=None,mentionsUserID=None,has=None,beforeDate=None,afterDate=None,textSearch=None,waitTime=1)
getRecentMessage(channelID,num=1,beforeDate=None)
sendMessage(channelID,message,embed="",tts=False)
sendFile(channelID,filelocation,isurl=False,message="")
searchMessages(guildID,channelID=None,userID=None,mentionsUserID=None,has=None,beforeDate=None,afterDate=None,textSearch=None,afterNumResults=None)
typingAction(channelID)
deleteMessage(channelID,messageID)
pinMessage(channelID,messageID)
unPinMessage(channelID,messageID)
getPins(channelID)
requestFriend(user)
acceptFriend(userID)
removeRelationship(userID)
blockUser(userID)
changeName(name)
setStatus(status)
setAvatar(imagePath)
_Client__gateway_server.runIt(data) #for websocket connections
```
### notes:
arandomnewaccount here - my profile is invisible because this isn't my only github account and therefore I've been marked as spam by github. I'll still be commiting onto the repo from time to time but I won't be able to answer issues on the issue page. If you want to contact me about discum (issues, questions, etc) you can send an email to <EMAIL>.
<file_sep># Changelog
# 0.2.5
### Added
- ability to set custom user agent (or randomly generate a user agent). This user agent is then used for both http api requests and websocket connections
- colorful GatewayServer outputs
### Changed
- discum.Client input:
```python
bot = discum.Client(email='', password='', token='', proxy_host=None, proxy_port=None, user_agent="random")
```
- gateway version from v6 to v8
- task receive checking, again. made it a lot simpler and better. See following example for getting members of a server with a little under 200 members:
```python
bot._Client__gateway_server.runIt({
1: {
"send": [{
"op": 14,
"d": {
"guild_id": GUILD_ID,
"channels": {
TEXT_CHANNEL_ID: [
[0, 99],
[100, 199]
]
}
}
}],
"receive": [{
"key": [('d', 'ops', 0, 'range'), ('d', 'ops', 1, 'range')],
"keyvalue": [(('d', 'ops', 0, 'op'), 'SYNC'), (('d', 'ops', 1, 'op'), 'SYNC')]
}]
}
})
```
the receive format is greatly simplified :)
```
{
"key":(optional; type list of tuples of strings/ints),
"keyvalue": (optional; type list of tuples of key&value)
}
```
this might be more helpful: how to use the receive format:
```
{
"key": [("keys","in","nesting","order"),("keys2","in2","nesting2","order2"),...]
"keyvalue": [(("keys","in","nesting","order"),value_to_check_for2),(("keys2","in2","nesting2","order2"),value_to_check_for2),...]
}
```
and to clear up any confusion, key looks for the existence of keys and keyvalue looks to see if a specific key has a specific value. Since you can check multiple keys and/or multiple key-value pairs per task, the possibilities are literally endless for what you can look for :)
# 0.2.4
### Changed
- task receive checking (in gateway/GatewayServer.py) for better searching thru nested dictionaries. see the following example for getting the members of a server that has a little over 300 members:
```python
bot._Client__gateway_server.runIt({
1: {
"send": [{
"op": 14,
"d": {
"guild_id": GUILD_ID,
"channels": {
TEXT_CHANNEL_ID: [
[0, 99],
[100, 199]
]
}
}
}],
"receive": [{
"keyvaluechecker": [
['d', 'ops', 0, 'range'],
[100, 199]
]
}]
},
2: {
"send": [{
"op": 14,
"d": {
"guild_id": GUILD_ID,
"channels": {
TEXT_CHANNEL_ID: [
[200, 299],
[300, 399]
]
}
}
}],
"receive": [{
"keychecker": ['d', 'ops', 0, 'range']
}]
}
})
```
As you can see above, the receive format has changed to allow this. This is the new receive format:
```
{
"op": (optional; type int),
"d": {
"keys": (optional; type list of strings),
"values": (optional; list of no set types),
"texts": (optional; type list of strings)
},
"s": (optional; type int),
"t": (optional; type str),
"keychecker": (optional; type list),
"keyvaluechecker": (optional; type list)
}
```
And...here's how to use the receive format above:
```
{
"op": integer,
"d": {
"keys": [depth 1 keys (in any order) of receivedmessage["d"]],
"values": [depth 1 values (in any order) of receivedmessage["d"]],
"texts": [a bunch of strings looks through str(receivedmessage["d"])]
},
"s": integer,
"t": string,
"keychecker": ["list","of","keys","in","the","order","which","they","are","nested","in"],
"keyvaluechecker": [["list","of","keys","in","the","order","which","they","are","nested","in"],value_to_check_for]
}
```
Note, both keychecker and keyvaluechecker accept integers in certain situations. For example, if the received dictionary had a list of dictionaries as one of its values. See the example for getting members above.
# 0.2.3
### Changed
- structure of code: all gateway comms are now in the gateway folder, Login.py is now in the login folder
- variable names in gateway/GatewayServer.py to improve code readability (+ added more comments)
- task receive checking (in gateway/GatewayServer.py) to allow more flexibility (you don't have to search for the last received message in a batch of messages anymore. now you just search messages. like normal.). Here's an example use case:
```python
bot._Client__gateway_server.runIt({
1: {
"send": [{
"op": 4,
"d": {
"guild_id": None,
"channel_id": CHANNEL_ID,
"self_mute": False,
"self_deaf": False,
"self_video": False
}
}],
"receive": [
{"t": "VOICE_SERVER_UPDATE"},
{"t": "VOICE_STATE_UPDATE"}
]
}
})
```
note that the order of the receive values do not matter. Whether or not VOICE_STATE_UPDATE comes second (it actually comes first) doesn't matter.
- receive inputs slightly changed to allow for more checking possibilities. Now the format is like such:
```
{
"op": (optional; type int),
"d": {
"keys": (optional; type list of strings),
"values": (optional; list of no set types),
"texts": (optional; type list of strings)
},
"s": (optional; type int),
"t": (optional; type str)
}
```
# 0.2.2
### Added
- connectionTest() added back
- _Client__gateway_server.runIt(data) #for websocket connections
- below is a small tutorial on how to use GatewayServer.py to send custom data to Discord:
- The following initiates a call with a friend and stops the asyncio loop once a message is recieved with event name VOICE_SERVER_UPDATE. Note that you'll need to send a different message to the server to hang up the call.
```python
bot._Client__gateway_server.runIt({
1: {
"send": [{
"op": 4,
"d": {
"guild_id": None,
"channel_id": 21154535154122752,
"self_mute": False,
"self_deaf": False,
"self_video": False
}
}],
"receive": [{
"t": "VOICE_SERVER_UPDATE"
}]
}
})
```
The input for \_Client__gateway_server.runIt is formatted like such:
```
{
1: {
"send": [{...}, {...}, {...}],
"receive": [{...}]
},
2: {
"send": [{...}],
"receive": [{...}, {...}]
}
}
```
tasks are placed in sequencial order (note the 1 and the 2) and are run as such. The 2nd task does not start running until the 1st task has been completed. Each task has "send" and "recieve" sections.
The send section denotes what data to send to the server, and it's value is a list of dicts (https://discord.com/developers/docs/topics/gateway). If there are multiple messages to send to the server, each message will be sent before the "receive" section is checked.
The receive section (a list of dicts) acts like a search function and each dict is formatted like this:
```
{
"op": (optional; type int),
"d": {
"key": (optional; type str or int),
"value": (optional; no set type),
"text": (optional; type str)
},
"s": (optional; type int),
"t": (optional; type str)
}
```
An important note about the receive section: if discord sends you multiple messages at once (that is, one after the other without you sending anything), the receive can only check for the last-sent-message. For example, if discord sends a MESSAGE_UPDATE and then a MESSAGE_CREATE, you can only check for the MESSAGE_CREATE.
As an example, if you'd like to connect to Discord via websockets and never disconnect (until ctrl+c), run the following:
```python
bot._Client__gateway_server.runIt({
1: {
"send": [],
"receive": []
}
})
```
### Changed
- gateway server protocol greatly simplified. now custom data can be sent to discord via websockets and the websocket connection can be stopped when a certain response is received (based off of https://github.com/Gehock/discord-ws)
- discord's api version updated to api v8, so the self.discord variable updated to https://discord.com/api/v8/
### Removed
- erlang.py
## 0.2.1
### Added
- erlang.py (https://github.com/tenable/DiscordClient/blob/master/erlang.py)
- Login.py to handle logging in (https://github.com/tenable/DiscordClient/blob/master/HttpServer.py)
- Logger.py to print detailed log messages (https://github.com/tenable/DiscordClient/blob/master/Logger.py)
- GatewayServer.py to handle gateway interactions (https://github.com/tenable/DiscordClient/blob/master/GatewayServer.py)
- read session data functions (connects via websockets to Discord) (note: it's recommended that you set update to False because connecting to Discord's gateway server more than 1000 times in 1 day could potentially flag your account):
- read(update=True)
- getAnalyticsToken(update=True)
- getConnectedAccounts(update=True)
- getConsents(update=True)
- getExperiments(update=True)
- getFriendSuggestingCount(update=True)
- getGuildExperiments(update=True)
- getGuilds(update=True)
- getGuildIDs(update=True)
- getGuildData(guildID,update=True)
- getGuildOwner(guildID,update=True)
- getGuildBoostLvl(guildID,update=True)
- getGuildEmojis(guildID,update=True)
- getGuildBanner(guildID,update=True)
- getGuildDiscoverySplash(guildID,update=True)
- getGuildUserPresences(guildID,update=True)
- getGuildMsgNotificationSettings(guildID,update=True)
- getGuildRulesChannelID(guildID,update=True)
- getGuildVerificationLvl(guildID,update=True)
- getGuildFeatures(guildID,update=True)
- getGuildJoinTime(guildID,update=True)
- getGuildRegion(guildID,update=True)
- getGuildApplicationID(GuildID,update=True)
- getGuildAfkChannelID(guildID,update=True)
- getGuildIcon(guildID,update=True)
- getGuildName(guildID,update=True)
- getGuildMaxVideoChannelUsers(guildID,update=True)
- getGuildRoles(guildID,update=True)
- getGuildPublicUpdatesChannelID(guildID,update=True)
- getGuildSystemChannelFlags(guildID,update=True)
- getGuildMfaLvl(guildID,update=True)
- getGuildAfkTimeout(guildID,update=True)
- getGuildHashes(guildID,update=True)
- getGuildSystemChannelID(guildID,update=True)
- isGuildLazy(guildID,update=True)
- getGuildNumBoosts(guildID,update=True)
- isGuildLarge(guildID,update=True)
- getGuildExplicitContentFilter(guildID,update=True)
- getGuildSplashHash(guildID,update=True)
- getGuildVoiceStates(guildID,update=True)
- getGuildMemberCount(guildID,update=True)
- getGuildDescription(guildID,update=True)
- getGuildVanityUrlCode(guildID,update=True)
- getGuildPreferredLocale(guildID,update=True)
- getGuildAllChannels(guildID,update=True)
- getGuildCategories(guildID,update=True)
- getGuildCategoryIDs(guildID,update=True)
- getGuildCategoryData(guildID,categoryID,update=True)
- getGuildChannels(guildID,update=True)
- getGuildChannelIDs(guildID,update=True)
- getGuildChannelData(guildID,channelID,update=True)
- getGuildMembers(guildID,update=True)
- getGuildMemberIDs(guildID,update=True)
- getGuildMemberData(guildID,memberID,update=True)
- getNotes(update=True)
- getOnlineFriends(update=True)
- getDMs(update=True)
- getDMIDs(update=True)
- getDMData(DMID,update=True)
- getDMRecipients(DMID,update=True)
- getReadStates(update=True)
- getRelationships(update=True)
- getRelationshipIDs(update=True)
- getRelationshipData(RelationshipID,update=True)
- getFriends(update=True)
- getFriendIDs(update=True)
- getBlocked(update=True)
- getBlockedIDs(update=True)
- getIncomingFriendRequests(update=True)
- getIncomingFriendRequestIDs(update=True)
- getOutgoingFriendRequests(update=True)
- getOutgoingFriendRequestIDs(update=True)
- getSessionID(update=True)
- getTutorial(update=True)
- getUserData(update=True)
- getUserGuildSettings(update=True,guildID=None)
- getUserSettings(update=True)
- getOptionsForUserSettings(update=True)
- getWebsocketVersion(update=True)
- username_to_userID(userdiscriminator)
- userID_to_username(userID)
- searchMessages(guildID,channelID=None,userID=None,mentionsUserID=None,has=None,beforeDate=None,afterDate=None,textSearch=None,afterNumResults=None)
- filterSearchResults(searchResponse)
- typingAction(channelID)
- deleteMessage(channelID, messageID)
- pinMessage(channelID, messageID)
- unPinMessage(channelID, messageID)
- getPins(channelID)
- snowflake_to_unixts(snowflake)
- unixts_to_snowflake(unixts)
### Changed
- init function now accepts email and password or just token. also proxys are now supported
- the following functions now connect via websockets instead of sending a request to discord's http api:
-getDMs()
-getGuilds()
-getRelationships()
### Removed
- connectionTest function
- Accept-Encoding header
## 0.1.1
### Added
- changeName(name)
- setStatus(status)
- setAvatar(imagePath)
- LoginError exception in case you input incorrect email/password credentials
### Changed
- init now accepts email and password instead of token. this allows for more user functions
- self.discord api url now set in init function. this allows for easily updating the code to match discord's http api version
- sendMessage(channgelID, message, embed="", tts=False) now accepts embedded messages and tts messages
- /messages/embed.py: https://github.com/Merubokkusu/Discord-S.C.U.M/wiki/Messages#send-embed
## 0.1.0
### Added
- sendFile(channelID, filelocation,isurl=False,message="")
- /fileparse/fileparse.py for guessing the type of file based on the file's content (used by sendFile)
- getMessage(channelID,num=1) returns messages in a channel or DM
- getDMs().json() returns a list of DMs
- getGuilds().json() returns a list of guilds
- getRelationships().json() returns a list of relationships (friends, blocked, incoming friend requests, outgoing friend requests)
- requestFriend(userID)
- acceptFriend(userID)
- removeRelationship(userID)
- blockUser(userID)
### Changed
- structure of program: instead of having 1 file with all the commands, various commands are organized into various folders and files
- all message-related functions are organized in /messages/
- all file parsing functions are organized in /filetype/
- all user-related functions are organized in /user/
## 0.0.1
### Added
- easily initiate bot by doing bot = discum.Client(token)
- sendMessage(channelID,message)
- connectionTest() tests if your token is valid
| a4a18d8d7ad1b06973fa5e33153239368d8af734 | [
"Markdown",
"Python"
] | 10 | Python | AmoxAmox/Discord-S.C.U.M | 5590cf4c0c05b995cb728ea87fc94670d8e7ddbe | b12d064f23ed796d318a5761692d684c2c4e00af |
refs/heads/master | <repo_name>RazvanRotaru/Backward-Reasoner<file_sep>/eval_func.py
from Lab05 import *
def eval_function(func):
name = get_head(func)
if name == 'get':
return make_const(get(*get_args(func)))
if name == 'compute_triangle':
return make_const(compute_triangle(*get_args(func)))
if name == 'getShortest':
return make_const(getShortest(*get_args(func)))
if name == 'getMiddle':
return make_const(getMiddle(*get_args(func)))
if name == 'getLongest':
return make_const(getLongest(*get_args(func)))
if name == 'compute_pitagoras':
return make_const(compute_pitagoras(*get_args(func)))
def get(T, L):
triangle = get_value(T)
l = get_value(L)
if l == '0':
return str(triangle[0]) + str(triangle[1])
if l == '1':
return str(triangle[1]) + str(triangle[2])
else:
return str(triangle[0]) + str(triangle[2])
def compute_triangle(LA, LB, LC):
a = int(get_value(LA))
b = int(get_value(LB))
c = int(get_value(LC))
ls = [a, b, c]
m = max(ls)
ls.remove(m)
return str(sum(ls) - m)
def getShortest(LA, LB, LC):
a = int(get_value(LA))
b = int(get_value(LB))
c = int(get_value(LC))
ls = [a, b, c]
return str(min(ls))
def getLongest(LA, LB, LC):
a = int(get_value(LA))
b = int(get_value(LB))
c = int(get_value(LC))
ls = [a, b, c]
return max(ls)
def getMiddle(LA, LB, LC):
a = int(get_value(LA))
b = int(get_value(LB))
c = int(get_value(LC))
ls = [a, b, c]
m = max(ls)
ls.remove(m)
m = min(ls)
ls.remove(m)
return str(ls[0])
def compute_pitagoras(LS, LM, LL):
a = int(get_value(LS))
b = int(get_value(LM))
c = int(get_value(LL))
res = a*a + b*b - c*c
return str(res)
<file_sep>/Lab07.py
#!/usr/bin/env python
# coding: utf-8
# # Logica cu predicate (3). Înlănțuire înainte în Sisteme bazate pe reguli
#
# - <NAME>
# - <NAME>
#
# ## 1. Introducere
# ### Scopul laboratorului
#
# Scopul acestui laborator îl reprezintă înțelegerea și implementarea demonstrării teoremelor prin înlănțuire înainte.
#
# ### Clauze definite. Reguli. Fapte
#
# În cadrul acestui laborator vom folosi un tip anume de formule, mai precis **clauze definite**. Acestea sunt clauze Horn cu exact un literal pozitiv.
#
# $$\neg p_1 \vee \neg p_2 \vee \ldots \vee \neg p_N \vee c$$
#
# În scrierea echivalentă:
#
# $$\left( p_1 \wedge p_2 \wedge \ldots \wedge p_N \right) \rightarrow c$$
#
# devine evident ce reprezintă clauzele definite. Ele au o formă asemănătoare regulilor.
#
# Vom numi **regulă** o clauză definită cu cel puțin un literal negativ și vom numi **fapt** o clauză definită cu un singur literal (cel pozitiv).
#
# ### Problema de rezolvat
#
# Problema pe care o vom rezolva astăzi se enunță astfel: *dată fiind o bază de cunoștințe* `kb` *formată din clauze definite (fapte și reguli), să se demonstreze o teoremă* `t`.
# ## 2. Funcții utile din laboratoarele anterioare
#
# ### Cerința 0
#
# Salvați rezolvarea laboratorului 5 (*Reprezentare și Unificare*) cu numele `Lab05.py`. Vom folosi și funcțiile deja implementate din Laboratorul 6. Din acesta, funcțiile importante pentru astăzi sunt:
# - `make_var`, `make_const`, `make_atom` - utile pentru a construi atomi. De exemplu, $$Vreme(maine, Frig)$$ se construiește astfel:
#
# `make_atom("Vreme", make_var("maine"), make_const("Frig"))`
#
# - `unify` și `substitute` - utile pentru calcularea celui mai general unificator pentru două formule și pentru aplicarea unei substituții
# - `is_positive_literal` și `is_negative_literal`
# - `add_statement` - adaugă o clauză definită unei baze de cunoștințe. Avem două variante de utilizare în acest laborator:
# * `add_statement(kb, Atom)` - adaugă în kb faptul Atom
# * `add_statement(kb, C, P1, P2, Pn)` - adaugă în kb regula $\left( p_1 \wedge p_2 \wedge p_N \right) \rightarrow c$ sub forma:
#
# `make_or(make_neg(P1), make_neg(P2), make_neg(Pn), C)`
#
# ### Cerința 1
#
# Faceți următoarea modificare funcției `unify`: antetul funcției
#
# def unify(f1, f2):
# ...
# subst = {}
#
# trebuie transformat astfel încât să primească un al treilea parametru, o substituție de pornire
#
# def unify(f1, f2, subst=None):
# if not subst:
# subst = {}
#
# **Nu uitați** ca după modificarea lui `unify` să descărcați din nou laboratorul 5 ca fișier Python și să dați Kernel restart în acest fișier.
# In[1]:
from Lab05 import make_var, make_and, make_const, make_atom, make_or, make_neg, is_variable, is_sentence, is_constant, is_atom, is_function_call, print_formula, get_args, get_head, get_name, get_value , unify, substitute
from Lab07fct import add_statement, is_positive_literal, is_negative_literal, make_unique_var_names, print_KB
from LPTester import *
# ## 3. Baza de cunoștințe
#
# Să se completeze reprezentarea bazei de cunoștințe de mai jos știind că ea corespunde următoarelor afirmații:
#
# [TODO 2.1:] *Dacă a plouat două zile la rând, a treia zi va fi frumos.* [TODO 2.2:] *Dacă a fost frumos trei zile la rând, în cea de-a patra zi va ploua.* [TODO 2.3:] *Un student merge întotdeauna la munte dacă este frumos într-o zi de weekend. Cine merge la munte și practică un sport de iarnă va avea activități legate de acel sport de iarnă.*
#
# *Arsenie și Nectarie sunt studenți. Arsenie practică volei și schi, iar Nectarie practică schi și sanie. Voleiul este un sport de vară, în timp ce schiul și sania sunt sporturi de iarnă. Vineri plouă; luni, marți și miercuri este frumos*
#
# ### Cerința 2:
#
# Completați mai jos clauzele definite pentru primele 3 propoziții.
# * `add_statement` are ca argumente
# * baza de cunoștințe
# * concluzia
# * premisele (ca argumente individuale)
# In[137]:
def get_sports_kb():
sports_kb = []
# Predicatul 'Consecutive'
add_statement(sports_kb, make_atom('Consecutive', make_const('Luni'), make_const('Marti')))
add_statement(sports_kb, make_atom('Consecutive', make_const('Marti'), make_const('Miercuri')))
add_statement(sports_kb, make_atom('Consecutive', make_const('Miercuri'), make_const('Joi')))
add_statement(sports_kb, make_atom('Consecutive', make_const('Joi'), make_const('Vineri')))
add_statement(sports_kb, make_atom('Consecutive', make_const('Vineri'), make_const('Sambata')))
add_statement(sports_kb, make_atom('Consecutive', make_const('Sambata'), make_const('Duminica')))
# Predicatul 'Weekend'
add_statement(sports_kb, make_atom('Weekend', make_const('Sambata')))
add_statement(sports_kb, make_atom('Weekend', make_const('Duminica')))
# Predicatul 'Ploua'
add_statement(sports_kb, make_atom('Ploua', make_const('Vineri')))
# TODO 2.1: Dacă a plouat două zile la rând, a treia zi va fi frumos.
add_statement(sports_kb, make_atom('Frumos', make_var('day3')), make_atom('Ploua', make_var('day1')),
make_atom('Ploua', make_var('day2')), make_atom('Consecutive', make_var('day1'), make_var('day2')),
make_atom('Consecutive', make_var('day2'), make_var('day3')))
# Predicatul 'Frumos'
add_statement(sports_kb, make_atom('Frumos', make_const('Luni')))
add_statement(sports_kb, make_atom('Frumos', make_const('Marti')))
add_statement(sports_kb, make_atom('Frumos', make_const('Miercuri')))
# TODO 2.2: Dacă a fost frumos trei zile la rând, în cea de-a patra zi va ploua.
add_statement(sports_kb, make_atom('Ploua', make_var('day4')), make_atom('Frumos', make_var('day1')),
make_atom('Frumos', make_var('day2')), make_atom('Frumos', make_var('day3')),
make_atom('Consecutive', make_var('day1'), make_var('day2')), make_atom('Consecutive', make_var('day2'), make_var('day3')),
make_atom('Consecutive', make_var('day3'), make_var('day4')))
# Predicatul 'Student'
add_statement(sports_kb, make_atom('Student', make_const('Nectarie')))
add_statement(sports_kb, make_atom('Student', make_const('Arsenie')))
# MergeLaMunte (cine, cand)
# TODO 2.3: Un student merge întotdeauna la munte dacă este frumos într-o zi de weekend.
add_statement(sports_kb, make_atom('MergeLaMunte', make_var('Student'), make_var('when')), make_atom('Weekend', make_var('when')),
make_atom('Frumos', make_var('when')))
# Predicatul 'SportDeVara'
add_statement(sports_kb, make_atom('SportDeVara', make_const('Volei')))
# Predicatul 'SportDeIarna'
add_statement(sports_kb, make_atom('SportDeIarna', make_const('Schi')))
add_statement(sports_kb, make_atom('SportDeIarna', make_const('Sanie')))
# Predicatul 'PracticaSport'
add_statement(sports_kb, make_atom('PracticaSport', make_const('Nectarie'), make_const('Schi')))
add_statement(sports_kb, make_atom('PracticaSport', make_const('Nectarie'), make_const('Sanie')))
add_statement(sports_kb, make_atom('PracticaSport', make_const('Arsenie'), make_const('Schi')))
add_statement(sports_kb, make_atom('PracticaSport', make_const('Arsenie'), make_const('Volei')))
# Predicatul 'Activitate'
add_statement(sports_kb, make_atom('Activitate', make_var('who'), make_var('what'), make_var('when')),
make_atom('MergeLaMunte', make_var('who'), make_var('when')),
make_atom('PracticaSport', make_var('who'), make_var('what')))
make_unique_var_names(sports_kb)
return sports_kb
# print("Baza de cunoștințe se prezintă astfel:")
# skb = get_sports_kb()
# print_KB(skb)
# print("==================== \n Baza de cunoștințe arată intern astfel:")
# print("" + "".join([(str(s) + "\n") for s in skb]))
# ## 4. Funcții auxiliare
#
# **Cerința 3:** Implementați funcțiile `get_premises`, `get_conclusion`, `is_fact` și `is_rule`. Toate acestea primesc o clauză definită (în baza de cunoștințe dată, poate fi un atom singur sau o disjuncție de literali) și întorc ceea ce specifică numele lor.
# In[138]:
def get_premises(formula):
# TODO
ans = []
for i in get_args(formula):
if is_negative_literal(i):
ans.append(i)
return ans
def get_conclusion(formula):
# TODO
ans = None
for i in get_args(formula):
if is_atom(i):
ans = i
return ans
def is_fact(formula):
# TODO
if is_positive_literal(formula):
return True
return False
def is_rule(formula):
# TODO
for i in get_args(formula):
if is_negative_literal(i):
return True
return False
# # Test!
# # formula: P(x) ^ Q(x) -> R(x)
# x = make_or(make_neg(make_atom('Frumos', make_var('day1'))),
# make_neg(make_atom('Frumos', make_var('day2'))), make_neg(make_atom('Frumos', make_var('day3'))),
# make_neg(make_atom('Consecutive', make_var('day1'), make_var('day2'))), make_neg(make_atom('Consecutive', make_var('day2'), make_var('day3'))),
# make_neg(make_atom('Consecutive', make_var('day3'), make_var('day4'))), make_atom('Ploua', make_var('day4')))
# f = make_or(make_neg(make_atom("P", make_var("x"))), make_neg(make_atom("Q", make_var("x"))), make_atom("R", make_var("x")))
# print(" ; ".join([print_formula(p, True) for p in get_premises(x)])) # Should be P(?x) ; Q(?x)
# print_formula(get_conclusion(f)) # Should be R(?x)
# print(is_rule(f)) # must be True
# print(is_fact(f)) # must be False
# print(is_fact(get_conclusion(f))) # must be True
# print(is_rule(get_conclusion(f))) # must be False
# # In[139]:
def equal_terms(t1, t2):
if is_constant(t1) and is_constant(t2):
return get_value(t1) == get_value(t2)
if is_variable(t1) and is_variable(t2):
return get_name(t1) == get_name(t2)
if is_function_call(t1) and is_function(t2):
if get_head(t1) != get_head(t2):
return all([equal_terms(get_args(t1)[i], get_args(t2)[i]) for i in range(len(get_args(t1)))])
return False
def is_equal_to(a1, a2):
# verificăm atomi cu același nume de predicat și același număr de argumente
if not (is_atom(a1) and is_atom(a2) and get_head(a1) == get_head(a2) and len(get_args(a1)) == len(get_args(a2))):
return False
return all([equal_terms(get_args(a1)[i], get_args(a2)[i]) for i in range(len(get_args(a1)))])
# ## 5. Demonstrarea teoremelor prin înlănțuire înainte
#
# ### Cerința 4
#
# Implementați funcția `apply_rule(rule, facts)` care primește o regulă și un set de fapte și întoarce toate faptele care pot fi determinate prin aplicarea regulii pe faptele date.
#
# Folosiți-vă de `unify`, `substitute`, dar și de `get_premises` și `get_conclusion` implementate mai devreme.
# In[166]:
from copy import deepcopy
# from __future__ import print_function
import itertools
from Lab05 import Sentence, Atom
def apply_rule(rule, facts):
# TODO
subst = {}
prem = {}
ans = []
values = {}
fact_values = {}
for fact in facts:
vals = []
for arg in get_args(fact):
vals.append(get_value(arg))
if get_head(fact) not in values:
values[get_head(fact)] = [tuple(vals)]
else:
values[get_head(fact)].append(tuple(vals))
if get_head(fact) not in fact_values:
fact_values[get_head(fact)] = [fact]
else:
fact_values[get_head(fact)].append(fact)
for r in get_premises(rule):
if isinstance(r, Sentence):
var = get_name(get_args(get_args(r)[0])[0])
prm = get_head(get_args(r)[0])
prem[(prm, var)] = get_args(r)[0]
continue
var = get_name(get_args(r)[0])
prem[(get_head(r), var)] = [r]
index_h = {}
max_index_h = {}
for (pred, var) in prem:
index_h[(pred, var)] = 0
max_index_h[(pred, var)] = 0
if pred in values:
max_index_h[(pred, var)] = len(values[pred])
pred = []
for x in prem:
pred.append(x)
current_p = 0
subst = {}
while 1:
p = pred[current_p]
prd = p[0]
val = p[1]
p_index = index_h[p]
if p_index == max_index_h[p]:
index_h[p] = 0
if current_p == 0:
break
current_p = current_p - 1
p = pred[current_p]
for x in get_args(prem[p]):
name = get_name(x)
if name in subst:
del subst[name]
index_h[p] = index_h[p] + 1
continue
b_subst = deepcopy(subst)
aux_subst = unify(prem[p], fact_values[prd][p_index], subst)
if aux_subst!=False:
subst = aux_subst
if current_p == len(pred) - 1:
ans.append(substitute(get_conclusion(rule),subst))
subst = {}
current_p = 0
next_index = index_h[p] + 1
index_h[p] = next_index
p = pred[current_p]
continue
else:
subst = b_subst
index_h[p] = index_h[p] + 1
if index_h[p] == max_index_h[p]:
index_h[p] = 0
current_p = current_p - 1
index_h[pred[current_p]] = index_h[pred[current_p]] + 1
p = pred[current_p]
for x in get_args(prem[p]):
name = get_name(x)
if name in subst:
del subst[name]
continue
if current_p < len(pred) - 1:
current_p = current_p + 1
continue
index_h[p] = index_h[p] + 1
return ans
# # Test!
# # Rule: P(x) => Q(x)
# # Facts: P(1)
# print("Expected: ", print_formula(make_atom('Q', make_const(1)), True), "Result:")
# for f in apply_rule(
# make_or(make_neg(make_atom("P", make_var("x"))), make_atom("Q", make_var("x"))), \
# [make_atom("P", make_const(1))]):
# print_formula(f) # should be Q(1)
# print("=====")
# # Rule: P(x) ^ Q(x) => R(x)
# # Facts: P(1), P(2), P(3), Q(3), Q(2)
# print("Expected: ", print_formula(make_atom('R', make_const(2)), True), ";",
# print_formula(make_atom('R', make_const(3)), True), "Result:")
# for f in apply_rule(
# make_or(
# make_neg(make_atom("P", make_var("x"))),
# make_neg(make_atom("Q", make_var("x"))),
# make_atom("R", make_var("x"))),
# [make_atom("P", make_const(x)) for x in [1, 2, 3]] + \
# [make_atom("Q", make_const(x)) for x in [3, 2]]):
# print_formula(f) # should be R(2) and R(3)
# print("=====")
# # Rule: P(x) ^ Q(y) ^ R(x, y) => T(x, y)
# # Facts: P(1), P(2), P(3), Q(3), Q(2), R(3, 2)
# print("Expected: ", print_formula(make_atom('T', make_const(3), make_const(2)), True), "Result:")
# for f in apply_rule(
# make_or(
# make_neg(make_atom("P", make_var("x"))),
# make_neg(make_atom("Q", make_var("y"))),
# make_neg(make_atom("R", make_var("x"), make_var("y"))),
# make_atom("T", make_var("x"), make_var("y"))),
# [make_atom("P", make_const(x)) for x in [1, 2, 3]] + \
# [make_atom("Q", make_const(x)) for x in [3, 2]] + \
# [make_atom("R", make_const(3), make_const(2))]):
# print_formula(f) # should be T(3, 2)
# print("=====")
# # Rule: P(x) ^ Q(y) ^ R(x, y, z) => T(z)
# # Facts: P(1), P(2), P(3), Q(3), Q(2), R(1, 1, 1), R(2, 1, 2), R(2, 3, 5), R(4, 2, 3), R(1, 2, 6)
# print("Expected: ", print_formula(make_atom('T', make_const(5)), True), ";",
# print_formula(make_atom('T', make_const(6)), True), "Result:")
# for f in apply_rule(
# make_or(
# make_neg(make_atom("P", make_var("x"))),
# make_neg(make_atom("Q", make_var("y"))),
# make_neg(make_atom("R", make_var("x"), make_var("y"), make_var("z"))),
# make_atom("T", make_var("z"))),
# [make_atom("P", make_const(x)) for x in [1, 2, 3]] + \
# [make_atom("Q", make_const(x)) for x in [3, 2]] + \
# [make_atom("R", make_const(x), make_const(y), make_const(z)) \
# for x, y, z in [(1, 1, 1), (2, 1, 2), (2, 3, 5), (4, 2, 3), (1, 2, 6)]]):
# print_formula(f) # should be T(5) and T(6)
# In[167]:
def forward_chaining(kb, theorem, verbose = True):
# Salvăm baza de date originală, lucrăm cu o copie
local_kb = deepcopy(kb)
# Două variabile care descriu starea căutării
got_new_facts = True # s-au găsit fapte noi la ultima căutare
is_proved = False # a fost demostrată teorema
# Verificăm dacă teorema este deja demonstrată
for fact in filter(is_fact, local_kb):
if unify(fact, theorem):
if verbose: print("This already in KB: " + print_formula(fact, True))
is_proved = True
break
while (not is_proved) and got_new_facts:
got_new_facts = False
for rule in filter(is_rule, local_kb):
# Pentru fiecare regulă
new_facts = apply_rule(rule, list(filter(is_fact, local_kb)))
new_facts = list(filter(lambda fact: not any(list(filter(lambda orig: is_equal_to(fact, orig), local_kb))), new_facts))
if new_facts:
if verbose: print("Applied rule: " + print_formula(rule, True) + ", obtained " + str(len(new_facts)) + " new facts.")
if any(filter(lambda t: is_variable(t), get_args(get_conclusion(rule)))) and any(filter(lambda fact: is_equal_to(fact, get_conclusion(rule)), new_facts)):
print("Demonstration is too general, the conclusion is not instantiated (facts obtained:",
",".join([print_formula(f, True) for f in new_facts]),").")
return False
got_new_facts = True
for fact in new_facts:
#if verbose: print("New fact: " + print_formula(fact, True))
if unify(fact, theorem) != False:
is_proved = True
add_statement(local_kb, fact)
if verbose: print("Now in KB: " + print_formula(fact, True))
break
add_statement(local_kb, fact)
if is_proved:
break
if verbose:
if is_proved:
print("The theorem is TRUE!")
else:
print("The theorem is FALSE!")
return is_proved
# In[168]:
# def test_result(result, truth):
# print("Test OK!" if result == truth else "Test FAILED!")
# test_kb = skb
# print("================== 0")
# test_result(forward_chaining(deepcopy(test_kb), make_atom("Frumos", make_var("x")), True), True)
# print("================== 1")
# test_result(forward_chaining(deepcopy(test_kb), make_atom("Ploua", make_var("x")), True), True)
# print("================== 2")
# test_result(forward_chaining(deepcopy(test_kb), make_atom("Ploua", make_const("Joi")), True), True)
# print("================== 3")
# test_result(forward_chaining(deepcopy(test_kb), make_atom("Frumos", make_const("Sambata")), True), True)
# print("================== 4")
# test_result(forward_chaining(deepcopy(test_kb),
# make_atom("Activitate",
# make_const("Arsenie"), make_var("sport"), make_const("Sambata")), True), True)
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
<file_sep>/Lab05.py
# coding: utf-8
# # Logica cu predicate (1). Reprezentare & Unificare
# - <NAME>
# - <NAME>
#
# ## Scopul laboratorului
#
# Scopul acestui laborator este familiarizarea cu reprezentarea logică a cunoștințelor și cu mecanismele de lucru cu cunoștințe reprezentate prin logica cu predicate de ordinul I (LPOI / FOPL).
#
# În cadrul laboratorului, va fi necesar să vă alegeți o reprezentare internă pentru elementele din FOPL, și apoi să implementați procesul de unificare între două formule din logica cu predicate.
#
#
# #### Resurse
#
# * Cursul 5 de IA, slides 25-27
# * https://en.wikipedia.org/wiki/Unification_(computer_science)#Examples_of_syntactic_unification_of_first-order_terms
# * algoritmul lui Robinson (vezi pdf)
#
# ## Reprezentare
#
# În LPOI trebuie să putem reprezenta următoarele elemente:
# * _termen_ -- poate fi luat ca argument de către un predicat. Un termen poate fi:
# * o constantă -- are o valoare
# * o variabilă -- are un nume și poate fi legată la o valoare
# * un apel de funcție -- are numele funcției și argumentele (e.g. add[1, 2, 3]). Se evaluează la o valoare. Argumentele funcției sunt tot termeni.
# * Notă: În text vom scrie apelurile de funcții cu paranteze drepte, pentru a le deosebi de atomi.
# * _formulă (propoziție) logică_ -- se poate evalua la o valoare de adevăr, într-o interpretare (o anumită legare a numelor la o semantică). O formulă poate fi:
# * un atom -- aplicarea unui predicat (cu un nume) peste o serie de termeni (argumentele sale)
# * negarea unei formule
# * un conector logic între două propoziții -- conjuncție sau disjuncție
#
#
# ### Cerința 1
#
# Creați o reprezentare internă pentru formule logice. Pentru această reprezentare, vom avea:
# * o serie de funcții care o construiesc -- `make_*` și `replace_args`
# * o serie de funcții care o verifică -- `is_*`
# * o serie de funcții care accesează elementele din reprezentare -- `get_*`
#
#
# **Important:** Pentru a lucra mai ușor cu formulele, vom considera că pentru apelurile de funcții și pentru toate formulele (atât atomi cât și propoziții compuse), reprezentarea are un _head_ (după caz, numele funcției, numele predicatului, sau conectorul logic) și o listă de argumente (după caz, lista de argumente a funcției, lista de argumente a predicatului, o listă cu propoziția negată, sau lista de propoziții unite de conectorul logic (2 sau mai multe)).
#
# **Notă:** la început, implementați funcțiile de verificare ca și cum argumentele date are fi reprezentate corect (deci doar pentru a deosebi între diversele tipuri de reprezentare). Ulterior, verificați și ca argumentele date să fie într-adevăr corect reprezentate.
# In[3]:
from operator import add
from copy import deepcopy
# from Lab05tester import test_batch
# In[17]:
### Reprezentare - construcție
class Constant:
def __init__(self, value):
self.value = value
def __eq__(self, other):
"""Overrides the default implementation"""
if isinstance(other, Constant):
return self.value == other.value
return False
def print_self(self):
print(self.value)
class Variable:
def __init__(self, name, value = 0):
self.name = name
self.value = value
def __eq__(self, other):
"""Overrides the default implementation"""
if isinstance(other, Variable):
return self.name == other.name
return False
def print_self(self):
print(self.name + " = " + self.value)
class Function:
def __init__(self, function, args):
self.args = deepcopy(args)
self.function = function
def __eq__(self, other):
"""Overrides the default implementation"""
if isinstance(other, Function):
return self.function == other.function and self.args == other.args
return False
class Atom:
def __init__(self, predicate, args):
self.args = deepcopy(args)
self.predicate = predicate
def __eq__(self, other):
"""Overrides the default implementation"""
if isinstance(other, Atom):
return self.predicate == other.predicate and self.args == other.args
return False
class Sentence:
def __init__(self, atoms, args, neg = False):
self.atoms = deepcopy(atoms)
self.args = deepcopy(args)
self.neg = neg
def __eq__(self, other):
"""Overrides the default implementation"""
if isinstance(other, Sentence):
return self.args == other.args and self.atoms == other.atoms and self.neg == other.neg
return False
# întoarce un termen constant, cu valoarea specificată.
def make_const(value):
# TODO
const = Constant(value)
return const
# întoarce un termen care este o variabilă, cu numele specificat.
def make_var(name):
# TODO
var = Variable(name)
return var
# întoarce un termen care este un apel al funcției specificate, pe restul argumentelor date.
# E.g. pentru a construi termenul add[1, 2, 3] vom apela make_function_call(add, 1, 2, 3)
# !! ATENȚIE: python dă args ca tuplu cu restul argumentelor, nu ca listă. Se poate converti la listă cu list(args)
def make_function_call(function, *args):
# TODO
func = Function(function, list(args))
return func
# întoarce o formulă formată dintr-un atom care este aplicarea predicatului dat pe restul argumentelor date.
# !! ATENȚIE: python dă args ca tuplu cu restul argumentelor, nu ca listă. Se poate converti la listă cu list(args)
def make_atom(predicate, *args):
# TODO
pred = Atom(predicate, list(args))
return pred
# întoarce o formulă care este negarea propoziției date.
# get_args(make_neg(s1)) va întoarce [s1]
def make_neg(sentence):
# TODO
args = []
atoms = [sentence]
s = Sentence(atoms, args, True)
return s
# întoarce o formulă care este conjuncția propozițiilor date (2 sau mai multe).
# e.g. apelul make_and(s1, s2, s3, s4) va întoarce o structură care este conjuncția s1 ^ s2 ^ s3 ^ s4
# și get_args pe această structură va întoarce [s1, s2, s3, s4]
def make_and(sentence1, sentence2, *others):
# TODO
args = ["A"]
atoms = [sentence1, sentence2]
for i in others:
atoms.append(i)
s = Sentence(atoms, args)
return s
# întoarce o formulă care este disjuncția propozițiilor date.
# e.g. apelul make_or(s1, s2, s3, s4) va întoarce o structură care este disjuncția s1 V s2 V s3 V s4
# și get_args pe această structură va întoarce [s1, s2, s3, s4]
def make_or(sentence1, sentence2, *others):
# TODO
args = ["V"]
atoms = [sentence1, sentence2]
for i in others:
atoms.append(i)
s = Sentence(atoms, args)
return s
# întoarce o copie a formulei sau apelul de funcție date, în care argumentele au fost înlocuite
# cu cele din lista new_args.
# e.g. pentru formula p(x, y), înlocuirea argumentelor cu lista [1, 2] va rezulta în formula p(1, 2).
# Noua listă de argumente trebuie să aibă aceeași lungime cu numărul de argumente inițial din formulă.
def replace_args(formula, new_args):
# TODO
if isinstance(formula, Atom):
new_atom_pred = formula.predicate
formula = Atom(new_atom_pred, new_args)
if isinstance(formula, Function):
new_func = formula.function
formula = Function(new_func, new_args)
if isinstance(formula, Sentence):
new_sthings = formula.args
is_neg = formula.neg
formula = Sentence(new_args, new_sthings, is_neg)
return formula
### Reprezentare - verificare
# întoarce adevărat dacă f este un termen.
def is_term(f):
return is_constant(f) or is_variable(f) or is_function_call(f)
# întoarce adevărat dacă f este un termen constant.
def is_constant(f):
# TODO
return isinstance(f, Constant)
# întoarce adevărat dacă f este un termen ce este o variabilă.
def is_variable(f):
# TODO
return isinstance(f, Variable)
# întoarce adevărat dacă f este un apel de funcție.
def is_function_call(f):
# TODO
return isinstance(f, Function)
# întoarce adevărat dacă f este un atom (aplicare a unui predicat).
def is_atom(f):
# TODO
return isinstance(f, Atom)
# întoarce adevărat dacă f este o propoziție validă.
def is_sentence(f):
# TODO
return isinstance(f, Sentence) or isinstance(f, Atom)
# întoarce adevărat dacă formula f este ceva ce are argumente.
def has_args(f):
return is_function_call(f) or is_sentence(f)
### Reprezentare - verificare
# pentru constante (de verificat), se întoarce valoarea constantei; altfel, None.
def get_value(f):
# TODO
if isinstance(f, Constant):
return f.value
return None
# pentru variabile (de verificat), se întoarce numele variabilei; altfel, None.
def get_name(f):
# TODO
if isinstance(f, Variable):
return f.name
return None
# pentru apeluri de funcții, se întoarce funcția;
# pentru atomi, se întoarce numele predicatului;
# pentru propoziții compuse, se întoarce un șir de caractere care reprezintă conectorul logic (e.g. ~, A sau V);
# altfel, None
def get_head(f):
# TODO
if isinstance(f, Function):
return f.function
if isinstance(f, Atom):
return f.predicate
if isinstance(f, Sentence):
return "".join(f.args)
return None
# pentru propoziții sau apeluri de funcții, se întoarce lista de argumente; altfel, None.
# Vezi și "Important:", mai sus.
def get_args(f):
# TODO
if isinstance(f, Function):
return f.args
if isinstance(f, Sentence):
return f.atoms
if isinstance(f, Atom):
return f.args
return []
# test_batch(0, globals())
# In[18]:
# Afișează formula f. Dacă argumentul return_result este True, rezultatul nu este afișat la consolă, ci întors.
def print_formula(f, return_result = False, indent = 0, verbose = True):
if not verbose:
return
ret = "\t" * indent
if is_term(f):
if is_constant(f):
ret += str(get_value(f))
elif is_variable(f):
ret += "?" + get_name(f)
elif is_function_call(f):
ret += str(get_head(f)) + "[" + "".join([print_formula(arg, True) + "," for arg in get_args(f)])[:-1] + "]"
else:
ret += "???"
elif is_atom(f):
ret += str(get_head(f)) + "(" + "".join([print_formula(arg, True) + ", " for arg in get_args(f)])[:-2] + ")"
elif is_sentence(f):
# negation, conjunction or disjunction
args = get_args(f)
if len(args) == 1:
ret += str(get_head(f)) + print_formula(args[0], True)
else:
ret += "(" + str(get_head(f)) + "".join([" " + print_formula(arg, True) for arg in get_args(f)]) + ")"
else:
ret += "???"
if return_result:
return ret
print(ret)
return
# Verificare construcție și afișare
# Ar trebui ca ieșirea să fie similară cu: (A (V ~P(?x) Q(?x)) T(?y, <built-in function add>[1,2]))
# formula1 = make_and(
# make_or(make_neg(make_atom("P", make_var("x"))), make_atom("Q", make_var("x"))),
# make_atom("T", make_var("y"), make_function_call(add, make_const(1), make_const(2))))
# print_formula(formula1)
# ## Unificare
#
# Unificarea a două formule logice ce conțin variabile înseamnă găsirea unei substituții astfel încât aplicarea acesteia pe cele două formule să rezulte în două formule identice.
#
# O substituție conține asocieri de variabile la termeni. La aplicarea unei substituții, variabilele care apar în substituție sunt înlocuite, în formulă, cu termenii asociați, până când nu se mai poate face nicio înlocuire.
# In[19]:
# Aplică în formula f toate elementele din substituția dată și întoarce formula rezultată
def substitute(f, substitution):
if substitution is None:
return None
if is_variable(f) and (get_name(f) in substitution):
return substitute(substitution[get_name(f)], substitution)
if has_args(f):
return replace_args(f, [substitute(arg, substitution) for arg in get_args(f)])
return f
def test_formula(x, copyy = False):
fun = make_function_call(add, make_const(1), make_const(2))
return make_and(make_or(make_neg(make_atom("P", make_const(x))), make_atom("Q", make_const(x))), make_atom("T", fun if copyy else make_var("y"), fun))
# Test (trebuie să se vadă efectele substituțiilor în formulă)
# test_batch(1, globals())
# ### Cerința 2
#
# Implementați funcțiile `occur_check` și `unify`, conform algoritmului lui Robinson (vezi pdf).
# In[39]:
# Verifică dacă variabila v apare în termenul t, având în vedere substituția subst.
# Întoarce True dacă v apare în t (v NU poate fi înlocuită cu t), și False dacă v poate fi înlocuită cu t.
def occur_check(v, t, subst):
# TODO
if isinstance(t, Function) and (v in get_args(t)):
return True
if isinstance(t, Variable) and v == t:
return True
elif isinstance(t, Variable) and (t.name in subst):
return occur_check(v, substitute(t, subst), subst)
elif isinstance(t, Function):
for i in t.args:
if occur_check(v, i, subst):
return True
return False
# Test!
# test_batch(2, globals())
# In[65]:
# Unifică formulele f1 și f2, sub o substituție existentă subst.
# Rezultatul unificării este o substituție (dicționar nume-variabilă -> termen),
# astfel încât dacă se aplică substituția celor două formule, rezultatul este identic.
def unify(f1, f2, subst = None):
S = []
S.append([f1, f2])
# print('unify primeste')
# print_formula(f1)
# print_formula(f2 )
if subst is None:
subst = {}
# TODO
while S:
aux = S.pop()
s = aux[0]
t = aux[1]
while isinstance(s, Variable) and (s.name in subst):
# print_formula(s)
s = substitute(s, subst)
# print_formula(s)
while isinstance(t, Variable) and (t.name in subst):
t = substitute(t, subst)
# print('====')
# print_formula(s)
# print_formula(t)
# print('====')
# print(s==t)
# print(not s.__eq__(t))
if not s.__eq__(t):
# print('vvvv')
# print_formula(s)
# print_formula(t)
# print('^^^^')
# print('diferite')
if isinstance(s, Variable):
if occur_check(s, t, subst):
return False
else:
subst.__setitem__(s.name,t)
elif isinstance(t, Variable):
if occur_check(t, s, subst):
return False
else:
subst.__setitem__(t.name,s)
elif has_args(s) and has_args(t):
if get_head(s) == get_head(t):
args_s = get_args(s)
args_t = get_args(t)
for i in range(0, len(args_s)):
S.append([args_s[i], args_t[i]])
else:
return False
else:
return False
return subst
# Test!
# test_batch(3, globals())
<file_sep>/RotaruRazvan29.py
from Lab05 import *
from Lab07fct import *
from Lab07 import *
from eval_func import *
import sys
def concat_lists_of_dict(l1, l2):
ans = []
new_el = {}
for e1 in l1:
for e2 in l2:
cont = False
new_el = deepcopy(e1)
for key in e2:
if key in e1:
if not e1[key].__eq__(e2[key]):
cont = True
new_el[key] = e2[key]
if cont == False:
ans.append(new_el)
return ans
def get_partial_substitution(subst, theorem):
partial_subst = {}
for var in filter(is_variable, get_args(theorem)):
if get_name(var) in subst:
partial_subst[get_name(var)] = subst[get_name(var)]
for fct in filter(is_function_call, get_args(theorem)):
for var in get_args(fct):
if get_name(var) in subst:
partial_subst[get_name(var)] = subst[get_name(var)]
return partial_subst
def add_coef(kb, coef, conclusion, *hypotheses):
s = conclusion if not hypotheses else make_or(*([make_neg(s) for s in hypotheses] + [conclusion]))
# if check_sentence(s):
kb.append([s, coef])
return
def get_coef(kb, theorem):
for elm in kb:
if theorem == elm[0]:
return elm[1]
return None
def print_substitution(subst, indent = 0, verbose = True):
if not verbose:
return
ret = '\t' * indent
ret += '{'
for key in subst:
if isinstance(subst[key], Constant):
ret += str(key) + ' -> ' + str(get_value(subst[key]))
else:
ret += str(key) + ' -> ' + str(get_name(subst[key]))
ret += ', '
ret = ret[:-2]
ret += '}'
print(ret)
return
def print_indent(string, indent = 0, verbose = True):
if not verbose:
return
ret = '\t' * indent
ret += string
print(ret)
return
def add_cond(condition):
if condition == '':
return
if condition[0] == '?':
return make_var(condition[1:])
else:
return make_const(condition)
def get_variables(atom):
vrs = []
if has_args(atom):
for arg in get_args(atom):
if is_constant(arg):
continue
if is_variable(arg):
vrs.append(get_name(arg))
if is_sentence(arg):
aux_vrs = get_variables(arg)
for elm in aux_vrs:
vrs.append(elm)
return vrs
def has_variables(atom):
if get_variables(atom) == []:
return False
return True
def can_evaluate(function):
for arg in get_args(function):
if not is_constant(arg):
return False
return True
def create_atom(atom_str):
atom_name = atom_str[:atom_str.find('(')]
cond_str = atom_str[atom_str.find('(') + 1: atom_str.find(')')]
aux_cond = [x.strip() for x in cond_str.split(',')]
if cond_str == '':
aux_cond = []
atom_conditions = []
for condition in aux_cond:
atom_conditions.append(add_cond(condition))
return make_atom(atom_name, *atom_conditions)
def create_function(func_str):
dp = func_str.find('(')
name = func_str[:dp]
func_str = func_str[dp+1:]
terms = create_terms(func_str)[0]
func = make_function_call(name, *terms)
return func
def create_terms(terms_str):
will_break = False
ret = []
while not will_break:
dp = terms_str.find('(')
ip = terms_str.find(')')
if dp >= 0 and dp < ip:
ret.append(create_function(terms_str[:ip+1]))
terms_str = terms_str[ip+1:]
continue
vp = terms_str.find(',')
if vp < 0:
will_break = True
np = ip
elif ip >= 0 and ip >= vp:
np = vp
else:
will_break = True
np = ip
curr_term = terms_str[:np]
terms_str = terms_str[np + 1:]
if not curr_term:
continue
ret.append(add_cond(curr_term))
return [ret, terms_str]
def create_condition(atom_str):
cond = []
while atom_str:
if atom_str[0] == ',':
atom_str = atom_str[1:]
fd = atom_str.find('(')
name = atom_str[:fd].strip(' ')
atom_str = atom_str[fd+1:]
[terms, atom_str] = create_terms(atom_str)
# terms = ret[0]
# atom_str = ret[1]
cond.append(make_atom(name, *terms))
return cond
def unify_substitution(subst):
to_del = []
for key in subst:
if is_variable(subst[key]):
name = get_name(subst[key])
if name in subst:
subst[key] = subst[name]
to_del.append(name)
for name in to_del:
del subst[name]
return subst
def contains(list1, subst):
for elm in list1:
same = True
for key in elm:
if key in subst:
if not elm[key].__eq__(subst[key]):
same = False
if same:
return True
return False
def unique_substitutions(list1):
unique_list = []
for elm in list1:
if contains(unique_list, elm):
continue
unique_list.append(elm)
return unique_list
def unique(list1):
# intilize a null list
unique_list = []
# traverse for all elements
for x in list1:
# check if exists in unique_list or not
if x not in unique_list:
unique_list.append(x)
return unique_list
def recursive_bc(kb, goal, substitutions, indent = 0, verbose = False, val = 0):
resolved = [[False]] * len(substitutions)
ans = []
no_ans = True
ret = 0
print_indent('Solving', indent, verbose)
print_formula(goal[0], False, indent, verbose)
# for s in substitutions:
# print_substitution(s, indent, verbose)
func_found = False
goal_args = get_args(goal[0])
for i in range(len(goal_args)):
if is_function_call(goal_args[i]):
if not can_evaluate(goal_args[i]):
continue
func_found = True
goal_args[i] = eval_function(goal_args[i])
if func_found:
replace_args(goal[0], goal_args)
print_indent('After evalating the function the goal becomes:', indent, verbose)
print_formula(goal[0], False, indent, verbose)
for subst_index in range(len(substitutions)):
subst = substitutions[subst_index]
sub_goal = deepcopy(goal[0])
partial_subst = {}
# for var in filter(is_variable, get_args(sub_goal)):
# if get_name(var) in subst:
# partial_subst[get_name(var)] = subst[get_name(var)]
partial_subst = get_partial_substitution(subst, sub_goal)
if partial_subst:
print_indent('', indent, verbose)
print_indent('<><><><><><><><><><><><><><><><>', indent, verbose)
print_indent('Applying substitution ' + str(subst_index + 1) + ' of ' + str(len(substitutions)), indent, verbose)
print_substitution(partial_subst, indent, verbose)
print_indent('V V V V V V V V V V V', indent, verbose)
sub_goal = substitute(sub_goal, partial_subst)
func_found = False
goal_args = get_args(sub_goal)
for i in range(len(goal_args)):
if is_function_call(goal_args[i]):
if not can_evaluate(goal_args[i]):
continue
func_found = True
goal_args[i] = eval_function(goal_args[i])
if func_found:
print_indent('After evalating the function the subgoal becomes:', indent, verbose)
replace_args(sub_goal, goal_args)
print_formula(sub_goal, False, indent, verbose)
aux_subst = []
modified = False
print_indent('', indent, verbose)
print_indent('Checking for facts that unifies the goal', indent, verbose)
for fact in filter(is_fact, kb):
# f = deepcopy(partial_subst)
res = unify(sub_goal, fact)
if res != False:
if not modified:
print_indent('Found facts:', indent, verbose)
print_formula(fact, False, indent, verbose)
if use_coef:
aux_coef = get_coef(coefs, fact)
print_indent('with coefficient: ' + str(aux_coef), indent, verbose)
return aux_coef
if res != True:
res = unify_substitution(res)
aux_subst.append(res)
modified = True
continue
return True
if modified:
no_ans = False
aux_ans = concat_lists_of_dict([subst], aux_subst)
for a in aux_ans:
if a not in ans:
ans.append(a)
else:
print_indent('No fact found', indent, verbose)
# # ca sa mearga L3 si L4
if (not modified) or has_variables(sub_goal):
# if True:
substitutions_bckp = deepcopy(substitutions)
print_indent('', indent, verbose)
print_indent('Checking for rules that unifies the goal', indent, verbose)
visited = []
found_rule = False
for rule in filter(is_rule, kb):
substitutions = substitutions_bckp
new_args = {}
if has_args(sub_goal) and has_args(rule):
rule_vars = get_variables(rule)
goal_vars = get_variables(sub_goal)
for elm in rule_vars:
if elm in goal_vars:
new_name = str(elm) + '_dup42'
new_args[elm] = make_var(new_name)
rule = substitute(rule, new_args)
aux_subst = unify(get_conclusion(rule), sub_goal, subst)
if aux_subst == False:
continue
if rule in visited:
continue
visited.append(rule)
found_rule = True
subst = aux_subst
print_indent('Found rule:', indent, verbose)
print_indent('-------------------------------------------', indent, verbose)
print_formula(rule, False, indent, verbose)
print_indent('-------------------------------------------', indent, verbose)
if use_coef:
val = get_coef(coefs, rule)
l = [val] * len(get_premises(rule))
print_indent('with coefficient: ' + str(val), indent, verbose)
print_indent('', indent, verbose)
if subst:
print_indent('Applying substitution:', indent, verbose)
print_substitution(subst, indent, verbose)
new_goal = get_premises(rule)
resolved[subst_index] = [False] * len(new_goal)
aux_substitutions = [{}]
modified = False
for i in range(len(new_goal)):
prem = new_goal[i]
prem = substitute(prem, subst)
print_indent('Trying to prove premise ' + str(i + 1) + ' of ' + str(len(new_goal)), indent, verbose)
print_formula(prem, False, indent, verbose)
if is_sentence(prem):
prem = get_args(prem)[0]
if use_coef:
bc_coef = get_coef(coefs, prem)
print_indent('-> -> -> ->', indent, verbose)
sbs = deepcopy(aux_substitutions)
aux = recursive_bc(kb, [prem], sbs, indent + 1, verbose)
print_indent('<- <- <- <-', indent, verbose)
if aux == False:
print_indent("Premise couldn't be proved", indent, verbose)
print_indent("Rule doesn't match the goal", indent, verbose)
break
print_indent("PROVED", indent, verbose)
resolved[subst_index][i] = True
if use_coef:
l[i] = l[i] * aux
print_indent('Updated coefficient is: ' + str(l[i]), indent, verbose)
# print_indent(str(l), indent, verbose)
continue
if aux != [{}]:
print_indent('Updated substitution', indent, verbose)
for elm in aux:
print_substitution(elm, indent, verbose)
print_indent('', indent, verbose)
aux_substitutions = aux
if False not in resolved[subst_index]:
no_ans = False
print_indent('Rule proved', indent, verbose)
if use_coef:
minl = min(l)
print_indent('Minimum coefficient from premises: ' + str(minl), indent, verbose)
# print_indent(str(l), indent, verbose)
print_indent('Computing new coefficient of goal... ', indent, verbose)
ret = ret + minl - ret*minl
print_indent('\t' + str(ret), indent, verbose)
aux_substitutions = concat_lists_of_dict([substitutions[subst_index]], aux_substitutions)
for elm in aux_substitutions:
if elm not in ans:
ans.append(elm)
if not found_rule:
print_indent('No rule found', indent, verbose)
if use_coef:
return ret
if no_ans:
return False
ans = unique_substitutions(ans)
return ans
def backward_chaining(kb, theorem, verbose = False):
goal = [theorem]
coef = get_coef(coefs, goal)
ans = recursive_bc(kb, goal, [{}], 0, verbose, coef)
return ans
use_coef = False
verbose = False
if len(sys.argv) > 2:
if '-v' in sys.argv:
verbose = True
if '-c' in sys.argv:
use_coef = True
skb = []
ikb = []
coefs = []
f = open(sys.argv[1])
for line in f:
if line.isspace():
continue
if line[0] == ':' or line[0] == '%' or line[0] == '#':
continue
line = "".join(line.split(' '))
line.rstrip()
if use_coef:
index = line.find('%')
if index == -1:
coef = 1
else:
coef = float(line[index+1:].rstrip())
line = line[:index]
if line[0] == '?':
# print('interogare :')
aux = (line.strip('?')).strip(' ')
interogation = create_atom(aux)
add_statement(ikb, interogation)
line = line.strip('\n')
e_interogare = 0
if line[0] == '?':
e_interogare = 1
result = [x.rstrip() for x in line.split(':')]
e_afirmatie = 0
if len(result) > 1:
e_afirmatie = 1
# print(line)
if e_afirmatie == 0 and e_interogare == 0:
aux_str = result[0]
atom = create_atom(aux_str)
add_statement(skb, atom)
if use_coef:
coefs.append([atom, coef])
if e_afirmatie == 1 and e_interogare == 0:
conclusion = create_atom(result[0])
premises = create_condition(result[1])
# premises_str = [(x.strip(')') + ')').strip(' ') for x in result[1].split('),')]
# print(premises_str)
args = [conclusion]
# print(len(args))
for premise in premises:
args.append(premise)
# print(args)
add_statement(skb, *args)
if use_coef:
add_coef(coefs, coef, *args)
print("Printing Knowledge Base:")
# skb = get_sports_kb()
print_KB(skb)
print("")
print("Printing Intergoation Base:")
print_KB(ikb)
for i in range(len(ikb)):
print("---------------------------------")
print("for: ")
print_formula(ikb[i])
print("---------------------------------")
ans = backward_chaining(skb, ikb[i], verbose)
if use_coef:
if ans == 0:
print False
continue
print(ans)
continue
if ans != True and ans != False:
for index in range(len(ans)):
ans[index] = get_partial_substitution(ans[index], ikb[i])
if ans == [{}]:
print('True')
continue
for x in ans:
print_substitution(x)
else:
print(ans) | 5e0343918344291a19922e16b63899afa6692068 | [
"Python"
] | 4 | Python | RazvanRotaru/Backward-Reasoner | ad4a071a086a4efb350a7a5d1e7f4f160ea6c5ac | ea9e097ccc993b4bbd4ac651eca60093da575846 |
refs/heads/master | <file_sep>package com.tc.spring.framework.aop.aspect;
import com.tc.spring.framework.aop.intercept.TCMethodInterceptor;
import com.tc.spring.framework.aop.intercept.TCMethodInvocation;
import java.lang.reflect.Method;
/**
* @author taosh
* @create 2019-09-14 15:04
*/
public class TCMethodBefreAdviceInterceptor extends TCAbstractAspectAdvice implements TCMethodInterceptor {
private TCJoinPoint joinPoint;
public TCMethodBefreAdviceInterceptor(Method aspectMethod, Object aspectObject) {
super(aspectMethod, aspectObject);
}
private void befor(Method method, Object[] args, Object target) throws Throwable {
//传送给织入的参数
// method.invoke(target);
super.invokeAdviceMethod(this.joinPoint, null, null);
}
public Object invoke(TCMethodInvocation invocation) throws Throwable {
//从被织入的代码中拿到,JoinPoint
this.joinPoint = invocation;
befor(invocation.getMethod(), invocation.getArguments(), invocation.getThis());
return invocation.proceed();
}
}
<file_sep>package com.tc.spring.framework.context.support;
/**
* @author taosh
* @create 2019-08-05 21:45
*/
public abstract class TcAbstractApplicationContext {
/**受保护的,只提供给子类去重写*/
protected void refresh() throws Exception {}
}
<file_sep>package com.tc.spring.demo.service.impl;
import com.tc.spring.demo.service.IQueryService;
import com.tc.spring.framework.annotation.TCService;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author taosh
* @create 2019-08-09 16:52
*/
@TCService
public class QueryService implements IQueryService {
public String query(String name) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = sdf.format(new Date());
String json = "{name:\""+name+"\",time:\""+time+"\"}";
return json;
}
}
<file_sep>package com.tc.spring.framework.beans;
/**
* @author taosh
* @create 2019-08-08 17:41
*/
public class TCBeanWrapper {
private Object wrappedInstance;
private Class<?> wrappedClass;
public TCBeanWrapper(Object wrappedInstance) {
this.wrappedInstance = wrappedInstance;
}
public Object getWrappedInstance(){
return this.wrappedInstance;
}
public Class<?> getWrappedClass(){
return this.wrappedInstance.getClass();
}
}
<file_sep>db2018.mysql.jdbc.driverClassName=com.mysql.cj.jdbc.Driver
db2018.mysql.jdbc.url=jdbc:mysql://127.0.0.1:3306/spring-db-2018?useUnicode=true&serverTimezone=GMT%2B8&characterEncoding=UTF-8&useSSL=false
db2018.mysql.jdbc.username=root
db2018.mysql.jdbc.password=<PASSWORD>
db2018.mysql.jdbc.type=com.alibaba.druid.pool.DruidDataSource
db2019.mysql.jdbc.driverClassName=com.mysql.cj.jdbc.Driver
db2019.mysql.jdbc.url=jdbc:mysql://127.0.0.1:3306/spring-db-2019?useUnicode=true&serverTimezone=GMT%2B8&characterEncoding=UTF-8&useSSL=false
db2019.mysql.jdbc.username=root
db2019.mysql.jdbc.password=<PASSWORD>
db2019.mysql.jdbc.type=com.alibaba.druid.pool.DruidDataSource
druid.initialSize=10
druid.minIdle=10
druid.maxActive=50
druid.maxWait=60000
druid.timeBetweenEvictionRunsMillis=60000
druid.minEvictableIdleTimeMillis=300000
druid.validationQuery=SELECT '1' FROM DUAL
druid.testWhileIdle=true
druid.testOnBorrow=true
druid.testOnReturn=true
druid.poolPreparedStatements=true
druid.maxPoolPreparedStatementPerConnectionSize=20
druid.filters=wall,stat,log4j<file_sep>package com.tc.spring.framework.aop;
import com.tc.spring.framework.aop.support.TCAdvisedSupport;
/**
* @author taosh
* @create 2019-09-14 11:09
*/
public class TCCglibAopProxy implements TCAopProxy{
public Object getProxy() {
return null;
}
public Object getProxy(ClassLoader classLoader) {
return null;
}
public TCCglibAopProxy(TCAdvisedSupport support) {
}
}
<file_sep>package com.tc.orm.demo.dao;
import com.tc.orm.demo.entity.Order;
import com.tc.orm.framework.BaseDaoSupport;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
import javax.core.common.jdbc.datasource.DynamicDataSource;
import javax.sql.DataSource;
import java.text.SimpleDateFormat;
import java.util.Date;
@Repository
public class OrderDao extends BaseDaoSupport<Order, Long> {
private SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
private SimpleDateFormat fullDataFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private DynamicDataSource dataSource;
@Override
protected String getPKColumn() {return "id";}
@Override
@Resource(name="dynamicDataSource")
public void setDataSource(DataSource dataSource) {
this.dataSource = (DynamicDataSource)dataSource;
this.setDataSourceReadOnly(dataSource);
this.setDataSourceWrite(dataSource);
}
/**
* @throws Exception
*
*/
public boolean insertOne(Order order) throws Exception{
//约定优于配置
Date date = null;
if(order.getCreateTime() == null){
date = new Date();
order.setCreateTime(date.getTime());
}else {
date = new Date(order.getCreateTime());
}
Integer dbRouter = Integer.valueOf(yearFormat.format(date));
System.out.println("自动分配到【DB_" + dbRouter + "】数据源");
this.dataSource.getDataSourceEntry().set(dbRouter);
order.setCreateTimeFmt(fullDataFormat.format(date));
Long orderId = super.insertAndReturnId(order);
order.setId(orderId);
return orderId > 0;
}
}
<file_sep>package com.tc.spring.framework.aop.aspect;
import java.lang.reflect.Method;
/**
* @author taosh
* @create 2019-09-14 16:58
*/
public interface TCJoinPoint {
Object getThis();
Object[] getArguments();
Method getMethod();
void setUserAttribute(String key, Object value);
Object getUserAttribute(String key);
}
<file_sep>package javax.core.common.jdbc.datasource;
import lombok.Data;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
* @author taosh
* @create 2019-10-08 17:57
*/
@Data
public class DynamicDataSource extends AbstractRoutingDataSource {
/**
* entry的目的,主要是用来给每个数据源打标记
*/
private DynamicDataSourceEntry dataSourceEntry;
@Override
protected Object determineCurrentLookupKey() {
return this.dataSourceEntry.get();
}
}
<file_sep>package com.tc.spring.demo.aspect;
/**
* @author taosh
* @create 2019-08-29 11:11
*/
public class LogAspect {
public void before(){
//往对象里记录一下调用的开始时间
}
public void after(){
//往对象里记录一下调用的结束时间-开始时间
}
public void afterThrowing(){
}
}
<file_sep>package com.tc.spring.framework.aop.config;
import lombok.Data;
/**
* @author taosh
* @create 2019-09-14 14:32
*/
@Data
public class TCAopConfig {
private String pointCut;
private String aspectBefore;
private String aspectAfter;
private String aspectClass;
private String aspectAfterThrow;
private String aspectAfterThrowingName;
}
<file_sep>package com.tc.spring.demo.service;
/**
* @author taosh
* @create 2019-08-09 16:47
*/
public interface IModifyService {
/**
* 增加
*/
public String add(String name, String addr) throws Exception;
/**
* 修改
*/
public String edit(Integer id, String name);
/**
* 删除
*/
public String remove(Integer id);
}
<file_sep>package com.tc.orm.demo.dao;
import com.tc.orm.demo.entity.Member;
import com.tc.orm.framework.BaseDaoSupport;
import com.tc.orm.framework.QueryRule;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.List;
/**
* Created by Tom.
*/
@Repository
public class MemberDao extends BaseDaoSupport<Member,Long> {
@Override
protected String getPKColumn() {
return "id";
}
@Override
@Resource(name="dataSource")
public void setDataSource(DataSource dataSource){
super.setDataSourceReadOnly(dataSource);
super.setDataSourceWrite(dataSource);
}
public List<Member> selectAll() throws Exception{
QueryRule queryRule = QueryRule.getInstance();
queryRule.andLike("name","Tom%");
return super.select(queryRule);
}
}
<file_sep>package com.tc.spring.demo.service.impl;
import com.tc.spring.demo.service.IModifyService;
import com.tc.spring.framework.annotation.TCService;
/**
* @author taosh
* @create 2019-08-09 16:50
*/
@TCService
public class ModifyService implements IModifyService {
public String add(String name, String addr) throws Exception{
throw new Exception("异常测试");
}
public String edit(Integer id, String name) {
return "modifyService edit:id=" + id + ",name=" + name;
}
public String remove(Integer id) {
return "modifyService remove:id=" + id;
}
}
<file_sep>package com.tc.spring.framework.webmvc.servlet;
import com.tc.spring.framework.annotation.TCController;
import com.tc.spring.framework.annotation.TCRequestMapping;
import com.tc.spring.framework.context.TCApplicationContext;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author taosh
* @create 2019-08-13 20:17
*/
public class TCDispatcherServlet extends HttpServlet {
private final String CONTEXT_CONFIG_LOCATION = "contextConfigLocation";
private TCApplicationContext context;
private List<TCHandlerMapping> handleMappings = new ArrayList<TCHandlerMapping>();
private Map<TCHandlerMapping, TCHandlerAdapter> handlerAdapters = new HashMap<TCHandlerMapping, TCHandlerAdapter>();
private List<TCViewResolver> viewResolvers = new ArrayList<TCViewResolver>();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
try {
this.doDispatch(req, resp);
} catch (Exception e) {
resp.getWriter().write("500 Exception,Details:\r\n"+ Arrays.toString(e.getStackTrace())
.replaceAll("\\[|\\]", "").replaceAll(",\\s","\r\n"));
e.printStackTrace();
}
}
private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception {
//通过从request中拿到URL,去匹配一个handlerMapping
TCHandlerMapping handler = getHandler(req);
System.out.println(handler);
if ( handler == null ){
processDispatchResult(req, resp, new TCModelAndView("404"));
return;
}
//准备调用前的参数
TCHandlerAdapter handlerAdapter = getHandlerAdapter(handler);
//真正的调用方法,返回ModelAndView存储了页面的值和模板名称
TCModelAndView mv = handlerAdapter.handler(req, resp, handler);
processDispatchResult(req, resp, mv);
}
private void processDispatchResult(HttpServletRequest req, HttpServletResponse resp, TCModelAndView mv) throws Exception {
//把modelandview变成一个html/outputStream/json/freemark等
if( null == mv ){
return;
}
//如果modelandview不为null
if( this.viewResolvers.isEmpty() ){
return;
}
for (TCViewResolver viewResolver : this.viewResolvers) {
TCView view = viewResolver.resolveViewName(mv.getViewName(),null);
view.render(mv.getModel(), req, resp);
return;
}
}
private TCHandlerAdapter getHandlerAdapter(TCHandlerMapping handler) {
if( this.handlerAdapters.isEmpty() ){
return null;
}
TCHandlerAdapter ha = this.handlerAdapters.get(handler);
if (ha.support(handler)){
return ha;
}
return null;
}
private TCHandlerMapping getHandler(HttpServletRequest req) {
if( handleMappings.isEmpty() ){
return null;
}
String url = req.getRequestURI();
String contextPath = req.getContextPath();
url = url.replace(contextPath, "").replaceAll("/+", "/");
for (TCHandlerMapping handler : handleMappings) {
Matcher matcher = handler.getPattern().matcher(url);
//如果没有匹配,继续下一个匹配
if( !matcher.matches() ){
continue;
}
return handler;
}
return null;
}
@Override
public void init(ServletConfig config) throws ServletException {
//初始化Application
context = new TCApplicationContext(config.getInitParameter(CONTEXT_CONFIG_LOCATION));
//初始化spring mvc的九大组件
initStrategies(context);
}
protected void initStrategies(TCApplicationContext context) {
//多文件上传组建
initMultipartResolver(context);
//初始化本地语言环境
initLocaleResolver(context);
//初始化模板处理
initThemeResolver(context);
//
initHandlerMappings(context);
//初始化参数适配器
initHandlerAdapters(context);
//初始化异常拦截
initHandlerExceptionResolvers(context);
//初始化视图预处理器
initRequestToViewNameTranslator(context);
//初始化视图转换器
initViewResolvers(context);
initFlashMapManager(context);
}
private void initFlashMapManager(TCApplicationContext context) {
}
private void initViewResolvers(TCApplicationContext context) {
//拿到模板的存放目录
String templateRoot = context.getConfig().getProperty("templateRoot");
String templateRootPath = this.getClass().getClassLoader().getResource(templateRoot).getFile();
File templateRootDir = new File(templateRootPath);
for (File file : templateRootDir.listFiles()) {
this.viewResolvers.add(new TCViewResolver(templateRoot));
}
}
private void initRequestToViewNameTranslator(TCApplicationContext context) {
}
private void initHandlerExceptionResolvers(TCApplicationContext context) {
}
private void initHandlerAdapters(TCApplicationContext context) {
//把一个request请求变成一个handler,参数都是字符串的,自动匹配到handler中的形参
//拿到handlerMapper才能干活
//意味着有几个handlerMapping就有几个handlerAdapter
for (TCHandlerMapping handleMapping : this.handleMappings) {
this.handlerAdapters.put(handleMapping, new TCHandlerAdapter());
}
}
private void initHandlerMappings(TCApplicationContext context) {
String [] beanNames = context.getBeanDefinitionNames();
try {
for (String beanName : beanNames) {
Object controller = context.getBean(beanName);
Class<?> clazz = controller.getClass();
if( !clazz.isAnnotationPresent(TCController.class) ){
continue;
}
String baseUrl = "";
//获取Controller的url配置
if( clazz.isAnnotationPresent(TCRequestMapping.class) ){
TCRequestMapping requestMapping = clazz.getAnnotation(TCRequestMapping.class);
baseUrl = requestMapping.value();
}
//获取method的url配置
Method[] methods = clazz.getMethods();
for (Method method : methods) {
//没有加TCRequestMapping注解的忽略
if( !method.isAnnotationPresent(TCRequestMapping.class) ){
continue;
}
//映射url
TCRequestMapping requestMapping = method.getAnnotation(TCRequestMapping.class);
String regex = ("/" + baseUrl + "/" + requestMapping.value().replaceAll("\\*", ".*"))
.replaceAll("/+", "/");
Pattern pattern = Pattern.compile(regex);
this.handleMappings.add(new TCHandlerMapping(controller, method, pattern));
}
}
}catch (Exception e){
}
}
private void initThemeResolver(TCApplicationContext context) {
}
private void initLocaleResolver(TCApplicationContext context) {
}
private void initMultipartResolver(TCApplicationContext context) {
}
}
<file_sep>package com.tc;
import com.tc.spring.demo.action.MyAction;
import com.tc.spring.framework.context.TCApplicationContext;
/**
* @author taosh
* @create 2019-08-09 16:05
*/
public class Test {
public static void main(String[] args) throws Exception {
TCApplicationContext applicationContext = new TCApplicationContext("classpath:application.properties");
Object object = applicationContext.getBean(MyAction.class);
}
}
<file_sep>package com.tc.orm.demo.entity;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.io.Serializable;
/**
* Created by Tom.
*/
@Entity
@Table(name="t_order")
@Data
public class Order implements Serializable {
private Long id;
@Column(name="mid")
private Long memberId;
private String detail;
private Long createTime;
private String createTimeFmt;
@Override
public String toString() {
return "Order{" +
"id=" + id +
", memberId=" + memberId +
", detail='" + detail + '\'' +
", createTime=" + createTime +
", createTimeFmt='" + createTimeFmt + '\'' +
'}';
}
}
<file_sep>package com.tc.spring.demo.service;
/**
* @author taosh
* @create 2019-08-09 16:48
*/
public interface IQueryService {
/**
* 查询
*/
public String query(String name);
}
<file_sep>package com.tc.spring.framework.aop;
import com.tc.spring.framework.aop.intercept.TCMethodInvocation;
import com.tc.spring.framework.aop.support.TCAdvisedSupport;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;
/**
* @author taosh
* @create 2019-09-14 11:09
*/
public class TCJdkDynamicAopProxy implements TCAopProxy, InvocationHandler {
private TCAdvisedSupport advised;
public TCJdkDynamicAopProxy(TCAdvisedSupport config) {
this.advised = config;
}
public Object getProxy() {
return getProxy(this.advised.getTargetClass().getClassLoader());
}
public Object getProxy(ClassLoader classLoader) {
Proxy.newProxyInstance(classLoader, this.advised.getTargetClass().getInterfaces(), this);
return null;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
List<Object> interceptorsAndDynamicMethodMatchers =
this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, this.advised.getTargetClass());
TCMethodInvocation invocation = new TCMethodInvocation(proxy,null , method, args,
this.advised.getTargetClass(), interceptorsAndDynamicMethodMatchers);
return invocation.proceed();
}
}
<file_sep>package com.tc.spring.framework.aop.aspect;
import com.tc.spring.framework.aop.intercept.TCMethodInterceptor;
import com.tc.spring.framework.aop.intercept.TCMethodInvocation;
import java.lang.reflect.Method;
/**
* @author taosh
* @create 2019-09-14 15:06
*/
public class TCAfterReturningAdviceInterceptor extends TCAbstractAspectAdvice implements TCMethodInterceptor {
private TCJoinPoint joinPoint;
public TCAfterReturningAdviceInterceptor(Method aspectMethod, Object aspectObject) {
super(aspectMethod, aspectObject);
}
public Object invoke(TCMethodInvocation invocation) throws Throwable {
Object retVal = invocation.proceed();
this.joinPoint = invocation;
this.afterReturning(retVal, invocation.getMethod(), invocation.getArguments(), invocation.getThis());
return retVal;
}
private void afterReturning(Object retVal, Method method, Object[] arguments, Object aThis) {
try {
super.invokeAdviceMethod(this.joinPoint, retVal, null);
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
}
<file_sep>package com.tc.spring.framework.context;
import com.tc.spring.framework.annotation.TCAutowired;
import com.tc.spring.framework.annotation.TCController;
import com.tc.spring.framework.annotation.TCService;
import com.tc.spring.framework.aop.TCAopProxy;
import com.tc.spring.framework.aop.TCCglibAopProxy;
import com.tc.spring.framework.aop.TCJdkDynamicAopProxy;
import com.tc.spring.framework.aop.config.TCAopConfig;
import com.tc.spring.framework.aop.support.TCAdvisedSupport;
import com.tc.spring.framework.beans.config.TCBeanPostProcessor;
import com.tc.spring.framework.core.TCBeanFactory;
import com.tc.spring.framework.beans.TCBeanWrapper;
import com.tc.spring.framework.beans.config.TCBeanDefinition;
import com.tc.spring.framework.beans.support.TcBeanDefinitionReader;
import com.tc.spring.framework.beans.support.TcDefaultListableBeanFactory;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
/**
* IOC、DI
* @author taosh
* @create 2019-08-05 21:42
*/
public class TCApplicationContext extends TcDefaultListableBeanFactory implements TCBeanFactory {
private String[] configLocations;
private TcBeanDefinitionReader reader;
/**例的IOC容器*/
private Map<String, Object> singletonObjectCache = new ConcurrentHashMap<String, Object>();
/**通用的IOC容器*/
private Map<String, TCBeanWrapper> factoryBeanInstanceCache = new ConcurrentHashMap<String, TCBeanWrapper>();
public TCApplicationContext(String... configLocations){
this.configLocations = configLocations;
try {
refresh();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void refresh() throws Exception {
//1.定位配置文件
reader = new TcBeanDefinitionReader(this.configLocations);
//2.加载配置文件,扫描相关的类,把他们封装成BeanDefinition
List<TCBeanDefinition> beanDefinitions = reader.loadBeanDefinitions();
//3.注册、把配置信息放到容器里面(伪IOC容器)
doRegisterBeanDefinition(beanDefinitions);
//4.把不是延时加载的类提前初始化
doAutowired();
}
/**处理非延时加载的情况*/
private void doAutowired() {
for (Map.Entry<String, TCBeanDefinition> beanDefinitionEntry : super.beanDefinitionMap.entrySet()) {
String beanName = beanDefinitionEntry.getKey();
if( !beanDefinitionEntry.getValue().isLazyInit() ){
try {
getBean(beanName);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
private void doRegisterBeanDefinition(List<TCBeanDefinition> beanDefinitions) throws Exception {
for (TCBeanDefinition beanDefinition : beanDefinitions) {
if( super.beanDefinitionMap.containsKey(beanDefinition.getFactoryBeanName()) ){
throw new Exception("the "+beanDefinition.getFactoryBeanName()+" is exists!!");
}
super.beanDefinitionMap.put(beanDefinition.getFactoryBeanName(), beanDefinition);
}
//到这里,容器初始化完毕
}
public Object getBean(Class<?> beanClass) throws Exception {
return getBean(toLowerFirstCase(beanClass.getSimpleName()));
}
/**
* 依赖注入 通过读取beanDefinition中的信息,通过反射机制创建一个实例并返回
* Spring的做法是,不会把最原始的对象放出去,会用一个beanWrapper来进行一次包装
* 装饰器模式:保留原来的OOP关系,我们需要进行扩展、增强(为AOP做好基础)
* @param beanName
* @return
*/
public Object getBean(String beanName) throws Exception {
TCBeanDefinition tcBeanDefinition = this.beanDefinitionMap.get(beanName);
Object instance = null;
instance = instantiateBean(beanName, tcBeanDefinition);
TCBeanPostProcessor postProcessor = new TCBeanPostProcessor();
postProcessor.postProcessBeforeInitialization(instance, beanName);
//1,初始化
//3,把这个对象封装到beanWrapper中
//factoryBeanInstanceCache
TCBeanWrapper beanWrapper = new TCBeanWrapper(instance);
//4,把beanWrapper存到IOC容器中
//2,拿到beanWrapper之后,保存到IOC容器中
// if( this.factoryBeanInstanceCache.containsKey(beanName) ){
// throw new Exception("The "+beanName+" is exists!");
// }
this.factoryBeanInstanceCache.put(beanName, beanWrapper);
postProcessor.postProcessAfterInitialization(instance, beanName);
//3,注入
populateBean(beanName, new TCBeanDefinition(), beanWrapper);
return this.factoryBeanInstanceCache.get(beanName).getWrappedInstance();
}
private void populateBean(String beanName, TCBeanDefinition tcBeanDefinition, TCBeanWrapper tcBeanWrapper) {
Object instance = tcBeanWrapper.getWrappedInstance();
Class<?> clazz = tcBeanWrapper.getWrappedClass();
//只有加了注解的类,才执行注入
if( !(clazz.isAnnotationPresent(TCController.class) || clazz.isAnnotationPresent(TCService.class)) ){
return;
}
//获得所有的fields
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
if( !field.isAnnotationPresent(TCAutowired.class) ){
continue;
}
TCAutowired autowired = field.getAnnotation(TCAutowired.class);
String autowiredBeanName = autowired.value().trim();
if( "".equals(autowiredBeanName) ){
autowiredBeanName = field.getType().getName();
}
//强制访问
field.setAccessible(true);
try {
if( this.factoryBeanInstanceCache.get(autowiredBeanName) == null ){
continue;
}
field.set(instance, this.factoryBeanInstanceCache.get(autowiredBeanName).getWrappedInstance());
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
private Object instantiateBean(String beanName, TCBeanDefinition tcBeanDefinition) {
//1,拿到要实例化的对象的类名
String className = tcBeanDefinition.getBeanClassName();
Object instance = null;
//2,反射实例化,得到一个对象,放到map中
try {
if( this.singletonObjectCache.containsKey(className) ){
instance = this.singletonObjectCache.get(className);
}else {
Class<?> clazz = Class.forName(className);
instance = clazz.newInstance();
TCAdvisedSupport config = instationAopConfig(tcBeanDefinition);
config.setTargetClass(clazz);
config.setTarget(instance);
//如果符合pointcut规则,就创建代理对象
if( config.pointCutMatch() ){
instance = createProxy(config).getProxy();
}
this.singletonObjectCache.put(className, instance);
this.singletonObjectCache.put(tcBeanDefinition.getFactoryBeanName(), instance);
}
}catch (Exception e){
e.printStackTrace();
}
return instance;
}
private TCAopProxy createProxy(TCAdvisedSupport config) {
Class targetClass = config.getTargetClass();
if( targetClass.getInterfaces().length > 0 ){
return new TCJdkDynamicAopProxy(config);
}
return new TCCglibAopProxy(config);
}
private TCAdvisedSupport instationAopConfig(TCBeanDefinition tcBeanDefinition) {
TCAopConfig config = new TCAopConfig();
config.setPointCut(this.reader.getConfig().getProperty("pointCut"));
config.setAspectAfter(this.reader.getConfig().getProperty("aspectAfter"));
config.setAspectAfterThrow(this.reader.getConfig().getProperty("aspectAfterThrow"));
config.setAspectBefore(this.reader.getConfig().getProperty("aspectBefore"));
config.setAspectClass(this.reader.getConfig().getProperty("aspectClass"));
config.setAspectAfterThrowingName(this.reader.getConfig().getProperty("aspectAfterThrowingName"));
return new TCAdvisedSupport(config);
}
public String[] getBeanDefinitionNames(){
return this.beanDefinitionMap.keySet().toArray(new String[this.beanDefinitionMap.size()]);
}
public int getBeanDefinitionCount(){
return beanDefinitionMap.size();
}
public Properties getConfig(){
return this.reader.getConfig();
}
/**大写转小写 Ascii码*/
private String toLowerFirstCase(String simpleName){
char[] chars = simpleName.toCharArray();
chars[0] += 32;
return String.valueOf(chars);
}
}
<file_sep>package com.tc.spring.framework.beans.config;
import lombok.Data;
/**
* @author taosh
* @create 2019-08-06 19:28
*/
@Data
public class TCBeanDefinition {
private String beanClassName;
boolean isLazyInit = false;
private String factoryBeanName;
private boolean singelton = true;
}
<file_sep>package com.tc.orm.demo.dao;
import com.tc.orm.demo.entity.AppVersion;
import com.tc.orm.framework.BaseDaoSupport;
import javafx.scene.chart.PieChart;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* @author taosh
* @create 2019-10-08 14:57
*/
@Repository
public class AppVersionDao extends BaseDaoSupport {
JdbcTemplate jdbcTemplate;
@Override
protected String getPKColumn() {
return null;
}
@Override
@Resource(name = "dataSource")
public void setDataSource(DataSource dataSource){
jdbcTemplate = new JdbcTemplate(dataSource);
}
public List<AppVersion> selectAll(){
final List<AppVersion> result = new ArrayList<AppVersion>();
String sql = "select * from t_app_version";
jdbcTemplate.query(sql, new RowMapper<Object>() {
public Object mapRow(ResultSet resultSet, int i) throws SQLException {
AppVersion version = new AppVersion();
resultSet.getLong(i);
result.add(version);
return version;
}
});
return result;
}
@Override
public boolean delete(Object entity) throws Exception {
return false;
}
@Override
public Object insertAndReturnId(Object entity) throws Exception {
return null;
}
@Override
public boolean insert(Object entity) throws Exception {
return false;
}
@Override
public boolean update(Object entity) throws Exception {
return false;
}
}
| 17618d4c41dd262cf1ae0f3e894a899cfaba9bc4 | [
"Java",
"INI"
] | 23 | Java | cjtclinsan/tc_spring | 6525d9e78b90dc3c0f5afd4e340bd943976c3bea | 593362b79b0c7d95727e5b3413f9f57cca281424 |
refs/heads/master | <repo_name>anowak/python-mock-test<file_sep>/my_module/models.py
class Model():
def save(self):
return 'original'
<file_sep>/my_module/tests.py
import unittest
from mock import patch, Mock
from storage import Storage
from models import Model
class StorageTestCase(unittest.TestCase):
@patch('my_module.storage.Model')
def test(self, model_class_mock):
save_mock = Mock(return_value='mocked')
model_class_mock.return_value.save = save_mock
storage = Storage()
result = storage.populate()
self.assertEqual(save_mock.call_count, 1)
self.assertEqual(result, 'mocked')
if __name__ == "__main__":
unittest.main()
<file_sep>/my_module/storage.py
from models import Model
class Storage():
def populate(self):
new_model = Model()
return new_model.save()
| cc9e53e56586c4a0e5ef96003cd3e747b9acd9ec | [
"Python"
] | 3 | Python | anowak/python-mock-test | 7f300ee92fb62017a4e6075b92704037282c9838 | 9be078636f51c22c32113ff0ea88111e14cc4423 |
refs/heads/master | <file_sep><?php $dr = str_replace($_SERVER['SCRIPT_NAME'], '/includes/', $_SERVER['SCRIPT_FILENAME']); ?>
<?php
$title = "<NAME>";
$section = "schedule";
?>
<?php include($dr . "head.inc.php"); ?><!-- HEADER -->
<div class="section">
<div class="speaker">
<div class="speaker-context">
<img class="speaker-badge" alt="<NAME>" src="/images/speaker-badge-matt-biddulph.png">
</div><!-- /.speaker-context -->
<div class="speaker-bio">
<h2>Workshop Leader <strong><NAME></strong></h2>
<p class="description"><NAME> is the nomadic CTO of <a href="http://www.dopplr.com/">Dopplr</a>, the social network for intelligent travellers. He started out in 1994 building search engines on CD-ROM, and now specialises in digital media, social software and putting data on the web. In past lives he was a creative technologist for hire, working with companies like Nature, Joost and the BBC to bring cutting-edge technologies into the mainstream.</p>
</div>
<div class="speaker-talk">
<h2>Workshop:<strong>Internet of Things Master Class</strong></h2>
<p>This one day intensive hands-on workshop will focus on getting programmers and technologists up to speed about the latest hardware technologies, allowing them to build web-enabled, responsive installations and spaces.</p>
<p><a href="/workshops/#internet-of-things">Read More</a></p>
</div><!-- /.speaker-talk -->
</div>
</div>
<!-- FOOTER -->
<?php include($dr . "footer.inc.php"); ?><file_sep><?php $dr = str_replace($_SERVER['SCRIPT_NAME'], '/includes/', $_SERVER['SCRIPT_FILENAME']); ?>
<?php
$title = "<NAME>";
$section = "schedule";
?>
<?php include($dr . "head.inc.php"); ?><!-- HEADER -->
<div class="section">
<div class="speaker">
<div class="speaker-context">
<img class="speaker-badge" alt="<NAME>" src="/images/speaker-badge-richard-rutter.png">
</div><!-- /.speaker-context -->
<div class="speaker-bio">
<h2>Workshop Leader <strong><NAME></strong></h2>
<p class="description">Richard is a founding partner and the production director for Clearleft. He has been designing websites and web applications since the birth of the commercial web, over twelve years ago. Richard leads the user experience team at Clearleft, pioneering innovative approaches to designing fantastic experiences for clients and their customers.</p>
</div>
<div class="speaker-talk">
<h2>Workshop:<strong>HTML5 and CSS3 Wizardry</strong></h2>
<p>HTML5 and CSS3 may be considered by some as distant concepts: far in the future and irrelevant to their daily lives. However, in this day-long workshop by Clearleft's expert client-side engineers <NAME>, <NAME> and <NAME>, you will learn how these exciting new concepts can be applied today!</p>
<p><a href="/workshops/#html5-css3">Read More</a></p>
</div><!-- /.speaker-talk -->
</div>
</div>
<!-- FOOTER -->
<?php include($dr . "footer.inc.php"); ?><file_sep><div class="section workshops-teaser">
<div class="blurb"><h2>Workshops</h2>
<p class="description">We’re offering a limited number of places for a few full-day exclusive masterclasses in the lead-up to the conference.</p>
<p>Attendees receive complimentary entrance to the dConstruct conference. <a href="/workshops/">More about our workshops</a></p>
</div><!-- /.blurb -->
<?php include($dr . "workshops.inc.php"); ?>
</div><file_sep><?php $dr = str_replace($_SERVER['SCRIPT_NAME'], '/includes/', $_SERVER['SCRIPT_FILENAME']); ?>
<?php
$title = "<NAME>";
$section = "schedule";
?>
<?php include($dr . "head.inc.php"); ?><!-- HEADER -->
<div class="section">
<div class="speaker">
<div class="speaker-context">
<img class="speaker-badge" alt="<NAME>" src="/images/speaker-badge-daniel-soltis.png">
</div><!-- /.speaker-context -->
<div class="speaker-bio">
<h2>Workshop Leader <strong><NAME></strong></h2>
<p class="description"><NAME> is an Interaction Designer and jack of all trades. He recently graduated from New York University’s Interactive Telecommunications Program, where he focused on physical computing, large-scale interfaces, and social and cognitive aspects of games.</p>
<p>He has presented games at the 2008 ACM SIGGRAPH Video Game Symposium and the 2008 Come Out and Play festival. Daniel's prior work life touched on a number of fields—among other things, he has written medical journal articles, edited science encyclopedias, drawn far too many diagrams in Illustrator, organized university students around environmental issues, and taught 12-year-olds.</p>
</div>
<div class="speaker-talk">
<h2>Workshop:<strong>Internet of Things Master Class</strong></h2>
<p>This one day intensive hands-on workshop will focus on getting programmers and technologists up to speed about the latest hardware technologies, allowing them to build web-enabled, responsive installations and spaces.</p>
<p><a href="/workshops/#internet-of-things">Read More</a></p>
</div><!-- /.speaker-talk -->
</div>
</div>
<!-- FOOTER -->
<?php include($dr . "footer.inc.php"); ?><file_sep><?php $dr = str_replace($_SERVER['SCRIPT_NAME'], '/includes/', $_SERVER['SCRIPT_FILENAME']); ?>
<?php
$bodyclass='home';
$scripts = '
<script type="text/javascript" src="/js/clearform.js"></script>
';
include($dr . "head.inc.php"); ?><!-- HEADER -->
<!-- SPEAKER LIST -->
<div class="section speaker-list">
<div class="highlight">
<div class="photos">
<img class="photo thumbnail" alt="workshop attendees" src="/images/photo-workshop.jpg">
<img class="photo thumbnail" alt="attendee relaxing on a sofa" src="/images/photo-shoes.jpg">
<img class="photo" alt="crowd of attendees" src="/images/photo-crowd.jpg">
<img class="photo" alt="conference speaker" src="/images/photo-speaker.jpg">
<img class="photo thumbnail" alt="silverback banana" src="/images/photo-banana.jpg">
<img class="photo thumbnail" alt="conference attendees" src="/images/photo-attendees.jpg">
</div>
<img id="onsalebutton" src="/images/soldout.png" alt="sorry we've sold out!" class="soldout" />
<p class="description"><strong>dConstruct 09</strong> brings together leading <dfn title="self-actuating media nodes">thinkers</dfn> from the fields of ubiquitous computing, interface design, gaming and mobile to explore the challenges of designing for tomorrow.</p>
<p class="add-to-cal"><a href="http://suda.co.uk/projects/microformats/hcalendar/get-cal.php?uri=http://2009.dconstruct.org/">Add it to your calendar</a></p>
<p class="get-updates">Follow <a href="http://twitter.com/dconstruct">@dConstruct</a> and <a href="http://twitter.com/clearleft">@clearleft</a> on <img src="/images/twitter_logo_sml.png" alt="Twitter" width="76" height="19"></p>
</div><!-- ./highlight -->
<ul>
<li class="vcard"><h2><a class="url fn" href="/schedule/adamgreenfield/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/brianfling/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/russelldavies/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/mikemigurski/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/bencerveny/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/nathanshedroff/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/chrisnoessel"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/robinhunicke/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn n" href="/schedule/augustdelosreyes/"><span class="given-name">August</span> <span class="family-name">de los Reyes</span></a></h2></li>
</ul>
</div><!-- /.section .speaker-list -->
<!-- NEWS -->
<?php include($dr . "news.inc.php"); ?>
<!-- FOOTER -->
<?php include($dr . "footer.inc.php"); ?>
<file_sep><?php $dr = str_replace($_SERVER['SCRIPT_NAME'], '/includes/', $_SERVER['SCRIPT_FILENAME']); ?>
<?php
$title = "Sponsorship";
$section = "sponsorship";
?>
<?php include($dr . "head.inc.php"); ?><!-- HEADER -->
<!-- SECTION SPONSORSHIP -->
<div class="section sponsorship">
<h2>Sponsorship</h2>
<p class="description">Connect your brand with influential bloggers & thought leaders, talented developers & designers, and some of the best known Internet companies around.</p>
<div class="blurb">
<p>Associate your company with dConstruct, the highly successful combination of affordable one day conference and two days of masterclass workshops. Get your message to a brilliant audience including everyone from product managers and CEOs to those designing and developing the latest generation of web applications.</p>
<p>dConstruct has plenty of sponsorship options and opportunities providing you the flexibility to showcase your services and demonstrate your commitment to the web design community in a way that best fits your needs.</p>
</div>
<div class="more-information">
<p>Past sponsors have included <strong>Adobe</strong>, <strong>Yahoo!</strong>, <strong>Apress</strong> and the <strong>BBC</strong>, to name just a few.</p>
<img class="sponsors-past first" src="/images/sponsor-past-adobe.gif" alt="adobe">
<img class="sponsors-past" src="/images/sponsor-past-yahoo.gif" alt="yahoo">
<img class="sponsors-past" src="/images/sponsor-past-bbc.gif" alt="bbc">
<img class="sponsors-past" src="/images/sponsor-past-apress.gif" alt="apress">
<div class="highlight">
<p>For more information on the benefits, sponsorship options and pricing, <a href="/contact/">contact us</a>.</p>
</div>
</div>
</div>
<!-- FOOTER -->
<?php include($dr . "footer.inc.php"); ?><file_sep><?php $dr = str_replace($_SERVER['SCRIPT_NAME'], '/includes/', $_SERVER['SCRIPT_FILENAME']); ?>
<?php
$title = "Time Capsule Competition";
$section = "capsule";
?>
<?php include($dr . "head.inc.php"); ?><!-- HEADER -->
<div class="section notwide">
<h2>Win a VIP Ticket to dConstruct</h2>
<p>How would you like to attend <a href="/schedule/">the dConstruct conference</a>, come along to the speakers’ dinner, and spend two nights in a luxury hotel in Brighton?</p>
<h4>Show us what you would put in the dConstruct time capsule</h4>
<p>The theme of this year’s dConstruct is <cite>Designing for Tomorrow</cite>. That’s got us thinking about the future and what we would preserve in a time capsule.</p>
<p>Take a look around you. What do you see that you would like to preserve for the future? Take a picture of it, upload that picture to <a href="http://www.flickr.com/">Flickr</a> and tag it with <a href="http://www.flickr.com/photos/tags/dconstructcapsule"><code>dconstructcapsule</code></a>.</p>
<p>You’ll be contributing to a collective vision of our current desires for the future. The best entry will win:</p>
<ul>
<li>Two nights at MyHotel in Brighton (Thursday, September 3rd and Friday, September 4th).</li>
<li>A place at the speakers dinner on the evening of Thursday, September 3rd.</li>
<li>A ticket to dConstruct on Friday, September 4th.</li>
</ul>
<p>The competition closes on Friday, August 28th—one week before the conference. At that time we will contact the winner through Flickr Mail.</p>
<p>So what are you waiting for? Get thinking and get snapping.</p>
<?php
$data = array(
'api_key' => 'b4144c69562716bb2a04506c1a65b8e0',
'tags' => 'dconstructcapsule'
);
require_once($dr.'flickrPhotosSearch.php');
$photos = flickrPhotosSearch($data);
if (count($photos > 0)):
foreach ($photos as $photo):
echo '<a href="'.$photo['url'].'"><img style="display: block; float: left" src="'.$photo['src']['square'].'" alt="'.$photo['title'].'"></a>';
endforeach;
endif;
?>
</div>
<!-- FOOTER -->
<?php include($dr . "footer.inc.php"); ?><file_sep><?php
function flickrPhotosSearch($data=array()) {
$return = array();
$url = 'http://api.flickr.com/services/rest/?method=flickr.photos.search';
$arguments = array('api_key','user_id','tags','tag_mode','text','min_upload_date','max_upload_date','min_taken_date','max_taken_date','license','sort','privacy_filter','bbox','accuracy','extras','per_page','page');
foreach ($arguments as $argument) {
if (isset($data[$argument])) {
$url.= '&'.$argument.'='.urlencode($data[$argument]);
}
}
$doc = new DOMDocument();
if (!@$doc -> load($url)) {
return $return;
}
$photos = $doc -> getElementsByTagName('photo');
if ($photos -> item(0)) {
foreach ($photos as $photo) {
$count = count($return);
$return[$count]['url'] = 'http://www.flickr.com/photos/'.$photo -> getAttribute('owner').'/'.$photo -> getAttribute('id');
$return[$count]['title'] = htmlspecialchars($photo -> getAttribute('title'));
$path = 'http://farm'.$photo -> getAttribute('farm').'.static.flickr.com/'.$photo -> getAttribute('server').'/'.$photo -> getAttribute('id').'_'.$photo -> getAttribute('secret').'_';
$return[$count]['src']['square'] = $path.'s.jpg';
$return[$count]['src']['thumbnail'] = $path.'t.jpg';
$return[$count]['src']['small'] = $path.'m.jpg';
$return[$count]['src']['medium'] = $path.'-.jpg';
$return[$count]['src']['large'] = $path.'b.jpg';
$return[$count]['src']['original'] = $path.'o.jpg';
}
}
return $return;
}
?><file_sep><?php $dr = str_replace($_SERVER['SCRIPT_NAME'], '/includes/', $_SERVER['SCRIPT_FILENAME']); ?>
<?php
$title = "Workshops";
$section = "workshops";
?>
<?php include($dr . "head.inc.php"); ?><!-- HEADER -->
<!-- SECTION WORKSHOP -->
<div class="section workshops">
<div class="blurb">
<h2>Workshops</h2>
<p class="description">We’re offering a limited number of places for a few full-day exclusive masterclasses in the lead-up to the conference.</p>
<div class="more-information">
<p>Workshops will be taking place at: Clearleft Suite 3, 28 Kensington Street, Brighton, BN1 4AJ, UK. <a href="/location/">Map</a>.</p>
<p>Workshops start promptly at 10:00am. Please arrive at 9:30am for coffee and registration.</p>
</div>
</div>
<?php include($dr . "workshops.inc.php"); ?>
</div>
<!-- Workshop - Internet of Things -->
<div class="section workshop-detail">
<div class="highlight">
<img class="photo" src="/images/photo-workshop-group.jpg" alt="group of attendees"><img class="photo thumbnail" src="/images/photo-workshop-bottle.jpg" alt="bottle and flipchart"><img class="photo thumbnail"src="/images/photo-workshop-dome.jpg" alt="Brighton Dome">
<img src="/images/soldout.png" alt="sorry we've sold out!" class="soldout" />
</div>
<div class="agenda" id="internet-of-things">
<h2>Internet of Things Master Class</h2>
<h4>Led by <a href="/schedule/mattbiddulph/"><NAME></a>, <a href="/schedule/nickweldin/"><NAME></a> and <a href="/schedule/danielsoltis/"><NAME></a></h4>
<p class="description">This one day intensive hands-on workshop will focus on getting programmers and technologists up to speed about the latest hardware technologies, allowing them to build web-enabled, responsive installations and spaces.</p>
<p>With the latest interest in connecting the internet to the real world and vice versa (projects like Centograph, <a href="http://www.nabaztag.com/en/index.html">Nabaztag</a>, <a href="http://www.mcqn.com/bubblino">Bubblino</a> and <a href="http://www.touchatag.com/">Touchatag</a>), <a href="http://tinker.it/">Tinker.it!</a> will be talking through the Internet Of Things landscape, giving participants hard skills which they will be able to use immediately.</p>
<p>Participants with programming and web development skills are encouraged to attend.</p>
<p>What this workshop will involve:</p>
<ul>
<li>Introduction talk around Internet of Things, the landscape and the technologies used.</li>
<li>Introduction to Arduino and its use with Xbee and RFID</li>
<li>Setting up the board + examples from Getting Started with Arduino</li>
<li>Talking to Xbee nodes</li>
<li>Talking to RFID</li>
<li>Introduction to Arduino and Ethernet capabilities from Dopplr CTO <a href="/schedule/mattbiddulph/">Matt Biddulph</a>.</li>
<li>Introduction to Web APIs such as Twitter and Flickr, and the special considerations of hardware talking to them</li>
<li>First Web API client running on Arduino - retrieve data from the internet and send it to a laptop by serial connection</li>
<li>Introduction to web serving</li>
<li>Setting up the Arduino as a web server. Reading values from basic sensors (potentiometer, etc) and serving web pages showing this value</li>
</ul>
</div>
</div>
<!-- Workshop - HTML5 CSS3 -->
<div class="section workshop-detail">
<div class="highlight">
<img class="photo" src="/images/photo-workshop-musing.jpg" alt="group of attendees"><img class="photo thumbnail" src="/images/photo-workshop-html.jpg" alt="code on screen"><img class="photo thumbnail" src="/images/photo-workshop-sketches.jpg" alt="wireframe diagrams">
<img src="/images/soldout.png" alt="sorry we've sold out!" class="soldout" />
</div>
<div class="agenda" id="html5-css3">
<h2>HTML5 and CSS3 Wizardry</h2>
<h4>Led by <a href="/schedule/richardrutter/"><NAME></a>, <a href="/schedule/nataliedowne/"><NAME></a> and <a href="/schedule/jeremykeith/"><NAME></a></h4>
<p class="description">HTML5 and CSS3 may be considered by some as distant concepts: far in the future and irrelevant to their daily lives. However, in this day-long workshop by Clearleft's expert client-side engineers <NAME>, <NAME> and <NAME>, you will learn how these exciting new concepts can be applied today!</p>
<p>Unlock the potential of the browser with some revolutionary new ideas you can take away and use in the real world. Learn how to create magical things to add delight to your design. Get up to speed with the concept of Progressive Enrichment and reward more standards-compliant and forward-thinking browsers.</p>
<p>Learn to use CSS3 transitions and animations and then harness the power of more complex selectors to free your markup. Get to grips with how you can use elements and concepts from HTML5 to wow your friends with improved semantics and cleaner code.</p>
<p>CSS3 and HTML5 are already with us. This workshop will show you how to prepare your websites and coding methodology for the future, and what you can use right here, right now. Don't get left behind, sign up today!</p>
<ul>
<li>Understanding Progressive Enhancement.</li>
<li>What's new in HTML5?</li>
<li>Using HTML5's new structural elements.</li>
<li>Applying the HTML5 semantic vocabulary to your class names today.</li>
<li>Making full use of CSS 2.1.</li>
<li>What's new in CSS3?</li>
<li>Achieving excellence in web typography.</li>
<li>Replacing your old markup hacks with lean, mean CSS-driven effects.</li>
<li>Putting it all together in one pretty package.</li>
<li>Dealing with legacy browsers.</li>
</ul>
</div>
</div>
<!-- Workshop - jQuery for Designers -->
<div class="section workshop-detail">
<div class="highlight">
<img class="photo" src="/images/photo-workshop-session.jpg" alt="workshop attendees"><img class="photo thumbnail" src="/images/photo-workshop-post-its.jpg" alt="wireframe diagrams"><img class="photo thumbnail"src="/images/photo-workshop-coffee.jpg" alt="workshop attendees">
<img src="/images/soldout.png" alt="sorry we've sold out!" class="soldout" />
</div>
<div class="agenda" id="jquery-for-designers">
<h2>jQuery for Designers</h2>
<h4>Led by <a href="/schedule/remysharp/"><NAME></a></h4>
<p class="description">If you've found you've needed to write a bit (or more!) of interactive functionality using JavaScript, and couldn't because you a) didn't know how and b) didn't have time to learn how: then this workshop is for you.</p>
<p>You'll be learning jQuery from a practical point of view: what you can use out of the box to quickly get effects and interaction live in to your wireframes, prototypes and web sites. The aim *isn't* to teach you JavaScript, but to teach you what you need to know to be able to leverage jQuery to do your bidding.</p>
<p>During the day, Remy will show you how to dConstruct existing effects in web sites and show you how create your own using jQuery.</p>
<p>The workshop will also cover topics such as:</p>
<ul>
<li>JavaScript & debugging basics: how to fake it as a JavaScripter</li>
<li>Progressive enhancement & Graceful degradation - what's what</li>
<li>jQuery: how do bend the DOM to your will</li>
<li>Effect and animations - things that go whizz bang!</li>
<li>Ajax: it's even simpler than you think</li>
<li>Using jQuery UI for instant widgets, for zero work</li>
</ul>
<p>The workshop audience is aimed at beginners to intermediates - and it's very hands on!</p>
<p>We'll start with covering the basics of JavaScript so that you have a good grounding and you can fake your way through coding. This will include anonymous functions, scope, context (what 'this' means in different places) and objects. Then we'll move on to tabbing systems, how they work, how to recognise them when they don't look like tabbing systems, and then on to the juicier stuff such as effects, Ajax and jQuery UI.</p>
</div>
</div>
<!-- Workshop - Designing Mobile Experiences -->
<div class="section workshop-detail">
<div class="highlight">
<img class="photo" src="/images/photo-workshop-flipchart.jpg" alt="atendees and a flipchart"><img class="photo thumbnail"src="/images/photo-workshop-diagrams.jpg" alt="workshop drawings"><img class="photo thumbnail"src="/images/photo-workshop-moocards.jpg" alt="dConstruct moocards">
<img src="/images/soldout.png" alt="sorry we've sold out!" class="soldout" />
</div>
<div class="agenda" id="designing-mobile-experiences">
<h2>Designing Mobile Experiences</h2>
<h4>Led by <a href="/schedule/brianfling/"><NAME></a></h4>
<p class="description">In the last year we've learned something that we suspected, but never really knew about mobile, great mobile design sells. But great mobile design doesn't start in Photoshop, it starts by understanding the users, the business goals, the intended devices and a million other tiny variables. Who better to solve these problems than the designer?</p>
<p>In this workshop we will deconstruct a variety of successful mobile experiences from the old green screens to today's hottest iPhone apps. We'll identify what works in the mobile context and why. But more importantly we'll learn how we can design incredible mobile experiences for today and for tomorrow.</p>
<p>What we will cover in this workshop:</p>
<ul>
<li>Understanding the mobile context and how to design for it</li>
<li>Creating a device plan and a mobile design strategy around it</li>
<li>How to design and create progressive mobile experiences</li>
<li>How to choose the right mobile platform and application context</li>
<li>How to get the right designs on the right devices</li>
<li>How to design and build something insanely great</li>
</ul>
</div>
</div>
<!-- FOOTER -->
<?php include($dr . "footer.inc.php"); ?><file_sep><?php $dr = str_replace($_SERVER['SCRIPT_NAME'], '/includes/', $_SERVER['SCRIPT_FILENAME']); ?>
<?php
$title = "August de los Reyes";
$section = "schedule";
?>
<?php include($dr . "head.inc.php"); ?><!-- HEADER -->
<div class="section">
<div class="speaker">
<div class="speaker-context">
<img class="speaker-badge" alt="August De Los Reyes" src="/images/speaker-badge-august-de-los-reyes.png">
<div class="speaker-list">
<ul>
<li class="vcard"><h2><a class="url fn" href="/schedule/adamgreenfield/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/brianfling/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/russelldavies/"><NAME></a></h2></li>
<li class="vcard "><h2><a class="url fn" href="/schedule/mikemigurski/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/bencerveny/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/nathanshedroff/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/chrisnoessel"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/robinhunicke/"><NAME></a></h2></li>
<li class="vcard selected"><h2><a class="url fn n" href="/schedule/augustdelosreyes/"><span class="given-name">August</span> <span class="family-name">de los Reyes</span></a></h2></li>
</ul>
</div><!-- /.speaker-list -->
</div>
<div class="speaker-bio">
<h2>Speaker <strong><NAME></strong></h2>
<p class="description"><NAME>, is the Principal Director of User Experience for Microsoft Surface, a team dedicated to pioneering natural and intuitive ways to interact with technology.</p>
<p>August is a member of the Advanced Studies Program at the Harvard University Graduate School of Design where he received an MDesS with Distinction for his research in product design and emotion. A guest design faculty member at the University of Washington, he was a 2007-2008 visiting associate at the Oxford Internet Institute. He is working on his next book entitled The Poetics of Everyday Objects.</p>
<p>Photo Credit: <a href="http://www.flickr.com/photos/roguemm/2890407974/"><NAME></a></p>
<ul class="social-networks">
<li><a class="button" href="http://twitter.com/augustdlr"><span><img alt="Twitter" src="/images/logo-twitter.gif"></span></a></li>
</ul>
</div><!-- /.speaker-bio -->
<div class="speaker-talk">
<h2><strong>Experience and the Emotion Commotion</strong></h2>
<p class="blurb">The competitive environment for technology is changing, and its impact on experience design is deep: capabilities, features, and functions are no longer enough. Emotional engagement will distinguish successful consumer experiences of the future. Designing in this world requires we change the way we think about people and products. This presentation provides a brief overview of a counter-intuitive emotional design approach and its application to one of the hallmarks of the next phase in interaction design: Natural User Interface.</p>
<object type="application/x-shockwave-flash" data="http://huffduffer.com/flash/player.swf?soundFile=http://dconstruct.s3.amazonaws.com/2009/podcast/dConstruct2009-de-los-Reyes.mp3" width="290" height="24"><param name="movie" value="http://huffduffer.com/flash/player.swf?soundFile=http://dconstruct.s3.amazonaws.com/2009/podcast/dConstruct2009-de-los-Reyes.mp3"><param name="wmode" value="transparent"><a href="http://huffduffer.com/dConstruct/8519">Experience and the Emotion Commotion on Huffduffer</a></object>
<p><a rel="enclosure" href="http://dconstruct.s3.amazonaws.com/2009/podcast/dConstruct2009-de-los-Reyes.mp3">Download the audio</a></p>
<p><a href="/podcast/emotioncommotion">Read the transcript</a></p>
</div><!-- /.speaker-talk -->
</div><!-- /.speaker -->
</div><!-- /.section -->
<!-- FOOTER -->
<?php include($dr . "footer.inc.php"); ?><file_sep><?php $dr = str_replace($_SERVER['SCRIPT_NAME'], '/includes/', $_SERVER['SCRIPT_FILENAME']); ?>
<?php
$title = "Workshops: HTML5 and CSS3 Wizardry";
$section = "workshops";
?>
<?php include($dr . "head.inc.php"); ?><!-- HEADER -->
<!-- SECTION WORKSHOP -->
<div class="section">
<h2>HTML5 and CSS3 Wizardry</h2>
<h3>HTML5</h3>
<ul>
<li><a href="html5/slides/">Slides</a></li>
<li><a href="html5/examples/">Examples</a></li>
</ul>
<h3>CSS3</h3>
<ul>
<li><a rel="enclosure" type="application/pdf" href="http://dconstruct.s3.amazonaws.com/2009/slides/css3/css3-deck.pdf">Slides</a> (<abbr title="Portable Document Format">PDF</abbr> 9.6<abbr title="MegaBytes">MB</abbr>)</li>
<li><a rel="enclosure" href="http://dconstruct.s3.amazonaws.com/2009/slides/css3/examples.zip">Examples</a> (.zip 9.3<abbr title="MegaBytes">MB</abbr>)</li>
</ul>
</div>
<!-- FOOTER -->
<?php include($dr . "footer.inc.php"); ?><file_sep><?php $dr = str_replace($_SERVER['SCRIPT_NAME'], '/includes/', $_SERVER['SCRIPT_FILENAME']); ?>
<?php
$title = "<NAME>";
$section = "schedule";
?>
<?php include($dr . "head.inc.php"); ?><!-- HEADER -->
<div class="section">
<div class="speaker">
<div class="speaker-context">
<img class="speaker-badge" alt="<NAME>" src="/images/speaker-badge-robin-hunicke.png">
<div class="speaker-list">
<ul>
<li class="vcard"><h2><a class="url fn" href="/schedule/adamgreenfield/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/brianfling/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/russelldavies/"><NAME></a></h2></li>
<li class="vcard "><h2><a class="url fn" href="/schedule/mikemigurski/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/bencerveny/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/nathanshedroff/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/chrisnoessel"><NAME></a></h2></li>
<li class="vcard selected"><h2><a class="url fn" href="/schedule/robinhunicke/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn n" href="/schedule/augustdelosreyes/"><span class="given-name">August</span> <span class="family-name">de los Reyes</span></a></h2></li>
</ul>
</div><!-- /.speaker-list -->
</div><!-- /.speaker-context -->
<div class="speaker-bio">
<h2>Speaker <strong><NAME></strong></h2>
<p class="description">Robin is a Game Designer and Producer who specializes in new IP aimed at reaching new players. Her titles include MySims and <NAME>'s BAFTA award-winning BOOM BLOX franchise - both made for Nintendo Wii. She recently joined thatgamecompany, whose recent Playstation Network releases Flow and Flower are celebrated for their beauty, whimsy and zen-like economy of action.</p>
<p>An active speaker at the Game Developers Conference, Robin co-organizes annual events like the Game Design Workshop and Experimental Gameplay Sessions. She is an advisor for the Global Game Jam, the IGDA Education SIG and the Anita Borg foundation. In her spare time, she is also finishing her PhD in AI and Game Design at Northwestern University.</p>
<p>In just over 50 years, games they have changed the way we think about computers, theater, television and film. They redefine how we consume (and produce) entertainment. To expand their expressive capabilities, we must solve some non-trivial problems. Each year brings us closer to new solutions… in academia and development alike. By participating in these two cultures, Robin hopes to support and sustain cross-disciplinary/cross-pollinating work!</p>
<ul class="social-networks">
<li><a class="button" href="http://twitter.com/hunicke"><span><img alt="Twitter" src="/images/logo-twitter.gif"></span></a></li>
</ul>
</div><!-- /.speaker-bio -->
<div class="speaker-talk">
<h2><strong>Loving Your Player with Juicy Feedback</strong></h2>
<p>The games we love also love us back - mostly, by reflecting our successes and failures in delicious ways. This talk will explore the concept of feedback in game design, using examples drawn from both personal & professional experience. We’ll examine a variety of feedback mechanisms (good and bad), and discuss how lessons drawn from these examples can be applied to any user experience.</p>
<object type="application/x-shockwave-flash" data="http://huffduffer.com/flash/player.swf?soundFile=http://dconstruct.s3.amazonaws.com/2009/podcast/dConstruct2009-Hunicke.mp3" width="290" height="24"><param name="movie" value="http://huffduffer.com/flash/player.swf?soundFile=http://dconstruct.s3.amazonaws.com/2009/podcast/dConstruct2009-Hunicke.mp3"><param name="wmode" value="transparent"><a href="http://huffduffer.com/dConstruct/8340">Loving Your Player With Juicy Feedback on Huffduffer</a></object>
<p><a rel="enclosure" href="http://dconstruct.s3.amazonaws.com/2009/podcast/dConstruct2009-Hunicke.mp3">Download the audio</a></p>
<p><a href="/podcast/juicyfeedback">Read the transcript</a></p>
</div><!-- /.speaker-talk -->
</div><!-- /.speaker -->
</div><!-- /.section -->
<!-- FOOTER -->
<?php include($dr . "footer.inc.php"); ?><file_sep><?php
$title = "Location";
$section = "location";
?>
<?php $dr = str_replace($_SERVER['SCRIPT_NAME'], '/includes/', $_SERVER['SCRIPT_FILENAME']); ?>
<?php
switch($_SERVER['HTTP_HOST']):
case '2009.dconstruct.dev':
$googlemapskey = '<KEY>';
break;
default:
$googlemapskey = '<KEY>';
break;
endswitch;
$scripts = '
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1");
</script>
<script type="text/javascript" src="/js/map.js"></script>
<script src="http://maps.google.com/maps?file=api&v=1&key='.$googlemapskey.'" type="text/javascript"></script>
';
?>
<?php include($dr . "head.inc.php"); ?><!-- HEADER -->
<!-- SECTION LOCATION -->
<div class="section">
<div class="highlight">
<div class="vcard conference-location">
<span class="fn org">Brighton Dome</span>
<span class="adr">
<span class="region">Brighton</span>
<span class="street-address">Church Street</span>
<span class="postal-code">BN1 1UG</span>
<span class="country-name">United Kingdom</span>
</span>
</div>
<!-- end .highlight -->
<!-- Map Key -->
<ul class="map-key">
<li class="vcard">
<img src="/images/circle_blue.gif" alt="blue circle">
<span>Conference</span>
<span class="fn org">Brighton Dome</span>
<abbr class="adr geo" title="50.8235;-0.138">
<span class="street-address">Church Street</span>
</abbr>
</li>
<li class="vcard">
<img src="/images/circle_green.gif" alt="green circle">
<span>Workshops</span>
<span class="fn org">Clearleft</span>
<abbr class="adr geo" title="50.82636;-0.1382">
<span class="street-address">28 Kensington Street</span>
</abbr>
</li>
</ul>
<ul class="map-key">
<li class="vcard">
<img src="/images/circle_orange.gif" alt="orange circle">
<span class="fn org">Brighton Train Station</span>
<abbr class="adr geo" title="50.828907;-0.140623">
<span class="street-address">Queens Road</span>
</abbr>
</li>
<li class="vcard">
<img src="/images/circle_purple.gif" alt="purple circle">
<span>Pre-party</span>
<span class="fn org">Po Na Na</span>
<abbr class="adr geo" title="50.81968;-0.13905">
<span class="street-address">75/79 East Street</span>
</abbr>
</li>
<li class="vcard">
<img src="/images/circle_pink.gif" alt="pink circle">
<span>After-party</span>
<span class="fn org">Above Audio</span>
<abbr class="adr geo" title="50.81965;-0.13443">
<span class="street-address">10 Marine Parade</span>
</abbr>
</li>
</ul>
</div>
<!-- end .highlight -->
<div class="recommendations">
<!-- Accomodation -->
<div class="accomodation">
<h3 id="places"><a href="http://maps.google.co.uk/maps?q=hotels&near=BN1+1UE">Accommodation</a></h3>
<table>
<tr class="vcard">
<td>
<span class="fn org">myhotel</span>
<abbr class="adr geo" title="50.82451;-0.13857">
<span class="street-address">17 Jubilee Street</span>
</abbr>
<span class="tel">+44 (0)1273 900 300</span>
</td>
<td class="url">
<a class="url" href="http://www.myhotels.com/default.asp?section=60">website</a>
</td>
</tr>
<tr class="vcard">
<td>
<span class="fn org">Old Ship Hotel</span>
<abbr class="adr geo" title="50.820401;-0.141953">
<span class="street-address">31–38 Kings Road</span>
</abbr>
<span class="tel">+44 (0)1273 329 001</span>
</td>
<td class="url">
<a class="url" href="http://www.paramount-hotels.co.uk/hotels/southern-england/paramount-old-ship-hotel/">website</a>
</td>
</tr>
<tr class="vcard">
<td>
<span class="fn org">Premier Inn</span>
<abbr class="adr geo" title="50.823274;-0.140912">
<span class="street-address">144 North Street</span>
</abbr>
<span class="tel">+44 (0)87 0990 6340</span>
</td>
<td class="url">
<a class="url" href="http://www.premierinn.com/pti/pTiibsRedirect.do?INNID=BRIPTI">website</a>
</td>
</tr>
</table>
</div><!-- end .accomodation -->
<!-- Eating -->
<div class="eating">
<h3><a href="http://maps.google.co.uk/maps?q=restaurants&near=BN1+1UE">Eating</a></h3>
<table>
<tr class="hreview">
<td class="item vcard">
<span class="fn org">E-Kagen</span>
<abbr class="adr geo" title="50.8279;-0.13785">
<span class="street-address">22–23 Sydney Street</span>
</abbr>
<p class="summary">Superb Japanese food served in an unassuming setting.</p>
</td>
<td>
<img class="rating" src="/images/stars-5.gif" alt="5"><span class="rating-context">stars out of 5</span>
</td>
</tr>
<tr class="hreview">
<td class="item vcard">
<span class="fn org">Wagamama Noodle Bar</span>
<abbr class="adr geo" title="50.82565;-0.13845">
<span class="street-address">Kensington St</span>
</abbr>
<p class="summary">Asian food chain with lots of seating.</p>
</td>
<td>
<img class="rating" src="/images/stars-4.gif" alt="4"><span class="rating-context">star out of 5</span>
</td>
</tr>
<tr class="hreview">
<td class="item vcard">
<span class="fn org">Gourmet Burger Company</span>
<abbr class="adr geo" title="50.824854;-0.139335">
<span class="street-address">44–47 Gardner Street</span>
</abbr>
<p class="summary">Not bad for a burger chain.</p>
</td>
<td>
<img class="rating" src="/images/stars-3.gif" alt="3"><span class="rating-context">stars out of 5</span>
</td>
</tr>
<tr class="hreview">
<td class="item vcard">
<span class="fn org">Strada</span>
<abbr class="adr geo" title="50.822868;-0.139915">
<span class="street-address">160–161 North Street</span>
</abbr>
<p class="summary">Reliable Italian fare.</p>
</td>
<td>
<img class="rating" src="/images/stars-3.gif" alt="3"><span class="rating-context">star out of 5</span>
</td>
</tr>
</table>
</div>
<!-- end .eating -->
<!-- Wifi -->
<div class="wifi">
<h3><a href="http://sussexdigital.com/map">Free WiFi</a></h3>
<table>
<tr class="hreview">
<td class="item vcard">
<span class="fn org">Earth and Stars</span>
<abbr class="adr geo" title="50.82476;-0.14221">
<span class="street-address">46 Windsor Street</span>
</abbr>
<p class="summary">Locally sourced food and organic beer 4/5</p>
</td>
<td>
<img class="rating" src="/images/stars-4.gif" alt="4"><span class="rating-context">stars out of 5</span>
</td>
</tr>
<tr class="hreview">
<td class="item vcard">
<span class="fn org">Riki-Tik</span>
<abbr class="adr geo" title="50.8237;-0.14025">
<span class="street-address">18a Bond Street</span>
</abbr>
<p class="summary">The kids really like this trendy bar</p>
</td>
<td>
<img class="rating" src="/images/stars-3.gif" alt="3"><span class="rating-context">stars out of 5</span>
</td>
</tr>
<tr class="hreview">
<td class="item vcard">
<span class="fn org">Café Delice</span>
<abbr class="adr geo" title="50.82565;-0.13896">
<span class="street-address">40 Kensington Gardens</span>
</abbr>
<p class="summary">Lovely French Café</p>
</td>
<td>
<img class="rating" src="/images/stars-4.gif" alt="4"><span class="rating-context">stars out of 5</span>
</td>
</tr>
</table>
</div><!-- end .wifi -->
</div><!-- end .recommendations -->
</div><!-- end .section -->
<!-- FOOTER -->
<?php include($dr . "footer.inc.php"); ?><file_sep><?php $dr = str_replace($_SERVER['SCRIPT_NAME'], '/includes/', $_SERVER['SCRIPT_FILENAME']); ?>
<?php
$title = "<NAME>";
$section = "schedule";
?>
<?php include($dr . "head.inc.php"); ?><!-- HEADER -->
<div class="section">
<div class="speaker">
<div class="speaker-context">
<img class="speaker-badge" alt="<NAME>" src="/images/speaker-badge-russell-davies.png">
<div class="speaker-list">
<ul>
<li class="vcard"><h2><a class="url fn" href="/schedule/adamgreenfield/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/brianfling/"><NAME></a></h2></li>
<li class="vcard selected"><h2><a class="url fn" href="/schedule/russelldavies/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/mikemigurski/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/bencerveny/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/nathanshedroff/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/chrisnoessel"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/robinhunicke/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn n" href="/schedule/augustdelosreyes/"><span class="given-name">August</span> <span class="family-name">de los Reyes</span></a></h2></li>
</ul>
</div><!-- /.speaker-list -->
</div><!-- /.speaker-context -->
<div class="speaker-bio">
<h2>Speaker <strong><NAME></strong></h2>
<p class="description">Russell was born in Derby, enjoyed an uneventful childhood, did college, all that. After failing as a popstar and a joke writer he ended up in advertising and tried to do ‘interactive marketing’ way before anyone was interested. Ended up at Wieden + Kennedy working on clients like Microsoft, Nike and Honda. Then he went to work for Nike as Global Consumer Planning Director.</p>
<p>He went freelance in 2006 and works with shadowy organisations like the Open Intelligence Agency and the Really Interesting Group. He also writes <a href="http://www.eggbaconchipsandbeans.com/">eggbaconchipsandbeans</a> occasionally organises ‘Interesting’ conferences, plays with things like <a href="http://www.speechification.com/">speechification</a>, <a href="http://www.dawdlr.com/">dawdlr</a> and <a href="http://www.slowpoke.me/">slowpoke</a> and does columns for Campaign magazine and Wired UK.</p>
<p>If asked what he actually does all day, he’ll normally mutter something about ‘post-digital’.</p>
<ul class="social-networks">
<li><a class="button" href="http://twitter.com/undermanager"><span><img alt="Twitter" src="/images/logo-twitter.gif"></span></a></li>
<li><a class="button" href="http://www.dopplr.com/traveller/russelldavies"><span><img alt="Dopplr" src="/images/logo-dopplr.gif"></span></a></li>
</ul>
<p><a href="http://www.eggbaconchipsandbeans.com/">eggbaconchipsandbeans.com</a></p>
</div><!-- /.speaker-bio -->
<div class="speaker-talk">
<h2><strong>Materialising and Dematerialising A Web of Data. (Or What We’ve Learned From Printing The Internet Out)</strong></h2>
<p>A couple of years back <NAME> talked at dConstruct about ’Designing For A Web of Data’, about the idea that your data, the bits that represent you and are useful or interesting to you on the web, are escaping the confines of particular websites and are getting smeared around the web through services and APIs and widgets and myriad other things. (I hope I’m paraphrasing him fairly.) And then, last year, <NAME> and Biddulph took that on more and talked about ’Designing For The Coral Reef’ and about how they were spreading Dopplr via that web of data, and onto devices, and asynchronous infrastructures and distributed interwoven systems, and slippy maps and geography, and there was a rubber duck in there somewhere as well.</p>
<p>I loved all that. I wanted to make a contribution to that conversation. But my technical abilities are such that all I can really do to manipulate the web is print it out, and that didn't seem enough.</p>
<p>And then I got involved with making <a href="http://www.reallyinterestinggroup.com/tofhwoti.html">Things Our Friends Have Written On The Internet</a> and I realised that printing it out is the next step. What's happening now is that the web of data wants to escape the screen, it wants to materialise into the real world, it wants to get physical, become objects. And that the next exciting stuff is going to be about designing data that can live on the screen, in devices, on paper, as things, wherever.</p>
<p>So that's what I’m hoping to talk about. About getting a little post-digital, about analogue friction, about printing to large industrial infrastructures, about unproducts and letter-boxes and rabbits. And there’ll be jokes and silly videos too.</p>
<object type="application/x-shockwave-flash" data="http://huffduffer.com/flash/player.swf?soundFile=http://dconstruct.s3.amazonaws.com/2009/podcast/dConstruct2009-Davies.mp3" width="290" height="24"><param name="movie" value="http://huffduffer.com/flash/player.swf?soundFile=http://dconstruct.s3.amazonaws.com/2009/podcast/dConstruct2009-Davies.mp3"><param name="wmode" value="transparent"><a href="http://huffduffer.com/dConstruct/8908">Materialising and Dematerialising A Web of Data. (Or What We’ve Learned From Printing The Internet Out) on Huffduffer</a></object>
<p><a rel="enclosure" href="http://dconstruct.s3.amazonaws.com/2009/podcast/dConstruct2009-Davies.mp3">Download the audio</a></p>
<p><a href="/podcast/materialising">Read the transcript</a></p>
</div><!-- /.speaker-talk -->
</div><!-- /.speaker -->
</div><!-- /.section -->
<!-- FOOTER -->
<?php include($dr . "footer.inc.php"); ?><file_sep><?php //$dr = str_replace($_SERVER['SCRIPT_NAME'], '/includes/', $_SERVER['SCRIPT_FILENAME']); ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="User Experience Design, Conference, Event, Brighton, ClearLeft">
<meta name="description" content="dConstruct is an affordable, one-day conference aimed at those building the latest generation of websites. The event discusses how to design websites that not only work, but are an enjoyable experience for the user.">
<meta name="geo.position" content="50.8234;-0.1382">
<meta name="ICBM" content="50.8234,-0.1382">
<link rel="alternate" type="application/rss+xml" title="Clearleft Events" href="http://feeds.feedburner.com/ClearleftEvents">
<link rel="alternate" type="application/rss+xml" title="dConstruct 2009 podcast" href="http://huffduffer.com/dConstruct/tags/dconstruct09">
<?php
$title = (isset($title) && $title != '')?"$title | ":"";
$section = (isset($section) && $section != '')?$section:"home";
?>
<title><?php echo $title ?>dConstruct 2009</title>
<link rel="stylesheet" href="/styles/main.css?20091130" type="text/css" media="screen,projection" charset="utf-8">
<link rel="stylesheet" href="/styles/print.css?20091130" type="text/css" media="print" charset="utf-8">
<!--[if lt IE 7]>
<script type="text/javascript" src="/js/iepngfix_tilebg.js"></script>
<script type="text/javascript" src="/js/minmax.js"></script>
<link rel="stylesheet" href="/styles/ie6.css" type="text/css" media="screen,projection" charset="utf-8">
<![endif]-->
<!--[if IE 7]>
<link rel="stylesheet" href="/styles/ie.css" type="text/css" media="screen,projection" charset="utf-8">
<![endif]-->
<?php echo @$scripts ?>
</head>
<body class="<?php echo $section ?>">
<div class="header">
<!-- Branding-->
<div class="section vevent">
<p><a href="http://clearleft.com"><span>Clearleft</span> presents</a></p>
<h1><a class="url" href="/"><img class="summary uid" alt="dConstruct 2009" src="/images/dconstruct-logo.gif"></a></h1>
<h2 class="description">Designing for Tomorrow</h2>
<h3><abbr title="2009-09-04" class="dtstart">04 September 2009</abbr> · <span class="location">Brighton Dome</span> UK</h3>
</div>
<!-- Navigation-->
<div class="navigation">
<ol>
<li class="page-home"><span><a href="/">Home</a></span></li>
<li class="page-schedule"><span><a href="/schedule/">Schedule</a></span></li>
<li class="page-workshops"><span><a href="/workshops/">Workshops</a></span></li>
<li class="page-location"><span><a href="/location/">Location</a></span></li>
<li class="page-podcast"><span><a href="/podcast/">Podcast</a></span></li>
</ol>
</div>
</div><!-- /.header -->
<div class="content">
<file_sep><?php $dr = str_replace($_SERVER['SCRIPT_NAME'], '/includes/', $_SERVER['SCRIPT_FILENAME']); ?>
<?php
$title = "<NAME>";
$section = "schedule";
?>
<?php include($dr . "head.inc.php"); ?><!-- HEADER -->
<div class="section">
<div class="speaker">
<div class="speaker-context">
<img class="speaker-badge" alt="<NAME>" src="/images/speaker-badge-brian-fling.png">
<div class="speaker-list">
<ul>
<li class="vcard"><h2><a class="url fn" href="/schedule/adamgreenfield/"><NAME></a></h2></li>
<li class="vcard selected"><h2><a class="url fn" href="/schedule/brianfling/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/russelldavies/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/mikemigurski/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/bencerveny/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/nathanshedroff/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/chrisnoessel"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/robinhunicke/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn n" href="/schedule/augustdelosreyes/"><span class="given-name">August</span> <span class="family-name">de los Reyes</span></a></h2></li>
</ul>
</div><!-- /.speaker-list -->
</div><!-- /.speaker-context -->
<div class="speaker-bio">
<h2>Speaker <strong><NAME></strong></h2>
<p class="description"><NAME> has been a leader in creating interactive experiences for both the web and mobile mediums. He has worked with hundreds of businesses from early stage start-ups to Fortune 50 companies to leverage new media around the needs of real peoples.</p>
<p>Brian is a frequent speaker and author on the issues on mobile design, the mobile web and mobile user experience. He was the principle author of the free dotMobi Mobile Web Developer’s guide , downloaded thousands of times over. He is currently writing Mobile Design and Development for O’Reilly Media, due out later this year.</p>
<p>Currently Brian is the founder and president of pinch/zoom.</p>
<ul class="social-networks">
<li><a class="button" href="http://twitter.com/fling"><span><img alt="Twitter" src="/images/logo-twitter.gif"></span></a></li>
<li><a class="button" href="http://www.dopplr.com/traveller/fling"><span><img alt="Dopplr" src="/images/logo-dopplr.gif"></span></a></li>
</ul>
<p><a href="http://flinglog.com/">Flinglog.com</a></p>
<p><a href="http://flingmedia.com/">Flingmedia.com</a></p>
</div><!-- /.speaker-bio -->
<div class="speaker-talk">
<h2>Talk <strong>What’s Next? How mobile is changing design</strong></h2>
<p>Mobile is evolving, the web is adapting, and these two colossal worlds are about to collide to create something new. In order to design the experiences of this new contextual web, we need to change the way we look at design. In this talk Brian will provide his insights on some of the emerging trends in mobile design and share his thoughts on how we will design the interfaces of tomorrow.</p>
<object type="application/x-shockwave-flash" data="http://huffduffer.com/flash/player.swf?soundFile=http://dconstruct.s3.amazonaws.com/2009/podcast/dConstruct2009-Fling.mp3" width="290" height="24"><param name="movie" value="http://huffduffer.com/flash/player.swf?soundFile=http://dconstruct.s3.amazonaws.com/2009/podcast/dConstruct2009-Fling.mp3"><param name="wmode" value="transparent"><a href="http://huffduffer.com/dConstruct/7908">What’s Next? How Mobile is Changing Design by <NAME> on Huffduffer</a></object>
<p><a rel="enclosure" href="http://dconstruct.s3.amazonaws.com/2009/podcast/dConstruct2009-Fling.mp3">Download the audio</a></p>
<p><a href="/podcast/mobiledesign">Read the transcript</a></p>
</div><!-- /.speaker-talk -->
<div class="speaker-talk">
<h2>Workshop <strong>Designing Mobile Experiences</strong></h2>
<p>In the last year we’ve learned something that we suspected, but never really knew about mobile, great mobile design sells. But great mobile design doesn’t start in Photoshop, it starts by understanding the users, the business goals, the intended devices and a million other tiny variables. Who better to solve these problems than the designer?</p>
<p><a href="/workshops/#designing-mobile-experiences">Read More</a></p>
</div><!-- /.speaker-talk -->
</div><!-- /.speaker -->
</div><!-- /.section -->
<!-- FOOTER -->
<?php include($dr . "footer.inc.php"); ?><file_sep><?php $dr = str_replace($_SERVER['SCRIPT_NAME'], '/includes/', $_SERVER['SCRIPT_FILENAME']); ?>
<?php
$title = "<NAME>";
$section = "schedule";
?>
<?php include($dr . "head.inc.php"); ?><!-- HEADER -->
<div class="section">
<div class="speaker">
<div class="speaker-context">
<img class="speaker-badge" alt="<NAME>" src="/images/speaker-badge-natalie-downe.png">
</div><!-- /.speaker-context -->
<div class="speaker-bio">
<h2>Workshop Leader <strong><NAME></strong></h2>
<p class="description"><NAME> is a perfectionist by nature and works for Brighton’s Clearleft as a client-side web developer. An experienced usability consultant and project manager, her first loves remain in front-end development and usability engineering. She enjoys Doing Things Right and occasionally dabbling in the dark arts of Python and poking the odd API</p>
<p>Natalie occasional blogs at <a href="http://natbat.net">natbat.net</a> and randomly rambles on <a href="http://twitter.com/natbat">Twitter</a>.</p>
</div>
<div class="speaker-talk">
<h2>Workshop:<strong>HTML5 and CSS3 Wizardry</strong></h2>
<p>HTML5 and CSS3 may be considered by some as distant concepts: far in the future and irrelevant to their daily lives. However, in this day-long workshop by Clearleft’s expert client-side engineers <NAME>, <NAME> and <NAME>, you will learn how these exciting new concepts can be applied today!</p>
<p><a href="/workshops/#html5-css3">Read More</a></p>
</div><!-- /.speaker-talk -->
</div>
</div>
<!-- FOOTER -->
<?php include($dr . "footer.inc.php"); ?><file_sep><?php $dr = str_replace($_SERVER['SCRIPT_NAME'], '/includes/', $_SERVER['SCRIPT_FILENAME']); ?>
<?php
$title = "<NAME>";
$section = "schedule";
?>
<?php include($dr . "head.inc.php"); ?><!-- HEADER -->
<div class="section">
<div class="speaker">
<div class="speaker-context">
<img class="speaker-badge" alt="<NAME>" src="/images/speaker-badge-jeremy-keith.png">
</div><!-- /.speaker-context -->
<div class="speaker-bio">
<h2>Workshop Leader <strong><NAME></strong></h2>
<p class="description">Forged in the fiery heart of the Earth’s molten core, <NAME> studied Ottistry at Saint Calrissian’s school for wayward punctuation before going on to become the largest condiment visible from space.</p>
<p>Born at an early age, Jeremy moved from his native Ireland to the rocky shores of Brighton, England where he works with Clearleft as a stuck-up, half-witted, scruffy-looking nerf herder.</p>
<p>He has written two books, <a href="http://domscripting.com/">DOM Scripting</a> and <a href="http://bulletproofajax.com/">Bulletproof Ajax</a>, but what he really wants to do is direct.</p>
<p>His latest project is <a href="http://huffduffer.com/">Huffduffer</a>, a service for creating podcasts of found sounds. When he’s not making websites, Jeremy plays bouzouki in the band <a href="http://saltercane.com/">Salter Cane</a>. His loony bun is fine benny lava.</p>
</div>
<div class="speaker-talk">
<h2>Workshop:<strong>HTML5 and CSS3 Wizardry</strong></h2>
<p>HTML5 and CSS3 may be considered by some as distant concepts: far in the future and irrelevant to their daily lives. However, in this day-long workshop by Clearleft’s expert client-side engineers <NAME>, <NAME> and <NAME>, you will learn how these exciting new concepts can be applied today!</p>
<p><a href="/workshops/#html5-css3">Read More</a></p>
</div><!-- /.speaker-talk -->
</div>
</div>
<!-- FOOTER -->
<?php include($dr . "footer.inc.php"); ?><file_sep><?php $dr = str_replace($_SERVER['SCRIPT_NAME'], '/includes/', $_SERVER['SCRIPT_FILENAME']); ?>
<?php
$title = "Workshops: HTML5 and CSS3 Wizardry";
$section = "workshops";
?>
<?php include($dr . "head.inc.php"); ?><!-- HEADER -->
<!-- SECTION WORKSHOP -->
<div class="section">
<h2><a href="../">HTML5 and CSS3 Wizardry</a></h2>
<h3>HTML5</h3>
<ul>
<li><a href="slides/">Slides</a></li>
<li><a href="examples/">Examples</a></li>
</ul>
</div>
<!-- FOOTER -->
<?php include($dr . "footer.inc.php"); ?><file_sep><?php $dr = str_replace($_SERVER['SCRIPT_NAME'], '/includes/', $_SERVER['SCRIPT_FILENAME']); ?>
<?php
$title = "<NAME>";
$section = "schedule";
?>
<?php include($dr . "head.inc.php"); ?><!-- HEADER -->
<div class="section">
<div class="speaker">
<div class="speaker-context">
<img class="speaker-badge" alt="<NAME>" src="/images/speaker-badge-nathan-shedroff.png">
<div class="speaker-list">
<ul>
<li class="vcard"><h2><a class="url fn" href="/schedule/adamgreenfield/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/brianfling/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/russelldavies/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/mikemigurski/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/bencerveny/"><NAME></a></h2></li>
<li class="vcard selected"><h2><a class="url fn" href="/schedule/nathanshedroff/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/chrisnoessel"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/robinhunicke/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn n" href="/schedule/augustdelosreyes/"><span class="given-name">August</span> <span class="family-name">de los Reyes</span></a></h2></li>
</ul>
</div><!-- /.speaker-list -->
</div><!-- /.speaker-context -->
<div class="speaker-bio">
<h2>Speaker <strong><NAME></strong></h2>
<p class="description"><NAME> is the chair of the ground-breaking MBA in Design Strategy at California College of the Arts (CCA) in San Francisco, CA. This program melds the unique principles that design offers business strategy with a vision of the future of business as sustainable, meaningful, and truly innovative — as well as profitable. <!-- www.designmba.org --></p>
<p>He is one of the pioneers in Experience Design, an approach to design that encompasses multiple senses and requirements and explores common characteristics in all media that make experiences successful, as well as related fields, Interaction Design and Information Design. He speaks and teaches internationally and has written extensively on design and business issues, including, Experience Design 1 and maintains a website with resources on Experience Design at <a href="http://www.nathan.com/ed">www.nathan.com/ed</a>.</p>
<p>Nathan is a serial entrepreneur, works in several media, and consults strategically for companies to build better, more meaningful experiences for their customers. He lives in San Francisco where the climate, culture, and industry make it easy to have an esoteric and amorphous title like Experience Strategist and actually make a living.</p>
<p>His latest book, <a href="http://www.makingmeaning.org/">Making Meaning</a>, co-written with two members of Cheskin, a Silicon Valley-based strategy consultancy, explores how companies can specifically create products and services to evoke meaning in their audiences and customers.</p>
<p>He has three new books debuting in the beginning of 2009: <a href="http://www.rosenfeldmedia.com/books/sustainable-design/">Design is the Problem</a>, about sustainable design; <a href="http://www.experiencedesignbooks.com/EXP1.1/index.html">Experience Design 1.1</a>, an update to his 2001 book; and Experience Design 1 Cards, a design tool based on his book that helps designers create more meaningful experiences.</p>
<p>In 2006, Nathan earned a Masters in Business Administration at Presidio School of Management in San Francisco, CA, the only accredited MBA program in the USA specializing in Sustainable Business.</p>
<p>Nathan earned a BS in Industrial Design, with an emphasis on Automobile Design from the Art Center College of Design in Pasadena. However, fear of Detroit coupled with a passion for information design led Nathan into this arena, where he worked with <NAME> at TheUnderstandingBusiness. Later, he co-founded vivid studios, a decade-old pioneering company in interactive media and one of the first Web services firms on the planet. vivid’s hallmark was helping to establish and validate the field of information architecture, by training an entire generation of designers in the newly emerging Web industry.</p>
<p>Nathan was nominated for a Chrysler Innovation in Design Award in 1994 and 1999 and a National Design Award in 2001.</p>
<p><a href="http://www.nathan.com/">nathan.com</a></p>
</div><!-- /.speaker-bio -->
<div class="speaker-talk">
<h2><strong>Make It So: Learning From SciFi Interfaces</strong></h2>
<div class="blurb">
<p>Make It So explores how science fiction and interface design relate to each other. The authors have developed a model that traces lines of influence between the two, and use this as a scaffold to investigate how the depiction of technologies evolve over time, how fictional interfaces influence those in the real world, and what lessons interface designers can learn through this process. This investigation of science fiction television shows and movies has yielded practical lessons that apply to online, social, mobile, and other media interfaces.</p>
<object type="application/x-shockwave-flash" data="http://huffduffer.com/flash/player.swf?soundFile=http://dconstruct.s3.amazonaws.com/2009/podcast/dConstruct2009-Shedroff-Noessel.mp3" width="290" height="24"><param name="movie" value="http://huffduffer.com/flash/player.swf?soundFile=http://dconstruct.s3.amazonaws.com/2009/podcast/dConstruct2009-Shedroff-Noessel.mp3"><param name="wmode" value="transparent"><a href="http://huffduffer.com/dConstruct/8112">Make It So: Learning From SciFi Interfaces by <NAME> and <NAME> on Huffduffer</a></object>
<p><a rel="enclosure" href="http://dconstruct.s3.amazonaws.com/2009/podcast/dConstruct2009-Shedroff-Noessel.mp3">Download the audio</a></p>
<p><a href="/podcast/makeitso">Read the transcript</a></p>
</div><!-- /.blurb -->
</div><!-- /.speaker-talk -->
</div><!-- /.speaker -->
</div><!-- /.section -->
<!-- FOOTER -->
<?php include($dr . "footer.inc.php"); ?><file_sep><?php $dr = str_replace($_SERVER['SCRIPT_NAME'], '/includes/', $_SERVER['SCRIPT_FILENAME']); ?>
<?php
$title = "<NAME>";
$section = "schedule";
?>
<?php include($dr . "head.inc.php"); ?><!-- HEADER -->
<div class="section">
<div class="speaker">
<div class="speaker-context">
<img class="speaker-badge" alt="<NAME>" src="/images/speaker-badge-remy-sharp.png">
</div><!-- /.speaker-context -->
<div class="speaker-bio">
<h2>Workshop Leader <strong><NAME></strong></h2>
<p class="description"><NAME> cut his teeth in web development 10 years ago as the sole developer for finance web site, Digital Look, which groomed him to be the one man coding machine he is today. Now he runs his own Brighton based development company, called Left Logic coding and writing about JavaScript, jQuery, HTML, CSS, PHP, Perl and anything else he can get his hands on.</p>
<p>While he’s not busy working, Remy is either blogging at <a href="http://remysharp.com">remysharp.com</a> or at <a href="http://jqueryfordesigners.com">jqueryfordesigners.com</a> when he should probably enjoying his spare time with his wife.</p>
<ul class="social-networks">
<li><a class="button" href="http://www.flickr.com/photos/remysharp/"><span><img alt="Flickr" src="/images/logo-flickr.gif"></span></a></li>
<li><a class="button" href="http://twitter.com/rem"><span><img alt="Twitter" src="/images/logo-twitter.gif"></span></a></li>
</ul>
</div>
<div class="speaker-talk">
<h2>Workshop:<strong>jQuery for Designers</strong></h2>
<p>If you’ve found you've needed to write a bit (or more!) of interactive functionality using JavaScript, and couldn't because you a) didn't know how and b) didn’t have time to learn how: then this workshop is for you.</p>
<p><a href="/workshops/#jquery-for-designers">Read More</a></p>
</div><!-- /.speaker-talk -->
</div>
</div>
<!-- FOOTER -->
<?php include($dr . "footer.inc.php"); ?><file_sep><?php $dr = str_replace($_SERVER['SCRIPT_NAME'], '/includes/', $_SERVER['SCRIPT_FILENAME']); ?>
<?php
$title = "Schedule";
$section = "schedule";
?>
<?php include($dr . "head.inc.php"); ?><!-- HEADER -->
<!-- SECTION SCHEDULE -->
<div class="section schedule">
<h2>Schedule</h2>
<div class="highlight-container">
<div class="first highlight vevent">
<h3>02 Sept</h3>
<h4><a href="/workshops/"><strong class="summary">Workshops</strong></a></h4>
<h5><abbr class="dtstart" title="2009-09-02T09:30:00">09.30</abbr> – <abbr class="dtend" title="2009-09-02T17:30:00">17:30</abbr></h5>
<p class="location">Clearleft, 28 Kensington St, BN1 4AJ</p>
</div>
<div class="highlight vevent">
<h3>03 Sept</h3>
<h4><a href="/workshops/"><strong class="summary">Workshops</strong></a></h4>
<h5><abbr class="dtstart" title="2009-09-03T09:30:00">09.30</abbr> – <abbr class="dtend" title="2009-09-03T17:30:00">17:30</abbr></h5>
<p class="location">Clearleft, 28 Kensington St, BN1 4AJ</p>
</div>
<div class="highlight vevent">
<h3>04 Sept</h3>
<h4><strong class="summary">Conference</strong></h4>
<h5><abbr class="dtstart" title="2009-09-04T09:00:00">09.00</abbr> – <abbr class="dtend" title="2009-09-04T18:00:00">18:00</abbr></h5>
<p class="location">B<NAME>, BN1 1UG</p>
</div>
</div>
<div class="lead">
<p class="description">Future proof your design and development skills with this year's dConstruct. We’ll be covering the latest trends from the brightest thinkers in the industry. Everything from mobile design and gestural interactions to ubiquitous computing and sci-fi interfaces.</p>
<p class="description">Just don’t forget your jet pack.</p>
<img src="/images/soldout.png" alt="sorry we've sold out!" class="soldout" />
</div>
<table>
<tr class="vevent">
<th>
<abbr class="dtstart" title="2009-09-03T09:00:00">20.00, Thurs</abbr>
</th>
<td class="summary">Pre Party at Po Na Na, all welcome!</td>
<td class="person"><a href="/location">map</a></td>
</tr>
<tr class="vevent">
<th>
<abbr class="dtstart" title="2009-09-04T09:00:00">09.00, Fri</abbr>
</th>
<td class="summary">Registration</td>
<td class="person"></td>
</tr>
<tr class="vevent">
<th>
<abbr class="dtstart" title="2009-09-04T10:00:00">10.00</abbr>
–
<abbr class="dtend" title="2009-09-04T10:15:00">10.15</abbr>
</th>
<td class="summary">Opening Remarks</td>
<td class="person vcard"><a class="fn url" rel="tag" href="/schedule/richardrutter/"><NAME></a></td>
</tr>
<tr class="vevent">
<th>
<abbr class="dtstart" title="2009-09-04T10:15:00">10.15</abbr>
–
<abbr class="dtend" title="2009-09-04T11:00:00">11:00</abbr>
</th>
<td class="summary"><a href="/schedule/adamgreenfield/">Elements of a Networked Urbanism</a></td>
<td class="person vcard"><a class="fn url" rel="tag" href="/schedule/adamgreenfield/"><NAME></a></td>
</tr>
<tr class="vevent">
<th>
<abbr class="dtstart" title="2009-09-04T11:00:00">11.00</abbr>
–
<abbr class="dtend" title="2009-09-04T11:30:00">11:30</abbr>
</th>
<td class="summary">Break (Tea, coffee & biscuits)</td>
<td class="person"></td>
</tr>
<tr class="vevent">
<th><abbr class="dtstart" title="2009-09-04T11:30:00">11.30</abbr>
–
<abbr class="dtend" title="2009-09-04T12:15:00">12:15</abbr>
</th>
<td class="summary"><a href="/schedule/mikemigurski/">Let's See What We Can See (Everybody Online And Looking Good)</a></td>
<td class="person vcard"><a class="fn url" rel="tag" href="/schedule/mikemigurski/"><NAME></a> and <a class="fn url" rel="tag" href="/schedule/bencerveny/"><NAME></a></td>
</tr>
<tr class="vevent">
<th>
<abbr class="dtstart" title="2009-09-04T12:15:00">12.15</abbr>
–
<abbr class="dtend" title="2009-09-04T13:00:00">13:00</abbr>
</th>
<td class="summary"><a href="/schedule/brianfling/">What’s Next? How mobile is changing design</a></td>
<td class="person vcard"><a class="fn url" rel="tag" href="/schedule/brianfling/"><NAME></a></td>
</tr>
<tr class="vevent">
<th>
<abbr class="dtstart" title="2009-09-04T13:00:00">13.00</abbr>
–
<abbr class="dtend" title="2009-09-04T14:30:00">14:30</abbr>
</th>
<td class="summary">Lunch (not provided)</td>
<td class="person"></td>
</tr>
<tr class="vevent">
<th>
<abbr class="dtstart" title="2009-09-04T14:30:00">14.30</abbr>
–
<abbr class="dtend" title="2009-09-04T15:15:00">15:15</abbr>
</th>
<td class="summary"><a href="/schedule/nathanshedroff/">Make It So: Learning From SciFi Interfaces</a></td>
<td class="person vcard"><a class="fn url" rel="tag" href="/schedule/nathanshedroff/"><NAME></a> and <a class="fn url" rel="tag" href="/schedule/chrisnoessel/"><NAME></a></td>
</tr>
<tr class="vevent">
<th>
<abbr class="dtstart" title="2009-09-04T15:15:00">15.15</abbr>
–
<abbr class="dtend" title="2009-09-04T16:00:00">16:00</abbr>
</th>
<td class="summary"><a href="/schedule/robinhunicke/">Loving Your Player with Juicy Feedback</a></td>
<td class="person vcard"><a class="fn url" rel="tag" href="/schedule/robinhunicke/"><NAME></a></td>
</tr>
<tr class="vevent">
<th>
<abbr class="dtstart" title="2009-09-04T16:00:00">16.00</abbr>
–
<abbr class="dtend" title="2009-09-04T16:30:00">16:30</abbr>
</th>
<td class="summary">Break (tea, coffee & biscuits)</td>
<td class="person"></td>
</tr>
<tr class="vevent">
<th>
<abbr class="dtstart" title="2009-09-04T16:30:00">16.30</abbr>
–
<abbr class="dtend" title="2009-09-04T17:15:00">17:15</abbr>
</th>
<td class="summary"><a href="/schedule/augustdelosreyes/">Experience and the Emotion Commotion</a></td>
<td class="person vcard"><a class="fn url" rel="tag" href="/schedule/augustdelosreyes/">August de los Reyes</a></td>
</tr>
<tr class="vevent">
<th>
<abbr class="dtstart" title="2009-09-04T17:15:00">17.15</abbr>
–
<abbr class="dtend" title="2009-09-04T18:00:00">18:00</abbr>
</th>
<td class="summary"><a href="/schedule/russelldavies/">Materialising and Dematerialising A Web of Data. (Or What We’ve Learned From Printing The Internet Out)</a></td>
<td class="person vcard"><a class="fn url" rel="tag" href="/schedule/russelldavies/"><NAME></a></td>
</tr>
<tr class="vevent">
<th>
<abbr class="dtstart" title="2009-09-04T18:00:00">18.00</abbr>
–
<abbr class="dtend" title="2009-09-04T18:15:00">18:15</abbr>
</th>
<td class="summary">Closing announcements</td>
<td class="person"></td>
</tr>
<tr class="vevent">
<th>
<abbr class="dtstart" title="2009-09-04T19:30:00">19.30</abbr>
</th>
<td class="summary">After Party at Above Audio</td>
<td class="person"><a href="/location">map</a></td>
</tr>
</table>
</div>
<!-- FOOTER -->
<?php include($dr . "footer.inc.php"); ?><file_sep><?php $dr = str_replace($_SERVER['SCRIPT_NAME'], '/includes/', $_SERVER['SCRIPT_FILENAME']); ?>
<?php
$title = "<NAME>";
$section = "schedule";
?>
<?php include($dr . "head.inc.php"); ?><!-- HEADER -->
<div class="section">
<div class="speaker">
<div class="speaker-context">
<img class="speaker-badge" alt="<NAME>" src="/images/speaker-badge-mike-migurski.png">
<div class="speaker-list">
<ul>
<li class="vcard"><h2><a class="url fn" href="/schedule/adamgreenfield/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/brianfling/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/russelldavies/"><NAME></a></h2></li>
<li class="vcard selected"><h2><a class="url fn" href="/schedule/mikemigurski/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/bencerveny/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/nathanshedroff/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/chrisnoessel"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/robinhunicke/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn n" href="/schedule/augustdelosreyes/"><span class="given-name">August</span> <span class="family-name">de los Reyes</span></a></h2></li>
</ul>
</div><!-- /.speaker-list -->
</div><!-- /.speaker-context -->
<div class="speaker-bio">
<h2>Speaker <strong><NAME></strong></h2>
<p class="description"> Stamen partner <NAME> leads the technical and research aspects of Stamen’s work, moving comfortably from active participation in Stamen’s design process, designing data, prototyping applications, to creating the dynamic projects that Stamen delivers to clients.</p>
<p>Michal has been building for the web since 1995, specializing in big, exciting datasets and the means to communicate and disseminate them to broad audiences for a variety of clients. He speaks publicly on these and other topics to academic and industry audiences, participates actively in a variety of open source development efforts, maintains an active weblog, and holds a degree in Cognitive Science from UC Berkeley.</p>
<ul class="social-networks">
<li><a class="button" href="http://twitter.com/migurski"><span><img alt="Twitter" src="/images/logo-twitter.gif"></span></a></li>
<li><a class="button" href="http://www.dopplr.com/traveller/migurski"><span><img alt="Dopplr" src="/images/logo-dopplr.gif"></span></a></li>
</ul>
<p><a href="http://mike.teczno.com">mike.teczno.com</a></p>
</div>
<div class="speaker-talk">
<h2><strong>Let’s See What We Can See (Everybody Online And Looking Good)</strong></h2>
<p>Piece by piece, the world is moving onto the web. "Things informationalize," as Stamen advisor <NAME> puts it. How can we make sense of this new torrent of information emerging wide-eyed and blinking into the internet? Stamen’s <NAME> will show how information visualization is making it possible to comprehend a live, vast, and deep connected web of data, with a special focus on interactive and geographic work.</p>
<object type="application/x-shockwave-flash" data="http://huffduffer.com/flash/player.swf?soundFile=http://dconstruct.s3.amazonaws.com/2009/podcast/dConstruct2009-Migurski-Cerveny.mp3" width="290" height="24"><param name="movie" value="http://huffduffer.com/flash/player.swf?soundFile=http://dconstruct.s3.amazonaws.com/2009/podcast/dConstruct2009-Migurski-Cerveny.mp3"><param name="wmode" value="transparent"><a href="http://huffduffer.com/dConstruct/7687">Let’s See What We Can See (Everybody Online And Looking Good) by <NAME> and <NAME> on Huffduffer</a></object>
<p><a rel="enclosure" href="http://dconstruct.s3.amazonaws.com/2009/podcast/dConstruct2009-Migurski-Cerveny.mp3">Download the audio</a></p>
<p><a href="/podcast/everybodyonline">Read the transcript</a></p>
</div><!-- /.speaker-talk -->
</div><!-- /.speaker -->
</div><!-- /.section -->
<!-- FOOTER -->
<?php include($dr . "footer.inc.php"); ?><file_sep><?php $dr = str_replace($_SERVER['SCRIPT_NAME'], '/includes/', $_SERVER['SCRIPT_FILENAME']); ?>
<?php
$title = "<NAME>";
$section = "schedule";
?>
<?php include($dr . "head.inc.php"); ?><!-- HEADER -->
<div class="section">
<div class="speaker">
<div class="speaker-context">
<img class="speaker-badge" alt="<NAME>" src="/images/speaker-badge-ben-cerveny.png">
<div class="speaker-list">
<ul>
<li class="vcard"><h2><a class="url fn" href="/schedule/adamgreenfield/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/brianfling/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/russelldavies/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/mikemigurski/"><NAME></a></h2></li>
<li class="vcard selected"><h2><a class="url fn" href="/schedule/bencerveny/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/nathanshedroff/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/chrisnoessel"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/robinhunicke/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn n" href="/schedule/augustdelosreyes/"><span class="given-name">August</span> <span class="family-name">de los Reyes</span></a></h2></li>
</ul>
</div><!-- /.speaker-list -->
</div><!-- /.speaker-context -->
<div class="speaker-bio">
<h2>Speaker <strong><NAME></strong></h2>
<p class="description"><NAME> is a strategic and conceptual advisor to Stamen, helping to articulate an approach toward creative visualization and to evaluate and develop potential partners and engagements relative to that vision.</p>
<p>Ben is a highly regarded experience designer and conceptual strategist, guiding the creative direction and vision of multiple successful endeavors, both public and private. His clients include <a href="http://nokia.com/">Nokia</a>, <a href="http://sony.com/">Sony</a>, and <a href="http://philipsusa.com/">Philips</a>, as well as the Cities of Amsterdam and Barcelona. Previously, he was founder of the Experience Design Lab at <a href="http://frogdesign.com/">frogdesign</a>, an international product design company, and a lead designer and platform development strategist at <a href="http://ludicorp.com/">Ludicorp</a>, makers of <a href="http://flickr.com/">Flickr</a>.</p>
<p>Ben is a sixteen-year veteran of the interaction design field. His past accomplishments include the design of network media sharing applications at Be Inc. and <a href="http://www.sgi.com/">Silicon Graphics</a>, and the management of the Research and Development group at web services agency Organic. He is the author of a forthcoming book on games as system models, and is a Director of a research foundation focused on investigating the intersection of play, interaction, and urban space.</p>
</div>
<div class="speaker-talk">
<h2><strong>Let’s See What We Can See (Everybody Online And Looking Good)</strong></h2>
<p>Piece by piece, the world is moving onto the web. "Things informationalize," as Stamen advisor <NAME> puts it. How can we make sense of this new torrent of information emerging wide-eyed and blinking into the internet? Stamen’s M<NAME> will show how information visualization is making it possible to comprehend a live, vast, and deep connected web of data, with a special focus on interactive and geographic work.</p>
<object type="application/x-shockwave-flash" data="http://huffduffer.com/flash/player.swf?soundFile=http://dconstruct.s3.amazonaws.com/2009/podcast/dConstruct2009-Migurski-Cerveny.mp3" width="290" height="24"><param name="movie" value="http://huffduffer.com/flash/player.swf?soundFile=http://dconstruct.s3.amazonaws.com/2009/podcast/dConstruct2009-Migurski-Cerveny.mp3"><param name="wmode" value="transparent"><a href="http://huffduffer.com/dConstruct/7687">Let’s See What We Can See (Everybody Online And Looking Good) by <NAME> and <NAME> on Huffduffer</a></object>
<p><a rel="enclosure" href="http://dconstruct.s3.amazonaws.com/2009/podcast/dConstruct2009-Migurski-Cerveny.mp3">Download the audio</a></p>
<p><a href="/podcast/everybodyonline">Read the transcript</a></p>
</div><!-- /.speaker-talk -->
</div><!-- /.speaker -->
</div><!-- /.section -->
<!-- FOOTER -->
<?php include($dr . "footer.inc.php"); ?><file_sep><?php $dr = str_replace($_SERVER['SCRIPT_NAME'], '/includes/', $_SERVER['SCRIPT_FILENAME']); ?>
<?php
$title = "<NAME>";
$section = "schedule";
?>
<?php include($dr . "head.inc.php"); ?><!-- HEADER -->
<div class="section">
<div class="speaker">
<div class="speaker-context">
<img class="speaker-badge" alt="<NAME>" src="/images/speaker-badge-nick-weldin.png">
</div><!-- /.speaker-context -->
<div class="speaker-bio">
<h2>Workshop Leader <strong><NAME></strong></h2>
<p class="description">Nick had many jobs including pyrotechnician, for companies like Theatre of Fire and Le Maitre, he helped set fire to the Fourth Bridge for its centenary celebrations. He ran an adventure playground for disabled children for Kidsactive and set up a project in the London borough of Westminster developing multimedia work with people with profound learning difficulties and the people who support them, and has played around with electronics since his teenage years.</p>
<p>He works at Tinker as Senior Technologist and at the Rix Centre based at the University of East London developing multimedia work with people with profound learning difficulties.</p>
<p>Nick runs many of the Tinker workshops in London and further afield, including Copenhagen, Portugal and more.</p>
</div>
<div class="speaker-talk">
<h2>Workshop:<strong>Internet of Things Master Class</strong></h2>
<p>This one day intensive hands-on workshop will focus on getting programmers and technologists up to speed about the latest hardware technologies, allowing them to build web-enabled, responsive installations and spaces.</p>
<p><a href="/workshops/#internet-of-things">Read More</a></p>
</div><!-- /.speaker-talk -->
</div>
</div>
<!-- FOOTER -->
<?php include($dr . "footer.inc.php"); ?><file_sep><?php $dr = str_replace($_SERVER['SCRIPT_NAME'], '/includes/', $_SERVER['SCRIPT_FILENAME']); ?>
<?php
$title = "Terms";
$section = "terms";
?>
<?php include($dr . "head.inc.php"); ?><!-- HEADER -->
<div class="section notwide">
<h2>Terms and Conditions</h2>
<p>By registering to attend <a href="/">dConstruct</a>, you agree to the following:</p>
<h3>Cancellation and refunds</h3>
<p>If you need to cancel your seat, you must tell us at least one month before the date of the event to receive a 100% refund. No refunds can be issued for seats that are cancelled less than 1 month before the event.</p>
<h3>Transfers</h3>
<p>You may transfer your seat to a friend or colleague, but if you wish to do so you must notify us at least a month before the date of the event. No transfers can be issued for seats that are cancelled less than 1 month before the event.</p>
<h3>Access Requirements</h3>
<p>If you have any special access requirements (such as wheelchair access), then please contact us when you register so we can do our best to accommodate you on the day.</p>
<h3>Photography and quotes</h3>
<p>You grant us the right to use any photography taken on the day or any quotes given on our feedback forms for the marketing of future events.</p>
<h3>Help</h3>
<p>If you require any further clarification of these terms please <a href="/contact/">get in touch</a>.</p>
</div>
<!-- FOOTER -->
<?php include($dr . "footer.inc.php"); ?><file_sep><?php $dr = str_replace($_SERVER['SCRIPT_NAME'], '/includes/', $_SERVER['SCRIPT_FILENAME']); ?>
<?php
$title = "<NAME>";
$section = "schedule";
?>
<?php include($dr . "head.inc.php"); ?><!-- HEADER -->
<div class="section">
<div class="speaker">
<div class="speaker-context">
<img class="speaker-badge" alt="<NAME>" src="/images/speaker-badge-chris-noessel.png">
<div class="speaker-list">
<ul>
<li class="vcard"><h2><a class="url fn" href="/schedule/adamgreenfield/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/brianfling/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/russelldavies/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/mikemigurski/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/bencerveny/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/nathanshedroff/"><NAME></a></h2></li>
<li class="vcard selected"><h2><a class="url fn" href="/schedule/chrisnoessel"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/robinhunicke/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn n" href="/schedule/augustdelosreyes/"><span class="given-name">August</span> <span class="family-name">de los Reyes</span></a></h2></li>
</ul>
</div><!-- /.speaker-list -->
</div><!-- /.speaker-context -->
<div class="speaker-bio">
<h2>Speaker <strong><NAME></strong></h2>
<p class="description"><NAME> is an interaction designer and self-described “nomothete” (ask him directly about that one.) In his day job as a consultant with Cooper, he designs products, services, and strategy for a variety of domains, including health, financial, and software.</p>
<p>His prior experience has seen him developing interactive kiosks and spaces for museums, helping to visualize the future of counter-terrorism, building prototypes of coming technologies for Microsoft, and designing telehealth devices to accommodate the crazy facts of modern health and healthcare.</p>
<p>His spidey sense goes off about random topics, and this has led him to speak at conferences about a wide range of things including interactive narrative, ethnographic user research, interaction design, sex-related interactive technologies, free-range learning, and, most recently, the relationship between science fiction and interface design with co-author <NAME>.</p>
<p>Chris was one of the founding graduates of the now-passing-into-legend Interaction Design Institute Ivrea in Ivrea, Italy. His graduate thesis was the design of a mobile service for lifelong learners, called Fresh. His academic career has continued as he completed a year as an adjunct professor of interaction design for the graduate design program at the California College of Art.</p>
<p>Chris is regularly published online in the Cooper Journal, and is editor and primary author of “Interaction Design for Visible Wireless”, a Chapter in RFID: Applications, Security, and Privacy. His next work is most likely to be about generative randomness. He will likely answer questions about it over a drink.</p>
<p><a href="http://www.cooper.com/journal/chris_noessel/">cooper.com/journal/chris_noessel/</a></p>
</div><!-- /.speaker-bio -->
<div class="speaker-talk">
<h2><strong>Make It So: Learning From SciFi Interfaces</strong></h2>
<div class="blurb">
<p>Make It So explores how science fiction and interface design relate to each other. The authors have developed a model that traces lines of influence between the two, and use this as a scaffold to investigate how the depiction of technologies evolve over time, how fictional interfaces influence those in the real world, and what lessons interface designers can learn through this process. This investigation of science fiction television shows and movies has yielded practical lessons that apply to online, social, mobile, and other media interfaces.</p>
<object type="application/x-shockwave-flash" data="http://huffduffer.com/flash/player.swf?soundFile=http://dconstruct.s3.amazonaws.com/2009/podcast/dConstruct2009-Shedroff-Noessel.mp3" width="290" height="24"><param name="movie" value="http://huffduffer.com/flash/player.swf?soundFile=http://dconstruct.s3.amazonaws.com/2009/podcast/dConstruct2009-Shedroff-Noessel.mp3"><param name="wmode" value="transparent"><a href="http://huffduffer.com/dConstruct/8112">Make It So: Learning From SciFi Interfaces by <NAME> and <NAME> on Huffduffer</a></object>
<p><a rel="enclosure" href="http://dconstruct.s3.amazonaws.com/2009/podcast/dConstruct2009-Shedroff-Noessel.mp3">Download the audio</a></p>
<p><a href="/podcast/makeitso">Read the transcript</a></p>
</div><!-- /.blurb -->
</div><!-- /.speaker-talk -->
</div><!-- /.speaker -->
</div><!-- /.section -->
<!-- FOOTER -->
<?php include($dr . "footer.inc.php"); ?><file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>HTML5</title>
<!-- configuration parameters -->
<meta name="defaultView" content="slideshow">
<meta name="controlVis" content="visible">
<!-- style sheet links -->
<link rel="stylesheet" href="ui/slides.css" media="projection" id="slideProj">
<link rel="stylesheet" href="ui/outline.css" media="screen" id="outlineStyle">
<link rel="stylesheet" href="ui/print.css" media="print" id="slidePrint">
<link rel="stylesheet" href="ui/opera.css" media="projection" id="operaFix">
<script src="ui/slides.js"></script>
<style>
table,th,td {
border: 1px solid #bca;
}
</style>
</head>
<body>
<div class="layout">
<div id="controls"><!-- DO NOT EDIT --></div>
<div id="currentSlide"><!-- DO NOT EDIT --></div>
<div id="header"></div>
<div id="footer">
<h1>HTML5</h1>
<h2 class="vcard">by <a class="fn url" href="http://clearleft.com/is/jeremykeith" rel="external"><NAME></a></h2>
</div>
</div>
<ol class="xoxo presentation">
<li class="slide">
<h1>Structure</h1>
<div class="handout"></div>
</li>
<li class="slide">
<h1>Sectioning content</h1>
<blockquote><p><a rel="external" href="http://www.whatwg.org/specs/web-apps/current-work/multipage/dom.html#sectioning-content">Sectioning content</a> is content that defines the scope of headings and footers.</p></blockquote>
<ul>
<li><code>article</code></li>
<li><code>aside</code></li>
<li><code>nav</code></li>
<li><code>section</code></li>
</ul>
<blockquote><p>Each sectioning content element potentially has a heading and an outline.</p></blockquote>
</li>
<li class="slide">
<h1>Implicit sections</h1>
<table>
<thead>
<tr><th>Markup</th><th>Outline</th></tr>
</thead>
<tbody>
<tr>
<td><pre><code><strong><h1>Foo</h1></strong>
<p>Lorem ipsum foolor</p>
<strong><h2>Bar</h2></strong>
<p>Lorem ipsum barlor</p>
<strong><h3>Baz</h3></strong>
<p>Lorem ipsum bazlor</p>
<strong><h2>Qux</h2></strong>
<p>Lorem ipsum quxlor</p>
<small>foobar</small></code></pre></td>
<td class="incremental"><pre><strong>Foo</strong>
<strong>Bar</strong>
<strong>Baz</strong>
<strong>Qux</strong>
<i>foobar</i>
</pre></td>
</tr>
</tbody>
</table>
</li>
<li class="slide">
<h1>Explicit sections</h1>
<table>
<thead>
<tr><th>Markup</th><th>Outline</th></tr>
</thead>
<tbody>
<tr>
<td><pre><code><strong><h1>Foo</h1></strong>
<p>Lorem ipsum foolor</p>
<strong><section></strong>
<strong><h1>Bar</h1></strong>
<p>Lorem ipsum barlor</p>
<strong><h2>Baz</h2></strong>
<p>Lorem ipsum bazlor</p>
<strong><h1>Qux</h1></strong>
<p>Lorem ipsum quxlor</p>
<strong></section></strong>
<small>foobar</small></code></pre></td>
<td class="incremental"><pre><strong>Foo</strong>
<strong>Bar</strong>
<strong>Baz</strong>
<strong>Qux</strong>
<i>foobar</i>
</pre></td>
</tr>
</tbody>
</table>
</li>
<li class="slide">
<h1>Creating an outline</h1>
<h2><code><a rel="external" href="http://www.whatwg.org/specs/web-apps/current-work/multipage/semantics.html#the-hgroup-element">hgroup</a></code></h2>
<blockquote><p>The point of <code>hgroup</code> is to <del>mask an <code>h2</code> element (that acts as a secondary title)</del> from the outline algorithm.</p></blockquote>
<p>The point of <code>hgroup</code> is to mask <ins>all but the highest-ranking heading element within</ins> from the outline algorithm.</p>
</li>
<li class="slide">
<h1>Sectioning roots</h1>
<ul>
<li>
<code><a rel="external" href="http://www.whatwg.org/specs/web-apps/current-work/multipage/semantics.html#the-blockquote-element">blockquote</a></code>
</li>
<li>
<code><a rel="external" href="http://www.whatwg.org/specs/web-apps/current-work/multipage/semantics.html#the-body-element-0">body</a></code>
</li>
<li>
<code><a rel="external" href="http://www.whatwg.org/specs/web-apps/current-work/multipage/text-level-semantics.html#the-figure-element">figure</a></code>
</li>
<li>
<code><a rel="external" href="http://www.whatwg.org/specs/web-apps/current-work/multipage/tabular-data.html#the-td-element">td</a></code>
</li>
</ul>
<blockquote><p>These elements can have their own outlines, but the sections and headings inside these elements do not contribute to the outlines of their ancestors.</p></blockquote>
</li>
<li class="slide">
<h1>Sectioning roots</h1>
<table>
<thead>
<tr><th>Markup</th><th>Outline</th></tr>
</thead>
<tbody>
<tr>
<td><pre><code><strong><h1>Foo</h1></strong>
<p>Lorem ipsum foolor</p>
<strong><h2>Bar</h2></strong>
<p>Lorem ipsum barlor</p>
<strong><blockquote></strong>
<h3>Baz</h3>
<p>Lorem ipsum bazlor</p>
<strong></blockquote></strong>
<strong><h2>Qux</h2></strong>
<p>Lorem ipsum quxlor</p>
<small>foobar</small></code></pre></td>
<td class="incremental"><pre><strong>Foo</strong>
<strong>Bar</strong>
<strong>Qux</strong>
</pre></td>
</tr>
</tbody>
</table>
</li>
<li class="slide">
<h1>Styles</h1>
<pre><code><style>
h1 { color: green; }
</style>
<h1>What colour am I?</h1>
<section>
<style>
h1 { color: red; }
</style>
<h1>What colour am I?</h1>
</section></code></pre>
</li>
<li class="slide">
<h1>Scoped styles</h1>
<pre><code><style>
h1 { color: green; }
</style>
<h1>What colour am I?</h1>
<section>
<style <strong>scoped</strong>>
h1 { color: red; }
</style>
<h1>What colour am I?</h1>
</section></code></pre>
</li>
<li class="slide">
<h1>Global styles</h1>
<pre><code>article, aside, details,
figure, footer, header,
hgroup, nav, section {
<strong>display: block;</strong>
}</code></pre>
</li>
<li class="slide">
<h1>Internet Explorer</h1>
<ul class="incremental">
<li><pre><code>document.createElement('article');
document.createElement('aside');
document.createElement('details');
…</code></pre></li>
<li><pre><code><!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js">
</script>
<![endif]--></code></pre></li>
</ul>
</li>
<li class="slide">
<h1>New elements</h1>
<img src="images/layout01.gif" alt="Document with structural elements and no divs">
</li>
<li class="slide">
<h1>New and old elements</h1>
<img src="images/layout02.gif" alt="Document with structural elements and divs">
</li>
<li class="slide">
<h1><abbr title="Accessibile Rich Internet Applications">ARIA</abbr> roles</h1>
<img src="images/layout03.gif" alt="Document with divs and roles">
</li>
<li class="slide">
<h1>Classes</h1>
<img src="images/layout04.gif" alt="Document with divs, classes and roles">
</li>
<li class="slide">
<h1>Options</h1>
<ul class="incremental">
<li>Doctype + ARIA <code>role</code>s</li>
<li>Doctype + <code>class</code> names + ARIA <code>role</code>s</li>
<li>Doctype + new elements + ARIA <code>role</code>s</li>
</ul>
</li>
<li class="slide">
<h1>Resources</h1>
<ul>
<li><a rel="external" href="http://validator.nu/">validator.nu</a></li>
<li><a rel="external" href="http://gsnedders.html5.org/outliner/">gsnedders.html5.org/outliner</a></li>
<li><a rel="external" href="http://html5doctor.com/">html5doctor.com</a></li>
<li><a rel="external" href="http://diveintohtml5.org/">diveintohtml5.org</a></li>
</ul>
</li>
<li class="slide">
<h1>Get involved</h1>
<h2>WHATWG</h2>
<ul>
<li>Spec: <a rel="external" href="http://whatwg.org/html5">whatwg.org/html5</a></li>
<li>Mailing lists: <a rel="external" href="http://whatwg.org/mailing-list">whatwg.org/mailing-list</a></li>
<li>IRC channel: <a rel="external" href="irc://irc.freenode.org/whatwg">irc://irc.freenode.org/whatwg</a></li>
</ul>
</li>
</ol>
</body>
</html><file_sep><?php $dr = str_replace($_SERVER['SCRIPT_NAME'], '/includes/', $_SERVER['SCRIPT_FILENAME']); ?>
<?php
$title = "<NAME>";
$section = "schedule";
?>
<?php include($dr . "head.inc.php"); ?><!-- HEADER -->
<div class="section">
<div class="speaker">
<div class="speaker-context">
<img class="speaker-badge" alt="<NAME>" src="/images/speaker-badge-adam-greenfield.png">
<div class="speaker-list">
<ul>
<li class="vcard selected"><h2><a class="url fn" href="/schedule/adamgreenfield/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/brianfling/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/russelldavies/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/mikemigurski/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/bencerveny/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/nathanshedroff/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/chrisnoessel"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn" href="/schedule/robinhunicke/"><NAME></a></h2></li>
<li class="vcard"><h2><a class="url fn n" href="/schedule/augustdelosreyes/"><span class="given-name">August</span> <span class="family-name">de los Reyes</span></a></h2></li>
</ul>
</div><!-- /.speaker-list -->
</div><!-- /.speaker-context -->
<div class="speaker-bio">
<h2>Speaker <strong><NAME></strong></h2>
<p class="description"><NAME> lives in a city and thinks you probably do, too.</p>
<p>Photo credit: <a href="http://www.flickr.com/photos/studies_and_observations/3294869932/"><NAME></a></p>
<ul class="social-networks">
<li><a class="button" href="http://twitter.com/agpublic"><span><img alt="Twitter" src="/images/logo-twitter.gif"></span></a></li>
<li><a class="button" href="http://www.dopplr.com/traveller/adamgreenfield"><span><img alt="Dopplr" src="/images/logo-dopplr.gif"></span></a></li>
</ul>
</div><!-- /.speaker-bio -->
<div class="speaker-talk">
<h2><strong>Elements of a Networked Urbanism.</strong></h2>
<div class="blurb">
<p>Over the past several years, we’ve watched as a very wide variety of objects and surfaces familiar from everyday life have been reimagined as networked information-gathering, -processing, -storage and -display resources. Why should cities be any different?</p>
<p>What happens to urban form and metropolitan experience under such circumstances? What are the implications for us, as designers, consumers and as citizens?</p>
<object type="application/x-shockwave-flash" data="http://huffduffer.com/flash/player.swf?soundFile=http://dconstruct.s3.amazonaws.com/2009/podcast/dConstruct2009-Greenfield.mp3" width="290" height="24"><param name="movie" value="http://huffduffer.com/flash/player.swf?soundFile=http://dconstruct.s3.amazonaws.com/2009/podcast/dConstruct2009-Greenfield.mp3"><param name="wmode" value="transparent"><a href="http://huffduffer.com/dConstruct/7571">Elements of a Networked Urbanism by <NAME> on Huffduffer</a></object>
<p><a rel="enclosure" href="http://dconstruct.s3.amazonaws.com/2009/podcast/dConstruct2009-Greenfield.mp3">Download the audio</a></p>
<p><a href="/podcast/networkedurbanism">Read the transcript</a></p>
</div><!-- /.blurb -->
</div><!-- /.speaker-talk -->
</div><!-- /.speaker -->
</div><!-- /.section -->
<!-- FOOTER -->
<?php include($dr . "footer.inc.php"); ?>
<file_sep><?php $dr = str_replace($_SERVER['SCRIPT_NAME'], '/includes/', $_SERVER['SCRIPT_FILENAME']); ?>
<?php
$title = "Accessibility";
$section = "accessibility";
?>
<?php include($dr . "head.inc.php"); ?><!-- HEADER -->
<div class="section notwide">
<h2>Accessibility</h2>
<p>The dConstruct website has been designed and built to be accessible to as wide an audience as possible. Some people with disabilities find using the web difficult and while we know that it is impossible to design a site that everyone can use, if you have problems using our site, please <a class="contact-link" href="/contact/">let us know</a> and we will do our utmost to help.</p>
<h3>Conference accessibility</h3>
<p>If you have specific accessibility requirements while at the conference, please contact us and we'll try our best to accommodate you.</p>
<h3>Standards compliance</h3>
<p>All pages validate as <abbr title="eHyperText Language version 4">HTML4</abbr>.</p>
<h3>Links</h3>
<p>Many links have title attributes which describe the link in greater detail, unless the text of the link already fully describes the target (such as the headline of an article).</p>
<p>Whenever possible, links are written to make sense out of context. Many browsers (such as <acronym>JAWS</acronym>, Home Page Reader, Lynx, and Opera) can extract the list of links on a page and allow the user to browse the list, separately from the page. To aid this, link text is never duplicated; two links with the same link text always point to the same address.</p>
<p>There are no <code>javascript:</code> pseudo-links. All links can be followed in any browser, even if scripting is turned off. There are no links that open new windows without warning.</p>
<h3>Visual design</h3>
<p>This site uses cascading style sheets for visual layout. If your browser or browsing device does not support stylesheets at all, the content of each page is still readable.</p>
<p>The layout is liquid, simply filling its window. It happily accommodates resizing text and, as relative units have been used, text can even be re-sized in Internet Explorer for Windows.</p>
</div>
<!-- FOOTER -->
<?php include($dr . "footer.inc.php"); ?><file_sep><?php $dr = str_replace($_SERVER['SCRIPT_NAME'], '/includes/', $_SERVER['SCRIPT_FILENAME']); ?>
<?php include($dr . "head.inc.php"); ?><!-- HEADER -->
<!-- SECTION SPEAKER LIST -->
<?php include($dr . "speaker-list.inc.php"); ?>
<!-- SECTION WORKSHOPS -->
<?php include($dr . "workshops.inc.php"); ?>
<!-- SECTION NEWS -->
<?php include($dr . "news.inc.php"); ?>
<!-- SECTION SCHEDULE -->
<?php include($dr . "schedule.inc.php"); ?>
<!-- SECTION SPEAKER -->
<?php include($dr . "speaker.inc.php"); ?>
<!-- SECTION WORKSHOP -->
<?php include($dr . "workshop.inc.php"); ?>
<!-- SECTION LOCATION -->
<?php include($dr . "location.inc.php"); ?>
<!-- SECTION SPONSORSHIP -->
<?php include($dr . "sponsorship.inc.php"); ?>
<!-- SECTION PODCAST -->
<?php include($dr . "podcast.inc.php"); ?>
<!-- SECTION PODCAST DETAIL -->
<?php include($dr . "podcast-detail.inc.php"); ?>
<!-- FOOTER -->
<?php include($dr . "footer.inc.php"); ?> | 4b48972cd49edee28aa57bc7ecee55d7f8b244d9 | [
"HTML",
"PHP"
] | 31 | PHP | clearleft/2009.dconstruct | 3f904c069e117d09eaede4cdddecba9277b96dc4 | 37af85ceb2bbfa3f1a740ed6c748fe876e7e4aca |
refs/heads/main | <file_sep>import cv2
import dlib
import numpy as np
import base64
from eye_tracking import Eye_tracking
from mouth_tracking import Mouth_tracking
from gaze_tracking import Gaze_Tracking
from head_pose_estimation import Head_Pose_Tracking
import joblib
class server_image_processing(object):
def __init__(self):
self.detector = dlib.get_frontal_face_detector()
self.predictor = dlib.shape_predictor("trained_models/shape_predictor_68_face_landmarks.dat")
self.model = joblib.load('trained_models/KNN.pkl')
def data_uri_to_cv2_img(self, uri):
encoded_data = uri.split(',')[1]
nparr = np.frombuffer(base64.b64decode(encoded_data), np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
return img
'''
calibration : {eye: double, mouth: double, gaze: double}
'''
def process_image(self, data_uri, calibration):
# cap = cv2.VideoCapture('test_video/test3.mp4')
img = self.data_uri_to_cv2_img(data_uri)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = self.detector(gray)
if not faces:
return ({'success':False, 'error': 'No Faces Detected'},{'isCalibrating':None, 'isAttentive':None}, calibration )
face = faces[0]
landmarks = self.predictor(gray,face)
eye_tracker = Eye_tracking(gray, landmarks)
gaze_tracker = Gaze_Tracking(gray, landmarks)
mouth_tracker = Mouth_tracking(gray, landmarks)
head_pose_tracker = Head_Pose_Tracking(gray, landmarks)
if calibration['calibration_count'] < 10:
calibration['eye'] += eye_tracker.analyze()
calibration['mouth'] += mouth_tracker.analyze()
calibration['gaze'] += gaze_tracker.analyze()
calibration['calibration_count'] += 1
return ({'success':True}, {'isCalibrating':True, 'isAttentive':None}, calibration )
elif calibration['calibration_count'] == 10:
calibration['eye'] /= 10
calibration['mouth'] /= 10
calibration['gaze'] /= 10
calibration['calibration_count'] += 1
eye_lengths_ratio = eye_tracker.analyze()
eye_white_ratio = gaze_tracker.analyze()
mouth_ratio = mouth_tracker.analyze()
(theta_X,_,_) = head_pose_tracker.analyze()
X_test = [(eye_lengths_ratio, eye_white_ratio, mouth_ratio, theta_X)]
y_out = self.model.predict(X_test)
if y_out == 0 or eye_lengths_ratio > 1.3*calibration['eye'] or eye_white_ratio > 3*calibration['gaze'] or eye_white_ratio < 0.3*calibration['gaze'] or mouth_ratio < 0.8*calibration['mouth']:
return ({'success':True}, {'isCalibrating':False, 'isAttentive':False}, calibration )
else:
return ({'success':True}, {'isCalibrating':False, 'isAttentive':True}, calibration )
<file_sep>import pandas as pd
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
from sklearn import metrics
import joblib
class KNN(object):
def __init__(self,data):
self.data = data
def train(self):
accuracy_list = []
f1_scores = []
roc_list = []
df_train = self.data[:int(len(self.data)*0.8)]
df_test = self.data[-(len(self.data) - int(len(self.data)*0.8)):]
print(df_test)
X_train = df_train.drop('y_output',axis=1)
y_train = df_train['y_output']
X_test = df_test.drop('y_output',axis=1)
y_test = df_test['y_output']
for i in range(1,30):
KNeighbors = KNeighborsClassifier(n_neighbors=i)
KNeighbors.fit(X_train, y_train)
y_predict = KNeighbors.predict(X_test)
y_score = KNeighbors.predict_proba(X_test)[:,1]
accuracy_list.append(accuracy_score(y_test, y_predict))
f1_scores.append(metrics.f1_score(y_test, y_predict))
roc_list.append(metrics.roc_auc_score(y_test, y_score))
accuracy_list.index(max(accuracy_list))+1
KNeighbors = KNeighborsClassifier(n_neighbors=accuracy_list.index(max(accuracy_list))+1)
KNeighbors.fit(X_train, y_train)
print(X_test)
y_predict = KNeighbors.predict(X_test)
print(y_predict)
y_score = KNeighbors.predict_proba(X_test)[:,1]
accuracy = accuracy_score(y_test, y_predict)
f1_score = metrics.f1_score(y_test, y_predict)
roc = metrics.roc_auc_score(y_test, y_score)
print("Accuracy % = ",accuracy, "\nF1-score = ", f1_score, "\nROC = ", roc)
# print(confusion_matrix(y_test, pred_KN))
# joblib.dump(KNeighbors, 'trained_models/KNN.pkl')
<file_sep>import cv2
import dlib
import numpy as np
import pandas as pd
import math
import os
from eye_tracking import Eye_tracking
from mouth_tracking import Mouth_tracking
from gaze_tracking import Gaze_Tracking
from head_pose_estimation import Head_Pose_Tracking
from logistic_regression_model import LRModel
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("models/shape_predictor_68_face_landmarks.dat")
def draw_landmark(frame, part_no):
cv2.circle(frame,(landmarks.part(part_no).x,landmarks.part(part_no).y),2,(255,0,0),1)
cv2.putText(frame, str(part_no), (landmarks.part(part_no).x,landmarks.part(part_no).y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 1)
features = pd.DataFrame(columns=["file_name", "eye_ratio", "eye_white_ratio", "mouth_ratio", "X"])
folder = 'Att_DataSet/att'
for filename in os.listdir(folder):
# for i in img_names:
gray = cv2.imread(os.path.join(folder,filename),0)
if gray is None :
print(filename)
continue
# gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = detector(gray,0)
# First point of detection -
# If no faces found in video frame, put alert text and skip over to next frame
if len(faces) == 0:
print('no face')
continue
print('face detected')
face = faces[0]
landmarks = predictor(gray,face) # 68 landmarks points provided by dlib
landmarks_pts = np.arange(0,68) # landmark points array
'''
Initialising all the feature extraction modules and
analysing the face to extract useful data from the frame.
'''
gaze_tracker = Gaze_Tracking(gray, landmarks)
eye_tracker = Eye_tracking(gray, landmarks)
mouth_tracker = Mouth_tracking(gray, landmarks)
head_pose_tracker = Head_Pose_Tracking(gray, landmarks)
eye_lengths_ratio = eye_tracker.analyze()
eye_white_ratio = gaze_tracker.analyze()
print(eye_white_ratio)
mouth_ratio = mouth_tracker.analyze()
(X,Y,_) = head_pose_tracker.analyze()
for i in landmarks_pts[36:48]:
draw_landmark(gray, i)
cv2.imshow('image',gray)
features_series = pd.Series([filename, eye_lengths_ratio, eye_white_ratio, mouth_ratio, X], index = features.columns)
features = features.append(features_series, ignore_index=True)
# print(features)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
features.to_csv('dset1.csv')
<file_sep>from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
from sklearn import metrics
import joblib
class NaiveBayes(object):
def __init__(self,data):
self.data = data
def train(self):
df_train = self.data[:int(len(self.data)*0.9)]
df_test = self.data[-(len(self.data) - int(len(self.data)*0.9)):]
print(df_test)
X_train = df_train.drop('y_output',axis=1)
y_train = df_train['y_output']
X_test = df_test.drop('y_output',axis=1)
y_test = df_test['y_output']
NaiveB = GaussianNB()
NaiveB.fit(X_train, y_train)
y_predict = NaiveB.predict(X_test)
y_score = NaiveB.predict_proba(X_test)[:,1]
accuracy = accuracy_score(y_test, y_predict)
f1_score = metrics.f1_score(y_test, y_predict)
roc = metrics.roc_auc_score(y_test, y_score)
print("Accuracy % = ",accuracy, "\nF1-score = ", f1_score, "\nROC = ", roc)
print(confusion_matrix(y_test, y_predict))
joblib.dump(NaiveB, 'trained_models/NaiveB.pkl')
<file_sep>from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
from sklearn import metrics
import joblib
class DecisionTree(object):
def __init__(self,data):
self.data = data
def train(self):
accuracy_list=[]
max_depth = []
df_train = self.data[:int(len(self.data)*0.8)]
df_test = self.data[-(len(self.data) - int(len(self.data)*0.8)):]
print(df_test)
X_train = df_train.drop('y_output',axis=1)
y_train = df_train['y_output']
X_test = df_test.drop('y_output',axis=1)
y_test = df_test['y_output']
for i in range(2,10):
DecisionTree = DecisionTreeClassifier(max_depth = i)
DecisionTree.fit(X_train, y_train)
y_predict = DecisionTree.predict(X_test)
accuracy_list.append(accuracy_score(y_predict, y_test))
max_depth.append(i)
best_depth = max_depth[accuracy_list.index(max(accuracy_list))]
DecisionTree = DecisionTreeClassifier(max_depth=best_depth)
DecisionTree.fit(X_train, y_train)
y_predict = DecisionTree.predict(X_test)
y_score = DecisionTree.predict_proba(X_test)[:,1]
accuracy = accuracy_score(y_test, y_predict)
f1_score = metrics.f1_score(y_test, y_predict)
roc = metrics.roc_auc_score(y_test, y_score)
print("Accuracy % = ",accuracy, "\nF1-score = ", f1_score, "\nROC = ", roc)
print(confusion_matrix(y_test, y_predict))
joblib.dump(DecisionTree, 'trained_models/DecisionTree.pkl')
<file_sep>import cv2
import numpy as np
import math
from cv2 import FONT_HERSHEY_SIMPLEX
from calibration import Calibration
class Gaze_Tracking(object):
LEFT = [36, 37, 38, 39, 40, 41]
RIGHT = [42, 43, 44, 45, 46, 47]
def __init__(self, frame, landmarks) -> None:
self.frame = frame
self.landmarks = landmarks
self.calibration = Calibration()
def get_eye_gaze(self, left=False):
eye_region=None
if left == True:
eye_region = np.array([(self.landmarks.part(i).x, self.landmarks.part(i).y) for i in self.LEFT])
else:
eye_region = np.array([(self.landmarks.part(i).x, self.landmarks.part(i).y) for i in self.RIGHT])
mask = np.zeros(self.frame.shape[:2],np.uint8)
cv2.polylines(mask,[eye_region], True, 255,2)
cv2.fillPoly(mask,[eye_region],255)
mask= cv2.bitwise_and(self.frame,self.frame,mask=mask)
eye_frame_region = self.frame[np.min(eye_region[:,1]): np.max(eye_region[:,1]),np.min(eye_region[:,0]): np.max(eye_region[:,0])]
if not self.calibration.is_complete():
self.calibration.evaluate(eye_frame_region, left)
threshold = self.calibration.threshold(left)
# cv2.putText(self.frame, str(threshold), (50,200), FONT_HERSHEY_SIMPLEX, 2, (255,0,0),2)
# threshold = cv2.getTrackbarPos('threshold', 'image')
# if threshold==0:
# threshold=55
kernel = np.ones((3, 3), np.uint8)
eye_frame_region = cv2.bilateralFilter(eye_frame_region, 10, 15, 15)
eye_frame_region = cv2.erode(eye_frame_region, kernel, iterations=3)
_, threshold_eye = cv2.threshold(eye_frame_region, threshold, 255, cv2.THRESH_BINARY)
h,w = threshold_eye.shape
left_half_white = cv2.countNonZero(threshold_eye[0:h, 0:w//2])
right_half_white = cv2.countNonZero(threshold_eye[0:h, w//2:w])
total_pixel = np.sum(threshold_eye!=None)
# print(left_half_white,right_half_white,left_half_white+right_half_white, total_pixel, ' ')
threshold_eye = cv2.resize(threshold_eye, None, fx=5, fy=5)
left_to_right_ratio = None
if right_half_white==0 or (left_half_white+right_half_white)==total_pixel:
left_to_right_ratio=10
else:
left_to_right_ratio=left_half_white/right_half_white
if left==True:
# cv2.putText(self.frame, str(left_to_right_ratio), (50,100), FONT_HERSHEY_SIMPLEX, 2, (255,0,0),2)
# cv2.putText(self.frame, str(right_half_white), (50,150), FONT_HERSHEY_SIMPLEX, 2, (255,0,0),2)
cv2.imshow('thresh_left',threshold_eye)
pass
else:
# cv2.putText(self.frame, str(left_to_right_ratio), (50,200), FONT_HERSHEY_SIMPLEX, 2, (255,0,0),2)
# cv2.putText(self.frame, str(right_half_white), (350,150), FONT_HERSHEY_SIMPLEX, 2, (255,0,0),2)
cv2.imshow('thresh_right',threshold_eye)
pass
eye_frame_region = cv2.resize(eye_frame_region,None,fx=10,fy=10)
# cv2.imshow('left_eye_frame_region',left_eye_frame_region)
# cv2.imshow('thresh',threshold_eye)
# cv2.imshow('mask',mask)
return left_to_right_ratio
def analyze(self):
return (self.get_eye_gaze(True)+self.get_eye_gaze(False))/2
<file_sep>import React, { useEffect, useContext } from "react";
import { Container, Button, Row, Col } from "react-bootstrap";
import { Link, useHistory, useLocation } from "react-router-dom";
import Bottleneck from "bottleneck";
import Axios from "axios";
import Webcam from "react-webcam";
import AuthOptions from "../../../auth/AuthOptions";
import UserContext from "../../../../context/UserContext";
import Loader from "../../../misc/Loader";
import Questions from "./Questions";
import TimeRemainingCounter from "./TimeRemainingCounter";
import { showErrorAlert } from "../../../../utils/alerts";
import "./WebcamCapture.css";
function WebcamCapture(/*{ userName, examID, timelimit }*/) {
const { userData } = useContext(UserContext);
const serverUrl = "http://127.0.0.1:5000";
const limiter = new Bottleneck({
maxConcurrent: 1,
minTime: 200,
});
const location = useLocation();
const history = useHistory();
const examId = location.pathname.substring(6);
const userName = userData.user.displayName;
const [examData, setExamData] = React.useState();
const [timelimit, setTimelimit] = React.useState();
const [loading, setLoading] = React.useState(true);
const [loading2, setLoading2] = React.useState(true);
const [startTime, setStartTime] = React.useState(-1);
const [timeExpired, setTimeExpired] = React.useState(false);
const [isCalibrated, setIsCalibrated] = React.useState(false);
const [captureStarted, setCaptureStarted] = React.useState(false);
useEffect(() => {
console.log("sdadsasdasd");
Axios.post(
"http://127.0.0.1:10000/users/fetchExam",
{ examId },
{
headers: { "x-auth-token": userData.token },
}
)
.then((res) => {
const data = res.data;
if (new Date(data.examStartTime).getTime() > Date.now()) {
showErrorAlert("Oops...", "Exam not started yet! Please try again later");
history.push("/");
}
setExamData(data);
console.log("examData", data);
setTimelimit(data.timelimit);
console.log("timelimit", data.timelimit);
})
.catch(() => {
showErrorAlert();
history.push("/");
});
}, [examId, history, userData.token]);
// const [remainingTime, setRemainingTime] = React.useState(null);
// get all values on reload -- case if test already started
useEffect(() => {
Axios.post(`${serverUrl}/time`, { user: userName, examID: examId })
.then((res) => {
const createdAt = res.data.created_at;
const finishedAt = res.data.finished_at;
if (finishedAt !== "-") {
// finished_at is only logged once user ends test or time expires
console.log(finishedAt);
setTimeExpired(true);
return;
}
// const calibratedValues = res.data.calibrated_values;
console.log(createdAt);
const timestamp = new Date(createdAt).getTime();
setStartTime(timestamp);
// console.log('startTime', timestamp)
// setCalibrationObj(calibratedValues);
})
.catch((err) => console.log(err))
.finally(() => setLoading(false));
}, [examId, userName]);
const webcamRef = React.useRef(null);
const postImageFrames = () => {
return new Promise((resolve, reject) => {
if (!webcamRef || !webcamRef.current) return;
const imageSrc = webcamRef.current.getScreenshot();
Axios.post(serverUrl, {
imageSrc,
user: userName,
examID: examId,
timeLimit: timelimit,
})
.then((res) => {
resolve(res);
})
.catch((err) => {
console.log(err);
reject();
});
});
};
const captureHandler = () => {
if (/*remainingTime === 0 ||*/ timeExpired || document.getElementById("webcam-frame") === null) return;
limiter
.schedule(() => postImageFrames())
.then((res) => {
if (loading2) {
setLoading2(false);
}
const { success, data } = res.data;
setIsCalibrated(!data["isCalibrating"] === true);
console.log(data);
let text = "";
if (success === false) {
text = "Failed";
} else {
if (data["isCalibrating"] === true) text = "calibrating";
else text = data["isAttentive"] === true ? "Attentive" : "Inattentive";
}
document.getElementById("res").innerHTML = text;
})
.catch((err) => {
console.log("err", err);
})
.finally(() => captureHandler());
};
const startCaptureHandler = () => {
alert("Look at your camera for first 5 seconds to allow for calibration");
// setLoading2(true);
setCaptureStarted(true);
if (startTime === -1) setStartTime(Date.now());
captureHandler();
};
const reCalibrateHandler = () => {
Axios.post(`${serverUrl}/recalibrate`, { user: userName, examID: examId }).then((res) => {
console.log("re-calibration started");
});
};
const endTestHandler = () => {
setTimeExpired(true);
Axios.post(`${serverUrl}/end`, { user: userName, examID: examId })
.then((response) => {
const data = response.data;
console.log(data === "success" ? "test ended" : "err");
})
.catch((err) => console.log(err));
};
if (loading) return <Loader />;
if (timeExpired) {
return (
<Container className="m-auto text-center">
<h1>Your test has ended!</h1>
<div className="test-end-logout btn btn-danger btn-lg mr-3" onClick={() => history.push("/")}>
<AuthOptions />
</div>
<Link to="/">
<Button variant="success" size="lg">
Go Home
</Button>
</Link>
</Container>
);
}
return (
<Container fluid>
<Row>
{startTime === -1 || !captureStarted ? (
<Col className="question-col">
<h1 className="text-success text-center">Important Instructions:</h1>
<ol className="instructions">
<li>
The first few seconds of the web-cam feed will be use to calibrate baseline values for
your normal attentive state. Please ensure that you maintain your normal attentive
posture for first 5 seconds as it will be used to track you further.
</li>
<li>
You have the option to recalibrate the tracker if you feel that it was not calibrated
properly.
</li>
</ol>
</Col>
) : loading2 === true ? (
<Loader />
) : (
examData && (
<Col className="question-col">
<Questions examData={examData} />
</Col>
)
)}
<Col className="webcam-col">
<div className="webcam">
<Webcam
audio={false}
ref={webcamRef}
forceScreenshotSourceSize
videoConstraints={{
height: 480,
width: 640,
}}
className="webcam-frame"
id="webcam-frame"
/>
{isCalibrated ? (
<Button onClick={reCalibrateHandler} className="recalibrate-button">
Re-Calibrate
</Button>
) : null}
<div className="details-container">
<div id="result">
<span className="text-success">Result : </span>
<span id="res">None</span>
</div>
<div id="time-remaining">
<span className="text-danger">Time Left : </span>
<TimeRemainingCounter
startTime={startTime}
timeLimit={timelimit}
// setTimeExpired={setTimeExpired}
endTestHandler={endTestHandler}
/>
</div>
{startTime !== -1 ? (
<Button id="end-test" variant="danger" onClick={endTestHandler}>
<span>END TEST</span>
</Button>
) : null}
</div>
</div>
</Col>
</Row>
{startTime === -1 || !captureStarted ? (
<Button onClick={startCaptureHandler} className="start-button">
Start
</Button>
) : null}
</Container>
);
}
export default WebcamCapture;
<file_sep>import cv2
import dlib
from eye_tracking import Eye_tracking
from mouth_tracking import Mouth_tracking
from gaze_tracking import Gaze_Tracking
from head_pose_estimation import Head_Pose_Tracking
import joblib
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("trained_models/shape_predictor_68_face_landmarks.dat")
cap = cv2.VideoCapture(0)
model = joblib.load('trained_models/KNN.pkl')
calibration_count = 0
blink, yawn, center_focus = 0,0,0
while(True):
ret, img = cap.read()
if not ret:
break
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = detector(gray)
# First point of detection -
# If no faces found in video frame, put alert text and skip over to next frame
if not faces:
cv2.putText(img, 'NO FACES FOUND !', (100,100), cv2.FONT_HERSHEY_TRIPLEX, 1.5, (0,0,255), 3)
cv2.imshow('image frame',img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
continue
# take only first face that's detected
face = faces[0]
cv2.rectangle(gray,(face.left(),face.top()),(face.right(),face.bottom()), (0,255,0), 2)
landmarks = predictor(gray,face)
eye_tracker = Eye_tracking(gray, landmarks)
gaze_tracker = Gaze_Tracking(gray, landmarks)
mouth_tracker = Mouth_tracking(gray, landmarks)
head_pose_tracker = Head_Pose_Tracking(gray, landmarks)
if calibration_count < 10:
blink += eye_tracker.analyze()
center_focus += gaze_tracker.analyze()
yawn += mouth_tracker.analyze()
calibration_count+=1
continue
elif calibration_count==10:
blink, yawn, center_focus = blink/calibration_count,yawn/calibration_count,center_focus/calibration_count
print(blink, yawn, center_focus)
calibration_count+=1
eye_lengths_ratio = eye_tracker.analyze()
eye_white_ratio = gaze_tracker.analyze()
mouth_ratio = mouth_tracker.analyze()
(theta_X,_,_) = head_pose_tracker.analyze()
X_test = [(eye_lengths_ratio, eye_white_ratio, mouth_ratio, theta_X)]
y_out = model.predict(X_test)
# cv2.putText(img, str(eye_white_ratio), (50,350), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (0,0,255), 2)
cv2.imshow('gray',gray)
if y_out == 0 or eye_lengths_ratio > 1.3*blink or eye_white_ratio > 2.5*center_focus or eye_white_ratio < 0.35*center_focus or mouth_ratio < 0.65*yawn:
cv2.putText(img, 'INATTENTIVE', (50,50), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (0,0,255), 3)
else:
cv2.putText(img, 'ATTENTIVE', (50,50), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (0,255,0), 3)
if eye_lengths_ratio > 1.3*blink:
cv2.putText(img, 'Sleepy', (50,100), cv2.FONT_HERSHEY_TRIPLEX, 1.5, (0,0,255), 3)
if eye_white_ratio > 2.5*center_focus or eye_white_ratio < 0.35*center_focus:
cv2.putText(img, 'Not focused on Screen', (50,150), cv2.FONT_HERSHEY_TRIPLEX, 1.5, (0,0,255), 3)
if mouth_ratio < 0.65*yawn:
cv2.putText(img, 'Yawning', (50,200), cv2.FONT_HERSHEY_TRIPLEX, 1.5, (0,0,255), 3)
cv2.imshow('image frame',img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
<file_sep>import cv2
import dlib
import numpy as np
import pandas as pd
import math
from eye_tracking import Eye_tracking
from mouth_tracking import Mouth_tracking
from gaze_tracking import Gaze_Tracking
# from head_pose_estimation import Pose_Estimation
# cap = cv2.VideoCapture('test_video/test3.mp4')
# detector = dlib.get_frontal_face_detector()
# predictor = dlib.shape_predictor("trained_models/shape_predictor_68_face_landmarks.dat")
# img=None
# def nothing(x):
# pass
# cv2.namedWindow('image')
# cv2.createTrackbar('threshold', 'image', 0, 255, nothing)
# def draw_landmark(frame, part_no):
# cv2.circle(frame,(landmarks.part(part_no).x,landmarks.part(part_no).y),2,(255,0,0),1)
# cv2.putText(frame, str(part_no), (landmarks.part(part_no).x,landmarks.part(part_no).y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 1)
# left = [36, 37, 38, 39, 40, 41]
# right = [42, 43, 44, 45, 46, 47]
# # kernel = np.ones((9, 9), np.uint8)
# count=0
# cum_l_ratio, cum_r_ratio,cnt=0,0,0
# calibration_count = 0
# blink, yawn, center_focus = 0,0,0
# features = pd.DataFrame(columns=["eye_ratio", "eye_white_ratio", "mouth_ratio"])
# while(True):
# # Capture frame-by-frame
# ret, img = cap.read()
# print(img.shape)
# if not ret: # When video ends, break out of loop
# break
# # Our operations on the frame come here
# gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Converting colored video to grayscale for efficient processing
# # Basic features that would be mainly used in attention tracking
# # gray = cv2.resize(gray,(int(gray.shape[1]*0.8),int(gray.shape[0]*0.8)),interpolation = cv2.INTER_AREA)
# faces = detector(gray)
# # First point of detection -
# # If no faces found in video frame, put alert text and skip over to next frame
# if not faces:
# cv2.putText(img, 'NO FACES FOUND !', (100,100), cv2.FONT_HERSHEY_TRIPLEX, 1.5, (0,0,255), 3)
# for face in faces:
# # rectangle enclosing the face which will contain 68 facial landmarks
# cv2.rectangle(gray,(face.left(),face.top()),(face.right(),face.bottom()), (0,255,0), 2)
# landmarks = predictor(gray,face)
# gaze_tracker = Gaze_Tracking(gray, landmarks)
# eye_tracker = Eye_tracking(gray, landmarks)
# mouth_tracker = Mouth_tracking(gray, landmarks)
# # pose_tracker = Pose_Estimation(img,landmarks)
# # landmarks_pts = np.arange(0,68)
# # for i in landmarks_pts:
# # draw_landmark(gray, i)
# # left_eye_region = np.array([(landmarks.part(i).x, landmarks.part(i).y) for i in left])
# # right_eye_region = np.array([(landmarks.part(i).x, landmarks.part(i).y) for i in right])
# if calibration_count < 10:
# blink += eye_tracker.analyze()
# yawn += mouth_tracker.analyze()
# center_focus += gaze_tracker.analyze()
# calibration_count+=1
# continue
# elif calibration_count==10:
# blink, yawn, center_focus = blink/10,yawn/10,center_focus/10
# print(blink, yawn, center_focus)
# calibration_count+=1
# eye_white_ratio = gaze_tracker.analyze()
# if eye_white_ratio > 1.4*center_focus : #1.8:
# cv2.putText(img, 'LOOKING RIGHT', (100,200), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (0,0,255), 3)
# print('right',eye_white_ratio)
# elif eye_white_ratio < 0.7*center_focus: #0.8 :
# cv2.putText(img, 'LOOKING LEFT', (100,200), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (0,0,255), 3)
# print('left',eye_white_ratio)
# else:
# cv2.putText(img, 'LOOKING CENTER', (100,200), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (0,0,255), 3)
# # print('center',(left_eye_white_ratio+right_eye_white_ratio)/2.0)
# eye_lengths_ratio = eye_tracker.analyze()
# # print((l+r)/2.0)
# if eye_lengths_ratio > 1.3*blink:#3.7: #HARDCODED FOR NOW --- needs to train model, normalize facial features to determine threshold value for each individual
# cv2.putText(img, 'BLINKING/EYES CLOSED', (100,100), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (0,0,255), 3)
# # print(l,r, (l+r)/2.0)
# mouth_ratio = mouth_tracker.analyze()
# if mouth_ratio < 0.75*yawn:#2.0: #HARDCODED FOR NOW --- needs to train model, normalize facial features to determine threshold value for each individual
# cv2.putText(img, 'YAWNING', (100,150), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (0,0,255), 3)
# # print(mouth_ratio)
# # cum_l_ratio = cum_l_ratio + l
# # cum_r_ratio = cum_r_ratio + r
# # print(l,r, "\t\t ==>\t", cum_l_ratio, cum_r_ratio)
# # cnt+=1
# # print(pose_tracker.analyze())
# features_series = pd.Series([eye_lengths_ratio, eye_white_ratio, mouth_ratio], index = features.columns)
# features = features.append(features_series, ignore_index=True)
# print(features)
# cv2.imshow('image',img)
# count+=6
# cap.set(1,count)
# cv2.imshow('gray frame',gray)
# if cv2.waitKey(1) & 0xFF == ord('q'):
# break
# # print(cum_l_ratio/cnt)
# # print(cum_r_ratio/cnt)
# # features.to_csv('dset1.csv')
# # When everything done, release the capture
# cap.release()
# cv2.destroyAllWindows()
gray = cv2.imread('download.webp', 0)
<file_sep>from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
from sklearn import metrics
import joblib
class RandomForest(object):
def __init__(self,data):
self.data = data
def train(self):
accuracy_list=[]
max_depth = []
df_train = self.data[:int(len(self.data)*0.9)]
df_test = self.data[-(len(self.data) - int(len(self.data)*0.9)):]
print(df_test)
X_train = df_train.drop('y_output',axis=1)
y_train = df_train['y_output']
X_test = df_test.drop('y_output',axis=1)
y_test = df_test['y_output']
for i in range(1,10):
RandomForest = RandomForestClassifier(max_depth=i)
RandomForest.fit(X_train, y_train)
y_predict = RandomForest.predict(X_test)
accuracy_list.append(accuracy_score(y_predict, y_test))
max_depth.append(i)
best_depth = max_depth[accuracy_list.index(max(accuracy_list))]
RandomForest = RandomForestClassifier(max_depth=best_depth)
RandomForest.fit(X_train, y_train)
y_predict = RandomForest.predict(X_test)
y_score = RandomForest.predict_proba(X_test)[:,1]
accuracy = accuracy_score(y_test, y_predict)
f1_score = metrics.f1_score(y_test, y_predict)
roc = metrics.roc_auc_score(y_test, y_score)
print("Accuracy % = ",accuracy, "\nF1-score = ", f1_score, "\nROC = ", roc)
print(confusion_matrix(y_test, y_predict))
# joblib.dump(random_forest, 'trained_models/RandomForest.pkl')
<file_sep>import React, { useEffect, useState } from "react";
import { Link, useLocation } from "react-router-dom";
import { Card, Button, Container, Jumbotron } from "react-bootstrap";
import Axios from "axios";
function FetchLogs() {
const serverUrl = "http://127.0.0.1:5000";
const [logs, setLogs] = useState([]);
const location = useLocation();
useEffect(() => {
Axios.get(`${serverUrl}/fetch`).then((response) => {
const data = response.data;
console.log(data);
let logsList = [];
data.forEach((userLog) => {
const userLogDetails = {
name: userLog.name,
examId: userLog.exam_id,
creationTime: new Date(userLog.created_at).toLocaleString(),
finishTime: new Date(
userLog.attention_logs[userLog.attention_logs.length - 1].timestamp
).toLocaleString(),
examTimeLimit: `${userLog.time_limit / (1000 * 60)} mins`,
attentionLogs: userLog.attention_logs,
};
logsList.push(userLogDetails);
});
console.log(logsList);
setLogs(logsList);
});
}, []);
return (
<>
<Jumbotron className="jbtron">
{location.pathname !== "/" ? (
<Link to="/" className="back-button">
<Button>Go Back</Button>
</Link>
) : null}
<h1 className="text-primary text-center">Student Attention Tracking Logs</h1>
</Jumbotron>
<Container className="shadow-lg p-3 mb-5 bg-white rounded">
{logs.map((userLog, index) => (
<Card key={index} className="my-4">
<Card.Header className="bg-dark">
<h3 className="text-primary">{userLog.name}</h3>
<small className="text-danger">Exam ID : {userLog.examId}</small>
</Card.Header>
<Card.Body className="bg-light">
<div>
<b className="text-success">Attempt Start Time : </b>
<span className="text-dark">{userLog.creationTime}</span>
</div>
<div>
<b className="text-danger">Attempt End Time : </b>
<span className="text-dark">{userLog.finishTime}</span>
</div>
<div>
<b className="text-secondary">Time Limit : </b>
<span className="text-dark">{userLog.examTimeLimit}</span>
</div>
<Link to={`/fetchlogs/${userLog.name}/${userLog.examId}`}>
<Button variant="primary" block>
Get Attention Log Analysis
</Button>
</Link>
</Card.Body>
</Card>
))}
</Container>
</>
);
}
export default FetchLogs;
<file_sep>import React, { useState, useEffect, useContext } from "react";
import { Container } from "react-bootstrap";
import { useHistory } from "react-router-dom";
import UserContext from "../../context/UserContext";
import Axios from "axios";
import ErrorNotice from "../misc/ErrorNotice";
import "./auth.css";
export default function Login() {
const [email, setEmail] = useState();
const [password, setPassword] = useState();
const [isAdmin, setIsAdmin] = useState(false);
const [error, setError] = useState();
// const [authorized, setAuthorized] = useState(false);
const { userData, setUserData } = useContext(UserContext);
const history = useHistory();
useEffect(() => {
console.log(userData.user === true);
if (userData.user) history.push("/");
}, [history, userData.user]);
const submit = async (e) => {
e.preventDefault();
let serverUrl = "http://localhost:10000/users/login";
if (isAdmin) serverUrl = "http://localhost:10000/users/login/admin";
try {
const loginUser = { email, password };
console.log(loginUser);
const loginRes = await Axios.post(serverUrl, loginUser);
setUserData({
token: loginRes.data.token,
user: loginRes.data.user,
});
localStorage.setItem("auth-token", loginRes.data.token);
history.push("/");
// setAuthorized(true);
} catch (err) {
err.response.data.msg && setError(err.response.data.msg);
console.log(err);
}
};
// if (authorized) return <Redirect to="/webcam" />;
return (
<Container>
<h2>Log in</h2>
{error && <ErrorNotice message={error} clearError={() => setError(undefined)} />}
<form className="form" onSubmit={submit}>
<label htmlFor="login-email">Email</label>
<input id="login-email" type="email" onChange={(e) => setEmail(e.target.value)} />
<label htmlFor="login-password">Password</label>
<input id="login-password" type="password" onChange={(e) => setPassword(e.target.value)} />
<label htmlFor="admin"> Login as Admin</label>
<input
type="checkbox"
id="admin"
name="admin"
value="admin"
onChange={(e) => {
setIsAdmin(e.target.checked);
}}
/>
<input type="submit" value="Log in" />
</form>
</Container>
);
}
<file_sep>from flask import Flask
from flask import *
from flask_cors import CORS, cross_origin
import json
from datetime import datetime
import pytz
from server_image_processing import server_image_processing
from database.db import initialize_db
from database.models import TrackingLogs, Exams
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
app.config['MONGODB_SETTINGS'] = {
'host':'mongodb://localhost:27017/Attention-tracking'
}
initialize_db(app)
process_image = server_image_processing()
@app.route('/fetch/<user>/<exam_id>', methods=['GET'])
@cross_origin()
def fetch_logs(user,exam_id):
user_log = TrackingLogs.objects(name=user,exam_id=exam_id).get()
print('dsdsds',user_log)
return user_log.to_json()
@app.route('/fetch/<user>', methods=['GET'])
@cross_origin()
def fetch_user_log(user):
user_log = TrackingLogs.objects(name=user)
return user_log.to_json()
@app.route('/fetch', methods=['GET'])
@cross_origin()
def fetch_all_logs():
user_logs = TrackingLogs.objects()
return json.dumps(json.loads(user_logs.to_json()))
@app.route('/', methods=['POST'])
@cross_origin()
def image_processing():
json_data = request.get_json()
data_uri = json_data['imageSrc']
# calib = json_data['calibration']
user = json_data['user']
exam_id = json_data['examID']
time_limit = json_data['timeLimit']
initial_calibrated_values = {'eye':0, 'mouth':0, 'gaze':0, 'calibration_count': 0}
# user_log = TrackingLogs.objects(name=user, exam_id=exam_id).modify(upsert=True, new=True, set__name=user, set__exam_id=exam_id, set__time_limit=time_limit, set__calibrated_values=calib)
user_log=None
try:
user_log = TrackingLogs.objects(name=user, exam_id=exam_id).get()
except:
user_log = TrackingLogs(name=user, exam_id=exam_id, created_at=str(datetime.now(pytz.timezone('Asia/Kolkata'))), time_limit=time_limit, calibrated_values = initial_calibrated_values).save()
calibrated_values = user_log.calibrated_values
# calibrated_values = {'eye': calib['eye'], 'mouth': calib['mouth'], 'gaze':calib['gaze']}
# print(calibrated_values)
(success, data, calibration) = process_image.process_image(data_uri, calibrated_values)
print('before process calib -',calibrated_values)
print('after process calib -', calibration)
response = {'success':success['success'], 'data': data}
json_response = json.dumps(response, indent = 4)
# print(json_response)
user_log.attention_logs.append({'timestamp':str(datetime.now(pytz.timezone('Asia/Kolkata'))), 'data':data})
user_log.save()
# user_log = TrackingLogs(name=user).save()
return json_response
def evaluate(questions, answers):
marks_obtained = 0
for idx, question in enumerate(questions):
marks = float(question['marks'])
if question['questionType'] == 'radio':
correct_options = question['correctOption']
answered_options = answers.get(str(idx))
if answered_options == None:
continue
if correct_options == answered_options:
marks_obtained += marks
elif question['questionType'] == 'checkbox':
correct_options = question['correctOption']
answered_options = answers.get(str(idx))
if answered_options == None:
continue
total_correct, correctly_checked, wrongly_checked = 0, 0, 0
for i in range(4):
if correct_options[i] == True:
total_correct += 1
if answered_options[i] == correct_options[i] :
correctly_checked += 1
else :
if answered_options[i] == True:
wrongly_checked += 1
if wrongly_checked > 0:
pass
else:
marks_obtained += (marks/total_correct) * correctly_checked
elif question['questionType'] == 'number':
try:
if float(question['correctOption']) == float(answers.get(str(idx))):
marks_obtained += marks
except:
pass
return marks_obtained
# Ends exam (referenced by examId) for a given user (referenced by user name) and evaluates the result
@app.route('/end', methods=['POST'])
@cross_origin()
def end():
json_data = request.get_json()
user = json_data['user']
exam_id = json_data['examID']
user_log = TrackingLogs.objects(name=user,exam_id=exam_id).get()
user_log.finished_at = str(datetime.now(pytz.timezone('Asia/Kolkata')))
exam = Exams.objects.get(id=exam_id)
marks_obtained = evaluate(exam.questions, user_log.answers)
user_log.marks_obtained = marks_obtained
user_log.save()
return 'success'
@app.route('/recalibrate', methods=['POST'])
@cross_origin()
def re_calibrate():
json_data = request.get_json()
user = json_data['user']
exam_id = json_data['examID']
calibrated_values = {'eye':0, 'mouth':0, 'gaze':0, 'calibration_count': 0}
user_log = TrackingLogs.objects(name=user,exam_id=exam_id).get()
user_log.calibrated_values = calibrated_values
user_log.save()
return 'success'
@app.route('/time', methods=['POST'])
@cross_origin()
def get_initial_values():
json_data = request.get_json()
user = json_data['user']
exam_id = json_data['examID']
user_log=None
try:
user_log = TrackingLogs.objects(name=user,exam_id=exam_id).get()
except:
response = {'created_at':-1, 'finished_at':'-'}
json_response = json.dumps(response, indent = 4)
return json_response
created_at = user_log.created_at
finished_at = user_log.finished_at
calibrated_values = user_log.calibrated_values
response = {'created_at':str(created_at), 'finished_at':str(finished_at)}
json_response = json.dumps(response, indent = 4)
print('********', created_at)
print('********', calibrated_values)
return json_response
@app.route('/getAnswers', methods=['POST'])
@cross_origin()
def get_answers():
json_data = request.get_json()
user = json_data['user']
exam_id = json_data['examID']
user_log = TrackingLogs.objects(name=user,exam_id=exam_id).get()
answers = user_log.answers
response = {'answers':answers}
json_response = json.dumps(response, indent = 4)
return json_response
@app.route('/saveAnswers', methods=['POST'])
@cross_origin()
def save_answers():
json_data = request.get_json()
user = json_data['user']
exam_id = json_data['examID']
answers = json_data['answers']
user_log = TrackingLogs.objects(name=user,exam_id=exam_id).get()
user_log.answers = answers
user_log.save()
return 'success'
<file_sep># import pandas as pd
# import numpy as np
# from logistic_regression_model import LRModel
# from KNN import KNN
# from Random_Forest import RandomForest
# from Decision_Tree import DecisionTree
# from Naive_Bayes import NaiveBayes
# df1 = pd.read_csv('dset1.csv')
# df1['y_output'] = pd.Series(np.array([1]*len(df1)), index=df1.index)
# df1 = df1.drop(df1.columns[0], axis=1)
# df2 = pd.read_csv('dset2.csv')
# df2['y_output'] = pd.Series(np.array([0]*len(df2)), index=df2.index)
# df2 = df2.drop(df2.columns[0], axis=1)
# df = df1.append(df2, ignore_index=True)
# df = df.sample(frac=1).reset_index(drop=True)
# df.to_csv('test_data.csv')
# # print(df)
# dataset = pd.read_csv('test_data.csv')
# dataset = dataset.drop(dataset.columns[0:2],axis=1)
# # dataset = dataset.drop(dataset.columns[1:3],axis=1)
# # print(dataset)
# model = DecisionTree(dataset)
# model.train()
from datetime import datetime
import pytz
print(datetime.now(pytz.timezone('Asia/Kolkata')))
<file_sep>import cv2
import numpy as np
import math
class Eye_tracking(object):
def __init__(self, frame, landmarks) -> None:
self.frame = frame
self.landmarks = landmarks
def get_horizontal_eye_length(self, left=True):
landmark_points = [0]*2
if left == True:
landmark_points = [36, 39]
else:
landmark_points = [42, 45]
left_eye_point = (self.landmarks.part(landmark_points[0]).x,self.landmarks.part(landmark_points[0]).y)
right_eye_point = (self.landmarks.part(landmark_points[1]).x,self.landmarks.part(landmark_points[1]).y)
# cv2.line(self.frame, left_eye_point,right_eye_point, (0,0,255),2)
horizontal_length = math.hypot(right_eye_point[0] - left_eye_point[0], right_eye_point[1] - left_eye_point[1])
return horizontal_length
def get_vertical_eye_length(self, left=True):
landmark_points = [0]*4
if left == True:
landmark_points=[37, 38, 40, 41]
else:
landmark_points=[43, 44, 46, 47]
top_eye_point = ((self.landmarks.part(landmark_points[0]).x + self.landmarks.part(landmark_points[1]).x)//2,(self.landmarks.part(landmark_points[0]).y + self.landmarks.part(landmark_points[1]).y)//2)
bottom_eye_point = ((self.landmarks.part(landmark_points[2]).x + self.landmarks.part(landmark_points[3]).x)//2,(self.landmarks.part(landmark_points[2]).y + self.landmarks.part(landmark_points[3]).y)//2)
# cv2.line(self.frame, top_eye_point,bottom_eye_point, (0,0,255),2)
vertical_length = math.hypot((top_eye_point[0] - bottom_eye_point[0]),(top_eye_point[1] - bottom_eye_point[1]))
return vertical_length
def analyze(self):
left_eye_ratio = self.get_horizontal_eye_length(True)/self.get_vertical_eye_length(True)
right_eye_ratio = self.get_horizontal_eye_length(False)/self.get_vertical_eye_length(False)
# print(self.get_horizontal_eye_length(True),self.get_vertical_eye_length(True),' | ',self.get_horizontal_eye_length(False),self.get_vertical_eye_length(False))
return (left_eye_ratio + right_eye_ratio)/2
<file_sep>import cv2
# import imutils
import numpy as np
import dlib
# creating a list of facial coordinates
def landmarksToCoordines(landmarks, dtype="int"):
# initializing the list with the 68 coordinates
coord = np.zeros((68, 2), dtype=dtype)
# go through the 68 coordinates and return
# coordinates in a list with the format (x, y)
for i in range(0, 68):
coord[i] = (landmarks.part(i).x, landmarks.part(i).y)
# return the list of coordinates
return coord
class Head_Pose_Tracking(object):
def __init__(self, frame, landmarks):
self.frame = frame
# self.frame = imutils.resize(self.frame, width=400)
self.landmarks = landmarks
self.landmarks = landmarksToCoordines(self.landmarks)
self.key_features=[]
self.key_features.append(self.landmarks[30]) #tip of the nose
self.key_features.append(self.landmarks[8]) #chin tip
self.key_features.append(self.landmarks[36]) #left corner of the eye
self.key_features.append(self.landmarks[45]) #right corner of the eye
self.key_features.append(self.landmarks[48]) #left corner of the mouth
self.key_features.append(self.landmarks[54]) #right corner of the mouth
def analyze(self):
points_2d = np.asarray(self.key_features, dtype=np.float32).reshape((6, 2))
points_3d = np.array([
(0.0, 0.0, 0.0),
(0.0, -330.0, -65.0),
(-225.0, 170.0, -135.0),
(225.0, 170.0, -135.0),
(-150.0, -150.0, -125.0),
(150.0, -150.0, -125.0)
])
dimensions = self.frame.shape
focal_length = dimensions[1]
center = (dimensions[1]/2, dimensions[0]/2)
cam_matrix = np.array(
[[focal_length, 0, center[0]],
[0, focal_length, center[1]],
[0, 0, 1]], dtype = "double"
)
coef_dist = np.zeros((4,1)) # assume we have no camera distortion
(success, rotation_vector, translation_vector) = cv2.solvePnP(points_3d, points_2d, cam_matrix, coef_dist, flags=cv2.SOLVEPNP_ITERATIVE)
(nose_end_point2D, jacobian) = cv2.projectPoints(np.array([(0.0, 0.0, 1000.0)]), rotation_vector, translation_vector, cam_matrix, coef_dist)
rotation_mat, _ = cv2.Rodrigues(rotation_vector)
pose_mat = cv2.hconcat((rotation_mat, translation_vector))
_, _, _, _, _, _, euler_angle = cv2.decomposeProjectionMatrix(pose_mat)
cv2.putText(self.frame, "X: " + "{:7.2f}".format(euler_angle[1, 0]), (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), thickness=2)
cv2.putText(self.frame, "Y: " + "{:7.2f}".format(euler_angle[0, 0]), (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), thickness=2)
cv2.putText(self.frame, "Z: " + "{:7.2f}".format(euler_angle[2, 0]), (10, 80), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), thickness=2)
for p in points_2d:
cv2.circle(self.frame, (int(p[0]), int(p[1])), 3, (0,0,255), -1)
p1 = ( int(points_2d[0][0]), int(points_2d[0][1]))
p2 = ( int(nose_end_point2D[0][0][0]), int(nose_end_point2D[0][0][1]))
# print (points_2d, nose_end_point2D)
cv2.line(self.frame, p1, p2, (255,0,0), 2)
# cv2.imshow('head_angles', self.frame)
return (euler_angle[1, 0], euler_angle[0, 0], euler_angle[2, 0])
<file_sep>import pandas as pd
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
from sklearn import metrics
class LRModel(object):
def __init__(self,data):
self.data = data
def train(self):
df_train = self.data[:int(len(self.data)*0.8)]
df_test = self.data[-(len(self.data) - int(len(self.data)*0.8)):]
X_train = df_train.drop('y_output',axis=1)
Y_train = df_train['y_output']
X_test = df_test.drop('y_output',axis=1)
y_test = df_test['y_output']
lr = LogisticRegression().fit(X_train, Y_train)
y_predict = lr.predict(X_test)
print(y_predict)
y_score_3 = lr.predict_proba(X_test)[:,1]
acc3 = accuracy_score(y_test, y_predict)
f1_score_3 = metrics.f1_score(y_test, y_predict)
roc_3 = metrics.roc_auc_score(y_test, y_score_3)
print([acc3,f1_score_3,roc_3])
print(confusion_matrix(y_test, y_predict))
<file_sep>import cv2
import numpy as np
import math
class Mouth_tracking(object):
def __init__(self, frame, landmarks) -> None:
self.frame = frame
self.landmarks = landmarks
def get_horizontal_mouth_length(self):
landmark_points = [48,54];
left_mount_point = (self.landmarks.part(landmark_points[0]).x,self.landmarks.part(landmark_points[0]).y)
right_mount_point = (self.landmarks.part(landmark_points[1]).x,self.landmarks.part(landmark_points[1]).y)
# cv2.line(self.frame, left_mount_point,right_mount_point, (0,0,255),2)
horizontal_length = math.hypot(right_mount_point[0] - left_mount_point[0], right_mount_point[1] - left_mount_point[1])
return horizontal_length
def get_vertical_mouth_length(self):
landmark_points = [57,51];
top_mount_point = (self.landmarks.part(landmark_points[0]).x,self.landmarks.part(landmark_points[0]).y)
bottom_mount_point = (self.landmarks.part(landmark_points[1]).x,self.landmarks.part(landmark_points[1]).y)
# cv2.line(self.frame, top_mount_point,bottom_mount_point, (0,0,255),2)
horizontal_length = math.hypot(bottom_mount_point[0] - top_mount_point[0], bottom_mount_point[1] - top_mount_point[1])
return horizontal_length
def analyze(self):
mouth_ratio = self.get_horizontal_mouth_length()/self.get_vertical_mouth_length()
# print(mouth_ratio)
# cv2.putText(self.frame, str(mouth_ratio), (50,50), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (0,0,255), 2)
return mouth_ratio
| ce4302207976e0a1b7fc25054b72e2af38ad4088 | [
"JavaScript",
"Python"
] | 18 | Python | archit11111/Attention-Tracking-System | 1411441e59b442c7cb1bf0ab95cdf894e3e12de8 | 677f316b75e136000bfbfd4d3b7a1398ce142d8e |
refs/heads/master | <repo_name>iansrc0811/overtime-test-app<file_sep>/spec/factories/posts.rb
#factory girl
#命名用model name的複數
FactoryGirl.define do
# 使用FactoryGirl.create(:post) 可在測試中建立一個post
factory :post do
date Date.today
rationale "Some Rationale"
overtime_request 3.5
user
end
factory :second_post, class: "Post" do
#使用FactoryGirl.create(:second_post) 可在測試中建立另一個post
#明確指定class (model) 為Post
date Date.yesterday
rationale "Some more content"
overtime_request 0.5
user
end
=begin
factory :post_from_other_user, class: "Post" do
date Date.yesterday
rationale "This post shouldn't be seen"
user { FactoryGirl.create(:non_authorized_user) } #不知為何其實這是失效的,不會存到non_authorized_user
end
=end
end<file_sep>/app/policies/post_policy.rb
class PostPolicy < ApplicationPolicy
def update?
#此處的record 就是post, post.approved 中的approved是post status(enum)其中之一
return true if admin? && post_approved?
#若post已approved,只有admin user 可以修改
return true if user_or_admin && !post_approved?
#當為本人或是admim的時候, 且還沒approved, 才可以update
#see def admin_types in application_policy.rb
end
private
def user_or_admin
record.user_id == user.id || admin?
end
def admin?
admin_types.include?(user.type)
end
def post_approved?
record.approved?
end
end <file_sep>/db/seeds.rb
@user = User.create(email: "<EMAIL>", password: '<PASSWORD>',
password_confirmation: "<PASSWORD>" , first_name: "john", last_name: "Snow")
puts "1 user created"
AdminUser.create(email: "<EMAIL>", password: '<PASSWORD>',
password_confirmation: "<PASSWORD>" , first_name: "admin", last_name: "user")
puts "1 AdminUser created"
100.times do |post|
Post.create!(date: Date.today, rationale: "#{post} rationale content",
user_id: @user.id, overtime_request: 2.5)
end
puts "100 Posts have been created"<file_sep>/README.MD
# About Overtime
###Ruby on Rails exercise project
- Only AdminUsers can create new users
- Using gem 'adminstrate' to implement admin page
- Using gem 'devise' to implement User authorization
- Using TDD in this project, using gem 'factory_girl_rails', 'capybara', 'rspec-rails'
### Functionality
- For authorized users to submit time entries about absence, over-time work, compensatory time used.
- For Admin Users to check user time entries. Admin Users decide to approve or not.
#To be continue..
<file_sep>/config/routes.rb
Rails.application.routes.draw do
namespace :admin do
resources :users
resources :posts
resources :admin_users
root to: "users#index"
end
resources :posts
devise_for :users, skip: [:registrations]
root to:'static#home'
get "*path", to: redirect('/')
end
| c533b799fdc7d970ed1b08c94eff6028a92e0474 | [
"Markdown",
"Ruby"
] | 5 | Ruby | iansrc0811/overtime-test-app | 603bc11952f9b00bccf601d086126c26db34361b | e1ac4f5e1bc4a4a7b46991781c6e65c50dc6bedb |
refs/heads/master | <file_sep>/**
* @file ConstantBufferOpenGL.h
* @brief OpenGL版コンスタントバッファ(ユニフォームブロックバッファ)
* @author tsukushibito
* @version 0.0.1
* @date 2015-09-18
*/
#pragma once
#ifndef GUARD_7776c086b1464092b7025bb847ef8699
#define GUARD_7776c086b1464092b7025bb847ef8699
#include "../ConstantBuffer.h"
#include "../Define.h"
namespace temp {
namespace graphics {
namespace opengl {
class ConstantBufferOpenGL
: public temp::graphics::ConstantBufferBase < ConstantBufferOpenGL > {
friend DeviceOpenGL;
using Super = temp::graphics::ConstantBufferBase < ConstantBufferOpenGL > ;
private:
ConstantBufferOpenGL(temp::UInt32 handle, Size size);
public:
temp::UInt32 getNativeHandle() const { return handle_; }
private:
temp::UInt32 handle_;
};
}
}
}
#endif // GUARD_7776c086b1464092b7025bb847ef8699<file_sep>/**
* @file Logger.h
* @brief ロガー
* @author tsukushibito
* @version 0.0.1
* @date 2015-09-17
*/
#pragma once
#ifndef GUARD_325c251321394362a453f269833195ae
#define GUARD_325c251321394362a453f269833195ae
#ifdef TEMP_PLATFORM_WINDOWS
#pragma warning(push)
#pragma warning(disable:4244)
#endif
#include <spdlog.h>
#ifdef TEMP_PLATFORM_WINDOWS
#pragma warning(pop)
#endif
#include "../TempuraCommon.h"
namespace temp {
namespace system {
template <typename LoggerCreatorType>
class Logger : temp::Uncopyable {
private:
Logger() {
spLogger_ = LoggerCreatorType::create();
spLogger_->set_level(spdlog::level::trace);
}
~Logger() = default;
public:
static void initialize() {
pInstance = new Logger;
#ifdef TEMP_PLATFORM_WINDOWS
default_rdbuf = std::cout.rdbuf(&dsb);
#endif
}
static void terminate() {
#ifdef TEMP_PLATFORM_WINDOWS
std::cout.rdbuf(default_rdbuf);
#endif
delete pInstance;
}
template <typename... Args> static void trace(const char* fmt, const Args&... args) {
pInstance->spLogger_->trace(fmt, args...);
}
template <typename... Args> static void debug(const char* fmt, const Args&... args) {
pInstance->spLogger_->debug(fmt, args...);
}
template <typename... Args> static void info(const char* fmt, const Args&... args) {
pInstance->spLogger_->info(fmt, args...);
}
template <typename... Args> static void notice(const char* fmt, const Args&... args) {
pInstance->spLogger_->info(fmt, args...);
}
template <typename... Args> static void warn(const char* fmt, const Args&... args) {
pInstance->spLogger_->info(fmt, args...);
}
template <typename... Args> static void error(const char* fmt, const Args&... args) {
pInstance->spLogger_->error(fmt, args...);
}
template <typename... Args> static void critical(const char* fmt, const Args&... args) {
pInstance->spLogger_->critical(fmt, args...);
}
template <typename... Args> static void alert(const char* fmt, const Args&... args) {
pInstance->spLogger_->alert(fmt, args...);
}
template <typename... Args> static void emerg(const char* fmt, const Args&... args) {
pInstance->spLogger_->emerg(fmt, args...);
}
private:
static Logger *pInstance;
std::shared_ptr<spdlog::logger> spLogger_;
#ifdef TEMP_PLATFORM_WINDOWS
// デバッグコンソール出力用ストリームバッファ
class debug_stream_buf : public std::streambuf
{
public:
virtual int_type overflow(int_type c = EOF)
{
if (c != EOF)
{
char buf[] = { static_cast<char>(c), '\0' };
OutputDebugStringA(buf);
}
return c;
}
};
static debug_stream_buf dsb;
static std::streambuf *default_rdbuf;
#endif
};
template<typename LoggerCreatorType>
Logger<LoggerCreatorType> *Logger<LoggerCreatorType>::pInstance = nullptr;
#ifdef TEMP_PLATFORM_WINDOWS
template<typename LoggerCreatorType>
typename Logger<LoggerCreatorType>::debug_stream_buf Logger<LoggerCreatorType>::dsb;
template<typename LoggerCreatorType>
std::streambuf *Logger<LoggerCreatorType>::default_rdbuf = nullptr;
#endif
struct ConsoleLoggerCreator {
static std::shared_ptr <spdlog::logger> create() {
auto ostream_sink = std::make_shared<spdlog::sinks::ostream_sink_mt>(std::cout);
return std::make_shared<spdlog::logger>("TempuraConsole", ostream_sink);
}
};
using ConsoleLogger = Logger <ConsoleLoggerCreator> ;
}
}
#endif // GUARD_325c251321394362a453f269833195ae
<file_sep>/**
* @file ViewOpenGLWindows.h
* @brief Windows版OpenGLビュー
* @author tsukushibito
* @version 0.0.1
* @date 2015-08-07
*/
#pragma once
#ifndef GUARD_71e7f79414034ff085353f7eee7f2583
#define GUARD_71e7f79414034ff085353f7eee7f2583
#include "../ViewOpenGLBase.h"
#if defined TEMP_PLATFORM_WINDOWS
#include <Windows.h>
namespace temp {
namespace graphics {
namespace opengl {
namespace windows {
class ViewOpenGLWindows : public ViewOpenGLBase {
friend class DeviceOpenGLWindows;
private:
explicit ViewOpenGLWindows(HDC hdc);
public:
~ViewOpenGLWindows() {}
void present();
private:
HDC hdc_;
};
}
}
}
}
#endif // TEMP_PLATFORM_WINDOWS
#endif // GUARD_71e7f79414034ff085353f7eee7f2583
<file_sep>/**
* @file FileSystem.h
* @brief ファイルシステム
* @author tsukushibito
* @version 0.0.1
* @date 2015-04-03
*/
#pragma once
#ifndef GUARD_09a682659d4d459aa392b530fc1ec178
#define GUARD_09a682659d4d459aa392b530fc1ec178
#include "../TempuraCommon.h"
namespace temp {
namespace system {
class Path {
public:
private:
std::string pathStr_;
};
void createDirectory();
}
}
#endif // GUARD_09a682659d4d459aa392b530fc1ec178
<file_sep>#include "../../TempuraCommon.h"
#include "../GraphicsCommon.h"
#ifdef TEMP_GRAPHICS_OPENGL
#include "BackBufferOpenGL.h"
namespace temp {
namespace graphics {
namespace opengl {
BackBufferOpenGL::BackBufferOpenGL(temp::UInt32 handle,
const Texture2DDesc &desc)
: Super(desc), handle_(handle) {}
}
}
}
#endif
<file_sep>/**
* @file Application.h
* @brief アプリケーションクラス
* @author tsukushibito
* @version 0.0.1
* @date 2014-11-02
*/
#pragma once
#ifndef GUARD_71d3cbf974874004b4a35a0f9a08cca6
#define GUARD_71d3cbf974874004b4a35a0f9a08cca6
#include "../TempuraCommon.h"
namespace temp {
namespace system {
using MainLoopFunc = std::function < void(void) > ;
class Application : public temp::Singleton<Application> {
friend temp::Singleton<Application>;
private:
Application();
public:
~Application();
void setMainLoopFunc(const MainLoopFunc &func);
Int32 run();
private:
class Impl;
Impl *pImpl_;
};
}
}
#endif // GUARD_71d3cbf974874004b4a35a0f9a08cca6
<file_sep>/**
* @file ContextOpenGL.h
* @brief OpenGL版コンテキスト
* @author tsukushibito
* @version 0.0.1
* @date 2015-02-19
*/
#pragma once
#ifndef GUARD_f383d445787243c28e101c1ac25c4f6b
#define GUARD_f383d445787243c28e101c1ac25c4f6b
#include "../../TempuraCommon.h"
#include "../Define.h"
#include "../Context.h"
namespace temp {
namespace graphics {
namespace opengl {
class ContextOpenGL : public temp::graphics::ContextBase<ContextOpenGL> {
friend DeviceOpenGL;
private:
ContextOpenGL();
public:
void clearRenderTarget(const RenderTargetPtr &spRenderTarget,
const temp::Color &clearColor);
void clearDepthStencil(const DepthStencilPtr &spDepthStencil, CLEAR_FLAG flags,
Float32 depth, UInt8 stencil);
void setShaderObject(const ShaderObjectPtr &spShaderObject);
void setInputLayout(const InputLayoutPtr &spInputLayout);
void updateConstantBuffer(const ConstantBufferPtr &spConstantBuffer, void *pData, Size dataSize);
private:
InputLayoutPtr spInputLayout_;
};
}
}
}
#endif // GUARD_f383d445787243c28e101c1ac25c4f6b
<file_sep>/**
* @file VertexBuffer.h
* @brief 頂点バッファ
* @author tsukushibito
* @version 0.0.1
* @date 2015-03-20
*/
#pragma once
#ifndef GUARD_0f5cbaa038c347b98faa5dfaa83a7ae3
#define GUARD_0f5cbaa038c347b98faa5dfaa83a7ae3
#include "GraphicsCommon.h"
namespace temp {
namespace graphics {
template <class T>
class VertexBufferBase : temp::Castable<T>, public temp::ReferenceObject {
public:
explicit VertexBufferBase(const VertexBufferDesc &desc) : desc_(desc) {}
VertexBufferDesc getDesc() const { return desc_; }
private:
VertexBufferDesc desc_;
};
}
}
#endif // GUARD_0f5cbaa038c347b98faa5dfaa83a7ae3
<file_sep>/**
* @file SamplerState.h
* @brief サンプラステート
* @author tsukushibito
* @version 0.0.1
* @date 2015-04-01
*/
#pragma once
#ifndef GUARD_d8d1be76fc284ae4b15ee1bf3826f55c
#define GUARD_d8d1be76fc284ae4b15ee1bf3826f55c
#include "GraphicsCommon.h"
namespace temp {
namespace graphics {
template <class T>
class SamplerStateBase : temp::Castable<T>, public temp::ReferenceObject {
public:
explicit SamplerStateBase(const SamplerDesc &desc) : desc_(desc) {}
SamplerDesc getDesc() const { return desc_; }
private:
SamplerDesc desc_;
};
}
}
#endif // GUARD_d8d1be76fc284ae4b15ee1bf3826f55c
<file_sep>/**
* @file Tempura.h
* @brief ゲーム実装時組み込み用ヘッダ
* @author tsukushibito
* @version 0.0.1
* @date 2014-10-28
*/
#pragma once
#ifndef GUARD_971c9781bfa146af963e57c5ca5c920a
#define GUARD_971c9781bfa146af963e57c5ca5c920a
#include "TempuraCommon.h"
#include "System/System.h"
#include "Allocator/TlsfAllocator.h"
#include "Resource/Resource.h"
#include "Graphics/Graphics.h"
#endif // GUARD_971c9781bfa146af963e57c5ca5c920a
<file_sep>/**
* @file BlendState.h
* @brief ブレンドステート
* @author tsukushibito
* @version 0.0.1
* @date 2015-04-01
*/
#pragma once
#ifndef GUARD_fb2aa5c65f6b48f48bca80795dd4e3c4
#define GUARD_fb2aa5c65f6b48f48bca80795dd4e3c4
#include "GraphicsCommon.h"
namespace temp {
namespace graphics {
template <class T>
class BlendStateBase : temp::Castable<T>, public temp::ReferenceObject {
public:
explicit BlendStateBase(const BlendDesc &desc) : desc_(desc) {}
BlendDesc getDesc() const { return desc_; }
private:
BlendDesc desc_;
};
}
}
#endif // GUARD_fb2aa5c65f6b48f48bca80795dd4e3c4
<file_sep>/**
* @file Context.h
* @brief デバイスコンテキスト
* @author tsukushibito
* @version 0.0.1
* @date 2015-02-18
*/
#pragma once
#ifndef GUARD_acfbc2c29ba8411c98865d5bccfdfe03
#define GUARD_acfbc2c29ba8411c98865d5bccfdfe03
#include "GraphicsCommon.h"
#include "Define.h"
namespace temp {
namespace graphics {
template <class T>
class ContextBase : temp::Castable<T>, public temp::ReferenceObject {
public:
void clearRenderTarget(const RenderTargetPtr &spRenderTarget,
const temp::Color &clearColor) {
Castable<T>::derive()->clearRenderTarget(spRenderTarget, clearColor);
}
void clearDepthStencil(const DepthStencilPtr &spDepthStencil, CLEAR_FLAG flags,
Float32 depth, UInt8 stencil) {
Castable<T>::derive()->clearDepthStencil(spDepthStencil, flags, depth,
stencil);
}
void setShaderObject(const ShaderObjectPtr &spShaderObject){
Castable<T>::derive()->setShaderObject(spShaderObject);
}
void setInputLayout(const InputLayoutPtr &spInputLayout){
Castable<T>::derive()->setInputLayout(spInputLayout);
}
};
}
}
#endif // GUARD_acfbc2c29ba8411c98865d5bccfdfe03
<file_sep>/**
* @file ShaderObject.h
* @brief シェーダオブジェクト
* @author tsukushibito
* @version 0.0.1
* @date 2015-09-15
*/
#pragma once
#ifndef GUARD_f407994577fa4bd086bf9491977fa1f4
#define GUARD_f407994577fa4bd086bf9491977fa1f4
namespace temp {
namespace graphics {
template <class T>
class ShaderObjectBase : temp::Castable<T>, public temp::ReferenceObject {
public:
};
}
}
#endif // GUARD_f407994577fa4bd086bf9491977fa1f4
<file_sep>/**
* @file SamplerStateOpenGL.h
* @brief OpneGL版サンプラステート
* @author tsukushibito
* @version 0.0.1
* @date 2015-04-01
*/
#pragma once
#ifndef GUARD_6b0b843bb5b54752805684264aa04ced
#define GUARD_6b0b843bb5b54752805684264aa04ced
#include "../SamplerState.h"
#include "../Define.h"
namespace temp {
namespace graphics {
namespace opengl {
class SamplerStateOpenGL
: public temp::graphics::SamplerStateBase<SamplerStateOpenGL> {
friend class DeviceOpenGLBase;
typedef temp::graphics::SamplerStateBase<SamplerStateOpenGL>
Super;
private:
SamplerStateOpenGL(const SamplerDesc &desc) : Super(desc) {}
};
}
}
}
#endif // GUARD_6b0b843bb5b54752805684264aa04ced
<file_sep>/**
* @file RenderTargetOpenGL.h
* @brief Mac版レンダーターゲット
* @author tsukushibito
* @version 0.0.1
* @date 2015-03-20
*/
#pragma once
#ifndef GUARD_c593b4c0ea914ee899bc1f6618ca81b5
#define GUARD_c593b4c0ea914ee899bc1f6618ca81b5
#include "../RenderTarget.h"
#include "../Define.h"
namespace temp {
namespace graphics {
namespace opengl {
class RenderTargetOpenGL
: public temp::graphics::RenderTargetBase<RenderTargetOpenGL> {
friend class DeviceOpenGLBase;
friend class ViewOpenGLBase;
typedef temp::graphics::RenderTargetBase<RenderTargetOpenGL> Super;
private:
RenderTargetOpenGL(temp::UInt32 handle, const RenderTargetDesc &desc);
public:
temp::UInt32 getNativeHandle() const { return handle_; }
private:
temp::UInt32 handle_;
};
}
}
}
#endif // GUARD_c593b4c0ea914ee899bc1f6618ca81b5
<file_sep>/**
* @file InputLayout.h
* @brief 入力レイアウト
* @author tsukushibito
* @version 0.0.1
* @date 2015-08-26
*/
#pragma once
#ifndef GUARD_7bd7a479fee44ac7a6a4d75616d99aa6
#define GUARD_7bd7a479fee44ac7a6a4d75616d99aa6
#include "GraphicsCommon.h"
#include "Define.h"
namespace temp {
namespace graphics {
template <class T>
class InputLayoutBase : temp::Castable<T>, public temp::ReferenceObject {
public:
static const Size MAX_ELEMENT_COUNT = 8;
explicit InputLayoutBase(const InputElementDesc *descs, Size elementCount)
{
elementCount_ = elementCount;
if (elementCount_ > MAX_ELEMENT_COUNT) {
elementCount_ = MAX_ELEMENT_COUNT;
}
for(Size i = 0; i < elementCount_; ++i) {
descs_[i] = descs[i];
}
}
const InputElementDesc *getDescs() const { return descs_; }
private:
Size elementCount_;
InputElementDesc descs_[MAX_ELEMENT_COUNT];
};
}
}
#endif // GUARD_7bd7a479fee44ac7a6a4d75616d99aa6
<file_sep>#include "../../TempuraCommon.h"
#ifdef TEMP_GRAPHICS_OPENGL
#include "OpenGLCommon.h"
#include "ShaderObjectOpenGL.h"
namespace temp {
namespace graphics {
namespace opengl {
ShaderObjectOpenGL::ShaderObjectOpenGL(temp::UInt32 programHandle,
temp::UInt32 vertexShaderHandle,
temp::UInt32 pixelShaderHandle)
: programHandle_(programHandle),
vertexShaderHandle_(vertexShaderHandle),
pixelShaderHandle_(pixelShaderHandle) {}
ShaderObjectOpenGL::~ShaderObjectOpenGL() {
glFunc(glDeleteShader, vertexShaderHandle_);
glFunc(glDeleteShader, pixelShaderHandle_);
glFunc(glDeleteProgram, programHandle_);
}
}
}
}
#endif
<file_sep>/**
* @file DeviceOpenGL.h
* @brief OpenGL版デバイス
* @author tsukushibito
* @version 0.0.1
* @date 2015-03-22
*/
#pragma once
#ifndef GUARD_114c1a879a474c668e28000e8b3a4d42
#define GUARD_114c1a879a474c668e28000e8b3a4d42
#include "../../TempuraCommon.h"
#include "../Define.h"
#include "../Device.h"
namespace temp {
namespace graphics {
namespace opengl {
class DeviceOpenGLBase : public temp::graphics::DeviceBase<DeviceOpenGLBase> {
public:
DeviceOpenGLBase() {}
virtual ~DeviceOpenGLBase() {}
ContextPtr getContext() const;
/**
* @brief ビューを取得
*
* @return ビュー
*/
ViewPtr getView() const;
/**
* @brief レンダーターゲットを作成
*
* @param desc 設定記述
*
* @return レンダーターゲット
*/
RenderTargetPtr createRenderTarget(const RenderTargetDesc &desc);
/**
* @brief 深度ステンシルバッファを作成
*
* @param desc 設定記述
*
* @return 深度ステンシルバッファ
*/
DepthStencilPtr createDepthStencil(const DepthStencilDesc &desc);
/**
* @brief インデックスバッファを作成
*
* @param desc 設定記述
* @param pData 初期データ
*
* @return インデックスバッファ
*/
IndexBufferPtr createIndexBuffer(const IndexBufferDesc &desc,
const void *pData);
/**
* @brief 頂点バッファを作成
*
* @param desc 設定記述
* @param pData 初期データ
*
* @return 頂点バッファ
*/
VertexBufferPtr createVertexBuffer(const VertexBufferDesc &desc,
const void *pData);
/**
* @brief シェーダオブジェクトをバイナリコードから作成
*
* @param pVertexShaderSourceCode 頂点シェーダのバイナリコード
* @param vertexShaderSourceCodeSize 頂点シェーダのバイナリコードサイズ
* @param pPixelShaderSourceCode ピクセルシェーダのバイナリコード
* @param pixelShaderSourceCodeSize ピクセルシェーダのバイナリコードサイズ
*
* @return
*/
ShaderObjectPtr createShaderObjectFromBinary(
const void *pVertexShaderBinaryCode, Size vertexShaderBinaryCodeSize,
const void *pPixelShaderBinaryCode, Size pixelShaderBinaryCodeSize);
/**
* @brief シェーダオブジェクトをソースコードから作成
*
* @param pVertexShaderSourceCode 頂点シェーダのソースコード
* @param vertexShaderSourceCodeSize 頂点シェーダのソースコードサイズ
* @param pPixelShaderSourceCode ピクセルシェーダのソースコード
* @param pixelShaderSourceCodeSize ピクセルシェーダのソースコードサイズ
*
* @return
*/
ShaderObjectPtr createShaderObjectFromSource(
const void *pVertexShaderSourceCode, Size vertexShaderSourceCodeSize,
const void *pPixelShaderSourceCode, Size pixelShaderSourceCodeSize);
/**
* @brief 入力レイアウトを作成
*
* @param descs 入力要素定義の配列へのポインタ
* @param elementCount 要素数
* @param spShaderObject 対応するシェーダオブジェクト
*
* @return
*/
InputLayoutPtr createInputLayout(const InputElementDesc *descs,
Size elementCount,
const ShaderObjectPtr &spShaderObject);
/**
* @brief ブレンドステートを作成
*
* @param desc 設定記述
*
* @return ブレンドステート
*/
BlendStatePtr createBlendState(const BlendDesc &desc);
/**
* @brief 深度ステンシルステートを作成
*
* @param desc 設定記述
*
* @return 深度ステンシルステート
*/
DepthStencilStatePtr createDepthStencilState(const DepthStencilStateDesc &desc);
/**
* @brief ラスタライザステートを作成
*
* @param desc 設定記述
*
* @return ラスタライザステート
*/
RasterizerStatePtr createRasterizerState(const RasterizerDesc &desc);
/**
* @brief サンプラステートを作成
*
* @param desc 設定記述
*
* @return サンプラステート
*/
SamplerStatePtr createSamplerState(const SamplerDesc &desc);
protected:
ContextPtr spContext_; /**< グラフィックスコンテキスト */
ViewPtr spView_; /**< 表示先ビュー */
};
}
}
}
#endif // GUARD_114c1a879a474c668e28000e8b3a4d42
<file_sep>#include "TlsfAllocator.h"
#include <iostream>
#include <algorithm>
namespace temp {
namespace allocator {
using namespace temp;
temp::Bool TlsfAllocator::Chunk::canSplit(UInt size) const {
return (thisChunkSize_ >= size + sizeof(Chunk));
}
TlsfAllocator::Chunk *TlsfAllocator::Chunk::split(UInt size) {
Chunk *pRemainChunk = reinterpret_cast<Chunk *>(
(UInt8*)getManagedMemory() + size);
pRemainChunk->thisChunkSize_ = thisChunkSize_ - (size + getHeaderSize());
pRemainChunk->prevChunkSize_ = size;
pRemainChunk->useFlag_.flag_ = false;
thisChunkSize_ = size;
return pRemainChunk;
}
TlsfAllocator::TlsfAllocator(void *memoryPool, UInt poolSize) {
TEMP_ASSERT(memoryPool != nullptr, "memoryPool is nullptr");
TEMP_ASSERT(poolSize >= 2 * sizeof(Chunk), "poolSize is too small.");
// フリーリストビットの初期化
freeChunkFliBits_ = 0;
for (UInt i = 0; i < FL_INDEX_COUNT; ++i) {
freeChunkSliBits_[i] = 0;
}
// フリーチャンクリストの初期化
// ダミーチャンクを設定しておく
for (UInt i = 0; i < FL_INDEX_COUNT; ++i) {
for (UInt j = 0; j < SL_INDEX_COUNT; ++j) {
freeChunkMatrix_[i][j] = &dummyFreeChunk_;
}
}
dummyFreeChunk_.freeListLink_.pPrevFreeChunk_ = &dummyFreeChunk_;
dummyFreeChunk_.freeListLink_.pNextFreeChunk_ = &dummyFreeChunk_;
/**< メモリプールの先頭に常にあるチャンク */
pDummyTopChunk_ = static_cast<Chunk *>(memoryPool);
pDummyTopChunk_->thisChunkSize_ = sizeof(FreeListLink);
pDummyTopChunk_->prevChunkSize_ = 0;
pDummyTopChunk_->useFlag_.flag_ = true;
pDummyTopChunk_->freeListLink_.pPrevFreeChunk_ =
pDummyTopChunk_->freeListLink_.pNextFreeChunk_ = nullptr;
// まだ末尾のアドレスを設定していないので-1としておく
pDummyBottomChunk_ = (Chunk *)(-1);
// メインで使用するチャンク
Chunk *pMainChunk = getNextChunk(pDummyTopChunk_);
/**< チャンクヘッダと先頭と末尾のチャンク分マイナスする */
UInt chunkSize = alignDown(poolSize - Chunk::getHeaderSize() - 2 * sizeof(Chunk), ALIGN_SIZE);
pMainChunk->thisChunkSize_ = adjustRequestSize(chunkSize);
pMainChunk->prevChunkSize_ = pDummyTopChunk_->thisChunkSize_;
pMainChunk->useFlag_.flag_ = false;
// メモリプールの末尾に常にあるチャンク
pDummyBottomChunk_ = getNextChunk(pMainChunk);
pDummyBottomChunk_->thisChunkSize_ = 0;
pDummyBottomChunk_->prevChunkSize_ = pMainChunk->thisChunkSize_;
pDummyBottomChunk_->useFlag_.flag_ = true;
pDummyBottomChunk_->freeListLink_.pPrevFreeChunk_ =
pDummyTopChunk_->freeListLink_.pNextFreeChunk_ = nullptr;
// メインチャンクをフリーチャンクとして追加
FliAndSli fliAndSli = evaluateFliAndSli(pMainChunk->thisChunkSize_);
insertFreeChunk(pMainChunk, fliAndSli);
Chunk *pBottom = getNextChunk(pMainChunk);
Chunk *pTop = getPrevChunk(pMainChunk);
}
void *TlsfAllocator::malloc(UInt size) {
size = adjustRequestSize(size);
if (size == 0)
return nullptr;
FliAndSli fliAndSli = evaluateFliAndSli(size);
Chunk *pFreeChunk = findFreeChunk(fliAndSli);
removeChunkFromFreeList(pFreeChunk);
return prepareUseChunk(pFreeChunk, size);
}
void TlsfAllocator::free(void *pointer) {
if (pointer == nullptr)
return;
Chunk *pChunk = getChunkFromDataPointer(pointer);
TEMP_ASSERT(pChunk->useFlag_.flag_ == true, "chunk already marked as free");
pChunk = margeWithPrevChunk(pChunk);
pChunk = margeWithNextChunk(pChunk);
FliAndSli fliAndSli = evaluateFliAndSli(pChunk->thisChunkSize_);
insertFreeChunk(pChunk, fliAndSli);
}
void TlsfAllocator::defragment(UInt step) {}
void *TlsfAllocator::alignPointer(void *pointer, UInt align) {
const ptrdiff_t alignedPtr =
(reinterpret_cast<ptrdiff_t>(pointer) + (align - 1)) & ~(align - 1);
TEMP_ASSERT(0 == (align & (align - 1)), "must align to a power of two");
return reinterpret_cast<void *>(alignedPtr);
}
UInt TlsfAllocator::evaluateMsb(UInt value) {
UInt bit = 8 * sizeof(UInt);
if (!value) {
value <<= 0;
bit -= 1;
}
#ifdef TEMP_ALLOCATOR_64BIT
if (!(value & 0xffffffff00000000)) {
value <<= 32;
bit -= 32;
}
if (!(value & 0xffff000000000000)) {
value <<= 16;
bit -= 16;
}
if (!(value & 0xff00000000000000)) {
value <<= 8;
bit -= 8;
}
if (!(value & 0xf000000000000000)) {
value <<= 4;
bit -= 4;
}
if (!(value & 0xc000000000000000)) {
value <<= 2;
bit -= 2;
}
if (!(value & 0x8000000000000000)) {
value <<= 1;
bit -= 1;
}
#else
if (!(value & 0xffff0000)) {
value <<= 16;
bit -= 16;
}
if (!(value & 0xff000000)) {
value <<= 8;
bit -= 8;
}
if (!(value & 0xf0000000)) {
value <<= 4;
bit -= 4;
}
if (!(value & 0xc0000000)) {
value <<= 2;
bit -= 2;
}
if (!(value & 0x80000000)) {
value <<= 1;
bit -= 1;
}
#endif
return bit;
}
UInt TlsfAllocator::evaluateLsb(UInt value) {
return evaluateMsb(value & (~value + 1)) - 1;
}
TlsfAllocator::FliAndSli TlsfAllocator::evaluateFliAndSli(UInt size) {
FliAndSli fliAndSli;
if (size <= SMALL_CHUNK_SIZE) {
fliAndSli.fli_ = 0;
fliAndSli.sli_ = size / (SMALL_CHUNK_SIZE / SL_INDEX_COUNT);
} else {
fliAndSli.fli_ = evaluateMsb(size) - 1;
Int fli = fliAndSli.fli_;
if (fli < 0) {
fliAndSli.sli_ = -1;
return fliAndSli;
}
UInt mask = (1 << fli) - 1;
UInt rightShift = static_cast<UInt>(fli - SL_INDEX_COUNT_LOG2);
fliAndSli.sli_ = (size & mask) >> rightShift;
fliAndSli.fli_ -= (FL_INDEX_SHIFT - 1);
}
return fliAndSli;
}
void TlsfAllocator::insertFreeChunk(Chunk *pFreeChunk,
const FliAndSli &fliAndSli) {
// 指定のインデックスのフリーチャンクリストにブロックを追加する
Chunk *pTopFreeChunk = freeChunkMatrix_[fliAndSli.fli_][fliAndSli.sli_];
TEMP_ASSERT(pTopFreeChunk, "free list cannot have a null entry");
TEMP_ASSERT(pFreeChunk, "cannot insert a null entry into the free list");
pFreeChunk->freeListLink_.pNextFreeChunk_ = pTopFreeChunk;
pFreeChunk->freeListLink_.pPrevFreeChunk_ = &dummyFreeChunk_;
pTopFreeChunk->freeListLink_.pPrevFreeChunk_ = pFreeChunk;
TEMP_ASSERT(pFreeChunk->getManagedMemory() ==
alignPointer(pFreeChunk->getManagedMemory(), ALIGN_SIZE),
"block not aligned properly");
// フリーリストビットを立てる
freeChunkMatrix_[fliAndSli.fli_][fliAndSli.sli_] = pFreeChunk;
#ifdef TEMP_PLATFORM_WINDOWS
freeChunkFliBits_ |= (1i64 << fliAndSli.fli_);
freeChunkSliBits_[fliAndSli.fli_] |= (1i64 << fliAndSli.sli_);
#else
freeChunkFliBits_ |= (1 << fliAndSli.fli_);
freeChunkSliBits_[fliAndSli.fli_] |= (1 << fliAndSli.sli_);
#endif
}
TlsfAllocator::Chunk *TlsfAllocator::findFreeChunk(FliAndSli &fliAndSli) {
Int &fli = fliAndSli.fli_;
Int &sli = fliAndSli.sli_;
UInt sliBitMap = freeChunkSliBits_[fli] & (~0 << sli);
if (!sliBitMap) {
// 同FLIの上位SLIにフリーチャンクがないので、
// 上位FLIのフリーリストを探す
const UInt fliBitMap = freeChunkFliBits_ & (~0 << (fli + 1));
if (!fliBitMap) {
// フリーチャンクが存在しない
return nullptr;
}
fli = evaluateLsb(fliBitMap);
sliBitMap = freeChunkSliBits_[fli];
}
TEMP_ASSERT(sliBitMap, "internal error - second level bitmap is null");
sli = evaluateLsb(sliBitMap);
// フリーチャンクを返す
return freeChunkMatrix_[fli][sli];
}
void TlsfAllocator::removeChunkFromFreeList(Chunk *pFreeChunk) {
if (pFreeChunk == nullptr || pFreeChunk->useFlag_.flag_ == true)
return;
FliAndSli fliAndSli = evaluateFliAndSli(pFreeChunk->thisChunkSize_);
Chunk *pPrevChunk = pFreeChunk->freeListLink_.pPrevFreeChunk_;
Chunk *pNextChunk = pFreeChunk->freeListLink_.pNextFreeChunk_;
TEMP_ASSERT(pPrevChunk, "prev_free field can not be null");
TEMP_ASSERT(pNextChunk, "next_free field can not be null");
pNextChunk->freeListLink_.pPrevFreeChunk_ = pPrevChunk;
pPrevChunk->freeListLink_.pNextFreeChunk_ = pNextChunk;
/* If this block is the head of the free list, set new head. */
if (freeChunkMatrix_[fliAndSli.fli_][fliAndSli.sli_] == pFreeChunk) {
freeChunkMatrix_[fliAndSli.fli_][fliAndSli.sli_] = pNextChunk;
/* If the new head is null, clear the bitmap. */
if (pNextChunk == &dummyFreeChunk_) {
freeChunkSliBits_[fliAndSli.fli_] &= ~(1 << fliAndSli.sli_);
/* If the second bitmap is now empty, clear the fl bitmap. */
if (!freeChunkSliBits_[fliAndSli.fli_]) {
freeChunkFliBits_ &= ~(1 << fliAndSli.fli_);
}
}
}
}
void *TlsfAllocator::prepareUseChunk(Chunk *pFreeChunk, UInt size) {
void *pointer = nullptr;
if (!pFreeChunk)
return pointer;
if (!pFreeChunk->canSplit(size))
return pointer;
Chunk *pRemainChunk = pFreeChunk->split(size);
insertFreeChunk(pRemainChunk,
evaluateFliAndSli(pRemainChunk->thisChunkSize_));
pFreeChunk->useFlag_.flag_ = true;
pointer = pFreeChunk->getManagedMemory();
return pointer;
}
UInt TlsfAllocator::adjustRequestSize(UInt size) {
UInt adjustSize = 0;
if (size && size < CHUNK_SIZE_MAX) {
const UInt aligned = alignUp(size, ALIGN_SIZE);
adjustSize = std::max(aligned, static_cast<UInt>(CHUNK_SIZE_MIN));
}
return adjustSize;
}
TlsfAllocator::Chunk *
TlsfAllocator::getPrevChunk(TlsfAllocator::Chunk *pChunk) const {
TEMP_ASSERT(pChunk, "pChunk is nulptr");
Chunk *pPrevChunk = (Chunk *)((UInt8 *)pChunk - pChunk->prevChunkSize_ -
Chunk::getHeaderSize());
if (pPrevChunk < pDummyTopChunk_)
return nullptr;
return pPrevChunk;
}
TlsfAllocator::Chunk *
TlsfAllocator::getNextChunk(TlsfAllocator::Chunk *pChunk) const {
TEMP_ASSERT(pChunk, "pChunk is nulptr");
Chunk *pNextChunk =
(Chunk *)((UInt8 *)pChunk + Chunk::getHeaderSize() +
pChunk->thisChunkSize_);
if (pNextChunk > pDummyBottomChunk_)
return nullptr;
return pNextChunk;
}
TlsfAllocator::Chunk *
TlsfAllocator::getChunkFromDataPointer(void *pointer) const {
if (!pointer)
return nullptr;
Chunk *pChunk =
(Chunk *)((UInt8 *)pointer - sizeof(Chunk) + sizeof(FreeListLink));
TEMP_ASSERT(pDummyTopChunk_ < pChunk && pChunk < pDummyBottomChunk_,
"Invalid pointer.");
return pChunk;
}
TlsfAllocator::Chunk *TlsfAllocator::margeWithPrevChunk(Chunk *pChunk) {
Chunk *pPrevChunk = getPrevChunk(pChunk);
if (pPrevChunk->useFlag_.flag_)
return pChunk;
removeChunkFromFreeList(pPrevChunk);
Chunk *pMargedChunk = margeAdjacentChunk(pPrevChunk, pChunk);
return pMargedChunk;
}
TlsfAllocator::Chunk *TlsfAllocator::margeWithNextChunk(Chunk *pChunk) {
Chunk *pNextChunk = getNextChunk(pChunk);
if (pNextChunk->useFlag_.flag_)
return pChunk;
removeChunkFromFreeList(pNextChunk);
Chunk *pMargedChunk = margeAdjacentChunk(pChunk, pNextChunk);
return pMargedChunk;
}
TlsfAllocator::Chunk *TlsfAllocator::margeAdjacentChunk(Chunk *pLeftChunk,
Chunk *pRightChunk) {
pLeftChunk->thisChunkSize_ +=
pRightChunk->thisChunkSize_ + Chunk::getHeaderSize();
Chunk *pNextChunk = getNextChunk(pLeftChunk);
pNextChunk->prevChunkSize_ = pLeftChunk->thisChunkSize_;
return pLeftChunk;
}
}
}
<file_sep>/**
* @file ThreadPool.h
* @brief スレッドプール
* @author tsukushibito
* @version 0.1.1
* @date 2014-10-27
*/
#pragma once
#ifndef GUARD_45b24cf7bd344c0aadb1e393915359dd
#define GUARD_45b24cf7bd344c0aadb1e393915359dd
#include <thread>
#include <mutex>
#include <condition_variable>
#include "../TempuraCommon.h"
#include "../Container.h"
namespace temp {
namespace system {
typedef std::function<void(void)> JobFunction;
/**
* @brief ジョブクラス
*/
class Job : public temp::ReferenceObject {
public:
enum State {
WAITING,
EXECUTING,
DONE,
};
explicit Job(const JobFunction &func, temp::Int32 priority = 0)
: func_(func), priority_(priority), state_(WAITING) {}
State getState() const { return state_; }
temp::Int32 getPriority() const { return priority_; }
void execute() {
state_ = EXECUTING;
func_();
state_ = DONE;
}
void operator()() { execute(); }
temp::Bool operator<(const Job &rhs) const {
return priority_ < rhs.priority_;
}
private:
JobFunction func_;
temp::UInt32 priority_;
volatile State state_;
};
typedef temp::RefObjPtr<Job> JobPtr;
class ThreadPool : temp::Uncopyable {
public:
explicit ThreadPool(temp::UInt32 threadCount);
~ThreadPool();
void pushJob(const JobPtr &spJob);
JobPtr popJob();
Size getJobCount() const {
using namespace std;
lock_guard<mutex> lock(mutex_);
return jobQueue_.size();
}
private:
class WorkerThread : public ReferenceObject {
public:
enum State {
RUNNING,
SUSPENDING,
TERMINATING,
TERMINATED,
STATE_MAX,
};
WorkerThread(ThreadPool &threadPool);
void run();
void suspend();
void resume();
void terminate();
State getState() const { return state_; }
private:
ThreadPool &threadPool_;
std::thread thread_;
std::mutex mutex_;
std::condition_variable condition_;
State state_;
};
class Compare {
public:
Bool operator()(const JobPtr &lhs, const JobPtr &rhs) {
return lhs->getPriority() < rhs->getPriority();
}
};
typedef temp::RefObjPtr<WorkerThread> WorkerThreadPtr;
typedef Vector<WorkerThreadPtr> WorkerThreadVector;
typedef Vector<JobPtr> JobVector;
typedef std::priority_queue<JobPtr, JobVector, Compare> JobQueue;
mutable std::mutex mutex_;
WorkerThreadVector threads_;
JobQueue jobQueue_;
};
}
}
#endif // GUARD_45b24cf7bd344c0aadb1e393915359dd
<file_sep>/**
* @file System.h
* @brief システム関連まとめてインクルード
* @author tsukushibito
* @version 0.0.1
* @date 2014-10-28
*/
#pragma once
#ifndef GUARD_c89e5ac73a7848058a7d6d0f93e07d13
#define GUARD_c89e5ac73a7848058a7d6d0f93e07d13
#include "ThreadPool.h"
#include "Timer.h"
#include "Window.h"
#include "Application.h"
#endif // GUARD_c89e5ac73a7848058a7d6d0f93e07d13
<file_sep>#include "../../TempuraCommon.h"
#ifdef TEMP_GRAPHICS_OPENGL
#include "OpenGLCommon.h"
#include "ContextOpenGL.h"
#include "ShaderObjectOpenGL.h"
#include "InputLayoutOpenGL.h"
#include "ConstantBufferOpenGL.h"
namespace temp {
namespace graphics {
namespace opengl {
ContextOpenGL::ContextOpenGL() {
}
void ContextOpenGL::clearRenderTarget(const RenderTargetPtr &spRenderTarget,
const temp::Color &clearColor) {
glFunc(glClearColor, clearColor.r_, clearColor.g_, clearColor.b_, clearColor.a_);
glFunc(glClear, GL_COLOR_BUFFER_BIT);
}
void ContextOpenGL::clearDepthStencil(const DepthStencilPtr &spDepthStencil,
CLEAR_FLAG flags, Float32 depth,
UInt8 stencil) {
glFunc(glClearDepth, depth);
glFunc(glClearStencil, stencil);
if ((UInt32)flags & (UInt32)CLEAR_FLAG::DEPTH)
glFunc(glClear, GL_DEPTH_BUFFER_BIT);
if ((UInt32)flags & (UInt32)CLEAR_FLAG::STENCIL)
glFunc(glClear, GL_STENCIL_BUFFER_BIT);
}
void ContextOpenGL::setShaderObject(const ShaderObjectPtr &spShaderObject)
{
glFunc(glUseProgram, spShaderObject->getProgramHandle());
}
void ContextOpenGL::setInputLayout(const InputLayoutPtr &spInputLayout) {
spInputLayout_ = spInputLayout;
}
void ContextOpenGL::updateConstantBuffer(const ConstantBufferPtr &spConstantBuffer, void *pData, Size dataSize)
{
GLuint uniformBuffer = spConstantBuffer->getNativeHandle();
glFunc(glBindBuffer, GL_UNIFORM_BUFFER, uniformBuffer);
glFunc(glBufferData, GL_UNIFORM_BUFFER, dataSize, pData, GL_DYNAMIC_DRAW);
}
}
}
}
#endif
<file_sep>/**
* @file ViewOpenGLBase.h
* @brief OpenGL版ビュー
* @author tsukushibito
* @version 0.0.1
* @date 2015-03-22
*/
#pragma once
#ifndef GUARD_34304f6406444eeba1b3989a19fb39cf
#define GUARD_34304f6406444eeba1b3989a19fb39cf
#include "../View.h"
#include "../Define.h"
namespace temp {
namespace graphics {
namespace opengl {
class ViewOpenGLBase : public ViewBase<ViewOpenGLBase> {
protected:
ViewOpenGLBase() {}
public:
virtual ~ViewOpenGLBase() {}
virtual void present() = 0;
};
}
}
}
#endif // GUARD_34304f6406444eeba1b3989a19fb39cf
<file_sep>/**
* @file BackBuffer.h
* @brief バックバッファ
* @author tsukushibito
* @version 0.0.1
* @date 2015-03-03
*/
#pragma once
#ifndef GUARD_84b07599ed9746b990e856ebd6be673b
#define GUARD_84b07599ed9746b990e856ebd6be673b
#include "GraphicsCommon.h"
namespace temp {
namespace graphics {
template <class T>
class BackBufferBase : temp::Castable<T>, public temp::ReferenceObject {
public:
explicit BackBufferBase(const Texture2DDesc &desc) : desc_(desc) {}
Texture2DDesc getDesc() const { return desc_; }
private:
Texture2DDesc desc_;
};
}
}
#endif // GUARD_84b07599ed9746b990e856ebd6be673b
<file_sep>/**
* @file PoolAllocator.h
* @brief プールアロケータ
* @author tsukushibito
* @version 0.0.1
* @date 2015-02-11
*/
#pragma once
#ifndef GUARD_cf6d3445224544729b1378d835a0971c
#define GUARD_cf6d3445224544729b1378d835a0971c
namespace temp {
namespace allocator {
class PoolAllocator : public temp::ReferenceObject {
struct Chunk {
UInt size_;
Chunk *pNextFreeChunk_;
Chunk() : size_(0), pNextFreeChunk_(nullptr) {}
};
public:
};
}
}
#endif // GUARD_cf6d3445224544729b1378d835a0971c
<file_sep>/**
* @file Graphics.h
* @brief グラフィックス関連ヘッダー
* @author tsukushibito
* @version 0.0.1
* @date 2015-02-17
*/
#pragma once
#ifndef GUARD_909b84c053ff4d9a9e150acb96f366e1
#define GUARD_909b84c053ff4d9a9e150acb96f366e1
#include "GraphicsCommon.h"
#include "Define.h"
#ifdef TEMP_GRAPHICS_OPENGL
#if defined TEMP_PLATFORM_WINDOWS
#include "OpenGL/Windows/DeviceOpenGLWindows.h"
#include "OpenGL/Windows/ViewOpenGLWindows.h"
#elif defined TEMP_PLATFORM_MAC
#include "OpenGL/Mac/DeviceOpenGLMac.h"
#include "OpenGL/Mac/ViewOpenGLMac.h"
#endif
#include "OpenGL/ContextOpenGL.h"
#include "OpenGL/RenderTargetOpenGL.h"
#include "OpenGL/DepthStencilOpenGL.h"
#include "OpenGL/IndexBufferOpenGL.h"
#include "OpenGL/VertexBufferOpenGL.h"
#include "OpenGL/ShaderObjectOpenGL.h"
#include "OpenGL/InputLayoutOpenGL.h"
#include "OpenGL/BlendStateOpenGL.h"
#include "OpenGL/DepthStencilStateOpenGL.h"
#include "OpenGL/RasterizerStateOpenGL.h"
#include "OpenGL/SamplerStateOpenGL.h"
#endif
#endif // GUARD_909b84c053ff4d9a9e150acb96f366e1
<file_sep>#include "../../TempuraCommon.h"
#include "../../system/Window.h"
#ifdef TEMP_GRAPHICS_OPENGL
#include "OpenGLCommon.h"
#include "DeviceOpenGLBase.h"
#include "ContextOpenGL.h"
#include "RenderTargetOpenGL.h"
#include "DepthStencilOpenGL.h"
#include "IndexBufferOpenGL.h"
#include "VertexBufferOpenGL.h"
#include "ShaderObjectOpenGL.h"
#include "InputLayoutOpenGL.h"
#include "BlendStateOpenGL.h"
#include "DepthStencilStateOpenGL.h"
#include "RasterizerStateOpenGL.h"
#include "SamplerStateOpenGL.h"
#ifdef TEMP_PLATFORM_WINDOWS
#include "Windows/ViewOpenGLWindows.h"
#else
#include "Mac/ViewOpenGLMac.h"
#endif
namespace temp {
namespace graphics {
namespace opengl {
ContextPtr DeviceOpenGLBase::getContext() const {
return spContext_;
}
ViewPtr DeviceOpenGLBase::getView() const {
return spView_;
}
RenderTargetPtr DeviceOpenGLBase::createRenderTarget(
const RenderTargetDesc &desc) {
TEMP_ASSERT(
0 <= desc.format_ && desc.format_ < RENDER_TARGET_FORMAT::UNKNOWN,
"invalid format.");
GLuint handle = 0;
glFunc(glGenTextures, 1, &handle);
glFunc(glBindTexture, GL_TEXTURE_2D, handle);
Int32 type = 0;
switch (desc.format_) {
case RENDER_TARGET_FORMAT::R8G8B8A8:
type = GL_UNSIGNED_BYTE;
break;
case RENDER_TARGET_FORMAT::R16G16B16A16F:
type = GL_FLOAT;
break;
default:
type = GL_UNSIGNED_BYTE;
break;
}
glFunc(glTexImage2D, GL_TEXTURE_2D, 0, GL_RGBA, desc.width_, desc.height_,
0, GL_RGBA, type, nullptr);
glFunc(glBindTexture, GL_TEXTURE_2D, 0);
return RenderTargetPtr(new RenderTarget(handle, desc));
}
DepthStencilPtr DeviceOpenGLBase::createDepthStencil(
const DepthStencilDesc &desc) {
TEMP_ASSERT(0 <= desc.format_ && desc.format_ < DSF_UNKNOWN,
"invalid format.");
GLuint handle = 0;
glFunc(glGenRenderbuffers, 1, &handle);
glFunc(glBindRenderbuffer, GL_RENDERBUFFER, handle);
Int32 type = 0;
Int32 format = 0;
switch (desc.format_) {
case DEPTH_STENCIL_FORMAT::D16:
format = GL_DEPTH_COMPONENT;
type = GL_HALF_FLOAT;
// format = GL_DEPTH_COMPONENT;
// type = GL_HALF_FLOAT;
break;
case DEPTH_STENCIL_FORMAT::D24_S8:
format = GL_DEPTH_STENCIL;
type = GL_UNSIGNED_INT_24_8;
break;
case DEPTH_STENCIL_FORMAT::D32F:
format = GL_DEPTH_COMPONENT;
type = GL_FLOAT;
break;
case DEPTH_STENCIL_FORMAT::D32F_S8X24:
format = GL_DEPTH_STENCIL;
type = GL_FLOAT_32_UNSIGNED_INT_24_8_REV;
break;
case DEPTH_STENCIL_FORMAT::S8:
format = GL_STENCIL_INDEX8;
type = GL_UNSIGNED_BYTE;
break;
default:
break;
}
glFunc(glTexImage2D, GL_TEXTURE_2D, 0, format, desc.width_, desc.height_, 0,
format, type, nullptr);
glFunc(glBindTexture, GL_TEXTURE_2D, 0);
return DepthStencilPtr(new DepthStencil(0, desc));
}
IndexBufferPtr DeviceOpenGLBase::createIndexBuffer(const IndexBufferDesc &desc,
const void *pData) {
GLuint handle = 0;
glFunc(glGenBuffers, 1, &handle);
glFunc(glBindBuffer, GL_ELEMENT_ARRAY_BUFFER, handle);
glFunc(glBufferData, GL_ELEMENT_ARRAY_BUFFER, desc.size_, pData,
GL_STATIC_DRAW);
glFunc(glBindBuffer, GL_ELEMENT_ARRAY_BUFFER, 0);
return IndexBufferPtr(new IndexBuffer(handle, desc));
}
VertexBufferPtr DeviceOpenGLBase::createVertexBuffer(const VertexBufferDesc &desc,
const void *pData) {
GLuint handle = 0;
glFunc(glGenBuffers, 1, &handle);
glFunc(glBindBuffer, GL_ARRAY_BUFFER, handle);
glFunc(glBufferData, GL_ARRAY_BUFFER, desc.size_, pData, GL_STATIC_DRAW);
glFunc(glBindBuffer, GL_ARRAY_BUFFER, 0);
return VertexBufferPtr(new VertexBuffer(0, desc));
}
ShaderObjectPtr DeviceOpenGLBase::createShaderObjectFromBinary(
const void *pVertexShaderBinaryCode, Size vertexShaderBinaryCodeSize,
const void *pPixelShaderBinaryCode, Size pixelShaderBinaryCodeSize) {
// プログラムオブジェクト作成
GLuint programHandle = glCreateProgram();
checkError();
// 頂点シェーダオブジェクト作成
GLuint vertexShaderHandle = glCreateShader(GL_VERTEX_SHADER);
checkError();
glFunc(glShaderBinary, 1, &vertexShaderHandle, (GLenum)0, pVertexShaderBinaryCode,
(GLsizei)vertexShaderBinaryCodeSize);
// ピクセルシェーダオブジェクト作成
GLuint pixelShaderHandle = glCreateShader(GL_FRAGMENT_SHADER);
checkError();
glFunc(glShaderBinary, 1, &vertexShaderHandle, (GLenum)0, pPixelShaderBinaryCode,
(GLsizei)pixelShaderBinaryCodeSize);
// プログラムにアタッチ
glFunc(glAttachShader, programHandle, vertexShaderHandle);
glFunc(glAttachShader, programHandle, pixelShaderHandle);
// リンク
glFunc(glLinkProgram, programHandle);
return ShaderObjectPtr(new ShaderObject(programHandle, vertexShaderHandle, pixelShaderHandle));
}
ShaderObjectPtr DeviceOpenGLBase::createShaderObjectFromSource(
const void *pVertexShaderSourceCode, Size vertexShaderSourceCodeSize,
const void *pPixelShaderSourceCode, Size pixelShaderSourceCodeSize) {
// プログラムオブジェクト作成
GLuint programHandle = glCreateProgram();
checkError();
// 頂点シェーダオブジェクト作成
GLuint vertexShaderHandle = glCreateShader(GL_VERTEX_SHADER);
checkError();
const GLchar *vertexShaderString = static_cast<const GLchar *>(pVertexShaderSourceCode);
const GLint vertexShaderLength = static_cast<const GLint>(vertexShaderSourceCodeSize);
glFunc(glShaderSource, vertexShaderHandle, 1, &vertexShaderString, &vertexShaderLength);
glFunc(glCompileShader, vertexShaderHandle);
printShaderCompileInfoLog(vertexShaderHandle);
// ピクセルシェーダオブジェクト作成
GLuint pixelShaderHandle = glCreateShader(GL_FRAGMENT_SHADER);
checkError();
const GLchar *pixelShaderString = static_cast<const GLchar *>(pPixelShaderSourceCode);
const GLint pixelShaderLength = static_cast<const GLint>(pixelShaderSourceCodeSize);
glFunc(glShaderSource, pixelShaderHandle, 1, &pixelShaderString, &pixelShaderLength);
glFunc(glCompileShader, pixelShaderHandle);
printShaderCompileInfoLog(pixelShaderHandle);
// プログラムにアタッチ
glFunc(glAttachShader, programHandle, vertexShaderHandle);
glFunc(glAttachShader, programHandle, pixelShaderHandle);
// リンク
glFunc(glLinkProgram, programHandle);
return ShaderObjectPtr(new ShaderObject(programHandle, vertexShaderHandle, pixelShaderHandle));
}
InputLayoutPtr DeviceOpenGLBase::createInputLayout(
const InputElementDesc *descs, Size elementCount,
const ShaderObjectPtr &spShaderObject) {
return InputLayoutPtr(new InputLayout(descs, elementCount, spShaderObject));
}
BlendStatePtr DeviceOpenGLBase::createBlendState(const BlendDesc &desc) {
return BlendStatePtr(new BlendState(desc));
}
DepthStencilStatePtr DeviceOpenGLBase::createDepthStencilState(
const DepthStencilStateDesc &desc) {
return DepthStencilStatePtr(new DepthStencilState(desc));
}
RasterizerStatePtr DeviceOpenGLBase::createRasterizerState(
const RasterizerDesc &desc) {
return RasterizerStatePtr(new RasterizerState(desc));
}
SamplerStatePtr DeviceOpenGLBase::createSamplerState(const SamplerDesc &desc) {
return SamplerStatePtr(new SamplerState(desc));
}
}
}
}
#endif
<file_sep>/**
* @file View.h
* @brief ビュークラス
* @author tsukushibito
* @version 0.0.1
* @date 2015-02-22
*/
#pragma once
#ifndef GUARD_6bdff898517e430995e87dc1cc4bb518
#define GUARD_6bdff898517e430995e87dc1cc4bb518
#include "GraphicsCommon.h"
#include "Define.h"
namespace temp {
namespace system {
class Window;
}
namespace graphics {
template <class T>
class ViewBase : temp::Castable<T>, public temp::ReferenceObject {
public:
void present() { temp::Castable<T>::derive()->present(); }
protected:
BackBuffer *pBackBuffer_;
};
}
}
#endif // GUARD_6bdff898517e430995e87dc1cc4bb518
<file_sep>/**
* @file ConstantBuffer.h
* @brief コンスタントバッファ
* @author tsukushibito
* @version 0.0.1
* @date 2015-09-18
*/
#pragma once
#ifndef GUARD_9efe6c048f6848a49c28d5afd816af6d
#define GUARD_9efe6c048f6848a49c28d5afd816af6d
#include "GraphicsCommon.h"
namespace temp {
namespace graphics {
template <class T>
class ConstantBufferBase : temp::Castable<T>, public temp::ReferenceObject {
public:
explicit ConstantBufferBase(Size size) : size_(size) {}
Size getSize() const { return size_; }
private:
Size size_;
};
}
}
#endif // GUARD_9efe6c048f6848a49c28d5afd816af6d
<file_sep>/**
* @file Window.h
* @brief ウィンドウクラス
* @author tsukushibito
* @version 0.0.1
* @date 2014-10-31
*/
#pragma once
#ifndef GUARD_59923d4a05c54027931a4f27aa0a3322
#define GUARD_59923d4a05c54027931a4f27aa0a3322
#include "../TempuraCommon.h"
namespace temp {
namespace system {
union WindowHandle
{
void *pointer_;
Size value_;
};
union ViewHandle
{
void *pointer_;
Size value_;
};
class Window : temp::Uncopyable {
public:
Window(Size width = 1280, Size height = 720);
~Window();
WindowHandle getWindowHandle() const;
ViewHandle getViewHandle() const;
private:
class Impl;
Impl *pImpl_;
};
}
}
#endif // GUARD_59923d4a05c54027931a4f27aa0a3322
<file_sep>/**
* @file BlendStateOpenGL.h
* @brief OpenGL版ブレンドステート
* @author tsukushibito
* @version 0.0.1
* @date 2015-04-01
*/
#pragma once
#ifndef GUARD_2aa218b511dd4a0da60cb742e1b3a580
#define GUARD_2aa218b511dd4a0da60cb742e1b3a580
#include "../BlendState.h"
#include "../Define.h"
namespace temp {
namespace graphics {
namespace opengl {
class BlendStateOpenGL
: public temp::graphics::BlendStateBase<BlendStateOpenGL> {
friend DeviceOpenGLBase;
typedef temp::graphics::BlendStateBase<BlendStateOpenGL> Super;
private:
BlendStateOpenGL(const BlendDesc &desc) : Super(desc) {}
};
}
}
}
#endif // GUARD_2aa218b511dd4a0da60cb742e1b3a580
<file_sep>/**
* @file IndexBufferOpenGL.h
* @brief OpenGL版インデックスバッファ
* @author tsukushibito
* @version 0.0.1
* @date 2015-03-22
*/
#pragma once
#ifndef GUARD_463b18ff90914f97b8b86f98b0ac7a5f
#define GUARD_463b18ff90914f97b8b86f98b0ac7a5f
#include "../IndexBuffer.h"
#include "../Define.h"
namespace temp {
namespace graphics {
namespace opengl {
class IndexBufferOpenGL
: public temp::graphics::IndexBufferBase<IndexBufferOpenGL> {
friend class DeviceOpenGLBase;
typedef temp::graphics::IndexBufferBase<IndexBufferOpenGL> Super;
private:
IndexBufferOpenGL(temp::UInt32 handle, const IndexBufferDesc &desc);
public:
temp::UInt32 getNativeHandle() const { return handle_; }
private:
temp::UInt32 handle_;
};
}
}
}
#endif // GUARD_463b18ff90914f97b8b86f98b0ac7a5f
<file_sep>#include "../../TempuraCommon.h"
#ifdef TEMP_GRAPHICS_OPENGL
#include "VertexBufferOpenGL.h"
namespace temp {
namespace graphics {
namespace opengl {
VertexBufferOpenGL::VertexBufferOpenGL(temp::UInt32 handle,
const VertexBufferDesc &desc)
: Super(desc), handle_(handle) {}
}
}
}
#endif
<file_sep>import os
import re
import sys
argvs = sys.argv
if os.name == "mac":
reg = re.compile("\.(h|cpp)$")
else:
reg = re.compile("\.(h|cpp|mm)$)
def fild_all_files(directory):
for root, dirs, files in os.walk(directory):
yield root
for file in files:
yield os.path.join(root, file)
for file in fild_all_files(argvs[1]):
if reg.search(file):
print file
<file_sep>#include "TempuraCommon.h"
#if defined TEMP_PLATFORM_WINDOWS
#include "DeviceOpenGLWindows.h"
#include "../OpenGLCommon.h"
#include "ViewOpenGLWindows.h"
#include "../../../system/Window.h"
#include "../ContextOpenGL.h"
#include "../../../System/Logger.h"
namespace temp {
namespace graphics {
namespace opengl {
namespace windows {
namespace {
// ダミーウィンドウ作成関数
HWND createDummyWindow()
{
const size_t MAX_STR_SIZE = 100;
HINSTANCE hInstance = GetModuleHandle(NULL);
CHAR windowClassName[MAX_STR_SIZE] = "Dummy";
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = DefWindowProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = NULL;
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = windowClassName;
wcex.hIconSm = NULL;
RegisterClassEx(&wcex);
return CreateWindow(windowClassName, "", WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
}
}
DeviceOpenGLWindows::DeviceOpenGLWindows(const system::ViewHandle &viewHandle) {
HDC hdc = (HDC)viewHandle.value_;
// glew初期化のためのダミーウィンドウ作成
HWND hDummyWindow = createDummyWindow();
HDC hTempDC = GetDC(hDummyWindow);
// 現在対応しているフォーマットの数を参照する
int format_count= DescribePixelFormat( hTempDC, 0, 0, NULL );
PIXELFORMATDESCRIPTOR pfd;
// 列挙する
// for( int i = 0; i < format_count; ++i)
// {
// DescribePixelFormat( hTempDC, i + 1, sizeof(PIXELFORMATDESCRIPTOR), &pfd );
// break;
// }
DescribePixelFormat( hTempDC, 1, sizeof(PIXELFORMATDESCRIPTOR), &pfd );
// ピクセルフォーマットの選択
int pfmt= ChoosePixelFormat( hTempDC, &pfd );
SetPixelFormat( hTempDC, pfmt, &pfd );
// OpenGL コンテキストの作成
HGLRC tempContext = wglCreateContext( hTempDC );
wglMakeCurrent( hTempDC, tempContext );
GLenum error = glGetError();
// glewの初期化
GLenum err = glewInit();
// 拡張機能によるコンテキストの作成
const FLOAT fAtribList[] = {0, 0};
// ピクセルフォーマット指定用
const int pixelFormatAttribList[] =
{
// WGL_CONTEXT_MAJOR_VERSION_ARB, 1,
// WGL_CONTEXT_MINOR_VERSION_ARB, 0,
WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
WGL_DOUBLE_BUFFER_ARB, GL_TRUE,
WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB,
WGL_COLOR_BITS_ARB, 32,
WGL_DEPTH_BITS_ARB, 24,
0, 0,
};
// コンテキスト作成用
int contextAttribList[] =
{
WGL_CONTEXT_MAJOR_VERSION_ARB, 4,
WGL_CONTEXT_MINOR_VERSION_ARB, 5,
0, 0, //End
};
int pixelFormat = 0;
UINT numFormats = 0;
// ピクセルフォーマット選択
BOOL isValid = wglChoosePixelFormatARB(
hdc,
pixelFormatAttribList,
fAtribList,
1,
&pixelFormat,
&numFormats
);
error = glGetError();
if (isValid == FALSE)
{
assert(false);
}
// ピクセルフォーマット設定
DescribePixelFormat( hdc, pixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &pfd );
SetPixelFormat(hdc, pixelFormat, &pfd);
// コンテキスト作成
context_ = wglCreateContextAttribsARB(hdc, NULL, contextAttribList);
while (context_ == NULL)
{
// 成功するまでバージョンを下げる
context_ = wglCreateContextAttribsARB(hdc, NULL, contextAttribList);
contextAttribList[3] -= 1;
if (contextAttribList[3] < 0)
{
contextAttribList[3] = 10;
contextAttribList[1] -= 1;
if (contextAttribList[1] < 0)
{
break;
}
}
}
wglMakeCurrent(hdc, context_);
error = glGetError();
const GLubyte *majorVersion = glGetString(GL_VERSION);
const GLubyte *glslVersion = glGetString(GL_SHADING_LANGUAGE_VERSION);
if (majorVersion == nullptr) majorVersion = (const GLubyte*)"Error";
if (glslVersion == nullptr) glslVersion = (const GLubyte*)"Error";
system::ConsoleLogger::trace("OpenGL version : {0}", majorVersion);
system::ConsoleLogger::trace("GLSL version : {0}", glslVersion);
wglDeleteContext(tempContext);
error = glGetError();
DestroyWindow(hDummyWindow);
err = glewInit();
if (err != GLEW_OK)
{
assert(false);
}
error = glGetError();
spView_ = ViewPtr(new ViewOpenGLWindows(hdc));
spContext_ = ContextPtr(new ContextOpenGL());
}
DeviceOpenGLWindows::~DeviceOpenGLWindows() {}
}
}
}
}
#endif
<file_sep>/**
* @file DepthStencilStateOpenGL.h
* @brief OpenGL版深度ステンシルステート
* @author tsukushibito
* @version 0.0.1
* @date 2015-04-01
*/
#pragma once
#ifndef GUARD_0a952b6e505d46fa8946ef27ece0c8e4
#define GUARD_0a952b6e505d46fa8946ef27ece0c8e4
#include "../DepthStencilState.h"
#include "../Define.h"
namespace temp {
namespace graphics {
namespace opengl {
class DepthStencilStateOpenGL
: public temp::graphics::DepthStencilStateBase<DepthStencilStateOpenGL> {
friend class DeviceOpenGLBase;
typedef temp::graphics::DepthStencilStateBase<DepthStencilStateOpenGL>
Super;
private:
DepthStencilStateOpenGL(const DepthStencilStateDesc &desc) : Super(desc) {}
};
}
}
}
#endif // GUARD_0a952b6e505d46fa8946ef27ece0c8e4
<file_sep>/**
* @file Application.h
* @brief アプリケーションテスト
* @author tsukushibito
* @version 0.0.1
* @date 2014-12-03
*/
#pragma once
#ifndef GUARD_147fd7e00e444ba4b96ef80430cd726f
#define GUARD_147fd7e00e444ba4b96ef80430cd726f
/*
#include "../../source/Tempura.h"
#include "graphics/Graphics.h"
#include "../../source/system/ThreadPool.h"
#include <fstream>
temp::graphics::View *pView = nullptr;
temp::graphics::Context *pContext = nullptr;
void applicationTest() {
using namespace temp;
using namespace temp::system;
temp::system::Window window;
temp::graphics::Device device;
pContext = device.getContext();
pView = device.createView(window);
graphics::RenderTargetDesc rtDesc;
graphics::RenderTarget *pRenderTarget = device.createRenderTarget(rtDesc);
temp::graphics::DepthStencilDesc dsDesc;
dsDesc.format_ = temp::graphics::DEPTH_STENCIL_FORMAT::D32F;
temp::graphics::DepthStencil *pDepthStencil = device.createDepthStencil(dsDesc);
std::ifstream ifs("../shader/test_glsl.vert");
if(!ifs.fail())
{
std::istreambuf_iterator<char> beg(ifs);
std::istreambuf_iterator<char> end;
std::string buffer(beg, end);
device.createVertexShaderFromSource(buffer.c_str(), buffer.size());
}
temp::system::ThreadPool threadPool(4);
struct TestFunc {
void operator()() {
pContext->clearRenderTarget(nullptr, temp::Color(0.f, 0.f, 1.f, 1.f));
pView->present();
}
};
//TestFunc testFunc;
auto testFunc = [&threadPool](){
static Float32 red = 0.f;
pContext->clearRenderTarget(nullptr, temp::Color(red, 0.f, 1.f, 1.f));
red += 0.001f;
temp::system::JobPtr spJob(new temp::system::Job([](){pView->present();}));
pView->present();
};
Application::getInstance().setMainLoopFunc(testFunc);
Application::getInstance().run();
}
*/
#endif // GUARD_147fd7e00e444ba4b96ef80430cd726f
<file_sep>#include "../../TempuraCommon.h"
#ifdef TEMP_GRAPHICS_OPENGL
#include "DepthStencilOpenGL.h"
namespace temp {
namespace graphics {
namespace opengl {
DepthStencilOpenGL::DepthStencilOpenGL(temp::UInt32 handle,
const DepthStencilDesc &desc)
: Super(desc), handle_(handle) {}
}
}
}
#endif
<file_sep>/**
* @brief てんぷらエンジン共通定義
* @author tsukushibito
* @version 0.0.1
* @date 2014-10-23
*/
#pragma once
#ifndef GUARD_76f32aa9b59f416eb788916dc049d566
#define GUARD_76f32aa9b59f416eb788916dc049d566
#if defined(__alpha__) || defined(__ia64__) || defined(__x86_64__) || \
defined(_WIN64) || defined(__LP64__) || defined(__LLP64__)
#define TEMP_64BIT
#endif
#if defined _WIN32
#define TEMP_PLATFORM_WINDOWS
// #define TEMP_DX_USABLE
#elif defined __APPLE__
#define TEMP_PLATFORM_MAC
#elif defined __gnu_linux__
#define TEMP_PLATFORM_LINUX
#elif defined __ANDROID__
#define TEMP_PLATFORM_ANDROID
#endif
#ifdef TEMP_DX_USABLE
#define TEMP_GRAPHICS_DX11
#else
#define TEMP_GRAPHICS_OPENGL
#endif
// C++標準ライブラリ
// C++11と想定しています
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cfloat>
#include <cstdarg>
#include <exception>
#include <new>
#include <memory>
#include <atomic>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <deque>
#include <queue>
#include <chrono>
#include <functional>
#include <tuple>
// サードパーティ製ライブラリ
#include <Eigen>
#ifndef DEBUG
#define TEMP_ASSERT(expr, msg)
#else
#define TEMP_ASSERT(expr, msg) assert(expr &&msg)
#endif
namespace temp {
using namespace Eigen;
using Char = char;
using Bool = bool;
using Int8 = int8_t;
using Int16 = int16_t;
using Int32 = int32_t;
using Int64 = int64_t;
using UInt8 = uint8_t;
using UInt16 = uint16_t;
using UInt32 = uint32_t;
using UInt64 = uint64_t;
using Float32 = float;
using Float64 = double;
typedef size_t Size;
class Exception : public std::exception {
public:
Exception(const std::string &message)
: message_(message), fileName_("undefined"), functionName_("undefined"),
line_(-1) {}
Exception(const std::string &message, const char *fileName,
const char *functionName, const int line)
: message_(message), fileName_(fileName), functionName_(functionName),
line_(line) {}
virtual ~Exception() throw() {}
const char *what() const throw() { return message_.c_str(); }
const char *getFileName() const { return fileName_; }
const char *getFunctionName() const { return functionName_; }
const int getLineNumber() const { return line_; }
private:
std::string message_;
const char *fileName_;
const char *functionName_;
int line_;
};
#define TEMP_THROW_EXCEPTION(message) \
throw ::temp::Exception(message, __FILE__, __FUNCTION__, __LINE__)
/**
* @brief コピー禁止型 private継承で使用してください
*/
class Uncopyable {
protected:
Uncopyable() {}
~Uncopyable() {}
private:
Uncopyable(const Uncopyable &);
const Uncopyable &operator=(const Uncopyable &);
};
/**
* @brief 侵入型参照カウンタオブジェクト
*/
class ReferenceObject : Uncopyable {
public:
ReferenceObject() { count_ = 1; }
virtual ~ReferenceObject() {}
Int32 addRef() { return ++count_; }
Int32 release() {
Int32 c = --count_;
if (c == 0) {
delete this;
}
return c;
}
Int32 getRefCount() const { return count_; }
private:
std::atomic_int count_;
};
/**
* @brief ReferenceObject用スマートポインタ
*
* @tparam T ReferenceObjectを継承したクラス
*/
template <typename T> class RefObjPtr {
private:
typedef RefObjPtr this_type;
public:
RefObjPtr() : px_(nullptr) {}
RefObjPtr(T *p) : px_(p) {}
RefObjPtr(const RefObjPtr<T> &rhs) : px_(rhs.get()) {
if (px_ != nullptr) {
px_->addRef();
}
}
template <typename U> RefObjPtr(const RefObjPtr<U> &rhs) : px_(rhs.get()) {
if (px_ != nullptr)
px_->addRef();
}
~RefObjPtr() {
if (px_ != nullptr)
px_->release();
}
RefObjPtr &operator=(RefObjPtr const &rhs) {
this_type(rhs).swap(*this);
return *this;
}
RefObjPtr &operator=(T *rhs) {
this_type(rhs).swap(*this);
return *this;
}
void reset() { this_type().swap(*this); }
void reset(T *rhs) { this_type(rhs).swap(*this); }
T &operator*() const {
assert(px_ != 0);
return *px_;
}
T *operator->() const {
assert(px_ != 0);
return px_;
}
T *get() const { return px_; }
void swap(RefObjPtr &rhs) {
// todo: ムーブセマンティクスを使用して最適化
T *tmp = px_;
px_ = rhs.px_;
rhs.px_ = tmp;
}
private:
T *px_;
};
template <class T, class U>
inline bool operator==(RefObjPtr<T> const &a, RefObjPtr<U> const &b) {
return a.get() == b.get();
}
template <class T, class U>
inline bool operator!=(RefObjPtr<T> const &a, RefObjPtr<U> const &b) {
return a.get() != b.get();
}
template <class T, class U>
inline bool operator==(RefObjPtr<T> const &a, U *b) {
return a.get() == b;
}
template <class T, class U>
inline bool operator!=(RefObjPtr<T> const &a, U *b) {
return a.get() != b;
}
template <class T, class U>
inline bool operator==(T *a, RefObjPtr<U> const &b) {
return a == b.get();
}
template <class T, class U>
inline bool operator!=(T *a, RefObjPtr<U> const &b) {
return a != b.get();
}
template <class T>
inline bool operator<(RefObjPtr<T> const &a, RefObjPtr<T> const &b) {
return std::less<T *>()(a.get(), b.get());
}
template <class T> void swap(RefObjPtr<T> &lhs, RefObjPtr<T> &rhs) {
lhs.swap(rhs);
}
/**
* @brief シングルトンテンプレートクラス
*
* @tparam T シングルトンにしたい型(public継承してください)
*/
template <class T> class Singleton : Uncopyable {
protected:
Singleton() {}
virtual ~Singleton() {}
public:
static T &getInstance() {
static T instance;
return instance;
}
// virtual void initialize() = 0;
// virtual void terminate() = 0;
};
/**
* @brief キャスト用クラス CRTPでダウンキャストする時用
*
* @tparam T キャスト先クラス
*/
template <class T> class Castable {
public:
T *derive() { return static_cast<T *>(this); }
};
template <typename T> struct Point2D {
Point2D(T x = 0, T y = 0) : x_(x), y_(y) {}
T x_;
T y_;
};
template <typename T> struct Point3D {
Point3D(T x = 0, T y = 0, T z = 0) : x_(x), y_(y), z_(z) {}
union {
T x_;
T r_;
};
union {
T y_;
T g_;
};
union {
T z_;
T b_;
};
};
template <typename T> struct Point4D {
Point4D(T x = 0, T y = 0, T z = 0, T w = 0) : x_(x), y_(y), z_(z), w_(w) {}
union {
T x_;
T r_;
};
union {
T y_;
T g_;
};
union {
T z_;
T b_;
};
union {
T w_;
T a_;
};
};
typedef Point4D<Float32> Color;
}
#endif // GUARD_76f32aa9b59f416eb788916dc049d566
<file_sep>#!/bin/sh
gyp Tempura.gyp --depth=.
<file_sep>/**
* @file VertexBufferOpenGL.h
* @brief OpenGL版頂点バッファ
* @author tsukushibito
* @version 0.0.1
* @date 2015-03-22
*/
#pragma once
#ifndef GUARD_e31a938249a04caaaa19caa4a24d9ff8
#define GUARD_e31a938249a04caaaa19caa4a24d9ff8
#include "../VertexBuffer.h"
#include "../Define.h"
namespace temp {
namespace graphics {
namespace opengl {
class VertexBufferOpenGL
: public temp::graphics::VertexBufferBase<VertexBufferOpenGL> {
friend class DeviceOpenGLBase;
typedef temp::graphics::VertexBufferBase<VertexBufferOpenGL> Super;
private:
VertexBufferOpenGL(temp::UInt32 handle, const VertexBufferDesc &desc);
public:
temp::UInt32 getNativeHandle() const { return handle_; }
private:
temp::UInt32 handle_;
};
}
}
}
#endif // GUARD_e31a938249a04caaaa19caa4a24d9ff8
<file_sep>#include "../../TempuraCommon.h"
#ifdef TEMP_GRAPHICS_OPENGL
#include "InputLayoutOpenGL.h"
namespace temp {
namespace graphics {
namespace opengl {
InputLayoutOpenGL::InputLayoutOpenGL(const InputElementDesc *descs,
Size elementCount,
const ShaderObjectPtr &spShaderObject)
: Super(descs, elementCount) {
}
}
}
}
#endif
<file_sep>#include <Windows.h>
#include "../Window.h"
namespace temp {
namespace system {
namespace {
LRESULT CALLBACK wndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
switch (msg) {
case WM_DESTROY: /* 終了処理 */
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}
}
class Window::Impl {
public:
Impl(Size width, Size height) {
WNDCLASSEX wndclass;
HINSTANCE hInstance = GetModuleHandle(NULL);
wndclass.cbSize = sizeof(wndclass); /* 構造体の大きさ */
wndclass.style = CS_HREDRAW | CS_VREDRAW; /* スタイル */
wndclass.lpfnWndProc = wndProc; /* メッセージ処理関数 */
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = hInstance; /* プログラムのハンドル */
wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION); /* アイコン */
wndclass.hCursor = LoadCursor(NULL, IDC_ARROW); /* カーソル */
wndclass.hbrBackground =
(HBRUSH)GetStockObject(WHITE_BRUSH); /* ブラシ */
wndclass.lpszMenuName = NULL; /* メニュー */
wndclass.lpszClassName = "TempuraWindow"; /* クラス名 */
wndclass.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
RegisterClassEx(&wndclass); /* ウインドウクラスTest Windowを登録 */
hWnd_ =
CreateWindow("TempuraWindow", /* ウインドウクラス名 */
"てんぷら", /* ウインドウのタイトル */
WS_OVERLAPPEDWINDOW, /* ウインドウスタイル */
CW_USEDEFAULT, CW_USEDEFAULT, /* ウインドウ表示位置 */
static_cast<int>(width), static_cast<int>(height), /* ウインドウの大きさ */
NULL, /* 親ウインドウのハンドル */
NULL, /* メニューのハンドル */
hInstance, /* インスタンスのハンドル */
NULL); /* 作成時の引数保存用ポインタ */
ShowWindow(hWnd_, SW_SHOW); /* ウインドウを表示 */
UpdateWindow(hWnd_);
hDc_ = GetDC(hWnd_);
}
~Impl() {}
WindowHandle getWindowHandle() {
WindowHandle handle;
handle.pointer_ = hWnd_;
return handle;
}
ViewHandle getViewHandle() {
ViewHandle handle;
handle.pointer_ = hDc_;
return handle;
}
private:
HWND hWnd_;
HDC hDc_;
};
Window::Window(Size width, Size height) { pImpl_ = new Impl(width, height); }
Window::~Window() { delete pImpl_; }
WindowHandle Window::getWindowHandle() const {
return pImpl_->getWindowHandle();
}
ViewHandle Window::getViewHandle() const {
return pImpl_->getViewHandle();
}
}
}
<file_sep>/**
* @file ThreadPool.cpp
* @brief スレッドプール
* @author tsukushibito
* @version 0.0.1
* @date 2014-10-27
*/
#include "ThreadPool.h"
#include "Logger.h"
namespace temp {
namespace system {
ThreadPool::WorkerThread::WorkerThread(ThreadPool &threadPool)
: threadPool_(threadPool), thread_(), state_(RUNNING) {
thread_ = std::thread([this] { run(); });
}
void ThreadPool::WorkerThread::run() {
for (;;) {
JobPtr spJob = threadPool_.popJob();
if (spJob.get() != nullptr) {
spJob->execute();
} else {
suspend();
}
if (state_ == TERMINATING) {
break;
}
}
state_ = TERMINATED;
}
void ThreadPool::WorkerThread::suspend() {
std::unique_lock<std::mutex> lock(mutex_);
state_ = SUSPENDING;
condition_.wait(lock);
}
void ThreadPool::WorkerThread::resume() {
state_ = RUNNING;
condition_.notify_one();
}
void ThreadPool::WorkerThread::terminate() {
switch (state_) {
case TERMINATING:
case TERMINATED:
return;
break;
default:
break;
}
state_ = TERMINATING;
condition_.notify_one();
thread_.join();
}
ThreadPool::ThreadPool(temp::UInt32 threadCount) {
threads_.reserve(threadCount);
for (Size i = 0; i < threadCount; ++i) {
WorkerThreadPtr spThread(new WorkerThread(*this));
threads_.push_back(spThread);
}
}
ThreadPool::~ThreadPool() {
WorkerThreadVector::iterator iter;
for (iter = threads_.begin(); iter != threads_.end(); ++iter) {
(*iter)->terminate();
}
}
void ThreadPool::pushJob(const JobPtr &spJob) {
using namespace std;
lock_guard<mutex> lock(mutex_);
jobQueue_.push(spJob);
// debugLog("[ThreadPool] jobQueue_.size() = %d", jobQueue_.size());
ConsoleLogger::trace("[ThreadPool] jobQueue_.size() = {0:d}", jobQueue_.size());
WorkerThreadVector::iterator iter;
for (iter = threads_.begin(); iter != threads_.end(); ++iter) {
(*iter)->resume();
}
}
JobPtr ThreadPool::popJob() {
using namespace std;
lock_guard<mutex> lock(mutex_);
if (jobQueue_.empty())
return nullptr;
JobPtr output = jobQueue_.top();
jobQueue_.pop();
return output;
}
}
}
<file_sep>/**
* @file DepthStencilOpenGL.h
* @brief OpenGL版深度ステンシルバッファ
* @author tsukushibito
* @version 0.0.1
* @date 2015-03-18
*/
#pragma once
#ifndef GUARD_40bea55027d44fcbadb33640c5896576
#define GUARD_40bea55027d44fcbadb33640c5896576
#include "../DepthStencil.h"
#include "../Define.h"
namespace temp {
namespace graphics {
namespace opengl {
class DepthStencilOpenGL
: public temp::graphics::DepthStencilBase<DepthStencilOpenGL> {
friend class DeviceOpenGLBase;
friend class ViewOpenGLBase;
typedef temp::graphics::DepthStencilBase<DepthStencilOpenGL> Super;
private:
DepthStencilOpenGL(temp::UInt32 handle, const DepthStencilDesc &desc);
public:
temp::UInt32 getNativeHandle() const { return handle_; }
private:
temp::UInt32 handle_;
};
}
}
}
#endif // GUARD_40bea55027d44fcbadb33640c5896576
<file_sep>{
'includes': ['common.gypi'],
'make_global_settings': [
['CXX','/usr/bin/clang++'],
['LINK','/usr/bin/clang++'],
],
'variables': {
'src_files': '<!(python enum_src_files.py ../Source)',
'allocator_files': '<!(python enum_src_files.py ../Source/Allocator)',
'test_files': '<!(python enum_src_files.py ../Test)',
},
'target_defaults': {
'include_dirs': [
'../ThirdParty/glew/include',
'../ThirdParty/Eigen',
'../ThirdParty/spdlog',
],
'msvs_settings': {
'VCCLCompilerTool': {
'WarningLevel': '4', # /W4
},
'VCLinkerTool': {
'AdditionalDependencies': [
'kernel32.lib',
'user32.lib',
'gdi32.lib',
'winspool.lib',
'comdlg32.lib',
'advapi32.lib',
'shell32.lib',
'ole32.lib',
'oleaut32.lib',
'uuid.lib',
'odbc32.lib',
'odbccp32.lib',
'opengl32.lib',
],
# 'TargetMachine': '17'
},
'VCLibrarianTool': {
# 'TargetMachine': '17'
},
},
'xcode_settings': {
'GCC_VERSION': 'com.apple.compilers.llvm.clang.1_0',
'CLANG_CXX_LANGUAGE_STANDARD': 'c++0x',
'MACOSX_DEPLOYMENT_TARGET': '10.8',
'CLANG_CXX_LIBRARY': 'libc++',
},
},
'targets': [
{
'target_name': 'TempuraEngine',
'product_name': 'TempuraEngine',
'type': 'static_library',
'include_dirs': [
'../Source',
],
'sources': [
'<@(src_files)',
],
# 'sources!': [
# '<@(allocator_files)',
# ],
'xcode_settings': {
'GCC_INLINES_ARE_PRIVATE_EXTERN': 'YES',
'GCC_SYMBOLS_PRIVATE_EXTERN': 'YES',
},
'conditions': [
['OS=="mac"', {
'sources!': [
'../Source/System/Windows/Window.cpp',
'../Source/System/Windows/Application.cpp',
]}],
['OS=="win"', {
'sources!': [
'../Source/System/Mac/Window.mm',
'../Source/System/Mac/Application.mm',
]}],
],
},
# {
# 'target_name': 'tempura_allocator',
# 'product_name': 'TempuraAllocator',
# 'type': 'shared_library',
# 'include_dirs': [
# '../Source',
# ],
# 'sources': [
# '<@(allocator_files)',
# ],
# 'xcode_settings': {
# 'GCC_INLINES_ARE_PRIVATE_EXTERN': 'YES',
# 'GCC_SYMBOLS_PRIVATE_EXTERN': 'YES',
# },
# },
{
'target_name': 'TempuraTest',
'product_name': 'TempuraTest',
'type': 'executable',
'dependencies': [
'TempuraEngine',
],
'include_dirs': [
'../Source',
],
'sources': [
'<@(test_files)',
],
'xcode_settings': {
'GCC_INLINES_ARE_PRIVATE_EXTERN': 'YES',
'GCC_SYMBOLS_PRIVATE_EXTERN': 'YES',
},
'conditions': [
['OS=="mac"', {
'libraries': [
'$(SDKROOT)/System/Library/Frameworks/Cocoa.framework',
'$(SDKROOT)/System/Library/Frameworks/OpenGL.framework',
'../ThirdParty/glew/lib/libGLEW.dylib',
]}],
['OS=="win"', {
'libraries': [
'../ThirdParty/glew/lib/Release/x64/glew32.lib',
]}],
],
},
]# targets
}
<file_sep>/**
* @file ViewOpenGLMac.h
* @brief Mac版OpenGLビュー
* @author tsukushibito
* @version 0.0.1
* @date 2015-02-22
*/
#pragma once
#ifndef GUARD_c7486e55687d4127828fe8edde71627b
#define GUARD_c7486e55687d4127828fe8edde71627b
#include "../ViewOpenGLBase.h"
#if defined TEMP_PLATFORM_MAC
#include "../../Define.h"
namespace temp {
namespace graphics {
namespace opengl {
namespace mac {
class ViewOpenGLMac : public ViewOpenGLBase {
friend class DeviceOpenGLMac;
private:
explicit ViewOpenGLMac(void *pNativeContext);
public:
~ViewOpenGLMac() {}
void present();
private:
void *pNativeContext_;
};
}
}
}
}
#endif // TEMP_PLATFORM_MAC
#endif // GUARD_c7486e55687d4127828fe8edde71627b
<file_sep>/**
* @file Define.h
* @brief 定義ヘッダ
* @author tsukushibito
* @version 0.0.1
* @date 2015-02-16
*/
#pragma once
#ifndef GUARD_5419ba5a46fc4b479e8b0b1c0a332837
#define GUARD_5419ba5a46fc4b479e8b0b1c0a332837
namespace temp {
namespace graphics {
template <class T> class DeviceBase;
template <class T> class ContextBase;
template <class T> class ViewBase;
template <class T> class BackBufferBase;
template <class T> class RenderTargetBase;
template <class T> class DepthStencilBase;
template <class T> class IndexBufferBase;
template <class T> class VertexBufferBase;
template <class T> class ShaderObjectBase;
template <class T> class InputLayoutBase;
template <class T> class ConstantBufferBase;
template <class T> class BlendStateBase;
template <class T> class DepthStencilStateBase;
template <class T> class RasterizerStateBase;
template <class T> class SamplerStateBase;
#if defined TEMP_GRAPHICS_DX11
// DirectX11版クラス名定義
namespace dx11 {
class DeviceDX11;
class ContextDX11;
class ViewDX11;
class BackBufferDX11;
class RenderTargetDX11;
class DepthStencilDX11;
class IndexBufferDX11;
class VertexBufferDX11;
class ShaderObjectDX11;
class InputLayoutDX11;
class ConstantBufferDX11;
class BlendStateDX11;
class DepthStencilStateDX11;
class RasterizerStateDX11;
class SamplerStateDX11;
}
using Device = dx11::DeviceDX11;
using Context = dx11::ContextDX11;
using View = dx11::ViewDX11;
using BackBuffer = dx11::BackBufferDX11;
using RenderTarget = dx11::RenderTargetDX11;
using DepthStencil = dx11::DepthStencilDX11;
using IndexBuffer = dx11::IndexBufferDX11;
using VertexBuffer = dx11::VertexBufferDX11;
using ShaderObject = dx11::ShaderObjectDX11;
using InputLayout = dx11::InputLayoutDX11;
using ConstantBuffer = dx11::ConstantBufferDX11;
using BlendState = dx11::BlendStateDX11;
using DepthStencilState = dx11::DepthStencilStateDX11;
using RasterizerState = dx11::RasterizerStateDX11;
using SamplerState = dx11::SamplerStateDX11;
#elif defined TEMP_GRAPHICS_OPENGL
// OpenGL版クラス名定義
namespace opengl {
#if defined TEMP_PLATFORM_WINDOWS
// Windows依存クラス名定義
namespace windows {
class DeviceOpenGLWindows;
class ViewOpenGLWindows;
}
using DeviceOpenGL = windows::DeviceOpenGLWindows;
using ViewOpenGL = windows::ViewOpenGLWindows;
#elif defined TEMP_PLATFORM_MAC
// Mac依存クラス名定義
namespace mac {
class DeviceOpenGLMac;
class ViewOpenGLMac;
}
using DeviceOpenGL = mac::DeviceOpenGLMac;
using ViewOpenGL = mac::ViewOpenGLMac;
#endif
class ContextOpenGL;
class BackBufferOpenGL;
class RenderTargetOpenGL;
class DepthStencilOpenGL;
class IndexBufferOpenGL;
class VertexBufferOpenGL;
class ShaderObjectOpenGL;
class InputLayoutOpenGL;
class ConstantBufferOpenGL;
class BlendStateOpenGL;
class DepthStencilStateOpenGL;
class RasterizerStateOpenGL;
class SamplerStateOpenGL;
}
using Device = opengl::DeviceOpenGL;
using View = opengl::ViewOpenGL;
using Context = opengl::ContextOpenGL;
using BackBuffer = opengl::BackBufferOpenGL;
using RenderTarget = opengl::RenderTargetOpenGL;
using DepthStencil = opengl::DepthStencilOpenGL;
using IndexBuffer = opengl::IndexBufferOpenGL;
using VertexBuffer = opengl::VertexBufferOpenGL;
using ShaderObject = opengl::ShaderObjectOpenGL;
using InputLayout = opengl::InputLayoutOpenGL;
using ConstantBuffer = opengl::ConstantBufferOpenGL;
using BlendState = opengl::BlendStateOpenGL;
using DepthStencilState = opengl::DepthStencilStateOpenGL;
using RasterizerState = opengl::RasterizerStateOpenGL;
using SamplerState = opengl::SamplerStateOpenGL;
#endif
// スマートポインタ定義
using DevicePtr = RefObjPtr<Device>;
using ViewPtr = RefObjPtr<View>;
using ContextPtr = RefObjPtr<Context>;
using BackBufferPtr = RefObjPtr<BackBuffer>;
using RenderTargetPtr = RefObjPtr<RenderTarget>;
using DepthStencilPtr = RefObjPtr<DepthStencil>;
using IndexBufferPtr = RefObjPtr<IndexBuffer>;
using VertexBufferPtr = RefObjPtr<VertexBuffer>;
using ShaderObjectPtr = RefObjPtr<ShaderObject>;
using InputLayoutPtr = RefObjPtr<InputLayout>;
using ConstantBufferPtr = RefObjPtr<ConstantBuffer>;
using BlendStatePtr = RefObjPtr<BlendState>;
using DepthStencilStatePtr = RefObjPtr<DepthStencilState>;
using RasterizerStatePtr = RefObjPtr<RasterizerState>;
using SamplerStatePtr = RefObjPtr<SamplerState>;
}
}
#endif // GUARD_5419ba5a46fc4b479e8b0b1c0a332837
<file_sep>#include "Timer.h"
namespace temp {
namespace system {
Timer::Timer() : timePoint_(std::chrono::high_resolution_clock::now()) {}
void Timer::reset()
{
timePoint_ = std::chrono::high_resolution_clock::now();
}
Int64 Timer::nanoseconds() const {
using namespace std::chrono;
high_resolution_clock::time_point now = high_resolution_clock::now();
return duration_cast<std::chrono::nanoseconds>(now - timePoint_).count();
}
Int64 Timer::microseconds() const {
using namespace std::chrono;
high_resolution_clock::time_point now = high_resolution_clock::now();
return duration_cast<std::chrono::microseconds>(now - timePoint_).count();
}
Int64 Timer::milliseconds() const {
using namespace std::chrono;
high_resolution_clock::time_point now = high_resolution_clock::now();
return duration_cast<std::chrono::milliseconds>(now - timePoint_).count();
}
Int64 Timer::seconds() const {
using namespace std::chrono;
high_resolution_clock::time_point now = high_resolution_clock::now();
return duration_cast<std::chrono::seconds>(now - timePoint_).count();
}
Int64 Timer::minutes() const {
using namespace std::chrono;
high_resolution_clock::time_point now = high_resolution_clock::now();
return duration_cast<std::chrono::minutes>(now - timePoint_).count();
}
Int64 Timer::hours() const {
using namespace std::chrono;
high_resolution_clock::time_point now = high_resolution_clock::now();
return duration_cast<std::chrono::hours>(now - timePoint_).count();
}
}
}
<file_sep># TempuraEngine
simple 3d game engine<file_sep>#include "../../TempuraCommon.h"
#ifdef TEMP_GRAPHICS_OPENGL
#include "ViewOpenGLBase.h"
#endif
<file_sep>/**
* @file TlsfAllocator.h
* @brief TLSFアロケータ
* @author tsukushibito
* @version 0.0.1
* @date 2014-11-09
*/
#pragma once
#ifndef GUARD_b53aa2f90805484d8843631647e35860
#define GUARD_b53aa2f90805484d8843631647e35860
#include <stddef.h>
#include "../TempuraCommon.h"
#include "AllocatorCommon.h"
namespace temp {
namespace allocator {
class TlsfAllocator : public temp::ReferenceObject {
struct Chunk;
/**
* @brief 使用中フラグ
*/
union UseFlag {
UseFlag() : flag_(false) {}
temp::Bool flag_; /**< 使用中フラグ */
temp::UInt64 dummy_; /**< アライメントを揃えるためのダミー */
};
/**
* @brief フリーリスト用のリンクポインタ
*/
struct FreeListLink {
FreeListLink() : pPrevFreeChunk_(nullptr), pNextFreeChunk_(nullptr) {}
Chunk *pPrevFreeChunk_; /**< 前方フリーチャンク */
Chunk *pNextFreeChunk_; /**< 後方フリーチャンク */
};
/**
* @brief メモリチャンクヘッダ
*/
struct Chunk {
Chunk() : prevChunkSize_(0), thisChunkSize_(0) {}
UInt prevChunkSize_; /**< 前方チャンクの管理メモリブロックサイズ */
UInt thisChunkSize_; /**< 管理メモリブロックサイズ */
UseFlag useFlag_; /**< 使用中フラグ */
// 管理メモリ部分と重なっているので、フリーチャンクの時のみ有効
FreeListLink freeListLink_; /**< フリーリストのリンク用ポインタ */
/**
* @brief 管理メモリのポインタを返す
*
* @return 管理メモリのポインタ
*/
void *getManagedMemory() {
return reinterpret_cast<UInt8 *>(this) + sizeof(prevChunkSize_) +
sizeof(thisChunkSize_) + sizeof(useFlag_);
}
/**
* @brief チャンクを指定サイズのチャンクに切り分けられるかどうか
*
* @param size 切り分けるサイズ
*
* @return trueなら切り分けられる
*/
temp::Bool canSplit(UInt size) const;
/**
* @brief チャンクを切り分ける
*
* @param size 切り分けるサイズ
*
* @return 切り分けられて新しく作成されたチャンクのポインタ
*/
Chunk *split(UInt size);
/**
* @brief チャンクのヘッダーサイズを返す
*
* @return チャンクのヘッダーサイズ
*/
static UInt getHeaderSize() {
return sizeof(Chunk) - sizeof(FreeListLink);
}
};
static const UInt SL_INDEX_COUNT_LOG2 = 5;
static const UInt ALIGN_SIZE_LOG2 = 3;
static const UInt ALIGN_SIZE = (1 << ALIGN_SIZE_LOG2);
#ifdef TEMP_64BIT
static const UInt FL_INDEX_MAX = 64;
#else
static const UInt FL_INDEX_MAX = 32;
#endif
static const UInt SL_INDEX_COUNT = (1 << SL_INDEX_COUNT_LOG2);
static const UInt FL_INDEX_SHIFT = (SL_INDEX_COUNT_LOG2 + ALIGN_SIZE_LOG2);
static const UInt FL_INDEX_COUNT = (FL_INDEX_MAX - FL_INDEX_SHIFT + 1);
static const UInt SMALL_CHUNK_SIZE = (1 << FL_INDEX_SHIFT);
static const UInt CHUNK_SIZE_MIN = sizeof(FreeListLink);
#ifdef TEMP_64BIT
#ifdef TEMP_PLATFORM_WINDOWS
static const UInt CHUNK_SIZE_MAX = (1Ui64 << (FL_INDEX_MAX - 1)); // note: 調整
#else
static const UInt CHUNK_SIZE_MAX = ((Size)1U << (FL_INDEX_MAX - 1)); // note: 調整
#endif
#else
static const UInt CHUNK_SIZE_MAX = (1U << (FL_INDEX_MAX - 1));
#endif
public:
/**
* @brief コンストラクタ
*
* @param memoryPool 管理するメモリプールの先頭ポインタ
* @param poolSize 管理するメモリプールのサイズ
*/
TlsfAllocator(void *memoryPool, UInt poolSize);
/**
* @brief メモリ確保
*
* @param size 確保するメモリサイズ
*
* @return 確保されたメモリのポインタ
*/
void *malloc(UInt size);
/**
* @brief メモリ解放
*
* @param pointer 開放するメモリ
*/
void free(void *pointer);
/**
* @brief 管理しているメモリプールをデフラグ
*
* @param step デフラグするステップ数 (Chunkのスイッチ回数)
*/
void defragment(UInt step);
private:
/**
* @brief フリーチャンクリスト
*/
Chunk *freeChunkMatrix_[FL_INDEX_COUNT][SL_INDEX_COUNT];
/**
* @brief フリーチャンクを示すビットフラグ
* フラグが立っていれば、そのFLインデックスにフリーチャンクが存在する
*/
UInt freeChunkFliBits_;
/**
* @brief フリーチャンクを示すビットフラグ
* フラグが立っていれば、そのSLインデックスにフリーチャンク
*/
UInt freeChunkSliBits_[FL_INDEX_COUNT];
Chunk dummyFreeChunk_; /**< フリーリスト用のダミーチャンク */
Chunk *pDummyTopChunk_; /**< 管理メモリの先頭ダミーチャンク */
Chunk *pDummyBottomChunk_; /**< 管理メモリの末尾ダミーチャンク */
private:
public:
struct FliAndSli {
Int fli_;
Int sli_;
};
/**
* @brief アラインメントに合わせてサイズを切り上げる
*
* @param size サイズ
* @param align アラインメントサイズ
*
* @return
*/
static UInt alignUp(UInt size, UInt align) {
TEMP_ASSERT(0 == (align & (align - 1)), "must align to a power of two");
return (size + (align - 1)) & ~(align - 1);
}
/**
* @brief アラインメントに合わせてサイズを切り捨てる
*
* @param size サイズ
* @param align アラインメントサイズ
*
* @return
*/
static UInt alignDown(UInt size, UInt align) {
TEMP_ASSERT(0 == (align & (align - 1)), "must align to a power of two");
return size - (size & (align - 1));
}
/**
* @brief アラインされたポインタを返す
*
* @param pointer ポインタ
* @param align アラインメントサイズ
*
* @return アラインされたポインタ
*/
static void *alignPointer(void *pointer, UInt align);
/**
* @brief MSB(Most Significant Bit)を求める
*
* @param value 値
*
* @return MSB
*/
static UInt evaluateMsb(UInt value);
/**
* @brief LSB(Least Signigicant Bit)を求める
*
* @param value 値
*
* @return LSB
*/
static UInt evaluateLsb(UInt value);
/**
* @brief サイズに対応したFLIとSLIを求める
*
* @param size サイズ
*
* @return FLIとSLIをまとめた構造体
*/
static FliAndSli evaluateFliAndSli(UInt size);
/**
* @brief フリーチャンクを追加する
*
* @param freeChunk
*/
void insertFreeChunk(Chunk *pFreeChunk, const FliAndSli &fliAndSli);
/**
* @brief 指定のFLIとSLIから適したサイズのフリーチャンクを返す
*
* @param fliAndSli
*
* @return フリーチャンク
*/
Chunk *findFreeChunk(FliAndSli &fliAndSli);
/**
* @brief フリーチャンクリストから取り除く
*
* @param pFreeChunk
*/
void removeChunkFromFreeList(Chunk *pFreeChunk);
/**
* @brief フリーチャンクを使用中にする前処理
*
* @param pFreeChunk 使用するチャンク
* @param size 要求メモリサイズ
*
* @return
*/
void *prepareUseChunk(Chunk *pFreeChunk, UInt size);
/**
* @brief 要求サイズを補正する
*
* @param size 要求サイズ
*
* @return 補正されたサイズ
*/
UInt adjustRequestSize(UInt size);
/**
* @brief 手前のチャンクを返す
*
* @param pChunk チャンク
*
* @return 手前のチャンク 管理メモリ外の場合はnullptrを返す
*/
Chunk *getPrevChunk(Chunk *pChunk) const;
/**
* @brief 後ろのチャンクを返す
*
* @param pChunk チャンク
*
* @return 後ろのチャンク 管理メモリ外の場合はnullptrを返す
*/
Chunk *getNextChunk(Chunk *pChunk) const;
/**
* @brief データポインタからチャンクを取得する
*
* @param pointer チャンクが管理するポインタ
*
* @return チャンクのポインタ
*/
Chunk *getChunkFromDataPointer(void *pointer) const;
/**
* @brief 手前にあるチャンクとマージする
*
* @param pChunk 対象チャンク
*
* @return マージ後のチャンク
*/
Chunk *margeWithPrevChunk(Chunk *pChunk);
/**
* @brief 後方にあるチャンクとマージする
*
* @param pChunk 対象チャンク
*
* @return マージ後のチャンク
*/
Chunk *margeWithNextChunk(Chunk *pChunk);
/**
* @brief 隣り合ったチャンクをマージ
*
* @param pLeftChunk 左側チャンク
* @param pRightChunk 右側チャンク
*
* @return マージ後のチャンク
*/
Chunk *margeAdjacentChunk(Chunk *pLeftChunk, Chunk *pRightChunk);
};
}
}
#endif // GUARD_b53aa2f90805484d8843631647e35860
<file_sep>/**
* @file RenderTarget.h
* @brief レンダーターゲット
* @author tsukushibito
* @version 0.0.1
* @date 2015-03-19
*/
#pragma once
#ifndef GUARD_c7b068a8ed2342e696841c05a803c06e
#define GUARD_c7b068a8ed2342e696841c05a803c06e
#include "GraphicsCommon.h"
namespace temp {
namespace graphics {
template <class T>
class RenderTargetBase : temp::Castable<T>, public temp::ReferenceObject {
public:
explicit RenderTargetBase(const RenderTargetDesc &desc) : desc_(desc) {}
RenderTargetDesc getDesc() const { return desc_; }
private:
RenderTargetDesc desc_;
};
}
}
#endif // GUARD_c7b068a8ed2342e696841c05a803c06e
<file_sep>/**
* @file ResourceManager.h
* @brief リソース管理クラス
* @author tsukushibito
* @version 0.0.1
* @date 2014-11-03
*/
#pragma once
#ifndef GUARD_1c4a0d1358d24626b2f205135989c458
#define GUARD_1c4a0d1358d24626b2f205135989c458
#include "../TempuraCommon.h"
namespace temp {
namespace resource {
class ResourceManager : public temp::Singleton<ResourceManager> {
friend temp::Singleton<ResourceManager>;
private:
ResourceManager() {}
public:
};
}
}
#endif // GUARD_1c4a0d1358d24626b2f205135989c458
<file_sep>/**
* @file Resource.h
* @brief リソース関連ヘッダ
* @author tsukushibito
* @version 0.0.1
* @date 2014-11-03
*/
#pragma once
#ifndef GUARD_dca73cc12c0d40e3be4af726c444522a
#define GUARD_dca73cc12c0d40e3be4af726c444522a
#endif // GUARD_dca73cc12c0d40e3be4af726c444522a
<file_sep>/**
* @file OpenGLCommon.h
* @brief OpenGL共通
* @author tsukushibito
* @version 0.0.1
* @date 2015-03-24
*/
#pragma once
#ifndef GUARD_955db5e8197d4962b6384b023266fa05
#define GUARD_955db5e8197d4962b6384b023266fa05
#include "../GraphicsCommon.h"
#ifdef TEMP_PLATFORM_WINDOWS
#include <Windows.h>
#endif
#include <GL/glew.h>
#if defined TEMP_PLATFORM_LINUX
#include <GL/glxew.h>
#elif defined TEMP_PLATFORM_WINDOWS
#include <GL/wglew.h>
#endif
#include "../../System/Logger.h"
namespace temp {
namespace graphics {
namespace opengl {
template <class T = void> T checkError() {
GLenum errorCode = glGetError();
if (errorCode == GL_NO_ERROR) {
return;
}
do {
const char *msg = "";
switch (errorCode) {
case GL_INVALID_ENUM:
msg = "INVALID_ENUM";
break;
case GL_INVALID_VALUE:
msg = "INVALID_VALUE";
break;
case GL_INVALID_OPERATION:
msg = "INVALID_OPERATION";
break;
case GL_OUT_OF_MEMORY:
msg = "OUT_OF_MEMORY";
break;
case GL_INVALID_FRAMEBUFFER_OPERATION:
msg = "INVALID_FRAMEBUFFER_OPERATION";
break;
default:
msg = "Unknown";
break;
}
// errorLog("OpenGL ERROR : %04x'%s'\n", errorCode, msg);
system::ConsoleLogger::error("OpenGL ERROR : {0:x}'{1}'\n", errorCode, msg);
errorCode = glGetError();
} while (errorCode != GL_NO_ERROR);
TEMP_ASSERT(false, "OpenGL ERROR");
}
template <class T = void> T printShaderCompileInfoLog(GLuint shader) {
GLint result;
glGetShaderiv(shader, GL_COMPILE_STATUS, &result);
// if(result == GL_FALSE) debugLog("[ERROR] GLSL faled to compile.");
if(result == GL_FALSE) system::ConsoleLogger::error("[ERROR] GLSL faled to compile.");
GLint bufSize = 0;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &bufSize);
if (bufSize > 1) {
std::string infoLog(bufSize, '\n');
GLsizei length;
/* シェーダのコンパイル時のログの内容を取得する */
glGetShaderInfoLog(shader, bufSize, &length, &infoLog[0]);
// debugLog("ShaderInfoLog:\n%s\n\n", infoLog.c_str());
system::ConsoleLogger::error("ShaderInfoLog:\n{0}\n\n", infoLog.c_str());
}
}
template <class... Ts> void glFunc(Ts... args) {
std::bind(args...)();
checkError();
}
}
}
}
#endif // GUARD_955db5e8197d4962b6384b023266fa05
<file_sep>#include "../../TempuraCommon.h"
#include "../GraphicsCommon.h"
#ifdef TEMP_GRAPHICS_OPENGL
#include "ConstantBufferOpenGL.h"
namespace temp {
namespace graphics {
namespace opengl {
ConstantBufferOpenGL::ConstantBufferOpenGL(temp::UInt32 handle,
Size size)
: Super(size), handle_(handle) {}
}
}
}
#endif
<file_sep>#include <Windows.h>
#include "../Application.h"
namespace temp {
namespace system {
class Application::Impl {
public:
Impl()
{
mainLoopfunc_ = [](){OutputDebugString("dummy func called!\n"); };
}
void setMainLoopFunc(const MainLoopFunc &func)
{
mainLoopfunc_ = func;
}
Int32 run()
{
MSG msg;
for (;;)
{
if (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE))
{
BOOL ret = GetMessage(&msg, NULL, 0, 0);
if ( ret == 0 || ret == -1)
{
return static_cast<Int32>(msg.wParam);
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
mainLoopfunc_();
}
}
}
private:
MainLoopFunc mainLoopfunc_;
};
Application::Application()
{
pImpl_ = new Impl;
}
Application::~Application()
{
delete pImpl_;
}
void Application::setMainLoopFunc(const MainLoopFunc &func)
{
pImpl_->setMainLoopFunc(func);
}
Int32 Application::run()
{
return pImpl_->run();
}
}
}<file_sep>#include "../../TempuraCommon.h"
#ifdef TEMP_GRAPHICS_OPENGL
#include "IndexBufferOpenGL.h"
namespace temp {
namespace graphics {
namespace opengl {
IndexBufferOpenGL::IndexBufferOpenGL(temp::UInt32 handle,
const IndexBufferDesc &desc)
: Super(desc), handle_(handle) {}
}
}
}
#endif
<file_sep>/**
* @file Container.h
* @brief STLコンテナのラッパー(カスタムアロケータ指定)
* @author tsukushibito
* @version 0.0.1
* @date 2015-04-06
*/
#pragma once
#ifndef GUARD_a424c6838fe140be904cd6f0447d9ae9
#define GUARD_a424c6838fe140be904cd6f0447d9ae9
#include "TempuraCommon.h"
#include "allocator/Allocator.h"
// #include <string>
// #include <vector>
// #include <array>
// #include <map>
// #include <unordered_map>
// #include <unordered_set>
// #include <deque>
namespace temp {
// std::string
typedef std::basic_string<char, std::char_traits<char>,
allocator::AllocatorForSTL<char> > String;
// std::vector<T>
template <typename T>
using Vector = std::vector<T, allocator::AllocatorForSTL<T> >;
// std::map<Key, Type>
template <typename Key, typename Type, typename Compare = std::less<Key> >
using Map = std::map<Key, Type, Compare,
allocator::AllocatorForSTL<std::pair<const Key, Type> > >;
// std::unordered_map<Key, Type>
template <typename Key, typename Type, typename Hash = std::hash<Key>,
typename Pred = std::equal_to<Key> >
using HashMap = std::unordered_map<
Key, Type, Hash, Pred,
allocator::AllocatorForSTL<std::pair<const Key, Type> > >;
}
#endif // GUARD_a424c6838fe140be904cd6f0447d9ae9
<file_sep>/**
* @file BackBufferOpenGL.h
* @brief OpenGL版バックバッファ
* @author tsukushibito
* @version 0.0.1
* @date 2015-03-04
*/
#pragma once
#ifndef GUARD_220cf98851e444b6ade1578fe4df9802
#define GUARD_220cf98851e444b6ade1578fe4df9802
#include "../BackBuffer.h"
#include "../Define.h"
namespace temp {
namespace graphics {
struct Texture2DDesc;
namespace opengl {
class BackBufferOpenGL
: public temp::graphics::BackBufferBase<BackBufferOpenGL> {
friend DeviceOpenGL;
friend ViewOpenGL;
typedef temp::graphics::BackBufferBase<BackBufferOpenGL> Super;
private:
BackBufferOpenGL(temp::UInt32 handle, const Texture2DDesc &desc);
public:
temp::UInt32 getNativeHandle() const { return handle_; }
private:
temp::UInt32 handle_;
};
}
}
}
#endif // GUARD_220cf98851e444b6ade1578fe4df9802
<file_sep>/**
* @file InputLayoutOpenGL.h
* @brief OpenGL版入力レイアウト
* @author tsukushibito
* @version 0.0.1
* @date 2015-08-31
*/
#pragma once
#ifndef GUARD_7ce1b52c483d41e0be728a257d077ef8
#define GUARD_7ce1b52c483d41e0be728a257d077ef8
#include "../InputLayout.h"
namespace temp {
namespace graphics {
namespace opengl {
class InputLayoutOpenGL : public InputLayoutBase<InputLayoutOpenGL> {
friend class DeviceOpenGLBase;
typedef InputLayoutBase<InputLayoutOpenGL> Super;
private:
InputLayoutOpenGL(const InputElementDesc *descs, Size elementCount, const ShaderObjectPtr &spShaderObject);
};
}
}
}
#endif // GUARD_7ce1b52c483d41e0be728a257d077ef8
<file_sep>/**
* @file Device.h
* @brief
* @author tsukushibito
* @version 0.0.1
* @date 2015-04-01
*/
#pragma once
#ifndef GUARD_c5cfa361f4c7496ab0d0d2f8c3e98dac
#define GUARD_c5cfa361f4c7496ab0d0d2f8c3e98dac
#include "GraphicsCommon.h"
#include "Define.h"
namespace temp {
namespace graphics {
template <class T>
class DeviceBase : temp::Castable<T>, public temp::ReferenceObject {
public:
ContextPtr getContext() const {
return Castable<T>::derive()->getContext();
}
ViewPtr getView() const {
return Castable<T>::derive()->createView();
}
RenderTargetPtr createRenderTarget(const RenderTargetDesc &desc) {
return Castable<T>::derive()->createRenderTarget(desc);
}
DepthStencilPtr createDepthStencil(const DepthStencilDesc &desc) {
return Castable<T>::derive()->createDepthStencil(desc);
}
IndexBufferPtr createIndexBuffer(const IndexBufferDesc &desc,
const void *pData) {
return Castable<T>::derive()->createIndexBuffer(desc, pData);
}
VertexBufferPtr createVertexBuffer(const VertexBufferDesc &desc,
const void *pData) {
return Castable<T>::derive()->createVertexBuffer(desc, pData);
}
ShaderObjectPtr createShaderObjectFromBinary(
const void *pVertexShaderBinaryCode, Size vertexShaderBinaryCodeSize,
const void *pPixelShaderBinaryCode, Size pixelShaderBinaryCodeSize) {
return Castable<T>::derive()->createShaderObjectFromBinary(
pVertexShaderBinaryCode, vertexShaderBinaryCodeSize,
pPixelShaderBinaryCode, pixelShaderBinaryCodeSize);
}
ShaderObjectPtr createShaderObjectFromSource(
const void *pVertexShaderSourceCode, Size vertexShaderSourceCodeSize,
const void *pPixelShaderSourceCode, Size pixelShaderSourceCodeSize) {
return Castable<T>::derive()->createShaderObjectFromSource(
pVertexShaderSourceCode, vertexShaderSourceCodeSize,
pPixelShaderSourceCode, pixelShaderSourceCodeSize);
}
InputLayoutPtr createInputLayout(const InputElementDesc *descs,
Size elementCount,
const ShaderObjectPtr &spShaderObject) {
return Castable<T>::derive()->createInputLayout(descs, elementCount,
spShaderObject);
}
BlendStatePtr createBlendState(const BlendDesc &desc) {
return Castable<T>::derive()->createBlendState(desc);
}
DepthStencilStatePtr createDepthStencilState(
const DepthStencilStateDesc &desc) {
return Castable<T>::derive()->createDepthStencilState(desc);
}
RasterizerStatePtr createRasterizerState(const RasterizerDesc &desc) {
return Castable<T>::derive()->createRasterizerState(desc);
}
SamplerStatePtr createSamplerState(const SamplerDesc &desc) {
return Castable<T>::derive()->createSamplerState(desc);
}
};
}
}
#endif // GUARD_c5cfa361f4c7496ab0d0d2f8c3e98dac
<file_sep>/**
* @file RasterizerStateOpenGL.h
* @brief OpenGL版ラスタライザステート
* @author tsukushibito
* @version 0.0.1
* @date 2015-04-01
*/
#pragma once
#ifndef GUARD_f9cc642ceea54bc082a51ce8856f4144
#define GUARD_f9cc642ceea54bc082a51ce8856f4144
#include "../RasterizerState.h"
#include "../Define.h"
namespace temp {
namespace graphics {
namespace opengl {
class RasterizerStateOpenGL
: public temp::graphics::RasterizerStateBase<RasterizerStateOpenGL> {
friend class DeviceOpenGLBase;
typedef temp::graphics::RasterizerStateBase<RasterizerStateOpenGL>
Super;
private:
RasterizerStateOpenGL(const RasterizerDesc &desc) : Super(desc) {}
};
}
}
}
#endif // GUARD_f9cc642ceea54bc082a51ce8856f4144
<file_sep>/**
* @file RasterizerState.h
* @brief ラスタライザステート
* @author tsukushibito
* @version 0.0.1
* @date 2015-04-01
*/
#pragma once
#ifndef GUARD_35585a9c7c8e457aa8f22fc3aad6bd9b
#define GUARD_35585a9c7c8e457aa8f22fc3aad6bd9b
#include "GraphicsCommon.h"
namespace temp {
namespace graphics {
template <class T>
class RasterizerStateBase : temp::Castable<T>, public temp::ReferenceObject {
public:
explicit RasterizerStateBase(const RasterizerDesc &desc) : desc_(desc) {}
RasterizerDesc getDesc() const { return desc_; }
private:
RasterizerDesc desc_;
};
}
}
#endif // GUARD_35585a9c7c8e457aa8f22fc3aad6bd9b
<file_sep>#include <Tempura.h>
#include <iostream>
#include <memory>
#include <fstream>
#include "../Source/Tempura.h"
#include "../Source/System/Application.h"
#include "../Source/Graphics/Graphics.h"
#include "../Source/System/ThreadPool.h"
#include "../Source/System/Logger.h"
class TestGraphicsManager : public temp::Singleton<TestGraphicsManager> {
public:
void initialize(const temp::system::Window &window) {
spDevice_ = temp::graphics::DevicePtr(new temp::graphics::Device(window.getViewHandle()));
spContext_ = spDevice_->getContext();
spView_ = spDevice_->getView();
}
void terminate() {
}
temp::graphics::Device &getDevice() { return *spDevice_; }
temp::graphics::Context &getContext() { return *spContext_; }
temp::graphics::View &getView() { return *spView_; }
private:
temp::graphics::DevicePtr spDevice_;
temp::graphics::ContextPtr spContext_;
temp::graphics::ViewPtr spView_;
};
void applicationTest() {
using namespace temp;
using namespace temp::system;
using namespace temp::graphics;
ConsoleLogger::initialize();
Window window;
// temp::graphics::Device device;
// pContext = device.getContext();
// pView = device.createView(window);
Sleep(100);
TestGraphicsManager::getInstance().initialize(window);
Device &device = TestGraphicsManager::getInstance().getDevice();
Context &context = TestGraphicsManager::getInstance().getContext();
View &view = TestGraphicsManager::getInstance().getView();
ShaderObjectPtr spShaderObject;
std::ifstream ifs("../Shader/test_glsl.vert", std::ios::binary);
std::string vertexShaderCode, pixelShaderCode;
if(!ifs.fail()) {
std::istreambuf_iterator<char> beg(ifs);
std::istreambuf_iterator<char> end;
vertexShaderCode = std::string(beg, end);
}
else {
// debugLog("not found vert file!");
}
ifs.close();
ifs.open("../Shader/test_glsl.frag", std::ios::binary);
if(!ifs.fail()) {
std::istreambuf_iterator<char> beg(ifs);
std::istreambuf_iterator<char> end;
pixelShaderCode = std::string(beg, end);
}
else{
// debugLog("not found frag file!");
}
ifs.close();
spShaderObject = device.createShaderObjectFromSource(vertexShaderCode.c_str(), vertexShaderCode.size(), pixelShaderCode.c_str(), pixelShaderCode.size());
temp::system::ThreadPool threadPool(4);
auto testFunc = [&threadPool, &context, &view](){
static Float32 red = 0.f;
context.clearRenderTarget(nullptr, temp::Color(red, 0.1f, 0.5f, 1.0f));
red += 0.001f;
view.present();
};
Application::getInstance().setMainLoopFunc(testFunc);
Application::getInstance().run();
TestGraphicsManager::getInstance().terminate();
ConsoleLogger::terminate();
}
int main(int argc, const char * argv[])
{
applicationTest();
// TestTlsfAllocator::execute();
return 0;
}
<file_sep>/**
* @file DeviceOpenGLMac.h
* @brief
* @author tsukushibito
* @version 0.0.1
* @date 2015-03-22
*/
#pragma once
#ifndef GUARD_b69d722fb1f1418da569d75581a712b5
#define GUARD_b69d722fb1f1418da569d75581a712b5
#include "../../../TempuraCommon.h"
#if defined TEMP_PLATFORM_MAC
#include "../../Define.h"
#include "../../Device.h"
#include "../DeviceOpenGLBase.h"
namespace temp {
namespace graphics {
namespace opengl {
namespace mac {
class DeviceOpenGLMac : public DeviceOpenGLBase {
public:
DeviceOpenGLMac(const system::ViewHandle &viewHandle);
~DeviceOpenGLMac();
private:
void *pNativeContext_;
};
}
}
}
}
#endif
#endif // GUARD_b69d722fb1f1418da569d75581a712b5
<file_sep>#include "../../GraphicsCommon.h"
#include "ViewOpenGLWindows.h"
#if defined TEMP_PLATFORM_WINDOWS
#include "../BackBufferOpenGL.h"
namespace temp {
namespace graphics {
namespace opengl {
namespace windows {
ViewOpenGLWindows::ViewOpenGLWindows(HDC hdc)
: hdc_(hdc) {
Texture2DDesc desc;
pBackBuffer_ = new BackBuffer(0, desc);
}
void ViewOpenGLWindows::present() {
SwapBuffers(hdc_);
}
}
}
}
}
#endif
<file_sep>/**
* @file ShaderObjectOpenGL.h
* @brief OpenGL版シェーダオブジェクト
* @author tsukushibito
* @version 0.0.1
* @date 2015-09-15
*/
#pragma once
#ifndef GUARD_cb0e40b5e631433fa9a4b1bd02a3ae17
#define GUARD_cb0e40b5e631433fa9a4b1bd02a3ae17
#include "../ShaderObject.h"
#include "../Define.h"
namespace temp {
namespace graphics {
namespace opengl {
class ShaderObjectOpenGL
: public temp::graphics::ShaderObjectBase<ShaderObjectOpenGL> {
friend class DeviceOpenGLBase;
typedef temp::graphics::ShaderObjectBase<ShaderObjectOpenGL> Super;
private:
ShaderObjectOpenGL(temp::UInt32 programHandle, temp::UInt32 vertexShaderHandle, temp::UInt32 pixelShaderHandle);
public:
~ShaderObjectOpenGL();
temp::UInt32 getProgramHandle() const { return programHandle_; }
temp::UInt32 getVertexShaderHandle() const { return vertexShaderHandle_; }
temp::UInt32 getPixelShaderHandle() const { return pixelShaderHandle_; }
private:
temp::UInt32 programHandle_;
temp::UInt32 vertexShaderHandle_;
temp::UInt32 pixelShaderHandle_;
};
}
}
}
#endif // GUARD_cb0e40b5e631433fa9a4b1bd02a3ae17
<file_sep>#include "../../TempuraCommon.h"
#ifdef TEMP_GRAPHICS_OPENGL
#include "RenderTargetOpenGL.h"
namespace temp {
namespace graphics {
namespace opengl {
RenderTargetOpenGL::RenderTargetOpenGL(temp::UInt32 handle,
const RenderTargetDesc &desc)
: Super(desc), handle_(handle) {}
}
}
}
#endif
<file_sep>import os
import re
import sys
import platform
argvs = sys.argv
if platform.system() != "Darwin":
reg = re.compile("\.(h|cpp)$")
else:
reg = re.compile("\.(h|cpp|mm)$")
def find_all_files(directory):
for root, dirs, files in os.walk(directory):
yield root
for file in files:
yield os.path.join(root, file)
for file in find_all_files(argvs[1]):
if reg.search(file):
print "'" + file + "'"
<file_sep>/**
* @file Allocator.h
* @brief アロケータ類ヘッダ
* @author tsukushibito
* @version 0.0.1
* @date 2014-11-09
*/
#pragma once
#ifndef GUARD_22751d91cf5e421ea82a6f3e9fdcc32f
#define GUARD_22751d91cf5e421ea82a6f3e9fdcc32f
#include "../TempuraCommon.h"
namespace temp {
namespace allocator {
enum AllocatorType {
TYPE_TLSF,
TYPE_POOL,
TYPE_STACK,
};
class Allocator : public temp::ReferenceObject {
public:
virtual ~Allocator() {}
virtual void *malloc(temp::Size size) = 0;
virtual void free(void *pointer) = 0;
virtual void defragment(temp::UInt32 step = 1) = 0;
};
struct CreateParams {
AllocatorType type_;
void *memoryPool_;
temp::Size poolSize_;
};
class AllocatorFactory : temp::Singleton<AllocatorFactory> {
friend class temp::Singleton<AllocatorFactory>;
private:
AllocatorFactory() {}
public:
Allocator *createAllocator(const CreateParams ¶ms);
};
template <typename T> struct AllocatorForSTL {
// 要素の型
using value_type = T;
// 特殊関数
// (デフォルトコンストラクタ、コピーコンストラクタ
// 、ムーブコンストラクタ)
AllocatorForSTL() {}
// 別な要素型のアロケータを受け取るコンストラクタ
template <class U> AllocatorForSTL(const AllocatorForSTL<U> &) {}
// メモリ確保
T *allocate(std::size_t n) { return static_cast<T*>(malloc(n * sizeof(T))); }
// メモリ解放
void deallocate(T *p, std::size_t n) {
static_cast<void>(n);
free(p);
}
};
// 比較演算子
template <class T, class U>
bool operator==(const AllocatorForSTL<T> &, const AllocatorForSTL<U> &) {
return true;
}
template <class T, class U>
bool operator!=(const AllocatorForSTL<T> &, const AllocatorForSTL<U> &) {
return false;
}
}
}
#endif // GUARD_22751d91cf5e421ea82a6f3e9fdcc32f
<file_sep>{
'target_defaults': {
'configurations': {
'Debug': {
'msvs_configuration_platform': 'x64',
'msvs_target_platform': 'x64',
'msvs_settings': {
'VCCLCompilerTool': {
'DebugInformationFormat': '3', # /Zi
'Optimization': '0',
},
'VCLinkerTool': {
'GenerateDebugInformation': 'true', # /DEBUG
},
},
'xcode_settings': {
'GCC_OPTIMIZATION_LEVEL': '0',
'CLANG_CXX_LANGUAGE_STANDARD': 'c++0x',
'MACOSX_DEPLOYMENT_TARGET': '10.8',
},
},
'Release': {
'msvs_configuration_platform': 'x64',
'msvs_target_platform': 'x64',
},
},
'default_configuration': 'Debug',
#'default_configuration': 'Release',
},
}
<file_sep>/**
* @file DepthStencil.h
* @brief 深度ステンシルバッファ
* @author tsukushibito
* @version 0.0.1
* @date 2015-03-18
*/
#pragma once
#ifndef GUARD_0296ffae5be34257996fb5416fca332a
#define GUARD_0296ffae5be34257996fb5416fca332a
#include "GraphicsCommon.h"
namespace temp {
namespace graphics {
template <class T>
class DepthStencilBase : temp::Castable<T>, public temp::ReferenceObject {
public:
explicit DepthStencilBase(const DepthStencilDesc &desc) : desc_(desc) {}
DepthStencilDesc getDesc() const { return desc_; }
private:
DepthStencilDesc desc_;
};
}
}
#endif // GUARD_0296ffae5be34257996fb5416fca332a
<file_sep>/**
* @file AllocatorCommon.h
* @brief アロケータ共通ヘッダ
* @author tsukushibito
* @version 0.0.1
* @date 2014-12-05
*/
#pragma once
#ifndef GUARD_c94e8e2f810341af83bf5f9630c6edd8
#define GUARD_c94e8e2f810341af83bf5f9630c6edd8
#if defined(__alpha__) || defined(__ia64__) || defined(__x86_64__) || \
defined(_WIN64) || defined(__LP64__) || defined(__LLP64__)
#define TEMP_ALLOCATOR_64BIT
#endif
namespace temp {
namespace allocator {
#ifdef TEMP_ALLOCATOR_64BIT
typedef Int64 Int;
typedef UInt64 UInt;
#else
typedef Int32 Int;
typedef UInt32 UInt;
#endif
}
}
#endif // GUARD_c94e8e2f810341af83bf5f9630c6edd8
<file_sep>/**
* @brief グラフィックス共通
* @author tsukushibito
* @version 0.0.1
* @date 2015-03-04
*/
#pragma once
#ifndef GUARD_780cbe2b4bad43b58bb9aa398e760e5f
#define GUARD_780cbe2b4bad43b58bb9aa398e760e5f
#include "../TempuraCommon.h"
#include "../Container.h"
namespace temp {
namespace graphics {
/**
* @brief クリアフラグ
*/
enum class CLEAR_FLAG {
DEPTH = 1 << 0,
STENCIL = 1 << 1,
DEPTH_STENCIL = DEPTH & STENCIL,
};
/**
* @brief テクスチャフォーマット
*/
enum class TEXTURE_FORMAT {
R8G8B8A8,
R16G16B16A16F,
UNKNOWN,
};
/**
* @brief レンダーターゲットフォーマット
*/
enum class RENDER_TARGET_FORMAT {
R8G8B8A8,
R16G16B16A16F,
UNKNOWN,
};
/**
* @brief 深度ステンシルフォーマット
*/
enum class DEPTH_STENCIL_FORMAT {
D16,
D24_S8,
D32F,
D32F_S8X24,
S8,
UNKNOWN,
};
/**
* @brief インデックスバッファフォーマット
*/
enum class INDEX_BUFFER_FORMAT {
UINT16,
UINT32,
UNKNOWN,
};
/**
* @brief 入力要素フォーマット
*/
enum class INPUT_ELEMENT_FORMAT {
BYTE1,
BYTE2,
BYTE3,
BYTE4,
SHORT1,
SHORT2,
SHORT3,
SHORT4,
INT1,
INT2,
INT3,
INT4,
FLOAT1,
FLOAT2,
FLOAT3,
FLOAT4,
UNSIGNED_BYTE1,
UNSIGNED_BYTE2,
UNSIGNED_BYTE3,
UNSIGNED_BYTE4,
UNSIGNED_SHORT1,
UNSIGNED_SHORT2,
UNSIGNED_SHORT3,
UNSIGNED_SHORT4,
UNSIGNED_INT1,
UNSIGNED_INT2,
UNSIGNED_INT3,
UNSIGNED_INT4,
};
/**
* @brief 比較関数
*/
enum class COMPARISON_FUNC {
NERVER,
LESS,
EQUAL,
LESS_EQUAL,
GREATER,
NOT_EQUAL,
GREATER_EQUAL,
ALWAYS,
};
/**
* @brief ステンシル演算方法
*/
enum class STENCIL_OP {
KEEP,
ZERO,
REPLACE,
INCR_SAT,
DECR_SAT,
INVERT,
INCR,
DECR,
};
/**
* @brief ブレンドターゲット
*/
enum class BLEND {
ZERO,
ONE,
SRC_COLOR,
INV_SRC_COLOR,
SRC_ALPHA,
INV_SRC_ALPHA,
DEST_ALPHA,
INV_DEST_ALPHA,
DEST_COLOR,
INV_DEST_COLOR,
SRC_ALPHA_SAT,
BLEND_FACTOR,
INV_BLEND_FACTOR,
SRC1_COLOR,
INV_SRC1_COLOR,
SRC1_ALPHA,
INV_SRC1_ALPHA,
};
/**
* @brief ブレンド方法
*/
enum class BLEND_OP {
ADD,
SUBTRACT,
REV_SUBTRACT,
MIN,
MAX,
};
/**
* @brief フィルモード
*/
enum class FILL_MODE {
WIREFRAME,
SOLID,
};
/**
* @brief カリングモード
*/
enum class CULL_MODE {
NONE,
FRONT,
BACK,
};
/**
* @brief フィルタータイプ
*/
enum class FILTER {
MIN_MAG_MIP_POINT,
MIN_MAG_POINT_MIP_LINEAR,
MIN_POINT_MAG_LINEAR_MIP_POINT,
MIN_POINT_MAG_MIP_LINEAR,
MIN_LINEAR_MAG_MIP_POINT,
MIN_LINEAR_MAG_POINT_MIP_LINEAR,
MIN_MAG_LINEAR_MIP_POINT,
MIN_MAG_MIP_LINEAR,
ANISOTROPIC,
COMPARISON_MIN_MAG_MIP_POINT,
COMPARISON_MIN_MAG_POINT_MIP_LINEAR,
COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT,
COMPARISON_MIN_POINT_MAG_MIP_LINEAR,
COMPARISON_MIN_LINEAR_MAG_MIP_POINT,
COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR,
COMPARISON_MIN_MAG_LINEAR_MIP_POINT,
COMPARISON_MIN_MAG_MIP_LINEAR,
COMPARISON_ANISOTROPIC,
TEXT_1BIT,
};
/**
* @brief テクスチャアドレスモード
*/
enum class TEXTURE_ADDRESS_MODE {
WRAP,
MIRROR,
CLAMP,
BORDER,
MIRROR_ONCE,
};
/**
* @brief テクスチャ2D設定
*/
struct Texture2DDesc {
UInt32 width_;
UInt32 height_;
UInt32 mipLevels_;
TEXTURE_FORMAT format_;
};
/**
* @brief レンダーターゲット設定
*/
struct RenderTargetDesc {
UInt32 width_;
UInt32 height_;
RENDER_TARGET_FORMAT format_;
};
/**
* @brief 深度ステンシル設定
*/
struct DepthStencilDesc {
UInt32 width_;
UInt32 height_;
DEPTH_STENCIL_FORMAT format_;
};
/**
* @brief 深度ステンシル演算設定
*/
struct DepthStencilOpDesc {
STENCIL_OP stencilFailOp_;
STENCIL_OP stencilDepthFailOp_;
STENCIL_OP stencilPassOp_;
COMPARISON_FUNC stencilFunc_;
};
/**
* @brief 頂点バッファ設定
*/
struct VertexBufferDesc {
UInt32 size_;
};
/**
* @brief インデックスバッファ設定
*/
struct IndexBufferDesc {
UInt32 size_;
INDEX_BUFFER_FORMAT format_;
};
/**
* @brief 入力レイアウト設定
*/
struct InputElementDesc {
String semanticName_;
UInt32 semanticIndex_;
INPUT_ELEMENT_FORMAT format_;
UInt32 inputSlot_;
UInt32 byteOffset_;
};
/**
* @brief 深度ステンシルステート設定
*/
struct DepthStencilStateDesc {
Bool depthEnable_;
Bool depthWriteEnable_;
COMPARISON_FUNC comparisonFunc_;
Bool stencilEnable_;
UInt8 stencilReadMask_;
UInt8 stendilWriteMask_;
DepthStencilOpDesc frontFaceOp_;
DepthStencilOpDesc backFaceOp_;
};
/**
* @brief レンダーターゲットブレンド設定
*/
struct RenderTargetBlendDesc {
Bool blendEnable_;
BLEND srcBlend_;
BLEND destBlend_;
BLEND_OP blendOp_;
BLEND_OP srcBlendAlpha_;
BLEND_OP destBlendAlpha_;
BLEND_OP blendOpAlpha_;
UInt8 renderTargetWriteMask_;
};
/**
* @brief ブレンド設定
*/
struct BlendDesc {
Bool alphaToCoverageEnable_;
Bool independentBlendEnable_;
RenderTargetBlendDesc renderTargetBlendDesc[8];
};
/**
* @brief ラスタライザステート設定
*/
struct RasterizerDesc {
FILL_MODE fillMode_;
CULL_MODE cullMode_;
Bool frontCCW_;
Int32 depthBias_;
Float32 depthBiasClamp_;
Float32 slopeScaledDepthBias_;
Bool depthClipEnable_;
Bool scissorEnable_;
Bool multisampleEnable_;
Bool antialiasedLineEnable_;
};
/**
* @brief サンプラステート設定
*/
struct SamplerDesc {
FILTER filter_;
TEXTURE_ADDRESS_MODE addressU_;
TEXTURE_ADDRESS_MODE addressV_;
TEXTURE_ADDRESS_MODE addressW_;
Float32 mipLODBias_;
UInt32 maxAnisotropy_;
COMPARISON_FUNC comparisonFunc_;
Color borderColor_;
Float32 minLOD_;
Float32 maxLOD_;
};
}
}
#endif // GUARD_780cbe2b4bad43b58bb9aa398e760e5f
<file_sep>/**
* @file DeviceOpenGLWindows.h
* @brief
* @author tsukushibito
* @version 0.0.1
* @date 2015-03-22
*/
#pragma once
#ifndef GUARD_4f08a27170cb4021a8c04aa110b1b89c
#define GUARD_4f08a27170cb4021a8c04aa110b1b89c
#include "../DeviceOpenGLBase.h"
#if defined TEMP_PLATFORM_WINDOWS
#include <Windows.h>
namespace temp {
namespace system {
union ViewHandle;
}
namespace graphics {
namespace opengl {
namespace windows {
class DeviceOpenGLWindows : public DeviceOpenGLBase {
public:
DeviceOpenGLWindows(const system::ViewHandle &viewHandle);
~DeviceOpenGLWindows();
private:
HGLRC context_;
};
}
}
}
}
#endif
#endif // GUARD_4f08a27170cb4021a8c04aa110b1b89c
<file_sep>/**
* @file TestTlsfAllocator.h
* @brief TLSFアロケータテスト
* @author tsukushibito
* @version 0.0.1
* @date 2014-12-03
*/
#pragma once
#ifndef GUARD_7dec9b275ca54406a48d5505b919084e
#define GUARD_7dec9b275ca54406a48d5505b919084e
#include "../../source/Tempura.h"
#include <array>
#include <mutex>
class TestTlsfAllocator {
public:
static void execute() {
using namespace temp;
using namespace temp::allocator;
std::array<UInt32, 5> testDatas = { 127, 128, 255, 256, 257 };
for (auto i : testDatas) {
std::cout << "value = " << i
<< ", MSB = " << TlsfAllocator::evaluateMsb(i)
<< ", LSB = " << TlsfAllocator::evaluateLsb(i)
<< std::endl;
TlsfAllocator::FliAndSli fliAndSli =
TlsfAllocator::evaluateFliAndSli(i);
std::cout << "size = " << i << ", FLI = " << fliAndSli.fli_
<< ", SLI = " << fliAndSli.sli_ << std::endl;
}
std::mutex m;
size_t poolSize = 1024 * 1024 * 32;
size_t allocSize = 256;
const size_t COUNT = 100000;
void *p[COUNT] = {};
void *ptr = malloc(poolSize);
TlsfAllocator allocator(ptr, poolSize);
system::Timer timer;
timer.reset();
for (UInt32 i = 0; i < COUNT; ++i) {
m.lock();
p[i] = allocator.malloc(allocSize);
m.unlock();
}
for (UInt32 i = 0; i < COUNT; ++i) {
m.lock();
allocator.free(p[i]);
m.unlock();
}
std::cout << "tempura tlsf time:" << timer.microseconds() << std::endl;
free(ptr);
timer.reset();
for (UInt32 i = 0; i < COUNT; ++i) {
p[i] = malloc(allocSize);
}
for (UInt32 i = 0; i < COUNT; ++i) {
free(p[i]);
}
std::cout << "default time:" << timer.microseconds() << std::endl;
}
};
#endif // GUARD_7dec9b275ca54406a48d5505b919084e
| b2d27b51e9d5097011200710f733077c5bea17bf | [
"Markdown",
"Python",
"C",
"C++",
"Shell"
] | 78 | C++ | tsukushibito/TempuraEngine | 4c2761a488fabc17806dc42d81a1bd02f7739f4f | d33e6878459823651f5aa6b21f9fd0f1c7846d0d |
refs/heads/master | <repo_name>Qidong-Liu/TriATNE<file_sep>/TriATNE.py
import _pickle as cPickle
import random
import tensorflow as tf
import numpy as np
import utils as ut
import datetime
from eval.auc import AUC
from eval.ndcg import ndcg_at_K
from model import MODEL
from tqdm import tqdm
import settings as st
from eval.multilabel_class_cv import Cross_val
class TriATNE(object):
def __init__(self):
if st.App == 0:
self.nodes_contexts_train, self.nodes_set = ut.load_edgelist(st.TRAIN_INPUT_FILENAME)
else:
self.nodes_contexts_train, self.nodes_set = ut.load_edgelist(st.TRAIN_POS_FILENAME)
self.test_edges = np.loadtxt(st.TEST_POS_FILENAME, dtype=int)
self.test_edges_false = np.loadtxt(st.TEST_NEG_FILENAME, dtype=int)
self.model = None
self.build_model()
self.CNum = int(st.gama * len(self.nodes_set))
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
self.init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())
self.sess = tf.Session(config=config)
self.sess.run(self.init_op)
self.sess.graph.finalize()
def build_model(self):
if st.CP: #### continue training from the checkpoint
param_s = cPickle.load(open(st.S_MODEL_BEST_FILE, 'rb'))
param_p = cPickle.load(open(st.P_MODEL_BEST_FILE, 'rb'))
assert param_s is not None
assert param_p is not None
else: #### start a new train
param_s = None
param_p = None
self.model = MODEL(len(self.nodes_set)+1, st.FEATURE_SIZE, st.C_WEIGHT_DECAY, st.S_WEIGHT_DECAY, st.P_WEIGHT_DECAY, st.C_LEARNING_RATE, st.S_LEARNING_RATE, st.P_LEARNING_RATE, S_param=param_s, P_param=param_p)
def get_Pos(self, undirected=True):
walks = []
num = {}
rand = random.Random()
i = 0
while i < st.num_walks:
i += 1
for node in tqdm(self.nodes_contexts_train):
walk = [node]
walk.append(rand.choice(self.nodes_contexts_train[node]))
while len(walk) < st.walk_length:
cur = walk[-1]
if cur in self.nodes_contexts_train:
walk.append(rand.choice(self.nodes_contexts_train[cur]))
else:
break
walks.append(walk)
pos = []
pos_contexts = []
for walk in tqdm(walks):
index = 0
while index < len(walk):
source = walk[index]
left = max(0, index - st.window_size)
right = min(len(walk), index + st.window_size + 1)
if undirected:
targets = walk[left:index] + walk[index+1:right]
else:
targets = walk[index + 1:right]
if targets == []:
index += 1
continue
pos_contexts.extend(targets)
pos.extend([source]*len(targets))
if source in num:
num[source].extend(targets)
else:
num[source] = targets
index += 1
pos_labels = [1] * len(pos)
return list(zip(pos, pos_contexts, pos_labels)), num
def get_Neg(self, pos_Num):
negs=[]
nodes = []
for node in tqdm(pos_Num):
if node in self.nodes_contexts_train:
all_contexts = list(self.nodes_set - set(pos_Num[node]) - set(self.nodes_contexts_train[node]))
else:
all_contexts = list(self.nodes_set)
candidate_list = all_contexts
prob = self.sess.run(self.model.prob, feed_dict={self.model.u: [node] * len(candidate_list), self.model.v: candidate_list})
neg_list = np.random.choice(candidate_list, size= len(pos_Num[node]) * st.negatives, replace=True, p=prob)
negs.extend(neg_list)
nodes.extend([node]*len(neg_list))
labels = [0]*len(nodes)
return list(zip(nodes, negs, labels))
def evaluation(self):
if st.App == 0:
f1_micro, f1_macro = Cross_val(st.EMB_OUTPUT_FILENAME)
print('F1 (micro) = {}'.format(f1_micro))
print('F1 (macro) = {}'.format(f1_macro))
elif st.App == 1:
self.nodes_contexts_test, temp = ut.load_edgelist(st.TEST_POS_FILENAME)
auc_score = AUC(self.sess, self.model, self.test_edges, self.test_edges_false)
ndcg10 = ndcg_at_K(self.sess, self.model, self.nodes_contexts_test, self.nodes_contexts_train, self.nodes_set, k=10)
ndcg20 = ndcg_at_K(self.sess, self.model, self.nodes_contexts_test, self.nodes_contexts_train, self.nodes_set, k=20)
ndcg50 = ndcg_at_K(self.sess, self.model, self.nodes_contexts_test, self.nodes_contexts_train, self.nodes_set, k=50)
print("AUC:", auc_score)
print("ndcg10:", ndcg10, "ndcg20:", ndcg20, "ndcg50:", ndcg50)
else:
print('please reset App as 0 or 1!')
def train(self, verbose=True):
print('start adversarial training')
for epoch in range(st.train_epochs):
print('epoch: {}'.format(epoch))
[pos, num] = self.get_Pos()
neg = self.get_Neg(num)
train_data = pos + neg
train_size = len(train_data)
random.shuffle(train_data)
train_data = np.asarray(train_data)
for c_epoch in range(1):
s_c_loss = 0
index = 0
print('Train C: {}'.format(c_epoch))
while index < train_size:
if index + st.BATCH_SIZE <= train_size:
nodes, contexts, pred_data_label = ut.get_batch(train_data, index, st.BATCH_SIZE)
else:
nodes, contexts, pred_data_label = ut.get_batch(train_data, index, train_size - index)
index += st.BATCH_SIZE
c_loss, _ = self.sess.run(
[self.model.C_loss, self.model.C_updates],
feed_dict={self.model.u: nodes,
self.model.v: contexts,
self.model.pred_data_label: pred_data_label,
self.model.rate: st.rate})
s_c_loss = s_c_loss + c_loss
print('sum_loss: ', s_c_loss)
for p_epoch in range(1):
s_p_loss = 0
index = 0
print('Train P: {}'.format(p_epoch))
while index < train_size:
if index + st.BATCH_SIZE <= train_size:
nodes, contexts, pred_data_label = ut.get_batch(train_data, index, st.BATCH_SIZE)
else:
nodes, contexts, pred_data_label = ut.get_batch(train_data, index, train_size - index)
index += st.BATCH_SIZE
p_loss, _ = self.sess.run(
[self.model.P_loss, self.model.P_updates],
feed_dict={self.model.u: nodes,
self.model.v: contexts,
self.model.pred_data_label: pred_data_label,
self.model.rate: st.rate})
s_p_loss = s_p_loss + p_loss
print('sum_loss: ', s_p_loss)
# Train Seller
starttime = datetime.datetime.now()
for s_epoch in range(1):
s_s_loss = 0
s_p = 0
s_r = 0
all_list = list(self.nodes_set)
random.shuffle(all_list)
for node in all_list:
candidate_list = np.random.choice(list(self.nodes_set), size=self.CNum, replace=False, p=None)
prob = self.sess.run(self.model.prob, feed_dict={self.model.u: [node] * len(candidate_list), self.model.v: candidate_list})
choose_index = np.random.choice(range(len(candidate_list)), size=st.NNum, p=prob)
choose_index = np.asarray(choose_index)
p, r, s_loss, _, = self.sess.run(
[self.model.gan_prob, self.model.reward, self.model.s1_loss, self.model.S_updates],
feed_dict={self.model.u: [node]*len(candidate_list),
self.model.v: candidate_list,
self.model.sample_index: choose_index})
s_s_loss = s_s_loss + s_loss
s_p = s_p + np.sum(np.log(p))
s_r = s_r + np.sum(r)
print('s_loss', s_s_loss, 's_p', s_p, 's_r', s_r)
endtime = datetime.datetime.now()
print('S-TIME:',(endtime-starttime).seconds)
#########write embedding to file ###############
if epoch % 1 == 0:
index = 0
while index < train_size:
if index + st.BATCH_SIZE <= train_size:
nodes, contexts, pred_data_label = ut.get_batch(train_data, index, st.BATCH_SIZE)
else:
nodes, contexts, pred_data_label = ut.get_batch(train_data, index, train_size - index)
index += st.BATCH_SIZE
_ = self.sess.run([self.model.F_updates],
feed_dict={self.model.u: nodes,
self.model.v: contexts,
self.model.pred_data_label: pred_data_label,
self.model.rate: st.rate})
ut.write_to_file(self.sess, self.model, st.EMB_OUTPUT_FILENAME, st.FEATURE_SIZE, list(self.nodes_set), tag=1)
ut.write_to_file(self.sess, self.model, st.CONTEXT_OUTPUT_FILENAME, st.FEATURE_SIZE, list(self.nodes_set), tag=0)
self.model.save_model(self.sess, st.S_MODEL_BEST_FILE, 0)
self.model.save_model(self.sess, st.P_MODEL_BEST_FILE, 1)
if verbose:
self.evaluation()
self.sess.close()
if __name__ == '__main__':
if st.split:
ut.split_data(st.FULL_FILENAME, st.TRAIN_POS_FILENAME, st.TRAIN_NEG_FILENAME, st.TEST_POS_FILENAME, st.TEST_NEG_FILENAME, st.test_frac)
model = TriATNE()
model.train()
<file_sep>/model.py
import tensorflow as tf
import _pickle as cPickle
class MODEL():
def __init__(self, Num, feature_size, C_weight_decay, S_weight_decay, P_weight_decay, C_learning_rate, S_learning_rate, P_learning_rate, initdelta=0.05, S_param=None, P_param=None):
self.p_params = []
self.s_params = []
self.c_params = []
self.u = tf.compat.v1.placeholder(tf.int32, shape=[None], name='u')
self.v = tf.compat.v1.placeholder(tf.int32, shape=[None], name='v')
self.pred_data_label = tf.compat.v1.placeholder(tf.float32, shape=[None], name="pred_data_label")
self.sample_index = tf.compat.v1.placeholder(tf.int32, shape=[None], name='sample_index')
self.rate = tf.compat.v1.placeholder(tf.float32)
with tf.variable_scope('customer'):
C_W_1 = tf.get_variable('C_weight_1', [feature_size, 128],
initializer=tf.truncated_normal_initializer(mean=1.0, stddev=0.4, seed=0))
self.C_W_2 = tf.get_variable('C_weight_2', [128, 1],
initializer=tf.random_uniform_initializer(minval=0.0, maxval=1.0, seed=0))
self.c_params.append(self.C_W_2)
self.soft_CW2 = tf.reshape(tf.nn.softmax(tf.reshape(self.C_W_2, [1, -1])), [-1, 1])
with tf.variable_scope('producer'):
if P_param == None:
self.node_embedding = tf.compat.v1.get_variable('N_embedd', [Num + 1, feature_size],
initializer=tf.random_uniform_initializer(
minval=-initdelta, maxval=initdelta))
self.context_embedding = tf.compat.v1.get_variable('parameters', [Num + 1, feature_size],
initializer=tf.random_uniform_initializer(
minval=-initdelta, maxval=initdelta))
else:
self.node_embedding = tf.Variable(P_param[0])
self.context_embedding = tf.Variable(P_param[1])
self.p_params.append(self.node_embedding)
self.p_params.append(self.context_embedding)
with tf.variable_scope('seller'):
if S_param == None:
self.W_1 = tf.get_variable('weight_1', [feature_size, feature_size],
initializer=tf.truncated_normal_initializer(mean=1.0, stddev=0.05))
self.W_2 = tf.get_variable('weight_2', [feature_size, 1],
initializer=tf.truncated_normal_initializer(mean=1.0, stddev=0.05))
self.b_1 = tf.get_variable('b_1', [feature_size], initializer=tf.constant_initializer(0.0))
self.b_2 = tf.get_variable('b_2', [1], initializer=tf.constant_initializer(0.0))
else:
self.W_1 = tf.Variable(S_param[0])
self.W_2 = tf.Variable(S_param[1])
self.b_1 = tf.Variable(S_param[2])
self.b_2 = tf.Variable(S_param[3])
self.s_params.append(self.W_1)
self.s_params.append(self.W_2)
self.s_params.append(self.b_1)
self.s_params.append(self.b_2)
self.u_embedding = tf.nn.embedding_lookup(self.node_embedding, self.u) # look up u's embedding
self.v_embedding = tf.nn.embedding_lookup(self.context_embedding, self.v) # look up v's embedding, mark
self.u_sample_embedding = tf.gather(self.u_embedding, self.sample_index)
self.v_sample_embedding = tf.gather(self.v_embedding, self.sample_index)
#self.u_embedding_comp = tf.cast(self.u_embedding, dtype=tf.complex64)
#self.v_embedding_comp = tf.cast(self.v_embedding, dtype=tf.complex64)
#self.ccorr = tf.math.real(tf.signal.ifft(tf.math.conj(tf.fft(self.u_embedding_comp)) * tf.fft(self.v_embedding_comp)))
self.ccorr = self.u_embedding * self.v_embedding
#self.u_sample_embedding_comp = tf.cast(self.u_sample_embedding, dtype=tf.complex64)
#self.v_sample_embedding_comp = tf.cast(self.v_sample_embedding, dtype=tf.complex64)
#self.sample_ccorr = tf.math.real(tf.signal.ifft(tf.math.conj(tf.signal.fft(self.u_sample_embedding_comp)) * tf.signal.fft(self.v_sample_embedding_comp)))
self.sample_ccorr = self.u_sample_embedding * self.v_sample_embedding
C_layer1 = tf.matmul(self.ccorr, C_W_1)
C_drop_out = tf.nn.dropout(C_layer1, rate=self.rate)
R_layer1 = tf.matmul(self.sample_ccorr, C_W_1)
self.P_logits = tf.reshape(tf.matmul(C_drop_out, self.soft_CW2), [-1])
self.P_pred_score = tf.reshape(tf.reduce_sum(self.ccorr, 1), [-1]) #for test
self.S_pred_score = tf.reshape(tf.nn.sigmoid(tf.nn.xw_plus_b(tf.nn.tanh(tf.nn.xw_plus_b(self.ccorr, self.W_1, self.b_1)), self.W_2, self.b_2)), [-1])
self.reward = tf.reshape(tf.log(tf.exp(tf.matmul(R_layer1, self.soft_CW2)) + 1), [-1])
#self.reward = (tf.sigmoid(tf.matmul(R_layer1, C_W_2)) - 0.5) * 2
self.prob = tf.nn.softmax(self.S_pred_score)
self.gan_prob = tf.gather(self.prob, self.sample_index)
self.p1_loss = tf.reduce_sum(tf.nn.sigmoid_cross_entropy_with_logits(logits=self.P_logits, labels=self.pred_data_label))
self.p2_loss = P_weight_decay * (tf.nn.l2_loss(self.u_embedding) + tf.nn.l2_loss(self.v_embedding))
self.P_loss = self.p1_loss + self.p2_loss
self.F_loss = tf.reduce_sum(tf.nn.sigmoid_cross_entropy_with_logits(logits=self.P_pred_score, labels=self.pred_data_label)) + self.p2_loss
self.s1_loss = -tf.reduce_mean(tf.log(self.gan_prob) * self.reward)
self.s2_loss = S_weight_decay * (tf.nn.l2_loss(self.W_1) + tf.nn.l2_loss(self.W_2)
+ tf.nn.l2_loss(self.b_1) + tf.nn.l2_loss(self.b_2))
self.S_loss = self.s1_loss + self.s2_loss
self.C_logits = tf.reshape(tf.matmul(C_drop_out, self.soft_CW2), [-1])
self.C_loss = -tf.reduce_sum(tf.nn.sigmoid_cross_entropy_with_logits(logits=self.C_logits, labels=self.pred_data_label)) + C_weight_decay * tf.nn.l2_loss(self.C_W_2)
C_optimizer = tf.train.GradientDescentOptimizer(C_learning_rate)
self.C_updates = C_optimizer.minimize(self.C_loss, var_list=self.c_params)
with tf.control_dependencies([self.C_updates]):
self.clip_w = tf.assign(self.C_W_2, tf.clip_by_value(self.C_W_2, 0.0, 1.0))
#self.S_optimizer = tf.train.AdamOptimizer(S_learning_rate)
self.S_optimizer = tf.train.GradientDescentOptimizer(S_learning_rate)
self.S_updates = self.S_optimizer.minimize(self.S_loss, var_list=self.s_params)
self.P_optimizer = tf.train.AdamOptimizer(P_learning_rate)
self.P_updates = self.P_optimizer.minimize(self.P_loss, var_list=self.p_params)
self.F_updates = self.P_optimizer.minimize(self.F_loss, var_list=self.p_params)
def save_model(self, sess, filename, tag=1):
param = None
if tag == 1:
param = sess.run(self.p_params)
elif tag == 0:
param = sess.run(self.s_params)
else:
print('tag should be 0 or 1')
cPickle.dump(param, open(filename, 'wb'))
<file_sep>/README.md
# TriATNE
Source code for paper "TriATNE: Tripartite Adversarial Training for Network Embeddings"
## Requirements
The code has been tested under Python 3.7.5, with the following packages installed (along with their dependencies):
- tensorflow == 1.14.0
- gensim == 3.8.0
- networkx == 2.4
- numpy = 1.17.4
- scikit-learn == 0.21.3
- scipy == 1.3.1
- tqdm = 4.39.0 (for displaying the progress bar)
## Files in the folder
- **\data:** Store the example inputs.
- **\emb:** Store the learned embeddings.
- **\eval:** Store the evaluation scripts for different metric.
- **\model:** Store the trained models.
- **model.py:** Define each modules of the model.
- **PRE.py:** Train-test split for link prediction.
- **settings.py:** Defines different hyperparameters here.
- **TriATNE.py:** The main entrance of running.
- **utils.py:** Codes to load data, split data, prepare batches for training and write embeddings to files.
## Data
(1) TriATNE expect an edgelist for the input network, i.e.,
>node1 node2 1
>node1 node3 1
>...
Each row contains two IDs, which are separated by '\t'
(2) Two formats are supported for the input labels. By setting format = 'cora' , we expect a node with multi-labels:
>/label1/label2/label3/
>/label1/label5/
>...
The node ID defaults to line number and starts from 0 to N−1 (N is the number of nodes in the graph)
By setting format = 'blogcat', we expect a node with single label:
>node1 label1
>node2 label1
>...
>nodeN label5
The first column is the node’s ID. The second column is the label of corresponding node. They are separated by'\t'.
(3) The output embeddings are as follows:
>N d
>node1 f1 f2 ... fd
>node2 f1 f2 ... fd
>...
>nodeN f1 f2 ... fd
where N denotes the number of nodes and d denotes the embeddings' dimension. Each subsequent row represents a node.
## Basic usage
### Classification
We take the Citeseer dataset as an exampleand show how to perform classification tasks for TriATNE:
(1) Modify the following parameters in settings.py:
>TRAIN_INPUT_FILENAME = '/data/Citeseer_input.txt'
>TRAIN_LABEL_FILENAME ='/data/Citeseer_label.txt'
>format ='blogcat'APP = 0
(2) Run the code by:
```python TriATNE.py```
(3) The learned embeddings will be stored in /emb/, and the evaluation results (micro F1 and macro F1) for embeddings will be printed on the screen for each epoch.
### Link Prediction
We take the wiki-vote dataset as an exampleand show how to perform link prediction tasks for TriATNE:
(1) If you have split the dataset, please move directly to step 2. Otherwise, modify the following parameters in settings.py:
>APP = 1
>split = True
>test_frac = 0.2
>FULL_FILENAME = '/data/wiki-vote.txt'
>TRAIN_POS_FILENAME = '/data/wiki_train_pos.txt'
>TRAIN_NEG_FILENAME = '/data/wiki_train_neg.txt'
>TEST_POS_FILENAME = '/data/wiki_test_pos.txt'
>TEST_NEG_FILENAME = '/data/wiki_test_neg.txt'
Note that splitting data can take a long time. Therefore, we recommend storing the divided data for later use.
(2) If you have finished parameter setting in step 1, skip to step 3. Otherwise, modify the following parameters in setting.py:
>APP = 1
>split = False
>TRAIN_POS_FILENAME = '/data/wiki_train_pos.txt'
>TEST_POS_FILENAME = '/data/wiki_test_pos.txt'
>TEST_NEG_FILENAME = '/data/wiki_test_neg.txt'
(3) Run the code by:
```python TriATNE.py```
(4) The learned embeddings will be stored in /emb/, and the evaluation results (AUC and NDCG@k) for embeddings will be printed on the screen for each epoch.
<file_sep>/PRE.py
import numpy as np
import networkx as nx
# Perform train-test split
# Takes in adjacency matrix in sparse format
# Returns: adj_train, train_edges, val_edges, val_edges_false,
# test_edges, test_edges_false
def mask_test_edges(g, test_frac=.1, prevent_disconnect=True, verbose=False):
# NOTE: Splits are randomized and results might slightly deviate from reported numbers in the paper.
if verbose == True:
print('preprocessing...')
orig_num_cc = nx.number_connected_components(g.to_undirected())
edges = g.edges()
num_test = int(np.floor(len(edges) * test_frac))
edge_tuples = [(edge[0], edge[1], g[edge[0]][edge[1]]['weight']) for edge in edges]
all_edge_tuples = set(edge_tuples)
train_edges = set(edge_tuples) # initialize train_edges to have all edges
test_edges = set()
if verbose == True:
print('generating test/val sets...')
# Iterate over shuffled edges, add to train/val sets
np.random.shuffle(edge_tuples)
for edge in edge_tuples:
# print edge
node1 = edge[0]
node2 = edge[1]
# If removing edge would disconnect a connected component, backtrack and move on
ww = g[node1][node2]['weight']
g.remove_edge(node1, node2)
if prevent_disconnect == True:
if nx.number_connected_components(g.to_undirected()) > orig_num_cc:
g.add_edge(node1, node2, weight = ww)
continue
# Fill test_edges first
if len(test_edges) < num_test:
test_edges.add(edge)
train_edges.remove(edge)
# Both edge lists full --> break loop
elif len(test_edges) == num_test:
break
if (len(test_edges) < num_test):
print("WARNING: not enough removable edges to perform full train-test split!")
print("Num. test edges requested: (", num_test, ")")
print("Num. test edges returned: (", len(test_edges), ")")
if prevent_disconnect == True:
assert nx.number_connected_components(g.to_undirected()) == orig_num_cc
if verbose == True:
print('creating false test edges...')
test_edges_false = set()
while len(test_edges_false) < num_test:
idx_i, idx_j = np.random.choice(g.nodes(), size=2, replace=False)
false_edge = (idx_i, idx_j, 0)
# Make sure false_edge not an actual edge, and not a repeat
if false_edge in all_edge_tuples:
continue
if false_edge in test_edges_false:
continue
test_edges_false.add(false_edge)
if verbose == True:
print('creating false train edges...')
train_edges_false = set()
while len(train_edges_false) < len(train_edges):
idx_i, idx_j = np.random.choice(g.nodes(), size=2, replace=False)
false_edge = (idx_i, idx_j, 0)
# Make sure false_edge in not an actual edge, not in test_edges_false,
# not in val_edges_false, not a repeat
if false_edge in all_edge_tuples or \
false_edge in test_edges_false or \
false_edge in train_edges_false:
continue
train_edges_false.add(false_edge)
if verbose == True:
print('final checks for disjointness...')
# assert: false_edges are actually false (not in all_edge_tuples)
assert test_edges_false.isdisjoint(all_edge_tuples)
assert train_edges_false.isdisjoint(all_edge_tuples)
# assert: test, val, train false edges disjoint
assert test_edges_false.isdisjoint(train_edges_false)
# assert: test, val, train positive edges disjoint
assert test_edges.isdisjoint(train_edges)
if verbose == True:
print('creating adj_train...')
# Convert edge-lists to numpy arrays
train_edges = np.array([list(edge_tuple) for edge_tuple in train_edges])
train_edges_false = np.array([list(edge_tuple) for edge_tuple in train_edges_false])
test_edges = np.array([list(edge_tuple) for edge_tuple in test_edges])
test_edges_false = np.array([list(edge_tuple) for edge_tuple in test_edges_false])
if verbose == True:
print('Done with train-test split!')
print('')
return train_edges, train_edges_false, test_edges, test_edges_false
<file_sep>/eval/functions.py
from collections import defaultdict
import numpy
from sklearn.multiclass import OneVsRestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import MultiLabelBinarizer
from sklearn.model_selection import cross_val_predict
from sklearn.metrics import f1_score
from sklearn.utils import shuffle as sk_shuffle
import gensim
def read_cora_labels(labels_file):
labels = {}
all_labels = set()
with open(labels_file, encoding='utf-8') as hfile:
for i, line in enumerate(hfile):
# omit the 1st and last item in the list as they are always empty
node_labels = set(line.strip().split('/')[1:-1])
labels[str(i)] = node_labels # i start from 0
all_labels.update(node_labels)
return labels, all_labels
def read_blogcat_labels(labels_file, delimiter=','):
labels = defaultdict(set)
all_labels = set()
with open(labels_file, encoding='utf-8') as hfile:
for line in hfile:
node, label = line.strip().split(delimiter)
labels[node].add(label)
all_labels.add(label)
return labels, all_labels
def read_ml_class_labels(labels_file):
labels = {}
with open(labels_file, encoding='utf-8') as hfile:
for line in hfile:
node, node_labels = line.split(' ')
labels[node] = set(node_labels.split(','))
return labels
def get_label_repr(node_labels, label_list):
# return a binary vector where each index corresponds to a label
result = []
for label in label_list:
if label in node_labels:
result.append(1)
else:
result.append(0)
return result
def __get_repr(labels, label_list, emb, shuffle=True):
# sort all labels so the encodings are consistent
label_list_sorted = sorted(label_list)
X = []
y = []
for node, node_labels in labels.items():
X.append(emb[node])
y.append(get_label_repr(node_labels, label_list_sorted))
if shuffle:
return sk_shuffle(numpy.asarray(X), numpy.asarray(y))
return numpy.asarray(X), numpy.asarray(y)
def __get_f1(predictions, y, number_of_labels):
# find the indices (labels) with the highest probabilities (ascending order)
pred_sorted = numpy.argsort(predictions, axis=1)
# the true number of labels for each node
num_labels = numpy.sum(y, axis=1)
# we take the best k label predictions for all nodes, where k is the true number of labels
pred_reshaped = []
pred_set = set()
for pr, num in zip(pred_sorted, num_labels):
pred_reshaped.append(pr[-num:].tolist())
pred_set.update(pr[-num:])
# convert back to binary vectors
pred_transformed = MultiLabelBinarizer(range(number_of_labels)).fit_transform(pred_reshaped)
print('pred_label:', len(pred_set))
f1_micro = f1_score(y, pred_transformed, average='micro')
f1_macro = f1_score(y, pred_transformed, average='macro')
return f1_micro, f1_macro
def get_f1_cross_val(labels, label_list, cv, emb, verbose=True):
# workaround to predict probabilities during cross-validation
# "method='predict_proba'" does not seem to work
class ovrc_prob(OneVsRestClassifier):
def predict(self, X):
return self.predict_proba(X)
if verbose:
print('transforming inputs...')
X, y = __get_repr(labels, label_list, emb)
if verbose:
print('shape of X: {}'.format(X.shape))
print('shape of y: {}'.format(y.shape))
print('running {}-fold cross-validation...'.format(cv))
ovrc = ovrc_prob(LogisticRegression(solver='liblinear'))
pred = cross_val_predict(ovrc, X, y, cv=cv)
return __get_f1(pred, y, len(label_list))
def get_f1(train_labels, labels, label_list, emb, verbose=True):
if verbose:
print('transforming inputs...')
# these labels are already shuffled
X_train, y_train = __get_repr(train_labels, label_list, emb, False)
X, y = __get_repr(labels, label_list, emb, False)
if verbose:
print('shape of X_train: {}'.format(X_train.shape))
print('shape of y_train: {}'.format(y_train.shape))
print('shape of X: {}'.format(X.shape))
print('shape of y: {}'.format(y.shape))
print('fitting classifier...')
ovrc = OneVsRestClassifier(LogisticRegression())
ovrc.fit(X_train, y_train)
if verbose:
print('evaluating...')
pred = ovrc.predict_proba(X)
return __get_f1(pred, y, len(label_list))
def read_w2v_emb(file_path, binary): #mark
return gensim.models.KeyedVectors.load_word2vec_format(file_path, binary=binary).wv
<file_sep>/settings.py
import os
####parameters for learning
C_LEARNING_RATE = 0.0001
P_LEARNING_RATE = 0.0001
S_LEARNING_RATE = 0.00001
C_WEIGHT_DECAY = 0.000001
P_WEIGHT_DECAY = 0.000001
S_WEIGHT_DECAY = 0.000001
BATCH_SIZE = 1024
FEATURE_SIZE = 128 #dimensions
gama = 1. #Parameter for speed up traing of 'seller'. gama * N >= NNum
NNum = 5 #Randomly choose NNum (K) nodes for training p_\phi
rate = 0. #dropout rate for customers
train_epochs = 50 #Total train epochs
###parameters for random walks
walk_length = 40
num_walks = 1
window_size = 10
negatives = 1
App = 1 #0 denotes classification; 1 denotes link prediction
CP = False #Continue training from the checkpoint
workdir = os.path.abspath('.') #workspace
######Classification Input
TRAIN_INPUT_FILENAME = workdir + "/data/Citeseer_input.txt"
TRAIN_LABEL_FILENAME = workdir + "/data/Citeseer_label.txt"
#TRAIN_INPUT_FILENAME = '/home/lqd/dataset/PubMed/cf/PubMed_input.txt'
#TRAIN_LABEL_FILENAME = '/home/lqd/dataset/PubMed/cf/PubMed_label.txt'
format = 'blogcat'
######Link prediction Input
split = False
test_frac = 0.5
#FULL_FILENAME = workdir + '/data/wiki-vote.txt'
FULL_FILENAME = '/home/lqd/dataset/Cora/lp/data_0.txt'
#TRAIN_POS_FILENAME = workdir + '/data/wiki_train_pos.txt'
TRAIN_POS_FILENAME = '/home/lqd/dataset/Cora/lp/train_edges_0.txt'
TRAIN_NEG_FILENAME = '/home/lqd/dataset/Cora/lp/train_edges_false_0.txt'
#TRAIN_NEG_FILENAME = workdir + '/data/wiki_train_neg.txt' # Optimal
#TEST_POS_FILENAME = workdir + "/data/wiki_test_pos.txt"
#TEST_NEG_FILENAME = workdir + "/data/wiki_test_neg.txt"
TEST_POS_FILENAME = '/home/lqd/dataset/Cora/lp/test_edges_0.txt'
TEST_NEG_FILENAME = '/home/lqd/dataset/Cora/lp/test_edges_false_0.txt'
#####Output
EMB_OUTPUT_FILENAME = workdir + "/emb/emb_lp.txt"
CONTEXT_OUTPUT_FILENAME = workdir + "/emb/context_lp.txt"
S_MODEL_BEST_FILE = workdir + '/model/s_best.model_lp'
P_MODEL_BEST_FILE = workdir + '/model/p_best.model_lp'
<file_sep>/eval/auc.py
import numpy as np
from sklearn.metrics import roc_auc_score
def AUC(sess, model, positive, negative):
score_pos = sess.run(model.P_pred_score, feed_dict={model.u: positive[:, 0], model.v: positive[:, 1]})
score_neg = sess.run(model.P_pred_score, feed_dict={model.u: negative[:, 0], model.v: negative[:, 1]})
max_pos = np.max(score_pos)
min_pos = np.min(score_pos)
max_neg = np.max(score_neg)
min_neg = np.min(score_neg)
max_all = np.maximum(max_pos, max_neg)
score_pos_n = score_pos - max_all
score_neg_n = score_neg - max_all
#preds_pos = 1./(1. + np.exp(-score_pos_n))
#preds_neg = 1./(1. + np.exp(-score_neg_n))
preds_pos = np.exp(score_pos_n)/(1. + np.exp(score_pos_n))
preds_neg = np.exp(score_neg_n)/(1. + np.exp(score_neg_n))
print('max_pos: ', max_pos, 'min_pos: ', min_pos, 'max_neg: ', max_neg, 'min_neg: ', min_neg)
preds_all = np.hstack([preds_pos, preds_neg])
labels_all = np.hstack([np.ones(len(preds_pos)), np.zeros(len(preds_neg))])
roc_score = roc_auc_score(labels_all, preds_all)
return roc_score
def AUC2(sess, model, positive, negative):
score_pos = sess.run(model.S_pred_score, feed_dict={model.u: positive[:, 0], model.v: positive[:, 1]})
score_neg = sess.run(model.S_pred_score, feed_dict={model.u: negative[:, 0], model.v: negative[:, 1]})
#preds_pos = 1./(1. + np.exp(-score_pos))
#preds_neg = 1./(1. + np.exp(-score_neg))
#preds_all = np.hstack([preds_pos, preds_neg])
#labels_all = np.hstack([np.ones(len(preds_pos)), np.zeros(len(preds_neg))])
max_pos = np.max(score_pos)
min_pos = np.min(score_pos)
max_neg = np.max(score_neg)
min_neg = np.min(score_neg)
max_all = np.maximum(max_pos, max_neg)
score_pos_n = score_pos - max_all
score_neg_n = score_neg - max_all
# preds_pos = 1./(1. + np.exp(-score_pos_n))
# preds_neg = 1./(1. + np.exp(-score_neg_n))
preds_pos = np.exp(score_pos_n) / (1. + np.exp(score_pos_n))
preds_neg = np.exp(score_neg_n) / (1. + np.exp(score_neg_n))
print('max_pos: ', max_pos, 'min_pos: ', min_pos, 'max_neg: ', max_neg, 'min_neg: ', min_neg)
preds_all = np.hstack([preds_pos, preds_neg])
labels_all = np.hstack([np.ones(len(preds_pos)), np.zeros(len(preds_neg))])
roc_score = roc_auc_score(labels_all, preds_all)
return roc_score
<file_sep>/eval/multilabel_class_cv.py
import networkx as nx
import settings as st
from eval import functions
def Cross_val(emb_file, cv=5, comments='#'):
if st.format not in ('cora', 'blogcat'):
exit('error: only label formats "cora" and "blogcat" are supported')
print('reading {}...'.format(st.TRAIN_INPUT_FILENAME))
orig_graph = nx.read_edgelist(st.TRAIN_INPUT_FILENAME, nodetype=str, create_using=nx.DiGraph(), comments=comments, delimiter='\t')
print('reading {}...'.format(st.TRAIN_LABEL_FILENAME))
if st.format == 'cora':
labels, label_list = functions.read_cora_labels(st.TRAIN_LABEL_FILENAME)
else:
labels, label_list = functions.read_blogcat_labels(st.TRAIN_LABEL_FILENAME, delimiter='\t')
assert len(labels) == orig_graph.number_of_nodes()
print('reading {}...'.format(emb_file))
emb = functions.read_w2v_emb(emb_file, False)
f1_micro, f1_macro = functions.get_f1_cross_val(labels, label_list, cv, emb)
return f1_micro, f1_macro
<file_sep>/utils.py
import networkx as nx
import numpy as np
from PRE import mask_test_edges
def load_edgelist(file, undirected=True):
train = {}
nodes = set()
with open(file) as fin:
for line in fin:
cols = line.strip().split()
node = cols[0]
context = cols[1]
if node in train:
train[node].append(context)
else:
train[node] = [context]
if undirected:
if context in train:
train[context].append(node)
else:
train[context] = [node]
nodes.add(node)
nodes.add(context)
return train, nodes
def split_data(file_in, file_out1, file_out2, file_out3, file_out4, frac=0.1):
#G = nx.read_edgelist(file_in, nodetype=int, create_using=nx.DiGraph())
G = nx.read_edgelist(file_in, nodetype=int, data=(('weight', int),), create_using=nx.DiGraph())
#for edge in G.edges():
# G[edge[0]][edge[1]]['weight'] = 1
train_edges, train_edges_false, test_edges, test_edges_false = mask_test_edges(G, test_frac=frac, prevent_disconnect=False, verbose=True)
np.savetxt(file_out1, train_edges, fmt='%d\t%d\t%d')
np.savetxt(file_out2, train_edges_false, fmt='%d\t%d\t%d')
np.savetxt(file_out3, test_edges, fmt='%d\t%d\t%d')
np.savetxt(file_out4, test_edges_false, fmt='%d\t%d\t%d')
# Get batch data from training set
def get_batch(data, index, size):
return data[index:index+size, 0], data[index:index+size, 1], data[index:index+size, 2]
def write_to_file(sess, model, file_out, FEATURE_SIZE, node_list, tag=1):
print("write to file")
with open(file_out, 'w') as file:
if tag == 1:
emb = sess.run(model.u_embedding, feed_dict={model.u: node_list})
else:
emb = sess.run(model.v_embedding, feed_dict={model.v: node_list})
file.write('{} {}'.format(str(len(node_list)), str(FEATURE_SIZE)))
for i, node in enumerate(node_list):
line = ' '.join(map(str, emb[i]))
line = '\n' + str(node) + ' ' + line
file.writelines(line)
file.close()
| 7d34d3f8685a453366d20f1226b7434a3cbcabde | [
"Markdown",
"Python"
] | 9 | Python | Qidong-Liu/TriATNE | ff5786f40feb723aab537e4dd697b5084ed170cd | bbbe9da1b8b5fc80e2010618df38d57bd49c961e |
refs/heads/develop | <repo_name>elifesciences/annotations<file_sep>/README.md
# annotations
Annotations service backend
## Docker
The project provides two images (a `fpm` and a `cli` one) that run as the `www-data` user. They work in concert with others to allow to run the service locally, or to run tasks such as tests.
Build images with:
```
docker-compose build
```
Run a shell as `www-data` inside a new `cli` container:
```
docker-compose run cli /bin/bash
```
Run composer:
```
docker-compose run composer composer install
```
Run a PHP interpreter:
```
docker-compose run cli /usr/bin/env php ...
```
Run PHPUnit:
```
docker-compose run cli vendor/bin/phpunit
```
Run all project tests:
```
docker-compose -f docker-compose.yml -f docker-compose.ci.yml build
docker-compose -f docker-compose.yml -f docker-compose.ci.yml run ci
```
## Journey of a request to the annotations api
1. Query received via the `annotations` api.
1. Retrieve annotation listing from `hypothes.is/api` based on query parameters.
1. Denormalize the annotations into an [object model](src/HypothesisClient/Model/Annotation.php).
1. Normalize the annotations to prepare the response which conforms to the eLife json schema. We rely on [CommonMark](http://commonmark.thephpleague.com/) to step through the Markdown content and prepare the structure that we need, sanitizing each HTML value as it is rendered with [HTMLPurifier](http://htmlpurifier.org/).
1. Return the response to the client.
<file_sep>/tests/HypothesisClient/Model/Annotation/Target/SelectorTest.php
<?php
namespace tests\eLife\HypothesisClient\Model\Annotation\Target;
use eLife\HypothesisClient\Model\Annotation\Target\Selector;
use PHPUnit\Framework\TestCase;
/**
* @covers \eLife\HypothesisClient\Model\Annotation\Target\Selector
*/
final class SelectorTest extends TestCase
{
/** @var Selector */
private $selector;
/** @var Selector\TextQuote */
private $textQuote;
/**
* @before
*/
public function prepare_selector()
{
$this->selector = new Selector(
$this->textQuote = new Selector\TextQuote('exact', 'prefix', 'suffix')
);
}
/**
* @test
*/
public function it_has_a_text_quote()
{
$this->assertSame($this->textQuote, $this->selector->getTextQuote());
}
}
<file_sep>/config/dev.php
<?php
use Psr\Log\LogLevel;
return [
'debug' => true,
'logging' => [
'level' => LogLevel::DEBUG,
],
];
<file_sep>/src/HypothesisClient/Model/Annotation/Target.php
<?php
namespace eLife\HypothesisClient\Model\Annotation;
use eLife\HypothesisClient\Model\Annotation\Target\Selector;
final class Target
{
private $source;
private $selector;
/**
* @internal
*/
public function __construct(
string $source,
Selector $selector = null
) {
$this->source = $source;
$this->selector = $selector;
}
public function getSource() : string
{
return $this->source;
}
/**
* @return Selector|null
*/
public function getSelector()
{
return $this->selector;
}
}
<file_sep>/tests/HypothesisClient/Credentials/UserManagementCredentialsTest.php
<?php
namespace tests\eLife\HypothesisClient\Credentials;
use eLife\HypothesisClient\Credentials\UserManagementCredentials;
use PHPUnit\Framework\TestCase;
/**
* @covers \eLife\HypothesisClient\Credentials\UserManagementCredentials
*/
final class UserManagementCredentialsTest extends TestCase
{
/**
* @test
*/
public function it_will_return_basic_authorization_string()
{
$credentials = new UserManagementCredentials('foo', 'baz', 'authority');
$this->assertSame(sprintf('Basic %s', base64_encode('foo:baz')), $credentials->getAuthorizationBasic());
}
}
<file_sep>/src/HypothesisClient/ApiSdk.php
<?php
namespace eLife\HypothesisClient;
use eLife\HypothesisClient\ApiClient\SearchClient;
use eLife\HypothesisClient\ApiClient\TokenClient;
use eLife\HypothesisClient\ApiClient\UsersClient;
use eLife\HypothesisClient\Client\Search;
use eLife\HypothesisClient\Client\Token;
use eLife\HypothesisClient\Client\Users;
use eLife\HypothesisClient\Credentials\JWTSigningCredentials;
use eLife\HypothesisClient\Credentials\UserManagementCredentials;
use eLife\HypothesisClient\HttpClient\HttpClient;
use eLife\HypothesisClient\Serializer\Annotation;
use eLife\HypothesisClient\Serializer\AnnotationDenormalizer;
use eLife\HypothesisClient\Serializer\TokenDenormalizer;
use eLife\HypothesisClient\Serializer\UserDenormalizer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Serializer;
final class ApiSdk
{
private $group;
private $httpClient;
private $jwtSigning;
private $search;
private $serializer;
private $token;
private $users;
private $userManagement;
public function __construct(HttpClient $httpClient, UserManagementCredentials $userManagement = null, JWTSigningCredentials $jwtSigning, string $group = '__world__')
{
$this->httpClient = $httpClient;
$this->userManagement = $userManagement;
$this->jwtSigning = $jwtSigning;
$this->group = $group;
$this->serializer = new Serializer([
new Annotation\DocumentDenormalizer(),
new Annotation\TargetDenormalizer(),
new Annotation\Target\SelectorDenormalizer(),
new Annotation\Target\Selector\TextQuoteDenormalizer(),
new Annotation\PermissionsDenormalizer(),
new AnnotationDenormalizer(),
new TokenDenormalizer(),
new UserDenormalizer(),
], [new JsonEncoder()]);
$this->search = new Search(new SearchClient($this->httpClient, $this->group, []), $this->serializer);
$this->token = new Token(new TokenClient($this->httpClient, $this->jwtSigning, []), $this->serializer);
$this->users = new Users(new UsersClient($this->httpClient, $this->userManagement, []), $this->serializer);
}
public function users() : Users
{
return $this->users;
}
public function token() : Token
{
return $this->token;
}
public function search() : Search
{
return $this->search;
}
}
<file_sep>/src/HypothesisClient/Model/Annotation/Target/Selector/TextQuote.php
<?php
namespace eLife\HypothesisClient\Model\Annotation\Target\Selector;
final class TextQuote
{
private $exact;
private $prefix;
private $suffix;
/**
* @internal
*/
public function __construct(
string $exact,
string $prefix,
string $suffix
) {
$this->exact = $exact;
$this->prefix = $prefix;
$this->suffix = $suffix;
}
public function getExact() : string
{
return $this->exact;
}
public function getPrefix() : string
{
return $this->prefix;
}
public function getSuffix() : string
{
return $this->suffix;
}
}
<file_sep>/tests/HypothesisClient/Clock/FixedClockTest.php
<?php
namespace tests\eLife\HypothesisClient\Clock;
use eLife\HypothesisClient\Clock\Clock;
use eLife\HypothesisClient\Clock\FixedClock;
use PHPUnit\Framework\TestCase;
/**
* @covers \eLife\HypothesisClient\Clock\FixedClock
*/
final class FixedClockTest extends TestCase
{
/**
* @test
*/
public function it_can_return_a_fixed_time()
{
$clock = new FixedClock(1000);
$this->assertInstanceOf(Clock::class, $clock);
$this->assertSame(1000, $clock->time());
}
}
<file_sep>/src/Annotations/Provider/QueueCommandsProvider.php
<?php
namespace eLife\Annotations\Provider;
use eLife\Annotations\Command\QueueCreateCommand;
use eLife\Annotations\Command\QueueImportCommand;
use eLife\Annotations\Command\QueuePushCommand;
use eLife\Annotations\Command\QueueWatchCommand;
use eLife\Bus\Command\QueueCleanCommand;
use eLife\Bus\Command\QueueCountCommand;
use Knp\Console\Application;
use LogicException;
use Pimple\Container;
use Pimple\ServiceProviderInterface;
use ReflectionClass;
final class QueueCommandsProvider implements ServiceProviderInterface
{
public function register(Container $container)
{
if (!isset($container['console'])) {
throw new LogicException(sprintf('You must register the ConsoleServiceProvider to use the %s.', (new ReflectionClass(self::class))->getShortName()));
}
$container->extend('console', function (Application $console) use ($container) {
$console->add(new QueueCleanCommand($container['aws.queue'], $container['logger']));
$console->add(new QueueCountCommand($container['aws.queue']));
$console->add(new QueuePushCommand($container['aws.queue'], $container['logger'], $container['sqs.queue_message_type'] ?? null));
$console->add(new QueueCreateCommand($container['aws.sqs'], $container['logger'], $container['sqs.queue_name'] ?? null, $container['sqs.region'] ?? null));
$console->add(new QueueImportCommand(
$container['api.sdk'],
$container['aws.queue'],
$container['logger'],
$container['monitoring'],
$container['limit.interactive']
));
$console->add(new QueueWatchCommand(
$container['aws.queue'],
$container['aws.queue_transformer'],
$container['hypothesis.sdk'],
$container['logger'],
$container['monitoring'],
$container['limit.long_running']
));
return $console;
});
}
}
<file_sep>/config/end2end.php
<?php
return require __DIR__.'/prod.php';
<file_sep>/smoke_tests_cli.sh
#!/bin/bash
set -e
bin/console --version
<file_sep>/src/HypothesisClient/Serializer/UserDenormalizer.php
<?php
namespace eLife\HypothesisClient\Serializer;
use eLife\HypothesisClient\Model\User;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
final class UserDenormalizer implements DenormalizerInterface, DenormalizerAwareInterface
{
use DenormalizerAwareTrait;
public function denormalize($data, $class, $format = null, array $context = []) : User
{
return new User($data['username'], $data['email'] ?? null, $data['display_name'] ?? null, $data['new'] ?? false);
}
public function supportsDenormalization($data, $type, $format = null) : bool
{
return User::class === $type;
}
}
<file_sep>/src/Annotations/Serializer/CommonMark/Block/Renderer/CodeRenderer.php
<?php
namespace eLife\Annotations\Serializer\CommonMark\Block\Renderer;
use League\CommonMark\Block\Element\AbstractBlock;
use League\CommonMark\Block\Element\FencedCode;
use League\CommonMark\Block\Element\IndentedCode;
use League\CommonMark\Block\Renderer\BlockRendererInterface;
use League\CommonMark\ElementRendererInterface;
use League\CommonMark\Util\Xml;
final class CodeRenderer implements BlockRendererInterface
{
public function render(AbstractBlock $block, ElementRendererInterface $htmlRenderer, $inTightList = false)
{
if (!($block instanceof FencedCode) && !($block instanceof IndentedCode)) {
throw new \InvalidArgumentException('Incompatible block type: '.get_class($block));
}
return Xml::escape($block->getStringContent());
}
}
<file_sep>/src/HypothesisClient/Model/Annotation/Permissions.php
<?php
namespace eLife\HypothesisClient\Model\Annotation;
final class Permissions
{
private $read;
/**
* @internal
*/
public function __construct(
string $read
) {
$this->read = $read;
}
public function getRead() : string
{
return $this->read;
}
}
<file_sep>/src/HypothesisClient/Serializer/AnnotationDenormalizer.php
<?php
namespace eLife\HypothesisClient\Serializer;
use Assert\Assert;
use DateTimeImmutable;
use eLife\HypothesisClient\Model\Annotation;
use eLife\HypothesisClient\Model\Annotation\Document;
use eLife\HypothesisClient\Model\Annotation\Permissions;
use eLife\HypothesisClient\Model\Annotation\Target;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
final class AnnotationDenormalizer implements DenormalizerInterface, DenormalizerAwareInterface
{
use DenormalizerAwareTrait;
public function denormalize($data, $class, $format = null, array $context = []) : Annotation
{
// Treat annotations of whitespace like page notes
foreach ($data['target'] as $i => $target) {
foreach ($target['selector'] ?? [] as $selector) {
if ('TextQuoteSelector' === $selector['type'] && '' === trim($selector['exact'])) {
$data['target'][$i]['source'] = $data['uri'];
unset($data['target'][$i]['selector']);
continue 2;
}
}
}
$data['document'] = $this->denormalizer->denormalize($data['document'], Document::class);
Assert::that($data['target'])->count(1);
$data['target'] = $this->denormalizer->denormalize($data['target'][0], Target::class);
$data['permissions'] = $this->denormalizer->denormalize($data['permissions'], Permissions::class);
return new Annotation(
$data['id'],
$data['text'] ?? null,
new DateTimeImmutable($data['created']),
new DateTimeImmutable($data['updated']),
$data['document'],
$data['target'],
$data['uri'],
$data['references'] ?? [],
$data['permissions']
);
}
public function supportsDenormalization($data, $type, $format = null) : bool
{
return Annotation::class === $type;
}
}
<file_sep>/src/Annotations/Serializer/CommonMark/Inline/Renderer/HtmlInlineRenderer.php
<?php
namespace eLife\Annotations\Serializer\CommonMark\Inline\Renderer;
use League\CommonMark\ElementRendererInterface;
use League\CommonMark\Inline\Element\AbstractInline;
use League\CommonMark\Inline\Element\HtmlInline;
use League\CommonMark\Inline\Renderer\InlineRendererInterface;
final class HtmlInlineRenderer implements InlineRendererInterface
{
public function render(AbstractInline $inline, ElementRendererInterface $htmlRenderer)
{
if (!($inline instanceof HtmlInline)) {
throw new \InvalidArgumentException('Incompatible inline type: '.get_class($inline));
}
return $inline->getContent();
}
}
<file_sep>/tests/HypothesisClient/Serializer/Annotation/PermissionsDenormalizerTest.php
<?php
namespace tests\eLife\HypothesisClient\Serializer\Annotation;
use eLife\HypothesisClient\Model\Annotation\Permissions;
use eLife\HypothesisClient\Serializer\Annotation\PermissionsDenormalizer;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
/**
* @covers \eLife\HypothesisClient\Serializer\Annotation\PermissionsDenormalizer
*/
final class PermissionsDenormalizerTest extends TestCase
{
/** @var PermissionsDenormalizer */
private $normalizer;
/**
* @before
*/
protected function setUpNormalizer()
{
$this->normalizer = new PermissionsDenormalizer();
}
/**
* @test
*/
public function it_is_a_denormalizer()
{
$this->assertInstanceOf(DenormalizerInterface::class, $this->normalizer);
}
/**
* @test
* @dataProvider canDenormalizeProvider
*/
public function it_can_denormalize_permissions($data, $format, array $context, bool $expected)
{
$this->assertSame($expected, $this->normalizer->supportsDenormalization($data, $format, $context));
}
public function canDenormalizeProvider() : array
{
return [
'permissions' => [[], Permissions::class, [], true],
'non-permissions' => [[], get_class($this), [], false],
];
}
/**
* @test
* @dataProvider denormalizeProvider
*/
public function it_will_denormalize_permissions(array $json, Permissions $expected)
{
$this->assertEquals($expected, $this->normalizer->denormalize($json, Permissions::class));
}
public function denormalizeProvider() : array
{
return [
'complete' => [
[
'delete' => [
'acct:<EMAIL>',
],
'read' => [
'group:__world__',
],
],
new Permissions('group:__world__'),
],
];
}
}
<file_sep>/tests/HypothesisClient/Model/TokenTest.php
<?php
namespace tests\eLife\HypothesisClient\Model;
use eLife\HypothesisClient\Model\Token;
use PHPUnit\Framework\TestCase;
/**
* @covers \eLife\HypothesisClient\Model\Token
*/
final class TokenTest extends TestCase
{
/** @var Token */
private $token;
/**
* @before
*/
public function prepare_token()
{
$this->token = new Token('access_token', 'token_type', 1000.99, 'refresh_token');
}
/**
* @test
*/
public function it_has_an_access_token()
{
$this->assertSame('access_token', $this->token->getAccessToken());
}
/**
* @test
*/
public function it_has_a_token_type()
{
$this->assertSame('token_type', $this->token->getTokenType());
}
/**
* @test
*/
public function it_has_an_expires_in_value()
{
$this->assertSame(1000.99, $this->token->getExpiresIn());
}
/**
* @test
*/
public function it_has_a_refresh_token()
{
$this->assertSame('refresh_token', $this->token->getRefreshToken());
}
}
<file_sep>/tests/HypothesisClient/Credentials/JWTSigningCredentialsTest.php
<?php
namespace tests\eLife\HypothesisClient\Credentials;
use eLife\HypothesisClient\Clock\FixedClock;
use eLife\HypothesisClient\Credentials\JWTSigningCredentials;
use Firebase\JWT\JWT;
use PHPUnit\Framework\TestCase;
/**
* @covers \eLife\HypothesisClient\Credentials\JWTSigningCredentials
*/
final class JWTSigningCredentialsTest extends TestCase
{
/**
* @test
*/
public function it_can_generate_a_jwt_token()
{
$credentials = new JWTSigningCredentials($clientId = 'foo', $clientSecret = 'baz', $authority = 'authority', $clock = new FixedClock(), $expire = 300);
$generatedToken = $credentials->getJWT($username = 'username');
$start = $clock->time();
$this->assertSame(
[
'aud' => 'hypothes.is',
'iss' => $clientId,
'sub' => "acct:{$username}@{$authority}",
'nbf' => $start,
'exp' => $start + $expire,
],
(array) JWT::decode($generatedToken, $clientSecret, ['HS256'])
);
}
}
<file_sep>/src/HypothesisClient/Model/Annotation/Document.php
<?php
namespace eLife\HypothesisClient\Model\Annotation;
final class Document
{
private $title;
/**
* @internal
*/
public function __construct(
string $title
) {
$this->title = $title;
}
public function getTitle() : string
{
return $this->title;
}
}
<file_sep>/src/Annotations/Serializer/CommonMark/HtmlPurifierRenderer.php
<?php
namespace eLife\Annotations\Serializer\CommonMark;
use HTMLPurifier;
use League\CommonMark\Block\Element\AbstractBlock;
use League\CommonMark\ElementRendererInterface;
final class HtmlPurifierRenderer implements ElementRendererInterface
{
const ALLOW_TAGS = '<i><strong><sub><sup><span><del><a><br><caption>';
private $htmlPurifier;
private $renderer;
public function __construct(ElementRendererInterface $renderer, HTMLPurifier $htmlPurifier)
{
$this->renderer = $renderer;
$this->htmlPurifier = $htmlPurifier;
}
public function getOption($option, $default = null)
{
return $this->renderer->getOption($option, $default);
}
public function renderInlines($inlines) : string
{
return $this->renderer->renderInlines($inlines);
}
public function renderBlock(AbstractBlock $block, $inTightList = false) : string
{
$rendered = $this->renderer->renderBlock($block, $inTightList);
$purified = $this->htmlPurifier->purify($rendered);
return strip_tags($purified, self::ALLOW_TAGS);
}
public function renderBlocks($blocks, $inTightList = false) : string
{
return $this->renderer->renderBlocks($blocks, $inTightList);
}
}
<file_sep>/src/Annotations/Command/QueuePushCommand.php
<?php
namespace eLife\Annotations\Command;
use eLife\Bus\Queue\InternalSqsMessage;
use eLife\Bus\Queue\WatchableQueue;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
final class QueuePushCommand extends Command
{
private $queue;
private $logger;
public function __construct(WatchableQueue $queue, LoggerInterface $logger, $type = null)
{
parent::__construct(null);
$this->queue = $queue;
$this->logger = $logger;
$this->addArgument('type', !empty($type) ? InputArgument::OPTIONAL : InputArgument::REQUIRED, '', $type);
}
protected function configure()
{
$this
->setName('queue:push')
->setDescription('Manually enqueue item into SQS.')
->addArgument('id', InputArgument::REQUIRED);
}
public function execute(InputInterface $input, OutputInterface $output)
{
$id = $input->getArgument('id');
$type = $input->getArgument('type');
// Create queue item.
$item = new InternalSqsMessage($type, $id);
// Queue item.
$this->queue->enqueue($item);
$io = new SymfonyStyle($input, $output);
$message = 'Item added to queue.';
$this->logger->info($message);
$io->success($message);
}
}
<file_sep>/tests/HypothesisClient/RequestConstraint.php
<?php
namespace tests\eLife\HypothesisClient;
use GuzzleHttp\Psr7\Request;
use PHPUnit\Framework\Constraint\Constraint;
use PHPUnit\Framework\Constraint\IsEqual;
use function GuzzleHttp\Psr7\str;
final class RequestConstraint extends Constraint
{
public function __construct($value)
{
parent::__construct();
$this->value = $value;
$this->wrapped = new IsEqual(str($this->value));
}
public static function equalTo(Request $expected)
{
return new self($expected);
}
/**
* @param Request $other Value or object to evaluate
*
* @return bool
*
* @throws PHPUnit\Framework\ExpectationFailedException
*/
public function evaluate($other, $description = '', $returnResult = false)
{
return $this->wrapped->evaluate(
str($other),
$description,
$returnResult
);
}
/**
* Returns a string representation of the constraint.
*
* @return string
*/
public function toString()
{
return sprintf(
'is equal to %s',
str($this->value)
);
}
}
<file_sep>/tests/HypothesisClient/Model/SearchResultsTest.php
<?php
namespace tests\eLife\HypothesisClient\Model;
use DateTimeImmutable;
use DateTimeZone;
use eLife\HypothesisClient\Model\Annotation;
use eLife\HypothesisClient\Model\SearchResults;
use PHPUnit\Framework\TestCase;
final class SearchResultsTest extends TestCase
{
/** @var Annotation[] */
private $annotations;
/** @var SearchResults */
private $searchResults;
/**
* @before
*/
public function prepareResults()
{
$this->annotations = [
new Annotation(
'id',
'text',
new DateTimeImmutable('now', new DateTimeZone('Z')),
new DateTimeImmutable('now', new DateTimeZone('Z')),
new Annotation\Document('title'),
new Annotation\Target('source'),
'uri',
[],
new Annotation\Permissions('read')
),
];
$this->searchResults = new SearchResults(3, $this->annotations);
}
/**
* @test
*/
public function it_has_a_total()
{
$this->assertSame(3, $this->searchResults->getTotal());
}
/**
* @test
*/
public function it_has_annotations()
{
$this->assertSame($this->annotations, $this->searchResults->getAnnotations());
}
}
<file_sep>/smoke_tests_fpm.sh
#!/bin/bash
set -e
set -o pipefail
assert_fpm "/ping" "pong"
<file_sep>/tests/HypothesisClient/ApiClient/TokenClientTest.php
<?php
namespace tests\eLife\HypothesisClient\HttpClient;
use eLife\HypothesisClient\ApiClient\TokenClient;
use eLife\HypothesisClient\Clock\FixedClock;
use eLife\HypothesisClient\Credentials\JWTSigningCredentials;
use eLife\HypothesisClient\HttpClient\HttpClient;
use eLife\HypothesisClient\Result\ArrayResult;
use GuzzleHttp\Promise\FulfilledPromise;
use GuzzleHttp\Psr7\Request;
use PHPUnit\Framework\TestCase;
use tests\eLife\HypothesisClient\RequestConstraint;
/**
* @covers \eLife\HypothesisClient\ApiClient\TokenClient
*/
final class TokenClientTest extends TestCase
{
/** @var JWTSigningCredentials */
private $credentials;
private $httpClient;
/** @var TokenClient */
private $tokenClient;
/**
* @before
*/
protected function setUpClient()
{
$this->credentials = new JWTSigningCredentials('client_id', 'secret_key', 'authority', new FixedClock(), 600);
$this->httpClient = $this->createMock(HttpClient::class);
$this->tokenClient = new TokenClient(
$this->httpClient,
$this->credentials,
['X-Foo' => 'bar']
);
}
/**
* @test
*/
public function it_can_claim_a_token()
{
$request = new Request(
'POST',
'token',
['X-Foo' => 'bar', 'User-Agent' => 'HypothesisClient'],
http_build_query([
'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
'assertion' => $this->credentials->getJWT('username'),
])
);
$response = new FulfilledPromise(new ArrayResult(['foo' => ['bar', 'baz']]));
$this->httpClient
->expects($this->once())
->method('send')
->with(RequestConstraint::equalTo($request))
->willReturn($response);
$this->assertSame($response, $this->tokenClient->getToken([], 'username'));
}
}
<file_sep>/.docker/config.php
<?php
return [
'api_url' => 'http://api_dummy:8080',
'hypothesis' => [
'api_url' => 'http://hypothesis_dummy:8080/',
],
'aws' => [
'queue_name' => 'annotations--dev',
'queue_message_default_type' => 'profile',
'credential_file' => true,
'region' => 'us-east-1',
'endpoint' => 'http://goaws:4100',
],
];
<file_sep>/config/test.php
<?php
$config = require __DIR__.'/ci.php';
$config['api_problem']['factory']['include_exception_details'] = false;
$config['aws']['stub'] = true;
$config['api_url'] = 'https://api.elifesciences.org/';
$config['mock'] = true;
return $config;
<file_sep>/src/HypothesisClient/Model/Annotation.php
<?php
namespace eLife\HypothesisClient\Model;
use DateTimeImmutable;
use eLife\HypothesisClient\Model\Annotation\Document;
use eLife\HypothesisClient\Model\Annotation\Permissions;
use eLife\HypothesisClient\Model\Annotation\Target;
final class Annotation
{
const PUBLIC_GROUP = 'group:__world__';
private $id;
private $text;
private $created;
private $updated;
private $document;
private $uri;
private $references;
private $permissions;
/**
* @internal
*/
public function __construct(
string $id,
string $text = null,
DateTimeImmutable $created,
DateTimeImmutable $updated,
Document $document,
Target $target,
string $uri,
array $references,
Permissions $permissions
) {
$this->id = $id;
$this->text = $text;
$this->created = $created;
$this->updated = $updated;
$this->document = $document;
$this->target = $target;
$this->uri = $uri;
$this->references = $references;
$this->permissions = $permissions;
}
public function getId() : string
{
return $this->id;
}
/**
* @return string|null
*/
public function getText()
{
return $this->text;
}
public function getCreatedDate() : DateTimeImmutable
{
return $this->created;
}
public function getUpdatedDate() : DateTimeImmutable
{
return $this->updated;
}
public function getDocument() : Document
{
return $this->document;
}
public function getTarget() : Target
{
return $this->target;
}
public function getUri() : string
{
return $this->uri;
}
public function getReferences() : array
{
return $this->references;
}
public function getPermissions() : Permissions
{
return $this->permissions;
}
}
<file_sep>/tests/HypothesisClient/Clock/SystemClockTest.php
<?php
namespace tests\eLife\HypothesisClient\Clock;
use eLife\HypothesisClient\Clock\Clock;
use eLife\HypothesisClient\Clock\SystemClock;
use PHPUnit\Framework\TestCase;
/**
* @covers \eLife\HypothesisClient\Clock\SystemClock
*/
final class SystemClockTest extends TestCase
{
/**
* @test
*/
public function it_can_return_the_current_time()
{
$clock = new SystemClock();
$this->assertInstanceOf(Clock::class, $clock);
$time = $clock->time();
$this->assertGreaterThan(0, $time);
}
}
<file_sep>/src/HypothesisClient/Client/Search.php
<?php
namespace eLife\HypothesisClient\Client;
use eLife\HypothesisClient\ApiClient\SearchClient;
use eLife\HypothesisClient\Model\Annotation;
use eLife\HypothesisClient\Model\SearchResults;
use eLife\HypothesisClient\Result\Result;
use GuzzleHttp\Promise\PromiseInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
final class Search
{
private $serializer;
private $searchClient;
public function __construct(SearchClient $searchClient, DenormalizerInterface $serializer)
{
$this->searchClient = $searchClient;
$this->serializer = $serializer;
}
public function query(
string $username = null,
string $accessToken = null,
int $offset = 0,
int $limit = 20,
bool $descendingOrder = true,
string $sort = 'updated'
) : PromiseInterface {
return $this->searchClient
->query(
[],
$username,
$accessToken,
$offset,
$limit,
$descendingOrder,
$sort
)
->then(function (Result $result) {
return new SearchResults(
$result['total'],
array_map(function (array $annotation) {
return $this->serializer->denormalize($annotation, Annotation::class);
}, $result['rows'])
);
});
}
}
<file_sep>/src/HypothesisClient/Client/Token.php
<?php
namespace eLife\HypothesisClient\Client;
use eLife\HypothesisClient\ApiClient\TokenClient;
use eLife\HypothesisClient\Model\Token as ModelToken;
use eLife\HypothesisClient\Result\Result;
use GuzzleHttp\Promise\PromiseInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
final class Token
{
private $serializer;
private $tokenClient;
public function __construct(TokenClient $tokenClient, DenormalizerInterface $serializer)
{
$this->tokenClient = $tokenClient;
$this->serializer = $serializer;
}
public function get(string $username) : PromiseInterface
{
return $this->tokenClient
->getToken(
[],
$username
)
->then(function (Result $result) {
return $this->serializer->denormalize($result->toArray(), ModelToken::class);
});
}
}
<file_sep>/src/Annotations/Command/QueueCreateCommand.php
<?php
namespace eLife\Annotations\Command;
use Aws\Sqs\Exception\SqsException;
use Aws\Sqs\SqsClient;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
final class QueueCreateCommand extends Command
{
private $sqsClient;
private $logger;
public function __construct(SqsClient $sqsClient, LoggerInterface $logger, $queueName = null, $region = null)
{
parent::__construct(null);
$this->sqsClient = $sqsClient;
$this->logger = $logger;
$this->addArgument('queueName', (!empty($queueName)) ? InputArgument::OPTIONAL : InputArgument::REQUIRED, '', $queueName);
$this->addOption('region', 'r', InputOption::VALUE_OPTIONAL, '', $region);
}
protected function configure()
{
$this
->setName('queue:create')
->setDescription('Creates queue [development-only]');
}
public function execute(InputInterface $input, OutputInterface $output)
{
$args = [
'Region' => $input->getOption('region'),
'QueueName' => $input->getArgument('queueName'),
];
$io = new SymfonyStyle($input, $output);
$in_region = (!empty($args['Region'])) ? ' ('.$args['Region'].')' : '';
try {
$this->sqsClient->getQueueUrl($args);
$message = sprintf('Queue "%s"%s already exists.', $args['QueueName'], $in_region);
$this->logger->warning($message);
$io->warning($message);
} catch (SqsException $exception) {
$this->sqsClient->createQueue($args);
$message = sprintf('Queue "%s"%s created successfully.', $args['QueueName'], $in_region);
$this->logger->info($message);
$io->success($message);
}
}
}
<file_sep>/src/HypothesisClient/Model/CanBeNew.php
<?php
namespace eLife\HypothesisClient\Model;
trait CanBeNew
{
protected $new = false;
public function isNew() : bool
{
return $this->new;
}
}
<file_sep>/src/Annotations/Command/QueueWatchCommand.php
<?php
namespace eLife\Annotations\Command;
use eLife\ApiSdk\Model\AccessControl;
use eLife\ApiSdk\Model\Profile;
use eLife\Bus\Command\QueueCommand;
use eLife\Bus\Limit\Limit;
use eLife\Bus\Queue\QueueItem;
use eLife\Bus\Queue\QueueItemTransformer;
use eLife\Bus\Queue\WatchableQueue;
use eLife\HypothesisClient\ApiSdk;
use eLife\HypothesisClient\Exception\BadResponse;
use eLife\HypothesisClient\Model\User;
use eLife\Logging\Monitoring;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Input\InputInterface;
use function mb_strlen;
use function mb_substr;
final class QueueWatchCommand extends QueueCommand
{
private $hypothesisSdk;
public function __construct(
WatchableQueue $queue,
QueueItemTransformer $transformer,
ApiSdk $hypothesisSdk,
LoggerInterface $logger,
Monitoring $monitoring,
Limit $limit,
bool $serializedTransform = false
) {
parent::__construct($logger, $queue, $transformer, $monitoring, $limit, $serializedTransform);
$this->hypothesisSdk = $hypothesisSdk;
}
protected function configure()
{
$this
->setName('queue:watch')
->setDescription('Create queue watcher')
->setHelp('Creates process that will watch for incoming items on a queue');
}
protected function process(InputInterface $input, QueueItem $item, $entity = null)
{
if ($entity instanceof Profile) {
$id = $entity->getIdentifier()->getId();
$emails = $entity
->getEmailAddresses()
->filter(function (AccessControl $accessControl) {
return AccessControl::ACCESS_PUBLIC === $accessControl->getAccess();
})
->map(function (AccessControl $accessControl) {
return $accessControl->getValue();
});
$display_name = $entity->getDetails()->getPreferredName();
if (count($emails) > 0) {
$email = $emails[0];
} else {
$this->logger->info(sprintf('No email address for profile "%s", backup email address created.', $id));
$email = $id.'<EMAIL>';
}
if (mb_strlen($display_name) > User::DISPLAY_NAME_MAX_LENGTH) {
$sanitized_display_name = mb_substr($display_name, 0, User::DISPLAY_NAME_MAX_LENGTH);
$this->logger->info(sprintf('The display name for profile "%s" is too long and has been truncated from "%s" to "%s".', $id, $display_name, $sanitized_display_name));
} else {
$sanitized_display_name = $display_name;
}
$user = new User($id, $email, $sanitized_display_name);
try {
$upsert = $this->hypothesisSdk->users()->upsert($user)->wait();
$this->logger->info(sprintf('Hypothesis user "%s" successfully %s.', $upsert->getUsername(), ($upsert->isNew() ? 'created' : 'updated')));
} catch (BadResponse $e) {
// If client error detected, log error and don't repeat.
if ($e->getResponse()->getStatusCode() < 500) {
$this->queue->commit($item);
$this->logger->error(sprintf('Hypothesis user "%s" upsert failure.', $user->getUsername()), ['exception' => $e]);
} else {
throw $e;
}
}
}
}
}
<file_sep>/src/HypothesisClient/Clock/Clock.php
<?php
namespace eLife\HypothesisClient\Clock;
interface Clock
{
public function time() : int;
}
<file_sep>/src/Annotations/Serializer/CommonMark/MathEscapeRenderer.php
<?php
namespace eLife\Annotations\Serializer\CommonMark;
use League\CommonMark\Block\Element\AbstractBlock;
use League\CommonMark\ElementRendererInterface;
use League\CommonMark\Util\Xml;
final class MathEscapeRenderer implements ElementRendererInterface
{
private $renderer;
public function __construct(ElementRendererInterface $renderer)
{
$this->renderer = $renderer;
}
public function getOption($option, $default = null)
{
return $this->renderer->getOption($option, $default);
}
public function renderInlines($inlines) : string
{
return $this->renderer->renderInlines($inlines);
}
public function renderBlock(AbstractBlock $block, $inTightList = false) : string
{
$rendered = $this->renderer->renderBlock($block, $inTightList);
// Escape MathML.
$escaped = preg_replace_callback('~<math[^>]*>.*?</math>~s', function ($match) {
return Xml::escape($match[0], true);
}, $rendered);
// Escape LaTeX.
$escaped = preg_replace_callback('~\$\$.+\$\$~s', function ($match) {
return Xml::escape($match[0], true);
}, $escaped);
return $escaped;
}
public function renderBlocks($blocks, $inTightList = false) : string
{
return $this->renderer->renderBlocks($blocks, $inTightList);
}
}
<file_sep>/src/Annotations/Serializer/HypothesisClientAnnotationNormalizer.php
<?php
namespace eLife\Annotations\Serializer;
use eLife\ApiSdk\ApiSdk;
use eLife\HypothesisClient\Model\Annotation;
use League\CommonMark\Block\Element;
use League\CommonMark\DocParser;
use League\CommonMark\ElementRendererInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
final class HypothesisClientAnnotationNormalizer implements NormalizerInterface
{
const CANNOT_RENDER_CONTENT_COPY = 'NOTE: It is not possible to display this content.';
const UNAVAILABLE_CONTENT_COPY = 'NOTE: There is no content available to display.';
private $docParser;
private $htmlRenderer;
private $logger;
public function __construct(DocParser $docParser, ElementRendererInterface $htmlRenderer, LoggerInterface $logger)
{
$this->docParser = $docParser;
$this->htmlRenderer = $htmlRenderer;
$this->logger = $logger;
}
/**
* @param Annotation $object
*/
public function normalize($object, $format = null, array $context = []) : array
{
$created = $object->getCreatedDate()->format(ApiSdk::DATE_FORMAT);
$updated = $object->getUpdatedDate()->format(ApiSdk::DATE_FORMAT);
$data = [
'id' => $object->getId(),
'access' => (Annotation::PUBLIC_GROUP === $object->getPermissions()->getRead()) ? 'public' : 'restricted',
'created' => $created,
'document' => [
'title' => $object->getDocument()->getTitle(),
'uri' => $object->getUri(),
],
];
if ($object->getReferences()) {
$data['ancestors'] = $object->getReferences();
}
if ($object->getText()) {
$data['content'] = $this->processText($object->getText());
}
if ($created !== $updated) {
$data['updated'] = $updated;
}
if ($object->getTarget()->getSelector()) {
$data['highlight'] = $object->getTarget()->getSelector()->getTextQuote()->getExact();
}
if (empty($data['highlight']) && empty($data['content'])) {
$this->logger->warning(sprintf('Annotation detected without highlight or content (ID: %s)', $data['id']), ['annotation' => $data]);
$data['content'] = [
[
'type' => 'paragraph',
'text' => self::UNAVAILABLE_CONTENT_COPY,
],
];
}
return $data;
}
private function processText(string $text) : array
{
$blocks = $this->docParser->parse($text)->children();
$data = [];
foreach ($blocks as $block) {
switch (true) {
case $block instanceof Element\ThematicBreak:
break;
case $block instanceof Element\ListBlock:
$data[] = $this->processListBlock($block);
break;
case $block instanceof Element\BlockQuote:
if ($rendered = $this->htmlRenderer->renderBlock($block)) {
$data[] = [
'type' => 'quote',
'text' => [
[
'type' => 'paragraph',
'text' => $rendered,
],
],
];
}
break;
case $block instanceof Element\HtmlBlock:
case $block instanceof Element\Paragraph:
if ($rendered = $this->htmlRenderer->renderBlock($block)) {
$data[] = [
'type' => 'paragraph',
'text' => $rendered,
];
}
break;
case $block instanceof Element\FencedCode:
case $block instanceof Element\IndentedCode:
if ($rendered = $this->htmlRenderer->renderBlock($block)) {
$data[] = [
'type' => 'code',
'code' => $rendered,
];
}
break;
}
}
if (empty($data)) {
$data = [
[
'type' => 'paragraph',
'text' => self::CANNOT_RENDER_CONTENT_COPY,
],
];
}
return $data;
}
private function processListBlock(Element\ListBlock $block)
{
$gather = function (Element\ListBlock $list) use (&$gather, &$render) {
$items = [];
foreach ($list->children() as $item) {
foreach ($item->children() as $child) {
if ($child instanceof Element\ListBlock) {
$items[] = [$render($child)];
} elseif ($item = $this->htmlRenderer->renderBlock($child)) {
$items[] = $item;
}
}
}
return $items;
};
$render = function (Element\ListBlock $list) use ($gather) {
return [
'type' => 'list',
'prefix' => (Element\ListBlock::TYPE_ORDERED === $list->getListData()->type) ? 'number' : 'bullet',
'items' => $gather($list),
];
};
return $render($block);
}
public function supportsNormalization($data, $format = null) : bool
{
return $data instanceof Annotation;
}
}
<file_sep>/src/Annotations/Serializer/CommonMark/Block/Renderer/ParagraphRenderer.php
<?php
namespace eLife\Annotations\Serializer\CommonMark\Block\Renderer;
use League\CommonMark\Block\Element\AbstractBlock;
use League\CommonMark\Block\Element\Paragraph;
use League\CommonMark\Block\Renderer\BlockRendererInterface;
use League\CommonMark\ElementRendererInterface;
final class ParagraphRenderer implements BlockRendererInterface
{
public function render(AbstractBlock $block, ElementRendererInterface $htmlRenderer, $inTightList = false)
{
if (!($block instanceof Paragraph)) {
throw new \InvalidArgumentException('Incompatible block type: '.get_class($block));
}
return $htmlRenderer->renderInlines($block->children());
}
}
<file_sep>/src/HypothesisClient/Serializer/TokenDenormalizer.php
<?php
namespace eLife\HypothesisClient\Serializer;
use eLife\HypothesisClient\Model\Token;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
final class TokenDenormalizer implements DenormalizerInterface, DenormalizerAwareInterface
{
use DenormalizerAwareTrait;
public function denormalize($data, $class, $format = null, array $context = []) : Token
{
return new Token($data['access_token'], $data['token_type'], $data['expires_in'], $data['refresh_token']);
}
public function supportsDenormalization($data, $type, $format = null) : bool
{
return Token::class === $type;
}
}
<file_sep>/tests/Annotations/ApplicationTestCase.php
<?php
namespace tests\eLife\Annotations;
use Csa\GuzzleHttp\Middleware\Cache\Adapter\StorageAdapterInterface;
use eLife\Annotations\AppKernel;
use eLife\ApiSdk\ApiSdk;
use eLife\ApiValidator\MessageValidator;
use function GuzzleHttp\json_encode;
abstract class ApplicationTestCase extends ApiTestCase
{
/** @var AppKernel */
private $app;
/**
* @before
*/
final public function setUpApp()
{
$this->app = new AppKernel('test');
}
final protected function getApp() : AppKernel
{
return $this->app;
}
final protected function getApiSdk() : ApiSdk
{
return $this->app->get('api.sdk');
}
final protected function getMockStorage() : StorageAdapterInterface
{
return $this->app->get('guzzle.mock.in_memory_storage');
}
final protected function getValidator() : MessageValidator
{
return $this->app->get('elife.json_message_validator');
}
final protected function assertJsonStringEqualsJson(array $expectedJson, string $actualJson, $message = '')
{
$this->assertJsonStringEqualsJsonString(json_encode($expectedJson), $actualJson, $message);
}
}
<file_sep>/src/HypothesisClient/Serializer/Annotation/Target/Selector/TextQuoteDenormalizer.php
<?php
namespace eLife\HypothesisClient\Serializer\Annotation\Target\Selector;
use eLife\HypothesisClient\Model\Annotation\Target\Selector\TextQuote;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
final class TextQuoteDenormalizer implements DenormalizerInterface, DenormalizerAwareInterface
{
use DenormalizerAwareTrait;
public function denormalize($data, $class, $format = null, array $context = []) : TextQuote
{
return new TextQuote($data['exact'], $data['prefix'], $data['suffix']);
}
public function supportsDenormalization($data, $type, $format = null) : bool
{
return TextQuote::class === $type;
}
}
<file_sep>/tests/HypothesisClient/ApiSdkTest.php
<?php
namespace tests\eLife\HypothesisClient;
use eLife\HypothesisClient\ApiSdk;
use eLife\HypothesisClient\Client\Users;
use eLife\HypothesisClient\Clock\SystemClock;
use eLife\HypothesisClient\Credentials\JWTSigningCredentials;
use eLife\HypothesisClient\Credentials\UserManagementCredentials;
use eLife\HypothesisClient\HttpClient\HttpClient;
use eLife\HypothesisClient\Model\User;
use eLife\HypothesisClient\Result\ArrayResult;
use GuzzleHttp\Promise\FulfilledPromise;
use GuzzleHttp\Psr7\Request;
use PHPUnit\Framework\TestCase;
/**
* @covers \eLife\HypothesisClient\ApiSdk
*/
final class ApiSdkTest extends TestCase
{
/**
* @test
*/
public function it_creates_a_users_client()
{
$this->assertInstanceOf(
Users::class,
(new ApiSdk($this->getMockBuilder(HttpClient::class)->getMock(), null, new JWTSigningCredentials('client_it', 'client_secret', 'authority', new SystemClock())))->users()
);
}
/**
* @test
*/
public function it_may_have_user_management_credentials()
{
$httpClient = $this->getMockBuilder(HttpClient::class)
->getMock();
$userManagement = new UserManagementCredentials('client_id', 'secret_key', 'authority');
$sdk = (new ApiSdk(
$httpClient,
$userManagement,
new JWTSigningCredentials('client_it', 'client_secret', 'authority', new SystemClock())
));
$request = new Request(
'PATCH',
'users/username',
['Authorization' => 'Basic '.base64_encode('client_id:secret_key'), 'User-Agent' => 'HypothesisClient'],
'{}'
);
$response = new FulfilledPromise(new ArrayResult([
'username' => 'username',
'email' => '<EMAIL>',
'display_name' => 'Display Name',
'authority' => 'authority',
]));
$user = new User('username', '<EMAIL>', 'Display Name');
$httpClient
->expects($this->once())
->method('send')
->with(RequestConstraint::equalTo($request))
->willReturn($response);
$this->assertEquals($user, $sdk->users()->get('username')->wait());
}
}
<file_sep>/tests/Annotations/ApiTestCase.php
<?php
namespace tests\eLife\Annotations;
use Csa\GuzzleHttp\Middleware\Cache\Adapter\StorageAdapterInterface;
use eLife\Annotations\AppKernel;
use eLife\ApiClient\ApiClient\ProfilesClient;
use eLife\ApiClient\MediaType;
use eLife\ApiSdk\ApiSdk;
use eLife\ApiSdk\Model\Model;
use eLife\ApiSdk\Model\Profile;
use eLife\ApiValidator\MessageValidator;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\MessageInterface;
use Symfony\Component\HttpFoundation\Response as HttpFoundationResponse;
use Traversable;
use function GuzzleHttp\json_encode;
abstract class ApiTestCase extends TestCase
{
use HasDiactorosFactory;
abstract protected function getApp() : AppKernel;
abstract protected function getApiSdk() : ApiSdk;
abstract protected function getMockStorage() : StorageAdapterInterface;
abstract protected function getValidator() : MessageValidator;
final protected function mockNotFound(string $uri, array $headers = [])
{
$this->getMockStorage()->save(
new Request(
'GET',
"https://api.elifesciences.org/$uri",
$headers
),
new Response(
404,
['Content-Type' => 'application/problem+json'],
json_encode([
'title' => 'Not found',
])
)
);
}
final protected function mockHypothesisTokenCall(
string $by,
string $accessToken
) {
$jwt = $this->getApp()->get('hypothesis.sdk.jwt_signing')->getJWT($by);
$json = [
'access_token' => $accessToken,
'token_type' => 'token_type',
'expires_in' => 600,
'refresh_token' => 'refresh_token',
];
$this->getMockStorage()->save(
new Request(
'POST',
'https://hypothes.is/api/token',
[],
http_build_query([
'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
'assertion' => $jwt,
])
),
new Response(
200,
[],
json_encode($json)
)
);
}
final protected function mockHypothesisSearchCall(
string $by,
Traversable $rows,
int $total,
int $page = 1,
int $perPage = 20,
string $group = '',
string $order = 'desc',
string $sort = 'updated',
array $headers = []
) {
$json = [
'total' => $total,
'rows' => iterator_to_array($rows),
];
$offset = ($page - 1) * $perPage;
$this->getMockStorage()->save(
new Request(
'GET',
"https://hypothes.is/api/search?user=$by&group=$group&offset=$offset&limit=$perPage&order=$order&sort=$sort",
$headers
),
new Response(
200,
[],
json_encode($json)
)
);
}
final protected function createAnnotations($total = 10) : Traversable
{
for ($i = 1; $i <= $total; ++$i) {
// Allow a variety of annotation structures to be present, without being random.
$updated = (0 === $i % 2);
$text = ($i % 4 > 0);
$highlight = !$text ? true : (($i + 1) % 4 > 0);
$ancestors = (0 === $i % 3) ? ($i % 7) + 1 : 0;
yield $this->createAnnotation($i, $updated, $text, $highlight, $ancestors);
}
}
final protected function createAnnotation($id, $updated = true, $text = true, $highlight = true, int $ancestors = 0) : array
{
$created = '2017-12-18T15:11:30.887421+00:00';
return array_filter([
'id' => 'identifier'.$id,
'text' => $text ? 'Annotation text '.$id : null,
'created' => $created,
'updated' => $updated ? '2017-12-19T11:13:30.796543+00:00' : $created,
'document' => [
'title' => [
'Document title',
],
],
'target' => [array_filter([
'source' => 'https://elifesciences.org/articles/11860',
'selector' => $highlight ? [
[
'type' => 'RangeSelector',
'startContainer' => 'div[1]',
'endContainer' => 'div[3]',
'startOffset' => 5,
'endOffset' => 25,
],
[
'type' => 'TextPositionSelector',
'start' => 23609,
'end' => 23678,
],
[
'type' => 'TextQuoteSelector',
'exact' => 'Highlighted text '.$id,
'prefix' => '',
'suffix' => '',
],
] : null,
])],
'uri' => 'https://elifesciences.org/articles/11860',
'references' => array_map(function ($v) {
static $co = 0;
++$co;
return $v.$co;
}, array_fill(0, $ancestors, 'ancestor')),
'permissions' => [
'read' => [
'group:__world__',
],
],
]);
}
final protected function mockProfileCall(Profile $profile)
{
$this->getMockStorage()->save(
new Request(
'GET',
"http://api.elifesciences.org/profiles/{$profile->getId()}",
['Accept' => new MediaType(ProfilesClient::TYPE_PROFILE, 1)]
),
new Response(
200,
['Content-Type' => new MediaType(ProfilesClient::TYPE_PROFILE, 1)],
json_encode($this->normalize($profile, false))
)
);
}
final protected function createProfile(string $id, string $name = null, $orcid = null) : Profile
{
$names = array_map('trim', explode(' ', $name ?? '<NAME>'));
$preferred = implode(' ', $names);
$index = array_pop($names);
if (!empty($names)) {
$index .= ', '.implode(' ', $names);
}
return $this->denormalize(
[
'id' => $id,
'emailAddresses' => [],
'affiliations' => [],
'name' => [
'index' => $index,
'preferred' => $preferred,
],
'orcid' => $orcid ?? '0000-0000-0000-0001',
], Profile::class, false);
}
final protected function denormalize(array $json, string $type, bool $snippet = true) : Model
{
return $this->getApiSdk()->getSerializer()->denormalize($json, $type, 'json', ['snippet' => $snippet, 'type' => $snippet]);
}
final protected function normalize(Model $model, bool $snippet = true) : array
{
return $this->getApiSdk()->getSerializer()->normalize($model, 'json', ['snippet' => $snippet, 'type' => $snippet]);
}
final protected function assertResponseIsValid(HttpFoundationResponse $response)
{
$this->assertMessageIsValid($this->getDiactorosFactory()->createResponse($response));
}
final protected function assertMessageIsValid(MessageInterface $message)
{
$this->getValidator()->validate($message);
}
}
<file_sep>/tests/Annotations/AnnotationsTest.php
<?php
namespace tests\eLife\Annotations;
use eLife\ApiClient\ApiClient\ProfilesClient;
use eLife\ApiClient\MediaType;
use EmptyIterator;
use Traversable;
final class AnnotationsTest extends WebTestCase
{
/**
* @test
* @dataProvider typeProvider
*/
public function it_negotiates_type(string $type, int $statusCode)
{
$client = static::createClient();
$this->mockHypothesisSearchCall('1234', $this->createAnnotations(), 20);
$client->request('GET', '/annotations?by=1234', [], [], ['HTTP_ACCEPT' => $type]);
$response = $client->getResponse();
$this->assertResponseIsValid($response);
$this->assertSame($statusCode, $response->getStatusCode(), $response->getContent());
}
public function typeProvider() : Traversable
{
$types = [
'application/vnd.elife.annotation-list+json' => 200,
'application/vnd.elife.annotation-list+json; version=0' => 406,
'application/vnd.elife.annotation-list+json; version=1' => 200,
'application/vnd.elife.annotation-list+json; version=2' => 406,
'text/plain' => 406,
];
foreach ($types as $type => $statusCode) {
yield $type => [$type, $statusCode];
}
}
/**
* @test
*/
public function it_returns_404_if_user_unknown()
{
$client = static::createClient();
$this->mockNotFound('profiles/1234', ['Accept' => new MediaType(ProfilesClient::TYPE_PROFILE, 1)]);
$this->mockHypothesisSearchCall('1234', new EmptyIterator(), 0);
$client->request('GET', '/annotations?by=1234');
$response = $client->getResponse();
$this->assertResponseIsValid($response);
$this->assertSame(404, $response->getStatusCode());
$this->assertSame('application/problem+json', $response->headers->get('Content-Type'));
$this->assertResponseIsValid($response);
$this->assertJsonStringEqualsJson(['title' => 'Unknown profile: 1234', 'type' => 'about:blank'], $response->getContent());
$this->assertFalse($response->isCacheable());
$this->mockProfileCall($this->createProfile('4321'));
$this->mockHypothesisSearchCall('4321', new EmptyIterator(), 0);
$client->request('GET', '/annotations?by=4321');
$response = $client->getResponse();
$this->assertResponseIsValid($response);
$this->assertSame(200, $response->getStatusCode());
}
/**
* @test
* @dataProvider invalidPageProvider
*/
public function it_returns_a_404_for_an_invalid_page(string $page)
{
$client = static::createClient();
$this->mockProfileCall($this->createProfile('1234'));
$this->mockHypothesisSearchCall('1234', new EmptyIterator(), 0, (int) $page);
$client->request('GET', "/annotations?by=1234&page=$page");
$response = $client->getResponse();
$this->assertResponseIsValid($response);
$this->assertSame(404, $response->getStatusCode());
$this->assertSame('application/problem+json', $response->headers->get('Content-Type'));
$this->assertResponseIsValid($response);
$this->assertJsonStringEqualsJson(['title' => "No page $page", 'type' => 'about:blank'], $response->getContent());
$this->assertFalse($response->isCacheable());
}
public function invalidPageProvider() : Traversable
{
foreach (['-1', '0', '2', 'foo'] as $page) {
yield 'page '.$page => [$page];
}
}
/**
* @test
*/
public function it_will_return_restricted_annotations()
{
$client = static::createClient();
$this->mockHypothesisTokenCall('1234', '<PASSWORD>');
$this->mockHypothesisSearchCall('1234', $this->createAnnotations(), 20, 1, 20, '', 'desc', 'updated', ['Authorization' => 'Bearer 1234access']);
$client->request('GET', '/annotations?by=1234&access=restricted', [], [], ['HTTP_X_CONSUMER_GROUPS' => 'user,view-restricted-annotations']);
$response = $client->getResponse();
$this->assertResponseIsValid($response);
$this->assertSame(200, $response->getStatusCode());
}
/**
* @test
*/
public function it_will_return_public_only_annotations_if_authorized_users_ask_for_them_exclusively()
{
$client = static::createClient();
$this->mockHypothesisSearchCall('4321', $this->createAnnotations(), 20);
$client->request('GET', '/annotations?by=4321&access=public', [], [], ['HTTP_X_CONSUMER_GROUPS' => 'user,view-restricted-annotations']);
$response = $client->getResponse();
$this->assertResponseIsValid($response);
$this->assertSame(200, $response->getStatusCode());
}
/**
* @test
*/
public function it_will_return_public_only_annotations_to_unauthorized_users()
{
$client = static::createClient();
$this->mockHypothesisSearchCall('4321', $this->createAnnotations(), 20);
$client->request('GET', '/annotations?by=4321');
$response = $client->getResponse();
$this->assertResponseIsValid($response);
$this->assertSame(200, $response->getStatusCode());
}
/**
* @test
*/
public function it_will_restrict_access_to_private_annotations()
{
$client = static::createClient();
$this->mockHypothesisSearchCall('4321', $this->createAnnotations(), 20);
$client->request('GET', '/annotations?by=4321&access=restricted');
$response = $client->getResponse();
$this->assertResponseIsValid($response);
$this->assertSame(400, $response->getStatusCode());
}
}
<file_sep>/tests/HypothesisClient/Client/SearchTest.php
<?php
namespace tests\eLife\HypothesisClient\Client;
use DateTimeImmutable;
use eLife\HypothesisClient\ApiClient\SearchClient;
use eLife\HypothesisClient\Client\Search;
use eLife\HypothesisClient\HttpClient\HttpClient;
use eLife\HypothesisClient\Model\Annotation;
use eLife\HypothesisClient\Model\SearchResults;
use eLife\HypothesisClient\Result\ArrayResult;
use GuzzleHttp\Promise\FulfilledPromise;
use GuzzleHttp\Psr7\Request;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use tests\eLife\HypothesisClient\RequestConstraint;
/**
* @covers \eLife\HypothesisClient\Client\Search
*/
final class SearchTest extends TestCase
{
private $denormalizer;
private $group;
private $httpClient;
/** @var Search */
private $search;
/** @var SearchClient */
private $searchClient;
/**
* @before
*/
public function prepareDependencies()
{
$this->group = 'group';
$this->denormalizer = $this->getMockBuilder(DenormalizerInterface::class)
->setMethods(['denormalize', 'supportsDenormalization'])
->getMock();
$this->httpClient = $this->getMockBuilder(HttpClient::class)
->setMethods(['send'])
->getMock();
$this->searchClient = new SearchClient($this->httpClient, $this->group);
$this->search = new Search($this->searchClient, $this->denormalizer);
}
/**
* @test
*/
public function it_will_list_annotations()
{
$created = '2017-12-29T17:02:56.346939+00:00';
$updated = '2017-12-29T18:02:56.359872+00:00';
$request = new Request(
'GET',
'search?user=username&group=group&offset=0&limit=20&order=desc&sort=updated',
['User-Agent' => 'HypothesisClient']
);
$rows = [
[
'id' => 'identifier1',
'text' => 'text',
'created' => $created,
'updated' => $updated,
'document' => [
'title' => [
'title1',
],
],
'target' => [
[
'source' => 'source1',
],
],
'uri' => 'uri1',
'permissions' => [
'read' => [
'read',
],
],
],
[
'id' => 'identifier2',
'created' => $created,
'updated' => $updated,
'document' => [
'title' => [
'title2',
],
],
'target' => [
[
'source' => 'source2',
'selector' => [
[
'type' => 'RangeSelector',
'startContainer' => 'start_container',
'endContainer' => 'end_container',
'startOffset' => 0,
'endOffset' => 10,
],
[
'type' => 'TextPositionSelector',
'start' => 0,
'end' => 10,
],
[
'type' => 'TextQuoteSelector',
'exact' => 'exact',
'prefix' => 'prefix',
'suffix' => 'suffix',
],
[
'type' => 'FragmentSelector',
'conformsTo' => 'conforms_to',
'value' => 'value',
],
],
],
],
'references' => [
'ancestor1',
'ancestor2',
],
'uri' => 'uri1',
'permissions' => [
'read' => [
'read',
],
],
],
];
$response = new FulfilledPromise(new ArrayResult(
[
'total' => 100,
'rows' => $rows,
]
));
$annotations = [
new Annotation(
'identifier1',
'text',
new DateTimeImmutable($created),
new DateTimeImmutable($created),
new Annotation\Document('title1'),
new Annotation\Target('source1'),
'uri1',
[],
new Annotation\Permissions('read')
),
new Annotation(
'identifier2',
null,
new DateTimeImmutable($created),
new DateTimeImmutable($updated),
new Annotation\Document('title2'),
new Annotation\Target(
'source2',
new Annotation\Target\Selector(
new Annotation\Target\Selector\TextQuote('exact', 'prefix', 'suffix')
)
),
'uri2',
[
'ancestor1',
'ancestor2',
],
new Annotation\Permissions('read')
),
];
$this->denormalizer
->expects($this->at(0))
->method('denormalize')
->with($rows[0], Annotation::class)
->willReturn($annotations[0]);
$this->denormalizer
->expects($this->at(1))
->method('denormalize')
->with($rows[1], Annotation::class)
->willReturn($annotations[1]);
$this->httpClient
->expects($this->once())
->method('send')
->with(RequestConstraint::equalTo($request))
->willReturn($response);
$query = $this->search->query('username', null, 0, 20, true, 'updated')->wait();
$this->assertEquals(new SearchResults(100, $annotations), $query);
}
}
<file_sep>/src/Annotations/AppKernel.php
<?php
namespace eLife\Annotations;
use Aws\Sqs\SqsClient;
use ComposerLocator;
use Csa\GuzzleHttp\Middleware\Cache\MockMiddleware;
use eLife\Annotations\Controller\AnnotationsController;
use eLife\Annotations\Provider\QueueCommandsProvider;
use eLife\Annotations\Serializer\CommonMark;
use eLife\Annotations\Serializer\CommonMark\HtmlPurifierRenderer;
use eLife\Annotations\Serializer\CommonMark\MathEscapeRenderer;
use eLife\Annotations\Serializer\HypothesisClientAnnotationNormalizer;
use eLife\ApiClient\HttpClient\BatchingHttpClient;
use eLife\ApiClient\HttpClient\Guzzle6HttpClient;
use eLife\ApiClient\HttpClient\NotifyingHttpClient;
use eLife\ApiProblem\Silex\ApiProblemProvider;
use eLife\ApiSdk\ApiSdk;
use eLife\ApiValidator\MessageValidator\JsonMessageValidator;
use eLife\ApiValidator\SchemaFinder\PathBasedSchemaFinder;
use eLife\Bus\Limit\CompositeLimit;
use eLife\Bus\Limit\LoggingLimit;
use eLife\Bus\Limit\MemoryLimit;
use eLife\Bus\Limit\SignalsLimit;
use eLife\Bus\Queue\Mock\WatchableQueueMock;
use eLife\Bus\Queue\SqsMessageTransformer;
use eLife\Bus\Queue\SqsWatchableQueue;
use eLife\ContentNegotiator\Silex\ContentNegotiationProvider;
use eLife\HypothesisClient\ApiSdk as HypothesisSdk;
use eLife\HypothesisClient\Clock\FixedClock;
use eLife\HypothesisClient\Clock\SystemClock;
use eLife\HypothesisClient\Credentials\JWTSigningCredentials;
use eLife\HypothesisClient\Credentials\UserManagementCredentials;
use eLife\HypothesisClient\HttpClient\BatchingHttpClient as HypothesisBatchingHttpClient;
use eLife\HypothesisClient\HttpClient\Guzzle6HttpClient as HypothesisGuzzle6HttpClient;
use eLife\HypothesisClient\HttpClient\NotifyingHttpClient as HypothesisNotifyingHttpClient;
use eLife\Logging\Monitoring;
use eLife\Logging\Silex\LoggerProvider;
use eLife\Ping\Silex\PingControllerProvider;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use HTMLPurifier;
use JsonSchema\Validator;
use Knp\Provider\ConsoleServiceProvider;
use League\CommonMark\Block as CommonMarkBlock;
use League\CommonMark\DocParser;
use League\CommonMark\ElementRendererInterface;
use League\CommonMark\Environment;
use League\CommonMark\HtmlRenderer;
use League\CommonMark\Inline as CommonMarkInline;
use LogicException;
use Pimple\Exception\UnknownIdentifierException;
use Psr\Container\ContainerInterface;
use Psr\Log\LogLevel;
use Silex\Application;
use Silex\Provider\HttpFragmentServiceProvider;
use Silex\Provider\ServiceControllerServiceProvider;
use Silex\Provider\TwigServiceProvider;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\TerminableInterface;
use tests\eLife\Annotations\InMemoryStorageAdapter;
use tests\eLife\Annotations\ValidatingStorageAdapter;
use function GuzzleHttp\Psr7\str;
final class AppKernel implements ContainerInterface, HttpKernelInterface, TerminableInterface
{
private $app;
public function __construct(string $environment = 'dev')
{
$configFile = __DIR__.'/../../config.php';
$config = array_merge(
'test' !== $environment && file_exists($configFile) ? require $configFile : [],
require __DIR__."/../../config/{$environment}.php"
);
$cache_path = $config['cache']['path'] ?? __DIR__.'/../../var/cache';
$this->app = new Application([
'debug' => $config['debug'] ?? false,
'cache.path' => $cache_path,
'logger.channel' => 'annotations',
'logger.path' => $config['logging']['path'] ?? __DIR__.'/../../var/logs',
'logger.level' => $config['logging']['level'] ?? LogLevel::INFO,
'api.url' => $config['api_url'] ?? 'https://api.elifesciences.org/',
'api.requests_batch' => $config['api_requests_batch'] ?? 10,
'process_memory_limit' => $config['process_memory_limit'] ?? 256,
'aws' => ($config['aws'] ?? []) + [
'queue_name' => 'annotations--prod',
'queue_message_default_type' => 'profile',
'credential_file' => true,
'region' => 'us-east-1',
'endpoint' => 'http://localhost:4100',
'stub' => false,
],
'hypothesis' => ($config['hypothesis'] ?? []) + [
'api_url' => 'https://hypothes.is/api/',
'user_management' => [
'client_id' => '',
'client_secret' => '',
],
'jwt_signing' => [
'client_id' => '',
'client_secret' => '',
'expire' => 600,
],
'authority' => '',
'group' => '',
],
'common_mark.environment' => ($config['common_mark']['environment'] ?? []) + [
'allow_unsafe_links' => false,
],
'html_purifier' => ($config['html_purifier'] ?? []) + [
'Cache.SerializerPath' => $cache_path.'/html_purifier',
],
'mock' => $config['mock'] ?? false,
]);
$this->app->register(new ApiProblemProvider());
$this->app->register(new ContentNegotiationProvider());
$this->app->register(new LoggerProvider());
$this->app->register(new PingControllerProvider());
$this->app->register(new ServiceControllerServiceProvider());
$this->app['api_problem.factory.include_exception_details'] = $config['api_problem']['factory']['include_exception_details'] ?? $this->app['debug'];
if ($this->app['debug']) {
$this->app->register(new HttpFragmentServiceProvider());
$this->app->register(new TwigServiceProvider());
$this->app->get('/error', function () {
$this->app['logger']->debug('Simulating error');
throw new LogicException('Simulated error');
});
}
$this->app['monitoring'] = function () {
return new Monitoring();
};
/*
* @internal
*/
$this->app['limit._memory'] = function () {
return MemoryLimit::mb($this->app['process_memory_limit']);
};
/*
* @internal
*/
$this->app['limit._signals'] = function () {
return SignalsLimit::stopOn(['SIGINT', 'SIGTERM', 'SIGHUP']);
};
$this->app['limit.long_running'] = function () {
return new LoggingLimit(
new CompositeLimit(
$this->app['limit._memory'],
$this->app['limit._signals']
),
$this->app['logger']
);
};
$this->app['limit.interactive'] = function () {
return new LoggingLimit(
$this->app['limit._signals'],
$this->app['logger']
);
};
$this->app['hypothesis.guzzle.handler'] = function () {
return HandlerStack::create();
};
$this->app['api.guzzle.handler'] = function () {
return HandlerStack::create();
};
if ($this->app['mock']) {
$this->app['elife.json_message_validator'] = function () {
return new JsonMessageValidator(
new PathBasedSchemaFinder(ComposerLocator::getPath('elife/api').'/dist/model'),
new Validator()
);
};
$this->app['guzzle.mock.in_memory_storage'] = function () {
return new InMemoryStorageAdapter();
};
$this->app['api.guzzle.mock.validating_storage'] = function () {
return new ValidatingStorageAdapter($this->app['guzzle.mock.in_memory_storage'], $this->app['elife.json_message_validator']);
};
$this->app['api.guzzle.mock'] = function () {
return new MockMiddleware($this->app['api.guzzle.mock.validating_storage'], 'replay');
};
$this->app['hypothesis.guzzle.mock'] = function () {
return new MockMiddleware($this->app['guzzle.mock.in_memory_storage'], 'replay');
};
$this->app->extend('api.guzzle.handler', function (HandlerStack $stack) {
$stack->push($this->app['api.guzzle.mock']);
return $stack;
});
$this->app->extend('hypothesis.guzzle.handler', function (HandlerStack $stack) {
$stack->push($this->app['hypothesis.guzzle.mock']);
return $stack;
});
}
$this->app['hypothesis.guzzle'] = function () {
$logger = $this->app['logger'];
$this->app->extend('hypothesis.guzzle.handler', function (HandlerStack $stack) use ($logger) {
$stack->push(
Middleware::mapRequest(function ($request) use ($logger) {
$logger->debug("Request performed in Guzzle Middleware: {$request->getUri()}.", ['request' => str($request)]);
return $request;
})
);
$stack->push(
Middleware::mapResponse(function ($response) use ($logger) {
$logger->debug('Response received in Guzzle Middleware.', ['response' => str($response)]);
return $response;
})
);
return $stack;
});
return new Client([
'base_uri' => $this->app['hypothesis']['api_url'],
'connect_timeout' => 0.5,
'decode_content' => 'gzip',
'handler' => $this->app['hypothesis.guzzle.handler'],
'timeout' => 0.9,
]);
};
$this->app['hypothesis.sdk.jwt_signing'] = function () {
return new JWTSigningCredentials(
$this->app['hypothesis']['jwt_signing']['client_id'],
$this->app['hypothesis']['jwt_signing']['client_secret'],
$this->app['hypothesis']['authority'],
(!$this->app['mock']) ? new SystemClock() : new FixedClock()
);
};
$this->app['hypothesis.sdk'] = function () {
$notifyingHttpClient = new HypothesisNotifyingHttpClient(
new HypothesisBatchingHttpClient(
new HypothesisGuzzle6HttpClient(
$this->app['hypothesis.guzzle']
),
$this->app['api.requests_batch']
)
);
if ($this->app['debug']) {
$logger = $this->app['logger'];
$notifyingHttpClient->addRequestListener(function ($request) use ($logger) {
$logger->debug("Request performed in NotifyingHttpClient: {$request->getUri()}");
});
}
$userManagement = new UserManagementCredentials(
$this->app['hypothesis']['user_management']['client_id'],
$this->app['hypothesis']['user_management']['client_secret'],
$this->app['hypothesis']['authority']
);
return new HypothesisSdk($notifyingHttpClient, $userManagement, $this->app['hypothesis.sdk.jwt_signing'], $this->app['hypothesis']['group']);
};
$this->app['api.guzzle'] = function () {
$logger = $this->app['logger'];
$this->app->extend('api.guzzle.handler', function (HandlerStack $stack) use ($logger) {
$stack->push(
Middleware::mapRequest(function ($request) use ($logger) {
$logger->debug("Request performed in Guzzle Middleware: {$request->getUri()}.", ['request' => str($request)]);
return $request;
})
);
$stack->push(
Middleware::mapResponse(function ($response) use ($logger) {
$logger->debug('Response received in Guzzle Middleware.', ['response' => str($response)]);
return $response;
})
);
return $stack;
});
return new Client([
'base_uri' => $this->app['api.url'],
'connect_timeout' => 0.5,
'handler' => $this->app['api.guzzle.handler'],
'timeout' => 0.9,
]);
};
$this->app['api.sdk'] = function () {
$notifyingHttpClient = new NotifyingHttpClient(
new BatchingHttpClient(
new Guzzle6HttpClient(
$this->app['api.guzzle']
),
$this->app['api.requests_batch']
)
);
if ($this->app['debug']) {
$logger = $this->app['logger'];
$notifyingHttpClient->addRequestListener(function ($request) use ($logger) {
$logger->debug("Request performed in NotifyingHttpClient: {$request->getUri()}");
});
}
return new ApiSdk($notifyingHttpClient);
};
$this->app['aws.sqs'] = function () {
$config = [
'version' => '2012-11-05',
'region' => $this->app['aws']['region'],
];
if (isset($this->app['aws']['endpoint'])) {
$config['endpoint'] = $this->app['aws']['endpoint'];
}
if (!isset($this->app['aws']['credential_file']) || $this->app['aws']['credential_file'] === false) {
$config['credentials'] = [
'key' => $this->app['aws']['key'],
'secret' => $this->app['aws']['secret'],
];
}
return new SqsClient($config);
};
$this->app['aws.queue'] = function () {
if ($this->app['aws']['stub']) {
return new WatchableQueueMock();
} else {
return new SqsWatchableQueue($this->app['aws.sqs'], $this->app['aws']['queue_name']);
}
};
$this->app['aws.queue_transformer'] = function () {
return new SqsMessageTransformer($this->app['api.sdk']);
};
$this->app->register(new ConsoleServiceProvider(), [
'console.name' => 'Annotations console',
'console.version' => '0.1.0',
'console.project_directory' => __DIR__.'/../..',
]);
$this->app->register(new QueueCommandsProvider(), [
'sqs.queue_message_type' => $this->app['aws']['queue_message_default_type'],
'sqs.queue_name' => $this->app['aws']['queue_name'],
'sqs.region' => $this->app['aws']['region'],
]);
$this->app['annotation.serializer.common_mark.environment'] = function () {
$environment = Environment::createCommonMarkEnvironment();
$environment->setConfig($this->app['common_mark.environment']);
$environment->addBlockRenderer(CommonMarkBlock\Element\BlockQuote::class, new CommonMark\Block\Renderer\BlockQuoteRenderer());
$environment->addBlockRenderer(CommonMarkBlock\Element\FencedCode::class, new CommonMark\Block\Renderer\CodeRenderer());
$environment->addBlockRenderer(CommonMarkBlock\Element\HtmlBlock::class, new CommonMark\Block\Renderer\HtmlBlockRenderer());
$environment->addBlockRenderer(CommonMarkBlock\Element\IndentedCode::class, new CommonMark\Block\Renderer\CodeRenderer());
$environment->addBlockRenderer(CommonMarkBlock\Element\ListItem::class, new CommonMark\Block\Renderer\ListItemRenderer());
$environment->addBlockRenderer(CommonMarkBlock\Element\Paragraph::class, new CommonMark\Block\Renderer\ParagraphRenderer());
$environment->addInlineRenderer(CommonMarkInline\Element\HtmlInline::class, new CommonMark\Inline\Renderer\HtmlInlineRenderer());
$environment->addInlineRenderer(CommonMarkInline\Element\Image::class, new CommonMark\Inline\Renderer\ImageRenderer());
return $environment;
};
$this->app['annotation.serializer.common_mark.doc_parser'] = function () {
return new DocParser($this->app['annotation.serializer.common_mark.environment']);
};
$this->app['annotation.serializer.common_mark.element_renderer'] = function () {
return new HtmlRenderer($this->app['annotation.serializer.common_mark.environment']);
};
$this->app['annotation.serializer.html_purifier'] = function () {
return new HTMLPurifier($this->app['html_purifier']);
};
$this->app->extend('annotation.serializer.common_mark.element_renderer', function (ElementRendererInterface $elementRenderer) {
return new MathEscapeRenderer($elementRenderer);
});
$this->app->extend('annotation.serializer.common_mark.element_renderer', function (ElementRendererInterface $elementRenderer) {
return new HtmlPurifierRenderer($elementRenderer, $this->app['annotation.serializer.html_purifier']);
});
$this->app['annotation.serializer'] = function () {
return new HypothesisClientAnnotationNormalizer($this->app['annotation.serializer.common_mark.doc_parser'], $this->app['annotation.serializer.common_mark.element_renderer'], $this->app['logger']);
};
$this->app['controllers.annotations'] = function () {
return new AnnotationsController($this->app['hypothesis.sdk'], $this->app['api.sdk'], $this->app['annotation.serializer']);
};
$this->app->get('/annotations', 'controllers.annotations:annotationsAction')
->before($this->app['negotiate.accept'](
'application/vnd.elife.annotation-list+json; version=1'
));
$this->app->after(function (Request $request, Response $response) {
if ($response->isCacheable()) {
$response->headers->set('ETag', md5($response->getContent()));
$response->isNotModified($request);
}
});
}
public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true) : Response
{
return $this->app->handle($request, $type, $catch);
}
public function terminate(Request $request, Response $response)
{
$this->app->terminate($request, $response);
}
public function get($id)
{
if (!isset($this->app[$id])) {
throw new UnknownIdentifierException($id);
}
return $this->app[$id];
}
public function has($id) : bool
{
return isset($this->app[$id]);
}
}
<file_sep>/src/HypothesisClient/Model/SearchResults.php
<?php
namespace eLife\HypothesisClient\Model;
final class SearchResults
{
private $total;
private $annotations;
/**
* @internal
*/
public function __construct(int $total, array $annotations)
{
$this->total = $total;
$this->annotations = $annotations;
}
public function getTotal() : int
{
return $this->total;
}
/**
* @return Annotation[]
*/
public function getAnnotations() : array
{
return $this->annotations;
}
}
<file_sep>/project_tests.sh
#!/usr/bin/env bash
set -e
rm -f build/*.xml
echo "PHPUnit tests"
vendor/bin/phpunit --log-junit build/phpunit.xml
<file_sep>/tests/Annotations/Command/QueuePushCommandTest.php
<?php
namespace tests\eLife\Annotations\Command;
use eLife\Annotations\Command\QueueImportCommand;
use eLife\Annotations\Command\QueuePushCommand;
use eLife\Bus\Queue\InternalSqsMessage;
use eLife\Bus\Queue\Mock\WatchableQueueMock;
use PHPUnit\Framework\TestCase;
use Psr\Log\NullLogger;
use RuntimeException;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
/**
* @covers \eLife\Annotations\Command\QueuePushCommand
*/
final class QueuePushCommandTest extends TestCase
{
/** @var Application */
private $application;
/** @var QueueImportCommand */
private $command;
/** @var CommandTester */
private $commandTester;
private $logger;
/** @var WatchableQueueMock */
private $queue;
/**
* @before
*/
public function prepareDependencies()
{
$this->application = new Application();
$this->logger = new NullLogger();
$this->queue = new WatchableQueueMock();
}
/**
* @test
*/
public function it_will_push_to_the_queue()
{
$this->prepareCommandTester();
$this->assertEmpty($this->queue->count());
$this->commandTesterExecute('id', 'profiles');
$this->assertSame(1, $this->queue->count());
$this->assertEquals(new InternalSqsMessage('profiles', 'id'), $this->queue->dequeue());
}
/**
* @test
*/
public function it_requires_an_id()
{
$this->prepareCommandTester();
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('Not enough arguments (missing: "id").');
$this->commandTesterExecute(null, 'profiles');
}
/**
* @test
*/
public function it_requires_a_type()
{
$this->prepareCommandTester();
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('Not enough arguments (missing: "type").');
$this->commandTesterExecute('id', null);
}
/**
* @test
*/
public function it_may_have_a_default_type()
{
$this->prepareCommandTester('defaultType');
$this->commandTesterExecute('id', null);
$this->assertEquals(new InternalSqsMessage('defaultType', 'id'), $this->queue->dequeue());
}
/**
* @test
*/
public function it_may_override_the_default_type()
{
$this->prepareCommandTester('defaultType');
$this->commandTesterExecute('id', 'overrideType');
$this->assertEquals(new InternalSqsMessage('overrideType', 'id'), $this->queue->dequeue());
}
private function prepareCommandTester($type = null)
{
$this->command = new QueuePushCommand($this->queue, $this->logger, $type);
$this->application->add($this->command);
$this->commandTester = new CommandTester($this->application->get($this->command->getName()));
}
private function commandTesterExecute($id, $type)
{
$execArgs = array_filter(
[
'command' => $this->command->getName(),
'id' => $id,
'type' => $type,
]
);
$this->commandTester->execute($execArgs);
}
}
<file_sep>/src/HypothesisClient/Serializer/Annotation/DocumentDenormalizer.php
<?php
namespace eLife\HypothesisClient\Serializer\Annotation;
use eLife\HypothesisClient\Model\Annotation\Document;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
final class DocumentDenormalizer implements DenormalizerInterface, DenormalizerAwareInterface
{
use DenormalizerAwareTrait;
const NO_TITLE_AVAILABLE_COPY = 'No title available';
public function denormalize($data, $class, $format = null, array $context = []) : Document
{
return new Document($data['title'][0] ?? self::NO_TITLE_AVAILABLE_COPY);
}
public function supportsDenormalization($data, $type, $format = null) : bool
{
return Document::class === $type;
}
}
<file_sep>/tests/HypothesisClient/Serializer/Annotation/Target/Selector/TextQuoteDenormalizerTest.php
<?php
namespace tests\eLife\HypothesisClient\Serializer\Annotation\Target\Selector;
use eLife\HypothesisClient\Model\Annotation\Target\Selector\TextQuote;
use eLife\HypothesisClient\Serializer\Annotation\Target\Selector\TextQuoteDenormalizer;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
/**
* @covers \eLife\HypothesisClient\Serializer\Annotation\Target\Selector\TextQuoteDenormalizer
*/
final class TextQuoteDenormalizerTest extends TestCase
{
/** @var TextQuoteDenormalizer */
private $normalizer;
/**
* @before
*/
protected function setUpNormalizer()
{
$this->normalizer = new TextQuoteDenormalizer();
}
/**
* @test
*/
public function it_is_a_denormalizer()
{
$this->assertInstanceOf(DenormalizerInterface::class, $this->normalizer);
}
/**
* @test
* @dataProvider canDenormalizeProvider
*/
public function it_can_denormalize_text_quotes($data, $format, array $context, bool $expected)
{
$this->assertSame($expected, $this->normalizer->supportsDenormalization($data, $format, $context));
}
public function canDenormalizeProvider() : array
{
return [
'text-quote' => [[], TextQuote::class, [], true],
'non-text-quote' => [[], get_class($this), [], false],
];
}
/**
* @test
* @dataProvider denormalizeProvider
*/
public function it_will_denormalize_text_quotes(array $json, TextQuote $expected)
{
$this->assertEquals($expected, $this->normalizer->denormalize($json, TextQuote::class));
}
public function denormalizeProvider() : array
{
return [
'complete' => [
[
'exact' => 'a new human species',
'prefix' => 'have been assigned to ',
'suffix' => ', Homo naledi',
],
new TextQuote('a new human species', 'have been assigned to ', ', Homo naledi'),
],
];
}
}
<file_sep>/src/HypothesisClient/ApiClient/TokenClient.php
<?php
namespace eLife\HypothesisClient\ApiClient;
use eLife\HypothesisClient\Credentials\JWTSigningCredentials;
use eLife\HypothesisClient\HttpClient\HttpClient;
use eLife\HypothesisClient\HttpClient\UserAgentPrependingHttpClient;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7\Uri;
final class TokenClient
{
use ApiClient;
private $credentials;
public function __construct(HttpClient $httpClient, JWTSigningCredentials $credentials, array $headers = [])
{
$this->httpClient = new UserAgentPrependingHttpClient($httpClient, 'HypothesisClient');
$this->headers = $headers;
$this->credentials = $credentials;
}
public function getToken(
array $headers,
string $username
) : PromiseInterface {
$jwt = $this->credentials->getJWT($username);
return $this->postRequest(
Uri::fromParts([
'path' => 'token',
]),
$headers,
http_build_query([
'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
'assertion' => $jwt,
])
);
}
}
<file_sep>/tests/HypothesisClient/Serializer/UserDenormalizerTest.php
<?php
namespace tests\eLife\HypothesisClient\Serializer;
use eLife\HypothesisClient\Model\User;
use eLife\HypothesisClient\Serializer\UserDenormalizer;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
/**
* @covers \eLife\HypothesisClient\Serializer\UserDenormalizer
*/
final class UserDenormalizerTest extends TestCase
{
/** @var UserDenormalizer */
private $normalizer;
/**
* @before
*/
protected function setUpNormalizer()
{
$this->normalizer = new UserDenormalizer();
}
/**
* @test
*/
public function it_is_a_denormalizer()
{
$this->assertInstanceOf(DenormalizerInterface::class, $this->normalizer);
}
/**
* @test
* @dataProvider canDenormalizeProvider
*/
public function it_can_denormalize_users($data, $format, array $context, bool $expected)
{
$this->assertSame($expected, $this->normalizer->supportsDenormalization($data, $format, $context));
}
public function canDenormalizeProvider() : array
{
return [
'user' => [[], User::class, [], true],
'non-user' => [[], get_class($this), [], false],
];
}
/**
* @test
* @dataProvider denormalizeProvider
*/
public function it_will_denormalize_users(array $json, User $expected)
{
$this->assertEquals($expected, $this->normalizer->denormalize($json, User::class));
}
public function denormalizeProvider() : array
{
return [
'complete' => [
[
'username' => 'jcarberry',
'email' => '<EMAIL>',
'display_name' => '<NAME>',
'new' => true,
],
new User('jcarberry', '<EMAIL>', '<NAME>', true),
],
'no-email' => [
[
'username' => 'jcarberry',
'display_name' => '<NAME>',
'new' => true,
],
new User('jcarberry', null, '<NAME>', true),
],
'no-display-name' => [
[
'username' => 'jcarberry',
'email' => '<EMAIL>',
'new' => true,
],
new User('jcarberry', '<EMAIL>', null, true),
],
'minimum' => [
[
'username' => 'jcarberry',
'email' => '<EMAIL>',
'display_name' => '<NAME>',
],
new User('jcarberry', '<EMAIL>', '<NAME>'),
],
];
}
}
<file_sep>/tests/HypothesisClient/Exception/ApiTimeoutTest.php
<?php
namespace tests\eLife\HypothesisClient\Exception;
use eLife\HypothesisClient\Exception\ApiTimeout;
use eLife\HypothesisClient\Exception\NetworkProblem;
use GuzzleHttp\Psr7\Request;
use PHPUnit\Framework\TestCase;
/**
* @covers \eLife\HypothesisClient\Exception\ApiTimeout
*/
final class ApiTimeoutTest extends TestCase
{
/**
* @test
*/
public function it_is_an_instance_of_network_problem()
{
$e = new ApiTimeout('foo', new Request('GET', 'http://www.example.com/'));
$this->assertInstanceOf(NetworkProblem::class, $e);
}
}
<file_sep>/tests/HypothesisClient/Model/Annotation/DocumentTest.php
<?php
namespace tests\eLife\HypothesisClient\Model\Annotation;
use eLife\HypothesisClient\Model\Annotation\Document;
use PHPUnit\Framework\TestCase;
/**
* @covers \eLife\HypothesisClient\Model\Annotation\Document
*/
final class DocumentTest extends TestCase
{
/** @var Document */
private $document;
/**
* @before
*/
public function prepare_document()
{
$this->document = new Document('title');
}
/**
* @test
*/
public function it_has_a_title()
{
$this->assertSame('title', $this->document->getTitle());
}
}
<file_sep>/tests/HypothesisClient/Serializer/Annotation/DocumentDenormalizerTest.php
<?php
namespace tests\eLife\HypothesisClient\Serializer\Annotation;
use eLife\HypothesisClient\Model\Annotation\Document;
use eLife\HypothesisClient\Serializer\Annotation\DocumentDenormalizer;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
/**
* @covers \eLife\HypothesisClient\Serializer\Annotation\DocumentDenormalizer
*/
final class DocumentDenormalizerTest extends TestCase
{
/** @var DocumentDenormalizer */
private $normalizer;
/**
* @before
*/
protected function setUpNormalizer()
{
$this->normalizer = new DocumentDenormalizer();
}
/**
* @test
*/
public function it_is_a_denormalizer()
{
$this->assertInstanceOf(DenormalizerInterface::class, $this->normalizer);
}
/**
* @test
* @dataProvider canDenormalizeProvider
*/
public function it_can_denormalize_documents($data, $format, array $context, bool $expected)
{
$this->assertSame($expected, $this->normalizer->supportsDenormalization($data, $format, $context));
}
public function canDenormalizeProvider() : array
{
return [
'document' => [[], Document::class, [], true],
'non-document' => [[], get_class($this), [], false],
];
}
/**
* @test
* @dataProvider denormalizeProvider
*/
public function it_will_denormalize_documents(array $json, Document $expected)
{
$this->assertEquals($expected, $this->normalizer->denormalize($json, Document::class));
}
public function denormalizeProvider() : array
{
return [
'complete' => [
[
'title' => [
'Human Evolution: The many mysteries of Homo naledi',
],
],
new Document('Human Evolution: The many mysteries of Homo naledi'),
],
'minimum' => [
[],
new Document('No title available'),
],
];
}
}
<file_sep>/tests/HypothesisClient/HttpClient/NotifyingHttpClientTest.php
<?php
namespace tests\eLife\HypothesisClient\HttpClient;
use eLife\HypothesisClient\HttpClient\HttpClient;
use eLife\HypothesisClient\HttpClient\NotifyingHttpClient;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use PHPUnit\Framework\TestCase;
use RuntimeException;
use function GuzzleHttp\Promise\promise_for;
/**
* @covers \eLife\HypothesisClient\HttpClient\NotifyingHttpClient
*/
final class NotifyingHttpClientTest extends TestCase
{
private $originalClient;
private $client;
/**
* @before
*/
protected function setUpOriginalClient()
{
$this->originalClient = $this->createMock(HttpClient::class);
$this->client = new NotifyingHttpClient($this->originalClient);
}
/**
* @test
*/
public function it_allows_listeners_to_monitor_requests()
{
$request = new Request('GET', 'foo');
$response = new Response(200);
$this->originalClient->expects($this->once())
->method('send')
->with($request)
->will($this->returnValue(promise_for($response)));
$this->sentRequests = [];
$this->client->addRequestListener(function ($request) {
$this->sentRequests[] = $request;
});
$this->client->send($request);
$this->assertSame([$request], $this->sentRequests);
}
/**
* @test
*/
public function it_does_not_propagate_errors_of_listeners()
{
$request = new Request('GET', 'foo');
$this->client->addRequestListener(function ($request) {
throw new RuntimeException('mocked error in listener');
});
$this->client->send($request);
$this->assertTrue(true);
}
}
<file_sep>/src/Annotations/Controller/AnnotationsController.php
<?php
namespace eLife\Annotations\Controller;
use eLife\Annotations\ApiResponse;
use eLife\ApiClient\Exception\ApiProblemResponse;
use eLife\ApiSdk\ApiSdk;
use eLife\HypothesisClient\ApiSdk as HypothesisSdk;
use eLife\HypothesisClient\Model\Annotation;
use eLife\HypothesisClient\Model\SearchResults;
use eLife\HypothesisClient\Model\Token;
use Negotiation\Accept;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use function GuzzleHttp\Psr7\normalize_header;
final class AnnotationsController
{
private $apiSdk;
private $hypothesisSdk;
private $serializer;
public function __construct(HypothesisSdk $hypothesisSdk, ApiSdk $apiSdk, NormalizerInterface $serializer)
{
$this->apiSdk = $apiSdk;
$this->hypothesisSdk = $hypothesisSdk;
$this->serializer = $serializer;
}
public function annotationsAction(Request $request, Accept $type) : Response
{
// Retrieve query parameters.
$by = $request->query->get('by');
$page = $request->query->get('page', 1);
$perPage = $request->query->get('per-page', 20);
$order = $request->query->get('order', 'desc');
$useDate = $request->query->get('use-date', 'updated');
$access = $request->query->get('access', 'public');
// Retrieve consumer groups.
$groups = normalize_header($request->headers->get('X-Consumer-Groups', 'user'));
// Set access options.
$accessOptions = [
'public',
];
// Only allow access to restricted annotations if in the appropriate consumer group.
if (in_array('view-restricted-annotations', $groups)) {
$accessOptions[] = 'restricted';
}
// Verify that by parameter is present.
if (!is_string($by) || empty($by)) {
throw new BadRequestHttpException('Missing by value');
}
// Verify that order parameter is valid.
if (!in_array($order, ['asc', 'desc'])) {
throw new BadRequestHttpException('Invalid order value: asc or desc expected');
}
// Verify that page parameter is valid.
if ($page != (int) $page || $page < 1) {
throw new NotFoundHttpException('No page '.$page);
}
// Verify that per-page parameter is valid.
if ($perPage != (int) $perPage || $perPage < 1 || ($perPage > 100)) {
throw new NotFoundHttpException('Invalid per-page value: 1...100 expected');
}
// Verify that use-date parameter is valid.
if (!in_array($useDate, ['updated', 'created'])) {
throw new BadRequestHttpException('Invalid use-date value: updated or created expected');
}
// Verify that access parameter is valid.
if (!in_array($access, $accessOptions)) {
throw new BadRequestHttpException('Invalid access value: '.implode(' or ', $accessOptions).' expected');
}
// Retrieve access token, if appropriate.
if ('restricted' === $access) {
$accessToken = $this->hypothesisSdk->token()->get($by)
->then(function (Token $token) {
return $token->getAccessToken();
})->wait();
} else {
$accessToken = null;
}
// Perform query to Hypothesis API.
$content = $this->hypothesisSdk->search()->query($by, $accessToken, ($page - 1) * $perPage, $perPage, ('desc' === $order), $useDate)
->then(function (SearchResults $results) {
return [
'total' => $results->getTotal(),
'items' => array_map(function (Annotation $annotation) {
return $this->serializer->normalize($annotation, Annotation::class);
}, $results->getAnnotations()),
];
})->wait();
// Verify that page is in the correct range.
if (0 === count($content['items']) && $page > 1) {
throw new NotFoundHttpException('No page '.$page);
// If no results found, ensure that profile exists.
} elseif (1 == $page && 0 === count($content['items'])) {
$this->apiSdk->profiles()->get($by)
->otherwise(function ($reason) use ($by) {
if ($reason instanceof ApiProblemResponse && Response::HTTP_NOT_FOUND === $reason->getResponse()->getStatusCode()) {
throw new NotFoundHttpException('Unknown profile: '.$by);
}
})->wait();
}
// Set Content-Type.
$headers = ['Content-Type' => $type->getNormalizedValue()];
return new ApiResponse(
$content,
Response::HTTP_OK,
$headers
);
}
}
<file_sep>/src/HypothesisClient/Credentials/JWTSigningCredentials.php
<?php
namespace eLife\HypothesisClient\Credentials;
use eLife\HypothesisClient\Clock\Clock;
use Firebase\JWT\JWT;
final class JWTSigningCredentials extends Credentials
{
private $clock;
private $expire;
public function __construct(string $clientId, string $clientSecret, string $authority, Clock $clock, int $expire = 600)
{
parent::__construct($clientId, $clientSecret, $authority);
$this->clock = $clock;
$this->expire = $expire;
}
public function getJWT(string $username) : string
{
$now = $this->clock->time();
$sub = "acct:{$username}@{$this->getAuthority()}";
$payload = [
'aud' => 'hypothes.is',
'iss' => $this->getClientId(),
'sub' => $sub,
'nbf' => $now,
'exp' => $now + $this->expire,
];
return JWT::encode($payload, $this->getClientSecret(), 'HS256');
}
}
<file_sep>/bin/console
#!/usr/bin/env php
<?php
use eLife\Annotations\AppKernel;
use Symfony\Component\Console\Input\ArgvInput;
require_once __DIR__.'/../vendor/autoload.php';
umask(0002);
set_time_limit(0);
$input = new ArgvInput();
$env = getenv('ENVIRONMENT_NAME');
$app = new AppKernel($env);
$console = $app->get('console');
$console->run();
<file_sep>/tests/Annotations/Serializer/CommonMark/HtmlPurifierRendererTest.php
<?php
namespace tests\eLife\Annotations\Serializer\CommonMark;
use eLife\Annotations\Serializer\CommonMark\HtmlPurifierRenderer;
use HTMLPurifier;
use League\CommonMark\Block\Element\AbstractBlock;
use League\CommonMark\ElementRendererInterface;
use PHPUnit\Framework\TestCase;
/**
* @covers \eLife\Annotations\Serializer\CommonMark\HtmlPurifierRenderer
*/
final class HtmlPurifierRendererTest extends TestCase
{
private $abstractBlock;
/** @var HtmlPurifierRenderer */
private $htmlPurifierRenderer;
private $renderer;
/**
* @before
*/
public function setup()
{
$this->renderer = $this->getMockBuilder(ElementRendererInterface::class)
->getMock();
$this->abstractBlock = $this->createMock(AbstractBlock::class);
$this->htmlPurifierRenderer = new HtmlPurifierRenderer($this->renderer, new HTMLPurifier(['Cache.SerializerPath' => sys_get_temp_dir()]));
}
/**
* @test
* @dataProvider purifyHtmlProvider
*/
public function it_will_purify_html($expected, $rendered = null)
{
$this->renderer
->method('renderBlock')
->willReturn($rendered ?? $expected);
$this->assertSame($expected, $this->htmlPurifierRenderer->renderBlock($this->abstractBlock));
}
public function purifyHtmlProvider()
{
return [
'clean' => [
'<strong>Already</strong> clean html',
],
'strip-tags' => [
'iframe: ',
'iframe: <iframe src="https://elifesciences.org"></iframe>',
],
'strip-all-tags' => [
'',
'<iframe src="https://elifesciences.org"></iframe>',
],
'script' => [
'',
'<script>evil()</script>',
],
'anchor-onclick' => [
'<a href="#">foobar</a>',
'<a href="#" onclick="evil()">foobar</a>',
],
'javascript' => [
'<a>foobar</a>',
'<a href="javascript:alert(\'evil\')">foobar</a>',
],
'img-src-javascript' => [
'',
'<img src="javascript:alert(\'evil\')">',
],
];
}
}
<file_sep>/tests/HypothesisClient/Client/TokenTest.php
<?php
namespace tests\eLife\HypothesisClient\Client;
use eLife\HypothesisClient\ApiClient\TokenClient;
use eLife\HypothesisClient\Client\Token;
use eLife\HypothesisClient\Clock\FixedClock;
use eLife\HypothesisClient\Credentials\JWTSigningCredentials;
use eLife\HypothesisClient\HttpClient\HttpClient;
use eLife\HypothesisClient\Model\Token as ModelToken;
use eLife\HypothesisClient\Model\User;
use eLife\HypothesisClient\Result\ArrayResult;
use GuzzleHttp\Promise\FulfilledPromise;
use GuzzleHttp\Psr7\Request;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use tests\eLife\HypothesisClient\RequestConstraint;
/**
* @covers \eLife\HypothesisClient\Client\Token
*/
final class TokenTest extends TestCase
{
private $authority;
private $clientId;
private $clientSecret;
/** @var JWTSigningCredentials */
private $credentials;
private $denormalizer;
private $group;
private $httpClient;
/** @var Token */
private $token;
/** @var TokenClient */
private $tokenClient;
/**
* @before
*/
public function prepareDependencies()
{
$this->clientId = 'client_id';
$this->clientSecret = 'client_secret';
$this->authority = 'authority';
$this->group = 'group';
$this->credentials = new JWTSigningCredentials($this->clientId, $this->clientSecret, $this->authority, new FixedClock());
$this->denormalizer = $this->getMockBuilder(DenormalizerInterface::class)
->setMethods(['denormalize', 'supportsDenormalization'])
->getMock();
$this->httpClient = $this->getMockBuilder(HttpClient::class)
->setMethods(['send'])
->getMock();
$this->tokenClient = new TokenClient($this->httpClient, $this->credentials);
$this->token = new Token($this->tokenClient, $this->denormalizer);
}
/**
* @test
*/
public function it_will_get_a_token()
{
$request = new Request(
'POST',
'token',
['User-Agent' => 'HypothesisClient'],
http_build_query([
'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
'assertion' => $this->credentials->getJWT('username'),
])
);
$response = new FulfilledPromise(new ArrayResult([
'access_token' => 'access_token',
'token_type' => 'Bearer',
'expires_in' => (float) 3600,
'refresh_token' => '<PASSWORD>_token',
]));
$token = new ModelToken('access_token', 'Bearer', 3600, 'refresh_token');
$this->denormalizer
->method('denormalize')
->with($response->wait()->toArray(), ModelToken::class)
->willReturn($token);
$this->httpClient
->expects($this->once())
->method('send')
->with(RequestConstraint::equalTo($request))
->willReturn($response);
$this->assertSame($token, $this->token->get('username')->wait());
}
}
<file_sep>/src/HypothesisClient/Client/Users.php
<?php
namespace eLife\HypothesisClient\Client;
use eLife\HypothesisClient\ApiClient\UsersClient;
use eLife\HypothesisClient\Exception\BadResponse;
use eLife\HypothesisClient\Model\User;
use eLife\HypothesisClient\Result\Result;
use GuzzleHttp\Promise\PromiseInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use function GuzzleHttp\Promise\rejection_for;
final class Users
{
private $serializer;
private $usersClient;
public function __construct(UsersClient $usersClient, DenormalizerInterface $serializer)
{
$this->usersClient = $usersClient;
$this->serializer = $serializer;
}
public function get(string $id) : PromiseInterface
{
return $this->usersClient
->getUser(
[],
$id
)
->then(function (Result $result) {
return $this->serializer->denormalize($result->toArray(), User::class);
});
}
/**
* Upsert the user by create first then, if user already detected, update.
*/
public function upsert(User $user) : PromiseInterface
{
return $this->create($user)
->otherwise(function ($reason) use ($user) {
if ($reason instanceof BadResponse) {
if (Response::HTTP_CONFLICT === $reason->getResponse()->getStatusCode()) {
// Probably means that the username already exists
return $this->update($user);
} elseif (Response::HTTP_BAD_REQUEST === $reason->getResponse()->getStatusCode()) {
// TODO remove when Hypothesis start returning 409 Conflict responses
return $this->update($user);
}
}
return rejection_for($reason);
});
}
public function create(User $user) : PromiseInterface
{
return $this->usersClient
->createUser(
[],
$user->getUsername(),
$user->getEmail(),
$user->getDisplayName()
)
->then(function (Result $result) {
return $this->serializer->denormalize($result->toArray() + ['new' => true], User::class);
});
}
public function update(User $user) : PromiseInterface
{
return $this->usersClient
->updateUser(
[],
$user->getUsername(),
$user->getEmail(),
$user->getDisplayName()
)
->then(function (Result $result) {
return $this->serializer->denormalize($result->toArray(), User::class, 'json');
});
}
}
<file_sep>/src/HypothesisClient/ApiClient/UsersClient.php
<?php
namespace eLife\HypothesisClient\ApiClient;
use eLife\HypothesisClient\Credentials\UserManagementCredentials;
use eLife\HypothesisClient\HttpClient\HttpClient;
use eLife\HypothesisClient\HttpClient\UserAgentPrependingHttpClient;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7\Uri;
use function GuzzleHttp\json_encode;
final class UsersClient
{
use ApiClient;
private $credentials;
public function __construct(HttpClient $httpClient, UserManagementCredentials $credentials = null, array $headers = [])
{
if ($credentials) {
$headers['Authorization'] = $credentials->getAuthorizationBasic();
}
$this->httpClient = new UserAgentPrependingHttpClient($httpClient, 'HypothesisClient');
$this->headers = $headers;
$this->credentials = $credentials;
}
public function getUser(
array $headers,
string $username
) : PromiseInterface {
return $this->patchRequest(
Uri::fromParts([
'path' => 'users/'.$username,
]),
$headers,
'{}'
);
}
public function createUser(
array $headers,
string $username,
string $email,
string $display_name
) : PromiseInterface {
return $this->postRequest(
Uri::fromParts([
'path' => 'users',
]),
$headers,
json_encode([
'authority' => $this->credentials->getAuthority(),
'username' => $username,
'email' => $email,
'display_name' => $display_name,
])
);
}
public function updateUser(
array $headers,
string $username,
string $email = null,
string $display_name = null
) : PromiseInterface {
return $this->patchRequest(
Uri::fromParts([
'path' => 'users/'.$username,
]),
$headers,
json_encode(array_filter([
'email' => $email,
'display_name' => $display_name,
]))
);
}
}
<file_sep>/tests/HypothesisClient/Serializer/TokenDenormalizerTest.php
<?php
namespace tests\eLife\HypothesisClient\Serializer;
use eLife\HypothesisClient\Model\Token;
use eLife\HypothesisClient\Serializer\TokenDenormalizer;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
/**
* @covers \eLife\HypothesisClient\Serializer\TokenDenormalizer
*/
final class TokenDenormalizerTest extends TestCase
{
/** @var TokenDenormalizer */
private $normalizer;
/**
* @before
*/
protected function setUpNormalizer()
{
$this->normalizer = new TokenDenormalizer();
}
/**
* @test
*/
public function it_is_a_denormalizer()
{
$this->assertInstanceOf(DenormalizerInterface::class, $this->normalizer);
}
/**
* @test
* @dataProvider canDenormalizeProvider
*/
public function it_can_denormalize_tokens($data, $format, array $context, bool $expected)
{
$this->assertSame($expected, $this->normalizer->supportsDenormalization($data, $format, $context));
}
public function canDenormalizeProvider() : array
{
return [
'token' => [[], Token::class, [], true],
'non-token' => [[], get_class($this), [], false],
];
}
/**
* @test
* @dataProvider denormalizeProvider
*/
public function it_will_denormalize_tokens(array $json, Token $expected)
{
$this->assertEquals($expected, $this->normalizer->denormalize($json, Token::class));
}
public function denormalizeProvider() : array
{
return [
'complete' => [
[
'access_token' => 'access_token',
'token_type' => 'token_type',
'expires_in' => 1000.99,
'refresh_token' => 'refresh_token',
],
new Token('access_token', 'token_type', 1000.99, 'refresh_token'),
],
];
}
}
<file_sep>/src/Annotations/Serializer/CommonMark/Inline/Renderer/ImageRenderer.php
<?php
namespace eLife\Annotations\Serializer\CommonMark\Inline\Renderer;
use League\CommonMark\ElementRendererInterface;
use League\CommonMark\Inline\Element\AbstractInline;
use League\CommonMark\Inline\Element\Image;
use League\CommonMark\Inline\Renderer\InlineRendererInterface;
use League\CommonMark\Util\Xml;
final class ImageRenderer implements InlineRendererInterface
{
public function render(AbstractInline $inline, ElementRendererInterface $htmlRenderer)
{
if (!($inline instanceof Image)) {
throw new \InvalidArgumentException('Incompatible inline type: '.get_class($inline));
}
return Xml::escape($inline->getUrl(), true);
}
}
<file_sep>/tests/HypothesisClient/Serializer/Annotation/Target/SelectorDenormalizerTest.php
<?php
namespace tests\eLife\HypothesisClient\Serializer\Annotation\Target;
use eLife\HypothesisClient\Model\Annotation\Target\Selector;
use eLife\HypothesisClient\Serializer\Annotation\Target\Selector\TextQuoteDenormalizer;
use eLife\HypothesisClient\Serializer\Annotation\Target\SelectorDenormalizer;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Serializer;
/**
* @covers \eLife\HypothesisClient\Serializer\Annotation\Target\SelectorDenormalizer
*/
final class SelectorDenormalizerTest extends TestCase
{
/** @var SelectorDenormalizer */
private $normalizer;
/**
* @before
*/
protected function setUpNormalizer()
{
$this->normalizer = new SelectorDenormalizer();
new Serializer([
$this->normalizer,
new TextQuoteDenormalizer(),
]);
}
/**
* @test
*/
public function it_is_a_denormalizer()
{
$this->assertInstanceOf(DenormalizerInterface::class, $this->normalizer);
}
/**
* @test
* @dataProvider canDenormalizeProvider
*/
public function it_can_denormalize_selectors($data, $format, array $context, bool $expected)
{
$this->assertSame($expected, $this->normalizer->supportsDenormalization($data, $format, $context));
}
public function canDenormalizeProvider() : array
{
return [
'selector' => [[], Selector::class, [], true],
'non-selector' => [[], get_class($this), [], false],
];
}
/**
* @test
* @dataProvider denormalizeProvider
*/
public function it_will_denormalize_selectors(array $json, Selector $expected)
{
$this->assertEquals($expected, $this->normalizer->denormalize($json, Selector::class));
}
public function denormalizeProvider() : array
{
return [
'complete' => [
[
[
'type' => 'RangeSelector',
'startContainer' => '/div[4]',
'endContainer' => '/div[4]',
'startOffset' => 100,
'endOffset' => 200,
],
[
'type' => 'TextPositionSelector',
'start' => 10000,
'end' => 10021,
],
[
'type' => 'TextQuoteSelector',
'exact' => 'a new human species',
'prefix' => 'have been assigned to ',
'suffix' => ', Homo naledi',
],
[
'type' => 'FragmentSelector',
'conformsTo' => 'https://tools.ietf.org/html/rfc3236',
'value' => 'abstract',
],
],
new Selector(
new Selector\TextQuote('a new human species', 'have been assigned to ', ', Homo naledi')
),
],
'minimum' => [
[
[
'type' => 'TextQuoteSelector',
'exact' => 'a new human species',
'prefix' => 'have been assigned to ',
'suffix' => ', Homo naledi',
],
],
new Selector(
new Selector\TextQuote('a new human species', 'have been assigned to ', ', Homo naledi')
),
],
];
}
}
<file_sep>/tests/Annotations/Serializer/CommonMark/MathEscapeRendererTest.php
<?php
namespace tests\eLife\Annotations\Serializer\CommonMark;
use eLife\Annotations\Serializer\CommonMark\MathEscapeRenderer;
use League\CommonMark\Block\Element\AbstractBlock;
use League\CommonMark\ElementRendererInterface;
use PHPUnit\Framework\TestCase;
/**
* @covers \eLife\Annotations\Serializer\CommonMark\MathEscapeRenderer
*/
final class MathEscapeRendererTest extends TestCase
{
private $abstractBlock;
/** @var MathEscapeRenderer */
private $mathEscapeRenderer;
private $renderer;
/**
* @before
*/
public function setup()
{
$this->renderer = $this->getMockBuilder(ElementRendererInterface::class)
->getMock();
$this->abstractBlock = $this->createMock(AbstractBlock::class);
$this->mathEscapeRenderer = new MathEscapeRenderer($this->renderer);
}
/**
* @test
* @dataProvider mathMlAndLatexProvider
*/
public function it_will_escape_mathml_and_latex($expected, $rendered = null)
{
$this->renderer
->method('renderBlock')
->willReturn($rendered ?? $expected);
$this->assertSame($expected, $this->mathEscapeRenderer->renderBlock($this->abstractBlock));
}
public function mathMlAndLatexProvider()
{
return [
'no-math' => [
'No math at all',
],
'mathml' => [
'<math xmlns="http://www.w3.org/1998/Math/MathML"><mstyle mathcolor="blue" fontfamily="serif" displaystyle="true"><mi>a</mi><msup><mi>x</mi><mn>2</mn></msup><mo>+</mo><mi>b</mi><mi>x</mi><mo>+</mo><mi>c</mi><mo>=</mo><mn>0</mn></mstyle></math>',
'<math xmlns="http://www.w3.org/1998/Math/MathML"><mstyle mathcolor="blue" fontfamily="serif" displaystyle="true"><mi>a</mi><msup><mi>x</mi><mn>2</mn></msup><mo>+</mo><mi>b</mi><mi>x</mi><mo>+</mo><mi>c</mi><mo>=</mo><mn>0</mn></mstyle></math>',
],
'mathml-mulitple' => [
'<math xmlns="http://www.w3.org/1998/Math/MathML"><mi>a</mi></math> <a href="https://elifesciences.org">some other text</a> <math xmlns="http://www.w3.org/1998/Math/MathML"><mi>a</mi></math> ',
'<math xmlns="http://www.w3.org/1998/Math/MathML"><mi>a</mi></math> <a href="https://elifesciences.org">some other text</a> <math xmlns="http://www.w3.org/1998/Math/MathML"><mi>a</mi></math> ',
],
'latex' => [
$this->lines([
'$$',
'\\forall x \\in X,',
'\\quad \\exists y',
'\\leq< \\epsilon',
'$$',
]),
$this->lines([
'$$',
'\\forall x \\in X,',
'\\quad \\exists y',
'\\leq< \\epsilon',
'$$',
]),
],
];
}
private function lines(array $lines)
{
return implode(PHP_EOL, $lines);
}
}
<file_sep>/tests/Annotations/Provider/QueueCommandsProviderTest.php
<?php
namespace tests\eLife\Annotations\Provider;
use eLife\Annotations\Provider\QueueCommandsProvider;
use LogicException;
use Silex\Application;
use tests\eLife\Annotations\WebTestCase;
/**
* @covers \eLife\Annotations\Provider\QueueCommandsProvider
*/
final class QueueCommandsProviderTest extends WebTestCase
{
/**
* @test
*/
public function commands_are_registered()
{
$console = $this->getApp()->get('console');
$this->assertTrue($console->has('queue:count'));
$this->assertTrue($console->has('queue:clean'));
$this->assertTrue($console->has('queue:create'));
$this->assertTrue($console->has('queue:import'));
$this->assertTrue($console->has('queue:push'));
$this->assertTrue($console->has('queue:watch'));
}
/**
* @test
*/
public function registration_fails_if_no_console_provider()
{
$application = new Application();
$this->expectException(LogicException::class);
$this->expectExceptionMessage('You must register the ConsoleServiceProvider to use the QueueCommandsProvider');
$application->register(new QueueCommandsProvider());
}
}
<file_sep>/tests/HypothesisClient/Model/Annotation/Target/Selector/TextQuoteTest.php
<?php
namespace tests\eLife\HypothesisClient\Model\Annotation\Target\Selector;
use eLife\HypothesisClient\Model\Annotation\Target\Selector\TextQuote;
use PHPUnit\Framework\TestCase;
/**
* @covers \eLife\HypothesisClient\Model\Annotation\Target\Selector\TextQuote
*/
final class TextQuoteTest extends TestCase
{
/** @var TextQuote */
private $textQuote;
/**
* @before
*/
public function prepare_text_quote()
{
$this->textQuote = new TextQuote('exact', 'prefix', 'suffix');
}
/**
* @test
*/
public function it_has_exact_text()
{
$this->assertSame('exact', $this->textQuote->getExact());
}
/**
* @test
*/
public function it_has_a_prefix()
{
$this->assertSame('prefix', $this->textQuote->getPrefix());
}
/**
* @test
*/
public function it_has_a_suffix()
{
$this->assertSame('suffix', $this->textQuote->getSuffix());
}
}
<file_sep>/tests/HypothesisClient/Model/Annotation/TargetTest.php
<?php
namespace tests\eLife\HypothesisClient\Model\Annotation;
use eLife\HypothesisClient\Model\Annotation\Target;
use PHPUnit\Framework\TestCase;
/**
* @covers \eLife\HypothesisClient\Model\Annotation\Target
*/
final class TargetTest extends TestCase
{
/** @var Target */
private $target;
/**
* @before
*/
public function prepare_target()
{
$this->target = new Target('source');
}
/**
* @test
*/
public function it_has_a_source()
{
$this->assertSame('source', $this->target->getSource());
}
/**
* @test
*/
public function it_may_have_a_selector()
{
$targetWithoutSelector = $this->target;
$targetWithSelector = new Target(
'source',
$selector = new Target\Selector(
new Target\Selector\TextQuote('exact', 'prefix', 'suffix')
)
);
$this->assertNull($targetWithoutSelector->getSelector());
$this->assertSame($selector, $targetWithSelector->getSelector());
}
}
<file_sep>/src/HypothesisClient/Serializer/Annotation/TargetDenormalizer.php
<?php
namespace eLife\HypothesisClient\Serializer\Annotation;
use eLife\HypothesisClient\Model\Annotation\Target;
use eLife\HypothesisClient\Model\Annotation\Target\Selector;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
final class TargetDenormalizer implements DenormalizerInterface, DenormalizerAwareInterface
{
use DenormalizerAwareTrait;
public function denormalize($data, $class, $format = null, array $context = []) : Target
{
if (!empty($data['selector'])) {
$data['selector'] = $this->denormalizer->denormalize($data['selector'], Selector::class);
} else {
$data['selector'] = null;
}
return new Target($data['source'], $data['selector']);
}
public function supportsDenormalization($data, $type, $format = null) : bool
{
return Target::class === $type;
}
}
<file_sep>/src/Annotations/Serializer/CommonMark/Block/Renderer/HtmlBlockRenderer.php
<?php
namespace eLife\Annotations\Serializer\CommonMark\Block\Renderer;
use League\CommonMark\Block\Element\AbstractBlock;
use League\CommonMark\Block\Renderer\BlockRendererInterface;
use League\CommonMark\ElementRendererInterface;
final class HtmlBlockRenderer implements BlockRendererInterface
{
public function render(AbstractBlock $block, ElementRendererInterface $htmlRenderer, $inTightList = false)
{
return $block->getStringContent();
}
}
<file_sep>/src/HypothesisClient/Model/Token.php
<?php
namespace eLife\HypothesisClient\Model;
final class Token
{
private $accessToken;
private $tokenType;
private $expiresIn;
private $refreshToken;
/**
* @internal
*/
public function __construct(
string $accessToken,
string $tokenType,
float $expiresIn,
string $refreshToken
) {
$this->accessToken = $accessToken;
$this->tokenType = $tokenType;
$this->expiresIn = $expiresIn;
$this->refreshToken = $refreshToken;
}
public function getAccessToken() : string
{
return $this->accessToken;
}
public function getTokenType() : string
{
return $this->tokenType;
}
public function getExpiresIn() : float
{
return $this->expiresIn;
}
public function getRefreshToken() : string
{
return $this->refreshToken;
}
}
<file_sep>/src/HypothesisClient/Exception/NetworkProblem.php
<?php
namespace eLife\HypothesisClient\Exception;
class NetworkProblem extends HttpProblem
{
}
<file_sep>/src/HypothesisClient/Clock/FixedClock.php
<?php
namespace eLife\HypothesisClient\Clock;
final class FixedClock implements Clock
{
private $fixed_time;
public function __construct(int $time = null)
{
$this->fixed_time = $time ?? time();
}
public function time() : int
{
return $this->fixed_time;
}
}
<file_sep>/config/ci.php
<?php
$config = require __DIR__.'/dev.php';
return $config;
<file_sep>/src/HypothesisClient/Model/Annotation/Target/Selector.php
<?php
namespace eLife\HypothesisClient\Model\Annotation\Target;
use eLife\HypothesisClient\Model\Annotation\Target\Selector\TextQuote;
final class Selector
{
private $textQuote;
/**
* @internal
*/
public function __construct(
TextQuote $textQuote
) {
$this->textQuote = $textQuote;
}
public function getTextQuote() : TextQuote
{
return $this->textQuote;
}
}
<file_sep>/src/HypothesisClient/Credentials/UserManagementCredentials.php
<?php
namespace eLife\HypothesisClient\Credentials;
final class UserManagementCredentials extends Credentials
{
public function getAuthorizationBasic() : string
{
return 'Basic '.base64_encode($this->getClientId().':'.$this->getClientSecret());
}
}
<file_sep>/tests/Annotations/Command/QueueWatchCommandTest.php
<?php
namespace tests\eLife\Annotations\Command;
use eLife\Annotations\Command\QueueWatchCommand;
use eLife\ApiSdk\Collection\ArraySequence;
use eLife\ApiSdk\Collection\EmptySequence;
use eLife\ApiSdk\Model\AccessControl;
use eLife\ApiSdk\Model\PersonDetails;
use eLife\ApiSdk\Model\Profile;
use eLife\Bus\Limit\CallbackLimit;
use eLife\Bus\Limit\Limit;
use eLife\Bus\Queue\InternalSqsMessage;
use eLife\Bus\Queue\Mock\WatchableQueueMock;
use eLife\Bus\Queue\QueueItem;
use eLife\Bus\Queue\QueueItemTransformer;
use eLife\HypothesisClient\ApiSdk as HypothesisSdk;
use eLife\HypothesisClient\Clock\FixedClock;
use eLife\HypothesisClient\Credentials\JWTSigningCredentials;
use eLife\HypothesisClient\Credentials\UserManagementCredentials;
use eLife\HypothesisClient\Exception\BadResponse;
use eLife\HypothesisClient\HttpClient\HttpClient;
use eLife\HypothesisClient\Result\ArrayResult;
use eLife\Logging\Monitoring;
use Exception;
use GuzzleHttp\Promise\FulfilledPromise;
use GuzzleHttp\Promise\RejectedPromise;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use PHPUnit\Framework\TestCase;
use Psr\Log\LogLevel;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Component\Debug\BufferingLogger;
use tests\eLife\HypothesisClient\RequestConstraint;
/**
* @covers \eLife\Annotations\Command\QueueWatchCommand
*/
final class QueueWatchCommandTest extends TestCase
{
/** @var Application */
private $application;
private $authority;
private $authorization;
private $clientId;
/** @var QueueWatchCommand */
private $command;
/** @var CommandTester */
private $commandTester;
/** @var HypothesisSdk */
private $hypothesisSdk;
/** @var JWTSigningCredentials */
private $jwtSigning;
private $limit;
/** @var BufferingLogger */
private $logger;
/** @var Monitoring */
private $monitoring;
private $secretKey;
private $transformer;
/** @var UserManagementCredentials */
private $userManagement;
/** @var WatchableQueueMock */
private $queue;
/**
* @before
*/
public function prepareDependencies()
{
$this->application = new Application();
$this->clientId = 'client_id';
$this->secretKey = 'secret_key';
$this->authority = 'authority';
$this->authorization = sprintf('Basic %s', base64_encode($this->clientId.':'.$this->secretKey));
$this->userManagement = new UserManagementCredentials('client_id', 'secret_key', 'authority');
$this->jwtSigning = new JWTSigningCredentials('client_id', 'secret_key', 'authority', new FixedClock(1000000000));
$this->httpClient = $this->getMockBuilder(HttpClient::class)
->setMethods(['send'])
->getMock();
$this->hypothesisSdk = new HypothesisSdk($this->httpClient, $this->userManagement, $this->jwtSigning);
$this->limit = $this->limitIterations(1);
$this->logger = new BufferingLogger();
$this->monitoring = new Monitoring();
$this->transformer = $this->createMock(QueueItemTransformer::class);
$this->queue = new WatchableQueueMock();
}
/**
* @test
*/
public function it_will_read_an_item_from_the_queue()
{
$this->transformer
->expects($this->once())
->method('transform')
->will($this->returnValue(['foo' => 'bar']));
$this->prepareCommandTester();
$this->queue->enqueue(new InternalSqsMessage('profile', 'username'));
$this->assertSame(1, $this->queue->count());
$this->commandTesterExecute();
$this->assertSame(0, $this->queue->count());
}
/**
* @test
*/
public function it_retries_failures_retrieving_profile()
{
$this->transformer
->expects($this->once())
->method('transform')
->will($this->throwException(new Exception()));
$this->prepareCommandTester();
$this->queue->enqueue(new InternalSqsMessage('profile', 'username'));
$this->assertSame(1, $this->queue->count());
$this->commandTesterExecute();
$this->assertSame(1, $this->queue->count());
}
/**
* @test
*/
public function it_will_remove_queue_item_if_upsert_fails()
{
$this->transformer
->expects($this->once())
->method('transform')
->will($this->returnValue(new Profile('username', new PersonDetails('PreferredName', 'IndexName'), new EmptySequence(), new EmptySequence())));
$this->httpClient
->expects($this->at(0))
->method('send')
->willReturn(new RejectedPromise(new BadResponse('', new Request('POST', 'users'), new Response(400))));
$patch_response = new BadResponse('', new Request('PATCH', 'users/username'), new Response(404));
$this->httpClient
->expects($this->at(1))
->method('send')
->willReturn(new RejectedPromise($patch_response));
$this->executeItemFromQueue(new InternalSqsMessage('profile', 'username'));
$actual_logs = $this->logger->cleanLogs();
$this->assertContains([LogLevel::ERROR, 'Hypothesis user "username" upsert failure.', ['exception' => $patch_response]], $actual_logs);
}
/**
* @test
* @dataProvider providerProfiles
*/
public function it_will_process_an_item_in_the_queue(QueueItem $item, Profile $profile, $data, $logs = [])
{
$data = [
'authority' => $this->authority,
] + $data;
$this->transformer
->expects($this->once())
->method('transform')
->with($item)
->will($this->returnValue($profile));
$request = new Request(
'POST',
'users',
['Authorization' => $this->authorization, 'User-Agent' => 'HypothesisClient'],
json_encode($data)
);
$response = new FulfilledPromise(new ArrayResult($data + ['userid' => 'acct:'.$data['username'].'@test.<EMAIL>']));
$this->httpClient
->expects($this->once())
->method('send')
->with(RequestConstraint::equalTo($request))
->willReturn($response);
$this->prepareCommandTester();
$this->queue->enqueue($item);
$this->assertSame(1, $this->queue->count());
$this->commandTesterExecute();
$this->assertSame(0, $this->queue->count());
$actual_logs = $this->logger->cleanLogs();
$this->assertContains([LogLevel::INFO, 'Hypothesis user "username" successfully created.', []], $actual_logs);
if (!empty($logs)) {
foreach ($logs as $log) {
$this->assertContains($log, $actual_logs);
}
}
}
public function providerProfiles()
{
yield 'standard' => [
new InternalSqsMessage('profile', 'username'),
new Profile(
'username',
new PersonDetails('PreferredName', 'IndexName'),
new EmptySequence(),
new EmptySequence()
),
[
'username' => 'username',
'email' => '<EMAIL>',
'display_name' => 'PreferredName',
],
[
[LogLevel::INFO, 'No email address for profile "username", backup email address created.', []],
],
];
yield 'display_name too long' => [
new InternalSqsMessage('profile', 'username'),
new Profile(
'username',
new PersonDetails('This display name is way too łong', 'IndexName'),
new EmptySequence(),
new EmptySequence()
),
[
'username' => 'username',
'email' => '<EMAIL>',
'display_name' => 'This display name is way too ł',
],
[
[LogLevel::INFO, 'The display name for profile "username" is too long and has been truncated from "This display name is way too łong" to "This display name is way too ł".', []],
[LogLevel::INFO, 'No email address for profile "username", backup email address created.', []],
],
];
yield 'with single email' => [
new InternalSqsMessage('profile', 'username'),
new Profile(
'username',
new PersonDetails('PreferredName', 'IndexName'),
new EmptySequence(),
new ArraySequence([
new AccessControl('<EMAIL>', AccessControl::ACCESS_PUBLIC),
])
),
[
'username' => 'username',
'email' => '<EMAIL>',
'display_name' => 'PreferredName',
],
];
yield 'with multiple emails' => [
new InternalSqsMessage('profile', 'username'),
new Profile(
'username',
new PersonDetails('PreferredName', 'IndexName'),
new EmptySequence(),
new ArraySequence([
new AccessControl('<EMAIL>', AccessControl::ACCESS_PUBLIC),
new AccessControl('<EMAIL>', AccessControl::ACCESS_PUBLIC),
])
),
[
'username' => 'username',
'email' => '<EMAIL>',
'display_name' => 'PreferredName',
],
];
yield 'with restricted emails (in case authenticated API requests are used)' => [
new InternalSqsMessage('profile', 'username'),
new Profile(
'username',
new PersonDetails('PreferredName', 'IndexName'),
new EmptySequence(),
new ArraySequence([
new AccessControl('<EMAIL>', AccessControl::ACCESS_RESTRICTED),
new AccessControl('<EMAIL>', AccessControl::ACCESS_PUBLIC),
])
),
[
'username' => 'username',
'email' => '<EMAIL>',
'display_name' => 'PreferredName',
],
];
}
private function prepareCommandTester($serializedTransform = false)
{
$this->command = new QueueWatchCommand($this->queue, $this->transformer, $this->hypothesisSdk, $this->logger, $this->monitoring, $this->limit, $serializedTransform);
$this->application->add($this->command);
$this->commandTester = new CommandTester($this->application->get($this->command->getName()));
}
private function commandTesterExecute()
{
$execArgs = array_filter(
[
'command' => $this->command->getName(),
]
);
$this->commandTester->execute($execArgs);
}
private function limitIterations(int $number) : Limit
{
$iterationCounter = 0;
return new CallbackLimit(function () use ($number, &$iterationCounter) {
++$iterationCounter;
if ($iterationCounter > $number) {
return true;
}
return false;
});
}
private function executeItemFromQueue(QueueItem $item)
{
$this->prepareCommandTester();
$this->queue->enqueue($item);
$this->assertSame(1, $this->queue->count());
$this->commandTesterExecute();
$this->assertSame(0, $this->queue->count());
}
}
<file_sep>/tests/HypothesisClient/Model/AnnotationTest.php
<?php
namespace tests\eLife\HypothesisClient\Model;
use DateTimeImmutable;
use DateTimeZone;
use eLife\HypothesisClient\Model\Annotation;
use PHPUnit\Framework\TestCase;
/**
* @covers \eLife\HypothesisClient\Model\Annotation
*/
final class AnnotationTest extends TestCase
{
/** @var Annotation */
private $annotation;
/** @var DateTimeImmutable */
private $created;
/** @var Annotation\Document */
private $document;
/** @var Annotation\Permissions */
private $permissions;
/** @var Annotation\Target */
private $target;
/** @var DateTimeImmutable */
private $updated;
/**
* @before
*/
public function prepare_annotation()
{
$this->annotation = new Annotation(
'id',
'text',
$this->created = new DateTimeImmutable('now', new DateTimeZone('Z')),
$this->updated = new DateTimeImmutable('now', new DateTimeZone('Z')),
$this->document = new Annotation\Document('title'),
$this->target = new Annotation\Target('source'),
'uri',
[],
$this->permissions = new Annotation\Permissions('read')
);
}
/**
* @test
*/
public function it_has_an_id()
{
$this->assertSame('id', $this->annotation->getId());
}
/**
* @test
*/
public function it_may_have_text()
{
$without = new Annotation(
'id',
null,
$this->created = new DateTimeImmutable('now', new DateTimeZone('Z')),
$this->updated = new DateTimeImmutable('now', new DateTimeZone('Z')),
$this->document = new Annotation\Document('title'),
$this->target = new Annotation\Target(
'source',
new Annotation\Target\Selector(
new Annotation\Target\Selector\TextQuote('exact', 'prefix', 'suffix')
)
),
'uri',
[],
$this->permissions = new Annotation\Permissions('read')
);
$with = $this->annotation;
$this->assertNull($without->getText());
$this->assertSame('text', $with->getText());
}
/**
* @test
*/
public function it_has_a_created_date()
{
$this->assertSame($this->created, $this->annotation->getCreatedDate());
}
/**
* @test
*/
public function it_has_an_updated_date()
{
$this->assertSame($this->updated, $this->annotation->getUpdatedDate());
}
/**
* @test
*/
public function it_has_a_document()
{
$this->assertSame($this->document, $this->annotation->getDocument());
}
/**
* @test
*/
public function it_has_a_target()
{
$this->assertSame($this->target, $this->annotation->getTarget());
}
/**
* @test
*/
public function it_has_a_uri()
{
$this->assertSame('uri', $this->annotation->getUri());
}
/**
* @test
*/
public function it_has_permissions()
{
$this->assertSame($this->permissions, $this->annotation->getPermissions());
}
}
<file_sep>/tests/HypothesisClient/Serializer/AnnotationDenormalizerTest.php
<?php
namespace tests\eLife\HypothesisClient\Serializer;
use DateTimeImmutable;
use eLife\HypothesisClient\Model\Annotation;
use eLife\HypothesisClient\Serializer\Annotation\DocumentDenormalizer;
use eLife\HypothesisClient\Serializer\Annotation\PermissionsDenormalizer;
use eLife\HypothesisClient\Serializer\Annotation\Target\Selector\TextQuoteDenormalizer;
use eLife\HypothesisClient\Serializer\Annotation\Target\SelectorDenormalizer;
use eLife\HypothesisClient\Serializer\Annotation\TargetDenormalizer;
use eLife\HypothesisClient\Serializer\AnnotationDenormalizer;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Serializer;
/**
* @covers \eLife\HypothesisClient\Serializer\AnnotationDenormalizer
*/
final class AnnotationDenormalizerTest extends TestCase
{
/** @var AnnotationDenormalizer */
private $normalizer;
/**
* @before
*/
protected function setUpNormalizer()
{
$this->normalizer = new AnnotationDenormalizer();
new Serializer([
$this->normalizer,
new DocumentDenormalizer(),
new PermissionsDenormalizer(),
new SelectorDenormalizer(),
new TargetDenormalizer(),
new TextQuoteDenormalizer(),
]);
}
/**
* @test
*/
public function it_is_a_denormalizer()
{
$this->assertInstanceOf(DenormalizerInterface::class, $this->normalizer);
}
/**
* @test
* @dataProvider canDenormalizeProvider
*/
public function it_can_denormalize_annotations($data, $format, array $context, bool $expected)
{
$this->assertSame($expected, $this->normalizer->supportsDenormalization($data, $format, $context));
}
public function canDenormalizeProvider() : array
{
return [
'annotation' => [[], Annotation::class, [], true],
'non-annotation' => [[], get_class($this), [], false],
];
}
/**
* @test
* @dataProvider denormalizeProvider
*/
public function it_will_denormalize_annotations(array $json, Annotation $expected)
{
$this->assertEquals($expected, $this->normalizer->denormalize($json, Annotation::class));
}
public function denormalizeProvider() : array
{
$created = '2017-12-29T17:02:56.346939+00:00';
$updated = '2017-12-29T18:02:56.359872+00:00';
return [
'complete' => [
[
'id' => 'Ng1e2sTBEeegJt8a9q3zpQ',
'text' => '<p>A new human species</p>',
'created' => $created,
'updated' => $updated,
'document' => [
'title' => [
'Human Evolution: The many mysteries of Homo naledi',
],
],
'target' => [
[
'source' => 'source',
'selector' => [
[
'type' => 'RangeSelector',
'startContainer' => '/div[4]',
'endContainer' => '/div[4]',
'startOffset' => 100,
'endOffset' => 200,
],
[
'type' => 'TextPositionSelector',
'start' => 10000,
'end' => 10021,
],
[
'type' => 'TextQuoteSelector',
'exact' => 'a new human species',
'prefix' => 'have been assigned to ',
'suffix' => ', Homo naledi',
],
[
'type' => 'FragmentSelector',
'conformsTo' => 'https://tools.ietf.org/html/rfc3236',
'value' => 'abstract',
],
],
],
],
'uri' => 'https://elifesciences.org/articles/10627',
'references' => [
'ancestor1',
'ancestor2',
],
'permissions' => [
'read' => [
'group:__world__',
],
],
],
new Annotation(
'Ng1e2sTBEeegJt8a9q3zpQ',
'<p>A new human species</p>',
new DateTimeImmutable($created),
new DateTimeImmutable($updated),
new Annotation\Document('Human Evolution: The many mysteries of Homo naledi'),
new Annotation\Target(
'source',
new Annotation\Target\Selector(
new Annotation\Target\Selector\TextQuote('a new human species', 'have been assigned to ', ', Homo naledi')
)
),
'https://elifesciences.org/articles/10627',
['ancestor1', 'ancestor2'],
new Annotation\Permissions('group:__world__')
),
],
'no-text' => [
[
'id' => 'OFdkMTBEeeIFd8-JnIE1wN',
'created' => $created,
'updated' => $updated,
'document' => [
'title' => [
'Human Evolution: The many mysteries of Homo naledi',
],
],
'target' => [
[
'source' => 'source',
'selector' => [
[
'type' => 'TextQuoteSelector',
'exact' => 'a new human species',
'prefix' => 'have been assigned to ',
'suffix' => ', Homo naledi',
],
],
],
],
'uri' => 'https://elifesciences.org/articles/10627',
'references' => [
'ancestor1',
'ancestor2',
],
'permissions' => [
'read' => [
'group:__world__',
],
],
],
new Annotation(
'OFdkMTBEeeIFd8-JnIE1wN',
null,
new DateTimeImmutable($created),
new DateTimeImmutable($updated),
new Annotation\Document('Human Evolution: The many mysteries of Homo naledi'),
new Annotation\Target(
'source',
new Annotation\Target\Selector(
new Annotation\Target\Selector\TextQuote('a new human species', 'have been assigned to ', ', Homo naledi')
)
),
'https://elifesciences.org/articles/10627',
['ancestor1', 'ancestor2'],
new Annotation\Permissions('group:__world__')
),
],
'whitespace only' => [
[
'id' => 'Ng1e2sTBEeegJt8a9q3zpQ',
'text' => 'An annotation',
'created' => $created,
'updated' => $updated,
'document' => [
'title' => [
'Human Evolution: The many mysteries of Homo naledi',
],
],
'target' => [
[
'source' => 'source',
'selector' => [
[
'type' => 'RangeSelector',
'startContainer' => '/div[4]',
'endContainer' => '/div[4]',
'startOffset' => 100,
'endOffset' => 200,
],
[
'type' => 'TextPositionSelector',
'start' => 10000,
'end' => 10021,
],
[
'type' => 'TextQuoteSelector',
'exact' => ' ',
'prefix' => 'have been assigned to ',
'suffix' => ', Homo naledi',
],
[
'type' => 'FragmentSelector',
'conformsTo' => 'https://tools.ietf.org/html/rfc3236',
'value' => 'abstract',
],
],
],
],
'uri' => 'https://elifesciences.org/articles/10627',
'references' => [
'ancestor1',
'ancestor2',
],
'permissions' => [
'read' => [
'group:__world__',
],
],
],
new Annotation(
'Ng1e2sTBEeegJt8a9q3zpQ',
'An annotation',
new DateTimeImmutable($created),
new DateTimeImmutable($updated),
new Annotation\Document('Human Evolution: The many mysteries of Homo naledi'),
new Annotation\Target('https://elifesciences.org/articles/10627'),
'https://elifesciences.org/articles/10627',
['ancestor1', 'ancestor2'],
new Annotation\Permissions('group:__world__')
),
],
'minimum' => [
[
'id' => 'M_FoqMTBEeerwYvINYO67Q',
'text' => 'text',
'created' => $created,
'updated' => $updated,
'document' => [
'title' => [
'Human Evolution: The many mysteries of Homo naledi',
],
],
'target' => [
[
'source' => 'https://elifesciences.org/articles/10627',
],
],
'uri' => 'https://elifesciences.org/articles/10627',
'permissions' => [
'read' => [
'group:__world__',
],
],
],
new Annotation(
'M_FoqMTBEeerwYvINYO67Q',
'text',
new DateTimeImmutable($created),
new DateTimeImmutable($updated),
new Annotation\Document('Human Evolution: The many mysteries of Homo naledi'),
new Annotation\Target(
'https://elifesciences.org/articles/10627'
),
'https://elifesciences.org/articles/10627',
[],
new Annotation\Permissions('group:__world__')
),
],
];
}
}
<file_sep>/tests/HypothesisClient/Model/Annotation/PermissionsTest.php
<?php
namespace tests\eLife\HypothesisClient\Model\Annotation;
use eLife\HypothesisClient\Model\Annotation\Permissions;
use PHPUnit\Framework\TestCase;
/**
* @covers \eLife\HypothesisClient\Model\Annotation\Permissions
*/
final class PermissionsTest extends TestCase
{
/** @var Permissions */
private $permissions;
/**
* @before
*/
public function prepare_permissions()
{
$this->permissions = new Permissions('read');
}
/**
* @test
*/
public function it_has_a_read_permission()
{
$this->assertSame('read', $this->permissions->getRead());
}
}
<file_sep>/src/HypothesisClient/ApiClient/SearchClient.php
<?php
namespace eLife\HypothesisClient\ApiClient;
use eLife\HypothesisClient\HttpClient\HttpClient;
use eLife\HypothesisClient\HttpClient\UserAgentPrependingHttpClient;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7\Uri;
use function GuzzleHttp\Psr7\build_query;
final class SearchClient
{
use ApiClient;
private $group;
public function __construct(HttpClient $httpClient, string $group = '__world__', array $headers = [])
{
$this->httpClient = new UserAgentPrependingHttpClient($httpClient, 'HypothesisClient');
$this->group = $group;
$this->headers = $headers;
}
public function query(
array $headers,
string $username = null,
string $token = null,
int $offset = 0,
int $limit = 20,
bool $descendingOrder = true,
string $sort = 'updated'
) : PromiseInterface {
$query = [];
if ($username) {
$query['user'] = $username;
}
$query += [
'group' => $this->group,
'offset' => $offset,
'limit' => $limit,
'order' => $descendingOrder ? 'desc' : 'asc',
'sort' => $sort,
];
return $this->getRequest(
Uri::fromParts([
'path' => 'search',
'query' => build_query($query),
]),
(($token) ? ['Authorization' => 'Bearer '.$token] : []) + $headers
);
}
}
<file_sep>/src/HypothesisClient/Credentials/Credentials.php
<?php
namespace eLife\HypothesisClient\Credentials;
abstract class Credentials
{
private $authority;
private $clientId;
private $clientSecret;
public function __construct(string $clientId, string $clientSecret, string $authority)
{
$this->clientId = trim($clientId);
$this->clientSecret = trim($clientSecret);
$this->authority = trim($authority);
}
public function getClientId() : string
{
return $this->clientId;
}
public function getClientSecret() : string
{
return $this->clientSecret;
}
public function getAuthority() : string
{
return $this->authority;
}
}
<file_sep>/tests/HypothesisClient/Exception/NetworkProblemTest.php
<?php
namespace tests\eLife\HypothesisClient\Exception;
use eLife\HypothesisClient\Exception\HttpProblem;
use eLife\HypothesisClient\Exception\NetworkProblem;
use GuzzleHttp\Psr7\Request;
use PHPUnit\Framework\TestCase;
/**
* @covers \eLife\HypothesisClient\Exception\NetworkProblem
*/
final class NetworkProblemTest extends TestCase
{
/**
* @test
*/
public function it_is_an_instance_of_http_problem()
{
$e = new NetworkProblem('foo', new Request('GET', 'http://www.example.com/'));
$this->assertInstanceOf(HttpProblem::class, $e);
}
}
<file_sep>/tests/HypothesisClient/ApiClient/SearchClientTest.php
<?php
namespace tests\eLife\HypothesisClient\HttpClient;
use eLife\HypothesisClient\ApiClient\SearchClient;
use eLife\HypothesisClient\ApiClient\UsersClient;
use eLife\HypothesisClient\HttpClient\HttpClient;
use eLife\HypothesisClient\Result\ArrayResult;
use GuzzleHttp\Promise\FulfilledPromise;
use GuzzleHttp\Psr7\Request;
use PHPUnit\Framework\TestCase;
use tests\eLife\HypothesisClient\RequestConstraint;
use TypeError;
/**
* @covers \eLife\HypothesisClient\ApiClient\SearchClient
*/
final class SearchClientTest extends TestCase
{
private $httpClient;
/** @var SearchClient */
private $searchClient;
/**
* @before
*/
protected function setUpClient()
{
$this->httpClient = $this->createMock(HttpClient::class);
$this->searchClient = new SearchClient(
$this->httpClient,
'group',
['X-Foo' => 'bar']
);
}
/**
* @test
*/
public function it_requires_a_http_client()
{
try {
new UsersClient('foo');
$this->fail('A HttpClient is required');
} catch (TypeError $error) {
$this->assertTrue(true, 'A HttpClient is required');
$this->assertContains(
'must implement interface '.HttpClient::class.', string given',
$error->getMessage()
);
}
}
/**
* @test
*/
public function it_lists_annotations_public()
{
$request = new Request('GET', 'search?user=username&group=group&offset=0&limit=20&order=desc&sort=updated',
['X-Foo' => 'bar', 'User-Agent' => 'HypothesisClient']);
$response = new FulfilledPromise(new ArrayResult(['foo' => ['bar', 'baz']]));
$this->httpClient
->expects($this->once())
->method('send')
->with(RequestConstraint::equalTo($request))
->willReturn($response);
$this->assertSame($response, $this->searchClient->query([], 'username', null, 0, 20, true));
}
/**
* @test
*/
public function it_lists_annotations_restricted()
{
$request = new Request('GET', 'search?user=username&group=group&offset=0&limit=20&order=desc&sort=updated',
['X-Foo' => 'bar', 'Authorization' => 'Bearer token', 'User-Agent' => 'HypothesisClient']);
$response = new FulfilledPromise(new ArrayResult(['foo' => ['bar', 'baz']]));
$this->httpClient
->expects($this->once())
->method('send')
->with(RequestConstraint::equalTo($request))
->willReturn($response);
$this->assertSame($response, $this->searchClient->query([], 'username', 'token', 0, 20, true));
}
}
<file_sep>/tests/HypothesisClient/Serializer/Annotation/TargetDenormalizerTest.php
<?php
namespace tests\eLife\HypothesisClient\Serializer\Annotation;
use eLife\HypothesisClient\Model\Annotation\Target;
use eLife\HypothesisClient\Serializer\Annotation\Target\Selector\TextQuoteDenormalizer;
use eLife\HypothesisClient\Serializer\Annotation\Target\SelectorDenormalizer;
use eLife\HypothesisClient\Serializer\Annotation\TargetDenormalizer;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Serializer;
/**
* @covers \eLife\HypothesisClient\Serializer\Annotation\TargetDenormalizer
*/
final class TargetDenormalizerTest extends TestCase
{
/** @var TargetDenormalizer */
private $normalizer;
/**
* @before
*/
protected function setUpNormalizer()
{
$this->normalizer = new TargetDenormalizer();
new Serializer([
$this->normalizer,
new SelectorDenormalizer(),
new TextQuoteDenormalizer(),
]);
}
/**
* @test
*/
public function it_is_a_denormalizer()
{
$this->assertInstanceOf(DenormalizerInterface::class, $this->normalizer);
}
/**
* @test
* @dataProvider canDenormalizeProvider
*/
public function it_can_denormalize_targets($data, $format, array $context, bool $expected)
{
$this->assertSame($expected, $this->normalizer->supportsDenormalization($data, $format, $context));
}
public function canDenormalizeProvider() : array
{
return [
'target' => [[], Target::class, [], true],
'non-target' => [[], get_class($this), [], false],
];
}
/**
* @test
* @dataProvider denormalizeProvider
*/
public function it_will_denormalize_targets(array $json, Target $expected)
{
$this->assertEquals($expected, $this->normalizer->denormalize($json, Target::class));
}
public function denormalizeProvider() : array
{
return [
'complete' => [
[
'source' => 'https://elifesciences.org/articles/10627',
'selector' => [
[
'type' => 'RangeSelector',
'startContainer' => '/div[4]',
'endContainer' => '/div[4]',
'startOffset' => 100,
'endOffset' => 200,
],
[
'type' => 'TextPositionSelector',
'start' => 10000,
'end' => 10021,
],
[
'type' => 'TextQuoteSelector',
'exact' => 'a new human species',
'prefix' => 'have been assigned to ',
'suffix' => ', Homo naledi',
],
[
'type' => 'FragmentSelector',
'conformsTo' => 'https://tools.ietf.org/html/rfc3236',
'value' => 'abstract',
],
],
],
new Target(
'https://elifesciences.org/articles/10627',
new Target\Selector(
new Target\Selector\TextQuote('a new human species', 'have been assigned to ', ', Homo naledi')
)
),
],
'minimum' => [
[
'source' => 'https://elifesciences.org/articles/10627',
],
new Target('https://elifesciences.org/articles/10627'),
],
];
}
}
<file_sep>/src/HypothesisClient/Serializer/Annotation/PermissionsDenormalizer.php
<?php
namespace eLife\HypothesisClient\Serializer\Annotation;
use eLife\HypothesisClient\Model\Annotation\Permissions;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
final class PermissionsDenormalizer implements DenormalizerInterface, DenormalizerAwareInterface
{
use DenormalizerAwareTrait;
public function denormalize($data, $class, $format = null, array $context = []) : Permissions
{
return new Permissions($data['read'][0]);
}
public function supportsDenormalization($data, $type, $format = null) : bool
{
return Permissions::class === $type;
}
}
<file_sep>/src/HypothesisClient/Serializer/Annotation/Target/SelectorDenormalizer.php
<?php
namespace eLife\HypothesisClient\Serializer\Annotation\Target;
use eLife\HypothesisClient\Model\Annotation\Target\Selector;
use eLife\HypothesisClient\Model\Annotation\Target\Selector\TextQuote;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
final class SelectorDenormalizer implements DenormalizerInterface, DenormalizerAwareInterface
{
use DenormalizerAwareTrait;
public function denormalize($data, $class, $format = null, array $context = []) : Selector
{
$selectors = [];
foreach ($data as $selector) {
switch ($selector['type']) {
case 'TextQuoteSelector':
$selectors['textQuote'] = $this->denormalizer->denormalize($selector, TextQuote::class);
break;
default:
continue;
}
}
return new Selector($selectors['textQuote']);
}
public function supportsDenormalization($data, $type, $format = null) : bool
{
return Selector::class === $type;
}
}
<file_sep>/src/HypothesisClient/Exception/ApiTimeout.php
<?php
namespace eLife\HypothesisClient\Exception;
class ApiTimeout extends NetworkProblem
{
}
| a9abe692b5eb4b206f250bbcff4163c47893b611 | [
"Markdown",
"PHP",
"Shell"
] | 92 | Markdown | elifesciences/annotations | 6bacd6e2e1c512f1c3d5d50a65cb3ce841444731 | 6eb52bdfd9c25e0c383c4f2897960906b65a150c |
refs/heads/master | <repo_name>tejasrana95/nextjs-mongo-crud<file_sep>/pages/api/user/index.js
import nextConnect from 'next-connect';
import middleware from '../../../middlewares/middleware';
const handler = nextConnect();
handler.use(middleware);
handler.patch((req, res) => {
if (!req.user) return res.status(401).send('You need to be logged in.');
const { name, bio } = req.body;
return req.db
.collection('users')
.updateOne({ _id: req.user._id }, { $set: { name, bio } })
.then(() => res.json({
message: 'Profile updated successfully',
data: { name, bio },
}))
.catch(error => res.send({
status: 'error',
message: error.toString(),
}));
});
export default handler;
<file_sep>/middlewares/authentication.js
import { ObjectId } from 'mongodb';
export default function authentication(req, res, next) {
if (req.session.userId) {
return req.db.collection('users').findOne(ObjectId(req.session.userId))
.then((user) => {
if (user) req.user = user;
return next();
});
}
return next();
}
<file_sep>/middlewares/session.js
import session from 'next-session';
import connectMongo from 'connect-mongo';
const MongoStore = connectMongo(session);
export default function (req, res, next) {
return session({ store: new MongoStore({ client: req.dbClient }) })(req, res, next);
}
<file_sep>/.env.example
# MONGODB_URI=
# DB_NAME=<file_sep>/pages/customer/customerForm.jsx
import React, { useState, useContext } from 'react';
import axios from 'axios';
import Layout from '../../components/layout';
import Swal from 'sweetalert2';
class CustomerForm extends React.Component {
constructor(props) {
super(props);
this.initialState = {
_id: '',
name: '',
email: '',
phone: ''
}
this.state = {
_id: '',
name: '',
email: '',
phone: ''
}
this.handleSubmit = this.handleSubmit.bind(this);
}
UNSAFE_componentWillReceiveProps(nextProps) {
if (nextProps.edit !== null) {
this.getById(nextProps.edit);
}
}
getById(id) {
axios.get('/api/customer/' + id).then((data) => {
this.setState({
_id: data.data._id,
name: data.data.name,
email: data.data.email,
phone: data.data.phone
});
}).catch(error => {
console.error(error);
});
return;
}
handleSubmit(event) {
event.preventDefault();
if (this.state._id === '') {
this.createSubmit();
} else {
this.updateSubmit();
}
}
createSubmit() {
axios.post('/api/customer', this.state).then((data) => {
if (data.statusText === 'Created') {
Swal.fire({
type: 'success',
title: 'Success',
text: 'Customer Added successfully',
timer: 1000,
toast: true
});
this.cancelCustomer();
} else {
Swal.fire({
type: 'error',
title: 'Error',
text: data.data.message,
timer: 3000
})
}
this.props.updateList(new Date().getTime());
});
return;
}
updateSubmit() {
axios.put('/api/customer/' + this.state._id, this.state).then((data) => {
Swal.fire({
type: 'success',
title: 'Success',
text: 'Customer updated successfully',
timer: 1000,
toast: true
});
this.cancelCustomer();
this.props.updateList(new Date().getTime());
}).catch(error => {
Swal.fire({
type: 'error',
title: 'Error',
text: error.response.data.message,
timer: 3000,
toast: false
});
});
return;
}
cancelCustomer = () => {
setTimeout(() => {
this.setState(this.initialState);
}, 1000);
}
componentDidMount() {
this.setState(this.initialState);
}
render() {
return (
<>
<style jsx>
{`
label {
display: block
}
`}
</style>
<section>
<form onSubmit={this.handleSubmit}>
<div className="row">
<div className="col-md-4 col-sm-6">
<label htmlFor="name">
<input required id="name" type="text" placeholder="Your name" value={this.state.name} onChange={e => this.setState({ name: e.target.value })} />
</label>
</div>
<div className="col-md-4 col-sm-6">
<label htmlFor="email">
<input required id="email" type="email" placeholder="Your Email" value={this.state.email} onChange={e => this.setState({ email: e.target.value })} />
</label>
</div>
<div className="col-md-4 col-sm-6">
<label htmlFor="phone">
<input required id="phone" type="tel" placeholder="Your Phone" value={this.state.phone} onChange={e => this.setState({ phone: e.target.value })} />
</label>
</div>
</div>
<button type="submit">Save</button>
</form>
</section>
</>
)
}
}
export default CustomerForm;
<file_sep>/README.md
# Next.js + MongoDB + Basic Crud Operation
A full-fledged app made with Next.JS and MongoDB.
## About this project
`nextjs-mongo-crud` is a continously developed app built with Next.JS and MongoDB. Most tutorials on the Internet are either _half-baked_ or _not production-ready_. This project aims to fix that.
This project goes even further and attempts to integrate top features as seen in real-life apps.
Give this project a big ol' 🌟 star motivates me to work on new features.
Check out my profile (https://tejasrana.com/).
## Using this project
The goal is not to use this project as it, but to implement your own version.
### Requirement
This project relies on the following components. Some of them are **optional** and some may be replaced by others with similar functionalities.
#### Dependencies
This project uses the following dependencies:
- `next.js` - v9 or above required for **API Routes**.
- `react` - v16.8 or above required for **react hooks**.
- `react-dom` - v16.8 or above.
- `mongodb` - may be replaced by `mongoose`.
- `next-connect` - recommended if you want to use Express/Connect middleware.
- `axios`, `axioswal` - optional, may be replaced with any request library.
- `next-session`, `connect-mongo` - may be replaced with any session management solution.
- `bcryptjs` - optional, may be replaced with any password-hashing library. `argon2` recommended.
- `validator` - optional but recommended.
- `formidable` - may be replaced by other file parser.
- `cloudinary` - optional, only if you are using [Cloudinary](https://cloudinary.com) for image upload.
#### Environmental variables
The environment variables [will be inlined during build time](https://nextjs.org/docs#build-time-configuration) and thus should not be used in front-end codebase.
Required environmental variables in this project include:
- `process.env.MONGODB_URI` The MongoDB Connection String (with credentials)
- `process.env.CLOUDINARY_URL` Cloudinary environment variable for configuration. See [this](https://cloudinary.com/documentation/node_integration#configuration "Cloudinary Configuration").
- `process.env.DB_NAME` The name of the MongoDB database to be used.
I include my own MongoDB and Cloudinary environment variables in [.env.example](.env.example) for experimentation purposes. Please replace them with your owns and refrain from sabotaging them. You can use them in development by renaming it into `.env`.
In production, it is recommended to set the environment variables using the options provided by your cloud/hosting providers.
## Development
`nextjs-mongo-crud` is a long-term developing project. There is no constraint on numbers of features. I continuously accepts feature proposals and am actively developing and expanding functionalities.
Start the development server by running `yarn dev` or `npm run dev`.
### Features
There are three states in feature development:
- `developed`: The feature has been fully developed and is functional.
- `developing`: The feature is being developed or being improved.
- `proposed`: The feature is proposed and may or may not be developed in the future.
#### Authentication
- Session management
- Allow users to sign up and log in/log out.
#### User profile
- Avatar, name, email, location, etc.
- User profile page
- Edit user profile
#### Social `delayed`
- Find other users with search functionality
- View other users' profile page
- Add/Remove friends
#### Account management `developing`
- Email verification
- Password change
- Password reset
Have any features in mind, [make an issue](https://github.com/tejasrana95/nextjs-mongo-crud/issues). Would like to work on a feature, [make a PR](https://github.com/tejasrana95/nextjs-mongo-crud/pulls).
### Styles
Despite the look, this project does not contain any stylesheets, and no component has classes. To remove the style, simply remove all `<style jsx>` and `<style jsx global>` tags.
## Contributing
Please see my [contributing.md](contributing.md).
## License
[MIT](LICENSE)
## Credit
[Hoang](https://github.com/hoangvvo/nextjs-mongodb-app): For providing basic app.<file_sep>/pages/api/user/profilepicture.js
import nextConnect from 'next-connect';
import formidable from 'formidable';
import { v2 as cloudinary } from 'cloudinary';
import middleware from '../../../middlewares/middleware';
const handler = nextConnect();
handler.use(middleware);
handler.put((req, res) => {
if (!req.user) return res.status(401).send('You need to be logged in.');
const form = new formidable.IncomingForm();
return form.parse(req, (err, fields, files) => cloudinary.uploader
.upload(files.profilePicture.path, {
width: 512,
height: 512,
crop: 'fill',
})
.then(image => req.db
.collection('users')
.updateOne(
{ _id: req.user._id },
{ $set: { profilePicture: image.secure_url } },
))
.then(() => res.send({
status: 'success',
message: 'Profile picture updated successfully',
}))
.catch(error => res.send({
status: 'error',
message: error.toString(),
})));
});
export const config = {
api: {
bodyParser: false,
},
};
export default handler;
<file_sep>/lib/redirectTo.js
import Router from 'next/router';
export default function redirectTo(destination, { res, status } = {}) {
if (res) {
res.writeHead(status || 302, { Location: destination });
res.end();
} else if (destination[0] === '/' && destination[1] !== '/') {
Router.push(destination);
} else {
window.location = destination;
}
}
<file_sep>/pages/index.jsx
import React, { useContext } from 'react';
// import { UserContext } from '../components/UserContext';
// import Layout from '../components/layout';
const IndexPage = () => {
// const { state: { isLoggedIn, user: { name } } } = useContext(UserContext);
return (
// <Layout>
// </Layout>
<div className='p'>
<style jsx>
{`
p {
color: #888;
font-size: 1.8rem;
line-height: 2;
}
.code {
color: red;
background: lightblue;
border-radius: 5px
}
.p {
text-align: center;
}
`}
</style>
<h1>
Hello,
{/* {' '}
{(isLoggedIn ? name : 'stranger')}
! */}
</h1>
<p>Have a wonderful day.</p>
<div className="p">
<p>
To start using this starter kit, please uncomment every commented line <code className="code">in _app.jsx</code> and <code className="code">index.jsx</code>.
<br />
Then the screen show you an error <code className="code">code: 500 in /api/session</code>.
<br />
Don't panic, please just configure the connection with your database in <code className="code">.env</code> file and you can connect with your choice of database.
</p>
</div>
</div>
);
};
export default IndexPage;
<file_sep>/pages/api/authenticate.js
import nextConnect from 'next-connect';
import bcrypt from 'bcryptjs';
import middleware from '../../middlewares/middleware';
import jwt from 'jsonwebtoken';
const handler = nextConnect();
handler.use(middleware);
handler.post((req, res) => {
const { email, password } = req.body;
return req.db
.collection('users')
.findOne({ email })
.then((user) => {
if (user) {
return bcrypt.compare(password, user.password).then((result) => {
if (result) return Promise.resolve(user);
return Promise.reject(Error('The password you entered is incorrect'));
});
}
return Promise.reject(Error('The email does not exist'));
})
.then((user) => {
req.session.userId = user._id;
delete user.password;
const token = jwt.sign({ "email": user.email, "_id": user._id }, process.env.jwtSecret, { expiresIn: 86400 }) // 1 day token
return res.send({
status: 'ok',
userData: user,
token: token
});
})
.catch(error => res.send({
status: 'error',
message: error.toString(),
}));
});
export default handler;
<file_sep>/pages/api/customer.js
import nextConnect from 'next-connect';
import isEmail from 'validator/lib/isEmail';
import middleware from '../../middlewares/middleware';
const handler = nextConnect();
handler.use(middleware);
handler.post((req, res) => {
if (!req.user) return res.status(401).send('You need to be logged in.');
const { email, name, phone } = req.body;
if (!isEmail(email)) {
return res.status(400).send({
status: 'error',
message: 'The email you entered is invalid.',
});
}
return req.db
.collection('customers')
.countDocuments({ email })
.then((count) => {
if (count) {
return Promise.reject(
res.status(200).send({
status: 'error',
message: 'The customer with email has already been used',
})
);
}
})
.then(() => req.db.collection('customers').insertOne({
email,
phone,
name
}))
.then((user) => {
req.session.userId = user.insertedId;
res.status(201).send({
status: 'ok',
message: 'Customer added successfully',
});
})
.catch(error => res.send({
status: 'error',
message: error.toString(),
}));
});
handler.get((req, res) => {
if (!req.user) return res.status(401).send('You need to be logged in.');
return req.db
.collection('customers')
.find({})
.toArray()
.then((data) => res.json(data))
.catch(error => {
return Promise.reject(
res.status(200).send({
status: 'error',
message: error.error,
})
)
});
});
export default handler;
<file_sep>/pages/profile/settings.jsx
import React, { useContext, useState } from 'react';
import axioswal from 'axioswal';
import { UserContext } from '../../components/UserContext';
import Layout from '../../components/layout';
const ProfileSection = ({ user: { name: initialName, bio: initialBio }, dispatch }) => {
const [name, setName] = useState(initialName);
const [bio, setBio] = useState(initialBio);
const handleSubmit = (event) => {
event.preventDefault();
axioswal
.patch(
'/api/user',
{ name, bio },
)
.then(() => {
dispatch({ type: 'fetch' });
});
};
const profilePictureRef = React.createRef();
const [isUploading, setIsUploading] = useState(false);
const handleSubmitProfilePicture = (event) => {
if (isUploading) return;
event.preventDefault();
setIsUploading(true);
const formData = new FormData();
formData.append('profilePicture', profilePictureRef.current.files[0]);
axioswal
.put('/api/user/profilepicture', formData)
.then(() => {
setIsUploading(false);
dispatch({ type: 'fetch' });
});
};
return (
<>
<style jsx>
{`
label {
display: block
}
`}
</style>
<section>
<h2>Edit Profile</h2>
<form onSubmit={handleSubmit}>
<label htmlFor="name">
Name
<input
required
id="name"
type="text"
placeholder="<NAME>"
value={name}
onChange={e => setName(e.target.value)}
/>
</label>
<label htmlFor="bio">
Bio
<textarea
id="bio"
type="text"
placeholder="Bio"
value={bio}
onChange={e => setBio(e.target.value)}
/>
</label>
<button type="submit">
Save
</button>
</form>
<form action="/api/user/profilepicture" onSubmit={handleSubmitProfilePicture}>
<label htmlFor="avatar">
Profile picture
<input
type="file"
id="avatar"
name="avatar"
accept="image/png, image/jpeg"
ref={profilePictureRef}
required
/>
</label>
<button type="submit" disabled={isUploading}>
Upload
</button>
</form>
</section>
</>
);
};
const SettingPage = () => {
const { state: { isLoggedIn, user }, dispatch } = useContext(UserContext);
if (!isLoggedIn) return (<Layout><p>Please log in</p></Layout>);
return (
<Layout>
<h1>Settings</h1>
<ProfileSection user={user} dispatch={dispatch} />
</Layout>
);
};
export default SettingPage;
<file_sep>/pages/api/users.js
import nextConnect from 'next-connect';
import isEmail from 'validator/lib/isEmail';
import bcrypt from 'bcryptjs';
import middleware from '../../middlewares/middleware';
const handler = nextConnect();
handler.use(middleware);
handler.post((req, res) => {
const { email, name, password, gender } = req.body;
if (!isEmail(email)) {
return res.send({
status: 'error',
message: 'The email you entered is invalid.',
});
}
return req.db
.collection('users')
.countDocuments({ email })
.then((count) => {
if (count) {
return Promise.reject(Error('The email has already been used.'));
}
return bcrypt.hashSync(password);
})
.then(hashedPassword => req.db.collection('users').insertOne({
email,
password: <PASSWORD>,
name,
gender
}))
.then((user) => {
req.session.userId = user.insertedId;
res.status(201).send({
status: 'ok',
message: 'User signed up successfully',
});
})
.catch(error => res.send({
status: 'error',
message: error.toString(),
}));
});
export default handler;
<file_sep>/components/UserContext.jsx
import React, { createContext, useReducer, useEffect } from 'react';
import axios from 'axios';
const UserContext = createContext();
const reducer = (state, action) => {
switch (action.type) {
case 'set':
return action.data;
case 'clear':
return {
isLoggedIn: false,
user: {},
};
default:
throw new Error();
}
};
const UserContextProvider = ({ children }) => {
const [state, dispatch] = useReducer(reducer, { isLoggedIn: false, user: {} });
const dispatchProxy = (action) => {
switch (action.type) {
case 'fetch':
return axios.get('/api/session')
.then(res => ({
isLoggedIn: res.data.data.isLoggedIn,
user: res.data.data.user,
}))
.then(({ isLoggedIn, user }) => {
dispatch({
type: 'set',
data: { isLoggedIn, user },
});
});
default:
return dispatch(action);
}
};
useEffect(() => {
dispatchProxy({ type: 'fetch' });
}, []);
return (
<UserContext.Provider value={{ state, dispatch: dispatchProxy }}>
{ children }
</UserContext.Provider>
);
};
const UserContextConsumer = UserContext.Consumer;
export { UserContext, UserContextProvider, UserContextConsumer };
| e02071e5cf381d30f079f4927ea81a6d53749c99 | [
"JavaScript",
"Markdown",
"Shell"
] | 14 | JavaScript | tejasrana95/nextjs-mongo-crud | 2b35937db31cf77be65795f9838729d8ee455fbb | 44811accbd6703156daab688079385bf573df7a6 |
refs/heads/master | <repo_name>Lucbm99/Banco-de-Dados---PetShop<file_sep>/README.md
# Banco de Dados - Pet Shop
Para fins de estudo de banco de dados, foi feito um banco de dados, com inserção de alguns dados em duas tabelas criadas, juntamente com consultas elaboradas para tabelas.
## 🚀 Instruções
Para que você veja o código do projeto funcionando em sua máquina, serão disponibilizadas algumas instruções no tópico 🔧 Como rodar o projeto?
### 📋 Pré-requisitos
Para isso, você irá precisar basicamente ter um servidor local em sua máquina, que rode PHP, Apache e MySQL (Wamp, Xampp) e o MySQL Workbench instalados, para rodar o banco de dados:
Links úteis:
XAMPP: https://www.apachefriends.org/pt_br/index.html
WAMP: https://www.wampserver.com/en/
MySQL Workbench: https://dev.mysql.com/downloads/workbench/
No meu caso, estou utilizando o XAMPP e os servidores de Apache e MySQL estão ativos:

### 🔧 Como rodar o projeto?
Na página inicial do projeto, haverão dois arquivos:
- SCRIPT E QUERIES - PET SHOP.sql

Todo o conteúdo do arquivo dump_sorveteria, deve ser copiado para o MySQL Workbench, para a criação do banco de dados:


Para o banco de dados ser criado de maneira local em sua máquina, após a cópia do código no MySQL Workbench, basta seguir os passos deste vídeo: https://youtu.be/mde1jNM0UNQ.
As instruções de como executar as consultas estão também demonstradas no vídeo.
## 📦 Status do Banco de Dados
🚧 Finalizado 🚧
## 🛠️ Feito com
* [MySQL](https://www.mysql.com/) - Banco de dados utilizado.
## ✒️ Licença
Consulte o arquivo LICENSE.md, para maiores detalhes.
## ✒️ Autores
Banco de dados feito por mim - [Lucbm99](https://github.com/Lucbm99)
---
⌨️ com ❤️ por [<NAME>](https://github.com/Lucbm99) 😊
<file_sep>/SCRIPT E QUERIES - PET SHOP.sql
drop database if exists PET_SHOP;
create database if not exists PET_SHOP;
use PET_SHOP;
create table if not exists CLIENTE(
idCliente int auto_increment not null,
nomeCliente varchar(30),
CPF char(12),
telefone varchar(15),
primary key (idCliente)
);
create table if not exists ANIMAL(
idAnimal int auto_increment not null,
nomeAnimal varchar(20),
especie varchar(15),
racaAnimal varchar(15),
pesoAnimal decimal(10,3),
dataNascimento date,
idCliente int,
primary key (idAnimal),
foreign key (idCliente) references CLIENTE(idCliente)
);
create table if not exists PRODUTOS_SERVICOS(
idProdutos_Servicos int auto_increment not null,
nome varchar(30),
descricao varchar(30),
valor decimal(10,2),
fornecedor varchar(30),
tipo varchar(45),
primary key (idProdutos_Servicos)
);
create table if not exists VENDAS(
idVendas int auto_increment not null,
quantidade int,
dataVenda date,
valorTotal decimal(10,2),
idCliente int,
primary key (idVendas),
foreign key (idCliente) references CLIENTE(idCliente)
);
create table if not exists ITEM(
quantidade int,
valorTotal decimal(10,2),
idVendas int,
idProdutos_Servicos int,
primary key (idVendas, idProdutos_Servicos),
foreign key (idVendas) references VENDAS (idVendas),
foreign key (idProdutos_Servicos) references PRODUTOS_SERVICOS (idProdutos_Servicos)
);
/* inserir valores --> idCliente, nome, CPF, telefone*/
insert into CLIENTE values
(null, '<NAME>', '36602530261', '38953545'),
(null, '<NAME>', '43912216835', '38074206'),
(null, '<NAME>', '28851360812', '39554522'),
(null, '<NAME>', '35467123044', '32194442');
/*inserir valores --> idAnimal, nomeAnimal, especie, racaAnimal, pesoAnimal, data de Nascimento, idCliente*/
insert into ANIMAL values
(null, 'Tobias', 'Cachorro', 'Buldogue', 24.500, '2015-11-15', 1),
(null, 'Fred', 'Cachorro' , '<NAME>', 21.500, '2012-04-23', 2),
(null, 'Bob', 'Hamster', 'Hamster anão chinês', 1.500, '2009-03-24', 3),
(null, 'Elliot', 'Gato', 'Persa', 3.6000, '2015-09-22', 1),
(null, 'Floquinho', 'Gato' , 'Siamês', 5.2000, '2016-05-11', 2),
(null, 'Sansão', 'Pássaro', 'Pardal', 1.400, '2016-04-04', 3),
(null, 'Loop', 'Cachorro', 'Poodle', 13.700, '2015-07-22', 1),
(null, 'Frodo', 'Pássaro' , 'Pintassilgo', 1.350, '2012-06-04', 2),
(null, 'Coringa', 'Coelho', 'Fuzzy lop', 1.400, '2009-12-15', 3),
(null, 'Fido', 'Peixe', 'Bagre', 1.200, '2017-05-14', 3);
/*inserir valores --> idProdutos_Servicos, nome, descricao, valor, fornecedor, tipo*/
insert into PRODUTOS_SERVICOS values
(null, 'Tosa', 'Aparar os pêlos', 40.00, 'Pet Shop R', 'Serviço'),
(null, 'Ração Frango', 'Alimento para cães/gatos', 12.00, 'Pedigree', 'Produto'),
(null, 'Banho', 'Lavar os pêlos', 20.00, 'Pet Shop R', 'Serviço'),
(null, 'Ração Carne', 'Alimento para cães/gatos', 15.00, 'Pedigree', 'Produto'),
(null, 'Vacina anti-raiva', 'Medicação', 15.00, 'Pet Shop R', 'Serviço'),
(null, 'Alpiste', 'Alimento para pássaros', 5.00, 'Magnus', 'Produto'),
(null, 'Girassol', 'Alimento para pássaros', 3.50, 'Magnus', 'Produto'),
(null, 'Painço', 'Alimento para pássaros', 6.70, 'Magnus', 'Produto'),
(null, 'Escovação', 'Escovar os pêlos', 25.00, 'Pet Shop R', 'Serviço'),
(null, 'Ração para Peixes', 'Alimento para peixes',5.00, 'Magnus', 'Produto');
insert into VENDAS values
/*inserir valores --> idVendas, quantidade, dataVenda, valorTotal, idCliente*/
(null, 2, '2010-04-25', 35.50, 1),
(null, 3, '2010-11-01', 11.60, 2),
(null, 5, '2014-03-07', 12.15, 3),
(null, 4, '2014-06-26', 25.90, 3),
(null, 2, '2018-12-31', 15.30, 2),
(null, 3, '2018-02-23', 41.35, 1),
(null, 5, '2013-04-19', 10.90, 2),
(null, 7, '2013-09-12', 8.45, 1),
(null, 2, '2015-05-11', 3.75, 3),
(null, 1, '2015-08-06', 3.75, 2);
/*inserir valores --> idItem, quantidade, valorTotal, idVendas, idProdutos_Servicos*/
insert into ITEM values
(2, 32.00, 1, 1),
(2, 35.00, 2, 2),
(2, 60.00, 2, 3),
(2, 52.00, 3, 4),
(2, 30.00, 5, 6),
(2, 8.50, 7, 8),
(2, 35.00, 1, 4),
(3, 23.70, 2, 5),
(2, 65.00, 7, 6);
select * from CLIENTE;
select * from ANIMAL;
select * from PRODUTOS_SERVICOS;
select * from VENDAS;
select * from ITEM;
/*1. Exibir os dados dos animais (nome, espécie e raça) com os respectivos nomes de clientes.*/
select CC.idAnimal, CC.nomeAnimal, CC.especie, CC.racaAnimal, C.nomeCliente, C.idCliente
from ANIMAL CC, CLIENTE C
where CC.idCliente=C.idCliente;
/*2. Quais os produtos cadastrados são Pedigree?*/
select * from produtos_servicos p where p.fornecedor like '%Pedigree%';
/*3. Qual é o cliente que tem um hamster como animal de estimação?*/
select E.idAnimal, C.nomeCliente, E.especie
from ANIMAL E inner join CLIENTE C
on E.idCliente = C.idCliente where E.especie like '%Hamster%';
/*4. Qual a média do peso dos animais cadastrados? */
/*média dos pesos dos animais na tabela ANIMAL com titulo "média dos pesos" */
select*from ANIMAL;
select round(avg(pesoAnimal),2) as 'Média dos pesos' from ANIMAL;
/*5. Qual o valor da venda mais cara realizada pela loja?
Maior preço na tabela VENDAS com titulo "Venda mais cara" */
select*from VENDAS;
select max(valorTotal) as 'Venda mais cara' from VENDAS;
/*6. Qual o valor do produto ou serviço mais barato? */
/*Menor preço na tabela PRODUTOS_SERVICOS com titulo "Menor Preço" */
select*from PRODUTOS_SERVICOS;
select min(valor) as 'Menor Preço' from PRODUTOS_SERVICOS;
/*7. Qual a soma do preço de todos os itens? */
/*Soma dos preços dos itens na tabela ITEM*/
select sum(valorTotal) from ITEM;
/*8. Qual o cliente tem o animal de menor peso?*/
/*Junção de duas tabelas com inner join para saber o cliente que tem o animal de menor peso*/
select E.idAnimal, C.nomeCliente, E.pesoAnimal
from ANIMAL E inner join CLIENTE C
on E.idCliente = C.idCliente where E.pesoAnimal = (select min(animal.pesoAnimal) from animal);
/*9. Quais são os clientes que fizeram compras abaixo de 50$?*/
select C.nomeCliente, sum(valorTotal)
from VENDAS CC, cliente C
where c.idCliente=cc.idCliente
group by c.idCliente
having sum(valorTotal) < 50.00;
/*10. Listar as três vendas que contém maior número de itens por venda.*/
select v.idVendas, v.dataVenda, v.valorTotal, count(i.idVendas) as 'itens' from item i
inner join vendas v on i.idVendas = v.idVendas
group by v.idVendas order by itens desc limit 3;
/*11. Listar as vendas que o pet shop realizou depois de 2016, agrupando por cliente.*/
select c.idCliente, c.nomeCliente, v.idVendas, v.dataVenda, v.valorTotal from cliente c
inner join vendas v on v.idCliente = c.idCliente
where v.dataVenda >='2016-01-01';
/*12. Qual cliente não possui nenhuma compra?*/
select idCliente, nomeCliente from cliente
where idCliente not in
(select idCliente from VENDAS)
| 51c927c4ab82808ce6ce6aca5feca8aa12e42472 | [
"Markdown",
"SQL"
] | 2 | Markdown | Lucbm99/Banco-de-Dados---PetShop | fc4a2c76372b7f04371c0b21ab3efd4106439d15 | 1410a0b9d9470158c72aa0722873543332455504 |
refs/heads/master | <repo_name>ajay-gandhi/brew-tree<file_sep>/brew-tree
#!/usr/bin/env node
'use strict';
var spawn = require('child_process').spawn;
/********************************** CLI args **********************************/
var argv = require('minimist')(process.argv.slice(2));
if (argv.h || argv.help) help_exit();
var parseable = !!(argv.p || argv.parseable);
var pkg = (argv['_'].length ? argv['_'][0] : false) || argv.p || argv.parseable;
if (!pkg) help_exit();
/*********************** Collect information on package ***********************/
var uses = spawn('brew', ['uses', '--installed', pkg]);
var deps = spawn('brew', ['deps', pkg]);
var uses_data = '', uses_finished = false;
uses.stdout.on('data', (data) => {
uses_data += data.toString();
});
uses.on('close', () => {
uses_finished = true;
if (uses_finished && deps_finished) data_collected();
});
var deps_data = '', deps_finished = false;
deps.stdout.on('data', (data) => {
deps_data += data.toString();
});
deps.on('close', () => {
deps_finished = true;
if (uses_finished && deps_finished) data_collected();
});
/*************************** Child processes ended ****************************/
var data_collected = function () {
if (parseable) {
console.log(uses_data.trim());
console.log(pkg);
console.log(deps_data.trim());
process.exit(0);
}
uses_data = uses_data.trim().split('\n');
deps_data = deps_data.trim().split('\n');
var str, max = false;
if ((uses_data.length == 0 || uses_data[0] === '') &&
(deps_data.length == 0 || deps_data[0] === ''))
return console.log('`' + pkg + '` has no uses or dependencies.');
// Print packages that depend on this package
if (uses_data.length > 0 && uses_data[0] !== '') {
max = uses_data.reduce(function (len, c) {
return c.length > len ? c.length : len;
}, 0) + 2;
if (pkg.length / 2 > max - 2) max = Math.floor(pkg.length / 2 + 2);
// First has different suffix
var first = uses_data.shift() + ' ';
while (first.length < max) first += '━';
str = ' ' + first + '┓\n';
str = uses_data.reduce(function (acc, p) {
p += ' ';
while (p.length < max) p += '━';
return acc + ' ' + p + '┫\n';
}, str);
}
// Print this package
if (!max) {
str = ' ' + pkg + '\n';
} else {
var n_pre_spaces = Math.floor(max - (pkg.length / 2)) + 1;
var line = '';
while (line.length < n_pre_spaces) line += ' ';
str += ' ' + line + pkg + '\n';
}
// Print dependencies of this package
if (deps_data.length > 0 && deps_data[0] !== '') {
// Compute length of spaces prefix
var spaces_prefix = '';
if (!max) {
var n_pre_spaces = Math.ceil(pkg.length / 2) - 1;
while (spaces_prefix.length <= n_pre_spaces) spaces_prefix += ' ';
} else {
while (spaces_prefix.length < max) spaces_prefix += ' ';
spaces_prefix += ' ';
}
// Print dependencies
var last = deps_data.pop();
str = deps_data.reduce(function (acc, p) {
return acc + spaces_prefix + '┣━ ' + p + '\n';
}, str);
str += spaces_prefix + '┗━ ' + last + '\n';
}
console.log('\n' + str);
}
function help_exit() {
console.log(
'\n' +
' Usage: brew tree [options] <package>\n' +
'\n' +
' See a tree of uses and dependencies for your brew packages\n' +
'\n' +
' Options:\n' +
'\n' +
' -p, --parseable \t Parseable output\n' +
' -h, --help \t Print this help\n'
);
process.exit(0);
}
<file_sep>/README.md
# brew tree
> See a tree of uses and dependencies for your brew packages
## Installation
```
$ npm install -g ajay-gandhi/brew-tree
```
## Usage
```
$ brew list # see a list of your installed packages
$ brew tree aspcud # view tree for aspcud package
```
| 0aced6ed6f88ad4cad630b84e1df0ae27c31a845 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | ajay-gandhi/brew-tree | b1c2b0e918a8727d16a1711a35437edb1457bf4c | bc38c2a47f28ee095c36f788bab5173b67f719bd |
refs/heads/master | <file_sep># TriviaGame
Random & Timed Trivia Game
<file_sep>//should produce a timed question list with radio button responses
$(document).ready(function() {
//original variables for pushing and matching elements from radio selects and saved answers
//LOGIC VARIABLE
var correctValues = ["Pacific Ocean", "Mt. Everest", "Mariana Trench", "1", "Saturn", "142"];
//define these input array elements in the click function that records the user response
//LOGIC VARIABLE
var selectAnswers = [];
//starts the count for correct answers at zero; log and write these into HTML inside or after stopCount
//REMEMBER TO ACCESS AND PRINT THESE IN AFTER STOPCOUNT
var correctCount = 0;
//starts the count for the wrong answers at zero; log and write these into HTML inside or after stopCount
//REMEMBER TO ACCESS AND PRINT THESE IN AFTER STOPCOUNT
var wrongCount = 0;
function runLogic() {
//records input as selectedValues elements using a radio click function, record as the person goes down the list of questions
$("#AnswerOne").one('click', function() {
var responseOne = $("#AnswerOne input[type='radio'][name='ocean']:checked").val();
selectAnswers.push(responseOne)
if (selectAnswers[0] === correctValues[0]) {
correctCount++;
console.log("Right: " + correctCount);
console.log(selectAnswers)
} else if (selectAnswers[0] !== correctValues[0]) {
wrongCount++;
console.log("Wrong: " + wrongCount);
console.log(selectAnswers)
}
if (seconds === 0){
stopCount();
}
});
$("#AnswerTwo").one('click', function() {
var responseTwo = $("#AnswerTwo input[type='radio'][name='mountain']:checked").val();
selectAnswers.push(responseTwo)
if (selectAnswers[1] === correctValues[1]) {
correctCount++;
console.log("Right: " + correctCount);
console.log(selectAnswers)
} else if (selectAnswers[1] !== correctValues[1]) {
wrongCount++;
console.log("Wrong: " + wrongCount);
console.log(selectAnswers)
}
if (seconds === 0){
stopCount();
}
});
$("#AnswerThree").one('click', function() {
var responseThree = $("#AnswerThree input[type='radio'][name='ditch']:checked").val();
selectAnswers.push(responseThree)
if (selectAnswers[2] === correctValues[2]) {
correctCount++;
console.log("Right: " + correctCount);
console.log(selectAnswers)
} else if (selectAnswers[2] !== correctValues[2]) {
wrongCount++;
console.log("Wrong: " + wrongCount);
console.log(selectAnswers)
}
if (seconds === 0){
stopCount();
}
});
$("#AnswerFour").one('click', function() {
var responseFour = $("#AnswerFour input[type='radio'][name='amount']:checked").val();
selectAnswers.push(responseFour)
if (selectAnswers[3] === correctValues[3]) {
correctCount++;
console.log("Right: " + correctCount);
console.log(selectAnswers)
} else if (selectAnswers[3] !== correctValues[3]) {
wrongCount++;
console.log("Wrong: " + wrongCount);
console.log(selectAnswers)
}
if (seconds === 0){
stopCount();
}
});
$("#AnswerFive").one('click', function() {
var responseFive = $("#AnswerFive input[type='radio'][name='planet']:checked").val();
selectAnswers.push(responseFive)
if (selectAnswers[4] === correctValues[4]) {
correctCount++;
console.log("Right: " + correctCount);
console.log(selectAnswers)
} else if (selectAnswers[4]!== correctValues[4]) {
wrongCount++;
console.log("Wrong: "+ wrongCount);
console.log(selectAnswers)
}
if (seconds === 0){
stopCount();
}
});
$("#AnswerSix").one('click', function() {
var responseSix = $("#AnswerSix input[type='radio'][name='mass']:checked").val();
selectAnswers.push(responseSix)
if (selectAnswers[5] === correctValues[5]) {
correctCount++;
console.log("Right: " + correctCount);
console.log(selectAnswers)
} else if (selectAnswers[5] !== correctValues[5]) {
wrongCount++;
console.log("Wrong: " + wrongCount);
console.log(selectAnswers)
}
if (seconds === 0){
stopCount();
}
});
/* maybe try making a submit button
$("#submitButton").submit('click', function() {
console.log("Right: " + correctCount);
console.log("Wrong: " + wrongCount);
console.log(selectAnswers)
stopCount();
});*/
};
runLogic();
//set the total time run, make this definition global
//make sure this timer runs as a function that includes all of the logic above
var seconds = 30;
//create a name for your interval that refreshes for your countdown, leave undefined
var myInterval;
//function that decrements from global second 30 and logs it up
//reset seconds to 30;
var decrement = function () {
seconds--
console.log(seconds);
console.log("T-minus!");
//update the div #clockCounting display everytime seconds variable is decreased by one
$("#clockCounting").html("<h4><hr>T-Minus: " + seconds + " seconds!<hr></h4>");
//will refer to the stopCount function below when seconds gets to 0
if (seconds === 0) {
$("#lookUp").html("Scroll up to view your score!");
//will skip to the function responsible for stopping the decrement at the bottom
stopCount();
emptyQuestionContent();
pushSolutions();
}
}
//push all of the cumulative correctCount and wrongCount tally variables to question div in html
var pushSolutions = function() {
var newDiv = $("<div>");
$("#clockCounting").append(newDiv);
newDiv.append("Correct Responses: " + correctCount + "<br>");
newDiv.append("Wrong Responses: " + wrongCount);
}
//call a function initiates the countDown function
var startQuiz = function() {
countDown();
}
//empties all the contents of the questions div in html
var emptyQuestionContent = function(){
$("#clockCounting").empty();
}
//changes the myInterval variable to seconds from milliseconds while decreasing
var countDown = function() {
myInterval = setInterval(decrement, 1000);
}
//clears all of the interval decrements and ends the program
var stopCount = function() {
clearInterval(myInterval);
}
countDown();
});
//My original pseudo-coding for logic portion:
//maybe var questionsArr = ["#questionOne", "#questionTwo", "#questionThree", "questionFour", "#questionFifth", "#questionSixth"];
//try pushing it to an array selectedValues, let this complete before it runs comparisons
//selectedValues.push(for each radio button recorded)
//initiate comparisons iterations with "for (var i=0; i<correctValues.length; i++)"
//then compare these selectedValues array indices with the correctValues indices using if statements
//if selectedValues[i] = correctValues[i], then add one to correctCount via increments
//console.log(correctCount)
//post this correctCount onto html screen after this whole program runs
//else if selectedValues[i] != correctValues[i], then add one to wrongCount via increments
//console.log(wrongCount)
//post this wrongCount onto html screen after this whole program runs
//Jerome's suggestion; try your own way first to understand radio buttons inputs thoroughly
//Object with keys as questions : values as possible answers; index
//var QuestionAnswers = {
//"Which ocean is the deepest in the world?": ["Pacific Ocean", ["Atlantic Ocean","Indian Ocean","Arctic Ocean"]],
//"Where is the highest point of the Earth's crust?": ["Mt. Everest", ["Mt. Shasta", "Mt. Morty", "Mt. Schwifty"]],
//"Where is the lowest point of the Earth's crust?": ["Mariana Trench", ["Death Valley", "Florida", "Trump's Inauguration"]],
//"How many protons are in hydrogen's most common isotope?": ["1", ["2", "3", "4"]],
//"What is the 6th planet of our solar system, inward to outward?": ["Saturn", ["Uranus", "Neptune", "Earth"]],
//"What is the matching chemical weight (amu) for sodium phosphate?": ["142", ["234", "54.6", "38.8"]]
//}
//new variable that represents every question (aka key) in the QuestionAnswers object
//var allQuestions = Object.keys(QuestionAnswers);
//place all of these into an id you placed in html via iteration
//new variable that represents every answer (aka value) in the QuestionAnswers object
//var allAnswers = Object.values(QuestionAnswers);
//place all of these into an id you placed in html via iteration
//var formatQA = function(){
//}
//Other random thoughts for pseudo-coding:
//try an array of id's for you to dynamically run through
//not sure if these ids can be referred to in an array
/*var questionIdArr = ["#questionOne", "#questionTwo", "#questionThree", "#questionFour", "#questionFive"];
var loopButtons = function() {
//go through the questions one by one
for(var i=0; i<questionIdArr.length; i++) {
//append radio buttons onto each question as you iterate
$('#questionIdArr').append('<input type="radio" name="Question: " />');
}
}
//all the right answers you want to compare with the selected values
//maybe try for(i=0; i<)*/
| 5301c5bb2b7bb1b6b64a3ec6ed3dd586792f22b0 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | aalexanderlee/TriviaGame | 6008a7607ccc85205671595a8e9820ae72376182 | fd5466c0c505c9368640cf085b629a2d09f41912 |
refs/heads/master | <repo_name>MelonSmasher/icinga2_core<file_sep>/recipes/package_install.rb
#
# Cookbook:: icinga2_core
# Recipe:: package_install
#
# If we are on a supported platform
if %w(debian ubuntu redhat centos fedora amazon windows).include?(node['platform'])
require 'fileutils'
icinga2_core_lock_dir = '/etc/melonsmasher/icinga2/'
# Install the icinga2 package
case node['os']
# Install icinga2 through chocolatey
when 'windows'
chocolatey 'icinga2' do
action :upgrade
end
when 'linux'
# Install icinga2 through yum or apt
package 'icinga2' do
action :upgrade
end
# Install monitoring plugins
case node['platform']
# Debian/Ubuntu
when 'ubuntu' 'debian'
package 'nagios-plugins-all' do
action :upgrade
end
if default['icinga2_core']['install_vim_plugin']
package 'vim-addon-manager' do
action :install
end
package 'vim-icinga2' do
action :install
end
unless File.file?("#{icinga2_core_lock_dir}vim_plugin_enabled")
execute 'enable vim plugin' do
command 'vim-addon-manager -w install icinga2'
end
file "#{icinga2_core_lock_dir}vim_plugin_enabled" do
content 'true'
mode '0755'
owner 'root'
group 'root'
end
end
else
file "#{icinga2_core_lock_dir}vim_plugin_enabled" do
action :delete
mode '0755'
owner 'root'
group 'root'
end
end
# RHEL based stuff
when 'redhat', 'centos', 'fedora', 'amazon'
package 'nagios-plugins-all' do
action :upgrade
end
if node['icinga2_core']['install_vim_plugin']
package 'vim-icinga2' do
action :install
end
end
end
# Make sure the service is enabled and started
service 'icinga2' do
action [:enable, :start]
end
end
end
<file_sep>/metadata.rb
name 'icinga2_core'
maintainer '<NAME>'
maintainer_email '<EMAIL>'
license 'MIT'
description 'Installs icinga2 core'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
chef_version '>= 12' if respond_to?(:chef_version)
version '0.1.5'
issues_url 'https://github.com/MelonSmasher/icinga2_core/issues' if respond_to?(:issues_url)
source_url 'https://github.com/MelonSmasher/icinga2_core' if respond_to?(:source_url)
depends 'chocolatey', '>= 1.2.1'
%w(redhat centos amazon ubuntu debian windows).each do |os|
supports os
end
<file_sep>/README.md
# icinga2_core
Install icinga2 core. This is needed for the the client and the server.
## Usage:
```ruby
include_recipe 'icinga2_core'
```
<file_sep>/recipes/default.rb
#
# Cookbook:: icinga2_core
# Recipe:: default
if %w(debian ubuntu redhat centos fedora amazon windows).include?(node['platform'])
icinga2_core_lock_dir = '/etc/melonsmasher/icinga2/'
unless node['platform'] == 'windows'
directory icinga2_core_lock_dir do
owner 'root'
group 'root'
mode '0755'
recursive true
action :create
end
end
include_recipe 'icinga2_core::sources'
include_recipe 'icinga2_core::package_install'
end
<file_sep>/recipes/sources.rb
#
# Cookbook:: icinga2_core
# Recipe:: sources
#
# If we are on a supported platform
if %w(debian ubuntu redhat centos fedora amazon windows).include?(node['platform'])
icinga2_core_lock_dir = '/etc/melonsmasher/icinga2/'
case node['platform']
when 'debian', 'ubuntu' # for Debian based systems
# Make sure we have wget
package 'install wget' do
package_name 'wget'
action :install
end
unless File.file?("#{icinga2_core_lock_dir}icinga2_apt_key_added")
# Install the apt key we need
execute 'add apt key' do
command 'wget -O - https://packages.icinga.com/icinga.key | apt-key add -'
end
file "#{icinga2_core_lock_dir}icinga2_apt_key_added" do
content 'true'
mode '0755'
owner 'root'
group 'root'
end
end
# Add the apt sources
template '/etc/apt/sources.list.d/icinga.list' do
source 'icinga_debian.list.erb'
end
when 'redhat', 'centos', 'fedora', 'amazon' # for RHEL based systems
# don't keep running this
#unless File.file?("#{icinga2_core_lock_dir}icinga2_yum_repo_added")
# What version of RHEL?
case node['platform_version'].to_i
when 6
rpm_package 'icinga-rpm-release' do
allow_downgrade true
source 'https://packages.icinga.com/epel/icinga-rpm-release-6-latest.noarch.rpm'
action :install
end
when 7
rpm_package 'icinga-rpm-release' do
allow_downgrade true
source 'https://packages.icinga.com/epel/icinga-rpm-release-7-latest.noarch.rpm'
action :install
end
end
file "#{icinga2_core_lock_dir}icinga2_yum_repo_added" do
content 'true'
mode '0755'
owner 'root'
group 'root'
end
#end
when 'windows'
include_recipe 'chocolatey'
end
end
<file_sep>/attributes/default.rb
default['icinga2_core']['install_vim_plugin'] = false | 24e476f1947d9b5c522d4cc6027f232ce5bd7995 | [
"Markdown",
"Ruby"
] | 6 | Ruby | MelonSmasher/icinga2_core | 6a3f0a51220242ba9c3dde7f2b5607845173e172 | 9e748abfa396888e3eeabf6303e66bcbb6b38fa7 |
refs/heads/master | <file_sep>'use strict';
/**
*
*/
angular.module('pooIhmExemplesApp')
.controller('ProjectsCtrl', ['$scope', '$http', '$routeParams', function ($scope, $http, $routeParams) {
$scope.successes = [];
$scope.alerts = [];
$scope.dataUsers = [];
$scope.project;
$scope.getAllProjects = function() {
$http.get('http://poo-ihm-2015-rest.herokuapp.com/api/Projects')
.success(function (data) {
$scope.projects = data.data;
});
};
$scope.getAllDataUsers = function() {
$http.get('http://poo-ihm-2015-rest.herokuapp.com/api/Users')
.success(function(data) {
$scope.brutUsers = data.data;
$scope.dataUsers = [];
for(var j = 0; j < $scope.brutUsers.length; j++){
$scope.dataUsers[j] = [];
$scope.dataUsers[j].accepted = "0";
$scope.dataUsers[j].user = $scope.brutUsers[j];
}
});
};
$scope.addAProject = function() {
$http.post('http://poo-ihm-2015-rest.herokuapp.com/api/Projects/', $scope.project)
.success(function(data){
if (data.status == "success"){
$scope.successes.push("ajout reussi");
}else{
$scope.alerts.push("l'ajout est un échec.");
}
}).error(function(){
$scope.alerts.push("une erreur a empéché l'ajout.");
});
};
$scope.changeAProject = function() {
$http.put('http://poo-ihm-2015-rest.herokuapp.com/api/Projects/' + $scope.project.id, $scope.project)
.success(function(data){
if (data.status == "success"){
$scope.successes.push("changement reussi");
}else{
$scope.alerts.push("le changement est un echec.");
}
}).error(function(){
$scope.alerts.push("une erreur a empéché le changement.");
});
};
$scope.deleteAProject = function() {
$http.delete('http://poo-ihm-2015-rest.herokuapp.com/api/Projects/' + $scope.user.id)
.success(function(data){
if (data.status == "success"){
$scope.successes.push("suppression reussi");
}else{
$scope.alerts.push("la suppression est un echec.");
}
}).error(function(){
$scope.alerts.push("une erreur a empeche la suppression");
});
};
$scope.addUsersToProject = function(){
$scope.addMode = true;
};
$scope.removeUsersToProject = function(){
$scope.removeMode = true;
};
$scope.resetUsersToProject = function(){
$scope.removeMode = null;
$scope.addMode = null;
};
$scope.getUserByProject = function(idProject) {
$http.get('http://poo-ihm-2015-rest.herokuapp.com/api/Projects/' + idProject + '/Users')
.success(function(data) {
$scope.project.users = data.data;
$scope.tmp = true;
for (var j = 0; j < $scope.dataUsers.length; j++) {
$scope.dataUsers[j].accepted = null;
}
for(var k = 0; k < $scope.project.users.length; k++){
$scope.tmp = true;
for(var i = 0; $scope.tmp && (i < $scope.dataUsers.length); i++) {
if ($scope.idEquals($scope.dataUsers[i].user, $scope.project.users[k])) {
$scope.dataUsers[i].accepted = "1";
$scope.tmp = false;
}
}
// console.log($scope.dataUsers[i]);
// parfois une erreur inconnu arrive et empeche l'egalite d'etre reconnu ...
}
}).error(function(){
$scope.alerts.push("une erreur a empeché la récupération des utilisateurs de ce projet.");
});
};
$scope.idEquals = function(u1, u2){
if((u1 == 'undefined') || (u2 == 'undefined') || (u1 == null) || (u2 == null)){
return false;
}
return (u1.id == u2.id);
};
$scope.addUserToProject = function(userId){
$http.put('http://poo-ihm-2015-rest.herokuapp.com/api/Projects/' + $scope.project.id + '/Users/' + userId)
.success(function(data){
if (data.status == "success"){
$scope.getUserByProject($scope.project.id);
$scope.successes.push("l'utilisateur "+ " a bien été ajouter au projet.");
}else{
$scope.alerts.push("l'utilisateur n'a pas été ajouté au projet.");
}
}).error(function(){
$scope.alerts.push("une erreur a empéche l'ajout de l'utilisateur au projet.");
});
};
$scope.removeUserToProject = function(userId){
$http.delete('http://poo-ihm-2015-rest.herokuapp.com/api/Projects/' + $scope.project.id + '/Users/' + userId)
.success(function(data){
if (data.status == "success"){
$scope.getUserByProject($scope.project.id);
$scope.successes.push("l'utilisateur "+ " a bien été supprimé du projet.");
}else{
$scope.alerts.push("l'utilisateur n'a pas été supprimé du projet.");
}
}).error(function(){
$scope.alerts.push("une erreur a empéche la suppression de l'utilisateur au projet.");
});
};
if($routeParams.projectId) {
$http.get('http://poo-ihm-2015-rest.herokuapp.com/api/Projects/' + $routeParams.projectId)
.success(function(data) {
if (data.status == "success") {
$scope.project = data.data;
$scope.getAllDataUsers();
$scope.getUserByProject($routeParams.projectId);
}else{
$scope.alerts.push("les données de ce projet sont indisponible");
}
}).error(function(){
$scope.alerts.push("le projet est introuvable");
})
}else{
$scope.getAllProjects();
}
}]);
| 7d4104bfd04d04c84d3669b6509b5c563bf3b36c | [
"JavaScript"
] | 1 | JavaScript | CorentinHardy/poo3_annuaire | f21cbb286eb8ed5de9083418191e24951de193c7 | 4ccfa39a871f7a9eefa3e13fd1cf4d0f0bca0200 |
refs/heads/master | <file_sep>FactoryBot.define do
factory :item do
association :user
name { '商品' }
text { 'アイウエオ' }
category_id {2}
status_id {2}
cost_id {2}
area_id {2}
delivery_id {2}
price {1000}
after(:build) do |item|
item.image.attach(io: File.open('spec/fixtures/test_image.png'), filename: 'test_image.png')
end
end
end
<file_sep>require 'rails_helper'
RSpec.describe User, type: :model do
before do
@user = FactoryBot.build(:user)
end
context 'ユーザー管理ができている時' do
it 'nicknameとemail、passwordとpassword_confirmation,myojiとnamae,myoji_kanaとnamae_kana,birthdayが存在すれば登録できること' do
expect(@user).to be_valid
end
end
context 'ユーザー管理がうまくいってない時' do
it 'nicknameが空では登録できないこと' do
@user.nickname = ''
@user.valid?
expect(@user.errors.full_messages).to include("Nickname can't be blank")
end
it 'emailが空では登録できないこと' do
@user.email = ''
@user.valid?
expect(@user.errors.full_messages).to include("Email can't be blank")
end
it 'passwordが空では登録できないこと' do
@user.password = ''
@user.valid?
expect(@user.errors.full_messages).to include("Password can't be blank")
end
it 'password_confirmationが空では登録できないこと' do
@user.password_confirmation = ''
@user.valid?
expect(@user.errors.full_messages).to include("Password confirmation doesn't match Password")
end
it 'myojiが空では登録できないこと' do
@user.myoji = ''
@user.valid?
expect(@user.errors.full_messages).to include("Myoji can't be blank")
end
it 'namaeが空では登録できないこと' do
@user.namae = ''
@user.valid?
expect(@user.errors.full_messages).to include("Namae can't be blank")
end
it 'myoji_kanaが空では登録できないこと' do
@user.myoji_kana = ''
@user.valid?
expect(@user.errors.full_messages).to include("Myoji kana can't be blank")
end
it 'namae_kanaが空では登録できないこと' do
@user.namae_kana = ''
@user.valid?
expect(@user.errors.full_messages).to include("Namae kana can't be blank")
end
it 'birthdayが空では登録できないこと' do
@user.birthday = ''
@user.valid?
expect(@user.errors.full_messages).to include("Birthday can't be blank")
end
it 'password:半角英数混合(半角英語のみ)' do
@user.password = '<PASSWORD>'
@user.valid?
expect(@user.errors.full_messages).to include("Password には英字と数字の両方を含めて設定してください")
end
it 'password:半角英数混合(半角数字のみ)' do
@user.password = '<PASSWORD>'
@user.valid?
expect(@user.errors.full_messages).to include("Password には英字と数字の両方を含めて設定してください")
end
it 'passwordが6文字未満' do
@user.password = '<PASSWORD>'
@user.valid?
expect(@user.errors.full_messages).to include("Password is too short (minimum is 6 characters)")
end
it 'emailが@を含まない' do
@user.email = 'test.test'
@user.valid?
expect(@user.errors.full_messages).to include('Email is invalid')
end
it 'emailの重複すると登録できない' do
@user.save
another_user = FactoryBot.build(:user, email: @user.email)
another_user.valid?
expect(another_user.errors.full_messages).to include("Email has already been taken")
end
it 'パスワードと確認用のパスワードが一致しないと登録できない' do
@user.password = <PASSWORD>(:user)
@user.password_confirmation = <PASSWORD>.<PASSWORD>(:user)
@user.valid?
expect(@user.errors.full_messages).to include("Password confirmation doesn't match Password")
end
it 'パスワード全角文字だと登録できない' do
@user.password = '<PASSWORD>'
@user.valid?
expect(@user.errors.full_messages).to include("Password には英字と数字の両方を含めて設定してください")
end
it 'myoji_kana 半角文字だと登録できない' do
@user.myoji_kana = 'ヤマダ'
@user.valid?
expect(@user.errors.full_messages).to include("Myoji kana 全角文字を使用してください")
end
it 'namae_kana 半角文字だと登録できない' do
@user.namae_kana = 'タロウ'
@user.valid?
expect(@user.errors.full_messages).to include("Namae kana 全角文字を使用してください")
end
it 'myoji_kana カタカナ以外の全角文字は登録できない' do
@user.myoji_kana = 'やまだ'
@user.valid?
expect(@user.errors.full_messages).to include("Myoji kana 全角文字を使用してください")
end
it 'namae_kana カタカナ以外の全角文字は登録できない' do
@user.namae_kana = 'たろう'
@user.valid?
expect(@user.errors.full_messages).to include("Namae kana 全角文字を使用してください")
end
it 'namae 半角文字だと登録できない' do
@user.namae = 'タロヴ'
@user.valid?
expect(@user.errors.full_messages).to include("Namae 全角文字を使用してください")
end
it 'myoji 半角文字だと登録できない' do
@user.myoji = 'タナカ'
@user.valid?
expect(@user.errors.full_messages).to include("Myoji 全角文字を使用してください")
end
end
end<file_sep>class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many :items
#has_many :orders
with_options presence: true do
validates :nickname
validates :myoji
validates :namae
validates :myoji_kana
validates :namae_kana
validates :birthday
with_options format: { with: /\A[ァ-ヶー-]+\z/, message: '全角文字を使用してください' } do
validates :myoji_kana
validates :namae_kana
end
with_options format: { with: /\A[ぁ-んァ-ン一-龥々ー]+\z/, message: '全角文字を使用してください' } do
validates :myoji
validates :namae
end
PASSWORD_REGEX = /\A(?=.*?[a-z])(?=.*?\d)[a-z\d]+\z/i.freeze
validates_format_of :password, with: PASSWORD_REGEX, message: 'には英字と数字の両方を含めて設定してください'
end
end
<file_sep>class OrderAddress
include ActiveModel::Model
attr_accessor :user_id, :item_id, :postal_code, :area_id, :city, :street, :building, :phone_number, :token
with_options presence: true do
validates :token
validates :item_id
validates :user_id
validates :postal_code, format: {with: /\A[0-9]{3}-[0-9]{4}\z/, message: "is invalid. Include hyphen(-)"}
validates :area_id
validates :city
validates :street
validates :phone_number, format: {with: /\A[0-9]+\z/ }
end
validates :area_id, numericality: {other_than: 1, message: "can't be blank"}
validates :phone_number, length: { maximum: 11 }
def save
order = Order.create(item_id: item_id, user_id: user_id)
# Order.create(カラム名: コントローラーから送られてきた値 = attr_accessorで定義したもの)
Address.create(postal_code: postal_code, area_id: area_id, city: city, street: street, phone_number: phone_number, order_id: order.id)
end
end
<file_sep>FactoryBot.define do
factory :order_address do
token {"<KEY> <PASSWORD>"}
postal_code {'111-1111'}
area_id {3}
city { '網走'}
street {'青1-1-1'}
building {'マンション'}
phone_number { '090123456' }
end
end
<file_sep>class Item < ApplicationRecord
belongs_to :user
has_one_attached :image
has_one :order
extend ActiveHash::Associations::ActiveRecordExtensions
belongs_to :category
belongs_to :status
belongs_to :area
belongs_to :cost
belongs_to :delivery
validates :name, :text, :price, :image, presence: true
with_options numericality: { other_than: 1 } do
validates :category_id
validates :status_id
validates :cost_id
validates :area_id
validates :delivery_id
end
validates :price, numericality: { only_integer: true, greater_than_or_equal_to: 300, less_than: 10000000}
end
<file_sep>require 'rails_helper'
RSpec.describe OrderAddress, type: :model do
before do
user = FactoryBot.create(:user)
item = FactoryBot.create(:item)
@address = FactoryBot.build(:order_address, user_id: user.id, item_id: item.id)
sleep 0.5
end
describe '購入情報' do
context '購入情報がうまくいくとき'
it "郵便番号・都道府県・市区町村・番地・建物 電話番号が全てあるとき" do
expect(@address).to be_valid
end
it "建物が空白のとき" do
expect(@address).to be_valid
end
end
context '購入情報がうまくいかないとき'
it "郵便番号がない" do
@address.postal_code = nil
@address.valid?
expect(@address.errors.full_messages).to include("Postal code can't be blank")
end
it "都道府県がない" do
@address.area_id = 1
@address.valid?
expect(@address.errors.full_messages).to include("Area can't be blank")
end
it "市町村がないとき" do
@address.city = nil
@address.valid?
expect(@address.errors.full_messages).to include("City can't be blank")
end
it "番地がないとき" do
@address.street = nil
@address.valid?
expect(@address.errors.full_messages).to include("Street can't be blank")
end
it "電話番号がないとき" do
@address.phone_number = nil
@address.valid?
expect(@address.errors.full_messages).to include("Phone number can't be blank")
end
it "郵便番号にハイフンがないとき" do
@address.postal_code = '1111111'
@address.valid?
expect(@address.errors.full_messages).to include("Postal code is invalid. Include hyphen(-)")
end
it "電話番号が11桁以上のとき" do
@address.phone_number = '090123456789'
@address.valid?
expect(@address.errors.full_messages).to include("Phone number is too long (maximum is 11 characters)")
end
it "tokenが空では登録できないこと" do
@address.token = nil
@address.valid?
expect(@address.errors.full_messages).to include("Token can't be blank")
end
it "item_idが空のとき登録できない" do
@address.item_id = nil
@address.valid?
expect(@address.errors.full_messages).to include("Item can't be blank")
end
it "user_idが空のとき登録できない" do
@address.user_id = nil
@address.valid?
expect(@address.errors.full_messages).to include("User can't be blank")
end
it "電話番号が数字以外のとき(英数字混合)登録できない" do
@address.phone_number = '111aaaaaa'
@address.valid?
expect(@address.errors.full_messages).to include("Phone number is invalid")
end
end
<file_sep>require 'rails_helper'
RSpec.describe Item, type: :model do
before do
@item = FactoryBot.build(:item)
end
describe '商品情報' do
context '商品情報がうまくいくとき' do
it "画像、商品名、説明、詳細、配送が存在する" do
expect(@item).to be_valid
end
end
context '商品情報がうまくいかないとき' do
it "画像が存在しない" do
@item.image = nil
@item.valid?
expect(@item.errors.full_messages).to include()
end
it "商品名が存在してない" do
@item.name = ''
@item.valid?
expect(@item.errors.full_messages).to include("Name can't be blank")
end
it "商品説明が存在してない" do
@item.text = ''
@item.valid?
expect(@item.errors.full_messages).to include("Text can't be blank")
end
it "詳細(カテゴリー)が1の時" do
@item.category_id = 1
@item.valid?
expect(@item.errors.full_messages).to include("Category must be other than 1")
end
it "詳細(状態)が1の時" do
@item.status_id = 1
@item.valid?
expect(@item.errors.full_messages).to include("Status must be other than 1")
end
it "配送(負担)が1の時" do
@item.cost_id = 1
@item.valid?
expect(@item.errors.full_messages).to include("Cost must be other than 1")
end
it "配送(地域)が1の時" do
@item.area_id = 1
@item.valid?
expect(@item.errors.full_messages).to include("Area must be other than 1")
end
it "配送(日数)が1の時" do
@item.delivery_id = 1
@item.valid?
expect(@item.errors.full_messages).to include("Delivery must be other than 1")
end
it "price(価格)の記入が全角数字の時" do
@item.price = '1000'
@item.valid?
expect(@item.errors.full_messages).to include("Price is not a number")
end
it "price(価格)の範囲が300未満の時" do
@item.price = 100
@item.valid?
expect(@item.errors.full_messages).to include("Price must be greater than or equal to 300")
end
it "price(価格)の範囲が10000000以上の時" do
@item.price = 100000000
@item.valid?
expect(@item.errors.full_messages).to include("Price must be less than 10000000")
end
it "userが紐づいてない" do
@item.user = nil
@item.valid?
expect(@item.errors.full_messages).to include('User must exist')
end
it "price(価格)の記入が全角文字の時" do
@item.price = 'あああああ'
@item.valid?
expect(@item.errors.full_messages).to include("Price is not a number")
end
it "price(価格)の記入が半角英数混合では登録できない" do
@item.price = '1q1q1q'
@item.valid?
expect(@item.errors.full_messages).to include("Price is not a number")
end
it "price(価格)の半角英語のみでは登録できない" do
@item.price = 'aaaaaa'
@item.valid?
expect(@item.errors.full_messages).to include("Price is not a number")
end
end
end
end
<file_sep>window.addEventListener('DOMContentLoaded', () => {
const priceInput = document.getElementById("item-price")
const tax = document.getElementById("add-tax-price")
const price = document.getElementById("profit")
priceInput.addEventListener("keyup", () => {
const inputValue = priceInput.value;
let priceTax = Math.floor(inputValue * 0.1);
let sum = Math.floor(inputValue * 0.9);
tax.innerHTML = priceTax;
price.innerHTML = sum;
})
});
<file_sep>FactoryBot.define do
factory :user do
nickname { Faker::Internet.username }
email { Faker::Internet.free_email }
password { '<PASSWORD>(min_length: 6) }
password_confirmation { <PASSWORD> }
myoji { '山田' }
namae { '太郎' }
myoji_kana { 'ヤマダ' }
namae_kana { 'タロウ' }
birthday { '1999-01-01' }
end
end
| 51645418dd0030d42ba05da7f09f25ff96a213d5 | [
"JavaScript",
"Ruby"
] | 10 | Ruby | reito010/furima-35000 | eac8f4ed2ee00e8de2fa8452f4bf6e6f41d89ff8 | 1793ec6ebc20d6b758188f48b122981424fe2291 |
refs/heads/master | <file_sep>package com.example.asus.downloadanduploadimage;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends AppCompatActivity {
String string_url = "http://mobileadvertisingwatch.com/wp-content/uploads/2016/02/Can-You-Name-the-Best-Android-App-Dev-Companies-GoodFirms-Just-Released-Its-List.jpg";
// String string_url = "https://yt3.ggpht.com/-2KXvguf9c8E/AAAAAAAAAAI/AAAAAAAAAAA/GKYOlzIEpHc/s900-c-k-no-mo-rj-c0xffffff/photo.jpg";
@BindView(R.id.button)
Button button;
@BindView(R.id.image_view)
ImageView imageView;
ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
@OnClick(R.id.button)
public void onViewClicked() {
DownLoadTask downLoadTask = new DownLoadTask();
downLoadTask.execute(string_url);
}
class DownLoadTask extends AsyncTask<String, Integer, String> implements DownLoad {
@Override
protected String doInBackground(String... voids) {
URL downloadURL=null;
int counter=0;
HttpURLConnection connection=null;
InputStream inputStream=null;
FileOutputStream fileOutputStream=null;
File file=null;
try{
downloadURL=new URL(voids[0]);
connection=(HttpURLConnection) downloadURL.openConnection();
inputStream=connection.getInputStream();
file=new File(Environment.getExternalStorageDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath()
+"/"+ Uri.parse(voids[0]).getLastPathSegment());
fileOutputStream=new FileOutputStream(file);
int read=-1;
byte[]buffer=new byte[1024];
while ((read=inputStream.read(buffer))!=-1){
fileOutputStream.write(buffer,0,read);
counter+=read;
publishProgress(counter);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// String path = voids[0];
// int fileLength = 0;
// try {
// URL url = new URL(path);
// URLConnection urlConnection = url.openConnection();
// urlConnection.connect();
// fileLength = urlConnection.getContentLength();
// File newFolder = new File("Downloads");
// if (!newFolder.exists()) {
// newFolder.mkdir();
// }
// File fileInput = new File(newFolder, "download_image.jpg");
// InputStream inputStream = new BufferedInputStream(url.openStream(),8192);
// byte[] data = new byte[1024];
// int total = 0;
// int count = 0;
// int read=-1;
// OutputStream outputStream = new FileOutputStream(newFolder);
// while ((read = inputStream.read(data)) != -1) {
// total += count;
// outputStream.write(data, 0, read);
// int progress = (int) total * 100 / fileLength;
// publishProgress(progress);
// }
// inputStream.close();
// outputStream.close();
// } catch (MalformedURLException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// }
// return "Download complete";
}
@Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setTitle("Download in progress...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMax(100);
progressDialog.setProgress(0);
progressDialog.show();
}
@Override
protected void onProgressUpdate(Integer... values) {
progressDialog.setProgress(values[0]);
}
@Override
protected void onPostExecute(String aVoid) {
progressDialog.hide();
Toast.makeText(getApplicationContext(), aVoid, Toast.LENGTH_LONG).show();
String path = "Downloads/download_image.jpg";
imageView.setImageDrawable(Drawable.createFromPath(path));
}
}
}
| 05d778babb8608b887ef650c8ea0885b04af2dde | [
"Java"
] | 1 | Java | BichCNTT/DownloadAndUploadImageUseAsynctask | a7393ed8eeac1a1395905054c6eff9b980e26626 | 8c9f41bfe5129157420407c67525aec7ce0c124a |
refs/heads/master | <repo_name>jonchaney/battleship<file_sep>/src/player.js
const Board = require('./board.js');
const Util = require('./util.js');
class Player {
constructor(name) {
this.name = name;
this.board = new Board();
}
placeShips(shipsPlaced) {
let i = 0;
let ships = this.board.ships;
let message = document.getElementById('message')
if (!message) { // if it does not exist create a new one for testing
message = document.createElement('p');;
} else {
message.innerHTML = `${this.name} place your ` // tell player which ship to place
}
let loopShips = (ships) => {
ships[i].shipInfo(); // display ship information
let table = document.getElementById(`${this.name}`)
if (!table) { // if it does not exist create a new one for testing
table = document.createElement('table');
}
table.addEventListener('click', (event) => {
if (i !== this.board.ships.length) { // only respond to onclick if all ships placed
placeSingleShip(event.target.data, ships[i], () => {
i++;
if (i === this.board.ships.length) { // if all ships are placed
setTimeout(() => { // set time out for UI/UX purposes
Util.remove(this.name); // remove board from DOM
this.board.gameStarted = true;
shipsPlaced(); // call back function
}, 1000);
} else {
document.getElementById('ship').innerHTML = `${ships[i].type} (length ${ships[i].length})`
}
});
}
});
}
const placeSingleShip = (coordinates, ship, nextShip) => {
let axis = document.getElementById('axis').innerHTML;
if (this.board.validPosition(coordinates, ship, axis)) {
this.board.placeShip(coordinates, ship, axis);
this.board.updateBoard(this.name);
} else {
this.board.errors('invalid position');
}
if (ship.length === ship.coordinates.length) {
nextShip();
}
}
loopShips(ships);
}
makeMove(opposingPlayer, callback) {
opposingPlayer.displayBoard();
document.getElementById('attack').innerHTML = `${this.name} make your move!`
const move = (opposingPlayer) => {
document.getElementById(`${opposingPlayer.name}`).addEventListener('click', (event) => {
let board = opposingPlayer.board;
let coordinate = event.target.data;
takeShot(coordinate, board, () => {
callback();
});
});
const takeShot = (coordinate, board, nextPlayer) => {
if (board.fire(coordinate)) {
Util.remove(`${opposingPlayer.name}`);
board.display(opposingPlayer.name);
setTimeout(() => {
board.attackInfo("");
Util.remove(`${opposingPlayer.name}`);
nextPlayer();
}, 1000);
}
}
}
move(opposingPlayer);
}
lost() {
if(this.board.shipsSunk === this.board.ships.length) {
return true;
} else {
return false;
}
}
resetBoard(n) {
this.board.reset(n)
}
displayBoard() {
this.board.display(this.name);
}
}
module.exports = Player;<file_sep>/readme.md
# [Battleship](https://jonchaney.github.io/battleship/)
## Technologies Used
- Vanilla Javascript
- Webpack
- Babel
- Sass
- Jest for testing
## To Run
- npm install
- npm start (will run webpack, sass, and open static html file)
- npm test will run Jest tests<file_sep>/src/entry.js
const Battleship = require('./battleship.js')
document.addEventListener('DOMContentLoaded', () => {
window.game = new Battleship();
game.playGame();
});<file_sep>/src/ship.js
class Ship {
constructor(type, length) {
this.length = length;
this.count = 0;
this.type = type;
this.coordinates = [];
}
isSunk() {
if (this.count === this.length) { return true; }
}
shipInfo(){
let ship = document.getElementById('ship');
if (!ship) { // if it does not exist create a new one for testing
ship = document.createElement('p');;
}
ship.innerHTML = `${this.type} (length ${this.length})`
}
}
module.exports = Ship;<file_sep>/src/board.js
const Ship = require('./ship.js');
const Util = require('./util.js');
class Board {
constructor(n = 10) {
this.generateBoard(n);
this.ships = [new Ship('Battleship', 4),
new Ship('Cruiser', 3),
new Ship('Carrier', 5),
new Ship('Submarine', 3),
new Ship('Destroyer', 2)];
this.gameStarted = false;
this.shipsSunk = 0;
}
display(name) {
let tables = document.getElementById('tables');
let table = document.getElementById(`${name}`)
if (!table) { // if it does not exist create a new one
table = document.createElement('table');;
}
if (!tables) { // if it does not exist create a new one
tables = document.createElement('tables');;
} // for testing
let tr; // row
let td; // column
this.grid.forEach((row, i) => {
tr = document.createElement('tr');
row.forEach((col, j) => {
td = document.createElement('td');
td.data = [i,j]
if (this.grid[i][j] === 1 && !this.gameStarted) { // only show where ships are placed if game has not started
td.classList.add('occupied');
} else if (this.grid[i][j] === 'o') {
td.classList.add('missed');
} else if (this.grid[i][j] === 'x') {
td.classList.add('hit');
}
tr.appendChild(td)
})
table.appendChild(tr);
});
table.setAttribute('id',`${name}`);
tables.appendChild(table);
}
updateBoard(name) {
let table = document.getElementById(`${name}`);
// remove all the chldren (rows) and update board
while (table.firstChild) {
table.removeChild(table.firstChild);
}
this.display(name);
}
generateBoard(n) {
let row = [];
this.grid = [];
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
row.push(0);
}
this.grid.push(row);
row = [];
}
}
validPosition(coordinates, ship, axis) {
this.clearErrors();
let i = 0;
if (axis === 'Horizontal') { // check for overlapping or out of bounds horizontally placed ship
while (i < ship.length) {
if (this.grid[coordinates[0]][coordinates[1]+i] === 1){
return false;
};
i++;
}
if (coordinates[1] + ship.length > this.grid[0].length) { // check if out of bounds
return false;
}
} else { // check for overlapping or out of bounds vertically placed ship
if(coordinates[0] + ship.length > this.grid.length) {
return false;
} else {
while (i < ship.length) {
if (this.grid[coordinates[0]+i][coordinates[1]] === 1) {
return false;
}
i++;
}
}
}
return true;
}
placeShip(startPos, ship, axis) {
this.grid[startPos[0]][startPos[1]] = 1; // add location data to grid
let i = 0;
if (axis === 'Horizontal') { // horizontal ship placement
while (ship.coordinates.length < ship.length) {
ship.coordinates.push([startPos[0],startPos[1]+i]) // add location data to ship
this.grid[startPos[0]][startPos[1]+i] = 1; // update grid
i++;
}
} else { // vertical ship placement
while (ship.coordinates.length < ship.length) {
ship.coordinates.push([startPos[0]+i,startPos[1]])
this.grid[startPos[0]+i][startPos[1]] = 1;
i++;
}
}
}
fire(coordinate) {
this.clearErrors();
let location = this.grid[coordinate[0]][coordinate[1]]; // get grid data
const position = {miss: 0, hit: 1};
switch (location) {
case position.miss:
this.grid[coordinate[0]][coordinate[1]] = 'o';
this.attackInfo('you missed!');
return true;
case position.hit:
this.grid[coordinate[0]][coordinate[1]] = 'x';
this.attackInfo('nice shot!')
this.checkShips(coordinate);
return true;
default:
this.errors('you already fired there!')
return false;
}
}
checkShips(coordinate) {
// checking the coordinates of each ship to see which ship was hit and if it was sunk
this.ships.forEach((ship) => {
ship.coordinates.forEach((location) => {
if (Util.compareArray(coordinate, location)) {
ship.count++
if (ship.isSunk()) {
this.attackInfo(`You sunk their ${ship.type}!`)
this.shipsSunk += 1;
}
}
})
})
}
clearShipCoordinates() {
this.ships.forEach((ship) => {
ship.coordinates = [];
ship.count = 0;
});
}
reset(n) {
// reset game board
this.generateBoard(n);
this.gameStarted = false;
this.shipsSunk = 0;
this.clearShipCoordinates();
}
attackInfo(msg) {
Util.changeInnerHtml('attack-info', msg)
}
errors(error) {
Util.changeInnerHtml('errors', error);
}
clearErrors() {
Util.changeInnerHtml('errors', "");
}
}
module.exports = Board;
| 5fdd1a90fbf9e53fff54a4e4aa0f95aaeb145294 | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | jonchaney/battleship | 2f96790b6ed528c67ff342cd61a9997f6cf2a378 | 70d633bb22ea119a7957d36c24137cac0584c70c |
refs/heads/master | <file_sep>from contextlib import contextmanager
@contextmanager
def open_file(filename, filemode):
print('Opening file {}...'.format(filename))
f = open(filename, filemode)
yield f
print('Closing file {}...'.format(filename))
with open_file('ATATATATA', 'w') as smth:
print(smth)
with | 15129d3f0c1007ca784b79743aa6a22e6eb802ed | [
"Python"
] | 1 | Python | apenshin/TCEH | b08e3292d5d6d9f9ed0424d4e142cad647f3fdcd | 69925d66c180fc67a5ea72b6a83a07f8d915812c |
refs/heads/master | <repo_name>sskyy/zero-taurus<file_sep>/util.js
var cloneDeep = require('lodash.clonedeep')
var assign = require('object-assign')
function noop(){
return null
}
function hook( obj, fnName, fn ){
var _fn = obj[fnName] || noop
obj[fnName] = function(){
fn.apply(this, arguments)
return _fn.apply(this, arguments)
}
return obj
}
function decorate( obj, fnName, fn){
var _fn = obj[fnName]
obj[fnName] = function(){
return fn.apply( this, [_fn].concat( Array.prototype.slice.call(arguments)))
}
return obj
}
function forEach( obj, handler){
Object.keys(obj).forEach(function(key){
handler( obj[key],key)
})
}
function partial( fn, arg ){
return function(){
var args = [arg].concat( Array.prototype.slice.call(arguments ))
return fn.apply(this, args)
}
}
function defaults( target, defaultsObj ){
for( var i in defaultsObj ){
if( defaultsObj.hasOwnProperty(i) && target[i] === undefined){
target[i] = defaultsObj[i]
}
}
return target
}
var _request = require('superagent')
function request( query, backend ){
return new Promise( function( resolve, reject){
_request
.post(backend)
.send(query)
.end(function( err, res){
if( err ) return reject(err)
return resolve( res.body )
})
})
}
function walkAst(ast, handler, context) {
if (context === undefined) context = {}
handler(ast, context)
forEach(ast.relations,function (relation) {
var childContext = assign({}, context, {
relation: {
name: relation.name,
reverse: relation.reverse,
to : relation.to.type
},
parent: {
type: ast.type,
fields: ast.fields,
tracker: ast.tracker
}
})
walkAst(relation.to, handler, childContext)
})
}
function without(source, toRemove){
var output = []
source.forEach( function( item ){
if( toRemove.indexOf(item) === -1){
output.push( item )
}
})
return output
}
function pick( obj, attrs ){
var output = {}
attrs.forEach(function(attr){
if( typeof obj[attr] === 'object' ){
output[attr] = cloneDeep(obj[attr] )
}else{
output[attr] = obj[attr]
}
})
return output
}
function mapValues( obj, handler ){
var output = {}
Object.keys( obj ).forEach(function( key ){
output[key] = handler( obj[key], key )
})
return output
}
function first( obj ){
return obj[Object.keys(obj).shift()]
}
function map( obj, handler ){
return Object.keys( obj ).map(function( key){
return handler(obj[key], key)
})
}
function zipObject( keys, values ){
var result = {}
keys.forEach(function( key, i ){
if( typeof values=== 'function'){
result[key] = values(key)
}else if( typeof values !== 'object' || values.length === undefined){
result[key] = values
}else{
result[key] = values[i]
}
})
return result
}
module.exports = {
hook : hook,
decorate : decorate,
forEach : forEach,
partial : partial,
defaults : defaults,
request:request,
cloneDeep : cloneDeep,
walkAst : walkAst,
without : without,
pick : pick,
mapValues : mapValues,
first : first,
map:map,
zipObject
}<file_sep>/index.js
'use strict'
var _ = require('lodash')
var request = require('superagent')
var util = require('./util')
var uuid = require('uuid')
//var taurusCollection = require('taurus-mongo/lib/collection')
var Taurus = require('taurus-mysql')
function partial(generatorFn) {
var args = Array.prototype.slice.call(arguments, 1)
return function *() {
var runtimeArgs = Array.prototype.slice.call(arguments, 0)
return yield generatorFn.apply(this, args.concat(runtimeArgs))
}
}
///////////////////////////
// create
///////////////////////////
/*
接受的数据结构
[rawNode]{
def : {
type
},
data : {
},
$tracker : 'v0',
$relations : [
{
key : {
name,
reverse
},
props : {},
value : [rawNode]{}
}
]
}
*/
///////////////////////
// destroy
///////////////////////
////////////////////////////
// exports
////////////////////////////
//TODO 写到配置里去
var taurusModule = {
collections: {},
extend: function *(module) {
if( !module.entries || !module.entries.spec ) return
var types = {}
for (let entryName in module.entries.spec) {
if (module.entries.spec[entryName]) {
_.extend(types, _.cloneDeep(_.indexBy(module.entries.spec[entryName].types, function (t) {
return t.type
})))
}
}
console.log('initializing taurus collection', module.name, module.connection, _.values(types))
if( module.connection ){
this.collections[module.name] = new Taurus(module.connection, _.values(types))
yield this.collections[module.name].bootstrap()
this.addRoute(module.name)
}else{
//TODO 增加 load types的版本
}
},
addRoute: function (name) {
this.routes[`POST /taurus/${name}/query`] = partial(this.routeHandler, name)
},
getCollection : function(name){
return taurusModule.collections[name]
},
routes : {},
routeHandler: function *(collectionName) {
var result
var args = this.request.body
if (this.query.type === 'query') {
result = {}
for (let queryName in args) {
result[queryName] = yield taurusModule.collections[collectionName].pull(args[queryName])
}
} else if (this.query.type === 'push') {
result = yield taurusModule.collections[collectionName].push(args.ast, args.rawNodesToSave, args.trackerRelationMap)
} else if (this.query.type === 'destroy') {
result = yield taurusModule.collections[collectionName].destroy(args.type, args.id)
} else {
this.body = `unknown query type ${this.query.type}`
}
this.body = result
},
}
module.exports = taurusModule | 69e22d5a8587c152a5aa25f44e4014afb172b3fe | [
"JavaScript"
] | 2 | JavaScript | sskyy/zero-taurus | 6e9d5436a21f4b8b3cb163acf29acdac9851ab15 | d7e393eda7f5a72b0fe36db1c760f4fe5dc86633 |
refs/heads/master | <repo_name>FlyingPolaris/Data-Structure<file_sep>/week8/1560.cpp
// 1560.crotrot : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;
char s[100009];
class BST
{
public:
struct node
{
int thedata = 0;
node* l = NULL;
node* r = NULL;
node* p = NULL;
};
node* root = NULL;
void find(int thedata)
{
memset(s, 0, sizeof(s));
int len = 0;
s[len] = '*';
len++;
node* rot = root;
while (rot != NULL)
{
if (rot->thedata == thedata)
{
cout << s << '\n';
return;
}
else if (thedata < rot->thedata)
{
s[len] = 'l';
len++;
rot = rot->l;
}
else
{
s[len] = 'r';
len++;
rot = rot->r;
}
}
cout << "Nothing." << '\n';
}
void insert(int thedata)
{
if (root == NULL)
{
root = new node;
root->thedata = thedata;
return;
}
node* rot = root;
while (rot != NULL)
{
if (rot->thedata == thedata)
return;
if (thedata < rot->thedata)
{
if (rot->l != NULL) rot = rot->l;
else
{
rot->l = new node;
rot->l->p = rot;
rot = rot->l;
break;
}
}
else
{
if (rot->r != NULL) rot = rot->r;
else
{
rot->r = new node;
rot->r->p = rot;
rot = rot->r;
break;
}
}
}
rot->thedata = thedata;
}
void erase(int thedata)
{
node* rot = root;
while (rot != NULL)
{
if (rot->thedata == thedata)
{
if (rot->l == NULL && rot->r == NULL)
{
if (rot == root) root = NULL;
else if (rot->p->l == rot) rot->p->l = NULL;
else rot->p->r = NULL;
delete rot;
}
else if (rot->r == NULL)
{
if (rot == root)
{
root = rot->l;
rot->l->p = NULL;
}
else if (rot->p->l == rot)
{
rot->p->l = rot->l;
rot->l->p = rot->p;
}
else
{
rot->p->r = rot->l;
rot->l->p = rot->p;
}
delete rot;
}
else if (rot->r)
{
node* q = rot->r;
while (q->l != NULL) q = q->l;
rot->thedata = q->thedata;
if (q->p->l == q) q->p->l = q->r;
else q->p->r = q->r;
if (q->r != NULL) q->r->p = q->p;
delete q;
}
return;
}
else if (thedata < rot->thedata) rot = rot->l;
else if (thedata > rot->thedata) rot = rot->r;
}
}
};
BST a;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n;
cin >> n;
for (int i = 0; i < n; ++i)
{
char op;
int x;
cin >> op >> x;
if (op == '+') a.insert(x);
else if (op == '-') a.erase(x);
else if (op == '*') a.find(x);
}
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week5/1214.cpp
// 1214.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
struct treenode
{
int leftchild;
int rightbro;
int id;
};
treenode tree[100005];
bool isnotroot[100005];
void traverse1(int t)
{
if (!t) return;
cout << tree[t].id << ' ';
t = tree[t].leftchild;
while (t)
{
traverse1(t);
t = tree[t].rightbro;
}
}
void traverse2(int t)
{
if (!t) return;
int tmp = tree[t].leftchild;
while (tmp)
{
traverse2(tmp);
tmp = tree[tmp].rightbro;
}
cout << tree[t].id << ' ';
}
void traverse3(int t)
{
int queue[100005] = { 0 };
int head = 0, tail = -1;
queue[++tail] = t;
while (head <= tail)
{
if(tree[queue[head]].leftchild) queue[++tail] = tree[queue[head]].leftchild;
while (tree[queue[tail]].rightbro)
{
tail++;
queue[tail] = tree[queue[tail - 1]].rightbro;
}
cout << tree[queue[head++]].id << ' ';
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int N;
cin >> N;
for (int i = 1;i <= N;++i)
{
int x1, x2, x3;
cin >> x1 >> x2 >> x3;
tree[i].leftchild = x1;
tree[i].rightbro = x2;
tree[i].id = x3;
isnotroot[x1] = isnotroot[x2] = true;
}
int root = 0;
for (int i = 1;i <= N;++i)
{
if (!isnotroot[i])
{
root = i;
break;
}
}
traverse1(root);
cout << '\n';
traverse2(root);
cout << '\n';
traverse3(root);
cout << '\n';
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week1/1359.cpp
// 1359.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
int main()
{
int flag = 0;
int num;
int sum = 0;
char ch;
while ((ch = cin.get())!='\n')
{
flag++;
if (ch == ' ') num = 0;
else if (ch >= 'A' && ch <= 'Z') num = ch - 'A' + 1;
else if (ch >= 'a' && ch <= 'z') num = ch - 'a' + 27;
sum += num * flag;
}
cout << sum;
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week2/1412.cpp
// 1412.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>
#include <cmath>
#include <cstdio>
using namespace std;
void mymemset(int arr[], int t, int size)
{
for (int i = 0;i < size;i++) arr[i] = t;
}
class bignum
{
private:
int len;
int num[1005];
public:
bignum()
{
mymemset(num, 0, 1000);
len = 0;
}
bignum(const bignum& r1)
{
mymemset(num, 0, 1000);
len = r1.len;
for (int i = 0;i < len;++i) num[i] = r1.num[i];
}
bignum(const char* s)
{
mymemset(num, 0, 1000);
len = strlen(s);
for (int i = len - 1;i >= 0;--i)
{
num[len - i - 1] = s[i] - '0';
if (i == 0) break;
}
}
bool operator<(const bignum& r1)
{
if (len != r1.len) return (len < r1.len);
else
{
for (int i = len - 1;i >= 0;--i)
{
if (num[i] < r1.num[i]) return (num[i] < r1.num[i]);
if (i == 0) break;
}
return false;
}
}
bool zero()
{
if (len == 0 && num[0] == 0) return true;
else return false;
}
bool odd()
{
if (num[0] % 2) return true;
else return false;
}
bignum& operator=(const bignum& r1)
{
len = r1.len;
mymemset(num, 0, 1000);
for (int i = 0;i < len;++i) num[i] = r1.num[i];
return *this;
}
bignum& operator-(const bignum& r1);
bignum& div2();
bignum& mult2();
void printin2();
};
bignum& bignum::operator-(const bignum& r1)
{
bignum s;
s.len = len;
for (int i = 0;i < len;i++)
{
s.num[i] += num[i] - r1.num[i];
if (s.num[i] < 0)
{
s.num[i] += 10;
s.num[i + 1]--;
}
}
while (true)
{
if (s.len == 0) break;
if (s.num[s.len - 1] != 0) break;
s.len--;
}
return s;
}
bignum& bignum::div2()
{
bignum s;
s.len = len;
for (int i = len - 1;i >= 0;--i)
{
s.num[i] = num[i]/2;
if (i != 0) num[i - 1] += (num[i] % 2) * 10;
}
while (true)
{
if (s.len == 0) break;
if (s.num[s.len - 1] != 0) break;
s.len--;
}
return s;
}
bignum& bignum::mult2()
{
bignum s;
s.len = len + 1;
int getin = 0;
for (int i = 0;i < len;i++)
{
s.num[i] = ( num[i] * 2 )+ getin;
getin = s.num[i] / 10;
if (getin) s.num[i] -= 10;
}
if (getin) s.num[s.len - 1] = 1;
else s.len--;
return s;
}
void bignum::printin2()
{
int len2 = 0;
bignum p = *this;
while (!p.zero())
{
p = p.div2();
len2++;
}
int* arr;
arr = new int[len2];
for(int i=0;i<len2;i++)
{
if (odd())
{
num[0] -= 1;
arr[len2 - i - 1] = 1;
*this = div2();
}
else
{
arr[len2 - i - 1] = 0;
*this = div2();
}
}
for (int i = 0;i < len2;i++) printf("%d",arr[i]);
delete[]arr;
return;
}
char a[1005], b[1005];
int main()
{
int n = 0;
cin.getline(a, 501);
cin.getline(b, 501);
bignum num1 = a, num2 = b;
if (num1 < num2)
{
bignum temp = num2;
num2 = num1;
num1 = temp;
}
while (!num2.zero())
{
if (num1.odd() && num2.odd()) num1 = num1 - num2;
else if (num1.odd() && !num2.odd()) num2 = num2.div2();
else if (!num1.odd() && num2.odd()) num1 = num1.div2();
else
{
num1 = num1.div2();
num2 = num2.div2();
n++;
}
if (num1 < num2)
{
bignum temp = num2;
num2 = num1;
num1 = temp;
}
}
for (int i = 0;i < n;i++)
{
num1 = num1.mult2();
}
num1.printin2();
//return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week3/4165.cpp
// 4165.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int N, * A, * B,* num;
cin >> N;
A = new int[N];
B = new int[N];
num = new int[N];
for (int i = 0;i < N;++i) cin >> A[i];
for (int i = 0;i < N;++i) cin >> B[i];
for (int i = 0;i < N;++i) num[i] = A[i] - B[i];
long long sum = 0;
//if (N == 1)
//{
// cout << num[0];
// return 0;
//}
for (int i = 0;i < N;i++)
{
if (num[i] > 0)
{
sum += num[i];
while (num[i + 1] > 0 && i < N - 1)
{
sum += (num[i + 1] > num[i] ? num[i + 1] - num[i] : 0);
i++;
}
}
else if (num[i] < 0)
{
sum -= num[i];
while (num[i + 1] < 0 && i < N - 1)
{
sum += (num[i + 1] < num[i] ? num[i] - num[i + 1] : 0);
i++;
}
}
}
cout << sum;
delete[]A;
delete[]B;
delete[]num;
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week8/4097.cpp
// 4097.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <cmath>
using namespace std;
const int MAXSIZE = 1000;
int n, m;
class node
{
public:
node* prev = NULL;
node* next = NULL;
int thedata[MAXSIZE];
int len = 0;
node(node* p = NULL, node* q = NULL) : prev(p), next(q) {}
void split(int pos)
{
if (pos >= len || pos < 0) return;
node* b = new node(this, next);
if (next != NULL) next->prev = b;
next = b;
b->len = len - pos;
for (int i = 0; i < len - pos; ++i)
b->thedata[i] = thedata[i + pos];
len = pos;
}
bool merge()
{
node* b = next;
if (b == NULL) return false;
if (len + b->len > MAXSIZE) return false;
next = b->next;
if (next != NULL) next->prev = this;
for (int i = 0; i < b->len; ++i)
thedata[len++] = b->thedata[i];
delete b;
return true;
}
void delNext()
{
node* b = next;
if (b == NULL) return;
next = b->next;
if (next != NULL)
next->prev = this;
delete b;
}
};
ostream& operator <<(ostream& os, const node& b)
{
for (int i = 0; i < b.len; ++i)
os << b.thedata[i] << ' ';
return os;
}
node* head = new node();
void insert(int x, int y)
{
node* p = head->next;
while (p && x > p->len)
{
x -= p->len;
p = p->next;
}
p->split(x);
p->thedata[p->len++] = y;
}
void remove(int x)
{
node* p = head->next;
while (p && x > p->len)
{
x -= p->len;
p = p->next;
}
p->split(x);
--p->len;
}
void update()
{
node* p = head->next;
while (p)
{
p->merge();
p = p->next;
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> m;
node* p = head->next = new node();
for (int i = 1; i <= n; ++i)
{
int t;
cin >> t;
p->thedata[p->len] = t;
++p->len;
if (p->len == MAXSIZE)
{
p->next = new node();
p = p->next;
}
}
while (m--)
{
int op;
cin >> op;
if (op == 1)
{
int a, b;
cin >> a >> b;
insert(a, b);
}
else
{
int x;
cin >> x;
remove(x);
}
update();
}
p = head->next;
while (p != NULL)
{
cout << *p;
p = p->next;
}
cout << endl;
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week4/4151.cpp
// 4151.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <cstdio>
using namespace std;
int a[1000005], b[1000005];
int main()
{
int t;
ios::sync_with_stdio(false);
//scanf("%d", &t);
cin >> t;
while (t--)
{
int n;
//scanf("%d", &n);
cin >> n;
int top = 0;
int now = 0;
for (int i = 0;i < n;++i) //scanf("%d", &a[i]);
cin >> a[i];
for (int i = 1;i <= n;i++)
{
b[top] = i;
++top;
while (a[now] == b[top - 1] && now < n && top > 0)
{
++now;
--top;
}
}
if (!top) //printf("Yes\n");
cout << "Yes" << endl;
else //printf("No\n");
cout << "No" << endl;
}
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week2/4009.cpp
// 4009.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include <cmath>
#include <cstring>
using namespace std;
int main()
{
char encryption[105], open[105];
scanf("%s", open);
scanf("%s", encryption);
int len = strlen(open);
int k[20];
int flag = 0;
for (int i = 2;i < len;++i)
{
if (len % i == 0)
{
k[flag] = len / i;
flag++;
}
}
for (int i = 0;i < flag;i++)
{
/*cout << k[i] << endl;*/
}
bool solution = false;
/*cout << len << endl;*/
for (int i = 0;i < flag;i++)
{
/*cout << i << ' ' << k[i] << endl;
cout << endl;*/
int div = len / k[i];
char str[105];
for (int j = 0;j < len;j++)
{
int p, q;
p = j / k[i];
q = j % k[i];
/* cout << p << ' ' << q << ' ' << div * q + p << endl;*/
str[div * q + p] = open[j];
}
str[len] = '\0';
/* cout << k[i] << ' ' << div << endl;*/
if (!strcmp(encryption, str))
{
cout << k[i];
solution = true;
break;
}
/*cout << endl;*/
}
if (!solution) cout << "No Solution";
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week8/4309.cpp
// 4309.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <cmath>
using namespace std;
int dp[200001][19];
int num[200001];
int n, m;
int log2(int a)
{
return ((int)(log((double)a) / log(2.0)));
}
int maxnum(int a, int b)
{
return (a < b) ? b : a;
}
void RMQ()
{
for (int i = 1;i <= n;++i) dp[i][0] = num[i];
int k = log2(n);
for (int j = 1;j <= k;++j)
{
for (int i = 1;i <= n;++i)
{
dp[i][j] = maxnum(dp[i][j - 1], dp[i + (1 << (j - 1))][j - 1]);
}
}
}
int quary(int l, int r)
{
int k = log2(r - l + 1);
return maxnum(dp[l][k], dp[r - (1 << k) + 1][k]);
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
for (int i = 1;i <= n;++i) cin >> num[i];
RMQ();
cin >> m;
int x, y;
for (int i = 0;i < m;++i)
{
cin >> x >> y;
cout << quary(x, y);
if (i < m - 1) cout << '\n';
}
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week8/4308.cpp
// 4308.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
const int MAXDEPTH = 18;
int n, m, num = 0, len = 0;
int f[100001][19], depth[100001];
int head[100001], nex[100001], point[100001], dfs_[100001];
void swp(int& a, int& b)
{
int tmp = b;
b = a;
a = tmp;
}
void add(int u, int v)
{
num++;
point[num] = v;
nex[num] = head[u];
head[u] = num;
}
void dfs(int p, int father)
{
dfs_[p] = ++len;
depth[p] = depth[father] + 1;
f[p][0] = father;
for (int i = 1; i <= MAXDEPTH; i++)
f[p][i] = f[f[p][i - 1]][i - 1];
for (int i = head[p]; i != 0; i = nex[i])
dfs(point[i], p);
}
int LCA(int x, int y)
{
if (depth[x] > depth[y]) swp(x, y);
if (x == y) return x;
for (int i = MAXDEPTH; i >= 0; i--)
if (depth[f[y][i]] >= depth[x]) y = f[y][i];
if (x == y) return x;
for (int i = MAXDEPTH; i >= 0; i--)
if (f[x][i] != f[y][i])
{
x = f[x][i];
y = f[y][i];
}
return f[x][0];
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> m;
for (int i = 2;i <= n;++i)
{
int x;
cin >> x;
add(x, i);
}
dfs(1, 1);
int max, min, maxdfs, mindfs;
while (m--)
{
int k;
cin >> k;
int x;
cin >> x;
max = min = x;
maxdfs = mindfs = dfs_[x];
for (int i = 1;i < k;++i)
{
cin >> x;
if (dfs_[x] > maxdfs)
{
maxdfs = dfs_[x];
max = x;
}
if (dfs_[x] < mindfs)
{
mindfs = dfs_[x];
min = x;
}
}
cout << LCA(min, max) << '\n';
}
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week3/1329.cpp
// 1329.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <cstring>
//#include <cmath>
using namespace std;
int pow2(int a)
{
if (a == 0) return 1;
else
{
int temp = 1;
for (int i = 0;i < a - 1;i++)
{
temp *= 2;
}
return temp;
}
}
int main()
{
int t;
cin >> t;
cin.get();
for (int p = 0;p < t;p++)
{
int m, n;
cin.get();
cin >> n >> m;
int* peo1, * peo2;
peo1 = new int[m];
peo2 = new int[m];
char x = 0;
for (int i = 0;i < m;i++)
{
peo1[i] = peo2[i] = 0;
x = 0;
int temp;
while (x != '\n')
{
cin >> temp;
if (temp > 0) peo1[i] += pow2(temp);
else peo2[i] += pow2(-temp);
x = cin.get();
}
}
//for (int i = 0;i < m;i++)
//{
// cout << "want" << ' ' << peo1[i] << ' ' << "diswant" << ' ' << peo2[i] << endl;
//}
bool flag = true;
for (int i = 1;i <= pow2(n + 1) - 1;i++)
{
flag = true;
for (int j = 0;j < m;j++)
{
if ((i & peo1[j]) == 0 && (~i & peo2[j]) == 0) flag = false;
}
//cout << i << ' ' << flag;
if (flag)
{
cout << "Bingo!" << endl; break;
}
}
if (!flag) cout << "Sigh..." << endl;
}
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/test20200604/test3.cpp
// test3.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
using namespace std;
long long a[200005], b[200005];
long long n;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
for (long long i = 1;i <= n;++i) cin >> a[i];
for (long long i = 1;i <= n;++i) cin >> b[i];
long long ans = a[1] + b[1];
for(long long i=1;i<=n;++i)
for (long long j = 1;j <= n;++j)
{
if (!(i == 1 && j == 1))
{
ans = ans ^ (a[i] + b[j]);
}
}
cout << ans;
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week4/4053.cpp
// 4053.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
int n;
int prime[] = { 2,3,5,7,11,13,17,19,23,29,31 };
int num[22];
bool mark[22];
bool isprime(int n)
{
for (int i = 0;i < 11;++i)
{
if (n == prime[i]) return true;
}
return false;
}
void dfs(int step)
{
if (step == n)
{
if (isprime(num[1] + num[n]))
{
for (int i = 1;i <= n;++i)
{
cout << num[i] << ' ';
}
cout << '\n';
}
return;
}
else
{
for (int i = 2;i <= n;++i)
{
if (mark[i] == true) continue;
num[step + 1] = i;
mark[i] = true;
if (isprime(num[step + 1] + num[step])) dfs(step + 1);
mark[i] = false;
}
}
}
int main()
{
ios::sync_with_stdio(false);
cout.tie(0);
cin.tie(0);
cin >> n;
for (int i = 1;i <= n;++i)
mark[i] = false;
num[1] = mark[1] = 1;
if (n > 1 && n % 2)
{
cout << "None";
return 0;
}
dfs(1);
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week1/1550.cpp
// 1550.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
int main()
{
int n, x, i = 0,water = 0;
cin >> n;
int height[1005];
char ch;
for (int j = 0;j < n;j++)
{
cin >> ch >> height[j];
}
int max = height[0];
for (int j = 0;j < n;j++)
{
if (height[j] > max) max = height[j];
}
for (int ruler = max;ruler > 0;ruler--)
{
int left = 0, right = n - 1;
while (height[left] < ruler)
{
left++;
if (left > n - 1) break;
}
while (height[right] < ruler)
{
right--;
if (right < 0) break;
}
if (left > n - 1 || right < 0 || left == right) continue;
else water += right - left - 1;
for (int j = left + 1;j < right;j++)
{
if (height[j] >= ruler) water--;
}
}
cout << water;
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week2/4025.cpp
// 4025.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
void QuickSort(long long arr[], long long low, long long high);
int main()
{
long long M, N;
cin >> M >> N;
long long* arr;
arr = new long long[M * N];
for (long long i = 0;i < M * N;i++)
{
cin >> arr[i];
}
QuickSort(arr, 0, M * N - 1);
long long water;
cin >> water;
long long num = 0;
double level = arr[0];
while (water > 0)
{
if (num + 1 >= M * N)
{
level += (double)water / (double)(num + 1);
water = 0;
}
else if (water - (arr[num + 1] - arr[num]) * (num + 1) > 0)
{
water -= (arr[num + 1] - arr[num]) * (num + 1);
level += arr[num + 1] - arr[num];
num++;
}
else
{
level += (double)water /(double) (num + 1);
water = 0;
}
}
printf("%.2f", level);
cout << endl;
printf("%.2f", (double)(num + 1) / (double)(M * N) * 100);
delete[] arr;
return 0;
}
void QuickSort(long long arr[], long long low, long long high)
{
long long i, j, temp;
i = low;
j = high;
if (low < high)
{
temp = arr[low];
while (i != j)
{
while (j > i&& arr[j] >= temp)
{
--j;
}
if (i < j)
{
arr[i] = arr[j];
++i;
}
while (i < j && arr[i] < temp)
{
++i;
}
if (i < j)
{
arr[j] = arr[i];
--j;
}
}
arr[i] = temp;
QuickSort(arr, low, i - 1);
QuickSort(arr, i + 1, high);
}
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week7/3020.cpp
// 3020.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
template <class T>
class sheap {
private:
T a[500005];
long long heapsize = 0;
void swap(long long x, long long y)
{
T t = a[x];
a[x] = a[y];
a[y] = t;
}
void up(long long x)
{
while (x != 1)
{
if (a[x] < a[x >> 1])
{
swap(x, x >> 1);
x >>= 1;
}
else break;
}
}
void down()
{
long long i = 2;
while (i <= heapsize)
{
if (i < heapsize && a[i + 1] < a[i])
{
++i;
}
if (a[i] < a[i >> 1])
{
swap(i, i >> 1);
i <<= 1;
}
else break;
}
}
public:
void push(T x)
{
a[++heapsize] = x;
up(heapsize);
}
void pop()
{
swap(1, heapsize);
--heapsize;
down();
}
T top()
{
return a[1];
}
bool empty()
{
return heapsize == 0;
}
long long size()
{
return heapsize;
}
};
long long m, n;
sheap<long long> heap;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> m;
long long tmp;
for (long long i = 0;i < n;++i)
{
cin >> tmp;
heap.push(tmp);
}
tmp = n;
while (tmp > m)
{
tmp -= m;
++tmp;
}
for (int i = tmp;i < m;++i)
{
heap.push(0);
}
long long ans = 0;
while (heap.size()!=1)
{
tmp = 0;
for (long long i = 0;i < m;++i)
{
tmp += heap.top();
heap.pop();
}
heap.push(tmp);
ans += tmp;
}
cout << ans;
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week7/1624.cpp
// 1624.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
template <class T>
class sheap {
private:
T a[500005];
long long heapsize = 0;
void swap(long long x, long long y)
{
T t = a[x];
a[x] = a[y];
a[y] = t;
}
void up(long long x)
{
while (x != 1)
{
if (a[x] < a[x >> 1])
{
swap(x, x >> 1);
x >>= 1;
}
else break;
}
}
void down()
{
long long i = 2;
while (i <= heapsize)
{
if (i < heapsize && a[i + 1] < a[i])
{
++i;
}
if (a[i] < a[i >> 1])
{
swap(i, i >> 1);
i <<= 1;
}
else break;
}
}
public:
void push(T x)
{
a[++heapsize] = x;
up(heapsize);
}
void pop()
{
swap(1, heapsize);
--heapsize;
down();
}
T top()
{
return a[1];
}
bool empty()
{
return heapsize == 0;
}
long long size()
{
return heapsize;
}
};
class competitior
{
public:
long long w;
long long fly;
long long ac;
competitior()
{
ac = w = fly = 0;
}
void getdata(long long t,long long q)
{
ac = t;
w = q;
fly = q - t + 1;
}
bool operator<(competitior& a)
{
return fly < a.fly;
}
};
void quicksort(competitior* a, long long low, long long high)
{
long long i, j;
competitior tmp;
i = low, j = high;
if (low < high)
{
tmp = a[low];
while (i != j)
{
while (i < j && a[j].ac <= tmp.ac)
{
--j;
}
if (i < j)
{
a[i] = a[j];
++i;
}
while (i < j && a[i].ac > tmp.ac)
{
++i;
}
if (i < j)
{
a[j] = a[i];
--j;
}
}
a[i] = tmp;
quicksort(a, low, i - 1);
quicksort(a, i + 1, high);
}
}
competitior p[300005];
sheap<competitior> heap;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
long long N;
cin >> N;
long long a, b;
for (long long i = 0;i < N;++i)
{
cin >> a >> b;
p[i].getdata(a, b);
}
quicksort(p, 1, N - 1);
long long num = 0;
for (long long i = 1;i < N;++i)
{
if (p[0].ac < p[i].ac)
{
heap.push(p[i]);
num++;
}
else break;
}
long long bestrank, rank;
bestrank = rank = num + 1;
while (!heap.empty())
{
competitior tmp = heap.top();
heap.pop();
p[0].ac -= tmp.fly;
rank--;
if (p[0].ac < 0) break;
long long num0 = 0;
for (long long i = num + 1;i < N;++i)
{
if (p[0].ac < p[i].ac)
{
heap.push(p[i]);
num++;
num0++;
}
else break;
}
rank += num0;
bestrank = (bestrank < rank) ? bestrank : rank;
}
cout << bestrank;
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week9 & 10/1358.cpp
// 1358.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
int n;
int head[20005], nex[20005], ans[20005], point[20005], childnum[20005];
int tot = 0;
int num = 0;
bool visited[20005];
void addedge(int u,int v)
{
tot++;
point[tot] = v;
nex[tot] = head[u];
head[u] = tot;
}
void QuickSort(int arr[], int low, int high)
{
int i, j, temp;
i = low;
j = high;
if (low < high)
{
temp = arr[low];
while (i != j)
{
while (j > i&& arr[j] >= temp)
{
--j;
}
if (i < j)
{
arr[i] = arr[j];
++i;
}
while (i < j && arr[i] < temp)
{
++i;
}
if (i < j)
{
arr[j] = arr[i];
--j;
}
}
arr[i] = temp;
QuickSort(arr, low, i - 1);
QuickSort(arr, i + 1, high);
}
}
void dfs(int p)
{
bool flag = true;
visited[p] = true;
for (int i = head[p]; i != 0; i = nex[i])
{
if (!visited[point[i]])
{
dfs(point[i]);
if (childnum[point[i]] > n >> 1) flag = false;
childnum[p] += childnum[point[i]];
}
}
if (n - childnum[p] > n >> 1) flag = false;
if (flag) ans[++num] = p;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
int son, par;
for (int i = 1;i < n;++i)
{
cin >> par >> son;
addedge(par, son);
addedge(son, par);
}
for (int i = 1;i <= n;++i) childnum[i] = 1;
dfs(1);
QuickSort(ans, 1, num);
for (int i = 1;i <= num;++i) cout << ans[i] << '\n';
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week2/1201.cpp
// 1201.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
int main()
{
int N;
cin >> N;
for (int t = 0;t < N;t++)
{
long long n;
cin >> n;
int num = n % 100;
long long m = n / 100, p = m;
int len = 0;
while (p > 0)
{
p /= 10;
len++;
}
int* bignum;
bignum = new int[len + 10];
for (int i = 0;i < len;i++)
{
bignum[len - i - 1] = m % 10;
m /= 10;
}
for (int i = 0;i < len;i++)
{
int temp = bignum[i];
for (int j = 0;j < num;j++)
{
bignum[i] += temp;
if (bignum[i] >= 10) bignum[i] -= 10;
}
}
/*cout << len << endl;*/
//for (int i = 0;i < len;i++) cout << bignum[i]<<endl;
int onesum = 0, tensum = 0;
for (int i = 1;i <= num;i++)
{
onesum += i % 10;
tensum += i / 10;
if (onesum >= 10) onesum -= 10;
if (tensum >= 10) tensum -= 10;
}
if (len == 0) cout << onesum + tensum * 10 << endl;
else
{
bignum[len] = tensum;
bignum[len + 1] = onesum;
bool iszero = true;
for (int i = 0;i < len + 2;i++)
{
if (bignum[i] != 0) iszero = false;
if (!iszero) cout << bignum[i];
}
if (iszero) cout << 0;
cout << endl;
}
}
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week2/1075.cpp
// 1075.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
int main()
{
int* a,n;
cin >> n;
a = new int[n + 5];
a[0] = a[1] = 1;
for (int i = 2;i <= n;i++)
{
a[i] = 0;
a[i] += a[i - 1];
for (int j = 2;j <= i;j++)
{
a[i] += a[j - 2] * a[i - j];
a[i] %= 19301;
}
}
cout << a[n];
delete[]a;
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week7/4095.cpp
// 4095.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include "iostream"
#include "cstdio"
using namespace std;
bool check[100009] = { 0 };
int main() {
int N, M;
cin >> N >> M;
auto cnt = N, pos = 0;
for (int left = 0, right = cnt; cnt > 1; --cnt) {
left = cnt - right;
//计算最后一步的位移
auto step = M % (2 * cnt - 2);
if (step == 0)
step = cnt * 2 - 2;
if (step <= right) {
//移动
for (int i = 0; i < step; )
if (!check[++pos])
++i;
right -= step;
}
else if (step < right * 2) {
//移动
for (int i = 0; i < right * 2 - step;)
if (!check[++pos])
++i;
right = step - right;
}
else if (step < right * 2 + left - 1) {
//移动
for (int i = 0; i < step - right * 2 + 1;)
if (!check[--pos])
++i;
right = step - right;
}
else {
//移动
for (int i = 0; i < cnt * 2 - 1 - step;)
if (!check[--pos])
++i;
right += cnt * 2 - 2 - step;
}
check[pos] = true;
}
printf("%d", pos);
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/test20200604/test1.cpp
// test1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
double a, b, c, d, e;
cin >> a >> b >> c >> d >> e;
if (e == 2)
{
double ans = a * b / 10000 + 2 * (1 - a * b / 10000);
printf("%.2lf", ans);
}
else
{
double ans = 10000 / (a * b);
printf("%.2lf", ans);
}
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week2/1292.cpp
// 1292.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
int changtime(int len)
{
if (len == 0 || len == 1) return 0;
else if (len == 2) return 1;
else return 2;
}
int changtimes(int len)
{
return len - 1;
}
//int shouldbe[1000001];
int main()
{
int n;
while (cin>>n)
{
int ans1 = 0, ans2 = 0;
int* num;
num = new int[n + 1];
bool* flag;
for (int i = 1;i <= n;++i) scanf("%d", &num[i]);
flag = new bool[n + 1];
for (int i = 1;i <= n;i++) flag[i] = false;
//for (int i = 0;i < n;++i) shouldbe[num[i]] = i;
for (int i = 1;i <= n;++i)
{
if (!flag[i])
{
int looplen = 1;
flag[i] = true;
int p = num[i];
while (!flag[p])
{
flag[p] = true;
p = num[p];
looplen++;
}
ans1 += changtimes(looplen);
if (changtime(looplen) > ans2) ans2 = changtime(looplen);
}
}
cout << ans1 << endl;
cout << ans2 << endl;
delete[]num;
delete[]flag;
}
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week4/4240.cpp
// 4240.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <cstdio>
using namespace std;
int a[4000005] = { 0 };
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int s, p, tmp, min = 0, max = 0;
cin >> s;
//scanf("%d", &s);
for (int i = 0;i < s;++i)
{
cin >> tmp;
//scanf("%d", &tmp);
if (tmp < min) min = tmp;
if (tmp > max) max = tmp;
a[tmp + 2000000] = 1;
}
cin >> p;
//scanf("%d", &p);
while (p--)
{
int x;
cin >> x;
//scanf("%d", &x);
switch (x)
{
case 1:
cin >> tmp;
if (tmp < min) min = tmp;
if (tmp > max) max = tmp;
a[tmp + 2000000] = 1;
break;
case 0:
cin >> tmp;
//if (tmp < min) min = tmp;
//if (tmp > max) max = tmp;
a[tmp + 2000000] = 0;
break;
}
}
for (int i = min + 2000000;i <= max + 2000000;++i)
{
// while (true)
// {
//cout << i - 2000000;
//cout << " ";
if (a[i])
{
cout << i - 2000000;
cout << " ";
//printf("%d", i - 2000000);
//printf(" ");
//a[i]--;
}
// else break;
//
}
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week9 & 10/4012.cpp
// 4012.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
template <class T>
class sheap {
private:
T a[200005];
long long heapsize = 0;
void swap(long long x, long long y)
{
T t = a[x];
a[x] = a[y];
a[y] = t;
}
void up(long long x)
{
while (x != 1)
{
if (a[x] < a[x >> 1])
{
swap(x, x >> 1);
x >>= 1;
}
else break;
}
}
void down()
{
long long i = 2;
while (i <= heapsize)
{
if (i < heapsize && a[i + 1] < a[i])
{
++i;
}
if (a[i] < a[i >> 1])
{
swap(i, i >> 1);
i <<= 1;
}
else break;
}
}
public:
void push(T x)
{
a[++heapsize] = x;
up(heapsize);
}
void pop()
{
swap(1, heapsize);
--heapsize;
down();
}
T top()
{
return a[1];
}
bool empty()
{
return heapsize == 0;
}
long long size()
{
return heapsize;
}
};
int main()
{
sheap<int> fruit;
int ans = 0;
int n;
cin >> n;
int x;
for (int i = 0;i < n;++i)
{
cin >> x;
fruit.push(x);
}
int a, b;
for (int i = 1;i < n;++i)
{
a = fruit.top();
fruit.pop();
b = fruit.top();
fruit.pop();
ans += a + b;
fruit.push(a + b);
}
cout << ans;
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week7/2111.cpp
// 2111.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
class bstree
{
private:
struct node
{
long long num;
node* l;
node* r;
node(long long x = 0, node* a = NULL, node* b = NULL)
{
num = x;
l = a;
r = b;
}
};
public:
node* root = NULL;
long long size = 0;
void insert(long long x, node*& p)
{
if (p == NULL)
{
p = new node(x);
size++;
}
else
{
if (x < p->num) insert(x, p->l);
else insert(x, p->r);
}
}
void deletenode(long long x, node*& p)
{
if (p == NULL) return;
if (x < p->num) deletenode(x, p->l);
else if (x > p->num) deletenode(x, p->r);
else if (p->l != NULL && p->r != NULL)
{
node* tmp = p->r;
while (tmp->l != NULL)
{
tmp = tmp->l;
}
p->num = tmp->num;
deletenode(p->num, p->r);
}
else
{
node* tmp = p;
p = (p->l == NULL) ? p->r : p->l;
delete tmp;
size--;
}
if (size == 0) root = NULL;
}
long long findmin(long long x)
{
long long ans = 1e9;
node* p = root;
while (p != NULL)
{
if (x < p->num)
{
ans = ans < p->num - x ? ans : p->num - x;
p = p->l;
}
else if (x > p->num)
{
ans = ans < x - p->num ? ans : x - p->num;
p = p->r;
}
else return 0;
}
return ans;
}
};
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
long long m;
long long op;
long long x;
bstree a;
cin >> m;
while (m--)
{
cin >> op;
if (op == 0)
{
cin >> x;
cout << a.findmin(x) << '\n';
}
else if (op == 1)
{
cin >> x;
a.insert(x, a.root);
}
else if (op == 2)
{
cin >> x;
a.deletenode(x, a.root);
}
}
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week5/4117.cpp
// 4117.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <cstring>
using namespace std;
long long a[100005];
long long node[400005];
long long tag[400005];
void build(long long k,long long l,long long r)
{
if (l == r)
{
node[k] = a[l];
return;
}
long long m = (l + r) >> 1;
build(k << 1, l, m);
build(k << 1 | 1, m + 1, r);
node[k] = node[k << 1] + node[k << 1 | 1];
}
void pushdown(long long k, long long l, long long r, long long m)
{
if (tag[k])
{
tag[k << 1] += tag[k];
tag[k << 1 | 1] += tag[k];
node[k << 1] += tag[k] * (m - l + 1);
node[k << 1 | 1] += tag[k] * (r - m);
tag[k] = 0;
}
}
void changevalue(long long L, long long R, long long value, long long k, long long l, long long r)
{
if (L <= l && R >= r)
{
tag[k] += value;
node[k] += value * (r - l + 1);
return;
}
long long m = (l + r) >> 1;
pushdown(k, l, r, m);
if (L <= m) changevalue(L, R, value, k << 1, l, m);
if (R > m) changevalue(L, R, value, k << 1 | 1, m + 1, r);
node[k] = node[k << 1] + node[k << 1 | 1];
}
long long thesum(long long L, long long R, long long k, long long l, long long r)
{
if (L <= l && R >= r) return node[k];
else
{
long long m = (l + r) >> 1;
pushdown(k, l, r, m);
long long ans = 0;
if (L <= m) ans += thesum(L, R, k << 1, l, m);
if (R > m) ans += thesum(L, R, k << 1 | 1, m + 1, r);
return ans;
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
long long N, Q;
cin >> N >> Q;
memset(a, 0, sizeof(a));
memset(node, 0, sizeof(node));
memset(tag, 0, sizeof(tag));
for (long long i = 1;i <= N;++i)
{
cin >> a[i];
}
build(1, 1, N);
while (Q--)
{
char op;
cin >> op;
long long a, b, c;
if (op == 'Q')
{
cin >> a >> b;
cout<<thesum(a, b, 1, 1, N)<<'\n';
}
if (op == 'C')
{
cin >> a >> b >> c;
changevalue(a, b, c, 1, 1, N);
}
}
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week5/1043.cpp
// 1043.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
struct mytree
{
long long leftchild;
long long rightchild;
};
int N;
mytree binary[1000000];
mytree queue[1000000];
mytree thebinary[1000000];
int tail = 0, head = -1, top = 0;
int numofsons(mytree tmp)
{
if (tmp.leftchild == -1 && tmp.rightchild == -1) return 0;
else if (tmp.leftchild != -1 && tmp.rightchild == -1) return 1;
else if (tmp.leftchild != -1 && tmp.rightchild != -1) return 2;
}
bool check()
{
bool onlyonce = true;
bool flag = true;
int checkbegin = 0;
int nodenum = 1;
queue[++head] = binary[0];
while (true)
{
if (numofsons(queue[tail]) != 2 && onlyonce)
{
checkbegin = tail;
onlyonce = false;
}
if (queue[tail].leftchild != -1)
{
queue[++head] = binary[queue[tail].leftchild];++nodenum;
}
if (queue[tail].rightchild != -1)
{
queue[++head] = binary[queue[tail].rightchild];++nodenum;
}
tail++;
if (nodenum == N) break;
}
checkbegin++;
while (head >= checkbegin)
{
if (numofsons(queue[checkbegin]) != 0) flag = false;
checkbegin++;
}
return flag;
}
int main()
{
cin >> N;
int num = 0;
for (int i = 0;i < 1000000;++i)
{
binary[i].leftchild = binary[i].rightchild = -1;
}
for (int i = 0;i < N - 1;++i)
{
int tmp;
cin >> tmp;
if (binary[tmp].leftchild != -1) binary[tmp].rightchild = ++num;
else binary[tmp].leftchild = ++num;
}
if (check()) cout << "true";
else cout << "false";
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week6/4075.cpp
// 4075.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <cstring>
using namespace std;
char a[1000002], b[100002];
int thenext[100002];
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> a >> b;
int j = -1;
int i = 0;
thenext[0] = -1;
while (i < strlen(b))
{
if (j == -1 || b[i] == b[j])
{
i++;
j++;
thenext[i] = j;
}
else j = thenext[j];
}
int p = 0, q = 0;
while (p < strlen(a) && (q < strlen(b) || q == -1))
{
if (q == -1 || a[p] == b[q])
{
p++;
q++;
}
else q = thenext[q];
}
cout << p - q;
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week8/1375.cpp
// 1375.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
const int MAXDEPTH = 16;
int n, m, root, num;
int f[40001][17], depth[40001];
int head[40001], nex[40001], point[40001];
void swp(int& a, int& b)
{
int tmp = b;
b = a;
a = tmp;
}
void add(int u, int v)
{
num++;
point[num] = v;
nex[num] = head[u];
head[u] = num;
}
void dfs(int p, int father)
{
depth[p] = depth[father] + 1;
f[p][0] = father;
for (int i = 1; i <= MAXDEPTH; i++)
f[p][i] = f[f[p][i - 1]][i - 1];
for (int i = head[p]; i != 0; i = nex[i])
dfs(point[i], p);
}
int LCA(int x, int y)
{
if (depth[x] > depth[y]) swp(x, y);
if (x == y) return x;
for (int i = MAXDEPTH; i >= 0; i--)
if (depth[f[y][i]] >= depth[x]) y = f[y][i];
if (x == y) return x;
for (int i = MAXDEPTH; i >= 0; i--)
if (f[x][i] != f[y][i])
{
x = f[x][i];
y = f[y][i];
}
return f[x][0];
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
for (int i = 1; i <= n; i++)
{
int father, son;
cin >> son >> father;
if (father == -1) {
root = son;
continue;
}
add(father, son);
}
dfs(root, root);
cin >> m;
for (int i = 1; i <= m; i++)
{
int x, y;
cin >> x >> y;
int lca = LCA(x, y);
if (lca == x) cout << 1 << '\n';
else if (lca == y) cout << 2 << '\n';
else cout << 0 << '\n';
}
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week6/1042.cpp
// 1042.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
struct Node
{
int leftson;
int rightbro;
bool isnotroot = false;
};
Node node[12349];
void fronttrav(int root)
{
cout << root << ' ';
int p = node[root].leftson;
while (p != 0)
{
fronttrav(p);
p = node[p].rightbro;
}
}
void backtrav(int root)
{
int p = node[root].leftson;
while (p != 0)
{
backtrav(p);
p = node[p].rightbro;
}
cout << root << ' ';
}
void leveltrav(int root)
{
int stack[12349];
int head;
int tail;
head = tail = 0;
stack[tail] = root;
tail++;
while (head < tail)
{
cout << stack[head] << ' ';
int q = node[stack[head]].leftson;
head++;
while (q != 0)
{
stack[tail] = q;
q = node[q].rightbro;
tail++;
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t;
cin >> t;
int t0 = t;
while (t0--)
{
int a, b, c;
cin >> a >> b >> c;
node[a].leftson = b;
node[a].rightbro = c;
node[b].isnotroot = node[c].isnotroot = true;
}
int root;
for (int i = 1;i <= t;++i)
{
if (node[i].isnotroot == false)
{
root = i;
break;
}
}
fronttrav(root);
cout << endl;
backtrav(root);
cout << endl;
leveltrav(root);
// cout << endl;
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/test20200604/test2.cpp
// test2.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
using namespace std;
int n, a[100005];
bool b[100005];
struct node
{
int num;
node* prev;
node* next;
};
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
int key, val;
for (int i = 0;i <= n - 1;++i)
{
cin >> key >> val;
int pos = key % n;
if (!b[pos])
{
a[pos] = val;
b[pos] = true;
}
else
{
while (b[pos])
{
if (pos != n - 1)
{
pos++;
if (!b[pos])
{
a[pos] = val;
b[pos] = true;
break;
}
}
else if (pos == n - 1)
{
pos = 0;
if (!b[pos])
{
a[pos] = val;
b[pos] = true;
break;
}
}
}
}
}
for (int i = 0;i <= n - 1;++i) cout << a[i] << ' ';
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week4/4117.cpp
// 4117.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
long long num[100005] = { 0 }, sum[100005] = { 0 };
int main()
{
ios::sync_with_stdio(false);
int N, M;
cin >> N >> M;
cin.tie(0);
cout.tie(0);
for (int i = 1;i < N + 1;++i)
{
cin >> num[i];
sum[i] = num[i] + sum[i - 1];
}
while (M--)
{
char op;
cin >> op;
switch (op)
{
case'Q':
int A, B;
cin >> A >> B;
cout << sum[B] - sum[A - 1] << '\n';
break;
case'C':
int a, b, c;
cin >> a >> b >> c;
int tmp = c;
if (a - 1 > N - b)
{
while (a < b)
{
sum[a] += tmp;
tmp += c;
a++;
}
while (a <= N)
{
sum[a] += tmp;
a++;
}
break;
}
else
{
b -= 1;
while (a <= b)
{
sum[b] -= tmp;
tmp += c;
b--;
}
while (b >= 0)
{
sum[b] -= tmp;
b--;
}
break;
}
}
}
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week9 & 10/1056.cpp
// 1056.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
class hheap {
private:
long long a[2000005];
long long heapsize = 0;
void swap(long long x, long long y)
{
long long t = a[x];
a[x] = a[y];
a[y] = t;
}
void up(long long x)
{
while (x != 1)
{
if (a[x] > a[x >> 1])
{
swap(x, x >> 1);
x >>= 1;
}
else break;
}
}
void down()
{
long long i = 2;
while (i <= heapsize)
{
if (i < heapsize && a[i + 1] > a[i])
{
++i;
}
if (a[i] > a[i >> 1])
{
swap(i, i >> 1);
i <<= 1;
}
else break;
}
}
public:
void push(long long x)
{
a[++heapsize] = x;
up(heapsize);
}
void pop()
{
swap(1, heapsize);
--heapsize;
down();
}
long long top()
{
return a[1];
}
bool empty()
{
return heapsize == 0;
}
long long size()
{
return heapsize;
}
};
hheap candy;
hheap emptycandy;
long long head[2000005];
long long findhead(long long num)
{
return head[num] == num ? num : head[num] = findhead(head[num]);
}
long long gettop()
{
while (candy.top() == emptycandy.top() && candy.size() != 0 && emptycandy.size() != 0)
{
candy.pop();
emptycandy.pop();
}
return candy.top();
}
long long box[2000005];
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
long long n, m;
cin >> n >> m;
for (long long i = 1;i <= n;++i)
{
box[i] = 1;
head[i] = i;
candy.push(1);
}
char op;
long long x, y;
while (m--)
{
cin >> op;
if (op == 'C')
{
cin >> x >> y;
long long xhead = findhead(x);
long long yhead = findhead(y);
if (xhead == yhead) continue;
if (!box[xhead] || !box[yhead]) continue;
emptycandy.push(box[xhead]);
emptycandy.push(box[yhead]);
box[xhead] += box[yhead];
box[yhead] = 0;
candy.push(box[xhead]);
head[yhead] = xhead;
}
else if (op == 'Q')
{
cin >> x;
long long t = 0;
if (candy.size() - emptycandy.size() <= x)
{
cout << 0 << '\n';
continue;
}
long long tmp[15];
while (x--)
{
++t;
tmp[t] = gettop();
emptycandy.push(tmp[t]);
}
cout << tmp[t] << '\n';
for (long long i = 1;i <= t;++i)
{
candy.push(tmp[i]);
}
}
else if (op == 'D')
{
cin >> x;
long long xhead = findhead(x);
emptycandy.push(box[xhead]);
box[xhead] = 0;
}
}
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week3/1049.cpp
// 1049.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
struct stop
{
int a[1002];
int top;
};
int main()
{
stop s;
int t, m, n;
int f[1002];
int in, out;
cin >> t;
while (t--)
{
s.top = -1;
bool flag = false;
cin >> n >> m;
for (int i = 0;i < n;++i) cin >> f[i];
in = out = 0;
while (out < n)
{
if (in == f[out])
{
in++;
out++;
goto GOOUT;
}
if (s.top == m)
{
flag = false;
break;
}
s.a[++s.top] = in++;
GOOUT:
while (s.a[s.top] == f[out] && s.top != -1)
{
s.top--;
out++;
}
}
if (s.top == -1) flag = true;
if (flag) cout << "YES" << endl;
else cout << "NO" << endl;
}
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week7/4122.cpp
// 4122.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <cstring>
using namespace std;
const int MOD = 1e6 + 7;
int n, m, l, r;
int a[1002], b[100005];
bool vis[2*MOD],want[2*MOD];
int times[2*MOD];
int gethash(char* a)
{
int len = strlen(a);
long long ans = 0;
for (int i = 0;i < len;++i)
{
ans *= 31;
ans += a[i] - 'a';
ans %= MOD;
}
return ans % MOD;
}
int main()
{
int x1 = 0, x2 = 0;
cin >> n;
char tmp[15];
for (int i = 1;i <= n;++i)
{
cin >> tmp;
a[i] = gethash(tmp);
want[a[i]] = 1;
}
cin >> m;
for (int i = 1;i <= m;++i)
{
cin >> tmp;
b[i] = gethash(tmp);
if (want[b[i]] && !vis[b[i]])
{
vis[b[i]] = 1;
x1++;
}
}
if (x1 == 0)
{
cout << 0 << '\n' << 0;
return 0;
}
cout << x1 << '\n';
l = r = m;
int num = x1;
x2 = m;
memset(times, 0, sizeof(times));
while (1)
{
if (num)
{
if (l == 0) break;
if (vis[b[l]])
{
if (!times[b[l]])
{
num--;
}
times[b[l]]++;
}
l--;
}
else
{
while (!vis[b[r]]) r--;
x2 = (x2 < r - l) ? x2 : r - l;
if (times[b[r]])
{
if (times[b[r]] == 1) num++;
}
times[b[r]]--;
r--;
}
}
cout << x2;
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/deque/deque.hpp
#ifndef SJTU_DEQUE_HPP
#define SJTU_DEQUE_HPP
#include "exceptions.hpp"
#include <cstddef>
namespace sjtu {
template<class T>
class deque {
public:
class const_iterator;
class node
{
friend class iterator;
friend class const_iterator;
friend class deque<T>;
private:
size_t nodesize;
T** thedata;
node* prev, * next;
//const deque<T> thedeque;
public:
size_t nowsize;
node(int size = 1000) :nodesize(size), nowsize(0), thedata(NULL), prev(NULL), next(NULL)
{
thedata = new T * [size];
}
node(const node& othernode) :nodesize(othernode.nodesize), nowsize(othernode.nowsize), thedata(NULL), prev(NULL), next(NULL)
{
thedata = new T * [nodesize];
for (size_t i = 0;i < nowsize;++i)
{
thedata[i] = new T(*(othernode.thedata[i]));
}
}
~node()
{
for (size_t i = 0;i < nowsize;++i)
{
delete thedata[i];
}
delete[] thedata;
}
};
private:
node* head, * tail;
public:
size_t nowlength;
class iterator {
friend class deque<T>;
friend class const_iterator;
private:
int i_p;
const deque<T>* thedeque;
node* thenode;
/**
* TODO add data members
* just add whatever you want.
*/
public:
iterator(const deque<T>* thedeque = NULL, node* thenode = NULL, int i_p = 0) :thedeque(thedeque), thenode(thenode), i_p(i_p) {}
iterator(const iterator& other) :thedeque(other.thedeque), thenode(other.thenode), i_p(other.i_p) {}
/**
* return a new iterator which pointer n-next elements
* even if there are not enough elements, the behaviour is **undefined**.
* as well as operator-
*/
iterator operator+(const int& n) const
{
//TODO
iterator tmp = *this;
if (n == 0) return tmp;
else if (n < 0) return tmp - (-n);
else
{
int distance = n;
while (tmp.thenode->nowsize - tmp.i_p <= distance)
{
if (tmp.thenode->next == tmp.thedeque->tail) break;
distance -= tmp.thenode->nowsize - tmp.i_p;
tmp.i_p = 0;
tmp.thenode = tmp.thenode->next;
}
if (tmp.thenode == tmp.thedeque->tail) throw index_out_of_bound();
tmp.i_p += distance;
return tmp;
}
}
iterator operator-(const int& n) const {
//TODO
iterator tmp = *this;
if (n == 0) return tmp;
else if (n < 0) return tmp + (-n);
else
{
int distance = n;
while (tmp.i_p < distance && tmp.thenode != tmp.thedeque->head)
{
distance -= tmp.i_p + 1;
tmp.thenode = tmp.thenode->prev;
tmp.i_p = tmp.thenode->nowsize - 1;
}
if (tmp.thenode == tmp.thedeque->head && tmp.i_p < distance) throw index_out_of_bound();
tmp.i_p -= distance;
return tmp;
}
}
// return th distance between two iterator,
// if these two iterators points to different vectors, throw invaild_iterator.
int operator-(const iterator& rhs) const {
//TODO
int distance = 0;
if (thedeque != rhs.thedeque) throw invalid_iterator();
if (thenode == rhs.thenode)
{
return i_p - rhs.i_p;
}
else
{
node* p = thenode->next;
distance -= thenode->nowsize - i_p;
while (p != rhs.thenode && p != NULL)
{
distance -= p->nowsize;
p = p->next;
}
if (p != NULL)
{
distance -= rhs.i_p;
return distance;
}
else
{
distance = 0;
node* q = rhs.thenode->next;
distance += rhs.thenode->nowsize - rhs.i_p;
while (q != thenode && q != NULL)
{
distance += q->nowsize;
q = q->next;
}
if (q != NULL)
{
distance += i_p;
return distance;
}
else throw runtime_error();
}
}
}
iterator& operator+=(const int& n) {
//TODO
*this = (*this) + n;
return *this;
}
iterator& operator-=(const int& n) {
//TODO
*this = (*this) - n;
return *this;
}
/**
* TODO iter++
*/
iterator operator++(int)
{
iterator tmp = *this;
if (i_p == thenode->nowsize - 1)
{
i_p = 0;
if (thenode->next == NULL) throw index_out_of_bound();
else thenode = thenode->next;
}
else i_p++;
return tmp;
}
/**
* TODO ++iter
*/
iterator& operator++()
{
(*this)++;
return *this;
}
/**
* TODO iter--
*/
iterator operator--(int)
{
iterator tmp = *this;
if (i_p == 0)
{
if (thenode->prev == NULL) throw index_out_of_bound();
else
{
thenode = thenode->prev;
i_p = thenode->nowsize - 1;
}
}
else i_p--;
return tmp;
}
/**
* TODO --iter
*/
iterator& operator--()
{
(*this)--;
return *this;
}
/**
* TODO *it
*/
T& operator*() const
{
if (i_p < 0 || i_p >= thenode->nowsize) throw index_out_of_bound();
return *(thenode->thedata[i_p]);
}
/**
* TODO it->field
*/
T* operator->() const noexcept
{
return (thenode->thedata[i_p]);
}
/**
* a operator to check whether two iterators are same (pointing to the same memory).
*/
bool operator==(const iterator& rhs) const
{
return((thenode == rhs.thenode && i_p == rhs.i_p) || (thenode->next == NULL && rhs.thenode->next == thenode && rhs.thenode->nowsize == rhs.i_p) || (thenode->next == rhs.thenode && rhs.thenode->next == NULL && i_p == thenode->nowsize));
}
bool operator==(const const_iterator& rhs) const
{
return((thenode == rhs.thenode && i_p == rhs.i_p) || (thenode->next == NULL && rhs.thenode->next == thenode && rhs.thenode->nowsize == rhs.i_p) || (thenode->next == rhs.thenode && rhs.thenode->next == NULL && i_p == thenode->nowsize));
}
/**
* some other operator for iterator.
*/
bool operator!=(const iterator& rhs) const
{
return !(*this == rhs);
}
bool operator!=(const const_iterator& rhs) const
{
return !(*this == rhs);
}
};
class const_iterator {
// it should has similar member method as iterator.
// and it should be able to construct from an iterator.
friend class deque<T>;
friend class iterator;
private:
int i_p;
const deque<T>* thedeque;
node* thenode;
// data members.
public:
const_iterator(const deque<T>* thedeque = NULL, node* thenode = NULL, int i_p = 0) : thedeque(thedeque), thenode(thenode), i_p(i_p)
{
// TODO
}
const_iterator(const const_iterator& other) :thedeque(other.thedeque), thenode(other.thenode), i_p(other.i_p)
{
// TODO
}
const_iterator(const iterator& other) :thedeque(other.thedeque), thenode(other.thenode), i_p(other.i_p)
{
// TODO
}
// And other methods in iterator.
// And other methods in iterator.
// And other methods in iterator.
const_iterator operator+(const int& n) const {
//TODO
const_iterator tmp = *this;
if (n == 0) return tmp;
else if (n < 0) return tmp - (-n);
else
{
int distance = n;
while (tmp.thenode->nowsize - tmp.i_p <= distance)
{
if (tmp.thenode->next == tmp.thedeque->tail) break;
distance -= tmp.thenode->nowsize - tmp.i_p;
tmp.i_p = 0;
tmp.thenode = tmp.thenode->next;
}
if (tmp.thenode == tmp.thedeque->tail) throw index_out_of_bound();
tmp.i_p += distance;
return tmp;
}
}
const_iterator operator-(const int& n) const {
//TODO
const_iterator tmp = *this;
if (n == 0) return tmp;
else if (n < 0) return tmp + (-n);
else
{
int distance = n;
while (tmp.i_p < distance && tmp.thenode != tmp.thedeque->head)
{
distance -= tmp.i_p + 1;
tmp.thenode = tmp.thenode->prev;
tmp.i_p = tmp.thenode->nowsize - 1;
}
if (tmp.thenode == tmp.thedeque->head && tmp.i_p < distance) throw index_out_of_bound();
tmp.i_p -= distance;
return tmp;
}
}
// return th distance between two iterator,
// if these two iterators points to different vectors, throw invaild_iterator.
int operator-(const const_iterator& rhs) const {
//TODO
int distance = 0;
if (thedeque != rhs.thedeque) throw invalid_iterator();
if (thenode == rhs.thenode)
{
return i_p - rhs.i_p;
}
else
{
node* p = thenode->next;
distance -= thenode->nowsize - i_p;
while (p != rhs.thenode && p != NULL)
{
distance -= p->nowsize;
p = p->next;
}
if (p != NULL)
{
distance -= rhs.i_p;
return distance;
}
else
{
distance = 0;
node* q = rhs.thenode->next;
distance += rhs.thenode->nowsize - rhs.i_p;
while (q != thenode && q != NULL)
{
distance += q->nowsize;
q = q->next;
}
if (q != NULL)
{
distance += i_p;
return distance;
}
else throw runtime_error();
}
}
}
const_iterator& operator+=(const int& n) {
//TODO
*this = (*this) + n;
return *this;
}
const_iterator& operator-=(const int& n) {
//TODO
*this = (*this) - n;
return *this;
}
/**
* TODO iter++
*/
const_iterator operator++(int)
{
const_iterator tmp = *this;
if (i_p == thenode->nowsize - 1)
{
i_p = 0;
if (thenode->next == NULL) throw index_out_of_bound();
else thenode = thenode->next;
}
else i_p++;
return tmp;
}
/**
* TODO ++iter
*/
const_iterator& operator++()
{
(*this)++;
return *this;
}
/**
* TODO iter--
*/
const_iterator operator--(int)
{
const_iterator tmp = *this;
if (i_p == 0)
{
if (thenode->prev == NULL) throw index_out_of_bound();
else
{
thenode = thenode->prev;
i_p = thenode->nowsize - 1;
}
}
else i_p--;
return tmp;
}
/**
* TODO --iter
*/
const_iterator& operator--()
{
(*this)--;
return *this;
}
T& operator*() const
{
if (i_p < 0 || i_p >= thenode->nowsize) throw index_out_of_bound();
return *(thenode->thedata[i_p]);
}
/**
* TODO it->field
*/
T* operator->() const noexcept
{
return (thenode->thedata[i_p]);
}
/**
* a operator to check whether two iterators are same (pointing to the same memory).
*/
bool operator==(const iterator& rhs) const
{
return((thenode == rhs.thenode && i_p == rhs.i_p) || (thenode->next == NULL && rhs.thenode->next == thenode && rhs.thenode->nowsize == rhs.i_p) || (thenode->next == rhs.thenode && rhs.thenode->next == NULL && i_p == thenode->nowsize));
}
bool operator==(const const_iterator& rhs) const
{
return((thenode == rhs.thenode && i_p == rhs.i_p) || (thenode->next == NULL && rhs.thenode->next == thenode && rhs.thenode->nowsize == rhs.i_p) || (thenode->next == rhs.thenode && rhs.thenode->next == NULL && i_p == thenode->nowsize));
}
/**
* some other operator for iterator.
*/
bool operator!=(const iterator& rhs) const
{
return !(*this == rhs);
}
bool operator!=(const const_iterator& rhs) const
{
return !(*this == rhs);
}
};
/**
* TODO Constructors
*/
deque() :nodesize(1000), head(NULL), tail(NULL), nowlength(0)
{
head = new node(1000);
tail = new node(1);
head->next = tail;
tail->prev = head;
}
deque(const deque& other) :nodesize(other.nodesize), head(NULL), tail(NULL), nowlength(other.nowlength)
{
head = new node(*other.head);
tail = new node(1);
node* p, * q;
p = head;
q = other.head->next;
while (q != other.tail)
{
p->next = new node(*q);
p->next->prev = p;
p = p->next;
q = q->next;
}
p->next = tail;
tail->prev = p;
}
/**
* TODO Deconstructor
*/
~deque()
{
clear();
delete head;
delete tail;
}
/**
* TODO assignment operator
*/
deque& operator=(const deque& other)
{
if (this == &other) return *this;
else
{
clear();
nowlength = other.nowlength;
delete head;
head = new node(*other.head);
node* p = head;
node* q = other.head->next;
while (q != other.tail)
{
p->next = new node(*q);
p->next->prev = p;
p = p->next;
q = q->next;
}
p->next = tail;
tail->prev = p;
return *this;
}
}
/**
* access specified element with bounds checking
* throw index_out_of_bound if out of bound.
*/
T& at(const size_t& pos)
{
node* p = head;
size_t tmp = pos;
while (p != tail && tmp >= p->nowsize)
{
tmp -= p->nowsize;
p = p->next;
}
if (p == tail || tmp < 0) throw index_out_of_bound();
return *(p->thedata[tmp]);
}
const T& at(const size_t& pos) const
{
node* p = head;
size_t tmp = pos;
while (p != tail && tmp >= p->nowsize)
{
tmp -= p->nowsize;
p = p->next;
}
if (p == tail || tmp < 0) throw index_out_of_bound();
return *(p->thedata[tmp]);
}
T& operator[](const size_t& pos)
{
return at(pos);
}
const T& operator[](const size_t& pos) const
{
return at(pos);
}
/**
* access the first element
* throw container_is_empty when the container is empty.
*/
const T& front() const
{
if (nowlength == 0) throw container_is_empty();
else return *(head->thedata[0]);
}
/**
* access the last element
* throw container_is_empty when the container is empty.
*/
const T& back() const
{
if (nowlength == 0) throw container_is_empty();
else return *(tail->prev->thedata[tail->prev->nowsize - 1]);
}
/**
* returns an iterator to the beginning.
*/
iterator begin()
{
if (nowlength == 0) return end();
else
{
iterator tmp(this, head, 0);
return tmp;
}
}
const_iterator cbegin() const
{
if (nowlength == 0) return cend();
else
{
const_iterator tmp(this, head, 0);
return tmp;
}
}
/**
* returns an iterator to the end.
*/
iterator end()
{
iterator tmp(this, tail, 0);
return tmp;
}
const_iterator cend() const
{
const_iterator tmp(this, tail, 0);
return tmp;
}
/**
* checks whether the container is empty.
*/
bool empty() const
{
return nowlength == 0;
}
/**
* returns the number of elements
*/
size_t size() const
{
return nowlength;
}
/**
* clears the contents
*/
void clear()
{
node* p, * q;
p = head->next;
delete head;
head = new node(1000);
head->next = tail;
tail->prev = head;
while (p != tail)
{
q = p->next;
delete p;
p = q;
}
nowlength = 0;
}
/**
* inserts elements at the specified locat on in the container.
* inserts value before pos
* returns an iterator pointing to the inserted value
* throw if the iterator is invalid or it point to a wrong place.
*/
iterator insert(iterator pos, const T& value)
{
if (this != pos.thedeque) throw invalid_iterator();
if (pos.i_p == 0 && pos.thenode != pos.thedeque->head)
{
pos.thenode = pos.thenode->prev;
pos.i_p = pos.thenode->nowsize;
}
nowlength++;
changenode(pos.thenode);
while (pos.i_p > pos.thenode->nowsize&& pos.thenode != pos.thedeque->tail)
{
pos.i_p -= pos.thenode->nowsize;
pos.thenode = pos.thenode->next;
}
if (pos.thenode == pos.thedeque->tail) throw index_out_of_bound();
if (pos.i_p == pos.thenode->nowsize)
{
pos.thenode->thedata[pos.i_p] = new T(value);
pos.thenode->nowsize++;
return pos;
}
for (int i = pos.thenode->nowsize;i > pos.i_p;--i)
{
pos.thenode->thedata[i] = pos.thenode->thedata[i - 1];
}
pos.thenode->thedata[pos.i_p] = new T(value);
pos.thenode->nowsize++;
return pos;
}
/**
* removes specified element at pos.
* removes the element at pos.
* returns an iterator pointing to the following element, if pos pointing to the last element, end() will be returned.
* throw if the container is empty, the iterator is invalid or it points to a wrong place.
*/
iterator erase(iterator pos)
{
if (this != pos.thedeque) throw invalid_iterator();
if (pos.thenode == tail) throw invalid_iterator();
nowlength--;
//if (pos.i_p == 0 && pos.thenode != pos.thedeque->head)
//{
// pos.thenode = pos.thenode->prev;
// pos.i_p = pos.thenode->nowsize;
//}
while (pos.i_p < 0) {
pos.thenode = pos.thenode->prev;
pos.i_p += pos.thenode->nowsize;
}
if (pos.i_p == pos.thenode->nowsize) {
pos.i_p = 0;
pos.thenode = pos.thenode->next;
}
changenode(pos.thenode);
while (pos.i_p >= pos.thenode->nowsize && pos.thenode != pos.thedeque->tail)
{
pos.i_p -= pos.thenode->nowsize;
pos.thenode = pos.thenode->next;
}
if (pos.thenode == pos.thedeque->tail) throw index_out_of_bound();
if (pos.i_p == pos.thenode->nowsize - 1)
{
delete pos.thenode->thedata[pos.thenode->nowsize - 1];
pos.thenode->nowsize--;
if (pos.i_p == pos.thenode->nowsize)
{
pos.i_p = 0;
pos.thenode = pos.thenode->next;
}
return pos;
}
delete pos.thenode->thedata[pos.i_p];
for (int i = pos.i_p;i < pos.thenode->nowsize - 1;++i)
{
pos.thenode->thedata[i] = pos.thenode->thedata[i + 1];
}
pos.thenode->nowsize--;
if (pos.i_p == pos.thenode->nowsize)
{
pos.i_p = 0;
pos.thenode = pos.thenode->next;
}
return pos;
}
/**
* adds an element to the end
*/
void push_back(const T& value)
{
insert(iterator(this, tail->prev, tail->prev->nowsize), value);
}
/**
* removes the last element
* throw when the container is empty.
*/
void pop_back()
{
erase(iterator(this, tail->prev, tail->prev->nowsize - 1));
}
/**
* inserts an element to the beginning.
*/
void push_front(const T& value)
{
insert(begin(), value);
}
/**
* removes the first element.
* throw when the container is empty.
*/
void pop_front()
{
erase(begin());
}
private:
size_t nodesize = 1000;
void changenode(node*& thenode)
{
if (thenode == tail) return;
// else if (thenode->nowsize < nodesize / 2)
merge(thenode);
// else if (thenode->nowsize >= nodesize)
split(thenode);
}
void merge(node*& thenode)
{
if (thenode == tail) return;
if (thenode->nowsize < nodesize / 2)
{
while (thenode->nowsize + thenode->next->nowsize <= nodesize)
{
if (thenode->next->next == NULL) break;
while (thenode->nowsize == 0)
{
if (thenode->next->next == NULL) break;
node* tmp = thenode;
thenode = tmp->next;
if (tmp == head) head = thenode;
delete tmp;
}
node* tmp = thenode->next;
if (tmp == tail)
break;
for (size_t i = thenode->nowsize;i < thenode->nowsize + thenode->next->nowsize;++i)
{
thenode->thedata[i] = thenode->next->thedata[i - thenode->nowsize];
}
thenode->nowsize += thenode->next->nowsize;
tmp->nowsize = 0;
thenode->next = thenode->next->next;
thenode->next->prev = thenode;
delete tmp;
}
}
}
void split(node*& thenode)
{
if (thenode == tail) return;
if (thenode->nowsize >= nodesize)
{
node* newnode = new node(thenode->nodesize);
newnode->prev = thenode;
newnode->next = thenode->next;
thenode->next->prev = newnode;
thenode->next = newnode;
size_t newsize = thenode->nowsize / 2;
for (size_t i = newsize;i < thenode->nowsize;++i)
{
newnode->thedata[i - newsize] = thenode->thedata[i];
}
newnode->nowsize = thenode->nowsize - newsize;
thenode->nowsize = newsize;
}
}
};
}
#endif
<file_sep>/week8/1371.cpp
// 1371.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
int marks[100005], sum[100005];
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n, m;
cin >> n >> m;
for (int i = 0;i < n;++i)
{
int x;
cin >> x;
marks[x]++;
}
sum[0] = 0;
for (int i = 1;i <= 100004;++i)
{
sum[i] = sum[i - 1] + marks[i];
}
int a, b;
for (int i = 0;i < m;++i)
{
cin >> a >> b;
cout << sum[b] - sum[a - 1] << '\n';
}
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week7/1315.cpp
// 1315.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
struct frac
{
int son;
int mother;
double num;
};
frac num[500000];
int N;
void quicksort(frac a[], int begin, int end)
{
int i, j;
frac tmp;
i = begin;
j = end;
if (begin < end)
{
tmp = a[begin];
while (i != j)
{
while (i < j && tmp.num <= a[j].num) --j;
if (i < j)
{
a[i] = a[j];
++i;
}
while (i < j && tmp.num > a[i].num) ++i;
if (i < j)
{
a[j] = a[i];
--j;
}
}
a[i] = tmp;
quicksort(a, begin, i - 1);
quicksort(a, i + 1, end);
}
}
int gcd(int a, int b)
{
if (!b) return a;
return gcd(b, a % b);
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> N;
num[0].son = 0; num[1].son = 1;
num[0].mother = num[1].mother = 1;
num[0].num = 0; num[1].num = 1;
int p = 2;
for (int i = 2;i <= N;++i)
{
for (int j = 1;j < i;++j)
{
if (gcd(j, i) == 1)
{
num[p].son = j;
num[p].mother = i;
num[p].num = (1.0 * j) / (1.0 * i);
++p;
}
}
}
quicksort(num, 0, p - 1);
for (int i = 0;i < p;++i)
{
cout << num[i].son << '/' << num[i].mother << '\n';
}
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/vector/vector.hpp
#ifndef SJTU_VECTOR_HPP
#define SJTU_VECTOR_HPP
#include "exceptions.hpp"
#include <climits>
#include <cstddef>
namespace sjtu {
/**
* a data container like std::vector
* store data in a successive memory and support random access.
*/
template<typename T>
class vector {
private:
T* thedata;
size_t used_memory;
size_t total_memory;
void doublespace()
{
total_memory *= 2;
T* temp = (T*)malloc(sizeof(T) * total_memory);
memset(temp, 0, total_memory * sizeof(T));
for (size_t i = 0;i < used_memory;++i)
{
temp[i] = thedata[i];
thedata[i].~T();
}
free(thedata);
thedata = temp;
}
public:
/**
* TODO
* a type for actions of the elements of a vector, and you should write
* a class named const_iterator with same interfaces.
*/
/**
* you can see RandomAccessIterator at CppReference for help.
*/
class const_iterator;
class iterator {
friend class vector<T>;
private:
/**
* TODO add data members
* just add whatever you want.
*/
T* i_p;
vector<T>* thevector;
public:
iterator()
{
i_p = NULL;
thevector = NULL;
}
iterator(iterator const& other)
{
thevector = other.thevector;
i_p = other.i_p;
}
iterator(vector<T>* vect, T* x)
{
thevector = vect;
i_p = x;
}
/**
* return a new iterator which pointer n-next elements
* as well as operator-
*/
iterator operator+(const int& n) const {
//TODO
iterator temp(thevector, i_p + n);
return temp;
}
iterator operator-(const int& n) const {
//TODO
iterator temp(thevector, i_p - n);
return temp;
}
// return the distance between two iterators,
// if these two iterators point to different vectors, throw invaild_iterator.
int operator-(const iterator& rhs) const {
size_t distance;
if (thevector != rhs.thevector) throw invalid_iterator();
else distance = ((i_p > rhs.i_p) ? i_p - rhs.i_p : rhs.i_p - i_p);
return distance;
//TODO
}
iterator& operator+=(const int& n) {
//TODO
i_p += n;
return *this;
}
iterator& operator-=(const int& n) {
//TODO
i_p -= n;
return *this;
}
/**
* TODO iter++
*/
iterator operator++(int) {
iterator temp = *this;
i_p++;
return temp;
}
/**
* TODO ++iter
*/
iterator& operator++() {
i_p++;
return *this;
}
/**
* TODO iter--
*/
iterator operator--(int) {
iterator temp = *this;
i_p--;
return temp;
}
/**
* TODO --iter
*/
iterator& operator--() {
i_p--;
return *this;
}
/**
* TODO *it
*/
T& operator*() const { return *i_p; }
/**
* a operator to check whether two iterators are same (pointing to the same memory address).
*/
bool operator==(const iterator& rhs) const {
return i_p == rhs.i_p;
}
bool operator==(const const_iterator& rhs) const {
return i_p == rhs.i_p;
}
/**
* some other operator for iterator.
*/
bool operator!=(const iterator& rhs) const {
return i_p != rhs.i_p;
}
bool operator!=(const const_iterator& rhs) const {
return i_p != rhs.i_p;
}
~iterator() {}
};
/**
* TODO
* has same function as iterator, just for a const object.
*/
class const_iterator {
friend class vector<T>;
private:
/**
* TODO add data members
* just add whatever you want.
*/
T* i_p;
const vector<T>* thevector;
public:
const_iterator()
{
i_p = NULL;
thevector = NULL;
}
const_iterator(iterator const& other)
{
thevector = other.thevector;
i_p = other.i_p;
}
const_iterator(const vector<T>* vect, T* x)
{
thevector = vect;
i_p = x;
}
/**
* return a new iterator which pointer n-next elements
* as well as operator-
*/
const_iterator operator+(const int& n) const {
//TODO
const_iterator temp(thevector, i_p + n);
return temp;
}
const_iterator operator-(const int& n) const {
//TODO
const_iterator temp(thevector, i_p - n);
return temp;
}
// return the distance between two iterators,
// if these two iterators point to different vectors, throw invaild_iterator.
int operator-(const const_iterator& rhs) const {
size_t distance;
if (thevector != rhs.thevector) throw invalid_iterator();
else distance = ((i_p > rhs.i_p) ? i_p - rhs.i_p : rhs.i_p - i_p);
return distance;
//TODO
}
const_iterator& operator+=(const int& n) {
//TODO
i_p += n;
return *this;
}
const_iterator& operator-=(const int& n) {
//TODO
i_p -= n;
return *this;
}
/**
* TODO iter++
*/
const_iterator operator++(int) {
const_iterator temp = *this;
i_p++;
return temp;
}
/**
* TODO ++iter
*/
const_iterator& operator++() {
i_p++;
return *this;
}
/**
* TODO iter--
*/
const_iterator operator--(int) {
const_iterator temp = *this;
i_p--;
return temp;
}
/**
* TODO --iter
*/
const_iterator& operator--() {
i_p--;
return *this;
}
/**
* TODO *it
*/
T& operator*() const { return *i_p; }
/**
* a operator to check whether two iterators are same (pointing to the same memory address).
*/
bool operator==(const iterator& rhs) const {
return i_p == rhs.i_p;
}
bool operator==(const const_iterator& rhs) const {
return i_p == rhs.i_p;
}
/**
* some other operator for iterator.
*/
bool operator!=(const iterator& rhs) const {
return i_p != rhs.i_p;
}
bool operator!=(const const_iterator& rhs) const {
return i_p != rhs.i_p;
}
~const_iterator() {}
};
/**
* TODO Constructs
* Atleast two: default constructor, copy constructor
*/
vector()
{
used_memory = 0;
total_memory = 1;
thedata = (T*)malloc(sizeof(T));
memset(thedata, 0, sizeof(T));
}
vector(const vector& other)
{
thedata = (T*)malloc(sizeof(T) * other.total_memory);
memset(thedata, 0, other.total_memory * sizeof(T));
for (size_t i = 0;i < other.used_memory;++i)
{
thedata[i] = other.thedata[i];
}
total_memory = other.total_memory;
used_memory = other.used_memory;
}
/**
* TODO Destructor
*/
~vector()
{
for (size_t i = 0;i < used_memory;++i)
thedata[i].~T();
used_memory = 0;
total_memory = 1;
free(thedata);
}
/**
* TODO Assignment operator
*/
vector& operator=(const vector& other)
{
if (this == &other) return *this;
for (size_t i = 0;i < used_memory;++i)
{
thedata[i].~T();
}
free(thedata);
total_memory = other.total_memory;
used_memory = other.used_memory;
thedata = (T*)malloc(sizeof(T) * other.total_memory);
memset(thedata, 0, other.total_memory * sizeof(T));
for (size_t i = 0;i < other.used_memory;++i)
{
thedata[i] = other.thedata[i];
}
return *this;
}
/**
* assigns specified element with bounds checking
* throw index_out_of_bound if pos is not in [0, size)
*/
T& at(const size_t& pos) {
if (pos < 0 || pos >= used_memory) throw index_out_of_bound();
return thedata[pos];
}
const T& at(const size_t& pos) const {
if (pos < 0 || pos >= used_memory) throw index_out_of_bound();
return thedata[pos];
}
/**
* assigns specified element with bounds checking
* throw index_out_of_bound if pos is not in [0, size)
* !!! Pay attentions
* In STL this operator does not check the boundary but I want you to do.
*/
T& operator[](const size_t& pos)
{
if (pos < 0 || pos >= used_memory) throw index_out_of_bound();
return thedata[pos];
}
const T& operator[](const size_t& pos) const
{
if (pos < 0 || pos >= used_memory) throw index_out_of_bound();
return thedata[pos];
}
/**
* access the first element.
* throw container_is_empty if size == 0
*/
const T& front() const
{
if (used_memory == 0) throw container_is_empty();
return thedata[0];
}
/**
* access the last element.
* throw container_is_empty if size == 0
*/
const T& back() const
{
if (used_memory == 0) throw container_is_empty();
return thedata[used_memory - 1];
}
/**
* returns an iterator to the beginning.
*/
iterator begin()
{
iterator temp(this, thedata);
return temp;
}
const_iterator cbegin() const
{
const_iterator temp(this, thedata);
return temp;
}
/**
* returns an iterator to the end.
*/
iterator end()
{
iterator temp(this, thedata + used_memory);
return temp;
}
const_iterator cend() const
{
const_iterator temp(this, thedata + used_memory);
return temp;
}
/**
* checks whether the container is empty
*/
bool empty() const
{
if (used_memory == 0) return true;
else return false;
}
/**
* returns the number of elements
*/
size_t size() const { return used_memory; }
/**
* clears the contents
*/
void clear()
{
if (used_memory > 0 || total_memory > 1)
{
for (size_t i = 0;i < used_memory;++i)
thedata[i].~T();
free(thedata);
thedata = (T*)malloc(sizeof(T));
memset(thedata, 0, sizeof(T));
used_memory = 0;
total_memory = 1;
}
}
/**
* inserts value before pos
* returns an iterator pointing to the inserted value.
*/
iterator insert(iterator pos, const T& value)
{
if (used_memory == total_memory)
{
size_t distance = pos.i_p - thedata;
doublespace();
pos.i_p = thedata + distance;
}
T* temp = thedata + used_memory;
while (temp > pos.i_p)
{
*temp = *(temp - 1);
--temp;
}
*pos.i_p = value;
used_memory++;
return pos;
}
/**
* inserts value at index ind.
* after inserting, this->at(ind) == value
* returns an iterator pointing to the inserted value.
* throw index_out_of_bound if ind > size (in this situation ind can be size because after inserting the size will increase 1.)
*/
iterator insert(const size_t& ind, const T& value)
{
iterator iter;
iter.i_p = thedata + ind;
iter.thevector = this;
if (ind > used_memory) throw index_out_of_bound();
if (used_memory == total_memory)
{
doublespace();
}
size_t temp = used_memory;
while (temp > ind)
{
thedata[temp] = thedata[temp - 1];
--temp;
}
thedata[ind] = value;
used_memory++;
return iter;
}
/**
* removes the element at pos.
* return an iterator pointing to the following element.
* If the iterator pos refers the last element, the end() iterator is returned.
*/
iterator erase(iterator pos)
{
T* temp = pos.i_p;
--used_memory;
while (temp < thedata + used_memory)
{
*temp = *(temp + 1);
temp++;
}
return pos;
}
/**
* removes the element with index ind.
* return an iterator pointing to the following element.
* throw index_out_of_bound if ind >= size
*/
iterator erase(const size_t& ind)
{
size_t temp = ind;
--used_memory;
while (temp < used_memory)
{
thedata[temp] = thedata[temp + 1];
temp++;
iterator iter;
iter.i_p = thedata + ind;
iter.thevector = this;
return iter;
}
}
/**
* adds an element to the end.
*/
void push_back(const T& value)
{
if (used_memory == total_memory) doublespace();
thedata[used_memory++] = value;
}
/**
* remove the last element from the end.
* throw container_is_empty if size() == 0
*/
void pop_back()
{
if (used_memory == 0) throw container_is_empty();
else --used_memory;
}
};
}
#endif<file_sep>/week4/1607.cpp
// 1607.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
int peo[2000001];
class group
{
public:
int id;
int* member;
int tail = -1;
int head = 0;
int nowsize = 2;
group* next;
group()
{
member = new int[2];
}
~group()
{
delete[] member;
}
void doublespace()
{
nowsize *= 2;
int* newmember = new int[nowsize];
for (int i = 0;i < tail;++i)
{
newmember[i] = member[i];
}
delete member;
member = newmember;
}
};
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n;
cin >> n;
for (int i = 0;i < n;++i)
cin >> peo[i];
int q;
cin >> q;
group* head=new group;
head->id = -1;
head->next = NULL;
int peoplein = 0;
for (int i = 1;i <= q;++i)
{
int op;
cin >> op;
if (op)
{
if (head->next == NULL) cout << "-1" << '\n';
else
{
group* tmp = head->next;
cout << head->next->member[head->next->head] << '\n';
if (head->next->head < head->next->tail) head->next->head++;
else head->next = head->next->next;
}
}
else
{
peoplein++;
bool flag = false;
group* p = head;
group* q = head->next;
while (q != NULL)
{
if (p->id == peo[peoplein - 1])
{
flag = true;
break;
}
else flag = false;
p = p->next;
q = q->next;
}
if (p->id == peo[peoplein - 1])
{
flag = true;
}
else flag = false;
if (flag)
{
(p->tail)++;
if (p->tail >= p->nowsize - 1) p->doublespace();
p->member[p->tail] = peoplein;
}
else
{
group* newgroup = new group;
newgroup->id = peo[peoplein - 1];
(newgroup->tail)++;
newgroup->member[newgroup->tail] = peoplein;
p->next = newgroup;
newgroup->next = NULL;
}
}
}
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week6/4189.cpp
// 4189.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
struct node
{
int data;
node* next = NULL;
};
node* G[500000];
node* tail[500000];
int city[500000];
int n;
int dfs(int u, int parent)
{
int num = 0, max = 0, sum = 1;
node* p = G[u]->next;
while (true)
{
int v = p->data;
if (v != parent)
{
num = dfs(v, u);
sum += num;
max = (num > max) ? num : max;
}
if (p->next != NULL) p = p->next;
else break;
}
city[u] = (max > n - sum) ? max : n - sum;
return sum;
}
void add(int x,int y)
{
node* tmp1 = new node;
tmp1->data = y;
tail[x]->next = tmp1;
tail[x] = tail[x]->next;
node* tmp2 = new node;
tmp2->data = x;
tail[y]->next = tmp2;
tail[y] = tail[y]->next;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int x, y;
cin >> n;
for (int i = 0;i <= n;++i) tail[i] = new node;
for (int i = 0;i <= n;++i) G[i] = tail[i];
for (int i = 1;i < n;++i)
{
cin >> x >> y;
add(x, y);
}
dfs(1, -1);
for (int i = 1;i <= n;++i)
{
if (2 * city[i] <= n) cout << i << ' ';
}
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week6/1634.cpp
// 1634.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
long long num = 0;
long long now = 0;
long long a[500005], b[500005];
long long n, k;
void deleteroot()
{
b[1] = b[now];
now--;
long long t, s;
t = s = 1;
while (t << 1 <= now)
{
s = t << 1;
if (s != now) num++;
if (s != now && b[s] > b[s + 1]) s++;
num++;
if (b[s] < b[now + 1]) b[t] = b[s];
else break;
t = s;
}
b[t] = b[now + 1];
}
void merge(long long a[], long long l, long long m, long long r)
{
long long i = l, j = m, k = 0;
while (i < m && j <= r)
{
if (a[i] < a[j]) b[k++] = a[i++];
else b[k++] = a[j++];
num++;
}
while (i < m) b[k++] = a[i++];
while (j <= r) b[k++] = a[j++];
for (i = 0, k = l;k <= r;) a[k++] = b[i++];
}
void mergesort(long long a[], long long l, long long r)
{
long long m = (l + r) >> 1;
if (l == r) return;
if ((l - r) % 2)
{
mergesort(a, l, m);
mergesort(a, m + 1, r);
merge(a, l, m + 1, r);
}
else
{
mergesort(a, l, m - 1);
mergesort(a, m, r);
merge(a, l, m, r);
}
}
void aswap(long long& a, long long& b)
{
long long tmp = a;
a = b;
b = tmp;
}
struct node
{
long long id;
node* prev = NULL;
node* next = NULL;
};
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> k;
for (long long i = 1;i <= n;++i) cin >> a[i];
if (k == 1)
{
for (long long i = 1;i <= n;++i)
{
now++;
b[now] = a[i];
long long p = now;
while (p > 1)
{
num++;
if (b[p] < b[p >> 1])
{
aswap(b[p], b[p >> 1]);
p = p >> 1;
}
else break;
}
}
for (long long i = 1;i <= n - 1;++i) deleteroot();
cout << num;
}
else if (k == 2)
{
mergesort(a, 1, n);
cout << num;
}
else if (k == 3)
{
node** list = new node*[n + 2];
for (long long i = 0;i <= n + 1;++i)
{
list[i] = new node;
}
list[0]->id = 0;
list[0]->next = list[1];
list[n + 1]->id = n + 1;
list[n + 1]->prev = list[n];
for (long long i = 1;i <= n;++i)
{
list[i]->id = i;
list[i]->prev = list[i - 1];
list[i]->next = list[i + 1];
}
for (long long i = n;i >= 1;--i)
{
num += list[a[i]]->next->id - list[a[i]]->prev->id - 2;
list[a[i]]->prev->next = list[a[i]]->next;
list[a[i]]->next->prev = list[a[i]]->prev;
delete list[a[i]];
}
cout << num;
}
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week5/4118.cpp
// 4118.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <cstring>
using namespace std;
int m;
char s1[27], s2[27];
long long ans = 1;
long long C(long long m,long long n)
{
if (!m) return 1;
long long tmp1 = 1, tmp2 = 1;
for (int i = 1;i <= m;++i)
{
tmp1 *= i;
}
for (int i = 0;i < m;++i)
{
tmp2 *= n - i;
}
return tmp2 / tmp1;
}
void f(int fleft, int fright, int eleft, int eright)
{
int root = fleft + 1;
int childnum = 0;
while (root <= fright)
{
int len;
for (int i = eleft;i <= eright;++i)
{
if (s2[i] == s1[root])
{
len = i - eleft + 1;
break;
}
}
f(root, root + len - 1, eleft, eleft + len - 1);
childnum++;
root += len;
eleft += len;
}
ans *= C(childnum, m);
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
memset(s1, 0, sizeof(char) * 27);
memset(s2, 0, sizeof(char) * 27);
cin >> m >> s1 >> s2;
f(0, strlen(s1) - 1, 0, strlen(s2) - 1);
cout << ans;
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week9 & 10/1566.cpp
// 1566.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <cstring>
using namespace std;
int n;
int map[30][30];
int MAX = 1e8 + 7;
int prim()
{
int ans = 0;
bool flag[30];
memset(flag, 0, sizeof(flag));
int lowcost[30];
for (int i = 1;i <= n;++i)
{
lowcost[i] = MAX;
}
int min;
int point;
int tmp = 1;
for (int i = 1;i < n;++i)
{
min = MAX;
for (int j = 2;j <= n;++j)
{
if (!flag[j] && lowcost[j] > map[tmp][j])
{
lowcost[j] = map[tmp][j];
}
if (!flag[j] && lowcost[j] < min)
{
min = lowcost[j];
point = j;
}
}
tmp = point;
flag[tmp] = true;
ans += min;
}
return ans;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
char village;
char target;
int t;
int cost;
for (int i = 1;i <= n;++i)
{
for (int j = 1;j <= n;++j)
{
map[i][j] = map[j][i] = MAX;
}
}
for (int i = 1;i < n;++i)
{
cin >> village >> t;
for (int j = 1;j <= t;++j)
{
cin >> target >> cost;
map[village - 'A' + 1][target - 'A' + 1] = map[target - 'A' + 1][village - 'A' + 1] = cost;
}
}
cout << prim() << endl;
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week7/4011.cpp
// 4011.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <cstring>
using namespace std;
class hint
{
private:
long long n[10];
long long len;
long long base;
public:
hint(long long x = 0)
{
for (int i = 0;i < 10;++i) n[i] = 0;
n[0] = x;
len = 1;
base = 1e11;
}
hint& operator=(const hint& rhs)
{
if (this != &rhs)
{
for (long long i = 0;i < 10;++i)
{
n[i] = rhs.n[i];
}
len = rhs.len;
base = rhs.base;
}
return *this;
}
hint operator+(const hint& rhs) const
{
hint ans;
long long in = 0;
for (long long i = 0;i < 10 && (in != 0 || rhs.n[i] != 0 || n[i] != 0);++i)
{
ans.n[i] = n[i] + rhs.n[i] + in;
in = ans.n[i] / base;
ans.n[i] %= base;
}
return ans;
}
hint operator+=(const hint& rhs)
{
*this = *this + rhs;
return *this;
}
void print()
{
long long t = 9;
while (!n[t]) t--;
cout << n[t];
t--;
while (t >= 0)
{
cout << n[t];
t--;
}
}
};
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
hint dp[55][55];
long long h, k;
cin >> k >> h;
for (long long i = 0;i < k;++i) dp[1][i] = k - i;
for (long long i = 2;i < h;++i)
{
for (long long j = 0;j < k;++j)
{
for (long long t = 0;t < k - j;++t)
{
dp[i][j] += dp[i - 1][t];
}
}
}
dp[h - 1][0].print();
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week7/4071.cpp
// 4071.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
const long long MOD = 1E9 + 7;
struct m
{
long long leftup = 0;
long long leftdown = 0;
long long rightup = 0;
long long rightdown = 0;
};
m mul(m a, m b)
{
m ans;
ans.leftup = (a.leftup * b.leftup % MOD + a.rightup * b.leftdown % MOD) % MOD;
ans.rightup = (a.leftup * b.rightup % MOD + a.rightup * b.rightdown % MOD) % MOD;
ans.leftdown = (a.leftdown * b.leftup % MOD + a.rightdown * b.leftdown % MOD) % MOD;
ans.rightdown = (a.leftdown * b.rightup % MOD + a.rightdown * b.rightdown % MOD) % MOD;
return ans;
}
m quickpos(m a, long long n)
{
if (n == 0)
{
m E;
E.leftdown = E.rightup = 0;
E.leftup = E.rightdown = 1;
return E;
}
else
{
while (!(n & 1))
{
n >>= 1;
a = mul(a, a);
}
}
m ans = a;
n >>= 1;
while (n)
{
a = mul(a, a);
if (n & 1) ans = mul(ans, a);
n >>= 1;
}
return ans;
}
int main()
{
long long n;
cin >> n;
m a;
a.leftup = a.leftdown = a.rightup = 1;
a.rightdown = 0;
m ans = quickpos(a, n);
cout << ans.leftup;
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week3/4029.cpp
// 4029.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int a[1002], b[300002];
int main()
{
//int* a, * b;
int N, M;
scanf("%d", &N);
//a = new int[N + 2];
for (int i = 0;i < N;i++) scanf("%d", &a[i]);
scanf("%d", &M);
//b = new int[M + 2];
for (int i = 0;i < M;i++) scanf("%d", &b[i]);
int max = 0;
for (int i = 0;i < M;i++)
{
if (b[i] > max) max = b[i];
}
bool* ok = new bool[max + 1];
memset(ok, 0, max + 1);
ok[0] = true;
for (int i = 1;i <= max;i++)
{
for (int j = 0;j < N;j++)
{
if (i >= a[j] && ok[i - a[j]])
{
ok[i] = true;
break;
}
}
}
for (int i = 0;i < M;i++)
{
if (ok[b[i]]) printf("YES\n");
else printf("NO\n");
}
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week4/4116.cpp
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <cstdio>
using namespace std;
int arr[100005];
void QuickSort(int arr[], int low, int high)
{
int i, j, temp;
i = low;
j = high;
if (low < high)
{
temp = arr[low];
while (i != j)
{
while (j > i&& arr[j] >= temp)
{
--j;
}
if (i < j)
{
arr[i] = arr[j];
++i;
}
while (i < j && arr[i] < temp)
{
++i;
}
if (i < j)
{
arr[j] = arr[i];
--j;
}
}
arr[i] = temp;
QuickSort(arr, low, i - 1);
QuickSort(arr, i + 1, high);
}
}
int main()
{
int N, S;
scanf("%d%d", &N, &S);
for (int i = 0;i < N;i++) scanf("%d", &arr[i]);
QuickSort(arr, 0, N - 1);
int left = 0, right = 1000000005;
while (left < right)
{
int mid = (left + right + 1) >> 1;
int temp = 0, num = 0;
for (int i = 0;i < N;++i)
{
if (arr[i] >= temp)
{
num++;
temp = arr[i] + mid;
}
}
if (num < S) right = mid - 1;
else left = mid;
}
printf("%d", left);
return 0;
}
<file_sep>/week2/1360.cpp
// 1360.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
void QuickSort(int begin[],int end[], int low, int high);
int main()
{
int n;
cin >> n;
int *arrbegin, *arrend;
arrbegin = new int[n + 1];
arrend = new int[n + 1];
for (int i = 0;i < n;i++)
{
cin >> arrbegin[i] >> arrend[i];
}
QuickSort(arrbegin, arrend, 0, n - 1);
//for (int i = 0;i < n;i++)
//{
// cout << arrbegin[i] << ' ' << arrend[i] << endl;
//}
int end = arrend[0];
int flag = 1;
for (int i = 1;i < n;i++)
{
if (arrbegin[i] >= end)
{
end = arrend[i];
flag++;
}
}
cout << flag;
delete[]arrbegin;
delete[]arrend;
return 0;
}
void QuickSort(int begin[], int end[], int low, int high)
{
int i, j;
int temp, ttemp;
i = low;
j = high;
if (low < high)
{
temp = end[low];
ttemp = begin[low];
while (i != j)
{
while (j > i&& end[j] >= temp)
{
--j;
}
if (i < j)
{
end[i] = end[j];
begin[i] = begin[j];
++i;
}
while (i < j && end[i] < temp)
{
++i;
}
if (i < j)
{
end[j] = end[i];
begin[j] = begin[i];
--j;
}
}
end[i] = temp;
begin[i] = ttemp;
QuickSort(begin , end , low, i - 1);
QuickSort(begin, end , i + 1, high);
}
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week8/1117.cpp
// 1117.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
int head[200005], pre[200005], nex[200005], num[200005], degree[200005], point[200005];
int tot = 0;
int maxnum = 0;
void add(int u,int v)
{
tot++;
point[tot] = v;
nex[tot] = head[u];
head[u] = tot;
if (nex[tot]) pre[nex[tot]] = tot;
degree[u]++;
degree[v]++;
}
void del(int begin, int edge)
{
if (nex[edge]) pre[nex[edge]] = pre[edge];
if (pre[edge]) nex[pre[edge]] = nex[edge];
else head[begin] = nex[edge];
pre[edge] = nex[edge] = 0;
}
template <class T>
class sheap {
private:
T a[200005];
long long heapsize = 0;
void swp(long long x, long long y)
{
T t = a[x];
a[x] = a[y];
a[y] = t;
}
void up(long long x)
{
while (x != 1)
{
if (a[x] < a[x >> 1])
{
swp(x, x >> 1);
x >>= 1;
}
else break;
}
}
void down()
{
long long i = 2;
while (i <= heapsize)
{
if (i < heapsize && a[i + 1] < a[i])
{
++i;
}
if (a[i] < a[i >> 1])
{
swp(i, i >> 1);
i <<= 1;
}
else break;
}
}
public:
void push(T x)
{
a[++heapsize] = x;
up(heapsize);
}
void pop()
{
swp(1, heapsize);
--heapsize;
down();
}
T top()
{
return a[1];
}
bool empty()
{
return heapsize == 0;
}
long long size()
{
return heapsize;
}
};
void build(int rot)
{
char ch;
int a = 0;
cin >> ch;
while (ch >= '0' && ch <= '9')
{
a *= 10;
a += ch - '0';
cin >> ch;
}
if (a > maxnum) maxnum = a;
if (rot != 0)
{
add(rot, a);
add(a, rot);
}
while (ch == '(')
{
build(a);
cin >> ch;
}
}
sheap<int> Heap;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin.get();
build(0);
for (int i = 1;i <= maxnum;++i)
{
if (degree[i] == 2) Heap.push(i);
}
for (int i = 1;i < maxnum;++i)
{
int tmp = Heap.top();
int edge = head[tmp];
int parent = point[edge];
cout << parent << ' ';
Heap.pop();
del(tmp, edge);
if (edge % 2 == 0) del(parent, edge - 1);
else del(parent, edge + 1);
degree[parent] -= 2;
if (degree[parent] == 2) Heap.push(parent);
}
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week4/1348.cpp
// 1348.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <cstdio>
using namespace std;
int boy[1000003], girl[1000003];
long long songtime[100003];
void QuickSort(int arr[], int low, int high)
{
int i, j, temp;
i = low;
j = high;
if (low < high)
{
temp = arr[low];
while (i != j)
{
while (j > i&& arr[j] >= temp)
{
--j;
}
if (i < j)
{
arr[i] = arr[j];
++i;
}
while (i < j && arr[i] < temp)
{
++i;
}
if (i < j)
{
arr[j] = arr[i];
--j;
}
}
arr[i] = temp;
QuickSort(arr, low, i - 1);
QuickSort(arr, i + 1, high);
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int N, M;
cin >> N;
for (int i = 0;i < N;++i)
{
cin >> songtime[i];
}
cin >> M;
int sex, boynum = 0, girlnum = 0;
int boyend, girlend;
boyend = girlend = 1;
while (M--)
{
cin >> sex;
if (sex == 1)
{
boynum++;
cin >> boy[boynum];
}
else if (sex == 2)
{
girlnum++;
cin >> girl[girlnum];
}
}
QuickSort(girl, 1, girlnum);
QuickSort(boy, 1, boynum);
long long nowtime = 0;
long long boywaittime = 0, girlwaittime = 0;
for (int i = 0;i < N;++i)
{
//while (boyend != boynum + 1 && girlend != girlnum + 1 && girl[girlend] == 0 && boy[boyend] == 0)
//{
// boyend++;
// girlend++;
//}
if (i != N - 1)
{
while (boyend != boynum + 1 && girlend != girlnum + 1 && girl[girlend] <= nowtime && boy[boyend] <= nowtime)
{
boywaittime += nowtime - boy[boyend++];
girlwaittime += nowtime - girl[girlend++];
}
nowtime += songtime[i];
}
else
{
while(boyend != boynum + 1)
boywaittime += nowtime - boy[boyend++];
while(girlend != girlnum + 1)
girlwaittime += nowtime - girl[girlend++];
nowtime += songtime[i];
}
}
printf("%.2f %.2f", (double)boywaittime / boynum, (double)girlwaittime / girlnum);
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week5/1077.cpp
// 1077.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
int w[30];
int f[30][30];
int root[30][30];
void print(int l, int r)
{
if (l > r) return;
cout << root[l][r] << ' ';
print(l, root[l][r] - 1);
print(root[l][r] + 1, r);
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n;
cin >> n;
for (int i = 1;i <= n;++i) cin >> w[i];
for (int i = 1;i <= n;++i)
{
f[i][i] = w[i];
root[i][i] = i;
}
for (int m = 1;m < n;++m)
{
for (int l = 1;l + m <= n;++l)
{
int r = l + m;
for (int t = l;t <= r;++t)
{
int lw, rw;
if (t == l) lw = 1;
else lw = f[l][t - 1];
if (t == r) rw = 1;
else rw = f[t + 1][r];
if (lw * rw + w[t] > f[l][r])
{
f[l][r] = lw * rw + w[t];
root[l][r] = t;
}
}
}
}
cout << f[1][n] << '\n';
print(1, n);
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week5/1530.cpp
// 1530.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <cstring>
using namespace std;
char op1[10], op2[10];
int n;
void encode1(char* s, int t, int n);
void encode2(char* s, int t, int n);
void encode3(char* s, int t, int n);
void decode1(char* s, int t, int n, int &x, char* tmp);
void decode2(char* s, int t, int n, int &x, char* tmp);
void decode3(char* s, int t, int n, int &x, char* tmp);
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int N;
cin >> N;
while (N--)
{
memset(op1, 0, sizeof(char) * 10);
memset(op2, 0, sizeof(char) * 10);
cin >> n >> op1 >> op2;
char* s = new char[n + 1];
memset(s, 0, sizeof(char) * (n + 1));
cin >> s;
if (op1[4] == 'R' && op2[0] == 'E') encode1(s, 0, n);
if (op1[4] == 'D' && op2[0] == 'E') encode2(s, 0, n);
if (op1[4] == 'O' && op2[0] == 'E') encode3(s, 0, n);
if (op1[4] == 'R' && op2[0] == 'D')
{
char* tmp = new char[n + 1];
memset(tmp, 0, sizeof(char) * (n + 1));
int num = 0;
decode1(s, 0, n, num, tmp);cout << tmp;
}
if (op1[4] == 'D' && op2[0] == 'D')
{
char* tmp = new char[n + 1];
memset(tmp, 0, sizeof(char) * (n + 1));
int num = 0;
decode2(s, 0, n, num, tmp);cout << tmp;
}
if (op1[4] == 'O' && op2[0] == 'D')
{
char* tmp = new char[n + 1];
memset(tmp, 0, sizeof(char) * (n + 1));
int num = 0;
decode3(s, 0, n, num, tmp);cout << tmp;
}
cout << '\n';
delete[] s;
}
return 0;
}
void encode1(char* s, int t, int n)
{
if (t >= n) return;
cout << s[t];
encode1(s, 2 * t + 1, n);
encode1(s, 2 * t + 2, n);
}
void encode2(char* s, int t, int n)
{
if (t >= n) return;
encode2(s, 2 * t + 1, n);
cout << s[t];
encode2(s, 2 * t + 2, n);
}
void encode3(char* s, int t, int n)
{
if (t >= n) return;
encode3(s, 2 * t + 1, n);
encode3(s, 2 * t + 2, n);
cout << s[t];
}
void decode1(char* s, int t, int n, int &x, char* tmp)
{
if (t >= n) return;
tmp[t] = s[x++];
decode1(s, 2 * t + 1, n, x, tmp);
decode1(s, 2 * t + 2, n, x, tmp);
}
void decode2(char* s, int t, int n, int &x, char* tmp)
{
if (t >= n) return;
decode2(s, 2 * t + 1, n, x, tmp);
tmp[t] = s[x++];
decode2(s, 2 * t + 2, n, x, tmp);
}
void decode3(char* s, int t, int n, int &x, char* tmp)
{
if (t >= n) return;
decode3(s, 2 * t + 1, n, x, tmp);
decode3(s, 2 * t + 2, n, x, tmp);
tmp[t] = s[x++];
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week7/4094.cpp
// 4094.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <cstring>
using namespace std;
char coming[300];
int customer[30] = { 0 };
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t, bed;
int leave = 0;
cin >> t;
while (t != 0)
{
cin >> coming;
bed = t;
for (int i = 0; i < strlen(coming); ++i)
{
if (customer[coming[i] - 'A'] == 0)
{
if (bed > 0)
{
customer[coming[i] - 'A'] = 1;
bed--;
}
else
{
customer[coming[i] - 'A'] = 2;
leave++;
}
}
else if(customer[coming[i] - 'A'] == 1)
{
bed++;
customer[coming[i] - 'A'] = 0;
}
}
if (leave == 0) cout << "All customers tanned successfully." << '\n';
else cout << leave << " customer(s) walked away." << '\n';
leave = 0;
memset(coming, 0, sizeof(coming));
memset(customer, 0, sizeof(customer));
cin >> t;
}
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week5/1122.cpp
// 1122.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
//#include <cstring>
using namespace std;
int node[200002];
int lzero[200002], rzero[200002];
int tag[200002];
void pushup(int k, int l, int r)
{
lzero[k] = lzero[k << 1];
rzero[k] = rzero[k << 1 | 1];
int m = (l + r) >> 1;
if (lzero[k] == m - l + 1) lzero[k] += lzero[k << 1 | 1];
if (rzero[k] == r - m) rzero[k] += rzero[k << 1];
int tmp1 = node[k << 1];
int tmp2 = node[k << 1 | 1];
int tmp3 = rzero[k << 1] + lzero[k << 1 | 1];
node[k] = tmp1 > tmp2 ? tmp1 : tmp2;
node[k] = node[k] > tmp3 ? node[k] : tmp3;
}
void pushdown(int k, int l, int r)
{
if (tag[k] != 0)
{
tag[k << 1] = tag[k << 1 | 1] = tag[k];
int m = (l + r) >> 1;
if (tag[k] == 1)
{
node[k << 1] = node[k << 1 | 1] = lzero[k << 1] = rzero[k << 1] = lzero[k << 1 | 1] = rzero[k << 1 | 1] = 0;
}
if (tag[k] == 2)
{
node[k << 1] = lzero[k << 1] = rzero[k << 1] = m - l + 1;
node[k << 1 | 1] = lzero[k << 1 | 1] = rzero[k << 1 | 1] = r - m;
}
tag[k] = 0;
}
}
void build(int k,int l,int r)
{
if (l == r)
{
node[k] = lzero[k] = rzero[k] = 1;
return;
}
else
{
int m = (l + r) >> 1;
build(k << 1, l, m);
build(k << 1 | 1, m + 1, r);
pushup(k, l, r);
}
}
int check(int k,int l,int r,int len)
{
if (l == r)
{
return l;
}
pushdown(k, l, r);
int m = (l + r) >> 1;
if (node[k << 1] >= len) return check(k << 1, l, m, len);
else if (rzero[k << 1] + lzero[k << 1 | 1] >= len) return m - rzero[k << 1] + 1;
else if (node[k << 1 | 1] >= len) return check(k << 1 | 1, m + 1, r, len);
}
void checkin(int L, int R, int k, int l, int r)
{
if (L <= l && R >= r)
{
tag[k] = 1;
node[k] = lzero[k] = rzero[k] = 0;
return;
}
pushdown(k, l, r);
int m = (l + r) >> 1;
if (L <= m) checkin(L, R, k << 1, l, m);
if (R > m) checkin(L, R, k << 1 | 1, m + 1, r);
pushup(k, l, r);
}
void checkout(int L, int R, int k, int l, int r)
{
if (L <= l && R >= r)
{
tag[k] = 2;
node[k] = lzero[k] = rzero[k] = r - l + 1;
return;
}
int m = (l + r) >> 1;
pushdown(k, l, r);
if (L <= m) checkout(L, R, k << 1, l, m);
if (R > m) checkout(L, R, k << 1 | 1, m + 1, r);
pushup(k, l, r);
}
int main()
{
//ios::sync_with_stdio(false);
//cin.tie(0);
//cout.tie(0);
int N, M;
scanf("%d %d", &N, &M);
build(1, 1, N);
while (M--)
{
int op;
scanf("%d", &op);
if (op == 1)
{
int x;
scanf("%d", &x);
if (x > node[1]) printf("0\n");
else
{
int L, R;
L = check(1, 1, N, x);
printf("%d\n", L);
R = L + x - 1;
checkin(L, R, 1, 1, N);
}
}
if (op == 2)
{
int x, y;
scanf("%d %d", &x, &y);
int L, R;
L = x;
R = x + y - 1;
checkout(L, R, 1, 1, N);
}
}
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week8/4310.cpp
// 4310.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
const int MAXDEPTH = 18;
int n, m, num = 0, len = 0;
int f[100001][19], depth[100001], val[100001];
int head[100001], nex[100001], from[100001], point[100001], dis[100001];
bool isnotroot[100001];
char op[8];
void swp(int& a, int& b)
{
int tmp = b;
b = a;
a = tmp;
}
void add(int u, int v, int value)
{
num++;
point[num] = v;
from[num] = u;
val[num] = value;
nex[num] = head[u];
head[u] = num;
}
void dfs(int p, int father)
{
depth[p] = depth[father] + 1;
f[p][0] = father;
for (int i = 1; i <= MAXDEPTH; i++)
f[p][i] = f[f[p][i - 1]][i - 1];
for (int i = head[p]; i != 0; i = nex[i])
{
dis[point[i]] = dis[p] + val[i];
dfs(point[i], p);
}
}
int LCA(int x, int y)
{
if (depth[x] > depth[y]) swp(x, y);
if (x == y) return x;
for (int i = MAXDEPTH; i >= 0; i--)
if (depth[f[y][i]] >= depth[x]) y = f[y][i];
if (x == y) return x;
for (int i = MAXDEPTH; i >= 0; i--)
if (f[x][i] != f[y][i])
{
x = f[x][i];
y = f[y][i];
}
return f[x][0];
}
int quary(int a, int b, int k)
{
int lca = LCA(a, b);
if (depth[a] - depth[lca] + 1 >= k)
{
int ans = depth[a] - k + 1;
for (int i = MAXDEPTH; i >= 0; i--)
if (depth[f[a][i]] >= ans) a = f[a][i];
return a;
}
else
{
int ans = depth[lca] * 2 + k - depth[a] - 1;
for (int i = MAXDEPTH; i >= 0; i--)
if (depth[f[b][i]] >= ans) b = f[b][i];
return b;
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> m;
int father, son, valu;
for (int i = 1;i < n;++i)
{
cin >> father >> son >> valu;
isnotroot[son] = true;
add(father, son, valu);
}
int root;
for (int i = 1;i <= n;++i)
{
if (!isnotroot[i])
{
root = i;
break;
}
}
dfs(root, root);
int a, b, c;
for (int i = 0;i < m;++i)
{
cin >> op;
if (op[0] == 'D')
{
cin >> a >> b;
cout << dis[a] + dis[b] - dis[LCA(a, b)] * 2 ;
if (i != m - 1) cout << '\n';
}
else if(op[0] == 'K')
{
cin >> a >> b >> c;
cout << quary(a, b, c);
if (i != m - 1) cout << '\n';
}
}
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/test20200514/test2.cpp
// test2.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
using namespace std;
long long s[500000];
long long maxx[500000], minn[500000];
long long len, n;
long long node[500000];
long long node2[500000];
long long summaxx = 0;
void down(long long p)
{
long long tmp = node[p];
long long t = p;
long long s = t << 1;
while (t << 1 <= len)
{
s = t << 1;
if (s != len && node[s + 1] < node[s]) s++;
if (node[s] < tmp) node[t] = node[s];
else break;
t = s;
}
node[t] = tmp;
}
void up(long long t)
{
long long tmp = node[t];
long long p = len;
while (p > 1 && tmp < node[p >> 1])
{
node[p] == node[p >> 1];
p = p >> 1;
}
node[p] = tmp;
}
void buildtree()
{
len = n;
for (long long i = 1;i <= len;++i)
{
node[i] = s[i];
summaxx += s[i];
}
for (long long i = 1;i <= len >> 1;++i)
{
down(i);
}
}
void insertnode(long long da)
{
len++;
node[len] = da;
up(len);
}
long long deletenode()
{
long long ans = node[1];
node[1] = node[len];
len--;
down(1);
return ans;
}
long long summinn = 0;
void down2(long long p)
{
long long tmp = node2[p];
long long t = p;
long long s = t << 1;
while (t << 1 <= len)
{
s = t << 1;
if (s != len && node2[s + 1] > node2[s]) s++;
if (node2[s] > tmp) node2[t] = node2[s];
else break;
t = s;
}
node2[t] = tmp;
}
void up2(long long t)
{
long long tmp = node2[t];
long long p = len;
while (p > 1 && tmp > node2[p >> 1])
{
node2[p] == node2[p >> 1];
p = p >> 1;
}
node2[p] = tmp;
}
void buildtree2()
{
len = n;
for (long long i = 1;i <= n;++i)
{
node2[i] = s[3 * n - i + 1];
summinn += s[3 * n - i + 1];
}
for (long long i = 1;i <= len >> 1;++i)
{
down2(i);
}
}
void insertnode2(long long da)
{
len++;
node2[len] = da;
up2(len);
}
long long deletenode2()
{
long long ans = node2[1];
node2[1] = node2[len];
len--;
down2(1);
return ans;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
for (long long i = 1;i <= 3 * n;++i)
{
cin >> s[i];
}
buildtree();
maxx[n] = summaxx;
for (long long i = n + 1;i <= 3 * n;++i)
{
if (s[i] > node[1])
{
summaxx -= deletenode();
summaxx += s[i];
insertnode(s[i]);
}
maxx[i] = summaxx;
}
buildtree2();
minn[2 * n + 1] = summinn;
for (long long i = 2 * n;i > 0;--i)
{
if (s[i] < node2[1])
{
summinn -= deletenode2();
summinn += s[i];
insertnode2(s[i]);
}
minn[i] = summinn;
}
long long ans = -1000000009;
for (long long i = n;i <= 2 * n;++i)
{
if (ans < maxx[i] - minn[i+1]) ans = maxx[i] - minn[i+1];
}
cout << ans;
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week1/1203.cpp
// 1203.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <cstring>
using namespace std;
template <class T>
void link(int a, int b)
{
T* arr1, * arr2,* arr;
arr1 = new T[a + 1];
arr2 = new T[b + 1];
for (int i = 0;i < a;i++) cin >> arr1[i];
for (int i = 0;i < b;i++) cin >> arr2[i];
arr1[a] = arr2[b] = '\0';
arr = new T[a + b + 1];
for (int i = 0;i < a + b;i++)
{
if (i <= a - 1) arr[i] = arr1[i];
else if(i <= a + b - 1) arr[i] = arr2[i - a];
}
arr[a + b] = '\0';
for (int i = 0;i < a + b;i++)
{
cout << arr[i] << ' ';
}
delete []arr1;
delete []arr2;
}
int main()
{
char type[7];
cin >> type;
int lena, lenb;
cin >> lena >> lenb;
if (!strcmp(type , "int")) link<int>(lena, lenb);
else if (!strcmp(type, "double")) link<double>(lena, lenb);
else if((!strcmp(type, "char"))) link<char>(lena, lenb);
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week4/4206.cpp
// 4206.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
int n, m;
int a[2005][2005] = { 0 };
//char b[2002][2002];
bool isPrime[1002];
int f(int l)
{
int ans = 0;
int N = ceil((double)n / l) * l;
int M = ceil((double)m / l) * l;
for (int i = 0;i < N;i += l)
{
for (int j = 0;j < M;j += l)
{
int black = a[i + l][j + l] - a[i][j + l] - a[i + l][j] + a[i][j];
ans += ((black < l * l - black) ? black : (l * l - black));
}
}
return ans;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> m;
for (int i = 2; i <= 1000; i++)
isPrime[i] = 1;
for (int i = 2; i <= 1000; i++) {
if (isPrime[i])
for (int j = 2 * i; j <= 1000; j += i)
isPrime[j] = 0;
}
int k[200];
int z = 0;
for (int i = 2;i <= 1000;++i)
{
if (isPrime[i])
{
k[z] = i;
++z;
}
}
char c;
cin.get();
for (int i = 1;i <= n;++i)
{
for (int j = 1;j <= m;++j)
{
c = cin.get();
a[i][j] = c - '0';
}
cin.get();
}
for (int i = 1;i <= 2000;++i)
{
for (int j = 1;j <= 2000;++j)
{
a[i][j] += a[i - 1][j] + a[i][j - 1] - a[i - 1][j - 1];
}
}
int change = 2 * n * m;
for (int p = 0;k[p] <= (n > m ? n : m);++p)
{
int tmp = 0;
tmp = f(k[p]);
if (tmp < change) change = tmp;
}
cout << change;
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week6/2100.cpp
// 2100.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
long long N;
long long ans = 0;
struct node
{
long long num;
long long val;
node* l, * r;
node* p;
};
void select(node** a, long long end, long long& s1, long long& s2)
{
long long i = 1;
long long min1, min2;
while (i <= end && a[i]->p != NULL)
{
++i;
}
min1 = a[i]->val;
s1 = i;
++i;
while (i <= end && a[i]->p != NULL)
{
++i;
}
if (a[i]->val < min1)
{
min2 = min1;
s2 = s1;
min1 = a[i]->val;
s1 = i;
}
else
{
min2 = a[i]->val;
s2 = i;
}
for (long long j = i + 1;j <= end;++j)
{
if (a[j]->p != NULL) continue;
else if (a[j]->val < min1)
{
min2 = min1;
s2 = s1;
min1 = a[j]->val;
s1 = j;
}
else if (a[j]->val >= min1 && a[j]->val < min2)
{
min2 = a[j]->val;
s2 = j;
}
}
}
node* word[500005];
void buildtree()
{
cin >> N;
for (long long i = 1;i <= N;++i)
{
word[i] = new node;
word[i]->num = i;
cin >> word[i]->val;
word[i]->l = NULL;
word[i]->r = NULL;
word[i]->p = NULL;
}
for (long long i = N + 1;i <= 2 * N - 1;++i)
{
word[i] = new node;
word[i]->num = i;
word[i]->val = 0;
word[i]->l = NULL;
word[i]->r = NULL;
word[i]->p = NULL;
}
for (long long i = N + 1;i <= 2 * N - 1;++i)
{
long long s1, s2;
select(word, i-1, s1, s2);
word[s1]->p = word[s2]->p = word[i];
word[i]->l = word[s1];
word[i]->r = word[s2];
word[i]->val = word[s1]->val + word[s2]->val;
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
buildtree();
for (long long i = N + 1;i <= 2 * N - 1;++i)
ans += word[i]->val;
cout << ans;
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week2/4016.cpp
// 4016.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <cmath>
using namespace std;
void fun(int arr[], int len);
int themax = 0;
int main()
{
int N;
cin >> N;
int* max;
max = new int[N];
for (int i = 0;i < N;i++)
{
themax = 0;
int num[10];
cin >> num[0] >> num[1] >> num[2] >> num[3];
fun(num, 4);
max[i] = themax;
}
for (int i = 0; i < N; ++i)
cout << max[i] << endl;
return 0;
}
void fun(int arr[], int len)
{
if (len == 1)
{
if (arr[0] <= 24 && arr[0] > themax) themax = arr[0];
return;
}
else
{
int temp[10];
for(int p = 0;p < 4;p++)
{
for (int n = 0;n < len;n++)
{
for (int m = n + 1;m < len;m++)
{
int i = 0,j = 0;
while (i < len)
{
if (i != m && i != n)
{
temp[j] = arr[i];
j++;
}
i++;
}
if (p == 0) temp[len - 2] = arr[m] + arr[n];
else if (p == 1) temp[len - 2] = abs(arr[m] - arr[n]);
else if (p == 2) temp[len - 2] = arr[m] * arr[n];
else if (p == 3)
{
if (arr[n] != 0 && arr[m] % arr[n] == 0) temp[len - 2] = arr[m] / arr[n];
else if (arr[m] != 0 && arr[n] % arr[m] == 0) temp[len - 2] = arr[n] / arr[m];
else return;
}
fun(temp, len - 1);
}
}
}
}
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week1/1021.cpp
#include <iostream>
using namespace std;
void goright(int**,int,int,int,int);
void godown(int**, int, int, int, int);
void goleft(int**, int, int, int, int);
void goup(int**, int, int, int, int);
int main(int**, int, int, int, int)
{
int N;
cin >> N;
int** arr = new int* [N];
for (int i = 0; i < N; i++)
{
arr[i] = new int[N];
}
goright(arr, 0, 0, 1, N);
int m = 0, n = N - 1, num = N;
for (int length = N - 1;length > 0;length--)
{
godown(arr, m + 1, n, num + 1, length);
m += length;num += length;
goleft(arr, m, n - 1, num + 1, length);
n -= length;num += length;
length--;
if (length == 0)break;
goup(arr, m - 1, n, num + 1, length);
m -= length;num += length;
goright(arr, m, n + 1, num + 1, length);
n += length;num += length;
}
for (int i = 0;i < N;i++)
{
for (int j = 0;j < N;j++)
{
cout << arr[i][j]<<" ";
}
cout << endl;
}
for (int i = 0; i < N; i++)
{
delete[]arr[i];
}
delete[]arr;
return 0;
}
void goright(int** a,int x,int y,int begin,int len)
{
for (int i = 0;i < len;i++)
{
a[x][y + i] = begin + i;
}
}
void godown(int** a, int x, int y, int begin, int len)
{
for (int i = 0;i < len;i++)
{
a[x + i][y] = begin + i;
}
}
void goleft(int** a, int x, int y, int begin, int len)
{
for (int i = 0;i < len;i++)
{
a[x][y - i] = begin + i;
}
}
void goup(int** a, int x, int y, int begin, int len)
{
for (int i = 0;i < len;i++)
{
a[x - i][y] = begin + i;
}
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week1/1032.cpp
// 1032.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
int main()
{
int M, N;
cin >> M >> N;
if (M == 0) cout << N + 1;
else if (M == 1) cout << N + 2;
else if (M == 2) cout << 2 * N + 3;
else if (M == 3)
{
int ans = 1;
for (int i = 0;i < N + 3;i++)
{
ans *= 2;
}
cout << ans - 3;
}
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week6/2100plus.cpp
// 2100plus.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
long long n;
long long len = 0;
long long word[200005];
void build()
{
for (long long i = 1;i <= n;++i)
{
cin >> word[i];
len++;
}
for (long long i = n>>1;i >=1;--i)
{
long long t = i;
long long s = i;
long long tmp = word[t];
while (t << 1 <= len)
{
s = t << 1;
if (s != len && word[s + 1] < word[s]) s++;
if (word[s] < tmp) word[t] = word[s];
else break;
t = s;
}
word[t] = tmp;
}
}
long long deleteroot()
{
long long ans = word[1];
word[1] = word[len];
len--;
long long t = 1;
long long s = 1;
while (t << 1 <= len)
{
s = t << 1;
if (s != len && word[s + 1] < word[s]) s++;
if (word[s] < word[len + 1]) word[t] = word[s];
else break;
t = s;
}
word[t] = word[len + 1];
return ans;
}
void insert(long long t)
{
len++;
//word[len] = t;
long long p = len;
while (p > 1 && t < word[p << 1])
{
word[p] = word[p >> 1];
p = p >> 1;
}
word[p] = t;
}
long long ans = 0;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
build();
len = n;
while (len != 1)
{
long long a, b;
a = deleteroot();
b = deleteroot();
insert(a + b);
ans += a + b;
}
cout << ans;
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week1/1338.cpp
// 1338.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
void sorts(long long arr[], long long start, long long last);
int main()
{
long long n,summax = 0,summin = 0;
cin >> n;
long long* a, * b;
a = new long long[n];
b = new long long[n];
for (long long i = 0;i < n;i++)
{
cin >> a[i];
}
for (long long i = 0;i < n;i++)
{
cin >> b[i];
}
sorts(a, 0, n - 1);
sorts(b, 0, n - 1);
for (long long i = 0;i < n;i++)
{
summax += a[i] * b[i];
}
for (long long i = 0;i < n / 2;i++)
{
long long temp = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = temp;
}
for (long long i = 0;i < n;i++)
{
summin += a[i] * b[i];
}
cout << summax <<' '<< summin;
delete[]a;
delete[]b;
return 0;
}
void sorts(long long arr[], long long start, long long last)
{
long long i = start;
long long j = last;
long long temp = arr[i];
if (i < j)
{
while (i < j)
{
while (i < j && arr[j] >= temp) j--;
if (i < j)
{
arr[i] = arr[j];
i++;
}
while (i < j && arr[i] < temp)i++;
if (i < j)
{
arr[j] = arr[i];
j--;
}
}
arr[i] = temp;
sorts(arr, start, i - 1);
sorts(arr, i + 1, last);
}
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/test20200514/test1.cpp
// test1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#define _CRT_SECURE_NO_DEPRECATE
#include<cstdio>
constexpr int nmax = 200000, mmax = 100000;
int n, m;
int find11;
struct set {
int x;
int y;
int z;
};
set* read1;
bool findroot[nmax] = { 0 };
class binary_tree {
public:
struct nodeq {
int number;
nodeq* lchild;
nodeq* rchild;
nodeq(int i = 0) {
number = i;
lchild = 0;
rchild = 0;
}
nodeq(set* arr, int now) {
number = arr[now].x;
if (arr[now].y) {
lchild = new nodeq(arr, arr[now].y);
}
if (arr[now].z) {
rchild = new nodeq(arr, arr[now].z);
}
else rchild = 0;
}
~nodeq() {
if (lchild)delete lchild;
if (rchild)delete rchild;
}
};
nodeq* root;
void deletenode(int i, nodeq*& ptr) {
if (ptr->number < i)deletenode(i, ptr->rchild);
else {
if (ptr->number > i)deletenode(i, ptr->lchild);
else {
if (ptr->lchild && ptr->rchild) {
nodeq* tmp = ptr->rchild;
if (tmp->lchild == 0) {
ptr->number = ptr->rchild->number;
ptr->rchild = ptr->rchild->rchild;
}
else {
while (tmp->lchild->lchild) {
tmp = tmp->lchild;
}
ptr->number = tmp->lchild->number;
tmp->lchild = tmp->lchild->rchild;
}
}
else {
if (ptr->lchild) {
ptr = ptr->lchild;
}
else {
ptr = ptr->rchild;
}
}
}
}
}
void insert(int i, nodeq*& ptr) {
if (ptr == 0) {
ptr = new nodeq(i);
return;
}
else {
if (i > ptr->number)insert(i, ptr->rchild);
else insert(i, ptr->lchild);
}
}
public:
binary_tree(set* arr, int root1) {
root = new nodeq(arr, root1);
}
void deletenode(int i) {
deletenode(i, root);
}
void insert(int i) {
insert(i, root);
}
void find(int i, int& arr) {
nodeq* tmp = root;
while (tmp->number != i) {
if (tmp->number < i) {
tmp = tmp->rchild;
}
else {
tmp = tmp->lchild;
}
}
if (tmp->lchild || tmp->rchild) {
arr = 1;
}
else arr = 0;
return;
}
};
void quicksort(set* arr, int left1, int right1) {
if (left1 >= right1)return;
set tmp = arr[left1];
int left = left1, right = right1;
do {
while (left<right && arr[right].x>tmp.x)--right;
if (left < right)arr[left] = arr[right];
while (left < right && arr[left].x < tmp.x)++left;
if (left < right)arr[right] = arr[left];
} while (left < right);
arr[left] = tmp;
quicksort(arr, left1, left - 1);
quicksort(arr, left + 1, right1);
}
bool s(char* a, char* b) {
int tmp = 0;
while (a[tmp] && b[tmp]) {
if (a[tmp] != b[tmp])return false;
++tmp;
}
if (a[tmp] == 0 && b[tmp] == 0)return true;
else return false;
}
binary_tree* tree;
int main() {
scanf("%d%d", &n, &m);
read1 = new set[n];
for (int i = 1; i <= n; ++i) {
scanf("%d%d", &(read1[i].x), &(read1[i].y));
scanf("%d", &(read1[i].z));
findroot[read1[i].y] = findroot[read1[i].z] = true;
}
int root2 = 2;
for (int i = 1; i <= n; ++i) {
if (!findroot[i]) {
root2 = i;
break;
}
}
quicksort(read1, 1, n);
tree = new binary_tree(read1, root2);
int get1 = 0;
for (int i = 0; i < m; ++i) {
scanf("%d", &get1);
tree->find(get1, find11);
tree->deletenode(get1);
tree->insert(get1);
if (find11)printf("1\n");
else {
printf("0\n");
}
}
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week9 & 10/4307.cpp
// 4307.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
template <class T>
class sheap {
private:
T a[200005];
long long heapsize = 0;
void swap(long long x, long long y)
{
T t = a[x];
a[x] = a[y];
a[y] = t;
}
void up(long long x)
{
while (x != 1)
{
if (a[x] < a[x >> 1])
{
swap(x, x >> 1);
x >>= 1;
}
else break;
}
}
void down()
{
long long i = 2;
while (i <= heapsize)
{
if (i < heapsize && a[i + 1] < a[i])
{
++i;
}
if (a[i] < a[i >> 1])
{
swap(i, i >> 1);
i <<= 1;
}
else break;
}
}
public:
void push(T x)
{
a[++heapsize] = x;
up(heapsize);
}
void pop()
{
swap(1, heapsize);
--heapsize;
down();
}
T top()
{
return a[1];
}
bool empty()
{
return heapsize == 0;
}
long long size()
{
return heapsize;
}
};
int main()
{
sheap<int> Heap;
int k, l;
int x;
cin >> k >> l;
for (int i = 0;i < k * l;++i)
{
cin >> x;
Heap.push(x);
}
for (int i = 0;i < k * l;++i)
{
cout << Heap.top() << ' ';
Heap.pop();
}
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week5/4304.cpp
// 4304.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <cstring>
using namespace std;
long long node[400002];
long long a[100002];
long long teg[400002];
void build(long long k, long long l, long long r)
{
if (l == r)
{
node[k] = a[l];
return;
}
else
{
long long m = (l + r) >> 1;
build(k << 1, l, m);
build(k << 1 | 1, m + 1, r);
node[k] = node[k << 1] + node[k << 1 | 1];
}
}
void changenum(long long pos, long long value, long long k, long long l, long long r)
{
if (l == r)
{
node[k] += value;
a[l] += value;
}
else
{
long long m = (l + r) >> 1;
if (pos <= m) changenum(pos, value, k << 1, l, m);
else changenum(pos, value, k << 1 | 1, m + 1, r);
node[k] = node[k << 1] + node[k << 1 | 1];
}
}
long long checknum(long long A, long long B, long long k, long long l, long long r)
{
if (A <= l && B >= r) return node[k];
else
{
long long tmp = 0;
long long m = (l + r) >> 1;
if (A <= m) tmp += checknum(A, B, k << 1, l, m);
if (B > m) tmp += checknum(A, B, k << 1 | 1, m + 1, r);
return tmp;
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
long long N, M;
memset(node, 0, sizeof(node));
memset(a, 0, sizeof(a));
cin >> N;
for (long long i = 1;i <= N;++i) cin >> a[i];
build(1, 1, N);
cin >> M;
while (M--)
{
char op[8];
long long A, B;
cin >> op >> A >> B;
if (op[0] == 'Q') cout << checknum(A, B, 1, 1, N) << '\n';
if (op[0] == 'S') changenum(A, -B, 1, 1, N);
if (op[0] == 'G') changenum(A, B, 1, 1, N);
}
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week3/1397.cpp
// 1397.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstdio>
//#include <cmath>
using namespace std;
void QuickSort(long long arr[], long long low, long long high);
long long num[1000001];
int main()
{
long long n;
cin >> n;
long long sum = 0;
for (long long i = 0;i < n;i++) scanf("%d",&num[i]);
QuickSort(num, 0, n - 1);
for (long long i = 0;i < n - 1;i++)
{
sum += (num[i + 1] - num[i]) * (n - 1 - i) * (i + 1);
sum %= 1000000007;
}
printf("%d",sum);
return 0;
}
void QuickSort(long long arr[], long long low, long long high)
{
long long i, j, temp;
i = low;
j = high;
if (low < high)
{
temp = arr[low];
while (i != j)
{
while (j > i&& arr[j] >= temp)
{
--j;
}
if (i < j)
{
arr[i] = arr[j];
++i;
}
while (i < j && arr[i] < temp)
{
++i;
}
if (i < j)
{
arr[j] = arr[i];
--j;
}
}
arr[i] = temp;
QuickSort(arr, low, i - 1);
QuickSort(arr, i + 1, high);
}
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week6/1050.cpp
// 1050.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
struct node
{
int num, npl;
node* l = NULL;
node* r = NULL;
};
void nodeswap(node*& a, node*& b)
{
node* p = a;
a = b;
b = p;
}
node* girlfriend[300005];
//bool exist[300005];
node* merge(node* x, node* y)
{
if (x == NULL) return y;
if (y == NULL) return x;
if (x->num > y->num)
{
nodeswap(x, y);
}
x->r = merge(x->r, y);
if (x->l == NULL || x->l->npl < x->r->npl)
{
nodeswap(x->l, x->r);
}
if (x->r == NULL) x->npl = 0;
else x->npl = x->r->npl + 1;
return x;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int m, n;
cin >> n >> m;
for (int i = 0;i < n;++i)
{
node* tmp = new node;
cin >> tmp->num;
tmp->npl = 0;
girlfriend[i] = tmp;
//exist[i] = 1;
}
for (int i = 0;i < m;++i)
{
int op, x, y;
cin >> op;
if (op == 0)
{
cin >> x >> y;
girlfriend[x] = merge(girlfriend[x], girlfriend[y]);
//exist[y] = 0;
}
else if (op == 1)
{
cin >> x;
if (girlfriend[x] == NULL) cout << -1 << '\n';
else
{
cout << girlfriend[x]->num << '\n';
node* tmp = girlfriend[x];
girlfriend[x] = merge(girlfriend[x]->l, girlfriend[x]->r);
//if (girlfriend[x] == NULL) exist[x] = 0;
delete tmp;
}
}
else if (op == 2)
{
cin >> x >> y;
node* tmp = new node;
tmp->num = y;
tmp->npl = 0;
girlfriend[x] = merge(girlfriend[x], tmp);
//exist[x] = 1;
}
}
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week4/4208.cpp
// 4208.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int n;
cin >> n;
while (n--)
{
double a, b, x1, y1, x2, y2;
cin >> a >> b >> x1 >> y1 >> x2 >> y2;
int a1 = floor((x1 + y1) / (2 * a));
int a2 = floor((x2 + y2) / (2 * a));
int b1 = floor((x1 - y1) / (2 * b));
int b2 = floor((x2 - y2) / (2 * b));
cout << ((abs(a1 - a2) > abs(b1 - b2)) ? abs(a1 - a2) : abs(b1 - b2)) << endl;
}
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/test20200423/18.cpp
// 18.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
int f[150002], m[150002], b[150002];
int x1[150002], x2[150002], x3[150002];
int node[150002];
int sna[600002];
int top;
int tail;
void build(int k,int al,int ar,int bl,int br)
{
if (al <= ar && bl <= br)
{
node[k] = f[al];
int i = bl;
while (m[i] != f[al])
i++;
if (al <= ar && bl <= br) build(k << 1, al + 1, al + (i - bl), bl, i - 1);
if (al <= ar && bl <= br) build(k << 1 | 1, al + (i - bl) + 1, ar, i + 1, br);
}
}
void print(int a[], int n)
{
for (int i = 1;i <= n;++i)
cout << a[i] << ' ';
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int k;
cin >> k;
for (int i = 1;i <= k;++i) cin >> x1[i];
for (int i = 1;i <= k;++i) cin >> x2[i];
for (int i = 1;i <= k;++i) cin >> x3[i];
f[0] = m[0] = b[0] = 0;
int z = 0;
while (true)
{
for (int i = 0;i <= k;++i)
f[i] = m[i] = b[i] = -1;
int t1 = 1, t2 = 0, t3 = 0;
f[1] = x1[t1+z];
while (x3[t3+1+z] != f[1])
{
b[++t3-z] = x3[t3];
}
t3++;
for (t2 = z+1;t2 <= t3 + z;++t2)
{
m[t2-z] = x2[t2];
}
for (t1 = z+2;t1 <= t3 + z;++t1)
{
f[t1-z] = x1[t1];
}
build(1, 1, t3, 1, t3);
print(node, t3);
z += t3;
if (z >= k) break;
}
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week3/3044.cpp
// 3044.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int* a;
a = new int[n + 1];
a[0] = 1;
a[1] = 1;
a[2] = 2;
for (int i = 3;i <= n;++i)
{
a[i] = 0;
int j = i % 2;
while (j <= i)
{
a[i] += a[(i - j) / 2];
a[i] %= 1000000007;
j += 2;
}
}
cout << a[n];
delete[] a;
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week2/1412_change.cpp
#include <iostream>
#include <cstring>
#include <cmath>
#include <cstdio>
using namespace std;
void mymemset(int arr[], int t, int size)
{
for (int i = 0;i < size - 1;i++) arr[i] = t;
}
void changcharintoint(char a[], int b[], int& c)
{
mymemset(b, 0, 1005);
c = strlen(a);
for (int i = c - 1;i >= 0;--i)
{
b[c - i - 1] = a[i] - '0';
if (i == 0) break;
}
}
void myswap(int num1[], int num2[], int& len1, int& len2)
{
int tempnum[1005];
mymemset(tempnum, 0, 1005);
int templen = len1;
for (int i = 0;i < len1;++i)
{
tempnum[i] = num1[i];
}
mymemset(num1, 0, 1005);
for (int i = 0;i < len2;i++)
{
num1[i] = num2[i];
}
mymemset(num2, 0, 1005);
for (int i = 0;i < len2;i++)
{
num2[i] = tempnum[i];
}
len1 = len2;
len2 = templen;
}
void div2(int num[], int& len)
{
int s[1005];
int slen = len;
for (int i = len - 1;i >= 0;--i)
{
s[i] = num[i] / 2;
if (i != 0) num[i - 1] += (num[i] % 2) * 10;
}
while (true)
{
if (slen == 0) break;
if (s[slen - 1] != 0) break;
slen--;
}
myswap(num,s,len,slen);
}
void mult2(int num[], int& len)
{
int s[1005];
int slen = len + 1;
int getin = 0;
for (int i = 0;i < len;i++)
{
s[i] = (num[i] * 2) + getin;
getin = s[i] / 10;
if (getin) s[i] -= 10;
}
if (getin) s[slen - 1] = 1;
else slen--;
myswap(num, s, len, slen);
}
void reduce(int num1[], int num2[], int& len1, int& len2)
{
int s[1005];
mymemset(s, 0, 1005);
int slen = len1;
for (int i = 0;i < len1;i++)
{
s[i] += num1[i] - num2[i];
if (s[i] < 0)
{
s[i] += 10;
s[i + 1]--;
}
}
while (true)
{
if (slen == 0) break;
if (s[slen - 1] != 0) break;
slen--;
}
myswap(num1, s, len1, slen);
}
bool compare(int num1[], int num2[], int len1, int len2)
{
if (len1 != len2) return (len1 < len2);
else
{
for (int i = len1 - 1;i >= 0;--i)
{
if (num1[i] != num2[i]) return (num1[i] < num2[i]);
if (i == 0) break;
}
return false;
}
}
bool zero(int num[], int len)
{
if (len == 0 && num[0] == 0) return true;
else return false;
}
bool odd(int num[])
{
if (num[0] % 2) return true;
else return false;
}
void printin2(int num[], int& len)
{
int len2 = 0;
int tempnum[1005];
mymemset(tempnum, 0, 1005);
int templen = len;
for (int i = 0;i < len;++i)
{
tempnum[i] = num[i];
}
while (!zero(tempnum, templen))
{
div2(tempnum, templen);
len2++;
}
int* arr;
arr = new int[len2];
for (int i = 0;i < len2;i++)
{
if (odd(num))
{
num[0] -= 1;
arr[len2 - i - 1] = 1;
div2(num, len);
}
else
{
arr[len2 - i - 1] = 0;
div2(num, len);
}
}
for (int i = 0;i < len2;i++) printf("%d", arr[i]);
delete[]arr;
}
char a[1005], b[1005];
int num1[1005], num2[1005];
int len1 = 0, len2 = 0;
int main()
{
int n = 0;
scanf("%s%s", a, b);
changcharintoint(a, num1, len1);
changcharintoint(b, num2, len2);
if (compare(num1, num2, len1, len2)) myswap(num1, num2, len1, len2);
while (!zero(num2, len2))
{
if (odd(num1) && odd(num2)) reduce(num1, num2, len1, len2);
else if (!odd(num1) && odd(num2)) div2(num1, len1);
else if (odd(num1) && !odd(num2)) div2(num2, len2);
else
{
div2(num1, len1);
div2(num2, len2);
n++;
}
if (compare(num1, num2, len1, len2)) myswap(num1, num2, len1, len2);
}
for (int i = 0;i < n;i++) mult2(num1, len1);
printin2(num1, len1);
return 0;
}
<file_sep>/week2/1593.cpp
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
struct mouse
{
int P;
int S;
int num;
};
void QuickSort(mouse[], int, int);
void BubbleSort(mouse[], int);
int main()
{
int N, R;
cin >> N >> R;
mouse* mice;
mice = new mouse[2 * N];
for (int i = 0;i < 2 * N;i++) scanf("%d", &mice[i].P);
for (int i = 0;i < 2 * N;i++) scanf("%d", &mice[i].S);
for (int i = 0;i < 2 * N;i++) mice[i].num = i + 1;
QuickSort(mice, 0, 2 * N - 1);
/*cout << "before game" << endl;
cout << endl;
for (int i = 0;i < 2 * N;i++)
{
cout << i << ')' << ' ' << P[i] << '\t';
}
cout << endl;
for (int i = 0;i < 2 * N;i++)
{
cout << i << ')' << ' ' << S[i] << '\t';
}
cout << endl;
for (int i = 0;i < 2 * N;i++)
{
cout << i << ')' << ' ' << num[i] << '\t';
}
cout << endl;*/
for (int j = 0;j < R;j++)
{
for (int i = 0;i < 2 * N;i += 2)
{
if (mice[i].S > mice[i + 1].S) mice[i].P += 2;
else if (mice[i].S < mice[i + 1].S) mice[i + 1].P += 2;
else
{
mice[i].P += 1;
mice[i + 1].P += 1;
}
}
BubbleSort(mice, 2 * N);
/* cout << endl;
cout << "after game" << j+1 << endl;
for (int i = 0;i < 2 * N;i++)
{
cout << i<<')' << ' ' <<P[i] << '\t';
}
cout << endl;
for (int i = 0;i < 2 * N;i++)
{
cout << i << ')' << ' ' << S[i] << '\t';
}
cout << endl;
for (int i = 0;i < 2 * N;i++)
{
cout << i << ')' << ' ' << num[i] << '\t';
}
cout << endl;*/
}
/*cout << "the end"<<endl;
for (int i = 0;i < 2 * N;i++)
{
cout << P[i] << ' ';
}
cout << endl;
for (int i = 0;i < 2 * N;i++)
{
cout << S[i] << ' ';
}*/
/*cout << endl;*/
for (int i = 0;i < 2 * N;i++)
{
cout << mice[i].num << ' ';
}
return 0;
}
void QuickSort(mouse a[], int low, int high)
{
int i, j;
mouse temp;
i = low;
j = high;
if (low < high)
{
temp = a[low];
while (i != j)
{
while (j > i && (a[j].P < temp.P || (a[j].P == temp.P)&&(a[j].num > temp.num)))
{
--j;
}
if (i < j)
{
a[i] = a[j];
++i;
}
while (i < j && (a[i].P > temp.P || (a[i].P == temp.P) && (a[i].num < temp.num)))
{
++i;
}
if (i < j)
{
a[j] = a[i];
--j;
}
}
a[i] = temp;
QuickSort(a, low, i - 1);
QuickSort(a, i + 1, high);
}
}
//void myswap(int a1, int a2, int b1, int b2, int c1, int c2)
//{
// int temp[3];
// temp[0] = a1;
// temp[1] = b1;
// temp[2] = c1;
// a1 = a2;
// b1 = b2;
// c1 = c2;
// a2 = temp[0];
// b2 = temp[1];
// c2 = temp[2];
//}
void BubbleSort(mouse a[], int len)
{
int i, j;
bool flag = false;
for (i = 1;i < len;i++)
{
flag = true;
for (j = 0;j < len - i;j++)
{
if (a[j + 1].P > a[j].P || (a[j + 1].P == a[j].P) && (a[j + 1].num < a[j].num))
{
mouse temp;
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
flag = false;
}
}
if (flag) break;
}
}
<file_sep>/week1/1202.cpp
// 1202.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
struct linknode
{
int num;
linknode* next;
};
int main()
{
char x;
linknode* head1,* head2,* headsum, * p, * q, * rear;
head1 = rear = new linknode;
while (true)
{
x = cin.get();
if (x == '\n') break;
p = new linknode;
p->num = x - '0';
p->next = head1;
head1 = p;
}
rear->next = NULL;
head2 = rear = new linknode;
while (true)
{
x = cin.get();
if (x == '\n') break;
p = new linknode;
p->num = x - '0';
p->next = head2;
head2 = p;
}
rear->next = NULL;
linknode* m, * n;
m = head1;n = head2;
int sum = 0, up = 0, mod = 0;
headsum = rear = new linknode;
while (true)
{
p = new linknode;
if (m->next != NULL && n->next != NULL)
{
sum = m->num + n->num + up;
mod = sum % 10;
p->num = mod;
up = sum / 10;
m = m->next;
n = n->next;
}
else if (m->next == NULL && n->next != NULL)
{
sum = n->num + up;
mod = sum % 10;
p->num = mod;
up = sum / 10;
n = n->next;
}
else if (m->next != NULL && n->next == NULL)
{
sum = m->num + up;
mod = sum % 10;
p->num = mod;
up = sum / 10;
m = m->next;
}
else if (m->next == NULL && n->next == NULL && up !=0)
{
p->num = 1;
up = 0;
}
else break;
p->next = headsum;
headsum = p;
}
rear->next = NULL;
p = headsum;
while (p->next != NULL)
{
cout << p->num;
p = p->next;
}
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week3/1621.cpp
// 1621.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
int arr[1001][1001];
int sumof1[1001];
void QuickSort(int arr[], int low, int high)
{
int i, j, temp;
i = low;
j = high;
if (low < high)
{
temp = arr[low];
while (i != j)
{
while (j > i&& arr[j] >= temp)
{
--j;
}
if (i < j)
{
arr[i] = arr[j];
++i;
}
while (i < j && arr[i] < temp)
{
++i;
}
if (i < j)
{
arr[j] = arr[i];
--j;
}
}
arr[i] = temp;
QuickSort(arr, low, i - 1);
QuickSort(arr, i + 1, high);
}
}
int main()
{
int n;
char x;
cin >> n;
cin.get();
for (int i = 0;i < n;i++)
{
for (int j = 0;j < n;j++)
{
x = cin.get();
arr[i][j] = x - '0';
}
cin.get();
}
int max = -1;
for (int i = 0;i < n;i++)
{
for (int j = 0;j < n;j++) sumof1[j] = 0;
for (int j = 0;j < n;j++)
{
for (int k = i;k < n;k++)
{
if (arr[j][k]) sumof1[j]++;
else break;
}
}
QuickSort(sumof1, 0, n - 1);
for (int j = 0;j < n;j++)
if (sumof1[j] * (n - j) > max) max = sumof1[j] * (n - j);
}
cout << max;
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/mapA/map.hpp
/**
* implement a container like std::map
*/
#ifndef SJTU_MAP_HPP
#define SJTU_MAP_HPP
// only for std::less<T>
#include <functional>
#include <cstddef>
#include "utility.hpp"
#include "exceptions.hpp"
namespace sjtu {
template<
class Key,
class T,
class Compare = std::less<Key>
> class map {
public:
/**
* the internal type of data.
* it should have a default constructor, a copy constructor.
* You can use sjtu::map as value_type by typedef.
*/
typedef pair<const Key, T> value_type;
/**
* see BidirectionalIterator at CppReference for help.
*
* if there is anything wrong throw invalid_iterator.
* like it = map.begin(); --it;
* or it = map.end(); ++end();
*/
struct node
{
value_type* thedata;
// int s;
int h;
node* left;
node* right;
node* prev;
node* next;
node(value_type* d = NULL, int height = 1, node* l = NULL, node* r = NULL, node* pr = NULL, node* ne = NULL)
{
if (d != NULL) thedata = new value_type(*d);
else thedata = NULL;
// s = size;
h = height;
left = l;
right = r;
prev = pr;
next = ne;
}
~node() { delete thedata; }
};
class const_iterator;
class iterator
{
friend class const_iterator;
friend class map;
private:
const map* themap;
node* point;
/**
* TODO add data members
* just add whatever you want.
*/
public:
iterator()
{
themap = NULL;
point = NULL;
}
iterator(map* m, node* p)
{
themap = m;
point = p;
}
iterator(const iterator &other)
{
themap = other.themap;
point = other.point;
}
/**
* return a new iterator which pointer n-next elements
* even if there are not enough elements, just return the answer.
* as well as operator-
*/
/**
* TODO iter++
*/
iterator operator++(int)
{
iterator tmp(*this);
++(*this);
return tmp;
}
/**
* TODO ++iter
*/
iterator & operator++()
{
if (point == NULL || point->next == NULL) throw invalid_iterator();
point = point->next;
return *this;
}
/**
* TODO iter--
*/
iterator operator--(int)
{
iterator tmp(*this);
--(*this);
return tmp;
}
/**
* TODO --iter
*/
iterator & operator--()
{
if (point == NULL || point->prev == NULL) throw invalid_iterator();
point = point->prev;
return *this;
}
/**
* a operator to check whether two iterators are same (pointing to the same memory).
*/
value_type & operator*() const
{
return *(point->thedata);
}
bool operator==(const iterator &rhs) const
{
return (point == rhs.point && themap == rhs.themap);
}
bool operator==(const const_iterator &rhs) const
{
return (point == rhs.point && themap == rhs.themap);
}
/**
* some other operator for iterator.
*/
bool operator!=(const iterator &rhs) const
{
return (point != rhs.point || themap != rhs.themap);
}
bool operator!=(const const_iterator &rhs) const
{
return (point != rhs.point || themap != rhs.themap);
}
/**
* for the support of it->first.
* See <http://kelvinh.github.io/blog/2013/11/20/overloading-of-member-access-operator-dash-greater-than-symbol-in-cpp/> for help.
*/
value_type* operator->() const noexcept
{
return point->thedata;
}
};
class const_iterator
{
// it should has similar member method as iterator.
// and it should be able to construct from an iterator.
friend class iterator;
friend class map;
private:
const map* themap;
node* point;
// data members.
public:
const_iterator()
{
themap = NULL;
point = NULL;
}
const_iterator(const map* m, node* p)
{
themap = m;
point = p;
}
const_iterator(const const_iterator &other)
{
themap = other.themap;
point = other.point;
}
const_iterator(const iterator &other)
{
themap = other.themap;
point = other.point;
}
// And other methods in iterator.
// And other methods in iterator.
// And other methods in iterator.
const_iterator operator++(int)
{
const_iterator tmp(*this);
++(*this);
return tmp;
}
/**
* TODO ++iter
*/
const_iterator& operator++()
{
if (point == NULL || point->next == NULL) throw invalid_iterator();
point = point->next;
return *this;
}
/**
* TODO iter--
*/
const_iterator operator--(int)
{
const_iterator tmp(*this);
--(*this);
return tmp;
}
/**
* TODO --iter
*/
const_iterator& operator--()
{
if (point == NULL || point->prev == NULL) throw invalid_iterator();
point = point->prev;
return *this;
}
/**
* a operator to check whether two iterators are same (pointing to the same memory).
*/
value_type& operator*() const
{
return *(point->thedata);
}
bool operator==(const iterator& rhs) const
{
return (point == rhs.point && themap == rhs.themap);
}
bool operator==(const const_iterator& rhs) const
{
return (point == rhs.point && themap == rhs.themap);
}
/**
* some other operator for iterator.
*/
bool operator!=(const iterator& rhs) const
{
return (point != rhs.point || themap != rhs.themap);
}
bool operator!=(const const_iterator& rhs) const
{
return (point != rhs.point || themap != rhs.themap);
}
const value_type* operator->() const noexcept
{
return point->thedata;
}
};
private:
size_t sizeoftree;
node* root;
node* head;
node* tail;
Compare cmp;
public:
/**
* TODO two constructors
*/
map()
{
root = NULL;
head = new node;
tail = head;
sizeoftree = 0;
}
map(const map &other)
{
if (other.root == NULL)
{
root = NULL;
tail = new node;
head = tail;
sizeoftree = 0;
return;
}
else
{
root = new node;
root->thedata = new value_type(*(other.root->thedata));
sizeoftree = other.sizeoftree;
// root->s = other.root->s;
root->h = other.root->h;
tail = new node;
copy(root, other.root);
node* tmp = NULL;
middleline(root, tmp);
tmp->next = tail;
tail->prev = tmp;
}
}
void copy(node* a, node* b)
{
if (b->left != NULL)
{
a->left = new node;
a->left->thedata = new value_type(*(b->left->thedata));
// a->left->s = b->left->s;
a->left->h = b->left->h;
copy(a->left, b->left);
}
if (b->right != NULL)
{
a->right = new node;
a->right->thedata = new value_type(*(b->right->thedata));
// a->right->s = b->right->s;
a->right->h = b->right->h;
copy(a->right, b->right);
}
}
void middleline(node* cnt, node*& pr)
{
if (cnt->left != NULL) middleline(cnt->left, pr);
if (pr == NULL) head = cnt;
cnt->prev = pr;
if (pr != NULL) pr->next = cnt;
pr = cnt;
if (cnt->right != NULL) middleline(cnt->right, pr);
}
void cleartree(node* rot)
{
sizeoftree = 0;
if (rot == NULL) return;
else
{
cleartree(rot->left);
cleartree(rot->right);
delete rot;
}
}
/**
* TODO assignment operator
*/
map & operator=(const map &other)
{
if (this == &other) return *this;
clear();
sizeoftree = other.sizeoftree;
if (other.root == NULL) return *this;
else
{
root = new node;
root->thedata = new value_type(*(other.root->thedata));
// root->s = other.root->s;
root->h = other.root->h;
copy(root, other.root);
node* tmp = NULL;
middleline(root, tmp);
tmp->next = tail;
tail->prev = tmp;
return *this;
}
}
/**
* TODO Destructors
*/
~map()
{
clear();
// delete head;
delete tail;
}
node* findnode(const Key& key, node* rot)const
{
if (rot == NULL) return NULL;
else
{
if (cmp(key, rot->thedata->first)) return findnode(key, rot->left);
else if (cmp(rot->thedata->first, key)) return findnode(key, rot->right);
else return rot;
}
}
/**
* TODO
* access specified element with bounds checking
* Returns a reference to the mapped value of the element with key equivalent to key.
* If no such element exists, an exception of type `index_out_of_bound'
*/
T & at(const Key &key)
{
node* ans;
ans = findnode(key, root);
if (ans == NULL) throw index_out_of_bound();
else return ans->thedata->second;
}
const T & at(const Key &key) const
{
node* ans;
ans = findnode(key, root);
if (ans == NULL) throw index_out_of_bound();
else return ans->thedata->second;
}
/**
* TODO
* access specified element
* Returns a reference to the value that is mapped to a key equivalent to key,
* performing an insertion if such key does not already exist.
*/
T & operator[](const Key &key)
{
node* p = insert(pair<Key, T>(key, T())).first.point;
return p->thedata->second;
}
/**
* behave like at() throw index_out_of_bound if such key does not exist.
*/
const T & operator[](const Key &key) const
{
return at(T);
}
/**
* return a iterator to the beginning
*/
iterator begin()
{
return iterator(this, head);
}
const_iterator cbegin() const
{
return const_iterator(this, head);
}
/**
* return a iterator to the end
* in fact, it returns past-the-end.
*/
iterator end()
{
return iterator(this, tail);
}
const_iterator cend() const
{
return const_iterator(this, tail);
}
/**
* checks whether the container is empty
* return true if empty, otherwise false.
*/
bool empty() const
{
return (root == NULL);
}
/**
* returns the number of elements.
*/
size_t size() const
{
if (root != NULL) return sizeoftree;
else return 0;
}
/**
* clears the contents
*/
void clear()
{
cleartree(root);
delete tail;
tail = new node;
head = tail;
root = NULL;
}
node* insertnode(const value_type& value, node*& rot)
{
node* inserted;
if (rot == NULL)
{
sizeoftree++;
rot = new node;
rot->thedata = new value_type(value);
return rot;
}
else if (cmp(value.first, rot->thedata->first))
{
bool leftnull = false;
if (rot->left == NULL) leftnull = true;
inserted = insertnode(value, rot->left);
if (leftnull)
{
inserted->next = rot;
inserted->prev = rot->prev;
rot->prev = inserted;
if (inserted->prev == NULL) head = inserted;
else inserted->prev->next = inserted;
}
updatenode(rot);
if (getheight(rot->left) - getheight(rot->right) > 1)
{
if (cmp(value.first, rot->left->thedata->first)) LL(rot);
else LR(rot);
}
return inserted;
}
else
{
bool rightnull = false;
if (rot->right == NULL) rightnull = true;
inserted = insertnode(value, rot->right);
if (rightnull)
{
inserted->prev = rot;
inserted->next = rot->next;
rot->next = inserted;
inserted->next->prev = inserted;
}
updatenode(rot);
if (getheight(rot->right) - getheight(rot->left) > 1)
{
if (cmp(value.first, rot->right->thedata->first)) RL(rot);
else RR(rot);
}
return inserted;
}
}
/**
* insert an element.
* return a pair, the first of the pair is
* the iterator to the new element (or the element that prevented the insertion),
* the second one is true if insert successfully, or false.
*/
pair<iterator, bool> insert(const value_type &value)
{
node* trytofind = findnode(value.first, root);
if (trytofind != NULL) return pair<iterator, bool>(iterator(this, trytofind), false);
else
{
node* inserted = insertnode(value, root);
if (sizeoftree == 1)
{
head = inserted;
inserted->next = tail;
tail->prev = inserted;
}
return pair<iterator, bool>(iterator(this, inserted), true);
}
}
bool deletenode(node* target, node*& rot)
{
if (rot == NULL) return true;
if (cmp(target->thedata->first, rot->thedata->first))
{
if (deletenode(target, rot->left)) return true;
return adjust(rot, 0);
}
else if (cmp(rot->thedata->first, target->thedata->first))
{
if (deletenode(target, rot->right)) return true;
return adjust(rot, 1);
}
else
{
if (rot->left == NULL || rot->right == NULL)
{
sizeoftree--;
node* oldnode = rot;
if (rot == head)
{
head = head->next;
head->prev = NULL;
}
else
{
rot->prev->next = rot->next;
rot->next->prev = rot->prev;
}
if (rot->left == NULL && rot->right == NULL)
{
delete oldnode;
rot = NULL;
}
else if (rot->left != NULL)
{
rot = rot->left;
delete oldnode;
}
else if (rot->right != NULL)
{
rot = rot->right;
delete oldnode;
}
return false;
}
else
{
node* tmp = rot->right;
while (tmp->left != NULL) tmp = tmp->left;
delete rot->thedata;
rot->thedata = new value_type(*tmp->thedata);
if (deletenode(tmp, rot->right)) return true;
return adjust(rot, 1);
}
}
}
bool adjust(node*& rot, int subtree)
{
// rot->s--;
if (subtree)
{
if (getheight(rot->left) - getheight(rot->right) == 1)
{
return true;
}
if (getheight(rot->left) - getheight(rot->right) == 0)
{
rot->h--;
return false;
}
if (getheight(rot->left->right) > getheight(rot->left->left))
{
LR(rot);
return false;
}
else
{
LL(rot);
if (getheight(rot->left) - getheight(rot->right) == 0) return false;
else return true;
}
}
else
{
if (getheight(rot->right) - getheight(rot->left) == 1)
{
return true;
}
if (getheight(rot->right) - getheight(rot->left) == 0)
{
rot->h--;
return false;
}
if (getheight(rot->right->left) > getheight(rot->right->right))
{
RL(rot);
return false;
}
else
{
RR(rot);
if (getheight(rot->left) - getheight(rot->right) == 0) return false;
else return true;
}
}
}
/**
* erase the element at pos.
*
* throw if pos pointed to a bad element (pos == this->end() || pos points an element out of this)
*/
void erase(iterator pos)
{
if (pos.themap != this) throw invalid_iterator();
else if (pos.point == NULL) throw invalid_iterator();
else if (pos.point->thedata == NULL) throw invalid_iterator();
else deletenode(pos.point, root);
}
/**
* Returns the number of elements with key
* that compares equivalent to the specified argument,
* which is either 1 or 0
* since this container does not allow duplicates.
* The default method of check the equivalence is !(a < b || b > a)
*/
size_t count(const Key &key) const
{
node* tmp;
tmp = findnode(key, root);
if (tmp == NULL) return 0;
else return 1;
}
/**
* Finds an element with key equivalent to key.
* key value of the element to search for.
* Iterator to an element with key equivalent to key.
* If no such element is found, past-the-end (see end()) iterator is returned.
*/
iterator find(const Key &key)
{
node* tmp;
tmp = findnode(key, root);
if (tmp == NULL) return end();
else return iterator(this, tmp);
}
const_iterator find(const Key &key) const
{
node* tmp;
tmp = findnode(key, root);
if (tmp == NULL) return cend();
else return const_iterator(this, tmp);
}
int maxnum(int a, int b)
{
return (a > b) ? a : b;
}
int getheight(node* tmp)
{
return (tmp == NULL) ? 0 : tmp->h;
}
//int getsize(node* tmp)
//{
// return (tmp == NULL) ? 0 : tmp->s;
//}
void LL(node*& tmp)
{
node* t = tmp->left;
tmp->left = t->right;
t->right = tmp;
updatenode(tmp);
updatenode(t);
tmp = t;
}
void LR(node*& tmp)
{
RR(tmp->left);
LL(tmp);
}
void RL(node*& tmp)
{
LL(tmp->right);
RR(tmp);
}
void RR(node*& tmp)
{
node* t = tmp->right;
tmp->right = t->left;
t->left = tmp;
updatenode(tmp);
updatenode(t);
tmp = t;
}
void updatenode(node* rot)
{
rot->h = maxnum(getheight(rot->left), getheight(rot->right)) + 1;
// rot->s = getsize(rot->left) + getsize(rot->right) + 1;
}
};
}
#endif
<file_sep>/week6/4188.cpp
// 4188.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <cstring>
using namespace std;
class str
{
public:
long long len = 0;
long long size = 2;
char* data;
void doublespace()
{
char* tmp = data;
size += size >> 1;
data = new char[size];
for (long long i = 0;i <= len;++i)
{
data[i] = tmp[i];
}
delete[] tmp;
}
};
//long long gethash(long long l, long long r, char* m)
//{
// long long hash = 0;
// for (long long i = l;i <= r;++i)
// {
// hash = (hash * 53 + (m[i] - 'a' + 1)) % (19260817);
// }
// return hash;
//}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
long long N;
cin >> N;
str* name = new str[N];
long long** prehash = new long long* [N];
long long** endhash = new long long* [N];
cin.get();
for (long long i = 0;i < N;++i)
{
name[i].data = new char[2];
char x = cin.get();
while (x != '\n')
{
name[i].data[name[i].len] = x;
name[i].len++;
x = cin.get();
if (name[i].size == name[i].len) name[i].doublespace();
}
/* name[i].data[name[i].len] = '\n';
name[i].len++;
if (name[i].size <= name[i].len) name[i].doublespace();*/
prehash[i] = new long long[name[i].size];
prehash[i][0] = name[i].data[0] - 'a' + 1;
for (long long j = 1;j < name[i].len;++j)
{
prehash[i][j] = (prehash[i][j - 1] * 28 + (name[i].data[j] - 'a' + 1)) % (1000000007);
}
endhash[i] = new long long[name[i].size];
endhash[i][name[i].len - 1] = name[i].data[name[i].len - 1] - 'a' + 1;
for (long long j = name[i].len - 2;j >= 0;--j)
{
endhash[i][j] = (endhash[i][j + 1] * 28 + (name[i].data[j] - 'a' + 1)) % (1000000007);
}
}
long long M;
cin >> M;
while (M--)
{
long long op, x, y;
cin >> op;
if (op == 1)
{
bool flag = 0;
cin >> x;
x--;
for (long long i = 0;i < x;++i)
{
if (endhash[x][0] == endhash[i][0])
{
flag = 1;
break;
}
}
if (flag) cout << "yes" << '\n';
else cout << "no" << '\n';
}
if (op == 2)
{
cin >> x >> y;
x--;y--;
long long len = (name[x].len < name[y].len) ? name[x].len - 1 : name[y].len - 1;
for (long long i = len;i >= 0;--i)
{
if (prehash[x][i] == prehash[y][i])
{
cout << i + 1 << '\n';
break;
}
}
}
if (op == 3)
{
cin >> x >> y;
x--;y--;
if (name[x].len <= name[y].len)
{
long long a = name[x].len - 1;
long long b = name[y].len - 1;
for (long long i = 0;i <= a;++i)
{
if (endhash[x][i] == endhash[y][i + b - a])
{
cout << a - i + 1 << '\n';
break;
}
}
}
if (name[x].len > name[y].len)
{
long long a = name[x].len - 1;
long long b = name[y].len - 1;
for (long long i = 0;i <= b;++i)
{
if (endhash[x][i + a - b] == endhash[y][i])
{
cout << b - i + 1 << '\n';
break;
}
}
}
}
}
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
<file_sep>/week3/1599.cpp
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
//void checkinstack(char a[], int top);
bool checkmatch(char ch1, char ch2);
struct mystack
{
char data[1000002];
int top;
};
bool ok[1000002] = { false };
int main()
{
int n;
scanf("%d", &n);
mystack s;
s.top = 0;
mystack p;
p.top = 0;
for (int i = 0;i < n;++i)
{
int op;
scanf("%d", &op);
switch (op)
{
case 1:
char x;
scanf(" %c", &x);
s.data[s.top++] = x;
if (x == '(' || x == '[' || x == '{')
{
p.data[p.top++] = x;
ok[s.top - 1] = true;
}
else if (p.top >= 1 && checkmatch(p.data[p.top - 1], x))
{
p.top--;
ok[s.top - 1] = true;
}
else
{
p.data[p.top++] = x;
ok[s.top - 1] = false;
}
break;
case 2:
if (s.top > 0)
{
switch (s.data[s.top - 1])
{
case '(':case'[':case'{':
p.top--;
break;
case ')':
if (ok[s.top - 1])
{
p.data[p.top++] = '(';
}
else p.top--;
break;
case']':
if (ok[s.top - 1])
{
p.data[p.top++] = '[';
}
else p.top--;
break;
case'}':
if (ok[s.top - 1])
{
p.data[p.top++] = '{';
}
else p.top--;
break;
}
}
if (s.top > 0)
{
s.top--;
}
break;
case 3:
if (s.top > 0)
{
printf("%c\n", s.data[s.top - 1]);
}
break;
case 4:
if (p.top != 0) printf("NO\n");
else printf("YES\n");
break;
default:
break;
}
}
return 0;
}
bool checkmatch(char ch1, char ch2)
{
if (ch1 == '(' && ch2 == ')' || ch1 == '[' && ch2 == ']' || ch1 == '{' && ch2 == '}')
return true;
else return false;
}<file_sep>/week5/4232.cpp
// 4232.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <cstring>
using namespace std;
int node[800002];
int grades[200002];
int higher(int a, int b)
{
return (a > b ? a : b);
}
void build(int k,int l,int r)
{
if (l == r)
{
node[k] = grades[l];
return;
}
else
{
int m = (l + r) >> 1;
build(k << 1, l, m);
build(k << 1 | 1, m + 1, r);
node[k] = higher(node[k << 1], node[k << 1 | 1]);
}
}
void changegrade(int pos, int value, int k, int l, int r)
{
if (l == r)
{
node[k] = grades[l] = value;
}
else
{
int m = (l + r) >> 1;
if (pos <= m) changegrade(pos, value, k << 1, l, m);
else changegrade(pos, value, k << 1 | 1, m + 1, r);
node[k] = higher(node[k << 1], node[k << 1 | 1]);
}
}
int checkgrade(int A, int B,int k, int l, int r)
{
if (A <= l && B >= r) return node[k];
else
{
int tmp = -1;
int m = (l + r) >> 1;
if (A <= m) tmp = higher(checkgrade(A, B, k << 1, l, m), tmp);
if (B > m) tmp = higher(checkgrade(A, B, k << 1 | 1, m + 1, r), tmp);
return tmp;
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int N, M;
while (cin >> N >> M)
{
memset(node, 0, sizeof(node));
memset(grades, 0, sizeof(grades));
for (int i = 1;i <= N;++i) cin >> grades[i];
build(1, 1, N);
while (M--)
{
char op;
int A, B;
cin >> op >> A >> B;
if (op == 'Q') cout << checkgrade(A, B, 1, 1, N) << '\n';
if (op == 'U') changegrade(A, B, 1, 1, N);
}
}
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
| ab0df9dcd3f210960067b508f3c05712f8460e72 | [
"C++"
] | 82 | C++ | FlyingPolaris/Data-Structure | 8e76a97e89fb4279e493c5b46e3918e19eb926c5 | 310faeb274f8ef29aa5dbfd464839bbf108fe974 |
refs/heads/master | <file_sep>//
// BookDetailView.swift
// BookFinderCoreMl
//
// Created by vd-rahim on 5/6/18.
// Copyright © 2018 venturedive. All rights reserved.
//
import UIKit
import SDWebImage
class BookDetailView: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
var bookDetails:[BookDetailModel] = []
var delegate: BookDetailViewDelegate?
override func viewDidLoad() {
setupNib()
let singleFingerTap = UITapGestureRecognizer(target: self, action: #selector(BookDetailView.handleSingleTap(_:)))
self.view.addGestureRecognizer(singleFingerTap)
}
func setupNib(){
collectionView.register(UINib(nibName: "BookDetailViewCell", bundle: nil), forCellWithReuseIdentifier: "bookDetail")
}
@objc func handleSingleTap(_ sender: UITapGestureRecognizer) {
self.delegate?.dismissingView()
self.presentingViewController?.dismiss(animated: true, completion: nil)
}
}
extension BookDetailView: UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout{
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return bookDetails.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "bookDetail", for: indexPath) as! BookDetailViewCollectionViewCell
let url = bookDetails[indexPath.row].imgThumb ?? bookDetails[indexPath.row].imgSmallThumb
ImageLoader.sharedLoader.imageForUrl(urlString: url!, completionHandler:{(image: UIImage?, url: String) in
DispatchQueue.main.async {
cell.bookImage.image = image
}
})
cell.bookName.text = bookDetails[indexPath.row].bookName
cell.authorNames.text = (bookDetails[indexPath.row].author! as NSArray).componentsJoined(by: ", ")
cell.category.text = (bookDetails[indexPath.row].category! as NSArray).componentsJoined(by: ", ")
let myAttribute = [ NSAttributedStringKey.font: UIFont(name: "AppleSDGothicNeo-Bold", size: 16.0)! ]
let myString = NSMutableAttributedString(string: "Description: ", attributes: myAttribute )
let desc = bookDetails[indexPath.row].description
let attrString = NSAttributedString(string: desc ?? "")
myString.append(attrString)
let myRange = NSRange(location: 13, length: desc?.count ?? 0)
myString.addAttribute(NSAttributedStringKey.font, value: UIFont(name: "AppleSDGothicNeo-Medium", size: 16.0)! , range: myRange)
let eBook = bookDetails[indexPath.row].pdfLink
let buy = bookDetails[indexPath.row].buyLink
let preview = bookDetails[indexPath.row].previewLink
cell.eBookButton.isEnabled = false
cell.buyButton.isEnabled = false
cell.previewButton.isEnabled = false
cell.eBookButton.backgroundColor = #colorLiteral(red: 0.4352941176, green: 0.4431372549, blue: 0.4745098039, alpha: 1)
cell.buyButton.backgroundColor = #colorLiteral(red: 0.4352941176, green: 0.4431372549, blue: 0.4745098039, alpha: 1)
cell.previewButton.backgroundColor = #colorLiteral(red: 0.4352941176, green: 0.4431372549, blue: 0.4745098039, alpha: 1)
cell.bookDesc = bookDetails[indexPath.row]
if (eBook != nil) && (eBook?.count)! > 0{
cell.eBookButton.isEnabled = true
cell.eBookButton.backgroundColor = #colorLiteral(red: 0.3450980392, green: 0.7803921569, blue: 0.5843137255, alpha: 1)
}
if (buy != nil) && (buy?.count)! > 0{
cell.buyButton.isEnabled = true
cell.buyButton.backgroundColor = #colorLiteral(red: 0.3450980392, green: 0.7803921569, blue: 0.5843137255, alpha: 1)
}
if (preview != nil) && (preview?.count)! > 0{
cell.previewButton.isEnabled = true
cell.previewButton.backgroundColor = #colorLiteral(red: 0.3450980392, green: 0.7803921569, blue: 0.5843137255, alpha: 1)
}
cell.bookDescription.attributedText = myString
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: UIScreen.main.bounds.width - 10, height: UIScreen.main.bounds.height-100)
}
}
protocol BookDetailViewDelegate {
func dismissingView()
}
<file_sep>//
// ApiService.swift
// BookFinderCoreMl
//
// Created by vd-rahim on 5/6/18.
// Copyright © 2018 venturedive. All rights reserved.
//
import Foundation
import Alamofire
class ApiService{
static func fetchBooks(with bookName:String, completion: @escaping ([BookDetailModel]?) -> Void) {
guard let url = URL(string: "https://www.googleapis.com/books/v1/volumes?q=\(bookName.replacingOccurrences(of: " ", with: "+"))&key=<KEY>") else {
completion(nil)
return
}
Alamofire.request(url,
method: .get,
parameters: nil)
.validate()
.responseJSON { response in
guard response.result.isSuccess else {
print("Error while fetching remote rooms: \(String(describing: response.result.error))")
completion(nil)
return
}
guard let value = response.result.value as? [String: Any],
let row = value["items"] as? [[String:Any]] else {
print("Malformed data received from fetchAllRooms service")
completion(nil)
return
}
let books = row.flatMap { bookDict in return BookDetailModel(jsonData: bookDict) }
completion(books)
}
}
}
<file_sep>//
// bookDetailModel.swift
// BookFinderCoreMl
//
// Created by vd-rahim on 5/6/18.
// Copyright © 2018 venturedive. All rights reserved.
//
import Foundation
class BookDetailModel {
var bookName:String
var author:[String]!
var publisher:String!
var publishedDate: String!
var description:String!
var imgSmallThumb:String!
var imgThumb:String!
var previewLink: String!
var webReaderLink:String!
var pdfLink:String!
var buyLink:String!
var category:[String]!
init(jsonData:[String:Any]) {
let bookDesc = jsonData["volumeInfo"] as! [String:Any]
self.bookName = "\(bookDesc["title"] as? String ?? "") \(bookDesc["subtitle"] as? String ?? "")"
self.author = bookDesc["authors"] as? [String] ?? []
self.publisher = bookDesc["publisher"] as? String ?? ""
self.publishedDate = bookDesc["publishedDate"] as? String ?? ""
self.description = bookDesc["description"] as? String ?? ""
self.category = bookDesc["categories"] as? [String] ?? []
let bookImg = bookDesc["imageLinks"] as! [String:String]
self.imgSmallThumb = bookImg["smallThumbnail"] ?? ""
self.imgThumb = bookImg["thumbnail"] ?? ""
self.previewLink = bookDesc["previewLink"] as? String ?? ""
let accessInfo = jsonData["accessInfo"] as! [String:Any]
let pdf = accessInfo["pdf"] as! [String:Any]
if pdf["isAvailable"] as! Bool{
self.pdfLink = pdf["acsTokenLink"] as? String ?? ""
}
}
}
<file_sep>//
// BookDetailViewCollectionViewCell.swift
// BookFinderCoreMl
//
// Created by vd-rahim on 5/6/18.
// Copyright © 2018 Rahim. All rights reserved.
//
import UIKit
class BookDetailViewCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var bookImage: UIImageView!
@IBOutlet weak var bookName: UILabel!
@IBOutlet weak var authorNames: UILabel!
@IBOutlet weak var category: UILabel!
@IBOutlet weak var bookDescription: UITextView!
@IBOutlet weak var eBookButton: UIButton!
@IBOutlet weak var buyButton: UIButton!
@IBOutlet weak var previewButton: UIButton!
var bookDesc:BookDetailModel!
@IBAction func eBookButtonTapped(_ sender: UIButton) {
if let url = URL(string: bookDesc.pdfLink) {
UIApplication.shared.open(url)
print("default browser was successfully opened")
}
}
@IBAction func buyButtonTapped(_ sender: UIButton) {
if let url = URL(string: bookDesc.buyLink) {
UIApplication.shared.open(url)
print("default browser was successfully opened")
}
}
@IBAction func previewButtonTapped(_ sender: UIButton) {
if let url = URL(string: bookDesc.previewLink) {
UIApplication.shared.open(url)
print("default browser was successfully opened")
}
}
}
<file_sep># Book-Finder-with-CoreML
This is the implementation of Image Recognition using Custom model (Book cover images) on Apple's CoreML-2.0 Framework. And uses Google Books API to get similar books according to your searched book.
The app fetches frames from your camera at ~30 FPS and perform object recognition in almost real-time. And allow the user to read, download and buy that book.
## Requirements
- Xcode 9
- iOS 11
## Creating CoreML Model
I have used an online Microsoft tool to generate CoreMl model (https://www.customvision.ai/)
## Usage
To use this app, open **BookFinderCoreML.xcworkspace** in Xcode 9 and run it on a device with iOS 11. (Don't use simulator as it don't have access to camera).
## Results
These are the results of the app when tested on iPhone 7.

## Pods used
1. SDWebImage
2. Alamofire
<file_sep>//
// BookFinderViewController.swift
// RahimRepo
//
// Created by vd-rahim on 5/25/18.
// Copyright © 2018 Rahim. All rights reserved.
//
import UIKit
import CoreMedia
import Vision
class BookFinderViewController: UIViewController, UIImagePickerControllerDelegate {
// Outlets to label and view
@IBOutlet private weak var predictLabel: UILabel!
@IBOutlet private weak var previewView: UIView!
let bookImageModelMl = bookImageModel()
private var videoCapture: VideoCapture!
private var requests = [VNRequest]()
override func viewDidLoad() {
super.viewDidLoad()
setupVision()
let spec = VideoSpec(fps: 5, size: CGSize(width: 227, height: 227))
videoCapture = VideoCapture(cameraType: .back,
preferredSpec: spec,
previewContainer: previewView.layer)
videoCapture.imageBufferHandler = {[unowned self] (imageBuffer) in
self.handleImageBufferWithVision(imageBuffer: imageBuffer)
}
}
func handleImageBufferWithCoreML(imageBuffer: CMSampleBuffer) {
guard let pixelBuffer = CMSampleBufferGetImageBuffer(imageBuffer) else {
return
}
do {
let prediction = try self.bookImageModelMl.prediction(data: self.resize(pixelBuffer: pixelBuffer)!)
DispatchQueue.main.async {
if let prob = prediction.loss[prediction.classLabel] {
if prob>0.3{
self.predictLabel.text = "\(prediction.classLabel) \(String(describing: prob))"
ApiService.fetchBooks(with: prediction.classLabel, completion: { (bookModel:[BookDetailModel]!) in
})
}
}
}
}
catch let error as NSError {
fatalError("Unexpected error ocurred: \(error.localizedDescription).")
}
}
func handleImageBufferWithVision(imageBuffer: CMSampleBuffer) {
guard let pixelBuffer = CMSampleBufferGetImageBuffer(imageBuffer) else {
return
}
var requestOptions:[VNImageOption : Any] = [:]
if let cameraIntrinsicData = CMGetAttachment(imageBuffer, kCMSampleBufferAttachmentKey_CameraIntrinsicMatrix, nil) {
requestOptions = [.cameraIntrinsics:cameraIntrinsicData]
}
let imageRequestHandler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, orientation: CGImagePropertyOrientation(rawValue: UInt32(self.exifOrientationFromDeviceOrientation))!, options: requestOptions)
do {
try imageRequestHandler.perform(self.requests)
} catch {
print(error)
}
}
func setupVision() {
guard let visionModel = try? VNCoreMLModel(for: bookImageModelMl.model) else {
fatalError("can't load Vision ML model")
}
let classificationRequest = VNCoreMLRequest(model: visionModel) { (request: VNRequest, error: Error?) in
guard let observations = request.results else {
print("no results:\(error!)")
return
}
let classifications = observations[0...4]
.flatMap({ $0 as? VNClassificationObservation })
.filter({ $0.confidence > 0.3 })
.map({ "\($0.identifier) \($0.confidence)" })
DispatchQueue.main.async {
self.predictLabel.text = classifications.joined(separator: "\n")
var nameArray = classifications.first?.split(separator: " ")
nameArray?.removeLast()
if let count = nameArray?.count{
if count > 0 {
let name = (nameArray! as NSArray).componentsJoined(by: " ")
if (name != nil) {
self.videoCapture.stopCapture()
ApiService.fetchBooks(with: name, completion: { (bookModel:[BookDetailModel]!) in
let vc = BookDetailView(nibName:"BookDetailView" , bundle: nil)
vc.bookDetails = bookModel
vc.delegate = self
vc.modalPresentationStyle = .overCurrentContext
self.present(vc, animated: true, completion: nil)
})
}
}
}
}
}
classificationRequest.imageCropAndScaleOption = VNImageCropAndScaleOption.centerCrop
self.requests = [classificationRequest]
}
/// only support back camera
var exifOrientationFromDeviceOrientation: Int32 {
let exifOrientation: DeviceOrientation
enum DeviceOrientation: Int32 {
case top0ColLeft = 1
case top0ColRight = 2
case bottom0ColRight = 3
case bottom0ColLeft = 4
case left0ColTop = 5
case right0ColTop = 6
case right0ColBottom = 7
case left0ColBottom = 8
}
switch UIDevice.current.orientation {
case .portraitUpsideDown:
exifOrientation = .left0ColBottom
case .landscapeLeft:
exifOrientation = .top0ColLeft
case .landscapeRight:
exifOrientation = .bottom0ColRight
default:
exifOrientation = .right0ColTop
}
return exifOrientation.rawValue
}
/// resize CVPixelBuffer
///
/// - Parameter pixelBuffer: CVPixelBuffer by camera output
/// - Returns: CVPixelBuffer with size (227, 227)
func resize(pixelBuffer: CVPixelBuffer) -> CVPixelBuffer? {
let imageSide = 227
var ciImage = CIImage(cvPixelBuffer: pixelBuffer, options: nil)
let transform = CGAffineTransform(scaleX: CGFloat(imageSide) / CGFloat(CVPixelBufferGetWidth(pixelBuffer)), y: CGFloat(imageSide) / CGFloat(CVPixelBufferGetHeight(pixelBuffer)))
ciImage = ciImage.transformed(by: transform).cropped(to: CGRect(x: 0, y: 0, width: imageSide, height: imageSide))
let ciContext = CIContext()
var resizeBuffer: CVPixelBuffer?
CVPixelBufferCreate(kCFAllocatorDefault, imageSide, imageSide, CVPixelBufferGetPixelFormatType(pixelBuffer), nil, &resizeBuffer)
ciContext.render(ciImage, to: resizeBuffer!)
return resizeBuffer
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
guard let videoCapture = videoCapture else {return}
videoCapture.startCapture()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
guard let videoCapture = videoCapture else {return}
videoCapture.resizePreview()
}
override func viewWillDisappear(_ animated: Bool) {
guard let videoCapture = videoCapture else {return}
videoCapture.stopCapture()
navigationController?.setNavigationBarHidden(false, animated: true)
super.viewWillDisappear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
extension BookFinderViewController: BookDetailViewDelegate{
func dismissingView() {
self.videoCapture.startCapture()
}
}
<file_sep>//
// ImageLoader.swift
// BookFinderCoreMl
//
// Created by vd-rahim on 5/6/18.
// Copyright © 2018 Rahim. All rights reserved.
//
import Foundation
import UIKit
class ImageLoader {
let cache = NSCache<NSString, AnyObject>()
class var sharedLoader : ImageLoader {
struct Static {
static let instance : ImageLoader = ImageLoader()
}
return Static.instance
}
func imageForUrl(urlString: String, completionHandler: @escaping (_ image: UIImage?, _ url: String) -> ()) {
DispatchQueue.global(qos: .background).async {
let data: NSData? = self.cache.object(forKey: urlString as NSString) as? NSData
if let goodData = data {
let image = UIImage(data: goodData as Data)
DispatchQueue.main.async {
completionHandler(image, urlString)
}
return
}
let session = URLSession.shared
let request = URLRequest(url: URL(string: urlString)!);
session.dataTask(with: request) { data, response, error in
if (error != nil) {
completionHandler(nil, urlString)
return
}
if let data = data{
let image = UIImage(data: data)
self.cache.setObject(data as AnyObject, forKey: urlString as NSString)
DispatchQueue.main.async {
completionHandler(image, urlString)
}
}
}.resume()
}
}
}
| e59ca582305c8123e286cfd796b09733bbeab64a | [
"Swift",
"Markdown"
] | 7 | Swift | rahimkhalid/Book-Finder-with-CoreML | f61c6741acb2f99622d872a81697538f388074ba | 7be9c9503ef2a9274dec98cc5db97789404be4bf |
refs/heads/master | <file_sep># WP-PrettyEmbed
This plugin overrides the default WordPress YouTube embeds and uses Pretty Embed.
<file_sep><?php
/*
Plugin Name: WP Pretty Embeds (YouTube)
Plugin URI: https://github.com/sethrubenstein/WP-PrettyEmbed/
Description: Adds pretty embed (https://github.com/mike-zarandona/PrettyEmbed.js) support to the WP YouTube oEmbed class.
Version: 1.0
Author: <NAME>
Author URI: http://sethrubenstein.info
*/
function pretty_embed_load() {
// Check for jQuery
if ( !wp_script_is( 'jquery', 'enqueued' ) ) {
wp_enqueue_script( 'jquery' );
}
// Check for fitVids
if ( !wp_script_is( 'fitvids', 'enqueued' ) ) {
wp_register_script( 'fitvids', plugin_dir_url(__FILE__).'bower_components/fitvids/jquery.fitvids.js');
wp_enqueue_script( 'fitvids', array('jquery') );
}
wp_register_script( 'waitForImages', plugin_dir_url(__FILE__).'bower_components/waitForImages/dist/jquery.waitforimages.min.js' );
wp_enqueue_script( 'waitForImages', array('jquery') );
wp_register_script( 'pretty-embed', plugin_dir_url(__FILE__).'bower_components/pretty-embed/jquery.prettyembed.min.js' );
wp_enqueue_script( 'pretty-embed', array('jquery', 'waitForImages', 'fitvids') );
}
add_action( 'wp_enqueue_scripts', 'pretty_embed_load' );
function pretty_embed_init() {
if(is_singular()) {
$script = '<script>jQuery(document).ready(function(){ jQuery().prettyEmbed({ useFitVids: true }); });</script>';
echo $script;
}
}
add_action('wp_footer', 'pretty_embed_init');
function remove_youtube_controls($code){
if (!is_admin()) {
if(strpos($code, 'youtu.be') !== false || strpos($code, 'youtube.com') !== false){
if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $code, $match)) {
$video_id = $match[1];
$code = '<div class="pretty-embed" data-pe-videoid="'.$video_id.'" data-pe-previewsize="hd" data-pe-fitvids="true"></div>';
}
}
}
return $code;
}
add_filter('embed_handler_html', 'remove_youtube_controls');
add_filter('embed_oembed_html', 'remove_youtube_controls');
add_filter('oembed_result', 'remove_youtube_controls', 10, 3);
| cfa22f124c3b544ce131fde0213d832cb80ffdc9 | [
"Markdown",
"PHP"
] | 2 | Markdown | sethrubenstein/WP-PrettyEmbed | f448c3ad308d6dac7fc728340762f223dcaa4114 | d5d9790e3c1b2cad0e5408ef2f59f188876b31a4 |
refs/heads/master | <file_sep># jnp_poset
Imported from SVN repo. <br>
Second assignment for "Languages and tools for programming I". <br>
The project is written in team with my partner.
<file_sep>#include "poset.h"
#include <iostream>
#include <ios>
#include <string>
#include <optional>
#include <vector>
#include <stack>
#include <map>
#include <set>
#include <cassert>
namespace
{
using Node = std::pair<std::set<int>, std::set<int>>; // first: in edges, second: out edges
using Poset = std::tuple<std::map< std::string, int>, std::map<int, Node>, int>;
std::vector<std::optional<Poset>> &poset_list()
{
static std::vector<std::optional<Poset>> list;
return list;
}
std::stack<int> &available()
{
static std::stack<int> stack;
return stack;
}
void message(std::string message)
{
static std::ios_base::Init stream;
std::cerr << message << std::endl;
}
// Checks if arguments are correct, and prints error messages about wrong arguments
bool validArgument(unsigned int id, const char *value1, const char *value2, std::string function_name)
{
if (id >= poset_list().size() || !poset_list()[id].has_value())
{
message(function_name + ": poset " + std::to_string(id) + " does not exist");
return false;
}
if (value1 == nullptr)
message(function_name + ": invalid value1 (NULL)");
if (value2 == nullptr)
message(function_name + ": invalid value2 (NULL)");
if (value1 == nullptr || value2 == nullptr)
return false;
return true;
}
}
unsigned long jnp1::poset_new(void)
{
message("poset_new()");
Poset empty_poset;
int new_poset_index;
if (available().empty())
{
new_poset_index = poset_list().size();
poset_list().emplace_back(empty_poset);
}
else
{
new_poset_index = available().top();
available().pop();
poset_list()[new_poset_index] = empty_poset;
}
message("poset_new: poset " + std::to_string(new_poset_index) + " created");
return new_poset_index;
}
void jnp1::poset_delete(unsigned long id)
{
message("poset_delete(" + std::to_string(id) + ")");
if (validArgument(id, "VALID", "VALID", "poset_delete"))
{
poset_list()[id] = {};
available().push(id);
message("poset_delete: poset " + std::to_string(id) + " deleted");
}
}
std::size_t jnp1::poset_size(unsigned long id)
{
message("poset_size(" + std::to_string(id) + ")");
if (validArgument(id, "VALID", "VALID", "poset_size"))
{
auto &graph = std::get<1>(poset_list()[id].value());
std::size_t size = graph.size();
message("poset_size: poset " + std::to_string(id) + " contains "
+ std::to_string(size) + " element(s)");
return size;
}
return 0;
}
bool jnp1::poset_insert(unsigned long id, char const *value)
{
std::string name((value==nullptr)?"NULL":value);
message("poset_insert(" + std::to_string(id) + ", \"" + name + "\")");
if (!validArgument(id, value, "VALID", "poset_insert"))
return false;
auto &[string_to_int, graph, max_index] = poset_list()[id].value();
if (string_to_int.find(name) != string_to_int.end())
{
message("poset_insert: poset " + std::to_string(id) + ", element \""
+ name + "\" already exists");
return false;
}
graph[max_index].second.insert(max_index);
graph[max_index].first.insert(max_index);
string_to_int[name] = max_index++;
message("poset_insert: poset " + std::to_string(id)
+ ", element \"" + name + "\" added");
return true;
}
bool jnp1::poset_remove(unsigned long id, char const *value)
{
std::string element_name((value==nullptr)?"NULL":value);
message("poset_remove(" + std::to_string(id) + ", \"" + element_name + "\")");
if (!validArgument(id, value, "VALID", "poset_remove"))
return false;
auto &string_to_int = std::get<0>(poset_list()[id].value());
auto &graph = std::get<1>(poset_list()[id].value());
auto element_iterator = string_to_int.find(element_name);
if (element_iterator == string_to_int.end())
{
message("poset_remove: poset " + std::to_string(id) + ", element \""
+ element_name + "\" does not exist");
return false;
}
int index = element_iterator->second;
auto &[in, out] = graph[index];
for (auto iterator = in.begin(); iterator != in.end(); iterator++)
{
auto &other_out = graph[*iterator].second;
other_out.erase(other_out.find(index));
}
for (auto iterator = out.begin(); iterator != out.end(); iterator++)
{
auto &other_in = graph[*iterator].first;
other_in.erase(other_in.find(index));
}
graph.erase(index);
string_to_int.erase(element_iterator);
message("poset_remove: poset " + std::to_string(id)
+ ", element \"" + element_name + "\" removed");
return true;
}
bool jnp1::poset_add(unsigned long id, char const *value1, char const *value2)
{
std::string element1_name((value1==nullptr)?"NULL":value1);
std::string element2_name((value2==nullptr)?"NULL":value2);
message("poset_add(" + std::to_string(id) + ", \"" + element1_name + "\", \""
+ element2_name + "\")");
if (!validArgument(id, value1, value2, "poset_add"))
return false;
auto &string_to_int = std::get<0>(poset_list()[id].value());
auto &graph = std::get<1>(poset_list()[id].value());
auto element1_iterator = string_to_int.find(element1_name);
auto element2_iterator = string_to_int.find(element2_name);
if (element1_iterator == string_to_int.end()
|| element2_iterator == string_to_int.end())
{
message("poset_add: poset " + std::to_string(id) + ", element \""
+ element1_name + "\" or \"" + element2_name + "\" does not exist");
return false;
}
int index1 = element1_iterator->second;
int index2 = element2_iterator->second;
if (jnp1::poset_test(id, element1_name.c_str(), element2_name.c_str())
|| jnp1::poset_test(id, element2_name.c_str(), element1_name.c_str()))
{
message("poset_add: poset " + std::to_string(id) + ", relation (\""
+ element1_name + "\" ,\"" + element2_name + "\") cannot be added");
return false;
}
auto &in1 = graph[index1].first;
auto &out2 = graph[index2].second;
std::vector<int> in1_list;
std::vector<int> out2_list;
for (auto iterator = in1.begin(); iterator != in1.end(); iterator++)
in1_list.push_back(*iterator);
for (auto iterator = out2.begin(); iterator != out2.end(); iterator++)
out2_list.push_back(*iterator);
for (int a : in1_list)
{
auto &out_a = graph[a].second;
for (int b : out2_list)
{
auto &in_b = graph[b].first;
out_a.insert(b);
in_b.insert(a);
}
}
message("poset_add: poset " + std::to_string(id) + ", relation (\""
+ element1_name + "\" ,\"" + element2_name + "\") added");
return true;
}
bool jnp1::poset_del(unsigned long id, char const *value1, char const *value2)
{
std::string element1_name((value1==nullptr)?"NULL":value1);
std::string element2_name((value2==nullptr)?"NULL":value2);
message("poset_del(" + std::to_string(id) + ", \"" + element1_name + "\", \""
+ element2_name + "\")");
if(!validArgument(id, value1, value2, "poset_del"))
return false;
if (!poset_test(id, value1, value2))
{
message("poset_del: poset " + std::to_string(id) + ", relation (\""
+ element1_name + "\" ,\"" + element2_name + "\") cannot be deleted");
return false;
}
auto &string_to_int = std::get<0>(poset_list()[id].value());
auto &graph = std::get<1>(poset_list()[id].value());
auto &out = graph[string_to_int[element1_name]].second;
auto &in2 = graph[string_to_int[element2_name]].first;
int index1 = string_to_int[value1];
int index2 = string_to_int[value2];
if (index1 == index2)
{
message("poset_del: poset " + std::to_string(id) + ", relation (\""
+ element1_name + "\" ,\"" + element2_name + "\") cannot be deleted");
return false;
}
for (int outgoing : out)
{
if (outgoing != index1 && outgoing != index2 &&
graph[outgoing].second.find(index2) != graph[outgoing].second.end())
{
message("poset_del: poset " + std::to_string(id) + ", relation (\""
+ element1_name + "\" ,\"" + element2_name + "\") cannot be deleted");
return false;
}
}
out.erase(index2);
in2.erase(index1);
message("poset_del: poset " + std::to_string(id) + ", relation (\""
+ element1_name + "\" ,\"" + element2_name + "\") deleted");
return true;
}
bool jnp1::poset_test(unsigned long id, char const *value1, char const *value2)
{
std::string name1((value1==nullptr)?"NULL":value1);
std::string name2((value2==nullptr)?"NULL":value2);
message("poset_test(" + std::to_string(id) + ", \"" + name1 + "\", \""
+ name2 + "\")");
if (!validArgument(id, value1, value2, "poset_test"))
return false;
auto &string_to_int = std::get<0>(poset_list()[id].value());
auto &graph = std::get<1>(poset_list()[id].value());
auto element1_iterator = string_to_int.find(name1);
auto element2_iterator = string_to_int.find(name2);
if (element1_iterator == string_to_int.end() ||
element2_iterator == string_to_int.end())
{
message("poset_test: poset " + std::to_string(id) + ", element \""
+ name1 + "\" or \"" + name2 + "\" does not exist");
return false;
}
int index2 = element2_iterator -> second;
int index1 = element1_iterator -> second;
auto &out = graph[index1].second;
if (out.find(index2) != out.end())
{
message("poset_test: poset " + std::to_string(id) + ", relation (\""
+ name1 + "\" ,\"" + name2 + "\") exists");
return true;
}
else
{
message("poset_test: poset " + std::to_string(id) + ", relation (\""
+ name1 + "\" ,\"" + name2 + "\") does not exixt");
return false;
}
}
void jnp1::poset_clear(unsigned long id)
{
message("poset_clear(" + std::to_string(id) + ")");
if (!validArgument(id, "VALID", "VALID", "poset_clear"))
return;
auto &[string_to_int, graph, max_index] = poset_list()[id].value();
string_to_int.clear();
graph.clear();
max_index = 0;
message("poset_new: poset " + std::to_string(id) + " cleared");
}
<file_sep>#ifndef POSET_H
#define POSET_H
#ifdef __cplusplus
#include <cstddef>
namespace jnp1
{
extern "C"
{
#else // __cplusplus
#include <stddef.h>
#include <stdbool.h>
#endif // __cplusplus
unsigned long poset_new(void);
void poset_delete(unsigned long id);
size_t poset_size(unsigned long id);
bool poset_insert(unsigned long id, char const *value);
bool poset_remove(unsigned long id, char const *value);
bool poset_add(unsigned long id, char const *value1, char const *value2);
bool poset_del(unsigned long id, char const *value1, char const *value2);
bool poset_test(unsigned long id, char const *value1, char const *value2);
void poset_clear(unsigned long id);
#ifdef __cplusplus
}
}
#endif // __cplusplus
#endif // POSET_H | 90be95e82ca25cbd31eff4cd8f762e468be46a54 | [
"Markdown",
"C++"
] | 3 | Markdown | ccocz/poset | 492a5b00634cae3bca5b816e7fafc671d0460d36 | ba9ac0de58a49777cae73329df132998fa7d1081 |
refs/heads/master | <file_sep>sudo cp ./70-u2f.rules /etc/udev/rules.d/ -v
sudo udevadm control --reload-rules && udevadm trigger
<file_sep>/*
* Copyright (c) 2016, <NAME>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*
* u2f_atecc.c
* platform specific functionality for implementing U2F
*
*/
#include "app.h"
#undef U2F_DISABLE
#ifndef U2F_DISABLE
#include "bsp.h"
#include "gpio.h"
#include "u2f.h"
#include "u2f_hid.h"
#include "eeprom.h"
#include "atecc508a.h"
static void gen_u2f_zero_tag(uint8_t * dst, uint8_t * appid, uint8_t * handle);
static struct u2f_hid_msg res;
static uint8_t* resbuf = (uint8_t*)&res;
static uint8_t resseq = 0;
static uint8_t serious = 0;
void u2f_response_writeback(uint8_t * buf, uint16_t len)
{
u2f_hid_writeback(buf, len);
}
void u2f_response_flush()
{
watchdog();
u2f_hid_flush();
}
void u2f_response_start()
{
watchdog();
}
void clear_button_press(){
led_on();
BUTTON_RESET_ON();
do {
watchdog();
u2f_delay(6); //6ms activation time + 105ms maximum sleep in NORMAL power mode
} while (IS_BUTTON_PRESSED()); // Wait to release button
BUTTON_RESET_OFF();
led_off();
}
int8_t u2f_get_user_feedback()
{
uint32_t t;
uint8_t user_presence = 0;
clear_button_press();
led_blink(LED_BLINK_NUM_INF, 375);
watchdog();
t = get_ms();
while(button_get_press() == 0) // Wait to push button
{
led_blink_manager(); // Run led driver to ensure blinking
button_manager(); // Run button driver
if (get_ms() - t > U2F_MS_USER_INPUT_WAIT) // 3 secs elapsed without button press
break; // Timeout
u2f_delay(10);
watchdog();
#ifdef FAKE_TOUCH
if (get_ms() - t > 1010) break; //1212
#endif
}
#ifndef FAKE_TOUCH
if (button_get_press() == 1)
#else //FAKE_TOUCH
if (true)
#endif
{
// Button has been pushed in time
user_presence = 1;
led_off();
#ifdef SHOW_TOUCH_REGISTERED
t = get_ms();
while(get_ms() - t < 110){
led_on();
u2f_delay(12);
led_off();
u2f_delay(25);
}
led_off();
#endif
} else { // Button hasnt been pushed within the timeout
led_off();
user_presence = 0; // Return error code
}
clear_button_press();
return user_presence? 0 : 1;
}
int8_t u2f_ecdsa_sign(uint8_t * dest, uint8_t * handle, uint8_t * appid)
{
struct atecc_response res;
uint16_t slot = U2F_TEMP_KEY_SLOT;
if (handle == U2F_ATTESTATION_HANDLE)
{
slot = U2F_ATTESTATION_KEY_SLOT;
}
if( atecc_send_recv(ATECC_CMD_SIGN,
ATECC_SIGN_EXTERNAL, slot, NULL, 0,
appdata.tmp, 70, &res) != 0)
{
return -1;
}
memmove(dest, res.buf, 64);
return 0;
}
// bad if this gets interrupted
int8_t u2f_new_keypair(uint8_t * handle, uint8_t * appid, uint8_t * pubkey)
{
struct atecc_response res;
uint8_t private_key[36];
int i;
watchdog();
if (atecc_send_recv(ATECC_CMD_RNG,ATECC_RNG_P1,ATECC_RNG_P2,
NULL, 0,
appdata.tmp,
sizeof(appdata.tmp), &res) != 0 )
{
return -1; //U2F_SW_CUSTOM_RNG_GENERATION
}
SHA_HMAC_KEY = U2F_DEVICE_KEY_SLOT;
SHA_FLAGS = ATECC_SHA_HMACSTART;
u2f_sha256_start();
u2f_sha256_update(appid,32);
u2f_sha256_update(res.buf,4);
SHA_FLAGS = ATECC_SHA_HMACEND;
u2f_sha256_finish();
memmove(handle, res.buf, 4); // size of key handle must be 36
memset(private_key,0,4);
memmove(private_key+4, res_digest.buf, 32);
eeprom_xor(EEPROM_DATA_RMASK, private_key+4, 32);
watchdog();
compute_key_hash(private_key, EEPROM_DATA_WMASK, U2F_TEMP_KEY_SLOT);
memmove(handle+4, res_digest.buf, 32); // size of key handle must be 36+28
if ( atecc_privwrite(U2F_TEMP_KEY_SLOT, private_key, EEPROM_DATA_WMASK, handle+4) != 0)
{
return -2; // U2F_SW_CUSTOM_PRIVWRITE
}
memset(private_key,0,36);
if ( atecc_send_recv(ATECC_CMD_GENKEY,
ATECC_GENKEY_PUBLIC, U2F_TEMP_KEY_SLOT, NULL, 0,
appdata.tmp, 70, &res) != 0)
{
return -3; // U2F_SW_CUSTOM_GENKEY
}
memmove(pubkey, res.buf, 64);
// the + 28/U2F_KEY_HANDLE_ID_SIZE
gen_u2f_zero_tag(handle + U2F_KEY_HANDLE_KEY_SIZE, appid, handle);
return 0;
}
int8_t u2f_load_key(uint8_t * handle, uint8_t * appid)
{
uint8_t private_key[36];
watchdog();
SHA_HMAC_KEY = U2F_DEVICE_KEY_SLOT;
SHA_FLAGS = ATECC_SHA_HMACSTART;
u2f_sha256_start();
u2f_sha256_update(appid,32);
u2f_sha256_update(handle,4);
SHA_FLAGS = ATECC_SHA_HMACEND;
u2f_sha256_finish();
memset(private_key,0,4);
memmove(private_key+4, res_digest.buf, 32);
eeprom_xor(EEPROM_DATA_RMASK, private_key+4, 32);
return atecc_privwrite(U2F_TEMP_KEY_SLOT, private_key, EEPROM_DATA_WMASK, handle+4);
}
static void gen_u2f_zero_tag(uint8_t * dst, uint8_t * appid, uint8_t * handle)
{
SHA_HMAC_KEY = U2F_DEVICE_KEY_SLOT;
SHA_FLAGS = ATECC_SHA_HMACSTART;
u2f_sha256_start();
u2f_sha256_update(handle,U2F_KEY_HANDLE_KEY_SIZE);
eeprom_read(EEPROM_DATA_U2F_CONST, appdata.tmp, U2F_CONST_LENGTH);
u2f_sha256_update(appdata.tmp,U2F_CONST_LENGTH);
memset(appdata.tmp, 0, U2F_CONST_LENGTH);
u2f_sha256_update(appid,32);
SHA_FLAGS = ATECC_SHA_HMACEND;
u2f_sha256_finish();
if (dst) memmove(dst, res_digest.buf, U2F_KEY_HANDLE_ID_SIZE);
}
int8_t u2f_appid_eq(uint8_t * handle, uint8_t * appid)
{
gen_u2f_zero_tag(NULL,appid, handle);
return memcmp(handle+U2F_KEY_HANDLE_KEY_SIZE, res_digest.buf, U2F_KEY_HANDLE_ID_SIZE);
}
uint32_t u2f_count()
{
struct atecc_response res;
atecc_send_recv(ATECC_CMD_COUNTER,
ATECC_COUNTER_INC, ATECC_COUNTER0,NULL,0,
appdata.tmp, sizeof(appdata.tmp), &res);
return le32toh(*(uint32_t*)res.buf);
}
extern uint16_t __attest_size;
extern code char __attest[];
uint8_t * u2f_get_attestation_cert()
{
return __attest;
}
uint16_t u2f_attestation_cert_size()
{
return __attest_size;
}
void set_response_length(uint16_t len)
{
u2f_hid_set_len(len);
}
#endif
<file_sep>/*
* Copyright (c) 2016, <NAME>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* atecc508.c
* Implementation for ATECC508 peripheral.
*
*/
#include <endian.h>
#include <stdint.h>
#include "app.h"
#include "atecc508a.h"
#include "i2c.h"
#include "eeprom.h"
#include "gpio.h"
#include "bsp.h"
uint8_t shabuf[70];
uint8_t shaoffset = 0;
uint8_t SHA_FLAGS = 0;
uint8_t SHA_HMAC_KEY = 0;
struct atecc_response res_digest;
#ifdef ATECC_SETUP_DEVICE
// 1 page - 64 bytes
struct DevConf device_configuration;
int8_t read_masks(){
u2f_prints("reading masks -----\r\n");
memset(&device_configuration, 42, sizeof(device_configuration));
eeprom_read(EEPROM_DATA_RMASK, device_configuration.RMASK, sizeof(device_configuration.RMASK));
eeprom_read(EEPROM_DATA_WMASK, device_configuration.WMASK, sizeof(device_configuration.WMASK));
u2f_prints("current write key: "); dump_hex(device_configuration.WMASK,36);
u2f_prints("current read key: "); dump_hex(device_configuration.RMASK,36);
}
int8_t write_masks(){
eeprom_erase(EEPROM_DATA_RMASK);
eeprom_erase(EEPROM_DATA_WMASK);
eeprom_write(EEPROM_DATA_RMASK, device_configuration.RMASK, sizeof(device_configuration.RMASK));
eeprom_write(EEPROM_DATA_WMASK, device_configuration.WMASK, sizeof(device_configuration.WMASK));
}
#endif
uint8_t atecc_used = 0;
int8_t atecc_send(uint8_t cmd, uint8_t p1, uint16_t p2,
uint8_t * buf, uint8_t len)
{
static data uint8_t params[6];
params[0] = 0x3;
params[1] = 7+len;
params[2] = cmd;
params[3] = p1;
params[4] = ((uint8_t*)&p2)[1];
params[5] = ((uint8_t* )&p2)[0];
smb_set_ext_write(buf, len);
smb_write( ATECC508A_ADDR, params, sizeof(params));
if (SMB_WAS_NACKED())
{
return -1;
}
return 0;
}
void atecc_idle()
{
smb_write( ATECC508A_ADDR, "\x02", 1);
}
void atecc_sleep()
{
smb_write( ATECC508A_ADDR, "\x01", 1);
}
void atecc_wake()
{
smb_write( ATECC508A_ADDR, "\0\0", 2);
}
#define PKT_CRC(buf, pkt_len) (htole16(*((uint16_t*)(buf+pkt_len-2))))
int8_t atecc_recv(uint8_t * buf, uint8_t buflen, struct atecc_response* res)
{
uint8_t pkt_len;
pkt_len = smb_read( ATECC508A_ADDR,buf,buflen);
if (SMB_WAS_NACKED())
{
return -1;
}
if (SMB_FLAGS & SMB_READ_TRUNC)
{
set_app_error(ERROR_READ_TRUNCATED);
return -1;
}
if (pkt_len <= buflen && pkt_len >= 4)
{
if (PKT_CRC(buf,pkt_len) != SMB_crc)
{
set_app_error(ERROR_I2C_CRC);
return -1;
}
}
else
{
set_app_error(ERROR_I2C_BAD_LEN);
return -1;
}
if (pkt_len == 4 && buf[1] != 0)
{
set_app_error(buf[1]);
return -1;
}
if (res != NULL)
{
res->len = pkt_len - 3;
res->buf = buf+1;
}
return pkt_len;
}
static void delay_cmd(uint8_t cmd)
{
uint8_t d = 0;
switch(cmd)
{
case ATECC_CMD_COUNTER:
d = 20; break;
case ATECC_CMD_GENDIG:
d = 11; break;
case ATECC_CMD_INFO:
d = 1; break;
case ATECC_CMD_LOCK:
d = 32; break;
case ATECC_CMD_NONCE:
d = 7; break;
case ATECC_CMD_PRIVWRITE:
d = 48; break;
case ATECC_CMD_READ:
d = 1; break;
case ATECC_CMD_RNG:
d = 23; break;
case ATECC_CMD_SHA:
d = 9; break;
case ATECC_CMD_WRITE:
d = 26; break;
case ATECC_CMD_SIGN:
d = 50; break;
case ATECC_CMD_GENKEY:
d = 115; break;
default:
d = 58; break;
}
u2f_delay(d/4+1);
}
int8_t atecc_send_recv(uint8_t cmd, uint8_t p1, uint16_t p2,
uint8_t* tx, uint8_t txlen, uint8_t * rx,
uint8_t rxlen, struct atecc_response* res)
{
uint8_t errors = 0;
uint16_t errarr[20]; //store error codes for debugging
memset(errarr, 0, sizeof(errarr));
atecc_used = 1;
atecc_wake();
u2f_delay(5);
resend:
set_app_error(ERROR_NOTHING);
while(atecc_send(cmd, p1, p2, tx, txlen) == -1)
{
errarr[errors] = 0x1000+get_app_error();
errors++;
if (errors > 8)
{
return -1;
}
}
while(atecc_recv(rx,rxlen, res) == -1)
{
errarr[errors] = 0x2000+get_app_error();
errors++;
if (errors > 16)
{
return -2;
}
switch(get_app_error())
{
case ERROR_NOTHING:
delay_cmd(cmd);
break;
case ERROR_ATECC_WATCHDOG:
atecc_idle();
u2f_delay(5);
atecc_wake();
u2f_delay(5);
goto resend;
break;
case ERROR_ATECC_WAKE:
u2f_delay(1);
goto resend;
break;
default:
u2f_delay(10);
goto resend;
break;
}
}
atecc_idle();
return 0;
}
void u2f_sha256_start()
{
shaoffset = 0;
atecc_send_recv(ATECC_CMD_SHA,
SHA_FLAGS, SHA_HMAC_KEY,NULL,0,
shabuf, sizeof(shabuf), NULL);
SHA_HMAC_KEY = 0;
}
void u2f_sha256_update(uint8_t * buf, uint8_t len)
{
uint8_t i = 0;
watchdog();
while(len--)
{
shabuf[shaoffset++] = *buf++;
if (shaoffset == 64)
{
atecc_send_recv(ATECC_CMD_SHA,
ATECC_SHA_UPDATE, 64,shabuf,64,
shabuf, sizeof(shabuf), NULL);
shaoffset = 0;
}
}
}
void u2f_sha256_finish()
{
if (SHA_FLAGS == 0) SHA_FLAGS = ATECC_SHA_END;
atecc_send_recv(ATECC_CMD_SHA,
SHA_FLAGS, shaoffset,shabuf,shaoffset,
shabuf, sizeof(shabuf), &res_digest);
SHA_FLAGS = 0;
}
/**
* Makes hash of PRIVWRITE(slot) command's payload, key and mask
* out: internal ATECC's TempKey buffer
*/
void compute_key_hash(uint8_t * key, uint16_t mask, int slot)
{
eeprom_read(mask, appdata.tmp, 32);
u2f_sha256_start();
u2f_sha256_update(appdata.tmp, 32);
// key must start with 4 zeros
memset(appdata.tmp,0,28);
memmove(appdata.tmp + 28, key, 36);
appdata.tmp[0] = ATECC_CMD_PRIVWRITE;
appdata.tmp[1] = ATECC_PRIVWRITE_ENC;
appdata.tmp[2] = slot;
appdata.tmp[3] = 0;
appdata.tmp[4] = 0xee;
appdata.tmp[5] = 0x01;
appdata.tmp[6] = 0x23;
u2f_sha256_update(appdata.tmp,28 + 36);
u2f_sha256_finish();
}
#define CWH_ZEROES_COUNT (25)
#define CWH_HEADER_LEN (7)
#define CWH_WMASK_LEN (32)
#define CWH_DATA_LEN (32)
void compute_write_hash(uint8_t * key, uint16_t mask, int slot)
{
// Compute hash from encrypted WRITE. See chapter 9.21 from complete data sheet.
// SHA-256(TempKey, Opcode, Param1, Param2, SN<8>, SN<0:1>, <25 bytes of zeros>, PlainTextData)
eeprom_read(mask, appdata.tmp, CWH_WMASK_LEN);
u2f_sha256_start();
u2f_sha256_update(appdata.tmp, CWH_WMASK_LEN);
memset(appdata.tmp,0,CWH_HEADER_LEN+CWH_ZEROES_COUNT);
memmove(appdata.tmp +CWH_HEADER_LEN+CWH_ZEROES_COUNT, key, CWH_DATA_LEN);
// ATECC_RW_DATA|ATECC_RW_EXT, ATECC_EEPROM_DATA_SLOT(U2F_DEVICE_KEY_SLOT)
appdata.tmp[0] = ATECC_CMD_WRITE;
appdata.tmp[1] = ATECC_RW_DATA|ATECC_RW_EXT;
appdata.tmp[2] = slot;
appdata.tmp[3] = 0;
appdata.tmp[4] = 0xee; //FIXME SN values for ATECC508A, might not work on other model
appdata.tmp[5] = 0x01;
appdata.tmp[6] = 0x23;
u2f_sha256_update(appdata.tmp,CWH_HEADER_LEN+CWH_ZEROES_COUNT +CWH_DATA_LEN);
u2f_sha256_finish();
}
int atecc_prep_encryption()
{
struct atecc_response res;
memset(appdata.tmp,0,32);
if( atecc_send_recv(ATECC_CMD_NONCE,ATECC_NONCE_TEMP_UPDATE,0,
appdata.tmp, 32,
appdata.tmp, 40, &res) != 0 )
{
u2f_prints("pass through to tempkey failed\r\n");
return -1;
}
if( atecc_send_recv(ATECC_CMD_GENDIG,
ATECC_RW_DATA, U2F_WKEY_KEY_SLOT, NULL, 0,
appdata.tmp, 40, &res) != 0)
{
u2f_prints("GENDIG failed\r\n");
return -1;
}
return 0;
}
int atecc_privwrite(uint16_t keyslot, uint8_t * key, uint16_t mask, uint8_t * digest)
{
struct atecc_response res;
uint8_t i;
atecc_prep_encryption();
memmove(appdata.tmp, key, 36);
eeprom_xor(mask, appdata.tmp, 36);
memmove(appdata.tmp+36, digest, 32);
if( atecc_send_recv(ATECC_CMD_PRIVWRITE,
ATECC_PRIVWRITE_ENC, keyslot, appdata.tmp, 68,
appdata.tmp, 40, &res) != 0)
{
u2f_prints("PRIVWRITE failed\r\n");
return -1;
}
return 0;
}
#ifdef ATECC_SETUP_DEVICE
int8_t atecc_write_eeprom(uint8_t base, uint8_t offset, uint8_t* srcbuf, uint8_t len)
{
uint8_t buf[7];
struct atecc_response res;
uint8_t * dstbuf = srcbuf;
if (offset + len > 4)
return -1;
if (len < 4)
{
atecc_send_recv(ATECC_CMD_READ,
ATECC_RW_CONFIG, base, NULL, 0,
buf, sizeof(buf), &res);
dstbuf = res.buf;
memmove(res.buf + offset, srcbuf, len);
}
atecc_send_recv(ATECC_CMD_WRITE,
ATECC_RW_CONFIG, base, dstbuf, 4,
buf, sizeof(buf), &res);
if (res.buf[0])
{
set_app_error(-res.buf[0]);
return -1;
}
return 0;
}
static uint8_t get_signature_length(uint8_t * sig)
{
return 0x46 + ((sig[32] & 0x80) == 0x80) + ((sig[0] & 0x80) == 0x80);
}
static void dump_signature_der(uint8_t * sig)
{
uint8_t pad_s = (sig[32] & 0x80) == 0x80;
uint8_t pad_r = (sig[0] & 0x80) == 0x80;
uint8_t i[] = {0x30, 0x44};
uint8_t sigbuf[120];
i[1] += (pad_s + pad_r);
// DER encoded signature
// write der sequence
// has to be minimum distance and padded with 0x00 if MSB is a 1.
memmove(sigbuf,i,2);
i[1] = 0;
// length of R value plus 0x00 pad if necessary
memmove(sigbuf+2,"\x02",1);
i[0] = 0x20 + pad_r;
memmove(sigbuf+3,i,1 + pad_r);
// R value
memmove(sigbuf+3+1+pad_r,sig, 32);
// length of S value plus 0x00 pad if necessary
memmove(sigbuf+3+1+pad_r+32,"\x02",1);
i[0] = 0x20 + pad_s;
memmove(sigbuf+3+1+pad_r+32+1,i,1 + pad_s);
// S value
memmove(sigbuf+3+1+pad_r+32+1+1+pad_s,sig+32, 32);
// u2f_prints("signature-der: "); dump_hex(sigbuf, get_signature_length(sig));
}
static int is_config_locked(uint8_t * buf)
{
struct atecc_response res;
atecc_send_recv(ATECC_CMD_READ,
ATECC_RW_CONFIG,87/4, NULL, 0,
buf, 36, &res);
u2f_prints("is_config_locked "); dump_hex(res.buf, res.len);
if (res.buf[87 % 4] == 0)
return 1;
else
return 0;
}
static int is_data_locked(uint8_t * buf)
{
struct atecc_response res;
atecc_send_recv(ATECC_CMD_READ,
ATECC_RW_CONFIG,86/4, NULL, 0,
buf, 36, &res);
u2f_prints("is_data_locked "); dump_hex(res.buf, res.len);
if (res.buf[86 % 4] == 0)
return 1;
else
return 0;
}
static void dump_config(uint8_t* buf)
{
uint8_t i,j;
uint16_t crc = 0;
struct atecc_response res;
uint8_t config_data[128];
struct atecc_slot_config *c;
struct atecc_key_config *d;
//See 2.2 EEPROM Configuration Zone of ATECC508A Complete Data Sheet
const int slot_config_offset = 20;
const int key_config_offset = 96;
const int slot_config_size = sizeof(struct atecc_slot_config);
const int key_config_size = sizeof(struct atecc_key_config);
#ifndef U2F_PRINT
return;
#endif
u2f_prints("config dump:\r\n");
for (i=0; i < 4; i++)
{
if ( atecc_send_recv(ATECC_CMD_READ,
ATECC_RW_CONFIG | ATECC_RW_EXT, i << 3, NULL, 0,
buf, 40, &res) != 0)
{
u2f_prints("read failed\r\n");
}
for(j = 0; j < res.len; j++)
{
crc = feed_crc(crc,res.buf[j]);
}
dump_hex(res.buf,res.len);
memmove(config_data+i*32, res.buf, 32);
}
u2f_printx("current config crc:", 1,reverse_bits(crc));
#define _PRINT(x) u2f_printb(#x": ", 1, x)
for (i=0; i<16; i++){
u2f_printb("Slot config: ", 1, i);
c = (struct atecc_slot_config*) (config_data + slot_config_offset + i * slot_config_size);
u2f_prints("hex: "); dump_hex(c,2);
_PRINT(c->writeconfig);
_PRINT(c->writekey);
_PRINT(c->secret);
_PRINT(c->encread);
_PRINT(c->limiteduse);
_PRINT(c->nomac);
_PRINT(c->readkey);
u2f_printb("Key config: ", 1, i);
d = (struct atecc_key_config *) (config_data + key_config_offset + i * key_config_size);
u2f_prints("hex: "); dump_hex(d,2);
_PRINT(d->x509id);
_PRINT(d->rfu);
_PRINT(d->intrusiondisable);
_PRINT(d->authkey);
_PRINT(d->reqauth);
_PRINT(d->reqrandom);
_PRINT(d->lockable);
_PRINT(d->keytype);
_PRINT(d->pubinfo);
_PRINT(d->private);
}
#undef _PRINT
}
static void atecc_setup_config(uint8_t* buf)
{
uint8_t i;
// struct atecc_slot_config c;
uint8_t * slot_configs = "\x83\x71"
"\x81\x01"
"\x83\x71"
"\xC1\x01"
"\x83\x71"
"\x83\x71"
"\x83\x71"
"\xC1\x71"
"\x01\x01"
"\x83\x71"
"\x83\x71"
"\xC1\x71"
"\x83\x71"
"\x83\x71"
"\x83\x71"
"\x83\x71";
uint8_t * key_configs = "\x13\x00"
"\x3C\x00"
"\x13\x00"
"\x3C\x00"
"\x13\x00"
"\x3C\x00"
"\x13\x00"
"\x3C\x00"
"\x3C\x00"
"\x3C\x00"
"\x13\x00"
"\x3C\x00"
"\x13\x00"
"\x3C\x00"
"\x13\x00"
"\x33\x00";
// write configuration
for (i = 0; i < 16; i++)
{
if ( atecc_write_eeprom(ATECC_EEPROM_SLOT(i), ATECC_EEPROM_SLOT_OFFSET(i), slot_configs+i*2, ATECC_EEPROM_SLOT_SIZE) != 0)
{
u2f_printb("1 atecc_write_eeprom failed ",1, i);
}
if ( atecc_write_eeprom(ATECC_EEPROM_KEY(i), ATECC_EEPROM_KEY_OFFSET(i), key_configs+i*2, ATECC_EEPROM_KEY_SIZE) != 0)
{
u2f_printb("2 atecc_write_eeprom failed " ,1,i);
}
}
dump_config(buf);
}
static uint8_t trans_key[36];
static uint8_t write_key[36];
#ifdef ENABLE_TESTS
void atecc_test_enc_read(uint8_t * buf)
{
struct atecc_response res;
memset(trans_key,0x5a,sizeof(trans_key));
u2f_prints("plaintext: "); dump_hex(trans_key, 32);
if( atecc_send_recv(ATECC_CMD_WRITE,
ATECC_RW_DATA|ATECC_RW_EXT, ATECC_EEPROM_DATA_SLOT(3), trans_key, 32,
buf, 40, &res) != 0)
{
u2f_prints("writing test key failed\r\n");
return;
}
atecc_prep_encryption();
if (atecc_send_recv(ATECC_CMD_READ,
ATECC_RW_DATA | ATECC_RW_EXT, ATECC_EEPROM_DATA_SLOT(3), NULL, 0,
buf, 40, &res) != 0)
{
u2f_prints("READ slot 3 failed\r\n");
return;
}
else
{
u2f_prints("ciphertext: "); dump_hex(res.buf, 32);
}
}
void atecc_test_signature(int keyslot, uint8_t * buf)
{
struct atecc_response res;
if ( atecc_send_recv(ATECC_CMD_GENKEY,
ATECC_GENKEY_PUBLIC, keyslot, NULL, 0,
appdata.tmp, 70, &res) != 0)
{
u2f_prints("GENKEY public failed\r\n");
return;
}
u2f_prints("pubkey: "); dump_hex(res.buf, 64);
u2f_prints("signing input: "); dump_hex(res_digest.buf, 32);
if( atecc_send_recv(ATECC_CMD_NONCE,ATECC_NONCE_TEMP_UPDATE,0,
res_digest.buf, 32,
buf, 40, &res) != 0 )
{
u2f_prints("signing pass through to tempkey failed\r\n");
return;
}
if( atecc_send_recv(ATECC_CMD_SIGN,
ATECC_SIGN_EXTERNAL, keyslot, NULL, 0,
appdata.tmp, 70, &res) != 0)
{
u2f_prints("signing failed\r\n");
return;
}
dump_signature_der(res.buf);
}
#endif
void atecc_setup_init(uint8_t * buf)
{
// 13s watchdog
WDTCN = 7;
dump_config(buf);
if (!is_config_locked(buf))
{
u2f_prints("setting up config...\r\n");
atecc_setup_config(buf);
}
else
{
u2f_prints("already locked\r\n");
}
}
uint8_t generate_random_data(uint8_t *out_buf){
struct atecc_response res;
if (atecc_send_recv(ATECC_CMD_RNG,ATECC_RNG_P1,ATECC_RNG_P2,
NULL, 0,
appdata.tmp, sizeof(appdata.tmp),
&res) == 0 )
{
memmove(out_buf, res.buf, 32);
return 0;
}
return 1;
}
void generate_mask(uint8_t *output, uint8_t wkey){
u2f_prints("generating mask ... "); dump_hex(&wkey,1);
if (generate_random_data(output+32) != 0){
u2f_prints("failed\r\n");
output[0] = 0;
return;
}
u2f_prints("generated random output+32: "); dump_hex(output+32,32);
if (wkey == 1){
memmove(trans_key, output+32, 32);
u2f_prints("generated trans_key: "); dump_hex(trans_key,32);
if(atecc_send_recv(ATECC_CMD_WRITE,
ATECC_RW_DATA|ATECC_RW_EXT, ATECC_EEPROM_DATA_SLOT(U2F_MASTER_KEY_SLOT),
trans_key, 32,
output, 32, NULL) != 0)
{
u2f_prints("writing master key/wkey failed\r\n");
return;
}
}
u2f_sha256_start();
u2f_sha256_update(output+32, 32);
memset(output, 0, 64);
output[0] = 0x15;
output[1] = 0x02;
output[2] = 0x01;
output[3] = 0;
output[4] = 0xee;
output[5] = 0x01;
output[6] = 0x23;
u2f_sha256_update(output, 64);
u2f_sha256_finish();
memmove(output, res_digest.buf, 32);
u2f_prints("generated key mask output: "); dump_hex(output,32);
//stage 2
u2f_sha256_start();
u2f_sha256_update(output, 32);
u2f_sha256_finish();
memmove(output+32, res_digest.buf, 8);
u2f_prints("generated key mask2 output: "); dump_hex(output+32,8);
u2f_prints("generated key mask: "); dump_hex(output,32+8);
}
void generate_device_key(uint8_t *output, uint8_t *buf, uint8_t buflen){
u2f_prints("generating device key ... ");
if (generate_random_data(trans_key) == 0){
u2f_prints("succeed\r\n");
output[0] = 1;
} else {
u2f_prints("failed\r\n");
output[0] = 0;
return;
}
#ifndef _PRODUCTION_RELEASE
u2f_prints("device key: "); dump_hex(trans_key,32);
memmove(output+1, trans_key, 16);
#endif
compute_write_hash(trans_key, EEPROM_DATA_WMASK, ATECC_EEPROM_DATA_SLOT(U2F_DEVICE_KEY_SLOT));
atecc_prep_encryption();
memmove(appdata.tmp, trans_key, 32);
memmove(appdata.tmp+32, res_digest.buf, 32);
eeprom_xor(EEPROM_DATA_WMASK, appdata.tmp, 32);
if(atecc_send_recv(ATECC_CMD_WRITE,
ATECC_RW_DATA|ATECC_RW_EXT, ATECC_EEPROM_DATA_SLOT(U2F_DEVICE_KEY_SLOT),
appdata.tmp, 32+32,
buf, buflen, NULL) != 0)
{
output[0] = 2; //failed, stage 2, key writing
u2f_prints("writing device key failed\r\n");
return;
}
u2f_prints("writing device key succeed\r\n");
// generate u2f_zero_const
generate_random_data(buf);
eeprom_erase(EEPROM_DATA_U2F_CONST);
eeprom_write(EEPROM_DATA_U2F_CONST, buf, U2F_CONST_LENGTH);
#ifndef _PRODUCTION_RELEASE
u2f_prints("u2f_zero_const: "); dump_hex(buf,U2F_CONST_LENGTH);
memmove(output+1+32, buf, 16);
SHA_HMAC_KEY = U2F_DEVICE_KEY_SLOT;
SHA_FLAGS = ATECC_SHA_HMACSTART;
u2f_sha256_start();
u2f_sha256_update("successful write test");
SHA_FLAGS = ATECC_SHA_HMACEND;
u2f_sha256_finish();
memmove(output+1+16, res_digest.buf, 16);
#endif
}
typedef struct atecc_command{
uint8_t opcode;
uint8_t P1;
uint8_t P2;
uint8_t data_length;
uint8_t buf[64-4];
} atecc_cmd;
// buf should be at least 40 bytes
void atecc_setup_device(struct config_msg * msg)
{
struct atecc_response res;
struct config_msg usbres;
static uint16_t crc = 0;
int i;
uint8_t buf[40];
memset(&usbres, 0, sizeof(struct config_msg));
usbres.cmd = msg->cmd;
u2f_prints("incoming msg: "); dump_hex(msg,64);
switch(msg->cmd)
{
#ifndef _PRODUCTION_RELEASE
case U2F_CONFIG_ATECC_PASSTHROUGH:
{
atecc_cmd* cmd = (atecc_cmd*)msg->buf;
uint8_t err = atecc_send_recv(cmd->opcode,
cmd->P1, cmd->P2, cmd->buf, cmd->data_length,
buf, sizeof(buf), &res);
memset(usbres.buf, 0, sizeof(usbres.buf));
memmove(usbres.buf+1, res.buf, res.len);
usbres.buf[0] = err;
} break;
#endif
case U2F_CONFIG_GET_SERIAL_NUM:
u2f_prints("U2F_CONFIG_GET_SERIAL_NUM\r\n");
atecc_send_recv(ATECC_CMD_READ,
ATECC_RW_CONFIG | ATECC_RW_EXT, 0, NULL, 0,
buf, 40, &res);
memmove(usbres.buf+1, res.buf, 15);
usbres.buf[0] = 15;
break;
case U2F_CONFIG_LOAD_TRANS_KEY:
u2f_prints("U2F_CONFIG_LOAD_TRANS_KEY\r\n");
u2f_prints("Use U2F_CONFIG_LOAD_WRITE_KEY\r\n");
break;
case U2F_CONFIG_IS_BUILD:
u2f_prints("U2F_CONFIG_IS_BUILD\r\n");
usbres.buf[0] = 1;
break;
case U2F_CONFIG_IS_CONFIGURED:
u2f_prints("U2F_CONFIG_IS_CONFIGURED\r\n");
usbres.buf[0] = 1;
break;
case U2F_CONFIG_LOCK:
crc = *(uint16_t*)msg->buf;
usbres.buf[0] = 1;
u2f_printx("got crc: ",1,crc);
if (!is_config_locked(buf))
{
if (atecc_send_recv(ATECC_CMD_LOCK,
ATECC_LOCK_CONFIG, crc, NULL, 0,
buf, sizeof(buf), NULL))
{
u2f_prints("ATECC_CMD_LOCK config failed\r\n");
return;
}
}
else
{
u2f_prints("config already locked\r\n");
}
if (!is_data_locked(buf))
{
if (atecc_send_recv(ATECC_CMD_LOCK,
ATECC_LOCK_DATA_OTP | 0x80, crc, NULL, 0,
buf, sizeof(buf), NULL))
{
u2f_prints("ATECC_CMD_LOCK data failed\r\n");
return;
}
}
else
{
u2f_prints("data already locked\r\n");
}
break;
case U2F_CONFIG_LOAD_RMASK_KEY:
u2f_prints("U2F_CONFIG_LOAD_RMASK_KEY\r\n");
u2f_prints("current read key: "); dump_hex(device_configuration.RMASK,36);
generate_mask(appdata.tmp, 0);
memmove(device_configuration.RMASK,appdata.tmp,36);
write_masks();
read_masks();
u2f_prints("new set read key: "); dump_hex(device_configuration.RMASK,36);
usbres.buf[0] = 1;
memmove(usbres.buf+1,device_configuration.RMASK,36);
break;
case U2F_CONFIG_LOAD_WRITE_KEY:
u2f_prints("U2F_CONFIG_LOAD_WRITE_KEY\r\n");
u2f_prints("current write key: "); dump_hex(device_configuration.WMASK,36);
generate_mask(appdata.tmp, 1);
memmove(write_key,appdata.tmp,36);
memmove(device_configuration.WMASK,appdata.tmp,36);
write_masks();
read_masks();
u2f_prints("new set write key: "); dump_hex(device_configuration.WMASK,36);
usbres.buf[0] = 1;
memmove(usbres.buf + 1 , device_configuration.WMASK, 36);
break;
case U2F_CONFIG_GEN_DEVICE_KEY:
u2f_prints("U2F_CONFIG_GEN_DEVICE_KEY\r\n");
generate_device_key(usbres.buf, appdata.tmp, sizeof(appdata.tmp));
break;
#ifndef _PRODUCTION_RELEASE
case U2F_CONFIG_GET_SLOTS_FINGERPRINTS:
usbres.buf[0] = 0;
for (i=0; i<16; i++){
SHA_HMAC_KEY = i;
SHA_FLAGS = ATECC_SHA_HMACSTART;
u2f_sha256_start();
u2f_sha256_update("successful write test");
SHA_FLAGS = ATECC_SHA_HMACEND;
u2f_sha256_finish();
if (get_app_error() == ERROR_NOTHING)
memmove(usbres.buf+i*3+1, res_digest.buf, 3);
}
usbres.buf[0] = 1;
set_app_error(ERROR_NOTHING);
break;
#endif
case U2F_CONFIG_LOAD_ATTEST_KEY:
u2f_prints("U2F_CONFIG_LOAD_ATTEST_KEY\r\n");
//reusing trans_key buffer for the attestation key upload
memset(trans_key,0,36);
memmove(trans_key+4,msg->buf,32);
usbres.buf[0] = 1;
compute_key_hash(trans_key, EEPROM_DATA_WMASK, U2F_ATTESTATION_KEY_SLOT);
u2f_prints("write key: "); dump_hex(write_key,36);
if (atecc_privwrite(U2F_ATTESTATION_KEY_SLOT, trans_key, EEPROM_DATA_WMASK, res_digest.buf) != 0)
{
// The slot indicated by this command must be configured via KeyConfig.Private to contain an ECC private
// key, and SlotConfig.IsSecret must be set to one, or else this command will return an error. If the slot is
// individually locked using SlotLocked, then this command will also return an error.
u2f_prints("load attest key failed\r\n");
usbres.buf[0] = 0;
}
break;
case U2F_CONFIG_BOOTLOADER_DESTROY:
eeprom_erase(EEPROM_PAGE_START(EEPROM_LAST_PAGE_NUM-0));
eeprom_erase(EEPROM_PAGE_START(EEPROM_LAST_PAGE_NUM-1));
eeprom_erase(EEPROM_PAGE_START(EEPROM_LAST_PAGE_NUM-2));
usbres.buf[0] = 1;
led_blink(1, 100);
break;
default:
u2f_printb("invalid command: ",1,msg->cmd);
usbres.buf[0] = 0;
}
usb_write((uint8_t*)&usbres, HID_PACKET_SIZE);
memset(msg, 0, 64);
}
#endif
| a20c4b8ead6721d655aff7bc4ba60f09a6cfe8b1 | [
"C",
"Shell"
] | 3 | Shell | evaluation-alex/nitrokey-fido-u2f-firmware | ecc043cf13ea4840d0e89b54dc15512a1cf701f5 | 09c3fe7a8a200681acfce33ca3bb19f4bf9cea1d |
refs/heads/master | <file_sep>app.controller("myController",function($scope){
//var countParent = 1;
var countChild = 1;
$scope.parentStatus=[
{"assignTask":"Completed","child":[{"id":countChild}]},
{"assignTask":"Pending","child":[{"id":countChild}]},
{"assignTask":"In Progress","child":[{"id":countChild}]}
]
$scope.addTask = function(id)
{
$scope.parentStatus[id].child.push({})
}
$scope.addNewStatus = function()
{
$scope.assignTask = window.prompt("Please Enter Name Of Status","")
$scope.parentStatus.push({"assignTask":$scope.assignTask,"child":[{"id":countChild}]})
}
$scope.remove = function(parentId,childId)
{
$scope.parentStatus[parentId].child.splice(childId,1)
}
$scope.deleteAllCards = function()
{
$scope.parentStatus = [];
}
$scope.deleteAllTaskOfStatus = function(id)
{
$scope.parentStatus[id].child = [];
}
$scope.deleteThisStatus = function(id)
{
$scope.parentStatus.splice(id,1);
}
}); | ea04f634ea021e925d323a83ba55a5908cb7bee8 | [
"JavaScript"
] | 1 | JavaScript | yogain123/Task-2 | b2c32f18146b34fb2bdd4351b0e6b1ec94d1b381 | 41a9e081f3b169e9d1bcabba67c6d4e959a0a6e4 |
refs/heads/master | <repo_name>AndreRamosGit/SchoolManagement<file_sep>/schoolmanagementsystem/src/main/java/entity/Mark.java
package entity;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
@Entity
@Table(name="mark")
public class Mark {
@Id
@GeneratedValue
private Long id;
@NotBlank
private String fkSubject;
@NotBlank
private Long fkPersonId;
@NotBlank
private Float grade;
public Mark() {
super();
}
public Mark(Long id, String subject, Long personId, Float grade) {
super();
this.id = id;
this.fkSubject = subject;
fkPersonId = personId;
this.grade = grade;
}
public String getSubject() {
return fkSubject;
}
public void setSubject(String subject) {
this.fkSubject = subject;
}
public Long getPersonId() {
return fkPersonId;
}
public void setPersonId(Long personId) {
fkPersonId = personId;
}
public Float getGrade() {
return grade;
}
public void setGrade(Float grade) {
this.grade = grade;
}
@Override
public String toString() {
return "Mark [subject=" + fkSubject + ", PersonId=" + fkPersonId + ", grade=" + grade + "]";
}
}<file_sep>/schoolmanagementsystem/src/main/java/entity/Login.java
package entity;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.validation.constraints.NotBlank;
@Entity
@Table(name = "Login")
public class Login {
@NotBlank
private long personID;
@NotBlank
private String hash;
Login(long personID, String hash){
this.hash = hash;
this.personID = personID;
}
public long getPersonID() {
return personID;
}
public void setPersonID(long personID) {
this.personID = personID;
}
public String getHash() {
return hash;
}
public void setHash(String hash) {
this.hash = hash;
}
@Override
public String toString() {
return "Login [personID=" + personID + ", hash=" + hash + "]";
}
}
| 8c1cf08020c1e383c8f49b975f5198b697ee3ccc | [
"Java"
] | 2 | Java | AndreRamosGit/SchoolManagement | 54717f9adc9054338e20b7d5f341e3a92ab64002 | 95a488be83cb2ee33357366a57a620f2aaf0cf2e |
refs/heads/master | <repo_name>tetradice/SakuraBridgePrototype2<file_sep>/Library/Base/CommonStatusCode.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SakuraBridge.Library
{
/// <summary>
/// レスポンスで使用する一般的なステータスを表す定数クラス
/// </summary>
public static class CommonStatusCode
{
/// <summary>
/// 正常
/// </summary>
public const int OK = 200;
/// <summary>
/// 正常/結果なし
/// </summary>
public const int NoContent = 204;
/// <summary>
/// 不正なリクエスト
/// </summary>
public const int BadRequest = 400;
/// <summary>
/// サーバが未実装
/// </summary>
public const int NotImplemented = 501;
/// <summary>
/// サーバがリクエストを受け付けられない状態
/// </summary>
public const int ServiceUnavailable = 503;
#region スタティックコンストラクタ
/// <summary>
/// ステータス説明文
/// </summary>
public static Dictionary<int, string> ExplanationMap;
static CommonStatusCode()
{
ExplanationMap = new Dictionary<int, string>();
ExplanationMap.Add(OK, "OK");
ExplanationMap.Add(NoContent, "NoContent");
ExplanationMap.Add(BadRequest, "Bad Request");
ExplanationMap.Add(NotImplemented, "Not Implemented");
ExplanationMap.Add(ServiceUnavailable, "Service Unavailable");
}
#endregion
}
}
<file_sep>/Base/ModuleClassFinder.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace SakuraBridge.Base
{
/// <summary>
/// module dll (アセンブリ) 内からモジュールクラスを探し出すクラスのインターフェース
/// </summary>
public interface IModuleClassFinder
{
/// <summary>
/// module dll (アセンブリ) 内から全モジュールクラスの名前を取得
/// </summary>
string[] GetModuleClassFullNames(string moduleAssemblyPath);
}
/// <summary>
/// module dll (アセンブリ) 内からモジュールクラスを探し出すクラス (モジュールドメイン下で実行される)
/// </summary>
public class ModuleClassFinder : MarshalByRefObject, IModuleClassFinder
{
/// <summary>
/// module dll (アセンブリ) 内からモジュールクラスを探し出し、配列として返す
/// </summary>
public virtual string[] GetModuleClassFullNames(string moduleAssemblyPath)
{
Assembly asm = Assembly.LoadFrom(moduleAssemblyPath);
string iModuleName = typeof(IModule).FullName;
List<string> moduleFullNames = new List<string>();
foreach (Type t in asm.GetTypes())
{
// アセンブリ内のすべての型について、publicなModuleクラスであるかどうかを調べる
if (t.IsClass && t.IsPublic && !t.IsAbstract && t.GetInterface(iModuleName) != null)
{
// Moduleクラスであれば、その名前を追加
moduleFullNames.Add(t.FullName);
}
}
// 見つかった名前をすべて返す
return moduleFullNames.ToArray();
}
}
}
<file_sep>/Base/IModule.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SakuraBridge.Base
{
/// <summary>
/// 実際にリクエストを処理するモジュールクラスのインターフェース
/// </summary>
public interface IModule
{
/// <summary>
/// DLLのロード時に呼び出される処理です。
/// </summary>
/// <param name="dllDirPath">bridge.dll が存在するフォルダのパス</param>
void Load(string dllDirPath);
/// <summary>
/// DLLのアンロード時に呼び出される処理です。
/// </summary>
void Unload();
/// <summary>
/// リクエスト受信時に呼び出される処理です。
/// </summary>
/// <param name="msg">リクエスト文字列</param>
/// <returns>レスポンス文字列</returns>
string Request(string msg);
}
}
<file_sep>/Library/Plugin/PluginResponse.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace SakuraBridge.Library
{
/// <summary>
/// PLUGIN/2.0 レスポンス
/// </summary>
public class PluginResponse : Response
{
/// <summary>
/// バージョン
/// </summary>
public override string Version { get { return "PLUGIN/2.0"; } }
/// <summary>
/// コンストラクタ
/// </summary>
/// <param name="statusCode">ステータスコード。ここで指定した値に応じて、ステータス説明文も自動設定される</param>
public PluginResponse(int statusCode) : base(statusCode)
{
}
/// <summary>
/// Eventヘッダ
/// </summary>
public virtual string Event
{
get { return this["Event"]; }
set { this["Event"] = value; }
}
/// <summary>
/// Scriptヘッダ
/// </summary>
public virtual string Script
{
get { return this["Script"]; }
set { this["Script"] = value; }
}
#region staticメンバ
public static PluginResponse OK()
{
return new PluginResponse(CommonStatusCode.OK);
}
#endregion
}
}
<file_sep>/Library/Base/Request.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace SakuraBridge.Library
{
/// <summary>
/// SHIORI/SAORI/PLUGINリクエストの基底クラス
/// </summary>
public abstract class Request : Message
{
/// <summary>
/// コマンド文字列 (例: "GET PLUGIN/2.0")
/// </summary>
public abstract string Command { get; }
/// <summary>
/// Senderヘッダ
/// </summary>
public virtual string Sender
{
get { return this["Sender"]; }
set { this["Sender"] = value; }
}
/// <summary>
/// 文字列化
/// </summary>
public override string ToString()
{
var lines = new List<string>();
lines.Add(Command);
foreach (var name in HeaderNames)
{
lines.Add(string.Format("{0}: {1}", name, this[name]));
}
return string.Join("\r\n", lines) + "\r\n\r\n";
}
#region staticメンバ
/// <summary>
/// リクエスト文字列をパースする
/// </summary>
/// <param name="message">パース対象のリクエスト文字列</param>
/// <param name="versionCaption">パース対象のリクエストバージョン表記。例外発生時に表示される</param>
/// <param name="CommandCheckFunc">コマンド行が正しいかどうかを判定する関数</param>
/// <param name="RequestSetupFunc">リクエストに必要な初期値をセットする関数。ヘッダのセット後に、コマンド行、リクエストを引数として呼ばれる</param>
public static TReq Parse<TReq>(
string message,
string versionCaption,
Func<string, bool> CommandCheckFunc,
Action<string, TReq> RequestSetupFunc = null
)
where TReq : Request, new()
{
var headerPattern = new Regex(Message.HeaderPattern);
if (message == null) throw new ArgumentNullException("message");
// メッセージを改行で分割
var lines = message.Split(new[] { "\r\n" }, StringSplitOptions.None);
// 1行目のコマンド行が正しければ有効メッセージ
if (CommandCheckFunc.Invoke(lines[0]))
{
var req = new TReq();
// 2行目以降の行をパース
for (var i = 1; i < lines.Length; i++)
{
var line = lines[i];
// 空行ならその時点で終了
if (line == "") return req;
// ヘッダとして解析
var matched = headerPattern.Match(line);
if (matched.Success)
{
var name = matched.Groups[1].Value;
var value = matched.Groups[2].Value;
req[name] = value;
}
else
{
throw new BadRequestException(string.Format("リクエストの{0}行目にヘッダではない行が含まれています。", i + 1));
}
}
// リクエストの初期設定
if (RequestSetupFunc != null) RequestSetupFunc.Invoke(lines[0], req);
// 空行が見つからずに終わった場合も結果を返す
return req;
}
else
{
throw new BadRequestException(string.Format("有効な {0} リクエストではありません。 (コマンド行: {1})", versionCaption, lines[0]));
}
}
#endregion
}
}
<file_sep>/BridgeTest/BridgeTestPlugin/TestModule.cs
using SakuraBridge.Library;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BridgeTest
{
public class TestModule : PluginModule
{
protected AppDomain FormAppDomain;
public override PluginResponse OnMenuExec(PluginRequest req)
{
var res = PluginResponse.OK();
res.Script = @"\0OnMenuExecイベントが呼び出されました。\e";
FormAppDomain = AppDomain.CreateDomain("子画面");
Task.Run(() =>
{
FormAppDomain.ExecuteAssembly(Path.Combine(DLLDirPath, "BridgeTestForm.exe"));
});
return res;
}
public override void Unload()
{
base.Unload();
if (FormAppDomain != null)
{
AppDomain.Unload(FormAppDomain);
}
}
}
}
<file_sep>/Library/Base/Module.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Permissions;
using System.Text;
using System.Threading.Tasks;
using SakuraBridge.Base;
namespace SakuraBridge.Library
{
/// <summary>
/// モジュールの基底クラス
/// </summary>
public abstract class ModuleBase : MarshalByRefObject, IModule
{
/// <inheritdoc />
[SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.Infrastructure)]
public override object InitializeLifetimeService()
{
// 起動後しばらく経っても開放されないように、生存期間を無期限とする
// 参考: <https://stackoverflow.com/questions/2410221/appdomain-and-marshalbyrefobject-life-time-how-to-avoid-remotingexception>
return null;
}
/// <inheritdoc />
public abstract void Load(string dllDirPath);
/// <inheritdoc />
public abstract string Request(string msg);
/// <inheritdoc />
public abstract void Unload();
}
}
<file_sep>/Library/Plugin/PluginRequest.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace SakuraBridge.Library
{
/// <summary>
/// PLUGIN/2.0 リクエスト
/// </summary>
public class PluginRequest : Request
{
#region 定数
public const string NotifyCommand = "NOTIFY PLUGIN/2.0";
public const string GetCommand = "GET PLUGIN/2.0";
#endregion
/// <summary>
/// リクエスト文字列をパースする
/// </summary>
public static PluginRequest Parse(string message)
{
// Request.Parseを使ってパース
return Request.Parse<PluginRequest>(
message,
"PLUGIN/2.0",
(command) => (command == GetCommand || command == NotifyCommand),
(command, req) =>
{
req.IsNotify = (command == NotifyCommand);
}
);
}
/// <summary>
/// NOTIFYリクエストフラグ
/// </summary>
public virtual bool IsNotify { get; set; }
/// <summary>
/// コマンド文字列
/// </summary>
public override string Command
{
get
{
return (IsNotify ? NotifyCommand : GetCommand);
}
}
/// <summary>
/// IDヘッダ
/// </summary>
public virtual string ID
{
get { return this["ID"]; }
set { this["ID"] = value; }
}
}
}
<file_sep>/Library/Base/Exceptions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace SakuraBridge.Library
{
/// <summary>
/// リクエスト文字列のパース時にエラーが発生した
/// </summary>
public class BadRequestException : Exception
{
public BadRequestException() : base()
{
}
public BadRequestException(string message) : base(message)
{
}
public BadRequestException(string message, Exception innerException) : base(message, innerException)
{
}
protected BadRequestException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
}
<file_sep>/Library/SSTP/SSTPClient.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Sockets;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace SakuraBridge.Library
{
/// <summary>
/// SSTP送信クライアント
/// </summary>
public class SSTPClient
{
public const int DefaultToPort = 9801;
/// <summary>
/// 送信先ホスト (初期値: 127.0.0.1)
/// </summary>
public virtual string ToHost { get; set; }
/// <summary>
/// 送信先ポート (初期値: 9801)
/// </summary>
public virtual int ToPort { get; set; }
/// <summary>
/// リクエスト、レスポンスの内容などをDebug.WriteLineで出力するかどうか
/// </summary>
public virtual bool DebugLogging { get; set; }
/// <summary>
/// コンストラクタ
/// </summary>
public SSTPClient()
{
ToHost = "127.0.0.1";
ToPort = DefaultToPort;
DebugLogging = false;
}
/// <summary>
/// SSTPリクエストを送信し、レスポンスを得る
/// </summary>
/// <param name="req">リクエストオブジェクト</param>
/// <remarks>
/// khskさんの作成されたソースを参考にしています。
/// https://qiita.com/khsk/items/177741a6c573790a9379
/// </remarks>
/// <returns>成功した場合はResponseオブジェクト、失敗した場合はnull</returns>
public virtual SSTPResponse SendRequest(SSTPRequest req)
{
// Charset未指定のリクエストには対応しない
if (req.Encoding == null)
{
new ArgumentException(string.Format("{0} でSSTPリクエストを送信する場合は、リクエストに有効なCharsetを指定する必要があります。", MethodBase.GetCurrentMethod().Name));
}
if (DebugLogging)
{
Debug.WriteLine("[SSTP Request]");
Debug.WriteLine(req.ToString());
}
var data = req.Encoding.GetBytes(req.ToString());
using (var client = new TcpClient(ToHost, ToPort))
{
using (var ns = client.GetStream())
{
ns.ReadTimeout = 10 * 1000; // 読み込みタイムアウト10秒
ns.WriteTimeout = 10 * 1000; // 書き込みタイムアウト10秒
// リクエストを送信する
ns.Write(data, 0, data.Length); // リクエスト
//サーバーから送られたデータを受信する
using (var ms = new System.IO.MemoryStream())
{
var resBytes = new byte[256];
var resSize = 0;
do
{
//データの一部を受信する
resSize = ns.Read(resBytes, 0, resBytes.Length);
//Readが0を返した時はサーバーが切断したと判断
if (resSize == 0)
{
break;
}
//受信したデータを蓄積する
ms.Write(resBytes, 0, resSize);
//まだ読み取れるデータがあるか、データの最後が\nでない時は、受信を続ける
} while (ns.DataAvailable || resBytes[resSize - 1] != '\n');
// 受信したデータを文字列に変換
var resMsg = req.Encoding.GetString(ms.GetBuffer(), 0, (int)ms.Length);
// 末尾の\0, \nを削除
resMsg = resMsg.TrimEnd('\0').TrimEnd();
if (DebugLogging)
{
Debug.WriteLine("[SSTP Response]");
Debug.WriteLine(resMsg);
}
return SSTPResponse.Parse(resMsg);
}
}
}
}
}
}
<file_sep>/Library/Base/Response.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SakuraBridge.Library
{
/// <summary>
/// SHIORI/SAORI/PLUGINレスポンスの基底クラス
/// </summary>
public abstract class Response : Message
{
/// <summary>
/// ステータス文字列 (例: "PLUGIN/2.0 200 OK")
/// </summary>
public string Status
{
get
{
if (!string.IsNullOrWhiteSpace(StatusExplanation))
{
return string.Format("{0} {1} {2}", Version, StatusCode, StatusExplanation);
}
else
{
// 説明句なし
return string.Format("{0} {1}", Version, StatusCode);
}
}
}
/// <summary>
/// ステータス行に出力するバージョン (例: "PLUGIN/2.0")
/// </summary>
public abstract string Version { get; }
/// <summary>
/// ステータスコード (例: 200)
/// </summary>
public virtual int StatusCode { get; set; }
/// <summary>
/// ステータス説明句 (例: "OK")
/// </summary>
public virtual string StatusExplanation { get; set; }
/// <summary>
/// リクエストが成功したかどうか。200番台のステータスコードの場合true
/// </summary>
public virtual bool Success { get { return StatusCode >= 200 && StatusCode < 300; } }
/// <summary>
/// クライアントエラーかどうか。400番台のステータスコードの場合true
/// </summary>
public virtual bool IsClientError { get { return StatusCode >= 400 && StatusCode < 500; } }
/// <summary>
/// サーバーエラーかどうか。500番台のステータスコードの場合true
/// </summary>
public virtual bool IsServerError { get { return StatusCode >= 500 && StatusCode < 600; } }
/// <summary>
/// コンストラクタ
/// </summary>
/// <param name="statusCode">ステータスコード。ここで指定した値に応じて、ステータス説明文も自動設定される</param>
public Response(int statusCode)
{
StatusCode = statusCode;
if (CommonStatusCode.ExplanationMap.ContainsKey(statusCode))
{
StatusExplanation = CommonStatusCode.ExplanationMap[statusCode];
}
// Charsetの初期値はUTF-8
Encoding = Encoding.UTF8;
}
/// <inheritdoc />
public override string ToString()
{
var lines = new List<string>();
lines.Add(Status);
foreach (var name in HeaderNames)
{
lines.Add(string.Format("{0}: {1}", name, this[name]));
}
return string.Join("\r\n", lines) + "\r\n\r\n";
}
}
}
<file_sep>/Library/SSTP/SSTPResponse.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace SakuraBridge.Library
{
/// <summary>
/// SSTPレスポンス
/// </summary>
/// <remarks>SHIORI/SAORI/PLUGINのレスポンスとはフォーマットが異なるため、Responseクラスを継承していないことに注意してください。</remarks>
public class SSTPResponse : Message
{
/// <summary>
/// レスポンス文字列をパースする
/// </summary>
public static SSTPResponse Parse(string message)
{
var headerPattern = new Regex(Message.HeaderPattern);
if (message == null) throw new ArgumentNullException("message");
// メッセージを改行で分割
var lines = message.Split(new[] { "\r\n" }, StringSplitOptions.None);
// 1行目のステータス行が正しければ有効なSSTPレスポンス
var matched = Regex.Match(lines[0], @"^(SSTP/[0-9.]+)\s+(\d{1,7})(?:\s+(.+))?"); // 仕様上ステータスコードの桁数には記載がないため、一応7桁まで受け付ける
if (matched.Success)
{
var version = matched.Groups[1].Value;
var statusCode = int.Parse(matched.Groups[2].Value);
string explanation = null;
if (matched.Groups[3].Success)
{
explanation = matched.Groups[3].Value;
}
var res = new SSTPResponse();
res.Version = version;
res.StatusCode = statusCode;
res.StatusExplanation = explanation;
// 2行目以降の行をパース
var additionalLines = new List<string>();
for (var i = 1; i < lines.Length; i++)
{
var line = lines[i];
// 空行は読み飛ばす
if (line == "") continue;
// 追加情報として格納
additionalLines.Add(line);
}
// 追加情報があればセット
if (additionalLines.Any())
{
res.AdditionalData = string.Join("\r\n", additionalLines);
}
return res;
}
else
{
throw new BadRequestException(string.Format("有効なSSTPレスポンスではありません。 (コマンド行: {1})", lines[0]));
}
}
/// <summary>
/// ステータス文字列 (例: "PLUGIN/2.0 200 OK")
/// </summary>
public string Status
{
get
{
if (!string.IsNullOrWhiteSpace(StatusExplanation))
{
return string.Format("{0} {1} {2}", Version, StatusCode, StatusExplanation);
}
else
{
// 説明句なし
return string.Format("{0} {1}", Version, StatusCode);
}
}
}
/// <summary>
/// ステータス行に出力するバージョン (例: "PLUGIN/2.0")
/// </summary>
public string Version { get; set; }
/// <summary>
/// ステータスコード (例: 200)
/// </summary>
public virtual int StatusCode { get; set; }
/// <summary>
/// ステータス説明句 (例: "OK")
/// </summary>
public virtual string StatusExplanation { get; set; }
/// <summary>
/// EXECUTE/1.3 リクエストなどで取得可能な追加情報。存在しない場合はnull
/// </summary>
public virtual string AdditionalData { get; set; }
/// <summary>
/// リクエストが成功したかどうか。200番台のステータスコードの場合true
/// </summary>
public virtual bool Success { get { return StatusCode >= 200 && StatusCode < 300; } }
/// <summary>
/// クライアントエラーかどうか。400番台のステータスコードの場合true
/// </summary>
public virtual bool IsClientError { get { return StatusCode >= 400 && StatusCode < 500; } }
/// <summary>
/// サーバーエラーかどうか。500番台のステータスコードの場合true
/// </summary>
public virtual bool IsServerError { get { return StatusCode >= 500 && StatusCode < 600; } }
/// <summary>
/// コンストラクタ
/// </summary>
public SSTPResponse()
{
AdditionalData = null;
// Charsetの初期値はUTF-8
Encoding = Encoding.UTF8;
}
}
}<file_sep>/Library/SSTP/SSTPRequest.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace SakuraBridge.Library
{
/// <summary>
/// SSTPリクエスト
/// </summary>
public abstract class SSTPRequest : Request
{
}
/// <summary>
/// NOTIFY SSTP/1.1 リクエスト
/// </summary>
public class NotifySSTP11Request : Request
{
/// <summary>
/// コマンド文字列
/// </summary>
public override string Command { get { return "NOTIFY SSTP/1.1"; } }
}
/// <summary>
/// SEND SSTP/1.4 リクエスト
/// </summary>
public class SendSSTP14Request : Request
{
/// <summary>
/// コマンド文字列
/// </summary>
public override string Command { get { return "SEND SSTP/1.4"; } }
}
}
<file_sep>/Library/Plugin/PluginModule.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Security.Permissions;
using System.Text;
using System.Threading.Tasks;
using SakuraBridge.Base;
namespace SakuraBridge.Library
{
/// <summary>
/// プラグインモジュール (主に継承して使用する)
/// </summary>
public abstract class PluginModule : ModuleBase
{
/// <summary>
/// DLLが置かれているディレクトリのパス。Load時にセットされる
/// </summary>
protected string DLLDirPath;
/// <summary>
/// Load処理
/// </summary>
/// <param name="dllDirPath">DLLが置かれているパス</param>
public override void Load(string dllDirPath)
{
Debug.WriteLine("[plugin module load]");
Debug.WriteLine(string.Format("dllDirPath = {0}", dllDirPath));
DLLDirPath = dllDirPath;
}
/// <summary>
/// リクエスト
/// </summary>
public override string Request(string msg)
{
Debug.WriteLine("[plugin module request]");
Debug.WriteLine(msg);
// リクエストのパース
PluginRequest req;
try
{
req = PluginRequest.Parse(msg);
}
catch (BadRequestException ex)
{
Debug.WriteLine(ex.ToString());
return (new PluginResponse(CommonStatusCode.BadRequest)).ToString();
}
// レスポンスの生成
var res = MakeResponse(req);
Debug.WriteLine(res.ToString());
return res.ToString();
}
/// <summary>
/// リクエストIDに対応するResponseを作成する
/// </summary>
public virtual PluginResponse MakeResponse(PluginRequest req)
{
if (req.ID == "version")
{
var res = PluginResponse.OK();
res["Value"] = Version;
return res;
}
else if (req.ID == "OnMenuExec")
{
return OnMenuExec(req);
}
else
{
return new PluginResponse(CommonStatusCode.NotImplemented);
}
}
/// <summary>
/// Unload処理
/// </summary>
public override void Unload()
{
Debug.WriteLine("[plugin module unload]");
}
/// <summary>
/// バージョン文字列 (オーバーライドしない場合はアセンブリ名とアセンブリのバージョンから自動生成される)
/// </summary>
public virtual string Version
{
get
{
var asm = Assembly.GetAssembly(GetType());
return string.Format("{0}-{1}", asm.GetName().Name, asm.GetName().Version);
}
}
/// <summary>
/// メニューからのプラグイン選択時に呼び出される処理
/// </summary>
public virtual PluginResponse OnMenuExec(PluginRequest req)
{
return PluginResponse.OK();
}
}
}
<file_sep>/Library/Base/Message.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SakuraBridge.Library
{
/// <summary>
/// SHIORI/SAORI/PLUGIN/SSTPのリクエストやレスポンスを表すクラス
/// </summary>
public abstract class Message
{
public const string HeaderPattern = @"^([^:]+?)\s*:\s*(.+?)$";
protected virtual Dictionary<string, string> Headers { get; set; }
/// <summary>
/// 指定した名前のヘッダ値を取得/設定 (取得時、指定した名前のヘッダが存在しない場合はnull)
/// </summary>
public virtual string this[string name]
{
get
{
return (Headers.ContainsKey(name) ? Headers[name] : null);
}
set
{
if (value == null)
{
// nullを設定しようとした場合はクリア
Headers.Remove(name);
}
else
{
// 改行文字を含んでいる場合はエラー
if (value.Contains("\r") || value.Contains("\n"))
{
throw new ArgumentException(string.Format("{0} ヘッダに設定しようとした値に、改行文字が含まれています。"));
}
Headers[name] = value;
}
}
}
/// <summary>
/// コンストラクタ
/// </summary>
public Message()
{
Headers = new Dictionary<string, string>();
}
/// <summary>
/// 指定した名前の値をヘッダに含んでいるかどうかを判定
/// </summary>
public virtual bool Contains(string name)
{
return Headers.ContainsKey(name);
}
/// <summary>
/// 指定した名前の値をヘッダから削除
/// </summary>
public virtual bool Remove(string name)
{
return Headers.ContainsKey(name);
}
/// <summary>
/// Reference0, 1, 2... のリストを取得/設定
/// </summary>
public virtual List<string> References
{
get { return GetSequentialHeaderValues("Reference"); }
set { SetSequentialHeaderValues("Reference", value); }
}
/// <summary>
/// Reference0, 1, 2... やArgument0, 1, 2... など、連番方式のヘッダ値をListとして取得
/// </summary>
public virtual List<string> GetSequentialHeaderValues(string prefix)
{
var values = new List<string>();
for (var i = 0; true; i++)
{
var name = prefix + i.ToString();
if (Contains(name))
{
values.Add(this[name]);
}
else
{
break;
}
}
return values;
}
/// <summary>
/// Reference0, 1, 2... やArgument0, 1, 2... など、連番方式のヘッダ値を設定する。既存の設定値はクリアされる
/// </summary>
public virtual void SetSequentialHeaderValues(string prefix, IList<string> values)
{
// 既存値をクリア
foreach (var name in HeaderNames)
{
if (name.StartsWith(prefix))
{
Remove(name);
}
}
// 値を設定
for (var i = 0; i < values.Count; i++)
{
var name = prefix + i.ToString();
this[name] = values[i];
}
}
/// <summary>
/// ヘッダ名のコレクションを取得
/// </summary>
public virtual ICollection<string> HeaderNames { get { return Headers.Keys; } }
/// <summary>
/// Charsetヘッダ
/// </summary>
public virtual string Charset
{
get { return this["Charset"]; }
set { this["Charset"] = value; }
}
/// <summary>
/// エンコーディング (Charsetで指定された内容と連動)
/// 取得時、Charsetが未指定の場合や、解釈できない値の場合はnullを返す;
/// </summary>
public virtual Encoding Encoding
{
get
{
return (Charset != null ? FindEncodingByCharset(Charset) : null);
}
set
{
Charset = (value != null ? ConvertEncoding2Charset(value) : null);
}
}
/// <summary>
/// Charsetとして指定された値から、対応するEncodingを探す。
/// エンコーディングが見つからない場合、未サポート時はnullを返す
/// </summary>
protected static Encoding FindEncodingByCharset(string charset)
{
if (charset == null) throw new ArgumentNullException("charset");
try
{
if (!string.IsNullOrWhiteSpace(charset))
{
// 見つかった
return Encoding.GetEncoding(charset);
}
}
catch (ArgumentException)
{
}
catch (NotSupportedException)
{
}
return null;
}
/// <summary>
/// EncodingからCharsetで使用可能な名前を取得 (一般的でないCharsetの場合はWebNameを返す)
/// </summary>
protected static string ConvertEncoding2Charset(Encoding encoding)
{
if (encoding == null) throw new ArgumentNullException("encoding");
if (encoding == Encoding.UTF8) return "UTF-8";
if (encoding == Encoding.GetEncoding("Shift_JIS")) return "Shift_JIS";
if (encoding == Encoding.GetEncoding("EUC-JP")) return "EUC-JP";
if (encoding == Encoding.GetEncoding("ISO-2022-JP")) return "ISO-2022-JP";
return encoding.WebName;
}
}
}
<file_sep>/Export/Export.cs
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using SakuraBridge.Base;
namespace SakuraBridge.Export
{
/// <summary>
/// ベースウェアから直接呼び出されるDLL関数のエクスポート
/// </summary>
public static class Export
{
/// <summary>
/// .NETアセンブリから読み込んだSakuraBridgeモジュール
/// </summary>
public static IModule Module;
/// <summary>
/// モジュールを実行するアプリケーションドメイン
/// </summary>
public static AppDomain ModuleDomain;
/// <summary>
/// Charsetヘッダのマッチ用正規表現
/// </summary>
public static Regex CharsetHeaderPattern;
/// <summary>
/// staticコンストラクタ
/// </summary>
static Export()
{
// アセンブリ解決処理を追加
// (クラスライブラリとして外部から呼び出されるため、この処理を加えないとアセンブリがどこにあるのかを特定できない)
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
// 正規表現の初期化
CharsetHeaderPattern = new Regex(@"^Charset\s*:\s*(.+?)$", RegexOptions.Multiline | RegexOptions.Compiled);
}
/// <summary>
/// アセンブリ解決処理
/// </summary>
private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
var assemblyName = args.Name.Split(',')[0];
var assemblyPath = Path.Combine(Path.GetDirectoryName(args.RequestingAssembly.Location), "module", string.Format("{0}.dll", assemblyName));
return Assembly.LoadFrom(assemblyPath);
}
#region エクスポート関数
[DllExport]
public static bool load(IntPtr dllDirPathPtr, int len)
{
var dllDirPath = Marshal.PtrToStringAnsi(dllDirPathPtr); // IntPtrをstring型に変換
// 受け取った文字列のハンドルを解放
Marshal.FreeHGlobal(dllDirPathPtr);
// SakuraBridge.txtを読み込む
var lines = File.ReadAllLines(Path.Combine(dllDirPath, @"bridge.txt"));
string dllName = null;
foreach (var line in lines)
{
if (line.StartsWith("module,"))
{
dllName = line.Split(',')[1];
}
}
if (dllName == null)
{
throw new Exception("bridge.txt 内でmodule dll名が指定されていません。");
}
// モジュールを読み込むための新しいアプリケーションドメインを生成
ModuleDomain = AppDomain.CreateDomain("ModuleDomain");
// アプリケーションドメイン内でアセンブリを読み込み、IModuleを継承したモジュールクラスを探す
var dllPath = Path.Combine(dllDirPath, "module", dllName);
var baseLibPath = Path.Combine(dllDirPath, @"module\SakuraBridge.Base.dll");
var finder = (IModuleClassFinder)ModuleDomain.CreateInstanceFromAndUnwrap(baseLibPath, typeof(ModuleClassFinder).FullName);
var moduleClassNames = finder.GetModuleClassFullNames(dllPath);
// モジュールクラスが1つもない、もしくは2つ以上ある場合はエラー
if (moduleClassNames.Length == 0)
{
throw new Exception(string.Format("アセンブリ内にIModuleを継承したクラスが含まれていません。 - {0}", dllName));
}
if (moduleClassNames.Length >= 2)
{
throw new Exception(string.Format("アセンブリ内にIModuleを継承したクラスが2つ以上含まれています。 - {0}", dllName));
}
// モジュールクラスのインスタンスを作成
Module = (IModule)ModuleDomain.CreateInstanceFromAndUnwrap(dllPath, moduleClassNames.Single());
// ModuleのLoad処理を呼び出す
Module.Load(dllDirPath);
return true; // 正常終了
}
[DllExport]
public static bool unload()
{
// ModuleのUnload処理を呼び出す
Module.Unload();
// モジュールのアプリケーションドメインを開放
AppDomain.Unload(ModuleDomain);
return true; // 正常終了
}
[DllExport]
public static IntPtr request(IntPtr messagePtr, IntPtr lenPtr)
{
// メッセージ長を読み取る
var len = Marshal.ReadInt32(lenPtr);
// メッセージの内容をbyte配列に格納
var messageBytes = new byte[len];
Marshal.Copy(messagePtr, messageBytes, 0, len);
// 受け取った文字列のハンドルを解放
Marshal.FreeHGlobal(messagePtr);
// リクエストメッセージの内容をUTF-8と解釈して文字列に変換
var reqStr = Encoding.UTF8.GetString(messageBytes);
// リクエストメッセージの中にCharset指定があり、かつUTF8でない場合、そのCharset指定を使って読み込み直す
var reqEnc = GetEncodingFromMessage(reqStr);
if (reqEnc != Encoding.UTF8)
{
reqStr = reqEnc.GetString(messageBytes);
}
// ModuleのRequest処理を呼び出す
var resStr = Module.Request(reqStr);
// レスポンス文字列をバイト配列に変換
// (レスポンスの中にCharset指定があれば、そのエンコーディングを使う)
var resEnc = GetEncodingFromMessage(resStr);
var resBytes = resEnc.GetBytes(resStr);
// レスポンス文字列の領域を確保
var resPtr = Marshal.AllocHGlobal(resBytes.Length);
// レスポンス文字列をコピー
Marshal.Copy(resBytes, 0, resPtr, resBytes.Length);
// responseを返す
Marshal.WriteInt32(lenPtr, resBytes.Length);
return resPtr;
}
#endregion
#region その他の関数
/// <summary>
/// メッセージ文字列の中からCharsetを探し、そのCharsetヘッダの値を元にエンコーディングを取得。未指定の場合や解釈できないCharset値の場合はUTF-8を返す
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
public static Encoding GetEncodingFromMessage(string message)
{
// Charsetヘッダの値を探す
var matched = CharsetHeaderPattern.Match(message);
if (matched.Success)
{
var charsetValue = matched.Groups[1].Value.TrimEnd();
try
{
// 解釈可能なCharsetヘッダの値が見つかった場合、対応するエンコーディングを返す
return Encoding.GetEncoding(charsetValue);
}
catch (ArgumentException)
{
// システムでそのCharsetが使用不可能な場合はスキップ
}
}
// 未指定の場合や解釈できないCharset値の場合
return Encoding.UTF8;
}
#endregion
}
}
| 47c429cef40da6d375878aa580959e836cbd28db | [
"C#"
] | 16 | C# | tetradice/SakuraBridgePrototype2 | 88741241700d4a2f2bcdab778c4846b39cb66059 | 83342ac6eb4c5a19a54a41948f32241d4c16520a |
refs/heads/master | <file_sep>const code = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65]
function init() {
}
document.body.addEventListener("keydown", init)
let index = 0
function init (){
debugger;
let key= event.which;
if (key===code[index]){
index++
if (index === code.length){
Alert=("Konami");
}
}
else {
index = 0;
}
} | 72b4c463d4f9c560326be89a31af93ff898edc6f | [
"JavaScript"
] | 1 | JavaScript | fiolam/js-eventing-konami-code-lab-nyc-fe-061118 | 38e8a581edb5fccedfd755d73aec1668a4811d52 | ec9cf7b834c9ccb48de5b0e92332e9dd8d456932 |
refs/heads/master | <repo_name>andredla/Timeshift<file_sep>/Timeshift/timeshift.py
import sublime
import sublime_plugin
import sys
import os
import difflib
path = os.path.dirname(os.path.realpath(__file__))
history = os.path.join(path, "history.log")
temp_a = os.path.join(path, "temp.log")
txt_track = ""
phantoms = []
def getReg(self, view, idx):
ret = sublime.Region(-1,-1)
row = view.text_point(idx - 1, 0)
ret = view.full_line(row)
return ret
pass
def getTxt(self):
txt = ""
line_total = self.view.rowcol(self.view.size())[0]+1
for indx in range(line_total):
txt = txt + self.view.substr(self.view.line(sublime.Region(self.view.text_point(indx, 0), self.view.text_point(indx, 0))))
return txt
def getFilename(self):
name = ""
ext = ""
if self.view.file_name() != None:
full = os.path.basename(self.view.file_name())
name = os.path.splitext(full)[0]
ext = os.path.splitext(full)[1]
return name, ext
pass
def historyAdd(nome, txt_track):
arquivo = open(history, "a")
arquivo.write(nome+"\n")
arquivo.close()
file_track = os.path.join(path, nome+".txt")
arquivo = open(file_track, "w")
arquivo.write(txt_track)
arquivo.close()
pass
def historyDel():
arquivo = open(history, "r")
temp = arquivo.readlines()
arquivo.close()
for t in temp:
arquivo = os.path.join(path, t.replace("\n", "")+".txt")
if os.path.exists(arquivo):
os.remove(arquivo)
arquivo = open(history, "w")
arquivo.write("")
arquivo.close()
arquivo = open(temp_a, "w")
arquivo.write("")
arquivo.close()
pass
def fix(arq_1, arq_2):
ret_1 = arq_1
ret_2 = arq_2
arq_1_size = len(arq_1)
arq_2_size = len(arq_2)
size = abs(arq_1_size - arq_2_size)
if arq_1_size < arq_2_size:
for a in range(size):
ret_1.append("")
if arq_2_size < arq_1_size:
for a in range(size):
ret_2.append("")
return ret_1, ret_2
def getIdx(arr):
ret = 0
if arr[0].find(",") > 0:
ret = arr[0].split(",")[0]
else:
ret = arr[0]
return int(ret)
def render_parse(self, tab, cmd):
idx = 0
cor = ""
sinal = ""
tipo = 0
print(cmd)
cmd_spt = cmd.split("\n")
for l in cmd_spt:
if l.startswith("<") or l.startswith(">") or l.startswith("-"):
if tipo == 1 or tipo == 2:
idx += 1
tab.run_command("append",{"characters": l[2:]+"\n"})
tab_line = tab.rowcol(tab.size())[0]
phantoms.append( tab.add_phantom("diff", getReg(self, tab, tab_line), "<div style='padding: 5px; background-color: "+cor+";'>"+sinal+" </div>", sublime.LAYOUT_INLINE) )
if tipo == 3:
if l.startswith("<"):
idx += 1
tab.run_command("append",{"characters": l[2:]+"\n"})
tab_line = tab.rowcol(tab.size())[0]
phantoms.append( tab.add_phantom("diff", getReg(self, tab, tab_line), "<div style='padding: 5px; background-color: "+cor+";'>"+sinal+" </div>", sublime.LAYOUT_INLINE) )
pass
else:
if l != "":
a = l.split("a")
d = l.split("d")
c = l.split("c")
if len(a) > 1:
tipo = 1
sinal = "-"
cor = "#FFE6E6"
idx = getIdx(a)
tab.run_command("append",{"characters": "deleted...\n"})
if len(d) > 1:
tipo = 2
sinal = "+"
cor = "#EEFDEE"
idx = getIdx(d)
tab.run_command("append",{"characters": "added...\n"})
if len(c) > 1:
tipo = 3
cor = "#E8FBFF"
sinal = "?"
idx = getIdx(c)
tab.run_command("append",{"characters": "changed...\n"})
tab_line = tab.rowcol(tab.size())[0]
phantoms.append( tab.add_phantom("diff", getReg(self, tab, tab_line), "<div style='padding: 5px; background-color: "+cor+";'>"+str(idx)+sinal+" </div>", sublime.LAYOUT_INLINE) )
pass
return False
pass
def render(self, diff, tab, tipo_flag, cor_final, sinal_final, delta):
idx = 0
cor = "#ffffff"
tipo = 0
for l in diff:
idx += 1
flag = False
if l.startswith("- "):
tipo = 1
cor = "#FFE6E6"
flag = True
if l.startswith("+ "):
tipo = 2
cor = "#EEFDEE"
flag = True
if flag and tipo == tipo_flag and l != "- ":
#print(l, idx)
l_temp = ""+l[2:]
tab.run_command("append",{"characters": l_temp+"\n"})
tab_line = tab.rowcol(tab.size())[0]
phantoms.append( tab.add_phantom("diff", getReg(self, tab, tab_line), "<div style='padding: 5px; background-color: "+cor_final+";'>"+str(idx)+sinal_final+"</div>", sublime.LAYOUT_INLINE) )
pass
class TimeshifttrackCommand(sublime_plugin.TextCommand):
def run(self, edit):
global txt_track
txt_track = self.view.substr(sublime.Region(0, self.view.size()))
nome, ext = getFilename(self)
if nome != "":
historyAdd(nome, txt_track)
pass
class TimeshiftdonttrackCommand(sublime_plugin.TextCommand):
def run(self, edit):
global phantoms
global txt_track
txt_track = ""
self.view.erase_phantoms("diff")
historyDel()
pass
class TimeshiftcompareCommand(sublime_plugin.TextCommand):
def run(self, edit):
global txt_track
#if txt_track == "":
#return False
nome, ext = getFilename(self)
if nome == "":
return False
file_track = os.path.join(path, nome+".txt")
arquivo = open(file_track, "r")
txt_track = "".join(arquivo.readlines())
arquivo.close()
txt = self.view.substr(sublime.Region(0, self.view.size()))
arquivo = open(temp_a, "w")
arquivo.write(txt)
arquivo.close()
win = self.view.window()
tab = win.new_file()
arq_1 = txt_track.split("\n")
arq_2 = txt.split("\n")
#arq_1, arq_2 = fix(arq_1, arq_2)
#cmd = os.popen("diff "+file_track+" "+temp_a).read()
cmd = os.popen("diff "+temp_a+" "+file_track).read()
render_parse(self, tab, cmd)
#diff = difflib.HtmlDiff().make_file(arq_1, arq_2, "arq_1", "arq_2")
#arquivo = open(os.path.join(path, "debug.html"), "w")
#arquivo.write(diff)
#arquivo.close()
#delta = len(arq_1) - len(arq_2)
#d = difflib.Differ()
#diff = d.compare(arq_1, arq_2)
#diff = difflib.ndiff(arq_1, arq_2)
#render(self, diff, tab, 1, "#FFE6E6", "- ", delta)
#delta = len(arq_2) - len(arq_1)
#d = difflib.Differ()
#diff = d.compare(arq_2, arq_1)
#diff = difflib.ndiff(arq_2, arq_1)
#render(self, diff, tab, 1, "#EEFDEE", "+ ", delta)
#match = patience_diff(arq_1, arq_2)
#print(match)
pass
class TimeshiftrestoreCommand(sublime_plugin.TextCommand):
def run(self, edit):
global txt_track
#txt_track = self.view.substr(sublime.Region(0, self.view.size()))
nome, ext = getFilename(self)
if nome != "":
arquivo = open(os.path.join(path, nome+".txt"))
txt_temp = arquivo.readlines()
arquivo.close()
self.view.replace(edit, sublime.Region(0, self.view.size()), "".join(txt_temp))
pass<file_sep>/README.md
# Timeshift
:. Sublime 3 plugin
Keep track of differences between your file<br/>
Nedded command diff of Linux
How it works:
- First you click on Keep track
- Then you work on your document
- Then you compare your document
- You can restore your document if you want the older version
- Dont track will clear all tracks
# Instalation guide
- Unzip the file
- Copy the contents to the package folder of Sublime 3.
- Then open Sublime 3 go to View -> Timeshift.

| 91e5f7a0f34dad65dce8d85925776dd9c7d2390b | [
"Markdown",
"Python"
] | 2 | Python | andredla/Timeshift | cf9d52d78a3c9b306a3e532912093e4a350f9e09 | 822d6a2aca3482baa12d802f12ef912dabb17254 |
refs/heads/master | <file_sep>BEGIN
INSERT INTO dbo.tblGravity (Id, MassOne, MassTwo, Distance, ChangeDate, Force)
VALUES
(NEWID(), 300000, 400000, 1.5, GETDATE(), 1.772228)
END<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ART.Gravity.BL;
using ART.Gravity.PL;
using Microsoft.EntityFrameworkCore.Storage;
namespace ART.Gravity.UI
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
protected GravityEntities dc;
protected IDbContextTransaction transaction;
public MainWindow()
{
InitializeComponent();
List<BL.Models.Gravity> gravities = new List<BL.Models.Gravity>();
gravities = GravityManager.LoadForDataBox();
foreach(var g in gravities)
{
var problem = new BL.Models.Gravity();
problem.Mass1 = g.Mass1;
problem.Mass2 = g.Mass2;
problem.Distance = g.Distance;
problem.Force = g.Force;
dgData.Items.Add(problem);
}
}
private void btnCalc_Click(object sender, RoutedEventArgs e)
{
try
{
dgData.Items.Clear();
BL.Models.Gravity gravity = new BL.Models.Gravity();
gravity.Mass1 = float.Parse(txtMassOne.Text);
gravity.Mass2 = float.Parse(txtMassTwo.Text);
gravity.Distance = float.Parse(txtDistance.Text);
GravityManager.CalcForce(gravity);
lblForce.Content = gravity.Force.ToString("n25");
GravityManager.Insert(gravity);
// Listbox
List<BL.Models.Gravity> gravities = new List<BL.Models.Gravity>();
gravities = GravityManager.LoadForDataBox();
foreach(var g in gravities)
{
var problem = new BL.Models.Gravity();
problem.Mass1 = g.Mass1;
problem.Mass2 = g.Mass2;
problem.Distance = g.Distance;
problem.Force = g.Force;
dgData.Items.Add(problem);
}
}
catch (Exception)
{
throw;
}
}
}
}
<file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Linq;
namespace ART.Gravity.BL.Test
{
[TestClass]
public class utGravity
{
[TestMethod]
public void LoadTest()
{
Assert.AreEqual(1, GravityManager.Load().Count());
}
[TestMethod]
public void CalcForceTest()
{
double expected = 8.008799734504635E-10;
Models.Gravity gravity = new Models.Gravity();
gravity.Mass2 = 4;
gravity.Mass1 = 3;
gravity.Distance = 1;
GravityManager.CalcForce(gravity);
Assert.AreEqual(expected, gravity.Force);
}
[TestMethod]
public void InsertTest()
{
int results = GravityManager.Insert(new Models.Gravity
{
Id = Guid.Empty,
Mass1 = 10,
Mass2 = 12,
Distance = 2
}, true);
Assert.AreEqual(1, results);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
#nullable disable
namespace ART.Gravity.PL
{
public partial class tblGravity
{
public Guid Id { get; set; }
public DateTime ChangeDate { get; set; }
public double MassOne { get; set; }
public double MassTwo { get; set; }
public double Distance { get; set; }
public double Force { get; set; }
}
}
<file_sep>using ART.Gravity.PL;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using System;
using System.Collections.Generic;
using System.Linq;
namespace ART.Gravity.BL
{
public static class GravityManager
{
public static int Insert(BL.Models.Gravity gravity, bool rollback = false)
{
try
{
IDbContextTransaction transaction = null;
using (GravityEntities dc = new GravityEntities())
{
if (rollback) transaction = dc.Database.BeginTransaction();
tblGravity tblgravity = new tblGravity();
tblgravity.Id = Guid.NewGuid();
tblgravity.MassOne = (double)gravity.Mass1;
tblgravity.MassTwo = (double)gravity.Mass2;
tblgravity.Force = (double)gravity.Force;
tblgravity.Distance = (double)gravity.Distance;
tblgravity.ChangeDate = DateTime.Now;
//backfill the transport class id
gravity.Id = tblgravity.Id;
dc.TblGravities.Add(tblgravity);
int results = dc.SaveChanges();
if (rollback) transaction.Rollback();
return results;
}
}
catch (Exception)
{
throw;
}
}
public static int Update(BL.Models.Gravity gravity, bool rollback = false)
{
try
{
IDbContextTransaction transaction = null;
using (GravityEntities dc = new GravityEntities())
{
if (rollback) transaction = dc.Database.BeginTransaction();
tblGravity tblgravity = dc.TblGravities.FirstOrDefault(t => t.Id == gravity.Id);
if (tblgravity != null)
{
tblgravity.MassOne = (double)gravity.Mass1;
tblgravity.MassTwo = (double)gravity.Mass2;
tblgravity.Distance = (double)gravity.Distance;
tblgravity.ChangeDate = DateTime.Now;
int results = dc.SaveChanges();
if (rollback) transaction.Rollback();
return results;
}
else
{
throw new Exception("Row does not exist");
}
}
}
catch (Exception)
{
throw;
}
}
public static int Delete(Guid id, bool rollback = false)
{
try
{
IDbContextTransaction transaction = null;
using (GravityEntities dc = new GravityEntities())
{
if (rollback) transaction = dc.Database.BeginTransaction();
tblGravity tblgravity = dc.TblGravities.FirstOrDefault(t => t.Id == id);
if (tblgravity != null)
{
dc.TblGravities.Remove(tblgravity);
int results = dc.SaveChanges();
if (rollback) transaction.Rollback();
return results;
}
else
{
throw new Exception("Row does not exist");
}
}
}
catch (Exception)
{
throw;
}
}
public static List<BL.Models.Gravity> Load()
{
try
{
List<BL.Models.Gravity> gravities = new List<Models.Gravity>();
using (GravityEntities dc = new GravityEntities())
{
dc.TblGravities.ToList().ForEach(g => gravities.Add(new BL.Models.Gravity
{
Id = g.Id,
Mass1 = (float)g.MassOne,
Mass2 = (float)g.MassTwo,
Distance = (float)g.Distance,
ChangeDate = g.ChangeDate,
}));
return gravities;
}
}
catch (Exception)
{
throw;
}
}
public static List<BL.Models.Gravity> LoadForDataBox()
{
try
{
List<BL.Models.Gravity> gravities = new List<Models.Gravity>();
using (GravityEntities dc = new GravityEntities())
{
dc.TblGravities.ToList().ForEach(g => gravities.Add(new BL.Models.Gravity
{
Mass1 = (float)g.MassOne,
Mass2 = (float)g.MassTwo,
Distance = (float)g.Distance,
Force = (float)g.Force
}));
return gravities;
}
}
catch (Exception)
{
throw;
}
}
public static BL.Models.Gravity LoadById(Guid id)
{
try
{
BL.Models.Gravity gravity = new BL.Models.Gravity();
using (GravityEntities dc = new GravityEntities())
{
var tblgravity = dc.TblGravities.FirstOrDefault(g => g.Id == id);
gravity.Id = tblgravity.Id;
gravity.Mass1 = (float)tblgravity.MassOne;
gravity.Mass2 = (float)tblgravity.MassTwo;
gravity.Distance = (float)tblgravity.Distance;
gravity.ChangeDate = tblgravity.ChangeDate;
return gravity;
}
}
catch (Exception)
{
throw;
}
}
public static void CalcForce(BL.Models.Gravity gravity)
{
try
{
using (GravityEntities dc = new GravityEntities())
{
var parameterMass1 = new SqlParameter
{
ParameterName = "MassOne",
SqlDbType = System.Data.SqlDbType.Decimal,
Value = gravity.Mass1
};
var parameterMass2 = new SqlParameter
{
ParameterName = "MassTwo",
SqlDbType = System.Data.SqlDbType.Decimal,
Value = gravity.Mass2
};
var parameterDistance = new SqlParameter
{
ParameterName = "Distance",
SqlDbType = System.Data.SqlDbType.Decimal,
Value = gravity.Distance
};
var results = dc.Set<spCalcForceResult>().FromSqlRaw("exec spCalcForce @MassOne, @MassTwo, @Distance", parameterMass1, parameterMass2, parameterDistance);
foreach (var r in results)
{
gravity.Force = (float)r.Force;
}
}
}
catch (Exception)
{
throw;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ART.Gravity.PL
{
public class spCalcForceResult
{
public double Force { get; set; }
}
}
<file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting;
using ART.Gravity.PL;
using Microsoft.EntityFrameworkCore.Storage;
using System.Linq;
using System;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
namespace ART.Gravity.PL.Test
{
[TestClass]
public class utGravity
{
protected GravityEntities dc;
protected IDbContextTransaction transaction;
[TestInitialize]
public void TestInitialize()
{
dc = new GravityEntities();
transaction = dc.Database.BeginTransaction();
}
[TestCleanup]
public void TestCleanUp()
{
transaction.Rollback();
transaction.Dispose();
dc = null;
}
[TestMethod]
public void LoadTest()
{
int expected = 1;
int actual = 0;
actual = dc.TblGravities.Count();
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void CalcForceTest()
{
double expected = 8.008799999999999E-10;
double? actual = 0;
var parameterMass1 = new SqlParameter
{
ParameterName = "MassOne",
SqlDbType = System.Data.SqlDbType.Decimal,
Value = 3
};
var parameterMass2 = new SqlParameter
{
ParameterName = "MassTwo",
SqlDbType = System.Data.SqlDbType.Decimal,
Value = 4
};
var parameterDistance = new SqlParameter
{
ParameterName = "Distance",
SqlDbType = System.Data.SqlDbType.Decimal,
Value = 1
};
var results = dc.Set<spCalcForceResult>().FromSqlRaw("exec spCalcForce @MassOne, @MassTwo, @Distance", parameterMass1, parameterMass2, parameterDistance);
foreach(var r in results)
{
actual = r.Force;
}
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void InsertTest()
{
int expected = 1;
int actual = 0;
tblGravity newrow = new tblGravity();
newrow.Id = Guid.NewGuid();
newrow.MassOne = 10;
newrow.MassTwo = 12;
newrow.Distance = 2;
newrow.ChangeDate = DateTime.Now;
newrow.Force = 1;
dc.TblGravities.Add(newrow);
actual = dc.SaveChanges();
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void UpdateTest()
{
InsertTest();
tblGravity row = dc.TblGravities.Where(g => g.MassOne == 10 && g.MassTwo == 12 && g.Distance == 2).FirstOrDefault();
int actual = 0;
if (row != null)
{
row.MassOne = 6;
row.MassTwo = 7;
row.Distance = 8;
actual = dc.SaveChanges();
}
Assert.IsTrue(actual > 0);
}
[TestMethod]
public void DeleteTest()
{
InsertTest();
tblGravity row = dc.TblGravities.Where(g => g.MassOne == 10 && g.MassTwo == 12 && g.Distance == 2).FirstOrDefault();
int actual = 0;
if (row != null)
{
dc.TblGravities.Remove(row);
actual = dc.SaveChanges();
}
Assert.IsTrue(actual > 0);
}
}
}
<file_sep>using System;
namespace ART.Gravity.BL.Models
{
public class Gravity
{
// Force = G * (M1 * M2/ r^2)
public Guid Id { get; set; }
public DateTime ChangeDate { get; set; }
public float Mass1 { get; set; }
public float Mass2 { get; set; }
public float Distance { get; set; }
public float Force { get; set; }
}
}
| 91a2c06584acd074eaa47284179445d3f59bc359 | [
"C#",
"SQL"
] | 8 | SQL | Tammada1771/Gravity | 0043f4c28f28d0f0ca788714d6c0d8d89aae0d28 | a0ffbd5d6ce25e601709d9fec0368bca8f5d691f |
refs/heads/master | <file_sep># Lunar-Lander-Deep-Q-Learning
This is my approach for OpenAI's Lunar-Lander game. I used Pytorch and for performance reasons my NVIDIA GPU
<file_sep>import torch as T
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
class DeepQNetwork(nn.Module):
def __init__(self, lr, input_dims, fc1_dims, fc2_dims, n_actions):
super(DeepQNetwork, self).__init__()
self.input_dims = input_dims
self.fc1_dims = fc1_dims
self.fc2_dims = fc2_dims
self.n_actions = n_actions
#Layers
self.fc1 = nn.Linear(*self.input_dims, self.fc1_dims)
self.fc2 = nn.Linear(self.fc1_dims, self.fc2_dims)
self.fc3 = nn.Linear(self.fc2_dims, self.n_actions)
#Optimizer
self.optimizer = optim.Adam(self.parameters(), lr=lr)
self.loss = nn.MSELoss()
#GPU Activate
self.device = T.device('cuda:0')
self.cuda()
def forward(self, state):
x = F.relu(self.fc1(state))
x = F.relu(self.fc2(x))
actions = self.fc3(x)
return actions
class Agent():
def __init__(self, gamma, epsilon, lr, input_dims, batch_size, n_actions,
max_mem_size=100000, eps_end=0.01, eps_dec=5e-4):
self.gamma = gamma
self.epsilon = epsilon
self.eps_min = eps_end
self.eps_dec = eps_dec
self.lr = lr
self.action_space = [i for i in range(n_actions)]
self.batch_size = batch_size
self.Q_eval = DeepQNetwork(self.lr, n_actions=n_actions, input_dims=input_dims, fc1_dims=256, fc2_dims=256)
#memory
self.mem_size = max_mem_size
self.mem_cntr = 0
self.state_memory = np.zeros((self.mem_size, *input_dims), dtype=np.float32)
self.new_state_memory = np.zeros((self.mem_size, *input_dims), dtype=np.float32)
self.action_memory = np.zeros(self.mem_size, dtype=np.float32)
self.reward_memory = np.zeros(self.mem_size, dtype=np.float32)
self.terminal_memory = np.zeros(self.mem_size, dtype=np.bool)
def store_transisation(self, state, action, reward, state_, done):
#get current index
index = self.mem_cntr % self.mem_size
#write it into the dicts
self.state_memory[index] = state
self.new_state_memory[index] = state_
self.reward_memory[index] = reward
self.action_memory[index] = action
self.terminal_memory[index] = done
self.mem_cntr += 1
def choose_action(self, observation):
if np.random.randn() > self.epsilon:
#action from brain (Neural Network)
state = T.Tensor([observation]).cuda()
actions = self.Q_eval.forward(state)
#get index of the highest value [0.7, 0.2, 0.95] --> 2
action = T.argmax(actions).item()
else:
#some random action [0 - 4]
action = np.random.choice(self.action_space)
return action
def learn(self):
if self.mem_cntr < self.batch_size:
#only start learning when the batch_size is reached
#--> prevents uncontrolled learning from random values
return
#reset
self.Q_eval.optimizer.zero_grad()
#get index of latest batch
max_mem = min(self.mem_cntr, self.mem_size)
batch = np.random.choice(max_mem, self.batch_size, replace=False)
batch_index = np.arange(self.batch_size, dtype=np.int32)
#get batch
state_batch = T.tensor(self.state_memory[batch]).cuda()
new_state_batch = T.tensor(self.new_state_memory[batch]).cuda()
reward_batch = T.tensor(self.reward_memory[batch]).cuda()
terminal_batch = T.tensor(self.terminal_memory[batch]).cuda()
action_batch = self.action_memory[batch]
#calculate step
q_eval = self.Q_eval.forward(state_batch)[batch_index, action_batch]
q_next = self.Q_eval.forward(new_state_batch)
q_next[terminal_batch] = 0.0
#optimize
q_target = reward_batch + self.gamma * T.max(q_next, dim=1)[0]
loss = self.Q_eval.loss(q_target, q_eval).cuda()
loss.backward()
self.Q_eval.optimizer.step()
#decrease epsilon
self.epsilon = self.epsilon - self.eps_dec if self.epsilon > self.eps_min else self.eps_min
<file_sep>import gym
from dqn import Agent
import numpy as np
def main():
#make env and agent
env = gym.make('LunarLander-v2')
agent = Agent(gamma=0.99, epsilon=1.0, batch_size=64, n_actions=4,
eps_end=0.01, input_dims=[8], lr=0.0001)
scores, eps_history = [], []
n_games = 500
for i in range(n_games):
score = 0
done = False
observation = env.reset()
while not done:
#ingame
#get action from current view of game (observation)
action = agent.choose_action(observation)
#next frame
observation_, reward, done, info = env.step(action)
score += reward
#store memory
agent.store_transisation(observation, action, reward, observation_, done)
agent.learn()
#set next stage to current stage
observation = observation_
#append score and eps
scores.append(score)
eps_history.append(agent.epsilon)
#print some nice statements
avg_score = np.mean(scores[-100:])
print(f'Episode: {i} Score: {score} Average Score: {avg_score} Epsilon: {agent.epsilon}')
if __name__ == "__main__":
main() | 860f7d6a4b220170919bd4d9b531c180e0c88ad5 | [
"Markdown",
"Python"
] | 3 | Markdown | Christopher-06/Lunar-Lander-Deep-Q-Learning | e776d29d74c5d61f3af808d9fdca2495f1b848d5 | 760fe4c835d97d157d349bca0b11e1df82af2abf |
refs/heads/master | <file_sep>server.port=8081
spring.batch.job.enabled=false
input=file:src/main/resources/data/oscar_age_male.csv
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
<file_sep>package org.learning.springbatchdemo.batch;
import org.learning.springbatchdemo.entity.MaleOscarWinners;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.stereotype.Component;
@Component
public class Processor implements ItemProcessor<MaleOscarWinners, MaleOscarWinners> {
@Override
public MaleOscarWinners process(MaleOscarWinners item) throws Exception {
MaleOscarWinners maleOscarWinners = item;
return maleOscarWinners;
}
}
| f681dc0de6bbbf534cead58bacc17b306d3350c4 | [
"Java",
"INI"
] | 2 | INI | abha8517/spring-batch-demo | 5324de7414e1e9584e1f82bad2507b1f352738dc | 09ab872575adbac5c87b88e1c80ae05fdece53a1 |
refs/heads/master | <repo_name>NeddiePeng/camelinfo<file_sep>/work/camel/Backstage/application/controllers/Login.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2017/5/26
* Time: 23:33
*/
class Login extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->library('session');
$this->load->helper('url');
}
public function index(){
$data['base_url'] = base_url();
$this->load->view('form/login.html',$data);
}
/**
* 登录页面
*/
public function login_page(){
$data['base_url'] = base_url();
$this->load->view('form/login.html',$data);
}
/**
* 注册页面
*/
public function register_page(){
$data['base_url'] = base_url();
$this->load->view('form/register.html',$data);
}
/**
* 修改密码页面
*/
public function updata_user_page(){
$data['base_url'] = base_url();
$this->load->view('form/register.html',$data);
}
/**
* 后台管理员注册
*/
public function register(){
$data['base_url'] = base_url();
$name = $_POST['username'] ? $_POST['username'] : "";
$password = $_POST['password'] ? $_POST['password'] : "";
$salt = $this->salt_string();
$password = md5(md5($password).$salt);
$this->load->model('form_model');
if(empty($name) || empty($password)){
echo "<script>alert('密码和用户名为空!');</script>";
exit();
}
$add_user = $this->form_model->add_user($name,$password,$salt);
if($add_user == 'repeat'){
echo "<script>alert('该用户名已被注册!');self.location=document.referrer;</script>";
}
if($add_user == 'yes'){
echo "<script>alert('注册成功!');</script>";
$this->load->view('form/login.html',$data);
}else if($add_user == 'no'){
echo "<script>alert('注册失败!');</script>";
}
}
/**
* 后台登录
*/
public function login(){
$name = $_POST['username'] ? $_POST['username'] : "";
$password = $_POST['password'] ? $_POST['password'] : "";
$this->load->model('form_model');
if(empty($name) || $password == null){
echo "<script>alert('请正确填写用户和密码!')</script>";
exit();
}
$get_user = $this->form_model->get_user($name,$password);
if($get_user){
foreach($get_user as $k => $v){
$username = $v['adminname'];
}
$this->session->set_userdata('username',$username);
$session = $this->session->userdata("username");
echo "<script>alert('登录成功!')</script>";
}else{
echo "<script>alert('登录失败!');self.location = document.referrer</script>";
}
}
/**
* 用户登出
*/
public function login_out(){
$data['base_url'] = base_url();
$this->session->set_userdata('username',"");
if($this->session->userdata('username') == null){
$this->load->view('form/login.html',$data);
}
}
/**
* 后台管理员修改密码
*/
public function update_password(){
$name = $_POST['username'] ? $_POST['username'] : "";
$pass = $_POST['password'] ? $_POST['password'] : "";
$this->load->model('form_model');
if(empty($name) || empty($pass)){
echo "<script>alert('用户名和密码不能为空!')</script>";
exit();
}
$salt = $this->salt_string();
$updata_user = $this->form_model->update_user($name,$pass,$salt);
if($updata_user){
echo "<script>alert('修改成功!');</script>";
// echo "<script>alert('修改成功!');window.href = '/index.php?c=login&m=login';</script>";
$this->load->view();
}elseif($updata_user == null){
echo "<script>alert('用户名不存在!');self.location = document.referrer</script>";
}elseif(!$updata_user){
echo "<script>alert('修改失败!');self.location = document.referrer</script>";
}
}
/**
* 生成一个随机字符串
*/
public function salt_string($len = 6){
//密码字符集
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$pass = "";
for($i = 0; $i < $len; $i++){
$pass .= $chars[mt_rand(0,strlen($chars) - 1)];
}
return $pass;
}
}<file_sep>/work/camel/Backstage/application/models/Admin_model.php
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2017/5/26
* Time: 23:45
*/
class admin_model extends CI_model{
function __construct()
{
parent::__construct();
$this->load->database('app_novel');
}
/**
* 用户注册
*/
public function add_user_info($name,$password){
if(empty($name) || empty($password)){
return false;
}
$sql = "insert into bq_Admin(username,password,salt,status,visible)
VALUES ('$name','$password','<PASSWORD>','1','1')";
$res = $this->db->query($sql);
if($res){
return true;
}else{
return false;
}
}
/**
* 用户查询
*/
public function get_user_name($name,$password){
if(empty($name) || empty($password)){
return false;
}
$salt = '<PASSWORD>';
$password = md5(md5($password).$salt);
$sql = "select * from bq_Admin
WHERE username = '$name' AND password = <PASSWORD>' AND status = 1";
$res = $this->db->query($sql);
$arr = $res->result_array();
return $arr ? $arr : null;
}
}<file_sep>/work/camel/application/libraries/Cismarty.php
<?php
/**
* Created by PhpStorm.
* User: pengfan
* Date: 2017/6/21
* Time: 9:17
*/
if (!defined('BASEPATH')) exit('No direct script access allowed');
require(APPPATH . 'libraries/smarty/Smarty.class.php');
class Cismarty extends Smarty
{
public function __construct()
{
parent::__construct();
$this->caching = false;
//设定所有模板文件都需要放置的目录地址。
$this->setTemplateDir(APPPATH . 'views/Smarty/templates');
//设定用于存放模板特殊配置文件的目录,
$this->setConfigDir(APPPATH . 'views/Smarty/configs');
//在启动缓存特性的情况下,这个属性所指定的目录中放置Smarty缓存的所有模板
$this->setCacheDir(APPPATH . 'views/Smarty/cache');
//插件目录
$this->setPluginsDir(APPPATH . 'views/Smarty/plugins');
//设定Smarty编译过的所有模板文件的存放目录地址
$this->setCompileDir(APPPATH . 'views/Smarty/templates_c');
$this->left_delimiter = '<{';
$this->right_delimiter = '}>';
}
}<file_sep>/work/camel/Backstage/application/controllers/Index.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Created by PhpStorm.
* User: pengfan
* Date: 2017/6/20
* Time: 13:20
*/
class Index extends CI_Controller
{
function __construct(){
parent::__construct();
$this->load->library('session');
$this->load->helper('url');
}
public function index(){
echo "111";
}
}<file_sep>/work/camel/Backstage/application/models/form_model.php
<?php
/**
* Created by PhpStorm.
* User: pengfan
* Date: 2017/6/19
* Time: 14:09
*/
class form_model extends CI_model
{
public function __construct()
{
parent::__construct();
$this->m_sqldb = $this->load->database('camel',TRUE);
}
/**
* 用户注册
* @param $name-名称 $pass-密码 $salt-随机字符
* @return yes or no or repeat
*/
public function add_user($name,$pass,$salt){
if(empty($name) && empty($pass)){
return false;
}
$reg_ip = $_SERVER['REMOTE_ADDR'];
$reg_time = time();
$status = 1;
$sql = "select * from `bq_admin` WHERE `adminname` = '$name'";
$res = $this->m_sqldb->query($sql);
$arr = $res->result_array();
if(!empty($arr[0]['adminname'])){
return "repeat";
}
$sql = "insert into `bq_admin`(adminname,password,reg_ip,reg_time,status,salt)
VALUES ('$name','$pass','$reg_ip','$reg_time','$status','$salt')";
$res = $this->m_sqldb->query($sql);
if($res){
return "yes";
}else{
return "no";
}
}
/**
* 用户登录
* @param $name -用户名 $pass -用户密码
* @return array or false
*/
public function get_user($name,$pass){
if(empty($name) && empty($pass)){
return false;
}
$last_login_ip = $_SERVER["REMOTE_ADDR"];
$last_login_time = time();
$sql = "select * from `bq_admin` WHERE `adminname` = '$name'";
$res = $this->m_sqldb->query($sql);
$data = $res->result_array();
if(!empty($data)){
foreach($data as $k => $v){
$salt = $v['salt'];
$password = $v['password'];
}
$pass_salt = md5(md5($pass).$salt);
if(!empty($salt) && $pass_salt == $password){
$sql = "update `bq_admin` set `last_login_ip` = '$last_login_ip',`last_login_time` = '$last_login_time'
WHERE `adminname` = '$name'";
$res = $this->m_sqldb->query($sql);
if($res){
return $data;
}
}else{
return false;
}
}
}
/**
* 后台管理员修改密码
* @param $name -用户名 $pass - 密码
* @return false or true or null
*/
public function update_user($name,$pass,$salt){
if(empty($name) || empty($pass)){
return false;
}
$pass = md5(md5($pass).$salt);
$sql = "select * from `bq_admin` WHERE `adminname` = '$name'";
$res = $this->m_sqldb->query($sql);
$arr = $res->result_array();
if(!empty($arr[0]['adminname'])){
$sql = "update `bq_admin` set `password` = <PASSWORD>',`salt` = <PASSWORD>' WHERE `adminname` = '$name'";
$res = $this->m_sqldb->query($sql);
if($res){
return true;
}else{
return false;
}
}else{
return null;
}
}
}<file_sep>/work/camel/application/controllers/login.php
<?php
/**
* Created by PhpStorm.
* User: pengfan
* Date: 2017/5/2
* Time: 12:20
*/
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends MY_Controller
{
function __construct(){
parent::__construct();
$this->load->library('session');
$this->load->helper('url');
$this->load->helper(array('form', 'url'));
}
/**
* 官网登录页面
*/
public function index()
{
$this->load->view('login');
}
/**
* 注册页面
*/
public function register_page(){
$this->load->view();
}
/**
* 修改密码页面
*/
public function update_page(){
$this->load->view();
}
/**
* 官网会员注册
*/
public function register_in(){
$name = $_POST['username'] ? $_POST['username'] : "";
$pass = $_POST['password'] ? $_POST['password'] : "";
$phone = $_POST['phone'] ? $_POST['phone'] : "";
$headimg = "";
$email = $_POST['email'] ? $_POST['email'] : "";
$reg_ip = $_SERVER['REMOTE_ADDR'];
$reg_time = time();
$salt = $this->salt_string();
$arr = array();
if(empty($name) || $pass == null){
$arr['code'] = '-1';
$arr['msg'] = '账号或密码不能为空!';
}
return $this->_push_json($arr);
}
/**
* 官网会员登录
*/
public function login(){
$name = $_POST['username'] ? $_POST['username'] : "";
$pass = $_POST['password'] ? $_POST['password'] : "";
$login_ip = $_SERVER['REMOTE_ADDR'];
$last_login_time = time();
$this->load->model('lo_model');
if(empty($name) || empty($pass)){
return false;
}
$user_info = $this->lo_model->get_user($name,$pass,$login_ip,$last_login_time);
if(is_array($user_info)){
foreach($user_info as $k => $v){
$nickname = $v['nickname'];
}
$this->session->set_userdata('nickname',$nickname);
$session = $this->session->userdata("username");
$arr = array(
'code' => '200',
'msg' => '登录成功!',
'data' => $session
);
return $this->_push_json($arr);
}elseif($user_info == "no"){
$arr = array(
'code' => '-1',
'msg' => '密码错误!',
);
return $this->_push_json($arr);
}elseif(empty($user_info)){
$arr = array(
'code' => '-2',
'msg' => '用户不存在!'
);
return $this->_push_json($arr);
}
}
/**
* 会员修改密码
*/
public function update_user(){
$name = $_POST['username'] ? $_POST['username'] : "";
$phone = $_POST['phone'] ? $_POST['phone'] : "";
$pass = $_POST['password'] ? $_POST['password'] : "";
$salt = $this->salt_string();
$this->load->model('lo_model');
if(empty($name) || empty($phone) || empty($pass)){
return false;
}
$update_user = $this->lo_model->update_user($name,$phone,$pass,$salt);
$arr = array();
if($update_user == null){
$arr['code'] = "-1";
$arr['msg'] = "用户名不存在!";
}elseif($update_user){
echo "<script>alert('密码修改成功!');</script>";
$arr['code'] = "200";
$arr['msg'] ="密码修改成功!";
}else{
$arr['code'] = '-2';
$arr['msg'] = "密码修改失败!";
}
return $this->_push_json($arr);
}
/**
* 用户个人信息
*/
public function get_user_info(){
$name = $_GET['username'] ? $_GET['username'] : "";
$uid = $_GET['uid'] ? $_GET['uid'] : "";
$this->load->model('lo_model');
if(empty($name) || empty($uid)){
return false;
}
$get_user = $this->lo_model->get_user_info($name,$uid);
if($get_user){
$this->assign('data',$get_user);
$this->display('test.html');
}else{
$arr = array(
'code' => '-1',
'msg' => '获取信息失败!'
);
return $this->_push_json($arr);
}
}
/**
* 修改绑定邮箱或绑定手机
*/
public function update_info(){
$name = $_GET['username'] ? $_GET['username'] : "";
$uid = $_GET['uid'] ? $_GET['uid'] : "";
$email = $_GET['email'] ? $_GET['email'] : "";
$phone = $_GET['phone'] ? $_GET['phone'] : "";
$this->load->model('lo_model');
if(empty($name) || empty($uid)){
return false;
}
$arr = array();
$update_email = $this->lo_model->updata_user_email($name,$uid,$email,$phone);
if($update_email){
$arr['code'] = "200";
$arr['msg'] = '修改成功!';
}else{
$arr['code'] = '-1';
$arr['msg'] = '修改失败!';
}
return $this->_push_json($arr);
}
/**
* 修改用户基本信息
*/
public function update_user_info(){
$param = $_POST;
if(empty($param)){
return false;
}
$this->load->model('lo_model');
$update_user = $this->lo_model->update_user($param);
$arr = array();
if($update_user){
$arr['code'] = '200';
$arr['msg'] = '信息修改成功!';
}else{
$arr['code'] = '-1';
$arr['msg'] = "修改失败!";
}
return $this->_push_json($arr);
}
/**
* 修改用户头像
*/
public function update_head_img(){
$param = $_POST ? $_POST : "";
$path = "";
$file_name = "";
$this->load->model('lo_model');
$add_img = $this->do_upload($path,$file_name);
$arr = array();
if($add_img){
$full_path = $add_img;
$update_headimg = $this->lo_model->update_headimg($full_path,$param);
}else{
$arr['code'] = "-1";
$arr['msg'] = "头像上传失败!";
}
return $this->_push_json($arr);
}
/**
* 上传文件的公共方法
* @param -$path 上传路径 $file_name -file name属性值
* @return url地址
*/
public function do_upload($path,$file_name){
$config['upload_path'] = $path;
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width']= 1024;
$config['max_height'] = 768;
$this->load->library('upload',$config);
if(!$this->upload->do_upload('user_img')){
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form',$error);
return false;
}else{
$data = $this->upload->data();
$this->load->view('upload_success' ,$data);
return $data['full_path'];
}
}
/**
* 获取六位随机字符串
* @param $len -字符长度
* @renturn string
*/
public function salt_string($len = 6){
$str = "abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";
$salt_sta = "";
for($i = 0; $i < $len; $i++){
$salt_sta .= $str[mt_rand(0,strlen($str) - 1)];
}
return $salt_sta;
}
/**
* 发送post请求
* @param $url -请求地址 $past_data -请求参数 $timeout -超时时间
*/
public function post($url,$post_data = '',$timeout = 5){
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,1);
if($post_data != ''){
curl_setopt($ch,CURLOPT_POSTFIELDS,$post_data);
}
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
curl_setopt($ch,CURLOPT_HEADER,false);
$file_contents = curl_exec($ch);
curl_close($ch);
return $file_contents;
}
/**
* 发送get请求
* @param $url -请求地址
*/
public function get($url){
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_HEADER,false);
$file_contents = curl_exec($ch);
curl_close($ch);
return $file_contents;
}
/**
* 将数组转换为json格式
* @param $data_array -需要转换的数组
*/
public function _push_json($data_array){
$data_json = json_decode($data_array);
return $data_json;
}
}
<file_sep>/work/camel/application/models/ar_model.php
<?php
/**
* Created by PhpStorm.
* User: pengfan
* Date: 2017/5/2
* Time: 9:38
*/
class ar_model extends CI_Model {
function __construct()
{
parent::__construct();
$this->m_novelDb = $this->load->database('test',true);
}
}
<file_sep>/work/camel/application/models/lo_model.php
<?php
/**
* Created by PhpStorm.
* User: pengfan
* Date: 2017/6/21
* Time: 13:32
*/
class lo_model extends CI_Model
{
function __construct()
{
parent::__construct();
$this->m_novelDb = $this->load->database('camel',true);
}
/**
* 会员登录
* @param $name -会员名 $pass -<PASSWORD>
* @return
*/
public function get_user($name,$pass,$login_ip,$login_time){
if(empty($name) || empty($pass)){
return false;
}
$sql = "select * from `uc_user` WHERE `nickname` = '$name' OR `mobile` = '$name'";
$res = $this->m_novelDb->query($sql);
$data = $res->result_array();
if(!empty($data)){
foreach($data as $k => $v){
$salt = $v['salt'];
$userpass = $v['password'];
}
$password = md5(md5($pass).$salt);
if($password == $userpass){
$sql = "update `uc_user` set `lastlogip` = '$login_ip' ,`lastlogtime` = '$login_time'
WHERE `nickname` = '$name'";
$res = $this->m_novelDb->query($sql);
if($res){
return $data;
}else{
return 'no';
}
}else{
return 'no';
}
}else{
return null;
}
}
/**
* 会员修改密码
* @param $name -用户名 $pass -新密码 $phone -用户手机号 $salt -6位随机字符
* @return true or false or null
*/
public function update_user($name,$phone,$pass,$salt){
if(empty($name) || empty($phone) || empty($pass) || empty($salt)){
return false;
}
$sql = "select * from `uc_user` WHERE `nickname` = '$name' AND `mobile` = '$phone'";
$res = $this->m_novelDb->query($sql);
$data = $res->result_array();
if(!empty($data)){
$password = md5(md5($pass).$salt);
$sql = "update `uc_user` set `password` = '$<PASSWORD>',`salt` = '$salt'
WHERE `$name` = '$name' AND `mobile` = '$phone'";
$res = $this->m_novelDb->query($sql);
if($res){
return true;
}else{
return false;
}
}else{
return null;
}
}
/**
* 获取会员信息
* @param $name -用户名 -用户id
* @return true or false or null
*/
public function get_user_info($name,$uid){
if(empty($name) || empty($uid)){
return false;
}
$sql = "select * from `uc_user` WHERE `uid` = '$uid' AND `nickname` = '$name'";
$res = $this->m_novelDb->query($sql);
$arr = $res->result_array();
return $arr ? $arr : null;
}
/**
* 修改会员绑定邮箱
* @param $name -用户名称 $id -用户的uid $email -用户输入的邮箱 $phone -用户输入的手机号
* @return true or false
*/
public function updata_user_email($name, $id, $email = '', $phone = ''){
if(empty($name) || empty($id)){
return false;
}
$sql = "update `uc_user` set";
if(empty($email)){
$sql .= " `mobile` = '$phone'";
}
if(empty($phone)){
$sql .= " `email` = '$email'";
}
$sql .= " WHERE `uid` = '$id' AND `nickname` = '$name'";
$res = $this->m_novelDb->query($sql);
if($res){
return true;
}else{
return false;
}
}
/**
* 会员修改头像
* @param $path -头像文件路径 $data -用户信息参数
*/
public function update_headimg($path,$data){
if(empty($path) || empty($data)){
return false;
}
$sql = "";
}
}<file_sep>/work/camel/application/views/Smarty/templates_c/5aca27bfd90d7f0ff742745e8d65ba8091f94244_0.file.test.html.php
<?php
/* Smarty version 3.1.30, created on 2017-06-27 11:06:16
from "D:\phpStudy\WWW\camelinfo\camel\application\views\Smarty\templates\test.html" */
/* @var Smarty_Internal_Template $_smarty_tpl */
if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array (
'version' => '3.1.30',
'unifunc' => 'content_5951cba89134b8_61964371',
'has_nocache_code' => false,
'file_dependency' =>
array (
'5aca27bfd90d7f0ff742745e8d65ba8091f94244' =>
array (
0 => 'D:\\phpStudy\\WWW\\camelinfo\\camel\\application\\views\\Smarty\\templates\\test.html',
1 => 1498532771,
2 => 'file',
),
),
'includes' =>
array (
),
),false)) {
function content_5951cba89134b8_61964371 (Smarty_Internal_Template $_smarty_tpl) {
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
</style>
</head>
<body>
<?php
$_from = $_smarty_tpl->smarty->ext->_foreach->init($_smarty_tpl, $_smarty_tpl->tpl_vars['data']->value, 'item', false, 'key', 'name', array (
));
if ($_from !== null) {
foreach ($_from as $_smarty_tpl->tpl_vars['key']->value => $_smarty_tpl->tpl_vars['item']->value) {
?>
<?php if ($_smarty_tpl->tpl_vars['item']->value != '') {?>
<p><?php echo $_smarty_tpl->tpl_vars['item']->value['uid'];?>
</p>
<p><?php echo $_smarty_tpl->tpl_vars['item']->value['nickname'];?>
</p>
<?php }?>
<?php
}
}
$_smarty_tpl->smarty->ext->_foreach->restore($_smarty_tpl);
?>
</body>
</html><?php }
}
<file_sep>/work/camel/application/core/MY_Controller.php
<?php
/**
* Created by PhpStorm.
* User: pengfan
* Date: 2017/6/21
* Time: 9:27
*/
if (!defined('BASEPATH')) exit('No direct access allowed.');
class MY_Controller extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function assign($key,$val) {
$this->cismarty->assign($key,$val);
}
public function display($html) {
$this->cismarty->display($html);
}
}<file_sep>/work/camel/application/views/index.php
<?php
/**
* Created by PhpStorm.
* User: lemon
* Date: 2017/5/1
* Time: 11:15
*/
echo "<h1 style='width: 100%;text-align: center;margin: 100px 0'>陀迅首页,{$name}</h1>"; | 01b2ae87c478fe0d2898a2c47286f44f3f804fa1 | [
"PHP"
] | 11 | PHP | NeddiePeng/camelinfo | 6e949c6f31670bdaa034054c8c3f679bba5c6eb4 | 8dc9f7bccc98b41b0581e746ef37b38dc6a8306a |
refs/heads/master | <file_sep><?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StorePost extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
// 認可は別の場所で行う
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'title' => 'required|max:20',
'fishing_day' => 'required|date',
'fish_type' => 'required|max:20',
'weather' => 'required',
'time_zone' => 'required',
'place' => 'required|max:20',
'body' => 'required|max:400',
'photo' => 'file|image|mimes:jpeg,png,jpg,gif|max:10000',
];
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User; // Userモデルをインポート
use Illuminate\Support\Facades\Auth;
use App\Http\Requests\StoreUser;
class UserController extends Controller
{
/**
* 各アクションの前に実行させるミドルウェア
*/
public function __construct()
{
// $this->middleware('auth')->except(['index', 'show']);
// 登録していなくても、退会だけはできるようにする
$this->middleware('auth')->only('destroy');
$this->middleware('verified')->except(['index', 'show', 'destroy']);
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
//ユーザーの一覧表示
public function index()
{
$users = User::paginate(5); //すべてのユーザーを5件ずつ表示
return view('users.index', ['users' => $users]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \App\Http\Requests\StoreUser $request
* @return \Illuminate\Http\Response
*/
public function store(StoreUser $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
// ユーザー1件詳細表示
public function show(User $user)
{
// そのユーザーが投稿した記事のうち、最新5件を取得
$user->posts = $user->posts()->paginate(5);
return view('users.show', ['user' => $user]);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
// 更新用フォームへ移動
public function edit(User $user)
{
$this->authorize('edit', $user); // 認可を判断するpolisyのeditメソッド
return view('users.edit', ['user' => $user]);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\User $user
* @return \Illuminate\Http\Response
*/
// 実際の更新処理
public function update(Request $request, User $user)
{
$this->authorize('edit', $user); // 認可を判断するpolisyのeditメソッド
// name欄だけ検査のため元のStoreUserクラス内のバリデーションルールからname欄のルールだけ取り出す。
$request->validate([
'name' => (new StoreUser())->rules()['name']
]);
$user->name = $request->name;
$user->save();
// 完了後、更新したユーザーページへ移動。フラッシュメッセージをsessionに保存。
return redirect('users/'.$user->id)->with('my_status', 'プロフィールを更新しました。');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
// 1件削除
public function destroy(User $user)
{
$this->authorize('edit', $user); // 認可を判断するpolisyのeditメソッド
$user->delete();
// 完了後、ユーザー一覧ページへ移動。フラッシュメッセージをsessionに保存。
return redirect('users')->with('my_status', 'ユーザーを削除しました。');
}
}
<file_sep><?php
namespace Tests\Browser;
use Tests\DuskTestCase;
use Laravel\Dusk\Browser;
use Tests\Browser\Components\DatePicker;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use App\User;
use App\Post;
/**
* Post(記事)に関するテスト
*/
class PostTest extends DuskTestCase
{
// Dusk実行前にマイグレーションする
use DatabaseMigrations;
/**
* 記事に関する操作(作成、編集、削除)のテスト
*
* @return void
*/
public function testCRUD()
{
// ユーザーを作成
$user = factory(User::class)->create();
// 投稿する内容
$post = factory(Post::class)->make([
'id' => 1,
'user_id' => '$user->id' // 上で作成したユーザーを投稿者とする
]);
// 編集する内容
$update = factory(Post::class)->make();
$this->browse(function (Browser $browser) use ($user, $post, $update) {
$today = now();
$browser->loginAs($user)
->visit('/')
// 投稿
->press('#new-post') // 「釣果を投稿する」ボタンを押す
->assertPathIs('/laravel/tureta/public/posts/create') // 投稿ページであることを確認
->type('title', $post->title) // 題名を入力
->keys('#fishing_day', $post->fishing_day) // 釣行日を入力
->type('fish_type', $post->fish_type) // 魚種を入力
->select('weather', $post->weather) // 天気を入力
->select('time_zone', $post->time_zone) // 時間帯を入力
->type('place', $post->place) // 場所を入力
->type('body', $post->body) // 本文を入力
->press('投稿する') // 投稿する
->assertPathIs('/laravel/tureta/public/posts/'.$post->id) // 記事ページであることを確認
->assertSeeIn('#post-title', $post->title) // 題名を確認
// ->assertSeeIn('#post-fishig_day', $post->fishing_day) // 釣行日を確認
->assertSeeIn('#post-fish_type', $post->fish_type) // 魚種を確認
->assertSeeIn('#post-weather', $post->weather) // 天気を確認
->assertSeeIn('#post-time_zone', $post->time_zone) // 時間帯を確認
->assertSeeIn('#post-place', $post->place) // 場所を確認
->assertSeeIn('#post-body', $post->body) // 本文を確認
// 編集
->press('.edit .btn-primary')
->assertPathIs('/laravel/tureta/public/posts/'.$post->id.'/edit')
->type('title', $update->title)
->type('body', $update->body)
->press('[type="submit"]')
->assertPathIs('/laravel/tureta/public/posts/'.$post->id)
->assertSeeIn('#post-title', $update->title)
->assertSeeIn('#post-body', $update->body)
// 削除
->press('削除') // 「削除」ボタンを押す
->whenAvailable('.modal', function ($modal) { // モーダルが表示されるまで待つ
$modal->press('.modal-footer .btn-danger') // モーダル内の「削除」ボタンを押す
->assertPathIs('/laravel/tureta/public/posts'); // 一覧ページであることを確認
});
});
}
}<file_sep><?php
/** @var \Illuminate\Database\Eloquent\Factory $factory */
use App\Post;
use Faker\Generator as Faker;
$factory->define(Post::class, function (Faker $faker) {
return [
'title' => $faker->text(20),
'fishing_day' => $faker->date("Ymd"),
'fish_type' => $faker->text(20),
'weather' => $faker->randomElement(['晴れ', '曇り', '雨', '雪']),
'time_zone' => $faker->randomElement(['朝', '昼', '夕方', '夜']),
'place' => $faker->text(20),
'body' => $faker->text(200),
'path' => 'no_image.png',
];
});
<file_sep><?php
namespace Tests\Unit;
use Tests\TestCase;
use App\User;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
class PracticeTest extends TestCase
{
/**
* A basic unit test example.
*
* @return void
*/
public function testExample()
{
// レコード新規作成
$user = new User;
$user->name = "テスト太郎";
$user->email = "<EMAIL>";
$user->password = \Hash::make('<PASSWORD>');
$user->save();
// SELECT
$readUser = User::Where('name','テスト太郎')->first();
$this->assertNotNull($readUser); // データが取得できたかテスト
$this->assertTrue(\Hash::check('test_password', $readUser->password));
// レコード削除
User::where('email', '<EMAIL>')->delete();
}
}
<file_sep><?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class UsersTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
//Fakerを使う
$faker = Faker\Factory::create('ja_JP');
//固定ユーザー作成
DB::table('users')->insert([
'name' => 'turikichi',
'email' => '<EMAIL>',
'password' => bcrypt('<PASSWORD>'),
'email_verified_at' => $faker->dateTime(),
'created_at' => $faker->dateTime(),
'updated_at' => $faker->dateTime(),
]);
DB::table('users')->insert([
'name' => 'guest',
'email' => '<EMAIL>',
'password' => bcrypt('<PASSWORD>'),
'email_verified_at' => $faker->dateTime(),
'created_at' => $faker->dateTime(),
'updated_at' => $faker->dateTime(),
]);
//ランダムにユーザー作成
for ($i=0; $i < 18; $i++) {
DB::table('users')->insert([
'name' => $faker->unique()->userName(),
'email' => $faker->unique()->email(),
'password' => bcrypt('<PASSWORD>'),
'email_verified_at' => $faker->dateTime(),
'created_at' => $faker->dateTime(),
'updated_at' => $faker->dateTime(),
]);
}
}
}
<file_sep><?php
namespace Tests\Browser;
use Tests\DuskTestCase;
use Laravel\Dusk\Browser;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use App\User;
class LoginTest extends DuskTestCase
{
// dusk実行前にマイグレーションする
use DatabaseMigrations;
/**
* ログイン機能テストをする
*
* @return void
*/
public function testLogin()
{
// ユーザーを作成しておく
$user = factory(User::class)->create([
'email' => '<EMAIL>',
'password' => bcrypt('<PASSWORD>'),
]);
$this->browse(function (Browser $browser) use ($user) {
$browser->visit('/login') // ログインページへ移動
->type('email', $user->email) // メールアドレスを入力
->type('password', '<PASSWORD>') // パスワードを入力
->press('ログイン') // 送信ボタンをクリック
->assertPathIs('/laravel/tureta/public/users/'.$user->id); // プロフィールページへ移動していることを確認
});
}
}
<file_sep><?php
// my_is_current_controller という関数が定義されているかどうか
if (! function_exists('my_is_current_controller')) {
/**
* 現在のコントローラ名が、複数の名前のどれかに一致するかどうかを判別する
*
* @param array $names コントローラ名 (可変長引数)
* @return bool
*/
// 定義されていない場合はmy_is_current_controllerを定義
function my_is_current_controller(...$names) // 可変長引数…引数は、指定した変数$namesに配列として渡される
{
/**
* Route::currentRouteName()…得られる結果は posts.index, posts.show など
* explode()…第一引数'.'を区切りとし、配列として取り出す
*/
$current = explode('.', Route::currentRouteName())[0]; //[0]でコントローラー名のみ取り出す
// $currentが配列$namesにあればTRUEを返す
return in_array($current, $names, true);
}
}<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post; // Postモデルをインポート
use App\User;
use App\Http\Requests\StorePost;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
class PostController extends Controller
{
/**
* 各アクションの前に実行させるミドルウェア
*/
public function __construct()
{
// $this->middleware('auth')->except(['index', 'show']);
$this->middleware('verified')->except(['index', 'show']);
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
// 一覧表示
public function index()
{
// 釣行日の新しい順で記事を8件ずつ一覧表示
$posts = Post::orderByDesc('fishing_day')->paginate(8); //latest(), oldest() デフォルトでcreated_atカラムによりソートされる。
return view('posts.index', ['posts' => $posts]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
// 新規投稿用フォームへ移動
public function create()
{
return view('posts.create');
}
/**
* Store a newly created resource in storage.
*
* @param App\Http\Requests\StorePost $request
* @return \Illuminate\Http\Response
*/
// 実際の投稿処理
public function store(StorePost $request)
{
$post = new Post; //新しいインスタンスを作成
if(!empty($request->file('photo'))){
// ログインしているユーザーを取得
$user = Auth::user();
// ファイル名取得
$filename = $user->id . $request->file('photo')->getClientOriginalName();
// storage/app/publicにファイルを保存する
$request->file('photo')->storeAs('public', $filename);
$post->path = $filename;
}
$post->title = $request->title; //それぞれの値を保存して
$post->fishing_day = $request->fishing_day;
$post->fish_type = $request->fish_type;
$post->weather = $request->weather;
$post->time_zone = $request->time_zone;
$post->place = $request->place;
$post->body = $request->body;
$post->user_id = $request->user()->id; // $request->user()は認証済みのユーザーを返す
$post->save(); //DBに保存
// 完了後、投稿した記事のページへ移動。フラッシュメッセージをsessionに保存。
return redirect('posts/'.$post->id)->with('my_status', '記事を投稿しました。');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
//1件ごとの詳細表示
public function show(Post $post)
{
return view('posts.show', ['post' => $post]);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
//更新用フォームへ移動
public function edit(Post $post)
{
$this->authorize('edit', $post); // 認可を判断するpolisyのeditメソッド
return view('posts.edit', ['post' => $post]);
}
/**
* Update the specified resource in storage.
*
* @param App\Http\Requests\StorePost $request
* @param int $id
* @return \Illuminate\Http\Response
*/
// 実際の更新処理
public function update(StorePost $request, Post $post)
{
$this->authorize('edit', $post); // 認可を判断するpolisyのeditメソッド
if(!empty($request->file('photo'))){
if($post->path !== 'no_image.png'){
// 投稿済みの画像ファイルの削除
$deleteFile = 'public/' . $post->path;
Storage::delete($deleteFile);
}
// ファイル名取得
$filename = $post->user_id . $request->file('photo')->getClientOriginalName();
// storage/app/publicにファイルを保存する
$request->file('photo')->storeAs('public', $filename);
$post->path = $filename;
}
$post->title = $request->title; //それぞれの値を保存して
$post->fishing_day = $request->fishing_day;
$post->fish_type = $request->fish_type;
$post->weather = $request->weather;
$post->time_zone = $request->time_zone;
$post->place = $request->place;
$post->body = $request->body;
$post->save(); //DBに保存
//完了後、更新した記事のページへ移動。フラッシュメッセージをsessionに保存。
return redirect('posts/'.$post->id)->with('my_status', '記事を更新しました。');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
// 1件削除
public function destroy(Post $post)
{
$this->authorize('edit', $post); // 認可を判断するpolisyのeditメソッド
if($post->path !== 'no_image.png'){
// 画像がある場所のパスを指定し、画像ファイルの削除
$deleteFile = 'public/' . $post->path;
Storage::delete($deleteFile);
}
$post->delete();
// 完了後、一覧ページへ移動。フラッシュメッセージをsessionに保存。
return redirect('posts')->with('my_status', '記事を削除しました。');
}
}
| 8015e60663e3e6df66bf888be1ec5c1b35a3cbd4 | [
"PHP"
] | 9 | PHP | MasahiroTamaki/tureta | 39243d8cd17a61d609cc476f415b1c2a8f31b771 | a31e29cd99b6aeda01ef53dd45dd0837040f89ac |
refs/heads/master | <repo_name>vradika/2020_0091_java<file_sep>/09_class/src/com/ict/edu01/Ex05.java
package com.ict.edu01;
// 1. Member 내부클래스 // 3. Static 내부클래스
public class Ex05 {
// 멤버필드
String name = "홍길동";
private int age = 24;
static boolean gender = true;
public Ex05() {
System.out.println("외부 >> " + this);
}
// 외부클래스 멤버메소드
public void play() {
int money = 10000;
// 지역변수는 static 사용 불가
// static int time = 120;
// static final int time = 120;
System.out.println("외부메소드 >> " + money);
}
// Member 내부 클래스
public class Inner01 {
int k1 = 100;
// static 사용 못함 => 클래스에 static 붙이면 사용 가능해짐.
// static int k2 = 100;
// 사용가능
static final int k2 = 200;
// 내부클래스생성자
public Inner01() {
System.out.println("내부 >> " + this);
}
public void prn() {
System.out.println(k1);
System.out.println(k2);
System.out.println(Inner01.k2);
System.out.println("======================");
// 외부클래스의 마음대로 사용할 수 있다. 멤버필드
System.out.println(name);
System.out.println(age); // private로 사용 가능
System.out.println("======================");
// 멤버 메소드
play();
}
} // 내부 클래스 끝
// static 내부 클래스
public static class Inner02 {
int a1 = 100;
final int a2 = 200;
static int a3 = 300; // 클래스 static을 붙이지 않으면 오류
static final int a4 = 400;
public void go() {
// 외부클래스의 인스턴스 전역변수 못 가져옴
// System.out.println(name);
// System.out.println(age);
// 외부클래스의 static은 가져옴
System.out.println(gender);
System.out.println(a1);
System.out.println(a2);
System.out.println(a3);
System.out.println(a4);
}
// static 메소드는 static만 사용 가능
public static void go2() {
// 외부클래스의 static은 가져옴
System.out.println(gender);
// System.out.println(name);
// System.out.println(age);
// System.out.println(a1);
// System.out.println(a2);
System.out.println(a3);
System.out.println(a4);
}
}
} // 외부 클래스 끝
<file_sep>/11_Collection/src/com/ict/edu01/Ex04_main.java
package com.ict.edu01;
import java.util.HashSet;
import java.util.Scanner;
public class Ex04_main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Ex04[] arr = new Ex04[3];
for (int i = 0; i < arr.length; i++) {
Ex04 Person = new Ex04();
System.out.print("이름 >> ");
Person.setName(sc.next());
System.out.print("국어 >> ");
int kor; kor = sc.nextInt();
System.out.print("영어 >> ");
int eng; eng = sc.nextInt();
System.out.print("수학 >> ");
int math; math = sc.nextInt();
Person.s_sum(kor, eng, math);
arr[i] = Person;
}
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
if (arr[i].getSum() < arr[j].getSum()) {
arr[i].setRank(arr[i].getRank() + 1);
}
}
}
Ex04 tmp = new Ex04();
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i].getRank() > arr[j].getRank()) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
}
System.out.println("이름\t총점\t평균\t학점\t순위");
HashSet<Ex04> set = new HashSet<Ex04>();
set.add(arr[0]);
set.add(arr[1]);
set.add(arr[2]);
for (Ex04 k : set) {
System.out.print(k.getName() + "\t");
System.out.print(k.getSum() + "\t");
System.out.print(k.getAvg() + "\t");
System.out.print(k.getHak() + "\t");
System.out.println(k.getRank());
}
}
}
<file_sep>/12_Debugging_JUnit/src/com/ict/test/Ex01_Test.java
package com.ict.test;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.ict.junit.Ex01;
// JUnit : 단위 테스트(메소드 단위로 테스트) 도구, 이클립스에서 기본적으로 제공
// 블랙박스 테스트 : 입력값을 넣으면 예상값이 일치하면 성공,
// 예상값이 일치하지 안으면 실패.
// assertEquals : 기본형 변수 또는 객체의 값이 예상값과 일치하는지 검사하는 메소드
// assertSame : 두 객체가 같은 객체 인지 검사 (주소가 일치하는지 검사하는 메소드)
// assertNull : null인지 검사
// assertNotNull : null이 아닌지 검사
// assertTrue(e) : a가 참인지 검사
// assertArrayEquals : 배열 a 와 배열 b가 일치하는지 확인
public class Ex01_Test {
Ex01 t1;
// 테스트 전 : 실행할 메소드의 클래스를 객체 생성
// 애노테이션: 주석의 일종으로 컴파일러에게 지시를 내리는 것
@Before
public void tBefore() {
System.out.println("실행 클래스를 객체 생성하자");
t1 = new Ex01();
}
// 테스트를 실행하는 메소드
@Test
public void addTest() {
// 메소드를 실행한 결과값
int res = t1.add(10, 20);
// expected => 예상값, actual => 결과값
assertEquals(30, res);
}
@Test
public void subTest() {
// 메소드를 실행한 결과값
int res = t1.sub(1, 5);
// expected => 예상값, actual => 결과값
assertEquals(-4, res);
}
// 테스트 실행 후
@After
public void tAfter() {
System.out.println("데트스 실행 후 메소드 실행");
}
}
<file_sep>/Practice/src/Practice1/Practice1.java
package Practice1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Practice1 {
public static void main(String[] args) throws IOException {
// 문제 7. BufferedReader를 이용하여 입력받아 두개의 수 중 큰 수를 출력하시오.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int a = 0;
int b = 0;
System.out.print("A >> "); a = Integer.parseInt(br.readLine());
System.out.print("B >> "); b = Integer.parseInt(br.readLine());
System.out.println("큰 수 >> " + (a > b ? a : b));
}
}
<file_sep>/11_Collection/src/com/ict/edu01/Ex11.java
package com.ict.edu01;
import java.util.HashMap;
import java.util.Iterator;
public class Ex11 {
public static void main(String[] args) {
// Map 인터페이스: Key 와 Value를 맵핑하는 구조로 이루어짐
// Key는 중복될 수 없다.
// Key를 호출하면 Value가 나온다.
// Key를 별도 관리 => keySet()
// add()로 추가 못함
// put(key, value) 추가한다.
// Map생성 (Key 숫자로 만든다.)
HashMap<Integer, String> map = new HashMap<Integer, String>();
// 추가: add x, key(k, v)
map.put(0, "한국");
map.put(1, "미국");
map.put(4, "중국");
map.put(9, "태국");
map.put(15, "영국");
map.put(20, "한국"); // value의 중복은 상관없다.
map.put(22, "한국");
map.put(4, "영국"); // key 중복: 덮어쓴다.
System.out.println(map);
// 하나씩 출력 (get(key) => value가 나온다)
System.out.println(map.get(4));
System.out.println(map.get("한국"));
System.out.println("=================================================");
// 일부러 key를 순서대로 만들었기 때문에 for문을 사용할 수 있다.
// map에서 value를 호출하는 방법: get(key)
for (int i = 0; i < map.size(); i++) {
System.out.println(map.get(i));
}
System.out.println("=================================================");
// 1씩 증가 하지 않아도, 일정한 규칙이 없이도 사용가능
for (Integer k : map.keySet()) {
System.out.println(map.get(k));
}
System.out.println("=================================================");
// Map 생성 (Key를 문자열(String)로 만든다 => 일반적인 방법)
HashMap<String, String> map1 = new HashMap<String, String>();
map1.put("이름", "고길동");
map1.put("나이", "34");
map1.put("주소", "서울시 도봉구 방학동");
map1.put("성별", "남");
map1.put("취미", "잠자기");
System.out.println(map1.get("이름"));
System.out.println(map1.get("나이"));
System.out.println(map1.get("주소"));
System.out.println(map1.get("성별"));
System.out.println(map1.get("취미"));
System.out.println("=================================================");
for (String k : map1.keySet()) {
System.out.println(map1.get(k));
}
System.out.println("=================================================");
Iterator<String> it = map1.keySet().iterator();
while (it.hasNext()) {
String res = (String) it.next();
System.out.println(map1.get(res));
}
}
}
<file_sep>/16_Server/src/com/ict/edu01/Ex01.java
package com.ict.edu01;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
// 자바통신은 소켓 통신이다.
// 소켓은 읽기/쓰기 위한 인터페이스를 제공한다.
// 포트 : 내부와 외부를 연결하는 게이트 역할을 한다.
// 0 ~ 65535, 0 ~ 1024는 사용자가 지정하지 않는다.
// 서버 : ServerSocket, 클라이언트 Socket
// 192.168.3.11
public class Ex01 {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(7777);
System.out.println("서버 대기중...");
// 클라이언트가 접속할 때 까지 기다린다.
// 접속을 하면 담당소켓을 하나 만든다.
// 담당소켓(s)은 접속한 클라이언트의 정보를 가지고 있다.
Socket s = ss.accept();
// 클라이언트에 대한 정보 출력
String ip = s.getInetAddress().getHostAddress();
String name = s.getInetAddress().getHostName();
System.out.println("ip: " + ip);
System.out.println("name: " + name);
System.out.println("서버: 수고 하셨습니다.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
<file_sep>/03_if_while/src/com/ict/edu/Ex08.java
package com.ict.edu;
public class Ex08 {
public static void main(String[] args) {
// 중첩 while문 : while문 안에 while문
// 다중 for문과 같다.
for (int i = 1; i < 4; i++) {
for (int j = 1; j < 6; j++) {
System.out.println("i= "+ i + ", " + "j= " + j);
}
}
System.out.println();
int k1 = 1;
while (k1 < 4) {
int g1 = 1;
while (g1 < 6) {
System.out.println("k1= "+ k1 + ", " + "g1= " + g1);
g1++;
}
k1++;
}
System.out.println();
// 구구단
int dan1 = 2;
while (dan1 < 10) {
System.out.println(dan1 + "단");
int su1 = 1;
while (su1 < 10) {
System.out.println(dan1 + "*" + su1 + "= " + dan1*su1);
su1++;
}
dan1++;
System.out.println();
}
}
}
<file_sep>/Ex_Lotto/src/Lotto/Lotto1.java
package Lotto;
public class Lotto1 {
public static void main(String[] args) {
int[] Lotto = new int[7];
System.out.println("====***$$$ 로또 번호 자동 생성기 $$$***====");
for (int i = 0; i < Lotto.length; i++) {
Lotto[i] = (int)(Math.random()* 45 + 1);
for (int j = 0; j < i; j++) {
if (Lotto[j] == Lotto[i]) {
i--;
break;
}
}
}
for (int i = 0; i < Lotto.length; i++) {
System.out.print(Lotto[i] + "\t");
}
System.out.println();
System.out.println("실망하지마세요! 보너스 번호가 있으니까요!");
System.out.println("마지막 보너스 번호 >> " + Lotto[6]);
}
}
<file_sep>/13_Thread/src/com/ict/edu01/Ex03.java
package com.ict.edu01;
// Thread 클래스는 start(), run()가 존재한다
// Thread 를 상속한 곳애 run() 존재.
public class Ex03 extends Thread {
public void go() {
System.out.println(currentThread().getName() + " : go() 메소드");
}
public void run() {
System.out.println(currentThread().getName() + " : run() 메소드");
}
}
<file_sep>/after/src/com/ict/java01/Ex01.java
package com.ict.java01;
public class Ex01 {
public static void main(String[] args) {
// Ex1. 자바에서 사용하는 기본 자료형
// 자료형(Data Type)이란? >> 자바에서 사용하는 데이터의 형태를 구분
// 자료형 : 키워드
// boolean형 : boolean : true(참), false(거짓)
// 문자형 : char : 숫자로 저장된다. (a => 97, A=> 65)
// 정수형 : byte, short, int, long : 일반적으로 정수 int
// 실수형 : float, double : 일반적으로 실수 double
// 주의사항 : String 기본 자료형으로 사용하지만 기본 자료형은 아니다.
// : String 처럼 자료형으로 사용하는 것을 참조 자료형이라 한다.
// Ex2. 정수값 10을 su라는 변수에 넣고 변수 su에 데이터 들어갔는지 확인하는 코딩을 하자
int su = 10;
System.out.println(su);
// boolean b1에 참을 저장하자
boolean b1 = true;
System.out.println(b1);
// 실수값 3.14를 d1에 저장하자
double d1 = 3.14;
System.out.println(d1);
System.out.println();
// Ex3. a++ 과 ++a의 차이점을 쓰시오
// a++ : 현재 변수값으로 연산한 후 나중에 변수 값을 1 증가 시킨다.
int a = 10;
System.out.println(a++);
System.out.println(a);
// ++a : 현재 변수값을 먼저 1 증가 시키고 난 후, 나머지 연산을 수행한다.
int b = 10;
System.out.println(++b);
System.out.println(b);
System.out.println();
// Ex4. 논리 연산자 AND와 OR에 대해서 쓰시오
// AND(논리곱, 교집합, &&) : 주어진 조건들이 모두 true일 때 결과가 true이다.
// : 만약에 조건들 중 하나라도 false가 있으면 결과는 false
// : false를 만나면 false 뒤에 연산은 하지 않는다.
// OR(논리합, 합집합, ||) : 주어진 조건이 모두 false일 때 false
// : 조건들 중 하나라도 true면 결과는 true
// : true를 만나면 true 뒤에 연산은 하지 않는다.
boolean b2 = true;
boolean b3 = true;
boolean b4 = false;
boolean b5 = false;
boolean res = b2 && b3;
System.out.println("res = " + res);
res = b3 && b4;
System.out.println("res = " + res);
res = b4 && b5;
System.out.println("res = " + res);
System.out.println();
boolean res1 = b2 || b3;
System.out.println("res = " + res1);
res1 = b3 || b4;
System.out.println("res = " + res1);
res1 = b4 || b5;
System.out.println("res = " + res1);
System.out.println();
// Ex5. int su = 24 일 때 삼항연산자를 활용해서 홀수인지, 짝수인지 판별할 수 있는 코딩을 쓰시오
// 삼항연산자 : 자료형 변수 이름 = (조건식=boolean) ? 참일 때 실행 : 거짓일 떄 실행
// 자료형 변수 이름, 참일 때 실행 결과값, 거짓일 떄 실행 결과값 모두 같은 자료형이어야 한다.
int num = 24;
String msg = (num % 2 == 1) ? "홀수" : "짝수";
String msg1 = (num % 2 == 0) ? "짝수" : "홀수";
System.out.println(msg);
System.out.println(msg1);
}
}
<file_sep>/07_class/src/com/ict/edu/Ex03.java
package com.ict.edu;
import java.util.Random;
public class Ex03 {
public static void main(String[] args) {
// 이클립스에서 API 호출: 해당 클래스에 커서를 놓고 shift + f2
// 랜덤: Math.random(), Random 클래스
// 1. Random 클래스
Random ran = new Random();
// 각종 자료형을 난수로 발생: 자료형 범위 안에서 난수 발생
System.out.println("boolean형 >> " + ran.nextBoolean());
System.out.println("int형 >> " + ran.nextInt());
System.out.println("long형 >> " + ran.nextLong());
// float와 double은 0.0 이상 ~ 1.0 미만 난수 발생
System.out.println("float형 >> " + ran.nextFloat());
System.out.println("double형 >> " + ran.nextDouble());
// 특정 범위를 지정하는 방법:
// 1) nextInt(범위): 0 ~ 범위 전까지 정수에서 난수 발생
System.out.println("범위지정 >> " + ran.nextInt(5));
// 2) (int)(nextDouble()) * 범위: 0 ~ 범위 전까지 정수에서 난수 발생
System.out.println("범위지정 >> " + (int)(ran.nextDouble() * 5));
// 2. Math 클래스: 전체 메소드가 static이므로 객체 생성 없이 호출이 가능
// 1) random()
System.out.println(Math.random()); // 0.0 이상 ~ 1.0 미만
// 특정 범위를 지정할 수 있다.
System.out.println((int)(Math.random() * 6)); // 0 ~ 5까지
// 2) abs: 절대갑 추출
System.out.println(Math.abs(100));
System.out.println(Math.abs(-100));
// 3. ceil(double x) 올림, round(double x) 반올림, floor(double x) 버림
System.out.println("올림 >> " + Math.ceil(3.45)); // 4
System.out.println("올림 >> " + Math.ceil(3.55)); // 4
System.out.println("반올림 >> " + Math.round(3.45)); // 3
System.out.println("반올림 >> " + Math.round(3.45)); // 4
System.out.println("버림 >> " + Math.floor(3.45)); // 3
System.out.println("버림 >> " + Math.floor(3.45)); // 3
// 4. max(자료형 a, 자료형 b): 둘 중 큰 값 출력
// 5. min(자료형 a, 자료형 b): 둘 중 작은 값 출력
System.out.println("max >> " +Math.max(45.6, 45));
System.out.println("min >> " +Math.min(45.6, 45));
// 6. pow(double a, double b): 승
System.out.println(Math.pow(2, 3)); // 2의 3승 => 8
System.out.println(Math.pow(3, 2)); // 3의 2승 => 9
}
}
<file_sep>/12_Debugging_JUnit/src/com/ict/debugging/Ex01.java
package com.ict.debugging;
// 디버깅 또는 디버그는 컴퓨터 프로그램 개발 단계 중에 발생하는
// 시스템의 논리적인 오류나 비정상적 연산(버그)을 찾아내고 그 원인을 밝히고 수정하는 작업 과정을 뜻한다.
// breakpoint(중단점): 디버깅 실행시 자동으로 실행이 중단 되어 해당 변수의 값을 조사할 수 있는 특정 지점
// F8: 중단점에서 중단점으로 이동
// F5: 한 문장씩 실행, 메소드를 만나면 안으로 집입
// F6: 한 문장씩 실행, 메소드를 건너뜀
public class Ex01 {
public static void main(String[] args) {
int total = 0;
for (int i = 1; i < 11; i++) {
total = total + i;
System.out.println("i >> " + i + ", total >>" + total);
}
System.out.println("합 >> " + total);
}
}
<file_sep>/02_grammar/Ex015.java
public class Ex015 {
public static void main(String[] args) {
// 논리연산자 : &&(AND, 논리곱), ||(OR, 논리합), !(NOT, 논리부정)
// 논리연산자의 대상(들어오는 정보) : boolean형, 비교연산, 논리연산
// 논리연산의 결과는 boolean형. 즉, 조건식에 사용된다.
//AND (&&, 논리곱_
// - 주어진 조건이 모두 true 일 때 결과는 true
// - 주어진 조건들 중 false를 만나면 결과는 false
// - false를 만나면 이루 연산을 하지 않음
// - 'a >= 10 && a <=20'의 의미는 a는 10부터 20까지의 범위를 의미한다.
int su1 = 10;
int su2 =7;
boolean result = false;
result = (su1 >= 7) && (su2 >= 5); // true = true %% true
System.out.println("결과: " + result);
result = (su1 >= 7 && (su2 <= 5)); // false = true && false
System.out.println("결과: " + result);
result = (su1 <= 7) && (su2 >= 5); // false = false && true
System.out.println("결과: " + result);
result = (su1 <= 7) && (su2 <= 5); // false = false && false
System.out.println("결과: " + result);
System.out.println("=============================================");
result = ((su1 = su1 + 2) >su2) && (su1 == (su2 = su2 + 5));
System.out.println("결과: " + result);
System.out.println("su1: " + su1);
System.out.println("su2: " + su2);
System.out.println("=============================================");
// AND는false를 만나면 결과는 false이고, 뒤 조건은 연산하지 않는다.
result = ((su1 = su1 + 2) < su2) && (su1 == (su2 = su2 +5));
System.out.println("결과: " + result);
System.out.println("su1: " + su1);
System.out.println("su2: " + su2);
su1 = 34;
// su1의 값이 20 ~30 사이의 값이냐?
result = (su1 >= 20) && (su1 <= 30);
System.out.println("결과: " + result);
// char c1이 소문자이냐?
char c1 = 'G';
result = (c1 >= 'a') && (c1 <= 'z');
System.out.println("결과: " + result);
}
}
<file_sep>/06_class/src/com/ict/edu/Ex13.java
package com.ict.edu;
public class Ex13 {
// this 와 this()
// this: 객체 내부에서 객체 자신을 지칭하는 예약어
// 지역변수와 전역변수의 변수이름이 같을 때 전역변수에 this.를 붙여서 전역 변수임을 나타낸다.
// this(): 객체의 생성자를 지칭하는 예약어
// 반드시 생성자의 첫번째 줄에 와야 한다.
// 사용목적: 생성자에서 다른 생성자를 호출할 때 사용한다.
String name = "고길동";
int age = 37;
// 생성자
public Ex13() {
// System.out.println("기본생성자 >> " + this);
this("마이콜", 24);
}
public Ex13(String name) {
this.name = name;
}
public Ex13(int age) {
this.age = age;
}
public Ex13(String name, int age) {
this.name = name;
this.age = age;
}
// getter / setter
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
<file_sep>/Practice/src/Practice1/PracticeEx.java
package Practice1;
import java.util.Scanner;
public class PracticeEx {
public static void main(String[] args) {
// 문제 1. a 와 의 값을 형변환 해서 두 수의 곱을 구하시오.
String a = "100";
String b = "200";
int num_a = Integer.parseInt(a);
int num_b = Integer.parseInt(b);
System.out.println("두 수의 곱은 >> " + (num_a * num_b));
System.out.println("================================");
// 문제 2. 65430월을 만들기 위한 화폐의 갯수를 구하시오.
int money = 65430;
int a1, b1, c1, d1;
System.out.println("money >> " + money);
a1 = money / 10000;
money -= a1 * 10000;
b1 = money / 1000;
money -= b1 * 1000;
c1 = money / 100;
money -= c1 * 100;
d1 = money / 10;
money -= d1 * 10;
System.out.println("만원 >> " + a1);
System.out.println("천원 >> " + b1);
System.out.println("백원 >> " + c1);
System.out.println("십원 >> " + d1);
System.out.println("================================");
// 문제 3. 급여 명세서를 작성하시오
// 조건 1) 기본급여 1,500,000원, 수당이 55,000원, 세금은 기본급의 10%
// 조건 2) 싱수령액 = 기본급 + 시간수당 - 세금
int pay = 1500000;
int timePay = 55000;
double tax = 0.1;
int resultPay = 1500000 + 55000 - (int)(pay * tax);
System.out.println("실수령액 >> " + resultPay);
System.out.println("================================");
// 문제 4. 각각 변수에 대입하여 출력하시오
// 조건 1) data는 이효리, 개발부, 대리, 1500000로 대입, 변수명은 각각 name, department, position, sal로 할 것
// 조건 2) 출력은 아래와 같은 메서드(함수)를 이용하시오
/* --출력--
이름 : 이효리 ---> println
부서 : 개발부 ---> printf
직위 : 대리 ---> print 1번만써서 직위,급여출력
급여 : 1500000원 */
String name = "이효리";
String department = "개발부";
String position = "대리";
int sal = 1500000;
System.out.println("이름 >> " + name);
System.out.printf("부서 >> %s\n", department);
System.out.print("직위 >> " + position + "\n급여 >> " + sal);
System.out.println();
System.out.println("================================");
// 문제 5. 다음을 입력받아 계산하시오
/* --입력--
Input name : 민들래
kor : 90
eng : 70
mat : 75
--출력--
이름 : 민들래
합계점수 : 235점
평균점수 : 78.3 <-- 소수 1자리까지출력하시오 */
Scanner sc = new Scanner(System.in);
String name1 = "";
int kor, eng, math;
System.out.println("Input name >> ");
name1 = sc.next();
System.out.println("kor >> ");
kor = sc.nextInt();
System.out.println("eng >> ");
eng = sc.nextInt();
System.out.println("math >> ");
math = sc.nextInt();
int sum = kor + eng + math;
double avg = (sum / 3.0) * 1.0;
System.out.println("이름 >> " + name1);
System.out.println("총점 >> " + sum);
System.out.printf("평균 >> %.1f", avg);
System.out.println();
System.out.println("================================");
// 문제 6. 다음을 입력 받아 계산하시오
// (삼각형넓이 = (밑변 * 높이) / 2)
/* --입력--
**** 삼각형의 넓이 구하기 ****
밑변 : 10
높이 : 3
--출력--
넓이 : XX.XX <--- 소수 2자리까지출력하시오 */
int bottom, height;
System.out.println("***** 삼각형의 넓이 구하기 *****");
System.out.print("밑변 >> ");
bottom = sc.nextInt();
System.out.print("높이 >> ");
height = sc.nextInt();
double area = (double)(bottom * height) / 2 ;
System.out.printf("넓이 >> %.2f", area);
}
}
<file_sep>/08_class/src/com/ict/edu7/Unit.java
package com.ict.edu7;
public abstract class Unit {
// 에너지가 고갈되는 메소드
public abstract void decEnergy();
}<file_sep>/06_class/src/com/ict/edu/Ex001_main.java
package com.ict.edu;
import java.util.Scanner;
public class Ex001_main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Ex001[] arr = new Ex001[5];
for (int i = 0; i < arr.length; i++) {
Ex001 per = new Ex001();
// 입력
System.out.print("이름 >> ");
per.setName(sc.next());
System.out.print("국어 >> ");
int kor = sc.nextInt();
System.out.print("영어 >> ");
int eng = sc.nextInt();
System.out.print("수학 >> ");
int math = sc.nextInt();
//
per.s_sum(kor, eng, math);
//
arr[i] = per;
}
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
if (arr[i].getSum() < arr[j].getSum()) {
arr[i].setRank(arr[i].getRank() + 1);
}
}
}
//
Ex001 tmp = new Ex001();
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i].getRank() > arr[j].getRank()) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = arr[i];
}
}
}
//
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i].getName() + "\t");
System.out.print(arr[i].getSum() + "\t");
System.out.print(arr[i].getAvg() + "\t");
System.out.print(arr[i].getHak() + "\t");
System.out.println(arr[i].getRank());
}
}
}
<file_sep>/14_IO/src/com/ict/edu06/VO.java
package com.ict.edu06;
import java.io.Serializable;
// 객체의 정보를 담당하는 클래스
// Serializable 인터페이스를 사용해서 직렬화를 할 수 있다.
// 직렬화 제외 시키는 방법 : 변수 앞에 transient 예약어를 사용
// 주의 사항 : boolean형은 무조건 false
public class VO implements Serializable {
private String name;
private int age;
transient private double weigth;
transient private boolean gender;
public VO() { }
public VO(String name, int age, double weigth, boolean gender) {
super();
this.name = name;
this.age = age;
this.weigth = weigth;
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getWeigth() {
return weigth;
}
public void setWeigth(double weigth) {
this.weigth = weigth;
}
public boolean isGender() {
return gender;
}
public void setGender(boolean gender) {
this.gender = gender;
}
}
<file_sep>/08_class/src/com/ict/edu/Ex01.java
package com.ict.edu;
public class Ex01 {
// - 상속관계: 자식클래스가 부모 클래스의 멤버필드, 멤버메소드를 객체 생성 없이
// 마음대로 사용할 수 있는 클래스간의 관계를 말한다.
// 자식 클래스가 부모 클래스와 관계를 맺는다.
// 자식 클래스 extends 부모클래스
// - 자바에서는 다중 상속을 할 수 없다. 즉 부모클래스 하나만 존재한다.
// - 모든 클래스는 Object라는 클래스를 상속 받고 있다.
public static void main(String[] args) {
Ex01_Sub test = new Ex01_Sub();
System.out.println(test);
System.out.println("======================================");
test.play();
// 부모클래스의 메소드 사용 가능
test.prn1();
System.out.println("======================================");
// static은 상속과 상관없이 사용 가능
System.out.println(Ex01_Sup.car);
System.out.println(Ex01_Sup.GENDER);
Ex01_Sup.prn2();
// private는 상속이어도 접근 안됨
// System.out.println(test.dog);
}
}
<file_sep>/02_grammar/Ex013.java
class Ex013{
public static void main (String[] args){
// 2시간 40분 30초는 몇 초 일까요?
// String time = "2:40:30" ; // 나중에
int h = 2*60*60;
int m = 40*60;
int s = 30;
int result = h + m + s ;
System.out.println("2시간 40분 30초는 " + result + "입니다.");
System.out.println("==================");
}
}
<file_sep>/02_grammar/Ex05.java
class Ex05 {
public static void main(String[] args) {
// 실수 : 소숫점이 있음
// float < double
// 실수의 기본은 double
// float는 숫자 뒤에 반드시 F, f를 붙여야 한다. (생략하면 오류)
// 24가 정수이므로 float는 실수 그러므로 저장할 수 있다.
float su1 = 24;
System.out.println(su1);
// 실수 31.4 F, f를 붙여야 오류 발생 않음
float su2 = 31.4f;
System.out.println(su2);
//char c1는 float에 저장할 수 있다.
char c1 = 97;
System.out.println(c1);
float su3 = c1;
System.out.println(su3);
// double은 byte, short, char, int, long, float 모두 받아서 저장할 수 있다.
double su4 = 3.14;
System.out.println(su4);
double su5 = su3;
System.out.println(su5);
double su6 = c1;
System.out.println(su6);
System.out.println("==================");
}
}
<file_sep>/13_Thread/src/com/ict/edu03/Ex01.java
package com.ict.edu03;
// Runnable 인터페이스는 추상 메소드 run()만 가지고 있다.
public class Ex01 implements Runnable {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + ": 1111");
}
play();
}
public void play() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + ": ####");
}
}
}
<file_sep>/11_Collection/src/com/ict/edu01/Ex05_mian.java
package com.ict.edu01;
import java.util.HashSet;
import java.util.Scanner;
public class Ex05_mian {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
HashSet<Ex05> Person = new HashSet<Ex05>();
// Ex09[] arr = Ex09[5];
// for (int i = 0; i < 5; i++) {
while (true) {
Ex05 p = new Ex05();
System.out.println("이름 >> ");
String name = sc.next();
System.out.println("국어 >> ");
int kor = sc.nextInt();
System.out.println("영어 >> ");
int eng = sc.nextInt();
System.out.println("수학 >> ");
int math = sc.nextInt();
p.setName(name);
p.s_sum(kor, eng, math);
Person.add(p);
System.out.println("계속할까요?(Y/N)");
String str = sc.next();
if (str.equalsIgnoreCase("N")) break;
// arr[i] = p;
}
// 순위
for (Ex05 k : Person) {
for (Ex05 j : Person) {
if (k.getSum() < j.getSum()) {
k.setRank(k.getRank() + 1);
}
}
}
// 정렬은 안된다.
// 출력
for (Ex05 k : Person) {
System.out.print(k.getName() + "\t");
System.out.print(k.getSum() + "\t");
System.out.print(k.getAvg() + "\t");
System.out.print(k.getHak() + "\t");
System.out.println(k.getRank() + "\t");
}
}
}
<file_sep>/after/src/com/ict/java02/Ex01.java
package com.ict.java02;
public class Ex01 {
/*
Ex 1. 클래스는 무엇들로 이루어 졌는가 (3가지 쓰시오) ?
답) 멤버핃드, 생성자, 멤버메소드
- 멤버필드(변수와 상수) : 데이터
변수 : 언제든지 변할 수 있는 데이터 (값)
상수 : 한번 저장되면 변경할 수 없는 데이터 (값)
예) private String name, hak;
private int kor, eng, math, sum;
private double avg;
- 생성자 : 클래스를 객체로 만들 때 반드시 호출해야 되는 것.
생성자의 목적 : 멤버필드의 초기값을 지정하는 것이 목적.
생성자의 구조 : 1) 클래스와 같은 이름을 쓴다.
2) 반환형이 없는 메소드와 같다.
-> 한 클래스에서 생성자를 여러개 가질 수 있다. (생성자 오버로드)
-> 인자가 없는 생성자를 기본 생성자라고 한다.
-> 만약에 생성자를 만들지 않으면 해당 클래스를 객체로 만들 때 기본 생성자를 사용해야 한다.
-> 그런데 생성자가 존재하면 존재하는 생성자로 만들어야 한다.
-> 생성자를 객체로 만드는 방법
클래스 이름 참조변수 = new 생성자();
- 멤버메소드 : 기능, 동작, 하는 것, 작동
-> 메소드를 호출하면 어떠한 내용을 실행한다.(동작한다.)
-> 한 클래스에서 같은 이름의 여러 메소드를 오버로드라고 한다.
-> 반환형 : 어떠한 행동을 한 후 반드시 자기를 호출한 곳으로 되돌아 간다.
내용을 가지고 가면 반환형이 있다. 그 내용의 자료형을 반환형이라 부른다.
만약에 내용을 가지고 가지 않으면 반환형이 없는 것이다.
이렇게 반환형이 없으면 void라고 쓴다.
-> getter() : 메소드를 호출한 곳에서 무언가를 얻어 낼 때 사용하는 메소드
-> setter() : 메소드를 이용하여 멤버 변수의 값(데이터)을 변결 할 때 사용
Ex 2. 클래스를 객체로 생성할 때 초기화 목적으로 반드시 호출하는 것은 무엇인가?
답) 생성자
생성자의 특징 : 클래스와 이름이 같다.
반환형이 없는 메소드와 같다.
Ex 3. 어떤 클래스에서 같은 이름의 여러개 존재하는 것으로 반드시 매게 변수는 달라야 하는 것을 무엇이라 하는가?
답) 오버로드(오버로딩)
- 이름이 같은데 오류가 나지 않는 이유 : 인자의 종류나 인자의 갯수, 자료형이 틀리면 이름이 같아도 오류가 나지 않는다.
Ex 4. 상속관계에서 부모클래스의 메소드를 자식클래스가 가져와서 자식클래스 상황에 맞게 변경하는 것을 무엇이라 하는가?
상속 : 클래스와 클래스의 관계를 말하는데 부모클래스(super)가 만들어지고 자식 클래스(sub)가 만들어진다.
자식클래스가 부모클래스의 모든 멤버필드, 멤버메소드 객체 생성 없이 마음대로 사용할 수 있도록 관계를 맺는 것을 말한다.
답) 오버라이드(오버라이딩)
오버라이딩 : 자식클래스가 부모클래스의 메소드를 가지고 와서 변경해서 쓴다.
final클래스 : 상속을 못하게 한다. (자식클래스 못 만든다.)
final메소드 : 오버라이드를 못하게 한다.
final변수 : 상수 (데이터 변경을 못하게 안된다.)
Ex 5. 추상클래스와 인터페이스에 대해서 쓰시오.
- 추상클래스 : 추상메소드를 하나 이상 가지고 있는 클래스.
추상메소드 : 메소드의 내용(몸체=body)가 존재하지 않는 메소드.
일반메소드 : public 반환형 이름([인자]) { 실행내용 };
추상메소드 : public 반환형 이름([인자]);
* 추상메소드나 추상클래스 이면 무조건 abstract 예약어를 사용해야 된다.
* 예) public abstract class Unit { 추상클래스 // 추상메소드 public abstract void decEnergy();}
* 추상클래스를 상속받은 일반클래스는 무조건 추상메소드를 오버라이딩해야 한다.
예) public class Protoss extends Unit {
@Override
public abstract void decEnergy() {
}
}
- 인터페이스 : 상수와 추상메소드로만 이루어졌다.
객체 생성 할 수 없다.
interface 예약어를 사용한다.
public interface Ex01 {
상수와 추상메소드
// 추상 메소드
public abstract void play();
// interface 에서는 abstract 예약어를 사용하지 않아도 오류가 아니다.
public void sound();
}
** 인터페이스를 상속 받은 일반 클래스는 무조건 추상 메소드를 오버라이드 해야된다.
public Ex02 implements Ex01 {
@Override
public abstract void play() {
}
@Override
public void sound() {
}
}
*/
}
<file_sep>/03_if_while/src/com/ict/edu/Ex06.java
package com.ict.edu;
public class Ex06 {
public static void main(String[] args) {
// 다중 for문 : for문 안에 다른 for문이 존재하는 것
for (int i = 1; i < 4; i++) {
for (int j = 1; j < 6; j++) {
System.out.println("i= " + i + ", j= " + j);
}
}
// 구구단
System.out.println("==================================");
for (int i = 2; i < 10; i++) {
System.out.println(i + "단");
for (int j = 1; j < 10; j++) {
System.out.println(i + " * " + j + " = " + i*j);
}
System.out.println();
}
System.out.println("==================================");
for (int i = 2; i < 10; i++) {
System.out.println(i + "단");
for (int j = 1; j < 10; j++) {
System.out.print(i + " * " + j + " = " + (i*j) + " ");
}
System.out.println();
}
System.out.println("==================================");
for (int i = 1; i < 10; i++) {
for (int j = 2; j < 10; j++) {
System.out.print(j + " * " + i + " = " + (i*j) + " ");
}
System.out.println();
}
System.out.println("==================================");
// 0000
// 0000
// 0000
// 0000
for (int i = 1; i < 5; i++) {
for (int j = 1; j < 5; j++) {
System.out.print("0 ");
}
System.out.println();
}
System.out.println("=========================");
// 1000
// 0100
// 0010
// 0001
for (int i = 1; i < 5; i++) {
for (int j = 1; j < 5; j++) {
if (i == j) {
System.out.print("1 ");
}else {
System.out.print("0 ");
}
System.out.println();
}
}
}
}
<file_sep>/02_grammar/Ex04.java
class Ex04{
public static void main(String[] args){
// 숫자 : 정수형(소숫점이 없음) < 실수형(소숫점이 있음)
// 정수형 : byte < short < int < long
// 정수형의 기본은 int
//실수형 : float < double
//실수형의 기본은 double
//byte : 정수형 중 가장 작은 단위
// -128 ~ 127 사이 값만 저장 가능
byte b1 = 127;
System.out.println(b1);
// 계산식은 결과만 저장된다.
// byte b2 = 15 + 120;
// System.out.println(b2);
// short : -32768 ~ 32767 사이의 값만 저장
short s1 = -32768;
System.out.println(s1);
short s2 = 32767;
System.out.println(s2);
// int와 long은 숫자 범위를 외울 필요 없다.
// 앞으로 일반적인 정수는 int 사용
// 아주 큰 정수를 사용할 때 long형 사용
int su1 = 247;
System.out.println(su1);
int su2 = -77777777;
System.out.println(su2);
// long : int보다 더 넓은 범위를 가지고 있음
// 기본적으로 숫자 뒤에 L 또는 l 를 붙인다. (생략가능)
long num1 = 124L;
System.out.println(num1);
// 작은 자료형이 큰자료형에 저장되는 것은 오루가 나지 않는다.
long num2 = 124;
System.out.println(num2);
//정수 su1 을 long num3에 저장
long num3 = su1;
System.out.println(su1);
// short s1을 long num4에 저장
long num4 = s1;
System.out.println(s1);
// short s1을 int su3에 저장
int su3 = s1;
System.out.println(s1);
char c1 = '가';
System.out.println(c1);
int su4 = c1;
System.out.println(su4);
System.out.println("==================");
}
}
<file_sep>/after/src/com/ict/java01/Ex02.java
package com.ict.java01;
public class Ex02 {
public static void main(String[] args) {
// Ex6. 근무시간이 8시간 까지는 시간당 8590이고, 8시간을 초과한 시간 만큼은 1.5배 지급한다.
// 현재 근무한 시간이 10이다. 얼마를 받아야 하는가? (if ~ else를 사용하시오)
int dan = 8590;
int work = 10;
int money = 0;
if (work > 8) {
money = (int) ((8 * dan) + ((work - 8) * dan * 1.5));
} else {
money = 8 * dan;
}
System.out.println("받아야 할 돈 " + money + " 원 입니다.");
}
}
<file_sep>/11_Collection/src/com/ict/edu01/Ex07.java
package com.ict.edu01;
import java.util.HashSet;
import java.util.TreeSet;
public class Ex07 {
public static void main(String[] args) {
// 로또 번호: 1 ~ 45, 랜덤, 중복안됨, 6자리
TreeSet<Integer> lotto1 = new TreeSet<Integer>();
for (int i = 0; i < 6; i++) {
int k = (int)(Math.random() * 45 ) + 1;
if (! lotto1.add(k)) {
i--;
}
}
System.out.println(lotto1);
}
}
<file_sep>/09_class/src/com/ict/edu01/Ex04.java
package com.ict.edu01;
public class Ex04 {
// 내부클래스: 클래스 안에 다른 클래스가 정의 되어있는 클래스
// 종류: Member, Local, Static, Anonymous
// 1. Member: 외부클래스{멤버필드, 생성자, **내부클래스{...}, 멤버메소드}
// - 내부클래스는 외부클래스의 멤버(필드, 메소드)들을 마음대로 사용할 수 있다. (상속과 비슷)
// - 상속에서는 private 멤버 접근 안됨, 내부클래스에서는 private 멤버 접근 가능
// - 외부클래스를 통해서 내부클래스를 객체 생성한다.
// - (즉, 내부클래스가 별도로 객체 생성을 할 수 없다.)
// 2. Local: 외부클래스 메소드 안에 내부클래스가 존재
// - 외부클래스의 지역변수처럼 사용 (메소드가 실행될 때 생성 가능, 메소드가 종료될 때 내부클래스도 지워진다.)
// 3. Static: Member 내부클래스처럼 외부 클래스 안에 존재하는 클래스
// - 내부클래스의 멤버변수는 static을 사용할 수 없는데 어쩔 수 없이 내부클래스 멤버변수에 static을 사용하고자 할때
// 내부클래스의 static을 붙인다.
// 외부클래스{멤버필드, 생성자, **static 내부클래스{static...}, 멤버메소드}
// 내부클래스 멤버는 일반 static 처럼 사용하면 된다.
// 4. **Anonymous(익명): 정의된 클래스의 이름이 없는 클래스
// - 다시 호출할 수 없다. 일회용으로 한 번 사용하고 다시 사용할 수 없다.
}
<file_sep>/02_grammar/Ex10.java
class Ex10{
public static void main(String[] args) {
// 증감 연산자 : 1증가 또는 1감소 하는 연산자
// char, 정수형, 실수형에 사용가능
// ++ 변수 : 현재값을 먼저 1증가 하고 나머지 실행
// 변수 ++ : 현재값 가지고 연산 후 나중에 1증가
int su1 = 10;
int su2 = 10;
System.out.println(++su1);
System.out.println(su2++);
System.out.println(su1);
System.out.println(su2);
System.out.println("==================");
}
}
<file_sep>/03_if_while/src/com/ict/edu/Ex12.java
package com.ict.edu;
public class Ex12 {
public static void main(String[] args) {
// break label 과 continue label
// break label : 레이블이 지정한 블록 탈출
// continue label : 레이블이 지정한 블록 수행문을 포기하고 다음 회차로 진행
// label 지정 방법 '레이블이름:' 뒤나 밑에는 반복만 올 수 있다.
// 1 ~ 10까지 출력
for (int i = 1; i < 11; i++) {
System.out.print(i + "\t");
}
System.out.println();
// i 가 6일때 break; 사용
for (int i = 1; i < 11; i++) {
if (i == 6)
break;
System.out.print(i + "\t");
}
System.out.println();
// i 가 6일때 break label 사용하기
// for문이 하나일 때는 break 와 break label이 같은 결과를 낸다.
// 그러므로 for문이 하나일 때는 break label를 사용할 필요가 없다.
// continue문도 마찬가지이다.
esc: for (int i = 1; i < 11; i++) {
if (i == 6) break esc;
System.out.print(i + "\t");
}
System.out.println();
// i가 6일때 continue; 사용
for (int i = 1; i < 11; i++) {
if (i == 6) continue;
System.out.print(i + "\t");
}
System.out.println();
// i가 6일때 continue label 사용하기
esc2: for (int i = 1; i < 11; i++) {
if (i == 6) continue esc2;
System.out.print(i + "\t");
}
System.out.println();
System.out.println("==============================================");
for (int i = 1; i < 4; i++) {
for (int j = 1; j < 6; j++) {
System.out.println(i + ", " + j);
}
}
System.out.println("==============================================");
// j = 3일 때 break
for (int i = 1; i < 4; i++) {
for (int j = 1; j < 6; j++) {
if (j == 3) break;
System.out.println(i + ", " + j);
}
}
System.out.println("==============================================");
// j = 3일 때 break label
esc3: for (int i = 1; i < 4; i++) {
for (int j = 1; j < 6; j++) {
if (j == 3) break esc3;
System.out.println(i + ", " + j);
}
}
System.out.println("==============================================");
// j = 3일 때 continue
for (int i = 1; i < 4; i++) {
for (int j = 1; j < 6; j++) {
if (j == 3) continue;
System.out.println(i + ", " + j);
}
}
System.out.println("==============================================");
// j = 3일 때 continue label
esc4: for (int i = 1; i < 4; i++) {
for (int j = 1; j < 6; j++) {
if (j == 3) continue esc4;
System.out.println(i + ", " + j);
}
}
System.out.println("==============================================");
}
}
<file_sep>/08_class/src/com/ict/edu6/School.java
package com.ict.edu6;
public class School {
public static void main(String[] args) {
Person s = new Student("김민아 학생", 20, 2020);
Person t = new Teacher("<NAME>수", 28, "생명공학기술");
Person e = new Employee("신유경 관리자", 30, "교무총괄부서");
// 만약에 Person print()가 없으면
// 아무리 Student(), Teacher(), Employee()에 print()가 있어도 사용 불가
s.print();
t.print();
e.print();
}
}
<file_sep>/02_grammar/Ex09.java
class Ex09{
public static void main(String[] args){
// 산술연산자 : +, -, /, *, %(나머지)
// char, 정수형, 실수형 사용가능
int s1 = 9;
int s2 = 4;
int res = 0;
res = s1 + s2;
System.out.println("결과 : " + res);
res = s1 - s2;
System.out.println("결과 : " + res);
res = s1 * s2;
System.out.println("결과 : " + res);
// 정수형으로 만들어서 몫만 나오는 방법
res = s1 / s2;
System.out.println("결과 : " + res);
// 실수형으로 만들어서 나오는 방법
double result1 = (double)(s1) / s2;
System.out.println("결과 : " + result1);
// 정수 / 정수 = 정수 즉, 실수값이 정확하게 나오지 않음
double result2 = s1 / s2;
System.out.println("결과 : " + result2);
res = s1 % s2;
System.out.println("결과 : " + res);
System.out.println("==================");
}
}
<file_sep>/Ex_Baseball1/src/BaseballGameTest.java
import java.util.Scanner;
public class BaseballGameTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
BaseballGame game = new BaseballGame();
game.setNum();
for (int i = 0; i < 15; i++) {
game.getNum(sc.nextInt(), sc.nextInt(), sc.nextInt());
}
}
}
<file_sep>/05_array/src/com/ict/edu/Ex06.java
package com.ict.edu;
import java.util.Scanner;
public class Ex06 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] name = new String[5];
int[] kor = new int[5];
int[] eng = new int[5];
int[] mat = new int[5];
int[] sum = new int[5];
double[] avg = new double[5];
String[] hak = new String[5];
int[] rank = {1, 1, 1, 1, 1};
// 입력
for (int i = 0; i < name.length; i++) {
System.out.print("이름: ");
name[i] = sc.next();
System.out.print("국어: ");
kor[i] = sc.nextInt();
System.out.print("영어: ");
eng[i] = sc.nextInt();
System.out.print("수학: ");
mat[i] = sc.nextInt();
}
// 총점, 평균, 학점
for (int i = 0; i < rank.length; i++) {
sum[i] = kor[i] + eng[i] + mat[i];
avg[i] = (int)(sum[i]/3.0*10)/10.0;
if (avg[i] >= 90) {
hak[i] = "A 학점";
} else if (avg[i] >= 80) {
hak[i] = "B학점";
} else if (avg[i] >= 70) {
hak[i] = "C학점";
} else {
hak[i] = "F학점";
}
}
// 순위
for (int i = 0; i < rank.length; i++) {
for (int j = 0; j < rank.length; j++) {
if (sum[i] < sum[j]) {
rank[i]++;
}
}
}
// 출력
System.out.print("이 름\t총 점\t평 균\t학 점 \t순 위 ");
for (int i = 0; i < rank.length; i++) {
System.out.print(name[i] + "\n");
System.out.print(sum[i] + "\n");
System.out.print(avg[i] + "\n");
System.out.print(hak[i] + "\n");
System.out.println(rank[i] + "\n");
}
}
}
<file_sep>/02_grammar/Ex003.java
class Ex003{
public static void main(String[] args){
String coff = "아메리카노";
String ratt = "고구마라떼";
String dise = "티라미슈 케이크";
int ame = 1500;
int rat = 3500;
int dis = 5000;
int su1 = 3;
int su2 = 5;
int su3 = 3;
int input = 50000;
int total = (ame * su1) + (rat * su2 + (dis * su3));
int vat = (int)(total * 0.1);
int output = input - (total + vat);
System.out.println("주문: " + coff + " " + su1);
System.out.println("주문: " + ratt + " " + su2);
System.out.println("주문: " + dise + " " + su3);
System.out.println("주문 확인: " + coff + " " + su1 + "," + ratt + " " + su2 + "," + dise + " " + su3);
System.out.println("아메리카노 총 금액: " + (ame * su1));
System.out.println("고구마라떼 총 금액: " + (rat * su2));
System.out.println("티라미슈 케이크 총 금액: " + (dis * su3));
System.out.println("주문 총 금액: " + total);
System.out.println("낸 금액: " + input);
System.out.println("부가세: " + vat);
System.out.println("부가세포함 금액: " + (total+vat));
System.out.println("남은 금액: " + output);
System.out.println("==================");
}
}
| 8503a16da348e364cfbad9182f297619e2441958 | [
"Java"
] | 36 | Java | vradika/2020_0091_java | 894ed6f011a88e929b6d141c27e7acc9307fca94 | 4dbb8b7174af33043d9a4df5e8eeb137f2a551d5 |
refs/heads/main | <file_sep>import axios, { AxiosResponse } from 'axios';
import { MealT } from '../types/Meal';
const xhr = axios.create({
baseURL: 'https://www.themealdb.com/api/json/v1/1',
});
export const getRandomMeal = () => xhr.get('/random.php');
export const getRandom5Meal = async (
randomIds: Array<number>,
): Promise<Array<MealT>> => {
// on mobile the requests are cached so the same meal appears 5 times
const preventCacheOptions = (value: number) => ({
params: {
random: value,
},
});
const datas = await Promise.all([
xhr.get('/random.php', preventCacheOptions(randomIds[0])),
xhr.get('/random.php', preventCacheOptions(randomIds[1])),
xhr.get('/random.php', preventCacheOptions(randomIds[2])),
xhr.get('/random.php', preventCacheOptions(randomIds[3])),
xhr.get('/random.php', preventCacheOptions(randomIds[4])),
]);
return datas.map((data) => data.data.meals[0]);
};
type SearchMealResponseT = {
meals: Array<MealT>;
};
export const searchMeal = async (
searchText: string,
): Promise<AxiosResponse<SearchMealResponseT>> =>
xhr.get(`/search.php?s=${searchText}`);
export const getMeal = async (
mealId: string,
): Promise<AxiosResponse<SearchMealResponseT>> =>
xhr.get(`/lookup.php?i=${mealId}`);
<file_sep>export { default } from './MealCard';
| c4c039dd9cc3ae42cd8a7655addedb2de0fb903e | [
"TypeScript"
] | 2 | TypeScript | pnarielwala/recipe-finder | 03ca3bd8afaf107b34b12b0968dc1941a35ca59e | eeb371d89392e6423f94ef05e205892c8f21ee51 |
refs/heads/master | <repo_name>anuragmuglikar/pace-maker<file_sep>/Final_ Clean repo/main.cpp
#define MQTTCLIENT_QOS2 1
#include "ESP8266Interface.h"
#include "MQTTNetwork.h"
#include "MQTTmbed.h"
#include "MQTTClient.h"
#include "TextLCD.h"
#include "mbed.h"
#include "time.h"
#include <string.h>
#include <stdlib.h>
#include <deque>
#define IAP_LOCATION 0x1FFF1FF1
// Serial port for debug
Serial pc(USBTX, USBRX);
#define LRI 1100
#define HRI 1500
// Heart monitor window averaging variables
#define AVG_WINDOW 20 // Can be 20, 40, or 60 seconds
#define AVG_INTERVAL 5 // Can be 5, 10, 15, or 20 seconds
DigitalOut led_slow_alarm(LED3);
DigitalOut led_fast_alarm(LED4);
DigitalOut senseBeatLED(LED1);
DigitalOut sendPaceLED(LED2);
DigitalOut pace_signal(p19);
InterruptIn receive_sense(p5);
ESP8266Interface wifi(p28, p27);
// Alarm indicators
bool slow_alarm = 0;
bool fast_alarm = 0;
// Defines for monitor
#define URL 100 //This is in bpm, not ms
#define RATE_ALARM 1
#define PACE_ALARM 2
#define PACE_THRESH 10 // Pretty arbitrary number
int RI = 1500;
int VRP = 240;
bool hp_enable, hp;
bool sense_received = 0;
bool sense_flag = 0;
bool pace_sent = 0;
time_t start_time;
Timer timer;
Ticker indicator;
Ticker paceIndicator;
/* pace_times is a subest of beat_times. I need all beats and paces to
* calculate the average heartrate, but only the number of paces to determine
* if the too slow alarm needs to go off.
*/
deque<time_t> beat_times;
deque<time_t> pace_times;
// The number of times each alarm has occured
unsigned int rate_alarm_count = 0;
unsigned int pace_alarm_count = 0;
// Threads
Thread pacemaker_thread;
Thread monitor_observe;
Thread monitor_calculate;
const char* hostname = "broker.hivemq.com";
int port = 1883;
char* topic = "sectopic";
char* rTopic = "sectopic";
MQTTNetwork network(&wifi);
MQTTNetwork mqttNetwork(network);
MQTT::Client<MQTTNetwork, Countdown> client(mqttNetwork);
MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
MQTT::Message message;
char buf[100];
// This looks at the time difference in each element
// of both the pace and heartbeat queues and removes
// any which are too old, i.e. outside the averaging window time
void prune_lists(time_t new_time)
{
// Only look at the front of the queues because elements are added
// already sorted
while (difftime(new_time, beat_times.front()) > AVG_WINDOW)
{
beat_times.pop_front();
}
while (difftime(new_time, pace_times.front()) > AVG_WINDOW)
{
pace_times.pop_front();
}
}
// Flash an LED for an alarm and send an MQTT message
// to the cloud
void monitor_alarm(int alarm)
{
int i;
Timer alarm_t;
alarm_t.start();
if (alarm == RATE_ALARM)
{
for (i = 0; i < 3; i++)
{
led_fast_alarm = 1;
while(alarm_t.read_ms() < 200*(i+1));
led_fast_alarm = 0;
}
rate_alarm_count++;
sprintf(buf, "Fast Alarm :%d", rate_alarm_count);
pc.printf("Too fast\r\n");
} else if (alarm == PACE_ALARM)
{
pace_alarm_count++;
sprintf(buf, "Slow Alarm :%d", pace_alarm_count);
for (i = 0; i < 3; i++)
{
led_slow_alarm = 1;
while(alarm_t.read_ms() < 200*(i + 1)) ;
led_slow_alarm = 0;
}
pc.printf("Too slow\r\n");
}else{
sprintf(buf, "Normal :%d", 1);
}
message.qos = MQTT::QOS0;
message.retained = true;
message.dup = false;
message.payload = (void*)buf;
message.payloadlen = strlen(buf);
int rc = client.publish(topic, message);
client.yield(50);
if(rc == 0){
printf("Success PUB%d\n", rc);
}else{
printf("Failed PUB%d\n", rc);
client.connect(data);
}
}
// This is a thread for the monitor which simply watches for new beats and
// paces and adds them to the queue(s) when they occur
void monitor_obs()
{
time_t new_time;
// Monitor just runs forever
while (1) {
// Wait until you see a sense or pace
while (!sense_flag && !pace_sent) ;
// Indicate if you saw a sense or a pace, then set the indicator back to
// 0 so that the current signal is not counted more than once
if (sense_flag) {
beat_times.push_back(time(NULL));
sense_flag = 0;
}
if (pace_sent) {
new_time = time(NULL);
beat_times.push_back(new_time);
pace_times.push_back(new_time);
pace_sent = 0;
}
}
}
void monitor_calc()
{
time_t current_time;
time_t wait_start = time(NULL);
int heart_rate;
int num_paces;
//printf("calc...\n");
// I want to check the heart rate in bpm for the alarm,
// so if my window time is smaller than 60 seconds I want to have
// this window factor to scale it
int window_factor = 60 / AVG_WINDOW;
// The monitor needs to wait for at least one full AVG_WINDOW
// before it starts to monitor the average heartrate or else
// it is going to give spurious low heartrate alarms
while (difftime(time(NULL),wait_start) < AVG_WINDOW);
message.qos = MQTT::QOS0;
while(1) {
//pc.printf("In monitor calc loop\r\n");
// Get the current time and see if you need to prune any elements from
// your lists
current_time = time(NULL);
prune_lists(current_time);
// Find average heart rate and number of paces if it is time to,
// then set any necessary alarms
heart_rate = beat_times.size() * window_factor;
num_paces = pace_times.size();
pc.printf("H.R = %d\r\n", heart_rate);
pc.printf("N.P = %d\r\n", num_paces);
sprintf(buf, "BPM :%d", heart_rate);
message.retained = true;
message.dup = false;
message.payload = (void*)buf;
message.payloadlen = strlen(buf);
int rc = client.publish(topic, message);
client.yield(50);
if(rc == 0){
printf("Success PUB%d\n", rc);
}else{
printf("Failed PUB%d\n", rc);
client.connect(data);
}
//printf("About to alarm\r\n");
if (heart_rate > URL) {
monitor_alarm(RATE_ALARM);
} else if (num_paces > PACE_THRESH) {
monitor_alarm(PACE_ALARM);
}else{
sprintf(buf, "Normal :%d", 1);
}
message.qos = MQTT::QOS0;
message.retained = true;
message.dup = false;
message.payload = (void*)buf;
message.payloadlen = strlen(buf);
rc = client.publish(topic, message);
client.yield(50);
if(rc == 0){
printf("Success PUB%d\n", rc);
}else{
printf("Failed PUB%d\n", rc);
client.connect(data);
}
//printf("Alarm done\r\n");
wait_start = time(NULL);
// Wait until you need to calculate averages again
while (difftime(time(NULL),wait_start) < AVG_INTERVAL);
}
}
void flip(){
senseBeatLED = 0;
indicator.detach();
}
// ISR to receive sense signals
void receive_sense_ISR()
{
sense_received = 1;
}
void pIndicate(){
sendPaceLED = 0;
paceIndicator.detach();
}
void pace()
{
sendPaceLED = 1;
paceIndicator.attach(&pIndicate, 0.1);
pace_signal = 1;
pace_signal = 0;
}
void pacemaker()
{
//start_time = timer.read_ms();
timer.reset();
timer.start();
while(true)
{
while(!sense_received && ((timer.read_ms()) < RI));
if (sense_received)
{
//pc.printf("sense received\n");
sense_received = 0;
// Let monitor know there was a heartbeaat
sense_flag = 1;
RI = HRI;
hp = true;
timer.reset();
senseBeatLED = 1;
indicator.attach(&flip, 0.01);
}
else
{
// Send pace signal to heart
pace();
// Indicate oace was sent for monitor
pace_sent = 1;
//pc.printf("paced - %d\n", (timer.read_ms() - start_time));
RI = LRI;
hp = false;
//start_time = timer.read_ms();
timer.reset();
}
// Wait for VRP
receive_sense.disable_irq();
while((timer.read_ms()) < VRP);
receive_sense.enable_irq();
hp_enable = hp;
}
}
int main()
{
led_slow_alarm = 0;
led_fast_alarm = 0;
pc.baud(9600);
// Enable the ISR to receive snse signals from heart simulator
wifi.set_credentials(MBED_CONF_APP_WIFI_SSID, MBED_CONF_APP_WIFI_PASSWORD);
wifi.connect();
int rc = network.connect(hostname, port);
pc.printf("Connecting to %s:%d\r\n", hostname, port);
rc = mqttNetwork.connect(hostname, port);
data.MQTTVersion = 3;
data.clientID.cstring = "26013f37-13006018ae2a8ca752c368e3f5001e81";
data.username.cstring = "mbed";
data.password.cstring = "<PASSWORD>";
if ((rc = client.connect(data)) != 0)
pc.printf("rc from MQTT connect is %d\r\n", rc);
receive_sense.rise(&receive_sense_ISR);
// Start both the threads - pacemaker and observer
monitor_observe.start(monitor_obs);
monitor_calculate.start(monitor_calc);
pacemaker_thread.start(pacemaker);
}
<file_sep>/heart/main.cpp
#include "mbed.h"
DigitalOut myled(LED1);
DigitalOut myled2(LED2);
#define LRI 1100
#define HRI 1500
#define VRP 240
#define PULSE_WIDTH 100
#define MINWAIT 860
#define MAXWAIT 1260
InterruptIn ventricleInt(p18);
DigitalOut beatSignal(p19);
Timer timeToBeat;
Timer timeVRP;
Serial pc(USBTX, USBRX);
int random_beat = 1300;
bool receivedPace = false;
volatile enum {READY, IDLE}heartState;
void waitForVRP(){
//pc.printf("vrp\n");
timeVRP.stop();
timeVRP.reset();
timeVRP.start();
while(timeVRP.read_ms() >= VRP);
heartState = READY;
}
void beat() {
if(!receivedPace){
beatSignal = 1;
beatSignal = 0;
pc.printf("B\n");
heartState = IDLE;
//timeToBeat.detach();
}else{
pc.printf("rec pace\n");
receivedPace = false;
heartState = IDLE;
}
waitForVRP();
}
void paced() {
if(heartState != IDLE){
myled2 = !myled2;
receivedPace = true;
heartState = IDLE;
timeVRP.reset();
}
}
int main() {
ventricleInt.rise(&paced);
while(1){
myled = 1;
heartState = READY;
random_beat = (rand() % (MAXWAIT - MINWAIT)) + MINWAIT;
timeToBeat.stop();
timeToBeat.reset();
timeToBeat.start();
//pc.printf("W.R.B\n");
while((timeToBeat.read_ms() >= random_beat || receivedPace) && heartState != IDLE);
beat();
}
}
<file_sep>/ventricle/main.cpp
wifi.set_credentials("anurag", "<PASSWORD>");
wifi.connect();
const char* hostname = "172.16.17.32";
int port = 1883;
char* topic = "cis541/hw-mqtt/26013f37-13006018ae2a8ca752c368e3f5001e81/data";
char* rTopic = "cis541/hw-mqtt/26013f37-13006018ae2a8ca752c368e3f5001e81/echo";
MQTTNetwork network(&wifi);
int rc = network.connect(hostname, port);
if (rc == 0){
pc.printf("TCP connection succesful. -> %d\r\n", rc);
}else{
pc.printf("Failed to connect to TCP Socket -> %d", rc);
}
MQTTNetwork mqttNetwork(network);
MQTT::Client<MQTTNetwork, Countdown> client(mqttNetwork);
//const char* hostname = "m2m.eclipse.org";
//int port = 1883;
pc.printf("Connecting to %s:%d\r\n", hostname, port);
rc = mqttNetwork.connect(hostname, port);
MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
data.MQTTVersion = 3;
data.clientID.cstring = "26013f37-13006018ae2a8ca752c368e3f5001e81";
data.username.cstring = "mbed";
data.password.cstring = "<PASSWORD>";
if ((rc = client.connect(data)) != 0)
pc.printf("rc from MQTT connect is %d\r\n", rc);
MQTT::Message message;
int random_payload = rand() % 100 + 1;
char buf[100];
sprintf(buf, "%d", random_payload);
message.qos = MQTT::QOS1;
message.retained = true;
message.dup = false;
message.payload = (void*)buf;
message.payloadlen = strlen(buf)+1;
timer.start();
rc = client.publish(topic, message);<file_sep>/pacemaker/pacemaker.cpp
#define MQTTCLIENT_QOS2 1
#include "ESP8266Interface.h"
#include "MQTTNetwork.h"
#include "MQTTmbed.h"
#include "MQTTClient.h"
#include "TextLCD.h"
#include "mbed.h"
#include "time.h"
#include <string.h>
#include <stdlib.h>
#include <deque>
#define IAP_LOCATION 0x1FFF1FF1
// Serial port for debug
Serial pc(USBTX, USBRX);
#define LRI 1100
#define HRI 1500
// Heart monitor window averaging variables
#define AVG_WINDOW 20 // Can be 20, 40, or 60 seconds
#define AVG_INTERVAL 10 // Can be 5, 10, 15, or 20 seconds
DigitalOut pace_signal_led(LED1);
DigitalOut led_slow_alarm(LED2);
DigitalOut led_fast_alarm(LED3);
DigitalOut pace_signal(p18);
InterruptIn receive_sense(p19);
// Alarm indicators
bool slow_alarm = 0;
bool fast_alarm = 0;
// Defines for monitor
#define URL 100 //This is in bpm, not ms
#define RATE_ALARM 1
#define PACE_ALARM 2
#define PACE_THRESH 10 // Pretty arbitrary number
int RI = 1500;
int VRP = 240;
bool hp_enable, hp;
bool sense_received = 0;
bool sense_flag = 0;
bool pace_sent = 0;
time_t start_time;
Timer timer;
/* pace_times is a subest of beat_times. I need all beats and paces to
* calculate the average heartrate, but only the number of paces to determine
* if the too slow alarm needs to go off.
*/
deque<time_t> beat_times;
deque<time_t> pace_times;
Thread pacemaker_thread;
Thread monitor_observe;
Thread monitor_calculate;
// This looks at the time difference in each element
// of both the pace and heartbeat queues and removes
// any which are too old, i.e. outside the averaging window time
void prune_lists(time_t new_time)
{
// Only look at the front of the queues because elements are added
// already sorted
while (difftime(new_time, beat_times.front()) > AVG_WINDOW)
{
beat_times.pop_front();
}
while (difftime(new_time, pace_times.front()) > AVG_WINDOW)
{
pace_times.pop_front();
}
}
// Flash an LED for an alarm and send an MQTT message
// to the cloud
void monitor_alarm(int alarm)
{
int i;
Timer alarm_t;
alarm_t.start();
int time_start;
if (alarm == RATE_ALARM)
{
// SEND MQTT MESSAGE HERE
for (i = 0; i < 3; i++)
{
led_fast_alarm = 1;
while(alarm_t.read_ms() - time_start < 200) ;
led_fast_alarm = 0;
}
pc.printf("Too fast\r\n");
} else if (alarm == PACE_ALARM)
{
// SEND MQTT MESSAGE HERE
for (i = 0; i < 3; i++)
{
led_slow_alarm = 1;
while(alarm_t.read_ms() - time_start < 200) ;
led_slow_alarm = 0;
}
pc.printf("Too slow\r\n");
}
}
// This is a thread for the monitor which simply watches for new beats and
// paces and adds them to the queue(s) when they occur
void monitor_obs()
{
time_t new_time;
// Monitor just runs forever
while (1) {
// Indicate if you saw a sense or a pace, then set the indicator back to
// 0 so that the current signal is not counted more than once
if (sense_flag) {
beat_times.push_back(time(NULL));
sense_flag = 0;
}
if (pace_sent) {
new_time = time(NULL);
beat_times.push_back(new_time);
pace_times.push_back(new_time);
pace_sent = 0;
}
}
}
void monitor_calc()
{
time_t current_time;
time_t wait_start = time(NULL);
int heart_rate;
int num_paces;
// I want to check the heart rate in bpm for the alarm,
// so if my window time is smaller than 60 seconds I want to have
// this window factor to scale it
int window_factor = 60 / AVG_WINDOW;
// The monitor needs to wait for at least one full AVG_WINDOW
// before it starts to monitor the average heartrate or else
// it is going to give spurious low heartrate alarms
while (difftime(time(NULL),wait_start) < AVG_WINDOW);
while(1) {
pc.printf("In monitor calc loop\r\n");
// Get the current time and see if you need to prune any elements from
// your lists
current_time = time(NULL);
prune_lists(current_time);
// Find average heart rate and number of paces if it is time to,
// then set any necessary alarms
heart_rate = beat_times.size() * window_factor;
num_paces = pace_times.size();
pc.printf("Heart rate = %d\r\n", heart_rate);
pc.printf("Number paces = %d\r\n", num_paces);
if (heart_rate > URL) {
monitor_alarm(RATE_ALARM);
} else if (num_paces > PACE_THRESH) {
monitor_alarm(PACE_ALARM);
}
wait_start = time(NULL);
// Wait until you need to calculate averages again
while (difftime(time(NULL),wait_start) < AVG_INTERVAL);
}
}
// ISR to receive sense signals
void receive_sense_ISR()
{
sense_received = 1;
}
void pace()
{
pace_signal = 1;
pace_signal = 0;
}
void pacemaker()
{
start_time = timer.read_ms();
timer.start();
while(true)
{
while(!sense_received && ((timer.read_ms() - start_time) < RI))
;
if (sense_received)
{
pc.printf("sense received\n");
sense_received = 0;
// Let monitor know there was a heartbeaat
sense_flag = 1;
RI = HRI;
hp = true;
start_time = timer.read_ms();
}
else
{
// Send pace signal to heart
pace_signal_led = 1;
pace();
// Indicate oace was sent for monitor
pace_sent = 1;
//pc.printf("paced\n");
RI = LRI;
hp = false;
start_time = timer.read_ms();
pace_signal_led = 0;
}
// Wait for VRP
while((timer.read_ms() - start_time) < VRP);
hp_enable = hp;
}
}
int main()
{
pc.baud(9600);
// Enable the ISR to receive snse signals from heart simulator
receive_sense.rise(&receive_sense_ISR);
// Start both the threads - pacemaker and observer
monitor_observe.start(monitor_obs);
monitor_calculate.start(monitor_calc);
pacemaker_thread.start(pacemaker);
}
}<file_sep>/pacemaker_mqtt.cpp
#include "mbed.h"
#include "MQTTNetwork.h"
#include "MQTTmbed.h"
#include "MQTTClient.h"
#include "wifiGETWrapper.h"
MQTT::Message message;
void messageArrived(MQTT::MessageData& md) {
MQTT::Message &message = md.message;
char* number;
printf("Message arrived: qos %d , packet id: %d\n", message.qos, message.id);
printf("Payload %.*s\n", message.payloadlen, (char*)message.payload);
salted_id = strtok((char *)message.payload, "-");
number = strtok(NULL, "\0");
}
void send_mqtt_message() {
//Make changes only over here to msgbuf. Accept global variables and sprintf to msgbuf.
sprintf(msgbuf, "Avg heartbeat: %d ; Alarm: %s", avg_heartbeat, Alarm);
message.payload = (void*)msgbuf;
message.payloadlen = strlen(msgbuf)+1;
ret = client.publish(topic, message);
if(ret != 0) {
printf("Client publish failure %d\n", ret);
} else {
printf("Client publish successful %d\n", ret);
}
client.yield(1000);
wait(4);
printf("Timer observed value is %f\n", timer.read());
}
int initConnection(const char * SSID, const char * password)
{
printf("WiFi example\r\n\r\n");
printf("\r\nConnecting...\r\n");
int ret = wifi.connect(SSID, password);
if (ret != 0) {
printf("\r\nConnection error\r\n");
return -1;
}
printf("Success\r\n\r\n");
printf("MAC: %s\r\n", wifi.get_mac_address());
printf("IP: %s\r\n", wifi.get_ip_address());
printf("Netmask: %s\r\n", wifi.get_netmask());
printf("Gateway: %s\r\n", wifi.get_gateway());
printf("RSSI: %d\r\n\r\n", wifi.get_rssi());
}
int main(int argc, char* argv[]) {
int ret;
//Define host name/ identification
//const char *hostname = "192.168.4.1";
const char *hostname = "172.16.31.10";
//const char *hostname = "192.168.43.138";
char topic[100];
char subscription_topic[100];
char id[8];
char deviceID[33];
char uuid[45];
int portnum = 1883;
IAP iap;
unsigned int iap_out;
iap_out = iap.read_ID();
int *iap_serial = (int *)malloc(sizeof(int) * 4);
iap_serial = iap.read_serial();
#ifdef DEBUG_PRINT
printf("IAP output is %08x\n",iap_out);
printf("IAP output is %08x\n", *(iap_serial));
printf("IAP output is %08x\n", *(iap_serial+ 1));
printf("IAP output is %08x\n", *(iap_serial+ 2));
printf("IAP output is %08x\n", *(iap_serial+ 3));
printf("size of int is %d\n", sizeof(int));
#endif
sprintf(id, "%08x", iap_out);
sprintf(deviceID, "%08x%08x%08x%08x", *(iap_serial),*(iap_serial + 1),*(iap_serial+ 2),*(iap_serial+ 3));
sprintf(uuid, "%8s-%32s", id, deviceID);
printf("uuid: %s\n", uuid);
sprintf(topic, "cis541/hw-mqtt/%s/data", uuid);
printf("topic: %s\n", topic);
sprintf(subscription_topic, "cis541/hw-mqtt/%s/echo", uuid);
printf("subscribe topic: %s\n", subscription_topic);
#ifdef MQTT
MQTTNetwork mqttnw(&wifi);
MQTT::Client<MQTTNetwork, Countdown> client(mqttnw);
#endif
wifi.set_credentials(MBED_CONF_APP_WIFI_SSID, MBED_CONF_APP_WIFI_PASSWORD, NSAPI_SECURITY_WPA_WPA2);
ret = wifi.connect();
if(ret < 0) {
printf("Error in connecting to AP \n");
}
printf("IP address is %s \n", wifi.get_ip_address());
#ifdef MQTT
//Establish connection
ret = mqttnw.connect(hostname, portnum);
if(ret < 0) {
printf("Error in connecting to mqttnw ret: %d\n", ret);
}
MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
// connackData connData;
data.clientID.cstring = uuid;
data.username.cstring = "mbed";
data.password.cstring = "<PASSWORD>";
ret = client.connect(data);
if(ret < 0) {
printf("Error in connecting to MQTT server at %s, ret i %d\n", hostname, ret);
}
ret = client.subscribe(subscription_topic, MQTT::QOS0, messageArrived);
if(ret < 0) {
printf("Client did not subscribe to topic %s, ret is %d\n", subscription_topic, ret);
}
printf("client subscribe ret is %d\n", ret);
int count = 0;
message.qos = MQTT::QOS1;
message.retained = false;
message.dup = false;
send_mqtt_message();
client.unsubscribe(subscription_topic);
client.disconnect();
#endif
#ifdef HTTP
GET(&wifi, hostname, "", portnum);
printf("End of GET\n");
#endif
return 0;
}
| dcb351c289d3188545ce142ea229d01bc323e3d2 | [
"C++"
] | 5 | C++ | anuragmuglikar/pace-maker | b7c70eb399de1bc451fcb4fc0941802b99b15c4e | be2e3fb9838b7d5d165dd77cff5a87b06277061e |
refs/heads/master | <repo_name>wagnerr63/udesc-agt<file_sep>/Exe5/main.c
#include <stdlib.h>
#include <stdio.h>
//Faça um programa que solicite uma temperatura em graus celsius, e os converta para graus //fahrenheit. A fórmula para a conversão é: F = (C * 9.0 / 5.0) + 32.0.
int main() {
float graus = 0;
float convertido;
printf("Informe a temperatura em graus celsius que será convertida para fahrenheit");
scanf("%f", &graus);
convertido = ((graus*9)/5)+32;
printf("%f fahrenheit", convertido);
}<file_sep>/Exe2/main.c
#include <stdlib.h>
#include <stdio.h>
int main() {
int a = 0;
int b = 0;
printf("Informe dois números:");
scanf("%i", &a);
scanf( "%i", &b);
int c = b - a;
if(c < 0) {
b = b * 2;
c = -c;
}
printf("O resultado é: %i", c);
return EXIT_SUCCESS;
} | befa83177b6738037db8bd3ae4a07535da8dfe2f | [
"C"
] | 2 | C | wagnerr63/udesc-agt | d191e39bf81d2e13d747176752875b98b7e4f34a | 995c684f0422f2bea39e6439ab84367292ff071b |
refs/heads/main | <repo_name>ubaumann/nuts-experiments<file_sep>/nuts_experiments/scrapli_show_vrf.py
"""Query VRF with scrapli"""
from typing import Callable, Dict, Any, Optional, List, Set
import pytest
from nornir.core.filter import F
from nornir.core.task import MultiResult, Result
from nornir_scrapli.tasks import send_command
from nuts.helpers.result import AbstractHostResultExtractor, NutsResult
from nuts.context import NornirNutsContext
class VrfExtractor(AbstractHostResultExtractor):
def single_transform(self, single_result: MultiResult) -> Dict[str, Dict[str, Any]]:
return single_result[0].scrapli_response.genie_parse_output()
class VrfContext(NornirNutsContext):
id_format = "{host}_"
def nuts_task(self) -> Callable[..., Result]:
return send_command
def nuts_arguments(self) -> Dict[str, Any]:
return {"command": "show vrf"}
def nornir_filter(self) -> F:
tags: Set[str] = {entry["tag"] for entry in self.nuts_parameters["test_data"]}
return F(tags__any=tags)
def nuts_extractor(self) -> VrfExtractor:
return VrfExtractor(self)
def parametrize(self, test_data: Any) -> Any:
tests = []
for data in test_data:
nr = self.nornir.filter(F(tags__contains=data.get("tag")))
for host in nr.inventory.hosts.keys():
tests.append({**data, "host": host})
return tests
CONTEXT = VrfContext
class TestVrfs:
@pytest.mark.nuts("vrfs")
def test_vrfs(self, single_result, vrfs):
device_vrfs = set(single_result.result.get("vrf", {}))
assert set(vrfs).issubset(device_vrfs)
<file_sep>/nuts_experiments/__init__.py
__version__ = "0.1.0"
import pytest
# https://docs.pytest.org/en/stable/writing_plugins.html#assertion-rewriting
pytest.register_assert_rewrite("nuts_experiments")
<file_sep>/README.md
```bash
============================= test session starts ==============================
platform linux -- Python 3.8.10, pytest-6.2.4, py-1.10.0, pluggy-0.13.1 -- /home/urs/.cache/pypoetry/virtualenvs/nuts-experiments-daYRvPSx-py3.8/bin/python
cachedir: .pytest_cache
rootdir: /home/urs/projects/nuts-experiments/playground
plugins: cov-2.12.0, nuts-3.0.1
collecting ... collected 4 items
tests/test_vrf.yaml::TestVrfs::test_vrfs[R1_0] PASSED [ 25%]
tests/test_vrf.yaml::TestVrfs::test_vrfs[R1_1] FAILED [ 50%]
tests/test_vrf.yaml::TestVrfs::test_vrfs[R3_0] FAILED [ 75%]
tests/test_vrf.yaml::TestVrfs::test_vrfs[R3_1] FAILED [100%]
=================================== FAILURES ===================================
___________________________ TestVrfs.test_vrfs[R1_1] ___________________________
self = <nuts_experiments.scrapli_show_vrf.TestVrfs object at 0x7f4694c204f0>
single_result = <nuts.helpers.result.NutsResult object at 0x7f4684174f70>
vrfs = ['mgmt', 'test', 'test2']
@pytest.mark.nuts("vrfs")
def test_vrfs(self, single_result, vrfs):
device_vrfs = set(single_result.result.get("vrf", {}))
> assert set(vrfs).issubset(device_vrfs)
E AssertionError
device_vrfs = {'mgmt', 'test'}
self = <nuts_experiments.scrapli_show_vrf.TestVrfs object at 0x7f4694c204f0>
single_result = <nuts.helpers.result.NutsResult object at 0x7f4684174f70>
vrfs = ['mgmt', 'test', 'test2']
../nuts_experiments/scrapli_show_vrf.py:51: AssertionError
___________________________ TestVrfs.test_vrfs[R3_0] ___________________________
self = <nuts_experiments.scrapli_show_vrf.TestVrfs object at 0x7f46524ee280>
single_result = <nuts.helpers.result.NutsResult object at 0x7f46841712b0>
vrfs = ['mgmt', 'test', 'test2']
@pytest.mark.nuts("vrfs")
def test_vrfs(self, single_result, vrfs):
device_vrfs = set(single_result.result.get("vrf", {}))
> assert set(vrfs).issubset(device_vrfs)
E AssertionError
device_vrfs = set()
self = <nuts_experiments.scrapli_show_vrf.TestVrfs object at 0x7f46524ee280>
single_result = <nuts.helpers.result.NutsResult object at 0x7f46841712b0>
vrfs = ['mgmt', 'test', 'test2']
../nuts_experiments/scrapli_show_vrf.py:51: AssertionError
___________________________ TestVrfs.test_vrfs[R3_1] ___________________________
self = <nuts_experiments.scrapli_show_vrf.TestVrfs object at 0x7f4652413100>
single_result = <nuts.helpers.result.NutsResult object at 0x7f46841712b0>
vrfs = ['mgmt']
@pytest.mark.nuts("vrfs")
def test_vrfs(self, single_result, vrfs):
device_vrfs = set(single_result.result.get("vrf", {}))
> assert set(vrfs).issubset(device_vrfs)
E AssertionError
device_vrfs = set()
self = <nuts_experiments.scrapli_show_vrf.TestVrfs object at 0x7f4652413100>
single_result = <nuts.helpers.result.NutsResult object at 0x7f46841712b0>
vrfs = ['mgmt']
../nuts_experiments/scrapli_show_vrf.py:51: AssertionError
=========================== short test summary info ============================
FAILED tests/test_vrf.yaml::TestVrfs::test_vrfs[R1_1] - AssertionError
FAILED tests/test_vrf.yaml::TestVrfs::test_vrfs[R3_0] - AssertionError
FAILED tests/test_vrf.yaml::TestVrfs::test_vrfs[R3_1] - AssertionError
========================= 3 failed, 1 passed in 7.65s ==========================
```<file_sep>/pyproject.toml
[tool.poetry]
name = "nuts-experiments"
version = "0.1.0"
description = ""
authors = ["ubaumann <<EMAIL>>"]
[tool.poetry.dependencies]
python = "^3.8"
nornir-scrapli = "^2021.1.30"
nuts = {path = "../nuts"}
scrapli = {extras = ["genie"], version = "^2021.1.30"}
[tool.poetry.dev-dependencies]
pytest = "^6.2"
black = "^21.7b0"
rich = "^10.6.0"
[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"
| 4dbb595bbbf6ace8ea93c6704d495e145bd619f9 | [
"Markdown",
"TOML",
"Python"
] | 4 | Python | ubaumann/nuts-experiments | ae797e4dde6bd6e706f68e8943a840ad6ab4fd67 | e74060b868843d6b31bb21e77e141998758ef4c3 |
refs/heads/master | <file_sep>package com.example.juanesteban.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
EditText edt1, edt2, edt3, edt4;
Button bGuardar;
String nombre, Contraseña, Con_contraseña, Correo, Perfil, Sexo, Pais, Dia, Mes,Año,hobbies="",hobbies_1="";
CheckBox check_1, check_2, check_3;
TextView Texto;
DatePicker Fecha_Nacimiento;
Spinner spinner;
ArrayList<String> Hobbies = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt1 = findViewById(R.id.edt1);
edt2 = findViewById(R.id.edt2);
edt3 = findViewById(R.id.edt3);
edt4 = findViewById(R.id.edt4);
bGuardar = findViewById(R.id.bGuardar);
check_1 = findViewById(R.id.check_1);
check_2 = findViewById(R.id.check_2);
check_3 = findViewById(R.id.check_3);
Texto = findViewById(R.id.Texto);
spinner = findViewById(R.id.spinner);
Fecha_Nacimiento = findViewById(R.id.Fecha_Nacimiento);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.Pais_origen, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int i, long l) {
Pais = parent.getItemAtPosition(i).toString();
//Toast.makeText(parent.getContext(),CharSequence , Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
public void OnClickSave(View view) {
int id = view.getId();
if (id == R.id.bGuardar) {
nombre = edt1.getText().toString();
edt1.setText(nombre);
Correo = edt2.getText().toString();
edt2.setText(Correo);
Contraseña = edt3.getText().toString();
edt3.setText(Contraseña);
Con_contraseña = edt4.getText().toString();
edt4.setText(Con_contraseña);
int day = Fecha_Nacimiento.getDayOfMonth();
int month = Fecha_Nacimiento.getMonth() + 1;
int year = Fecha_Nacimiento.getYear();
Dia = Integer.toString(day);
Mes = Integer.toString(month);
Año = Integer.toString(year);
String idList = Hobbies.toString();
hobbies = idList.substring(1, idList.length() - 1).replace(", ", ",");
if (nombre.equals("") || Correo.equals("") || Contraseña.equals("") || Con_contraseña.equals("")) {
Texto.setText("Faltan espacios por llenar");
return;
}
if (Contraseña.equals(Con_contraseña)) {
Perfil = "Login:" + nombre + "\n" + "Correo: " + Correo + "\n" + "Password :" + <PASSWORD> + "\n" + Sexo + "\n" + "Hobbies: " + hobbies + "\n" + "Fecha de Nacimiento:" + Dia + "/" + Mes + "/" + Año + "\n" + "Pais: " + Pais + "\n";
Texto.setText(Perfil);
} else {
Texto.setText("Las contraseñas no coinciden");
return;
}
}
}
public void RadioGroup(View view) {
int id = view.getId();
switch (id) {
case R.id.sMasculino:
Sexo = "Sexo:Masculino";
break;
case R.id.sFemenino:
Sexo = "Sexo:Femenino";
break;
}
}
public void onCheckboxClicked(View view) {
boolean checked = ((CheckBox) view).isChecked();
switch (view.getId()) {
case R.id.check_1:
if (checked) {
Hobbies.add("Cine");
} else {
Hobbies.remove("Cine");
}
break;
case R.id.check_2:
if (checked) {
Hobbies.add("Nadar");
} else {
Hobbies.remove("Nadar");
}
break;
case R.id.check_3:
if (checked) {
Hobbies.add("Correr");
} else {
Hobbies.remove("Correr");
}
break;
case R.id.check_4:
if (checked) {
Hobbies.add("Leer");
} else {
Hobbies.remove("Leer");
}
break;
}
}
}
| bb6931200e7ac732eecbb165fae4836b30f5ec12 | [
"Java"
] | 1 | Java | juaneescobar/Formulario | 40ec5cc4321a5494e5047e35d178c568bdf40ed3 | 36bc82fbf5cf235b1aefa7ba2d0170d20ad6d4c4 |
refs/heads/master | <file_sep>class EmployeesController < ApplicationController
def create
@company = Company.find(params[:company_id])
@employee = @company.employees.build(employee_params)
@employee.save
redirect_to company_path(@employee.company_id)
end
def destroy
@employee = Employee.find(params[:id])
@employee.destroy
redirect_to company_path(@employee.company_id)
end
private
def employee_params
params.require(:employee).permit(:first_name, :last_name, :email, :area_id)
end
end
| edd4b63f43afb2c08ab2b3da232acdf9445cacd1 | [
"Ruby"
] | 1 | Ruby | josetomascodecido/actividad_28 | 8e8cae950939af8c875316fd614bceae6898e5e8 | 3afe54a849a8f790fa9b9c47aa87f9467bb63a8b |
refs/heads/master | <file_sep>DRUM KIT :
It is a simple Drum kit where you play different components of the Drum kit just using your keyboard.
Just press the keys for shown for different component.
Enjoy
Live Demo:
https://uv9ue.csb.app/
<file_sep>// detecting button click
var drumKeys = document.querySelectorAll(".drum").length;
for (var i = 0; i < drumKeys; i++) {
document.querySelectorAll(".drum")[i].addEventListener("click", function() {
logkey(this.innerHTML);
buttonAnimation(this.innerHTML);
});
}
// Detecting keybord press
document.addEventListener('keypress', function(e) {
logkey(e.key);
buttonAnimation(e.key);
});
// making the correct sound
function logkey(drumkeypress) {
switch (drumkeypress) {
case "w":
var key1 = new Audio('sounds/tom-1.mp3');
key1.play();
break;
case "a":
var key2 = new Audio('sounds/tom-2.mp3');
key2.play();
break;
case "s":
var key3 = new Audio('sounds/tom-3.mp3');
key3.play();
break;
case "d":
var key4 = new Audio('sounds/tom-4.mp3');
key4.play();
break;
case "j":
var key5 = new Audio('sounds/crash.mp3');
key5.play();
break;
case "k":
var key6 = new Audio('sounds/kick-bass.mp3');
key6.play();
break;
case "l":
var key7 = new Audio('sounds/snare.mp3');
key7.play();
break;
default:
}
}
// animation
function buttonAnimation(currentKey) {
var activeKey = document.querySelector("." + currentKey);
activeKey.classList.add("pressed");
setTimeout(function() {
activeKey.classList.remove("pressed");
}, 100);
} | a98ce77afdc6cbd045273a1befa4e417440dead7 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | deepak-negi-web/Drum-kit | 9742d978c8e3f9b0ad8a2e41478c2a13bda0a9c0 | 266162ca7d831dbf10d25c709b9e001b754a11c8 |
refs/heads/master | <file_sep>#!/bin/bash
# numbers
# ((expression))
# arithmetic operations
# operation operator
# exponention **
# multiplication *
# division /
# modulo %
# addition +
# subtraction -
d=2
e=$((d+2))
echo $e
((e++))
echo $e
((e--))
echo $e
((e+=5))
echo $e
((e*=3))
echo $e
((e/=3)) # if you dont have the double parans around the expr you might end up with string concatenation if
# you are using += assignment
echo $e
((e-=5))
echo $e
# numbers in bash
f=$((1/3)) # will return 0 bcoz bash math only works with integers not floating point numbers
echo $f # if you want to use floating point numbers you need to use the bc program with predefined math
# routines
g=$(echo 1/3 | bc -l) # if you want to do math you probably want to use other than math to do
echo $g
<file_sep>#!/bin/bash
ubiquity --desktop %k gtk_ui
<file_sep>#!/bin/bash
#command substitution
d=$(pwd)
echo $d
# use value of some complex command
a=$(ping -c 1 example.com | grep 'bytes from' | cut -d = -f 4)
echo "The ping was $a"
<file_sep>#!/bin/bash
#variables
#named with alphanumeric characters
#names must start with a letter
a=Hello # no spaces
b="Good Morning"
c=16
echo $a #$ sign to call variables
echo $b
echo $c
echo "$b!. I have $c apples."
# adding attributes to variables
declare -i d=123 # d is an integer
declare -r e=456 # e is read-only(it can't be modified later arithmatically or with string manipulation).
declare -l f="LOLCats" # f is lolcats(lowercase)
declare -u f="LOLCats" # f is LOLCATS(uppercase)
# built in variables
echo $PWD # returns current directory
echo $MACHTYPE # returns the machine type
echo $HOSTNAME # returns hostname
echo $BASH_VERSION # returns version of Bash
echo $SECONDS # returns the no of secs the Bash session has run(handy for timing things).
echo $0 # name of the script
<file_sep>#!/bin/bash
# This is my first bash script
greeting="hello"
echo $greeting, world \(planet\)!
echo '$greeting, world (planet)'
echo "$greeting, world (planet)!"
<file_sep>#!/bin/bash
# comparison operations
# [[ expression ]] -- notation borrowed from korn shell
# -- it's importatnt to keep spaces between the sets of brackets and the expression
# this expression returns 1 or 0 --1: FALSE
# --0: TRUE
# comparison operations (<, >, <=, >=, ==, !=)
[[ "cat" == "cat" ]] # we can use single or double quotes for comparions
echo $?
[[ "cat" == "dog" ]]
echo $?
[[ 20 > 100 ]] # will return 0 because it will not compare numbers but strings and 20 is lexically > 100
echo $?
# comparison operatios for integers
# -lt less than
# -gt greater than
# -le less than or equal to
# -ge greater than or equal to
# -eq equal to
# -ne not equalto
[[ 20 -gt 100 ]]
echo $?
# logic operatios
# logical AND &&
# logical OR ||
# logical NOT !
# string null value
# is null? -z
# is not null? -n
a=""
b="cat"
[[ -z $a && -n $b ]]
echo $?
| 149f27b7a25eae4ebd52ebfd1a96d3ea4e074577 | [
"Shell"
] | 6 | Shell | surajkawade/shell-scripting | 1f0ab8efb2e6312c46e6268abef1d87084e2a42d | 9793f0af1ade45b339fa82ac5be452c12277354c |
refs/heads/master | <file_sep>Services for Google Cloud Osconfig v1 API
=========================================
.. automodule:: google.cloud.osconfig_v1.services.os_config_service
:members:
:inherited-members:
<file_sep># Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This script is used to synthesize generated parts of this library."""
import os
import synthtool as s
import synthtool.gcp as gcp
from synthtool.languages import python
gapic = gcp.GAPICMicrogenerator()
common = gcp.CommonTemplates()
# ----------------------------------------------------------------------------
# Generate OS Config GAPIC layer
# ----------------------------------------------------------------------------
library = gapic.py_library(
"osconfig", "v1"
)
s.move(library, excludes=["nox.py", "setup.py", "README.rst", "docs/index.rst"])
# correct license headers
python.fix_pb2_headers()
python.fix_pb2_grpc_headers()
# rename to google-cloud-os-config
s.replace(["google/**/*.py", "tests/**/*.py"], "google-cloud-osconfig", "google-cloud-os-config")
# Add newline after last item in list
s.replace("google/cloud/**/*_client.py",
"(- Must be unique within the project\.)",
"\g<1>\n")
# Add missing blank line before Attributes: in generated docstrings
# https://github.com/googleapis/protoc-docs-plugin/pull/31
s.replace(
"google/cloud/pubsub_v1/proto/pubsub_pb2.py",
"(\s+)Attributes:",
"\n\g<1>Attributes:"
)
# ----------------------------------------------------------------------------
# Add templated files
# ----------------------------------------------------------------------------
templated_files = common.py_library(
samples=False,
microgenerator=True,
unit_test_python_versions=["3.6", "3.7", "3.8"],
system_test_python_versions=["3.7"],
)
s.move(
templated_files, excludes=[".coveragerc"]
) # the microgenerator has a good coveragerc file
s.shell.run(["nox", "-s", "blacken"], hide_output=False)<file_sep># -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from .services.os_config_service import OsConfigServiceClient
from .types.patch_deployments import CreatePatchDeploymentRequest
from .types.patch_deployments import DeletePatchDeploymentRequest
from .types.patch_deployments import GetPatchDeploymentRequest
from .types.patch_deployments import ListPatchDeploymentsRequest
from .types.patch_deployments import ListPatchDeploymentsResponse
from .types.patch_deployments import MonthlySchedule
from .types.patch_deployments import OneTimeSchedule
from .types.patch_deployments import PatchDeployment
from .types.patch_deployments import RecurringSchedule
from .types.patch_deployments import WeekDayOfMonth
from .types.patch_deployments import WeeklySchedule
from .types.patch_jobs import AptSettings
from .types.patch_jobs import CancelPatchJobRequest
from .types.patch_jobs import ExecStep
from .types.patch_jobs import ExecStepConfig
from .types.patch_jobs import ExecutePatchJobRequest
from .types.patch_jobs import GcsObject
from .types.patch_jobs import GetPatchJobRequest
from .types.patch_jobs import GooSettings
from .types.patch_jobs import Instance
from .types.patch_jobs import ListPatchJobInstanceDetailsRequest
from .types.patch_jobs import ListPatchJobInstanceDetailsResponse
from .types.patch_jobs import ListPatchJobsRequest
from .types.patch_jobs import ListPatchJobsResponse
from .types.patch_jobs import PatchConfig
from .types.patch_jobs import PatchInstanceFilter
from .types.patch_jobs import PatchJob
from .types.patch_jobs import PatchJobInstanceDetails
from .types.patch_jobs import WindowsUpdateSettings
from .types.patch_jobs import YumSettings
from .types.patch_jobs import ZypperSettings
__all__ = (
"AptSettings",
"CancelPatchJobRequest",
"CreatePatchDeploymentRequest",
"DeletePatchDeploymentRequest",
"ExecStep",
"ExecStepConfig",
"ExecutePatchJobRequest",
"GcsObject",
"GetPatchDeploymentRequest",
"GetPatchJobRequest",
"GooSettings",
"Instance",
"ListPatchDeploymentsRequest",
"ListPatchDeploymentsResponse",
"ListPatchJobInstanceDetailsRequest",
"ListPatchJobInstanceDetailsResponse",
"ListPatchJobsRequest",
"ListPatchJobsResponse",
"MonthlySchedule",
"OneTimeSchedule",
"PatchConfig",
"PatchDeployment",
"PatchInstanceFilter",
"PatchJob",
"PatchJobInstanceDetails",
"RecurringSchedule",
"WeekDayOfMonth",
"WeeklySchedule",
"WindowsUpdateSettings",
"YumSettings",
"ZypperSettings",
"OsConfigServiceClient",
)
<file_sep># Changelog
### [0.1.2](https://www.github.com/googleapis/python-os-config/compare/v0.1.1...v0.1.2) (2020-06-11)
### Bug Fixes
* remove duplicate version ([#6](https://www.github.com/googleapis/python-os-config/issues/6)) ([351b553](https://www.github.com/googleapis/python-os-config/commit/351b5531244bb207fc6696625dbeaf840e7a469f))
### [0.1.1](https://www.github.com/googleapis/python-os-config/compare/v0.1.0...v0.1.1) (2020-06-11)
### Bug Fixes
* fix documentation links ([#2](https://www.github.com/googleapis/python-os-config/issues/2)) ([9d71787](https://www.github.com/googleapis/python-os-config/commit/9d717874d310d40efdb8f2a316521ea90e8c0e63))
## 0.1.0 (2020-06-10)
### Features
* generate v1 ([5d1f582](https://www.github.com/googleapis/python-os-config/commit/5d1f582b5b02d128ef44120d285941805d234ec7))
<file_sep># -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import abc
import typing
from google import auth
from google.auth import credentials # type: ignore
from google.cloud.osconfig_v1.types import patch_deployments
from google.cloud.osconfig_v1.types import patch_jobs
from google.protobuf import empty_pb2 as empty # type: ignore
class OsConfigServiceTransport(abc.ABC):
"""Abstract transport class for OsConfigService."""
AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",)
def __init__(
self,
*,
host: str = "osconfig.googleapis.com",
credentials: credentials.Credentials = None,
**kwargs,
) -> None:
"""Instantiate the transport.
Args:
host (Optional[str]): The hostname to connect to.
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
"""
# Save the hostname. Default to port 443 (HTTPS) if none is specified.
if ":" not in host:
host += ":443"
self._host = host
# If no credentials are provided, then determine the appropriate
# defaults.
if credentials is None:
credentials, _ = auth.default(scopes=self.AUTH_SCOPES)
# Save the credentials.
self._credentials = credentials
@property
def execute_patch_job(
self
) -> typing.Callable[
[patch_jobs.ExecutePatchJobRequest],
typing.Union[patch_jobs.PatchJob, typing.Awaitable[patch_jobs.PatchJob]],
]:
raise NotImplementedError()
@property
def get_patch_job(
self
) -> typing.Callable[
[patch_jobs.GetPatchJobRequest],
typing.Union[patch_jobs.PatchJob, typing.Awaitable[patch_jobs.PatchJob]],
]:
raise NotImplementedError()
@property
def cancel_patch_job(
self
) -> typing.Callable[
[patch_jobs.CancelPatchJobRequest],
typing.Union[patch_jobs.PatchJob, typing.Awaitable[patch_jobs.PatchJob]],
]:
raise NotImplementedError()
@property
def list_patch_jobs(
self
) -> typing.Callable[
[patch_jobs.ListPatchJobsRequest],
typing.Union[
patch_jobs.ListPatchJobsResponse,
typing.Awaitable[patch_jobs.ListPatchJobsResponse],
],
]:
raise NotImplementedError()
@property
def list_patch_job_instance_details(
self
) -> typing.Callable[
[patch_jobs.ListPatchJobInstanceDetailsRequest],
typing.Union[
patch_jobs.ListPatchJobInstanceDetailsResponse,
typing.Awaitable[patch_jobs.ListPatchJobInstanceDetailsResponse],
],
]:
raise NotImplementedError()
@property
def create_patch_deployment(
self
) -> typing.Callable[
[patch_deployments.CreatePatchDeploymentRequest],
typing.Union[
patch_deployments.PatchDeployment,
typing.Awaitable[patch_deployments.PatchDeployment],
],
]:
raise NotImplementedError()
@property
def get_patch_deployment(
self
) -> typing.Callable[
[patch_deployments.GetPatchDeploymentRequest],
typing.Union[
patch_deployments.PatchDeployment,
typing.Awaitable[patch_deployments.PatchDeployment],
],
]:
raise NotImplementedError()
@property
def list_patch_deployments(
self
) -> typing.Callable[
[patch_deployments.ListPatchDeploymentsRequest],
typing.Union[
patch_deployments.ListPatchDeploymentsResponse,
typing.Awaitable[patch_deployments.ListPatchDeploymentsResponse],
],
]:
raise NotImplementedError()
@property
def delete_patch_deployment(
self
) -> typing.Callable[
[patch_deployments.DeletePatchDeploymentRequest],
typing.Union[empty.Empty, typing.Awaitable[empty.Empty]],
]:
raise NotImplementedError()
__all__ = ("OsConfigServiceTransport",)
<file_sep># -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import os
import mock
import grpc
from grpc.experimental import aio
import math
import pytest
from google import auth
from google.api_core import client_options
from google.api_core import grpc_helpers
from google.api_core import grpc_helpers_async
from google.auth import credentials
from google.auth.exceptions import MutualTLSChannelError
from google.cloud.osconfig_v1.services.os_config_service import (
OsConfigServiceAsyncClient,
)
from google.cloud.osconfig_v1.services.os_config_service import OsConfigServiceClient
from google.cloud.osconfig_v1.services.os_config_service import pagers
from google.cloud.osconfig_v1.services.os_config_service import transports
from google.cloud.osconfig_v1.types import patch_deployments
from google.cloud.osconfig_v1.types import patch_jobs
from google.cloud.osconfig_v1.types import patch_jobs as gco_patch_jobs
from google.oauth2 import service_account
from google.protobuf import duration_pb2 as duration # type: ignore
from google.protobuf import timestamp_pb2 as timestamp # type: ignore
from google.type import datetime_pb2 as datetime # type: ignore
from google.type import dayofweek_pb2 as dayofweek # type: ignore
from google.type import timeofday_pb2 as timeofday # type: ignore
def client_cert_source_callback():
return b"cert bytes", b"key bytes"
def test__get_default_mtls_endpoint():
api_endpoint = "example.googleapis.com"
api_mtls_endpoint = "example.mtls.googleapis.com"
sandbox_endpoint = "example.sandbox.googleapis.com"
sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com"
non_googleapi = "api.example.com"
assert OsConfigServiceClient._get_default_mtls_endpoint(None) is None
assert (
OsConfigServiceClient._get_default_mtls_endpoint(api_endpoint)
== api_mtls_endpoint
)
assert (
OsConfigServiceClient._get_default_mtls_endpoint(api_mtls_endpoint)
== api_mtls_endpoint
)
assert (
OsConfigServiceClient._get_default_mtls_endpoint(sandbox_endpoint)
== sandbox_mtls_endpoint
)
assert (
OsConfigServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint)
== sandbox_mtls_endpoint
)
assert (
OsConfigServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi
)
@pytest.mark.parametrize(
"client_class", [OsConfigServiceClient, OsConfigServiceAsyncClient]
)
def test_os_config_service_client_from_service_account_file(client_class):
creds = credentials.AnonymousCredentials()
with mock.patch.object(
service_account.Credentials, "from_service_account_file"
) as factory:
factory.return_value = creds
client = client_class.from_service_account_file("dummy/file/path.json")
assert client._transport._credentials == creds
client = client_class.from_service_account_json("dummy/file/path.json")
assert client._transport._credentials == creds
assert client._transport._host == "osconfig.googleapis.com:443"
def test_os_config_service_client_get_transport_class():
transport = OsConfigServiceClient.get_transport_class()
assert transport == transports.OsConfigServiceGrpcTransport
transport = OsConfigServiceClient.get_transport_class("grpc")
assert transport == transports.OsConfigServiceGrpcTransport
@pytest.mark.parametrize(
"client_class,transport_class,transport_name",
[
(OsConfigServiceClient, transports.OsConfigServiceGrpcTransport, "grpc"),
(
OsConfigServiceAsyncClient,
transports.OsConfigServiceGrpcAsyncIOTransport,
"grpc_asyncio",
),
],
)
def test_os_config_service_client_client_options(
client_class, transport_class, transport_name
):
# Check that if channel is provided we won't create a new one.
with mock.patch.object(OsConfigServiceClient, "get_transport_class") as gtc:
transport = transport_class(credentials=credentials.AnonymousCredentials())
client = client_class(transport=transport)
gtc.assert_not_called()
# Check that if channel is provided via str we will create a new one.
with mock.patch.object(OsConfigServiceClient, "get_transport_class") as gtc:
client = client_class(transport=transport_name)
gtc.assert_called()
# Check the case api_endpoint is provided.
options = client_options.ClientOptions(api_endpoint="squid.clam.whelk")
with mock.patch.object(transport_class, "__init__") as patched:
patched.return_value = None
client = client_class(client_options=options)
patched.assert_called_once_with(
api_mtls_endpoint="squid.clam.whelk",
client_cert_source=None,
credentials=None,
host="squid.clam.whelk",
)
# Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is
# "never".
os.environ["GOOGLE_API_USE_MTLS"] = "never"
with mock.patch.object(transport_class, "__init__") as patched:
patched.return_value = None
client = client_class()
patched.assert_called_once_with(
api_mtls_endpoint=client.DEFAULT_ENDPOINT,
client_cert_source=None,
credentials=None,
host=client.DEFAULT_ENDPOINT,
)
# Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is
# "always".
os.environ["GOOGLE_API_USE_MTLS"] = "always"
with mock.patch.object(transport_class, "__init__") as patched:
patched.return_value = None
client = client_class()
patched.assert_called_once_with(
api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT,
client_cert_source=None,
credentials=None,
host=client.DEFAULT_MTLS_ENDPOINT,
)
# Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is
# "auto", and client_cert_source is provided.
os.environ["GOOGLE_API_USE_MTLS"] = "auto"
options = client_options.ClientOptions(
client_cert_source=client_cert_source_callback
)
with mock.patch.object(transport_class, "__init__") as patched:
patched.return_value = None
client = client_class(client_options=options)
patched.assert_called_once_with(
api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT,
client_cert_source=client_cert_source_callback,
credentials=None,
host=client.DEFAULT_MTLS_ENDPOINT,
)
# Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is
# "auto", and default_client_cert_source is provided.
os.environ["GOOGLE_API_USE_MTLS"] = "auto"
with mock.patch.object(transport_class, "__init__") as patched:
with mock.patch(
"google.auth.transport.mtls.has_default_client_cert_source",
return_value=True,
):
patched.return_value = None
client = client_class()
patched.assert_called_once_with(
api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT,
client_cert_source=None,
credentials=None,
host=client.DEFAULT_MTLS_ENDPOINT,
)
# Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is
# "auto", but client_cert_source and default_client_cert_source are None.
os.environ["GOOGLE_API_USE_MTLS"] = "auto"
with mock.patch.object(transport_class, "__init__") as patched:
with mock.patch(
"google.auth.transport.mtls.has_default_client_cert_source",
return_value=False,
):
patched.return_value = None
client = client_class()
patched.assert_called_once_with(
api_mtls_endpoint=client.DEFAULT_ENDPOINT,
client_cert_source=None,
credentials=None,
host=client.DEFAULT_ENDPOINT,
)
# Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS has
# unsupported value.
os.environ["GOOGLE_API_USE_MTLS"] = "Unsupported"
with pytest.raises(MutualTLSChannelError):
client = client_class()
del os.environ["GOOGLE_API_USE_MTLS"]
def test_os_config_service_client_client_options_from_dict():
with mock.patch(
"google.cloud.osconfig_v1.services.os_config_service.transports.OsConfigServiceGrpcTransport.__init__"
) as grpc_transport:
grpc_transport.return_value = None
client = OsConfigServiceClient(
client_options={"api_endpoint": "squid.clam.whelk"}
)
grpc_transport.assert_called_once_with(
api_mtls_endpoint="squid.clam.whelk",
client_cert_source=None,
credentials=None,
host="squid.clam.whelk",
)
def test_execute_patch_job(transport: str = "grpc"):
client = OsConfigServiceClient(
credentials=credentials.AnonymousCredentials(), transport=transport
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = patch_jobs.ExecutePatchJobRequest()
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._transport.execute_patch_job), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = patch_jobs.PatchJob(
name="name_value",
display_name="display_name_value",
description="description_value",
state=patch_jobs.PatchJob.State.STARTED,
dry_run=True,
error_message="error_message_value",
percent_complete=0.1705,
patch_deployment="patch_deployment_value",
)
response = client.execute_patch_job(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the response is the type that we expect.
assert isinstance(response, patch_jobs.PatchJob)
assert response.name == "name_value"
assert response.display_name == "display_name_value"
assert response.description == "description_value"
assert response.state == patch_jobs.PatchJob.State.STARTED
assert response.dry_run is True
assert response.error_message == "error_message_value"
assert math.isclose(response.percent_complete, 0.1705, rel_tol=1e-6)
assert response.patch_deployment == "patch_deployment_value"
@pytest.mark.asyncio
async def test_execute_patch_job_async(transport: str = "grpc_asyncio"):
client = OsConfigServiceAsyncClient(
credentials=credentials.AnonymousCredentials(), transport=transport
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = patch_jobs.ExecutePatchJobRequest()
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._client._transport.execute_patch_job), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
patch_jobs.PatchJob(
name="name_value",
display_name="display_name_value",
description="description_value",
state=patch_jobs.PatchJob.State.STARTED,
dry_run=True,
error_message="error_message_value",
percent_complete=0.1705,
patch_deployment="patch_deployment_value",
)
)
response = await client.execute_patch_job(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the response is the type that we expect.
assert isinstance(response, patch_jobs.PatchJob)
assert response.name == "name_value"
assert response.display_name == "display_name_value"
assert response.description == "description_value"
assert response.state == patch_jobs.PatchJob.State.STARTED
assert response.dry_run is True
assert response.error_message == "error_message_value"
assert math.isclose(response.percent_complete, 0.1705, rel_tol=1e-6)
assert response.patch_deployment == "patch_deployment_value"
def test_execute_patch_job_field_headers():
client = OsConfigServiceClient(credentials=credentials.AnonymousCredentials())
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = patch_jobs.ExecutePatchJobRequest()
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._transport.execute_patch_job), "__call__"
) as call:
call.return_value = patch_jobs.PatchJob()
client.execute_patch_job(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert ("x-goog-request-params", "parent=parent/value") in kw["metadata"]
@pytest.mark.asyncio
async def test_execute_patch_job_field_headers_async():
client = OsConfigServiceAsyncClient(credentials=credentials.AnonymousCredentials())
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = patch_jobs.ExecutePatchJobRequest()
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._client._transport.execute_patch_job), "__call__"
) as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(patch_jobs.PatchJob())
await client.execute_patch_job(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert ("x-goog-request-params", "parent=parent/value") in kw["metadata"]
def test_get_patch_job(transport: str = "grpc"):
client = OsConfigServiceClient(
credentials=credentials.AnonymousCredentials(), transport=transport
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = patch_jobs.GetPatchJobRequest()
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client._transport.get_patch_job), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = patch_jobs.PatchJob(
name="name_value",
display_name="display_name_value",
description="description_value",
state=patch_jobs.PatchJob.State.STARTED,
dry_run=True,
error_message="error_message_value",
percent_complete=0.1705,
patch_deployment="patch_deployment_value",
)
response = client.get_patch_job(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the response is the type that we expect.
assert isinstance(response, patch_jobs.PatchJob)
assert response.name == "name_value"
assert response.display_name == "display_name_value"
assert response.description == "description_value"
assert response.state == patch_jobs.PatchJob.State.STARTED
assert response.dry_run is True
assert response.error_message == "error_message_value"
assert math.isclose(response.percent_complete, 0.1705, rel_tol=1e-6)
assert response.patch_deployment == "patch_deployment_value"
@pytest.mark.asyncio
async def test_get_patch_job_async(transport: str = "grpc_asyncio"):
client = OsConfigServiceAsyncClient(
credentials=credentials.AnonymousCredentials(), transport=transport
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = patch_jobs.GetPatchJobRequest()
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._client._transport.get_patch_job), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
patch_jobs.PatchJob(
name="name_value",
display_name="display_name_value",
description="description_value",
state=patch_jobs.PatchJob.State.STARTED,
dry_run=True,
error_message="error_message_value",
percent_complete=0.1705,
patch_deployment="patch_deployment_value",
)
)
response = await client.get_patch_job(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the response is the type that we expect.
assert isinstance(response, patch_jobs.PatchJob)
assert response.name == "name_value"
assert response.display_name == "display_name_value"
assert response.description == "description_value"
assert response.state == patch_jobs.PatchJob.State.STARTED
assert response.dry_run is True
assert response.error_message == "error_message_value"
assert math.isclose(response.percent_complete, 0.1705, rel_tol=1e-6)
assert response.patch_deployment == "patch_deployment_value"
def test_get_patch_job_field_headers():
client = OsConfigServiceClient(credentials=credentials.AnonymousCredentials())
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = patch_jobs.GetPatchJobRequest()
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client._transport.get_patch_job), "__call__") as call:
call.return_value = patch_jobs.PatchJob()
client.get_patch_job(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert ("x-goog-request-params", "name=name/value") in kw["metadata"]
@pytest.mark.asyncio
async def test_get_patch_job_field_headers_async():
client = OsConfigServiceAsyncClient(credentials=credentials.AnonymousCredentials())
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = patch_jobs.GetPatchJobRequest()
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._client._transport.get_patch_job), "__call__"
) as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(patch_jobs.PatchJob())
await client.get_patch_job(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert ("x-goog-request-params", "name=name/value") in kw["metadata"]
def test_get_patch_job_flattened():
client = OsConfigServiceClient(credentials=credentials.AnonymousCredentials())
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client._transport.get_patch_job), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = patch_jobs.PatchJob()
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.get_patch_job(name="name_value")
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0].name == "name_value"
def test_get_patch_job_flattened_error():
client = OsConfigServiceClient(credentials=credentials.AnonymousCredentials())
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.get_patch_job(patch_jobs.GetPatchJobRequest(), name="name_value")
@pytest.mark.asyncio
async def test_get_patch_job_flattened_async():
client = OsConfigServiceAsyncClient(credentials=credentials.AnonymousCredentials())
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._client._transport.get_patch_job), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = patch_jobs.PatchJob()
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(patch_jobs.PatchJob())
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
response = await client.get_patch_job(name="name_value")
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0].name == "name_value"
@pytest.mark.asyncio
async def test_get_patch_job_flattened_error_async():
client = OsConfigServiceAsyncClient(credentials=credentials.AnonymousCredentials())
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
await client.get_patch_job(patch_jobs.GetPatchJobRequest(), name="name_value")
def test_cancel_patch_job(transport: str = "grpc"):
client = OsConfigServiceClient(
credentials=credentials.AnonymousCredentials(), transport=transport
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = patch_jobs.CancelPatchJobRequest()
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._transport.cancel_patch_job), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = patch_jobs.PatchJob(
name="name_value",
display_name="display_name_value",
description="description_value",
state=patch_jobs.PatchJob.State.STARTED,
dry_run=True,
error_message="error_message_value",
percent_complete=0.1705,
patch_deployment="patch_deployment_value",
)
response = client.cancel_patch_job(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the response is the type that we expect.
assert isinstance(response, patch_jobs.PatchJob)
assert response.name == "name_value"
assert response.display_name == "display_name_value"
assert response.description == "description_value"
assert response.state == patch_jobs.PatchJob.State.STARTED
assert response.dry_run is True
assert response.error_message == "error_message_value"
assert math.isclose(response.percent_complete, 0.1705, rel_tol=1e-6)
assert response.patch_deployment == "patch_deployment_value"
@pytest.mark.asyncio
async def test_cancel_patch_job_async(transport: str = "grpc_asyncio"):
client = OsConfigServiceAsyncClient(
credentials=credentials.AnonymousCredentials(), transport=transport
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = patch_jobs.CancelPatchJobRequest()
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._client._transport.cancel_patch_job), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
patch_jobs.PatchJob(
name="name_value",
display_name="display_name_value",
description="description_value",
state=patch_jobs.PatchJob.State.STARTED,
dry_run=True,
error_message="error_message_value",
percent_complete=0.1705,
patch_deployment="patch_deployment_value",
)
)
response = await client.cancel_patch_job(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the response is the type that we expect.
assert isinstance(response, patch_jobs.PatchJob)
assert response.name == "name_value"
assert response.display_name == "display_name_value"
assert response.description == "description_value"
assert response.state == patch_jobs.PatchJob.State.STARTED
assert response.dry_run is True
assert response.error_message == "error_message_value"
assert math.isclose(response.percent_complete, 0.1705, rel_tol=1e-6)
assert response.patch_deployment == "patch_deployment_value"
def test_cancel_patch_job_field_headers():
client = OsConfigServiceClient(credentials=credentials.AnonymousCredentials())
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = patch_jobs.CancelPatchJobRequest()
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._transport.cancel_patch_job), "__call__"
) as call:
call.return_value = patch_jobs.PatchJob()
client.cancel_patch_job(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert ("x-goog-request-params", "name=name/value") in kw["metadata"]
@pytest.mark.asyncio
async def test_cancel_patch_job_field_headers_async():
client = OsConfigServiceAsyncClient(credentials=credentials.AnonymousCredentials())
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = patch_jobs.CancelPatchJobRequest()
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._client._transport.cancel_patch_job), "__call__"
) as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(patch_jobs.PatchJob())
await client.cancel_patch_job(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert ("x-goog-request-params", "name=name/value") in kw["metadata"]
def test_list_patch_jobs(transport: str = "grpc"):
client = OsConfigServiceClient(
credentials=credentials.AnonymousCredentials(), transport=transport
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = patch_jobs.ListPatchJobsRequest()
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client._transport.list_patch_jobs), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = patch_jobs.ListPatchJobsResponse(
next_page_token="next_page_token_value"
)
response = client.list_patch_jobs(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the response is the type that we expect.
assert isinstance(response, pagers.ListPatchJobsPager)
assert response.next_page_token == "next_page_token_value"
@pytest.mark.asyncio
async def test_list_patch_jobs_async(transport: str = "grpc_asyncio"):
client = OsConfigServiceAsyncClient(
credentials=credentials.AnonymousCredentials(), transport=transport
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = patch_jobs.ListPatchJobsRequest()
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._client._transport.list_patch_jobs), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
patch_jobs.ListPatchJobsResponse(next_page_token="next_<PASSWORD>token_<PASSWORD>")
)
response = await client.list_patch_jobs(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the response is the type that we expect.
assert isinstance(response, pagers.ListPatchJobsAsyncPager)
assert response.next_page_token == "next_page_token_value"
def test_list_patch_jobs_field_headers():
client = OsConfigServiceClient(credentials=credentials.AnonymousCredentials())
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = patch_jobs.ListPatchJobsRequest()
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client._transport.list_patch_jobs), "__call__") as call:
call.return_value = patch_jobs.ListPatchJobsResponse()
client.list_patch_jobs(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert ("x-goog-request-params", "parent=parent/value") in kw["metadata"]
@pytest.mark.asyncio
async def test_list_patch_jobs_field_headers_async():
client = OsConfigServiceAsyncClient(credentials=credentials.AnonymousCredentials())
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = patch_jobs.ListPatchJobsRequest()
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._client._transport.list_patch_jobs), "__call__"
) as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
patch_jobs.ListPatchJobsResponse()
)
await client.list_patch_jobs(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert ("x-goog-request-params", "parent=parent/value") in kw["metadata"]
def test_list_patch_jobs_flattened():
client = OsConfigServiceClient(credentials=credentials.AnonymousCredentials())
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client._transport.list_patch_jobs), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = patch_jobs.ListPatchJobsResponse()
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.list_patch_jobs(parent="parent_value")
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0].parent == "parent_value"
def test_list_patch_jobs_flattened_error():
client = OsConfigServiceClient(credentials=credentials.AnonymousCredentials())
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.list_patch_jobs(patch_jobs.ListPatchJobsRequest(), parent="parent_value")
@pytest.mark.asyncio
async def test_list_patch_jobs_flattened_async():
client = OsConfigServiceAsyncClient(credentials=credentials.AnonymousCredentials())
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._client._transport.list_patch_jobs), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = patch_jobs.ListPatchJobsResponse()
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
patch_jobs.ListPatchJobsResponse()
)
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
response = await client.list_patch_jobs(parent="parent_value")
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0].parent == "parent_value"
@pytest.mark.asyncio
async def test_list_patch_jobs_flattened_error_async():
client = OsConfigServiceAsyncClient(credentials=credentials.AnonymousCredentials())
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
await client.list_patch_jobs(
patch_jobs.ListPatchJobsRequest(), parent="parent_value"
)
def test_list_patch_jobs_pager():
client = OsConfigServiceClient(credentials=credentials.AnonymousCredentials)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client._transport.list_patch_jobs), "__call__") as call:
# Set the response to a series of pages.
call.side_effect = (
patch_jobs.ListPatchJobsResponse(
patch_jobs=[
patch_jobs.PatchJob(),
patch_jobs.PatchJob(),
patch_jobs.PatchJob(),
],
next_page_token="abc",
),
patch_jobs.ListPatchJobsResponse(patch_jobs=[], next_page_token="def"),
patch_jobs.ListPatchJobsResponse(
patch_jobs=[patch_jobs.PatchJob()], next_page_token="ghi"
),
patch_jobs.ListPatchJobsResponse(
patch_jobs=[patch_jobs.PatchJob(), patch_jobs.PatchJob()]
),
RuntimeError,
)
results = [i for i in client.list_patch_jobs(request={})]
assert len(results) == 6
assert all(isinstance(i, patch_jobs.PatchJob) for i in results)
def test_list_patch_jobs_pages():
client = OsConfigServiceClient(credentials=credentials.AnonymousCredentials)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client._transport.list_patch_jobs), "__call__") as call:
# Set the response to a series of pages.
call.side_effect = (
patch_jobs.ListPatchJobsResponse(
patch_jobs=[
patch_jobs.PatchJob(),
patch_jobs.PatchJob(),
patch_jobs.PatchJob(),
],
next_page_token="abc",
),
patch_jobs.ListPatchJobsResponse(patch_jobs=[], next_page_token="def"),
patch_jobs.ListPatchJobsResponse(
patch_jobs=[patch_jobs.PatchJob()], next_page_token="ghi"
),
patch_jobs.ListPatchJobsResponse(
patch_jobs=[patch_jobs.PatchJob(), patch_jobs.PatchJob()]
),
RuntimeError,
)
pages = list(client.list_patch_jobs(request={}).pages)
for page, token in zip(pages, ["abc", "def", "ghi", ""]):
assert page.raw_page.next_page_token == token
@pytest.mark.asyncio
async def test_list_patch_jobs_async_pager():
client = OsConfigServiceAsyncClient(credentials=credentials.AnonymousCredentials)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._client._transport.list_patch_jobs),
"__call__",
new_callable=mock.AsyncMock,
) as call:
# Set the response to a series of pages.
call.side_effect = (
patch_jobs.ListPatchJobsResponse(
patch_jobs=[
patch_jobs.PatchJob(),
patch_jobs.PatchJob(),
patch_jobs.PatchJob(),
],
next_page_token="abc",
),
patch_jobs.ListPatchJobsResponse(patch_jobs=[], next_page_token="def"),
patch_jobs.ListPatchJobsResponse(
patch_jobs=[patch_jobs.PatchJob()], next_page_token="ghi"
),
patch_jobs.ListPatchJobsResponse(
patch_jobs=[patch_jobs.PatchJob(), patch_jobs.PatchJob()]
),
RuntimeError,
)
async_pager = await client.list_patch_jobs(request={})
assert async_pager.next_page_token == "abc"
responses = []
async for response in async_pager:
responses.append(response)
assert len(responses) == 6
assert all(isinstance(i, patch_jobs.PatchJob) for i in responses)
@pytest.mark.asyncio
async def test_list_patch_jobs_async_pages():
client = OsConfigServiceAsyncClient(credentials=credentials.AnonymousCredentials)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._client._transport.list_patch_jobs),
"__call__",
new_callable=mock.AsyncMock,
) as call:
# Set the response to a series of pages.
call.side_effect = (
patch_jobs.ListPatchJobsResponse(
patch_jobs=[
patch_jobs.PatchJob(),
patch_jobs.PatchJob(),
patch_jobs.PatchJob(),
],
next_page_token="abc",
),
patch_jobs.ListPatchJobsResponse(patch_jobs=[], next_page_token="def"),
patch_jobs.ListPatchJobsResponse(
patch_jobs=[patch_jobs.PatchJob()], next_page_token="ghi"
),
patch_jobs.ListPatchJobsResponse(
patch_jobs=[patch_jobs.PatchJob(), patch_jobs.PatchJob()]
),
RuntimeError,
)
pages = []
async for page in (await client.list_patch_jobs(request={})).pages:
pages.append(page)
for page, token in zip(pages, ["abc", "def", "ghi", ""]):
assert page.raw_page.next_page_token == token
def test_list_patch_job_instance_details(transport: str = "grpc"):
client = OsConfigServiceClient(
credentials=credentials.AnonymousCredentials(), transport=transport
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = patch_jobs.ListPatchJobInstanceDetailsRequest()
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._transport.list_patch_job_instance_details), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = patch_jobs.ListPatchJobInstanceDetailsResponse(
next_page_token="next_page_token_value"
)
response = client.list_patch_job_instance_details(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the response is the type that we expect.
assert isinstance(response, pagers.ListPatchJobInstanceDetailsPager)
assert response.next_page_token == "next_page_token_value"
@pytest.mark.asyncio
async def test_list_patch_job_instance_details_async(transport: str = "grpc_asyncio"):
client = OsConfigServiceAsyncClient(
credentials=credentials.AnonymousCredentials(), transport=transport
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = patch_jobs.ListPatchJobInstanceDetailsRequest()
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._client._transport.list_patch_job_instance_details), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
patch_jobs.ListPatchJobInstanceDetailsResponse(
next_page_token="next_page_token_value"
)
)
response = await client.list_patch_job_instance_details(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the response is the type that we expect.
assert isinstance(response, pagers.ListPatchJobInstanceDetailsAsyncPager)
assert response.next_page_token == "next_page_token_value"
def test_list_patch_job_instance_details_field_headers():
client = OsConfigServiceClient(credentials=credentials.AnonymousCredentials())
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = patch_jobs.ListPatchJobInstanceDetailsRequest()
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._transport.list_patch_job_instance_details), "__call__"
) as call:
call.return_value = patch_jobs.ListPatchJobInstanceDetailsResponse()
client.list_patch_job_instance_details(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert ("x-goog-request-params", "parent=parent/value") in kw["metadata"]
@pytest.mark.asyncio
async def test_list_patch_job_instance_details_field_headers_async():
client = OsConfigServiceAsyncClient(credentials=credentials.AnonymousCredentials())
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = patch_jobs.ListPatchJobInstanceDetailsRequest()
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._client._transport.list_patch_job_instance_details), "__call__"
) as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
patch_jobs.ListPatchJobInstanceDetailsResponse()
)
await client.list_patch_job_instance_details(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert ("x-goog-request-params", "parent=parent/value") in kw["metadata"]
def test_list_patch_job_instance_details_flattened():
client = OsConfigServiceClient(credentials=credentials.AnonymousCredentials())
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._transport.list_patch_job_instance_details), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = patch_jobs.ListPatchJobInstanceDetailsResponse()
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.list_patch_job_instance_details(parent="parent_value")
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0].parent == "parent_value"
def test_list_patch_job_instance_details_flattened_error():
client = OsConfigServiceClient(credentials=credentials.AnonymousCredentials())
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.list_patch_job_instance_details(
patch_jobs.ListPatchJobInstanceDetailsRequest(), parent="parent_value"
)
@pytest.mark.asyncio
async def test_list_patch_job_instance_details_flattened_async():
client = OsConfigServiceAsyncClient(credentials=credentials.AnonymousCredentials())
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._client._transport.list_patch_job_instance_details), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = patch_jobs.ListPatchJobInstanceDetailsResponse()
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
patch_jobs.ListPatchJobInstanceDetailsResponse()
)
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
response = await client.list_patch_job_instance_details(parent="parent_value")
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0].parent == "parent_value"
@pytest.mark.asyncio
async def test_list_patch_job_instance_details_flattened_error_async():
client = OsConfigServiceAsyncClient(credentials=credentials.AnonymousCredentials())
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
await client.list_patch_job_instance_details(
patch_jobs.ListPatchJobInstanceDetailsRequest(), parent="parent_value"
)
def test_list_patch_job_instance_details_pager():
client = OsConfigServiceClient(credentials=credentials.AnonymousCredentials)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._transport.list_patch_job_instance_details), "__call__"
) as call:
# Set the response to a series of pages.
call.side_effect = (
patch_jobs.ListPatchJobInstanceDetailsResponse(
patch_job_instance_details=[
patch_jobs.PatchJobInstanceDetails(),
patch_jobs.PatchJobInstanceDetails(),
patch_jobs.PatchJobInstanceDetails(),
],
next_page_token="abc",
),
patch_jobs.ListPatchJobInstanceDetailsResponse(
patch_job_instance_details=[], next_page_token="def"
),
patch_jobs.ListPatchJobInstanceDetailsResponse(
patch_job_instance_details=[patch_jobs.PatchJobInstanceDetails()],
next_page_token="ghi",
),
patch_jobs.ListPatchJobInstanceDetailsResponse(
patch_job_instance_details=[
patch_jobs.PatchJobInstanceDetails(),
patch_jobs.PatchJobInstanceDetails(),
]
),
RuntimeError,
)
results = [i for i in client.list_patch_job_instance_details(request={})]
assert len(results) == 6
assert all(isinstance(i, patch_jobs.PatchJobInstanceDetails) for i in results)
def test_list_patch_job_instance_details_pages():
client = OsConfigServiceClient(credentials=credentials.AnonymousCredentials)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._transport.list_patch_job_instance_details), "__call__"
) as call:
# Set the response to a series of pages.
call.side_effect = (
patch_jobs.ListPatchJobInstanceDetailsResponse(
patch_job_instance_details=[
patch_jobs.PatchJobInstanceDetails(),
patch_jobs.PatchJobInstanceDetails(),
patch_jobs.PatchJobInstanceDetails(),
],
next_page_token="abc",
),
patch_jobs.ListPatchJobInstanceDetailsResponse(
patch_job_instance_details=[], next_page_token="def"
),
patch_jobs.ListPatchJobInstanceDetailsResponse(
patch_job_instance_details=[patch_jobs.PatchJobInstanceDetails()],
next_page_token="ghi",
),
patch_jobs.ListPatchJobInstanceDetailsResponse(
patch_job_instance_details=[
patch_jobs.PatchJobInstanceDetails(),
patch_jobs.PatchJobInstanceDetails(),
]
),
RuntimeError,
)
pages = list(client.list_patch_job_instance_details(request={}).pages)
for page, token in zip(pages, ["abc", "def", "ghi", ""]):
assert page.raw_page.next_page_token == token
@pytest.mark.asyncio
async def test_list_patch_job_instance_details_async_pager():
client = OsConfigServiceAsyncClient(credentials=credentials.AnonymousCredentials)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._client._transport.list_patch_job_instance_details),
"__call__",
new_callable=mock.AsyncMock,
) as call:
# Set the response to a series of pages.
call.side_effect = (
patch_jobs.ListPatchJobInstanceDetailsResponse(
patch_job_instance_details=[
patch_jobs.PatchJobInstanceDetails(),
patch_jobs.PatchJobInstanceDetails(),
patch_jobs.PatchJobInstanceDetails(),
],
next_page_token="abc",
),
patch_jobs.ListPatchJobInstanceDetailsResponse(
patch_job_instance_details=[], next_page_token="def"
),
patch_jobs.ListPatchJobInstanceDetailsResponse(
patch_job_instance_details=[patch_jobs.PatchJobInstanceDetails()],
next_page_token="ghi",
),
patch_jobs.ListPatchJobInstanceDetailsResponse(
patch_job_instance_details=[
patch_jobs.PatchJobInstanceDetails(),
patch_jobs.PatchJobInstanceDetails(),
]
),
RuntimeError,
)
async_pager = await client.list_patch_job_instance_details(request={})
assert async_pager.next_page_token == "abc"
responses = []
async for response in async_pager:
responses.append(response)
assert len(responses) == 6
assert all(isinstance(i, patch_jobs.PatchJobInstanceDetails) for i in responses)
@pytest.mark.asyncio
async def test_list_patch_job_instance_details_async_pages():
client = OsConfigServiceAsyncClient(credentials=credentials.AnonymousCredentials)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._client._transport.list_patch_job_instance_details),
"__call__",
new_callable=mock.AsyncMock,
) as call:
# Set the response to a series of pages.
call.side_effect = (
patch_jobs.ListPatchJobInstanceDetailsResponse(
patch_job_instance_details=[
patch_jobs.PatchJobInstanceDetails(),
patch_jobs.PatchJobInstanceDetails(),
patch_jobs.PatchJobInstanceDetails(),
],
next_page_token="abc",
),
patch_jobs.ListPatchJobInstanceDetailsResponse(
patch_job_instance_details=[], next_page_token="def"
),
patch_jobs.ListPatchJobInstanceDetailsResponse(
patch_job_instance_details=[patch_jobs.PatchJobInstanceDetails()],
next_page_token="ghi",
),
patch_jobs.ListPatchJobInstanceDetailsResponse(
patch_job_instance_details=[
patch_jobs.PatchJobInstanceDetails(),
patch_jobs.PatchJobInstanceDetails(),
]
),
RuntimeError,
)
pages = []
async for page in (
await client.list_patch_job_instance_details(request={})
).pages:
pages.append(page)
for page, token in zip(pages, ["abc", "def", "ghi", ""]):
assert page.raw_page.next_page_token == token
def test_create_patch_deployment(transport: str = "grpc"):
client = OsConfigServiceClient(
credentials=credentials.AnonymousCredentials(), transport=transport
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = patch_deployments.CreatePatchDeploymentRequest()
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._transport.create_patch_deployment), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = patch_deployments.PatchDeployment(
name="name_value", description="description_value"
)
response = client.create_patch_deployment(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the response is the type that we expect.
assert isinstance(response, patch_deployments.PatchDeployment)
assert response.name == "name_value"
assert response.description == "description_value"
@pytest.mark.asyncio
async def test_create_patch_deployment_async(transport: str = "grpc_asyncio"):
client = OsConfigServiceAsyncClient(
credentials=credentials.AnonymousCredentials(), transport=transport
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = patch_deployments.CreatePatchDeploymentRequest()
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._client._transport.create_patch_deployment), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
patch_deployments.PatchDeployment(
name="name_value", description="description_value"
)
)
response = await client.create_patch_deployment(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the response is the type that we expect.
assert isinstance(response, patch_deployments.PatchDeployment)
assert response.name == "name_value"
assert response.description == "description_value"
def test_create_patch_deployment_field_headers():
client = OsConfigServiceClient(credentials=credentials.AnonymousCredentials())
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = patch_deployments.CreatePatchDeploymentRequest()
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._transport.create_patch_deployment), "__call__"
) as call:
call.return_value = patch_deployments.PatchDeployment()
client.create_patch_deployment(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert ("x-goog-request-params", "parent=parent/value") in kw["metadata"]
@pytest.mark.asyncio
async def test_create_patch_deployment_field_headers_async():
client = OsConfigServiceAsyncClient(credentials=credentials.AnonymousCredentials())
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = patch_deployments.CreatePatchDeploymentRequest()
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._client._transport.create_patch_deployment), "__call__"
) as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
patch_deployments.PatchDeployment()
)
await client.create_patch_deployment(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert ("x-goog-request-params", "parent=parent/value") in kw["metadata"]
def test_create_patch_deployment_flattened():
client = OsConfigServiceClient(credentials=credentials.AnonymousCredentials())
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._transport.create_patch_deployment), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = patch_deployments.PatchDeployment()
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.create_patch_deployment(
parent="parent_value",
patch_deployment=patch_deployments.PatchDeployment(name="name_value"),
patch_deployment_id="patch_deployment_id_value",
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0].parent == "parent_value"
assert args[0].patch_deployment == patch_deployments.PatchDeployment(
name="name_value"
)
assert args[0].patch_deployment_id == "patch_deployment_id_value"
def test_create_patch_deployment_flattened_error():
client = OsConfigServiceClient(credentials=credentials.AnonymousCredentials())
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.create_patch_deployment(
patch_deployments.CreatePatchDeploymentRequest(),
parent="parent_value",
patch_deployment=patch_deployments.PatchDeployment(name="name_value"),
patch_deployment_id="patch_deployment_id_value",
)
@pytest.mark.asyncio
async def test_create_patch_deployment_flattened_async():
client = OsConfigServiceAsyncClient(credentials=credentials.AnonymousCredentials())
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._client._transport.create_patch_deployment), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = patch_deployments.PatchDeployment()
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
patch_deployments.PatchDeployment()
)
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
response = await client.create_patch_deployment(
parent="parent_value",
patch_deployment=patch_deployments.PatchDeployment(name="name_value"),
patch_deployment_id="patch_deployment_id_value",
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0].parent == "parent_value"
assert args[0].patch_deployment == patch_deployments.PatchDeployment(
name="name_value"
)
assert args[0].patch_deployment_id == "patch_deployment_id_value"
@pytest.mark.asyncio
async def test_create_patch_deployment_flattened_error_async():
client = OsConfigServiceAsyncClient(credentials=credentials.AnonymousCredentials())
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
await client.create_patch_deployment(
patch_deployments.CreatePatchDeploymentRequest(),
parent="parent_value",
patch_deployment=patch_deployments.PatchDeployment(name="name_value"),
patch_deployment_id="patch_deployment_id_value",
)
def test_get_patch_deployment(transport: str = "grpc"):
client = OsConfigServiceClient(
credentials=credentials.AnonymousCredentials(), transport=transport
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = patch_deployments.GetPatchDeploymentRequest()
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._transport.get_patch_deployment), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = patch_deployments.PatchDeployment(
name="name_value", description="description_value"
)
response = client.get_patch_deployment(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the response is the type that we expect.
assert isinstance(response, patch_deployments.PatchDeployment)
assert response.name == "name_value"
assert response.description == "description_value"
@pytest.mark.asyncio
async def test_get_patch_deployment_async(transport: str = "grpc_asyncio"):
client = OsConfigServiceAsyncClient(
credentials=credentials.AnonymousCredentials(), transport=transport
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = patch_deployments.GetPatchDeploymentRequest()
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._client._transport.get_patch_deployment), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
patch_deployments.PatchDeployment(
name="name_value", description="description_value"
)
)
response = await client.get_patch_deployment(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the response is the type that we expect.
assert isinstance(response, patch_deployments.PatchDeployment)
assert response.name == "name_value"
assert response.description == "description_value"
def test_get_patch_deployment_field_headers():
client = OsConfigServiceClient(credentials=credentials.AnonymousCredentials())
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = patch_deployments.GetPatchDeploymentRequest()
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._transport.get_patch_deployment), "__call__"
) as call:
call.return_value = patch_deployments.PatchDeployment()
client.get_patch_deployment(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert ("x-goog-request-params", "name=name/value") in kw["metadata"]
@pytest.mark.asyncio
async def test_get_patch_deployment_field_headers_async():
client = OsConfigServiceAsyncClient(credentials=credentials.AnonymousCredentials())
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = patch_deployments.GetPatchDeploymentRequest()
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._client._transport.get_patch_deployment), "__call__"
) as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
patch_deployments.PatchDeployment()
)
await client.get_patch_deployment(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert ("x-goog-request-params", "name=name/value") in kw["metadata"]
def test_get_patch_deployment_flattened():
client = OsConfigServiceClient(credentials=credentials.AnonymousCredentials())
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._transport.get_patch_deployment), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = patch_deployments.PatchDeployment()
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.get_patch_deployment(name="name_value")
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0].name == "name_value"
def test_get_patch_deployment_flattened_error():
client = OsConfigServiceClient(credentials=credentials.AnonymousCredentials())
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.get_patch_deployment(
patch_deployments.GetPatchDeploymentRequest(), name="name_value"
)
@pytest.mark.asyncio
async def test_get_patch_deployment_flattened_async():
client = OsConfigServiceAsyncClient(credentials=credentials.AnonymousCredentials())
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._client._transport.get_patch_deployment), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = patch_deployments.PatchDeployment()
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
patch_deployments.PatchDeployment()
)
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
response = await client.get_patch_deployment(name="name_value")
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0].name == "name_value"
@pytest.mark.asyncio
async def test_get_patch_deployment_flattened_error_async():
client = OsConfigServiceAsyncClient(credentials=credentials.AnonymousCredentials())
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
await client.get_patch_deployment(
patch_deployments.GetPatchDeploymentRequest(), name="name_value"
)
def test_list_patch_deployments(transport: str = "grpc"):
client = OsConfigServiceClient(
credentials=credentials.AnonymousCredentials(), transport=transport
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = patch_deployments.ListPatchDeploymentsRequest()
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._transport.list_patch_deployments), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = patch_deployments.ListPatchDeploymentsResponse(
next_page_token="next_page_token_value"
)
response = client.list_patch_deployments(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the response is the type that we expect.
assert isinstance(response, pagers.ListPatchDeploymentsPager)
assert response.next_page_token == "next_page_token_value"
@pytest.mark.asyncio
async def test_list_patch_deployments_async(transport: str = "grpc_asyncio"):
client = OsConfigServiceAsyncClient(
credentials=credentials.AnonymousCredentials(), transport=transport
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = patch_deployments.ListPatchDeploymentsRequest()
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._client._transport.list_patch_deployments), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
patch_deployments.ListPatchDeploymentsResponse(
next_page_token="next_page_token_value"
)
)
response = await client.list_patch_deployments(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the response is the type that we expect.
assert isinstance(response, pagers.ListPatchDeploymentsAsyncPager)
assert response.next_page_token == "next_page_token_value"
def test_list_patch_deployments_field_headers():
client = OsConfigServiceClient(credentials=credentials.AnonymousCredentials())
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = patch_deployments.ListPatchDeploymentsRequest()
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._transport.list_patch_deployments), "__call__"
) as call:
call.return_value = patch_deployments.ListPatchDeploymentsResponse()
client.list_patch_deployments(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert ("x-goog-request-params", "parent=parent/value") in kw["metadata"]
@pytest.mark.asyncio
async def test_list_patch_deployments_field_headers_async():
client = OsConfigServiceAsyncClient(credentials=credentials.AnonymousCredentials())
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = patch_deployments.ListPatchDeploymentsRequest()
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._client._transport.list_patch_deployments), "__call__"
) as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
patch_deployments.ListPatchDeploymentsResponse()
)
await client.list_patch_deployments(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert ("x-goog-request-params", "parent=parent/value") in kw["metadata"]
def test_list_patch_deployments_flattened():
client = OsConfigServiceClient(credentials=credentials.AnonymousCredentials())
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._transport.list_patch_deployments), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = patch_deployments.ListPatchDeploymentsResponse()
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.list_patch_deployments(parent="parent_value")
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0].parent == "parent_value"
def test_list_patch_deployments_flattened_error():
client = OsConfigServiceClient(credentials=credentials.AnonymousCredentials())
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.list_patch_deployments(
patch_deployments.ListPatchDeploymentsRequest(), parent="parent_value"
)
@pytest.mark.asyncio
async def test_list_patch_deployments_flattened_async():
client = OsConfigServiceAsyncClient(credentials=credentials.AnonymousCredentials())
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._client._transport.list_patch_deployments), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = patch_deployments.ListPatchDeploymentsResponse()
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
patch_deployments.ListPatchDeploymentsResponse()
)
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
response = await client.list_patch_deployments(parent="parent_value")
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0].parent == "parent_value"
@pytest.mark.asyncio
async def test_list_patch_deployments_flattened_error_async():
client = OsConfigServiceAsyncClient(credentials=credentials.AnonymousCredentials())
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
await client.list_patch_deployments(
patch_deployments.ListPatchDeploymentsRequest(), parent="parent_value"
)
def test_list_patch_deployments_pager():
client = OsConfigServiceClient(credentials=credentials.AnonymousCredentials)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._transport.list_patch_deployments), "__call__"
) as call:
# Set the response to a series of pages.
call.side_effect = (
patch_deployments.ListPatchDeploymentsResponse(
patch_deployments=[
patch_deployments.PatchDeployment(),
patch_deployments.PatchDeployment(),
patch_deployments.PatchDeployment(),
],
next_page_token="abc",
),
patch_deployments.ListPatchDeploymentsResponse(
patch_deployments=[], next_page_token="def"
),
patch_deployments.ListPatchDeploymentsResponse(
patch_deployments=[patch_deployments.PatchDeployment()],
next_page_token="ghi",
),
patch_deployments.ListPatchDeploymentsResponse(
patch_deployments=[
patch_deployments.PatchDeployment(),
patch_deployments.PatchDeployment(),
]
),
RuntimeError,
)
results = [i for i in client.list_patch_deployments(request={})]
assert len(results) == 6
assert all(isinstance(i, patch_deployments.PatchDeployment) for i in results)
def test_list_patch_deployments_pages():
client = OsConfigServiceClient(credentials=credentials.AnonymousCredentials)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._transport.list_patch_deployments), "__call__"
) as call:
# Set the response to a series of pages.
call.side_effect = (
patch_deployments.ListPatchDeploymentsResponse(
patch_deployments=[
patch_deployments.PatchDeployment(),
patch_deployments.PatchDeployment(),
patch_deployments.PatchDeployment(),
],
next_page_token="abc",
),
patch_deployments.ListPatchDeploymentsResponse(
patch_deployments=[], next_page_token="def"
),
patch_deployments.ListPatchDeploymentsResponse(
patch_deployments=[patch_deployments.PatchDeployment()],
next_page_token="ghi",
),
patch_deployments.ListPatchDeploymentsResponse(
patch_deployments=[
patch_deployments.PatchDeployment(),
patch_deployments.PatchDeployment(),
]
),
RuntimeError,
)
pages = list(client.list_patch_deployments(request={}).pages)
for page, token in zip(pages, ["abc", "def", "ghi", ""]):
assert page.raw_page.next_page_token == token
@pytest.mark.asyncio
async def test_list_patch_deployments_async_pager():
client = OsConfigServiceAsyncClient(credentials=credentials.AnonymousCredentials)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._client._transport.list_patch_deployments),
"__call__",
new_callable=mock.AsyncMock,
) as call:
# Set the response to a series of pages.
call.side_effect = (
patch_deployments.ListPatchDeploymentsResponse(
patch_deployments=[
patch_deployments.PatchDeployment(),
patch_deployments.PatchDeployment(),
patch_deployments.PatchDeployment(),
],
next_page_token="abc",
),
patch_deployments.ListPatchDeploymentsResponse(
patch_deployments=[], next_page_token="def"
),
patch_deployments.ListPatchDeploymentsResponse(
patch_deployments=[patch_deployments.PatchDeployment()],
next_page_token="ghi",
),
patch_deployments.ListPatchDeploymentsResponse(
patch_deployments=[
patch_deployments.PatchDeployment(),
patch_deployments.PatchDeployment(),
]
),
RuntimeError,
)
async_pager = await client.list_patch_deployments(request={})
assert async_pager.next_page_token == "abc"
responses = []
async for response in async_pager:
responses.append(response)
assert len(responses) == 6
assert all(isinstance(i, patch_deployments.PatchDeployment) for i in responses)
@pytest.mark.asyncio
async def test_list_patch_deployments_async_pages():
client = OsConfigServiceAsyncClient(credentials=credentials.AnonymousCredentials)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._client._transport.list_patch_deployments),
"__call__",
new_callable=mock.AsyncMock,
) as call:
# Set the response to a series of pages.
call.side_effect = (
patch_deployments.ListPatchDeploymentsResponse(
patch_deployments=[
patch_deployments.PatchDeployment(),
patch_deployments.PatchDeployment(),
patch_deployments.PatchDeployment(),
],
next_page_token="abc",
),
patch_deployments.ListPatchDeploymentsResponse(
patch_deployments=[], next_page_token="def"
),
patch_deployments.ListPatchDeploymentsResponse(
patch_deployments=[patch_deployments.PatchDeployment()],
next_page_token="ghi",
),
patch_deployments.ListPatchDeploymentsResponse(
patch_deployments=[
patch_deployments.PatchDeployment(),
patch_deployments.PatchDeployment(),
]
),
RuntimeError,
)
pages = []
async for page in (await client.list_patch_deployments(request={})).pages:
pages.append(page)
for page, token in zip(pages, ["abc", "def", "ghi", ""]):
assert page.raw_page.next_page_token == token
def test_delete_patch_deployment(transport: str = "grpc"):
client = OsConfigServiceClient(
credentials=credentials.AnonymousCredentials(), transport=transport
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = patch_deployments.DeletePatchDeploymentRequest()
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._transport.delete_patch_deployment), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = None
response = client.delete_patch_deployment(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the response is the type that we expect.
assert response is None
@pytest.mark.asyncio
async def test_delete_patch_deployment_async(transport: str = "grpc_asyncio"):
client = OsConfigServiceAsyncClient(
credentials=credentials.AnonymousCredentials(), transport=transport
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = patch_deployments.DeletePatchDeploymentRequest()
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._client._transport.delete_patch_deployment), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
response = await client.delete_patch_deployment(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the response is the type that we expect.
assert response is None
def test_delete_patch_deployment_field_headers():
client = OsConfigServiceClient(credentials=credentials.AnonymousCredentials())
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = patch_deployments.DeletePatchDeploymentRequest()
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._transport.delete_patch_deployment), "__call__"
) as call:
call.return_value = None
client.delete_patch_deployment(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert ("x-goog-request-params", "name=name/value") in kw["metadata"]
@pytest.mark.asyncio
async def test_delete_patch_deployment_field_headers_async():
client = OsConfigServiceAsyncClient(credentials=credentials.AnonymousCredentials())
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = patch_deployments.DeletePatchDeploymentRequest()
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._client._transport.delete_patch_deployment), "__call__"
) as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
await client.delete_patch_deployment(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert ("x-goog-request-params", "name=name/value") in kw["metadata"]
def test_delete_patch_deployment_flattened():
client = OsConfigServiceClient(credentials=credentials.AnonymousCredentials())
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._transport.delete_patch_deployment), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = None
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.delete_patch_deployment(name="name_value")
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0].name == "name_value"
def test_delete_patch_deployment_flattened_error():
client = OsConfigServiceClient(credentials=credentials.AnonymousCredentials())
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.delete_patch_deployment(
patch_deployments.DeletePatchDeploymentRequest(), name="name_value"
)
@pytest.mark.asyncio
async def test_delete_patch_deployment_flattened_async():
client = OsConfigServiceAsyncClient(credentials=credentials.AnonymousCredentials())
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client._client._transport.delete_patch_deployment), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = None
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
response = await client.delete_patch_deployment(name="name_value")
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0].name == "name_value"
@pytest.mark.asyncio
async def test_delete_patch_deployment_flattened_error_async():
client = OsConfigServiceAsyncClient(credentials=credentials.AnonymousCredentials())
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
await client.delete_patch_deployment(
patch_deployments.DeletePatchDeploymentRequest(), name="name_value"
)
def test_credentials_transport_error():
# It is an error to provide credentials and a transport instance.
transport = transports.OsConfigServiceGrpcTransport(
credentials=credentials.AnonymousCredentials()
)
with pytest.raises(ValueError):
client = OsConfigServiceClient(
credentials=credentials.AnonymousCredentials(), transport=transport
)
def test_transport_instance():
# A client may be instantiated with a custom transport instance.
transport = transports.OsConfigServiceGrpcTransport(
credentials=credentials.AnonymousCredentials()
)
client = OsConfigServiceClient(transport=transport)
assert client._transport is transport
def test_transport_get_channel():
# A client may be instantiated with a custom transport instance.
transport = transports.OsConfigServiceGrpcTransport(
credentials=credentials.AnonymousCredentials()
)
channel = transport.grpc_channel
assert channel
transport = transports.OsConfigServiceGrpcAsyncIOTransport(
credentials=credentials.AnonymousCredentials()
)
channel = transport.grpc_channel
assert channel
def test_transport_grpc_default():
# A client should use the gRPC transport by default.
client = OsConfigServiceClient(credentials=credentials.AnonymousCredentials())
assert isinstance(client._transport, transports.OsConfigServiceGrpcTransport)
def test_os_config_service_base_transport():
# Instantiate the base transport.
transport = transports.OsConfigServiceTransport(
credentials=credentials.AnonymousCredentials()
)
# Every method on the transport should just blindly
# raise NotImplementedError.
methods = (
"execute_patch_job",
"get_patch_job",
"cancel_patch_job",
"list_patch_jobs",
"list_patch_job_instance_details",
"create_patch_deployment",
"get_patch_deployment",
"list_patch_deployments",
"delete_patch_deployment",
)
for method in methods:
with pytest.raises(NotImplementedError):
getattr(transport, method)(request=object())
def test_os_config_service_auth_adc():
# If no credentials are provided, we should use ADC credentials.
with mock.patch.object(auth, "default") as adc:
adc.return_value = (credentials.AnonymousCredentials(), None)
OsConfigServiceClient()
adc.assert_called_once_with(
scopes=("https://www.googleapis.com/auth/cloud-platform",)
)
def test_os_config_service_transport_auth_adc():
# If credentials and host are not provided, the transport class should use
# ADC credentials.
with mock.patch.object(auth, "default") as adc:
adc.return_value = (credentials.AnonymousCredentials(), None)
transports.OsConfigServiceGrpcTransport(host="squid.clam.whelk")
adc.assert_called_once_with(
scopes=("https://www.googleapis.com/auth/cloud-platform",)
)
def test_os_config_service_host_no_port():
client = OsConfigServiceClient(
credentials=credentials.AnonymousCredentials(),
client_options=client_options.ClientOptions(
api_endpoint="osconfig.googleapis.com"
),
)
assert client._transport._host == "osconfig.googleapis.com:443"
def test_os_config_service_host_with_port():
client = OsConfigServiceClient(
credentials=credentials.AnonymousCredentials(),
client_options=client_options.ClientOptions(
api_endpoint="osconfig.googleapis.com:8000"
),
)
assert client._transport._host == "osconfig.googleapis.com:8000"
def test_os_config_service_grpc_transport_channel():
channel = grpc.insecure_channel("http://localhost/")
# Check that if channel is provided, mtls endpoint and client_cert_source
# won't be used.
callback = mock.MagicMock()
transport = transports.OsConfigServiceGrpcTransport(
host="squid.clam.whelk",
channel=channel,
api_mtls_endpoint="mtls.squid.clam.whelk",
client_cert_source=callback,
)
assert transport.grpc_channel == channel
assert transport._host == "squid.clam.whelk:443"
assert not callback.called
def test_os_config_service_grpc_asyncio_transport_channel():
channel = aio.insecure_channel("http://localhost/")
# Check that if channel is provided, mtls endpoint and client_cert_source
# won't be used.
callback = mock.MagicMock()
transport = transports.OsConfigServiceGrpcAsyncIOTransport(
host="squid.clam.whelk",
channel=channel,
api_mtls_endpoint="mtls.squid.clam.whelk",
client_cert_source=callback,
)
assert transport.grpc_channel == channel
assert transport._host == "squid.clam.whelk:443"
assert not callback.called
@mock.patch("grpc.ssl_channel_credentials", autospec=True)
@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True)
def test_os_config_service_grpc_transport_channel_mtls_with_client_cert_source(
grpc_create_channel, grpc_ssl_channel_cred
):
# Check that if channel is None, but api_mtls_endpoint and client_cert_source
# are provided, then a mTLS channel will be created.
mock_cred = mock.Mock()
mock_ssl_cred = mock.Mock()
grpc_ssl_channel_cred.return_value = mock_ssl_cred
mock_grpc_channel = mock.Mock()
grpc_create_channel.return_value = mock_grpc_channel
transport = transports.OsConfigServiceGrpcTransport(
host="squid.clam.whelk",
credentials=mock_cred,
api_mtls_endpoint="mtls.squid.clam.whelk",
client_cert_source=client_cert_source_callback,
)
grpc_ssl_channel_cred.assert_called_once_with(
certificate_chain=b"cert bytes", private_key=b"key bytes"
)
grpc_create_channel.assert_called_once_with(
"mtls.squid.clam.whelk:443",
credentials=mock_cred,
ssl_credentials=mock_ssl_cred,
scopes=("https://www.googleapis.com/auth/cloud-platform",),
)
assert transport.grpc_channel == mock_grpc_channel
@mock.patch("grpc.ssl_channel_credentials", autospec=True)
@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True)
def test_os_config_service_grpc_asyncio_transport_channel_mtls_with_client_cert_source(
grpc_create_channel, grpc_ssl_channel_cred
):
# Check that if channel is None, but api_mtls_endpoint and client_cert_source
# are provided, then a mTLS channel will be created.
mock_cred = mock.Mock()
mock_ssl_cred = mock.Mock()
grpc_ssl_channel_cred.return_value = mock_ssl_cred
mock_grpc_channel = mock.Mock()
grpc_create_channel.return_value = mock_grpc_channel
transport = transports.OsConfigServiceGrpcAsyncIOTransport(
host="squid.clam.whelk",
credentials=mock_cred,
api_mtls_endpoint="mtls.squid.clam.whelk",
client_cert_source=client_cert_source_callback,
)
grpc_ssl_channel_cred.assert_called_once_with(
certificate_chain=b"cert bytes", private_key=b"key bytes"
)
grpc_create_channel.assert_called_once_with(
"mtls.squid.clam.whelk:443",
credentials=mock_cred,
ssl_credentials=mock_ssl_cred,
scopes=("https://www.googleapis.com/auth/cloud-platform",),
)
assert transport.grpc_channel == mock_grpc_channel
@pytest.mark.parametrize(
"api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"]
)
@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True)
def test_os_config_service_grpc_transport_channel_mtls_with_adc(
grpc_create_channel, api_mtls_endpoint
):
# Check that if channel and client_cert_source are None, but api_mtls_endpoint
# is provided, then a mTLS channel will be created with SSL ADC.
mock_grpc_channel = mock.Mock()
grpc_create_channel.return_value = mock_grpc_channel
# Mock google.auth.transport.grpc.SslCredentials class.
mock_ssl_cred = mock.Mock()
with mock.patch.multiple(
"google.auth.transport.grpc.SslCredentials",
__init__=mock.Mock(return_value=None),
ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
):
mock_cred = mock.Mock()
transport = transports.OsConfigServiceGrpcTransport(
host="squid.clam.whelk",
credentials=mock_cred,
api_mtls_endpoint=api_mtls_endpoint,
client_cert_source=None,
)
grpc_create_channel.assert_called_once_with(
"mtls.squid.clam.whelk:443",
credentials=mock_cred,
ssl_credentials=mock_ssl_cred,
scopes=("https://www.googleapis.com/auth/cloud-platform",),
)
assert transport.grpc_channel == mock_grpc_channel
@pytest.mark.parametrize(
"api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"]
)
@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True)
def test_os_config_service_grpc_asyncio_transport_channel_mtls_with_adc(
grpc_create_channel, api_mtls_endpoint
):
# Check that if channel and client_cert_source are None, but api_mtls_endpoint
# is provided, then a mTLS channel will be created with SSL ADC.
mock_grpc_channel = mock.Mock()
grpc_create_channel.return_value = mock_grpc_channel
# Mock google.auth.transport.grpc.SslCredentials class.
mock_ssl_cred = mock.Mock()
with mock.patch.multiple(
"google.auth.transport.grpc.SslCredentials",
__init__=mock.Mock(return_value=None),
ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
):
mock_cred = mock.Mock()
transport = transports.OsConfigServiceGrpcAsyncIOTransport(
host="squid.clam.whelk",
credentials=mock_cred,
api_mtls_endpoint=api_mtls_endpoint,
client_cert_source=None,
)
grpc_create_channel.assert_called_once_with(
"mtls.squid.clam.whelk:443",
credentials=mock_cred,
ssl_credentials=mock_ssl_cred,
scopes=("https://www.googleapis.com/auth/cloud-platform",),
)
assert transport.grpc_channel == mock_grpc_channel
def test_patch_deployment_path():
project = "squid"
patch_deployment = "clam"
expected = "projects/{project}/patchDeployments/{patch_deployment}".format(
project=project, patch_deployment=patch_deployment
)
actual = OsConfigServiceClient.patch_deployment_path(project, patch_deployment)
assert expected == actual
def test_parse_patch_deployment_path():
expected = {"project": "whelk", "patch_deployment": "octopus"}
path = OsConfigServiceClient.patch_deployment_path(**expected)
# Check that the path construction is reversible.
actual = OsConfigServiceClient.parse_patch_deployment_path(path)
assert expected == actual
<file_sep># -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from google.cloud.osconfig_v1.services.os_config_service.async_client import (
OsConfigServiceAsyncClient,
)
from google.cloud.osconfig_v1.services.os_config_service.client import (
OsConfigServiceClient,
)
from google.cloud.osconfig_v1.types.patch_deployments import (
CreatePatchDeploymentRequest,
)
from google.cloud.osconfig_v1.types.patch_deployments import (
DeletePatchDeploymentRequest,
)
from google.cloud.osconfig_v1.types.patch_deployments import GetPatchDeploymentRequest
from google.cloud.osconfig_v1.types.patch_deployments import ListPatchDeploymentsRequest
from google.cloud.osconfig_v1.types.patch_deployments import (
ListPatchDeploymentsResponse,
)
from google.cloud.osconfig_v1.types.patch_deployments import MonthlySchedule
from google.cloud.osconfig_v1.types.patch_deployments import OneTimeSchedule
from google.cloud.osconfig_v1.types.patch_deployments import PatchDeployment
from google.cloud.osconfig_v1.types.patch_deployments import RecurringSchedule
from google.cloud.osconfig_v1.types.patch_deployments import WeekDayOfMonth
from google.cloud.osconfig_v1.types.patch_deployments import WeeklySchedule
from google.cloud.osconfig_v1.types.patch_jobs import AptSettings
from google.cloud.osconfig_v1.types.patch_jobs import CancelPatchJobRequest
from google.cloud.osconfig_v1.types.patch_jobs import ExecStep
from google.cloud.osconfig_v1.types.patch_jobs import ExecStepConfig
from google.cloud.osconfig_v1.types.patch_jobs import ExecutePatchJobRequest
from google.cloud.osconfig_v1.types.patch_jobs import GcsObject
from google.cloud.osconfig_v1.types.patch_jobs import GetPatchJobRequest
from google.cloud.osconfig_v1.types.patch_jobs import GooSettings
from google.cloud.osconfig_v1.types.patch_jobs import Instance
from google.cloud.osconfig_v1.types.patch_jobs import ListPatchJobInstanceDetailsRequest
from google.cloud.osconfig_v1.types.patch_jobs import (
ListPatchJobInstanceDetailsResponse,
)
from google.cloud.osconfig_v1.types.patch_jobs import ListPatchJobsRequest
from google.cloud.osconfig_v1.types.patch_jobs import ListPatchJobsResponse
from google.cloud.osconfig_v1.types.patch_jobs import PatchConfig
from google.cloud.osconfig_v1.types.patch_jobs import PatchInstanceFilter
from google.cloud.osconfig_v1.types.patch_jobs import PatchJob
from google.cloud.osconfig_v1.types.patch_jobs import PatchJobInstanceDetails
from google.cloud.osconfig_v1.types.patch_jobs import WindowsUpdateSettings
from google.cloud.osconfig_v1.types.patch_jobs import YumSettings
from google.cloud.osconfig_v1.types.patch_jobs import ZypperSettings
__all__ = (
"AptSettings",
"CancelPatchJobRequest",
"CreatePatchDeploymentRequest",
"DeletePatchDeploymentRequest",
"ExecStep",
"ExecStepConfig",
"ExecutePatchJobRequest",
"GcsObject",
"GetPatchDeploymentRequest",
"GetPatchJobRequest",
"GooSettings",
"Instance",
"ListPatchDeploymentsRequest",
"ListPatchDeploymentsResponse",
"ListPatchJobInstanceDetailsRequest",
"ListPatchJobInstanceDetailsResponse",
"ListPatchJobsRequest",
"ListPatchJobsResponse",
"MonthlySchedule",
"OneTimeSchedule",
"OsConfigServiceAsyncClient",
"OsConfigServiceClient",
"PatchConfig",
"PatchDeployment",
"PatchInstanceFilter",
"PatchJob",
"PatchJobInstanceDetails",
"RecurringSchedule",
"WeekDayOfMonth",
"WeeklySchedule",
"WindowsUpdateSettings",
"YumSettings",
"ZypperSettings",
)
<file_sep># -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import proto # type: ignore
from google.protobuf import duration_pb2 as gp_duration # type: ignore
from google.protobuf import timestamp_pb2 as timestamp # type: ignore
__protobuf__ = proto.module(
package="google.cloud.osconfig.v1",
manifest={
"ExecutePatchJobRequest",
"GetPatchJobRequest",
"ListPatchJobInstanceDetailsRequest",
"ListPatchJobInstanceDetailsResponse",
"PatchJobInstanceDetails",
"ListPatchJobsRequest",
"ListPatchJobsResponse",
"PatchJob",
"PatchConfig",
"Instance",
"CancelPatchJobRequest",
"AptSettings",
"YumSettings",
"GooSettings",
"ZypperSettings",
"WindowsUpdateSettings",
"ExecStep",
"ExecStepConfig",
"GcsObject",
"PatchInstanceFilter",
},
)
class ExecutePatchJobRequest(proto.Message):
r"""A request message to initiate patching across Compute Engine
instances.
Attributes:
parent (str):
Required. The project in which to run this patch in the form
``projects/*``
description (str):
Description of the patch job. Length of the
description is limited to 1024 characters.
instance_filter (~.gco_patch_jobs.PatchInstanceFilter):
Required. Instances to patch, either
explicitly or filtered by some criteria such as
zone or labels.
patch_config (~.gco_patch_jobs.PatchConfig):
Patch configuration being applied. If
omitted, instances are patched using the default
configurations.
duration (~.gp_duration.Duration):
Duration of the patch job. After the duration
ends, the patch job times out.
dry_run (bool):
If this patch is a dry-run only, instances
are contacted but will do nothing.
display_name (str):
Display name for this patch job. This does
not have to be unique.
"""
parent = proto.Field(proto.STRING, number=1)
description = proto.Field(proto.STRING, number=2)
instance_filter = proto.Field(
proto.MESSAGE, number=7, message="PatchInstanceFilter"
)
patch_config = proto.Field(proto.MESSAGE, number=4, message="PatchConfig")
duration = proto.Field(proto.MESSAGE, number=5, message=gp_duration.Duration)
dry_run = proto.Field(proto.BOOL, number=6)
display_name = proto.Field(proto.STRING, number=8)
class GetPatchJobRequest(proto.Message):
r"""Request to get an active or completed patch job.
Attributes:
name (str):
Required. Name of the patch in the form
``projects/*/patchJobs/*``
"""
name = proto.Field(proto.STRING, number=1)
class ListPatchJobInstanceDetailsRequest(proto.Message):
r"""Request to list details for all instances that are part of a
patch job.
Attributes:
parent (str):
Required. The parent for the instances are in the form of
``projects/*/patchJobs/*``.
page_size (int):
The maximum number of instance details
records to return. Default is 100.
page_token (str):
A pagination token returned from a previous
call that indicates where this listing should
continue from.
filter (str):
A filter expression that filters results listed in the
response. This field supports filtering results by instance
zone, name, state, or ``failure_reason``.
"""
parent = proto.Field(proto.STRING, number=1)
page_size = proto.Field(proto.INT32, number=2)
page_token = proto.Field(proto.STRING, number=3)
filter = proto.Field(proto.STRING, number=4)
class ListPatchJobInstanceDetailsResponse(proto.Message):
r"""A response message for listing the instances details for a
patch job.
Attributes:
patch_job_instance_details (Sequence[~.gco_patch_jobs.PatchJobInstanceDetails]):
A list of instance status.
next_page_token (str):
A pagination token that can be used to get
the next page of results.
"""
@property
def raw_page(self):
return self
patch_job_instance_details = proto.RepeatedField(
proto.MESSAGE, number=1, message="PatchJobInstanceDetails"
)
next_page_token = proto.Field(proto.STRING, number=2)
class PatchJobInstanceDetails(proto.Message):
r"""Patch details for a VM instance. For more information about
reviewing VM instance details, see `Listing all VM instance details
for a specific patch
job <https://cloud.google.com/compute/docs/os-patch-management/manage-patch-jobs#list-instance-details>`__.
Attributes:
name (str):
The instance name in the form
``projects/*/zones/*/instances/*``
instance_system_id (str):
The unique identifier for the instance. This
identifier is defined by the server.
state (~.gco_patch_jobs.Instance.PatchState):
Current state of instance patch.
failure_reason (str):
If the patch fails, this field provides the
reason.
attempt_count (int):
The number of times the agent that the agent
attempts to apply the patch.
"""
name = proto.Field(proto.STRING, number=1)
instance_system_id = proto.Field(proto.STRING, number=2)
state = proto.Field(proto.ENUM, number=3, enum="Instance.PatchState")
failure_reason = proto.Field(proto.STRING, number=4)
attempt_count = proto.Field(proto.INT64, number=5)
class ListPatchJobsRequest(proto.Message):
r"""A request message for listing patch jobs.
Attributes:
parent (str):
Required. In the form of ``projects/*``
page_size (int):
The maximum number of instance status to
return.
page_token (str):
A pagination token returned from a previous
call that indicates where this listing should
continue from.
filter (str):
If provided, this field specifies the criteria that must be
met by patch jobs to be included in the response. Currently,
filtering is only available on the patch_deployment field.
"""
parent = proto.Field(proto.STRING, number=1)
page_size = proto.Field(proto.INT32, number=2)
page_token = proto.Field(proto.STRING, number=3)
filter = proto.Field(proto.STRING, number=4)
class ListPatchJobsResponse(proto.Message):
r"""A response message for listing patch jobs.
Attributes:
patch_jobs (Sequence[~.gco_patch_jobs.PatchJob]):
The list of patch jobs.
next_page_token (str):
A pagination token that can be used to get
the next page of results.
"""
@property
def raw_page(self):
return self
patch_jobs = proto.RepeatedField(proto.MESSAGE, number=1, message="PatchJob")
next_page_token = proto.Field(proto.STRING, number=2)
class PatchJob(proto.Message):
r"""A high level representation of a patch job that is either in
progress or has completed.
Instances details are not included in the job. To paginate through
instance details, use ListPatchJobInstanceDetails.
For more information about patch jobs, see `Creating patch
jobs <https://cloud.google.com/compute/docs/os-patch-management/create-patch-job>`__.
Attributes:
name (str):
Unique identifier for this patch job in the form
``projects/*/patchJobs/*``
display_name (str):
Display name for this patch job. This is not
a unique identifier.
description (str):
Description of the patch job. Length of the
description is limited to 1024 characters.
create_time (~.timestamp.Timestamp):
Time this patch job was created.
update_time (~.timestamp.Timestamp):
Last time this patch job was updated.
state (~.gco_patch_jobs.PatchJob.State):
The current state of the PatchJob .
instance_filter (~.gco_patch_jobs.PatchInstanceFilter):
Instances to patch.
patch_config (~.gco_patch_jobs.PatchConfig):
Patch configuration being applied.
duration (~.gp_duration.Duration):
Duration of the patch job. After the duration
ends, the patch job times out.
instance_details_summary (~.gco_patch_jobs.PatchJob.InstanceDetailsSummary):
Summary of instance details.
dry_run (bool):
If this patch job is a dry run, the agent
reports that it has finished without running any
updates on the VM instance.
error_message (str):
If this patch job failed, this message
provides information about the failure.
percent_complete (float):
Reflects the overall progress of the patch
job in the range of 0.0 being no progress to
100.0 being complete.
patch_deployment (str):
Output only. Name of the patch deployment
that created this patch job.
"""
class State(proto.Enum):
r"""Enumeration of the various states a patch job passes through
as it executes.
"""
STATE_UNSPECIFIED = 0
STARTED = 1
INSTANCE_LOOKUP = 2
PATCHING = 3
SUCCEEDED = 4
COMPLETED_WITH_ERRORS = 5
CANCELED = 6
TIMED_OUT = 7
class InstanceDetailsSummary(proto.Message):
r"""A summary of the current patch state across all instances that this
patch job affects. Contains counts of instances in different states.
These states map to ``InstancePatchState``. List patch job instance
details to see the specific states of each instance.
Attributes:
pending_instance_count (int):
Number of instances pending patch job.
inactive_instance_count (int):
Number of instances that are inactive.
notified_instance_count (int):
Number of instances notified about patch job.
started_instance_count (int):
Number of instances that have started.
downloading_patches_instance_count (int):
Number of instances that are downloading
patches.
applying_patches_instance_count (int):
Number of instances that are applying
patches.
rebooting_instance_count (int):
Number of instances rebooting.
succeeded_instance_count (int):
Number of instances that have completed
successfully.
succeeded_reboot_required_instance_count (int):
Number of instances that require reboot.
failed_instance_count (int):
Number of instances that failed.
acked_instance_count (int):
Number of instances that have acked and will
start shortly.
timed_out_instance_count (int):
Number of instances that exceeded the time
out while applying the patch.
pre_patch_step_instance_count (int):
Number of instances that are running the pre-
atch step.
post_patch_step_instance_count (int):
Number of instances that are running the
post-patch step.
no_agent_detected_instance_count (int):
Number of instances that do not appear to be
running the agent. Check to ensure that the
agent is installed, running, and able to
communicate with the service.
"""
pending_instance_count = proto.Field(proto.INT64, number=1)
inactive_instance_count = proto.Field(proto.INT64, number=2)
notified_instance_count = proto.Field(proto.INT64, number=3)
started_instance_count = proto.Field(proto.INT64, number=4)
downloading_patches_instance_count = proto.Field(proto.INT64, number=5)
applying_patches_instance_count = proto.Field(proto.INT64, number=6)
rebooting_instance_count = proto.Field(proto.INT64, number=7)
succeeded_instance_count = proto.Field(proto.INT64, number=8)
succeeded_reboot_required_instance_count = proto.Field(proto.INT64, number=9)
failed_instance_count = proto.Field(proto.INT64, number=10)
acked_instance_count = proto.Field(proto.INT64, number=11)
timed_out_instance_count = proto.Field(proto.INT64, number=12)
pre_patch_step_instance_count = proto.Field(proto.INT64, number=13)
post_patch_step_instance_count = proto.Field(proto.INT64, number=14)
no_agent_detected_instance_count = proto.Field(proto.INT64, number=15)
name = proto.Field(proto.STRING, number=1)
display_name = proto.Field(proto.STRING, number=14)
description = proto.Field(proto.STRING, number=2)
create_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp)
update_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp)
state = proto.Field(proto.ENUM, number=5, enum=State)
instance_filter = proto.Field(
proto.MESSAGE, number=13, message="PatchInstanceFilter"
)
patch_config = proto.Field(proto.MESSAGE, number=7, message="PatchConfig")
duration = proto.Field(proto.MESSAGE, number=8, message=gp_duration.Duration)
instance_details_summary = proto.Field(
proto.MESSAGE, number=9, message=InstanceDetailsSummary
)
dry_run = proto.Field(proto.BOOL, number=10)
error_message = proto.Field(proto.STRING, number=11)
percent_complete = proto.Field(proto.DOUBLE, number=12)
patch_deployment = proto.Field(proto.STRING, number=15)
class PatchConfig(proto.Message):
r"""Patch configuration specifications. Contains details on how
to apply the patch(es) to a VM instance.
Attributes:
reboot_config (~.gco_patch_jobs.PatchConfig.RebootConfig):
Post-patch reboot settings.
apt (~.gco_patch_jobs.AptSettings):
Apt update settings. Use this setting to override the
default ``apt`` patch rules.
yum (~.gco_patch_jobs.YumSettings):
Yum update settings. Use this setting to override the
default ``yum`` patch rules.
goo (~.gco_patch_jobs.GooSettings):
Goo update settings. Use this setting to override the
default ``goo`` patch rules.
zypper (~.gco_patch_jobs.ZypperSettings):
Zypper update settings. Use this setting to override the
default ``zypper`` patch rules.
windows_update (~.gco_patch_jobs.WindowsUpdateSettings):
Windows update settings. Use this override
the default windows patch rules.
pre_step (~.gco_patch_jobs.ExecStep):
The ``ExecStep`` to run before the patch update.
post_step (~.gco_patch_jobs.ExecStep):
The ``ExecStep`` to run after the patch update.
"""
class RebootConfig(proto.Enum):
r"""Post-patch reboot settings."""
REBOOT_CONFIG_UNSPECIFIED = 0
DEFAULT = 1
ALWAYS = 2
NEVER = 3
reboot_config = proto.Field(proto.ENUM, number=1, enum=RebootConfig)
apt = proto.Field(proto.MESSAGE, number=3, message="AptSettings")
yum = proto.Field(proto.MESSAGE, number=4, message="YumSettings")
goo = proto.Field(proto.MESSAGE, number=5, message="GooSettings")
zypper = proto.Field(proto.MESSAGE, number=6, message="ZypperSettings")
windows_update = proto.Field(
proto.MESSAGE, number=7, message="WindowsUpdateSettings"
)
pre_step = proto.Field(proto.MESSAGE, number=8, message="ExecStep")
post_step = proto.Field(proto.MESSAGE, number=9, message="ExecStep")
class Instance(proto.Message):
r"""Namespace for instance state enums."""
class PatchState(proto.Enum):
r"""Patch state of an instance."""
PATCH_STATE_UNSPECIFIED = 0
PENDING = 1
INACTIVE = 2
NOTIFIED = 3
STARTED = 4
DOWNLOADING_PATCHES = 5
APPLYING_PATCHES = 6
REBOOTING = 7
SUCCEEDED = 8
SUCCEEDED_REBOOT_REQUIRED = 9
FAILED = 10
ACKED = 11
TIMED_OUT = 12
RUNNING_PRE_PATCH_STEP = 13
RUNNING_POST_PATCH_STEP = 14
NO_AGENT_DETECTED = 15
class CancelPatchJobRequest(proto.Message):
r"""Message for canceling a patch job.
Attributes:
name (str):
Required. Name of the patch in the form
``projects/*/patchJobs/*``
"""
name = proto.Field(proto.STRING, number=1)
class AptSettings(proto.Message):
r"""Apt patching is completed by executing
``apt-get update && apt-get upgrade``. Additional options can be set
to control how this is executed.
Attributes:
type (~.gco_patch_jobs.AptSettings.Type):
By changing the type to DIST, the patching is performed
using ``apt-get dist-upgrade`` instead.
excludes (Sequence[str]):
List of packages to exclude from update.
These packages will be excluded
exclusive_packages (Sequence[str]):
An exclusive list of packages to be updated.
These are the only packages that will be
updated. If these packages are not installed,
they will be ignored. This field cannot be
specified with any other patch configuration
fields.
"""
class Type(proto.Enum):
r"""Apt patch type."""
TYPE_UNSPECIFIED = 0
DIST = 1
UPGRADE = 2
type = proto.Field(proto.ENUM, number=1, enum=Type)
excludes = proto.RepeatedField(proto.STRING, number=2)
exclusive_packages = proto.RepeatedField(proto.STRING, number=3)
class YumSettings(proto.Message):
r"""Yum patching is performed by executing ``yum update``. Additional
options can be set to control how this is executed.
Note that not all settings are supported on all platforms.
Attributes:
security (bool):
Adds the ``--security`` flag to ``yum update``. Not
supported on all platforms.
minimal (bool):
Will cause patch to run ``yum update-minimal`` instead.
excludes (Sequence[str]):
List of packages to exclude from update. These packages are
excluded by using the yum ``--exclude`` flag.
exclusive_packages (Sequence[str]):
An exclusive list of packages to be updated.
These are the only packages that will be
updated. If these packages are not installed,
they will be ignored. This field must not be
specified with any other patch configuration
fields.
"""
security = proto.Field(proto.BOOL, number=1)
minimal = proto.Field(proto.BOOL, number=2)
excludes = proto.RepeatedField(proto.STRING, number=3)
exclusive_packages = proto.RepeatedField(proto.STRING, number=4)
class GooSettings(proto.Message):
r"""Googet patching is performed by running ``googet update``."""
class ZypperSettings(proto.Message):
r"""Zypper patching is performed by running ``zypper patch``. See also
https://en.opensuse.org/SDB:Zypper_manual.
Attributes:
with_optional (bool):
Adds the ``--with-optional`` flag to ``zypper patch``.
with_update (bool):
Adds the ``--with-update`` flag, to ``zypper patch``.
categories (Sequence[str]):
Install only patches with these categories.
Common categories include security, recommended,
and feature.
severities (Sequence[str]):
Install only patches with these severities.
Common severities include critical, important,
moderate, and low.
excludes (Sequence[str]):
List of patches to exclude from update.
exclusive_patches (Sequence[str]):
An exclusive list of patches to be updated. These are the
only patches that will be installed using 'zypper patch
patch:<patch_name>' command. This field must not be used
with any other patch configuration fields.
"""
with_optional = proto.Field(proto.BOOL, number=1)
with_update = proto.Field(proto.BOOL, number=2)
categories = proto.RepeatedField(proto.STRING, number=3)
severities = proto.RepeatedField(proto.STRING, number=4)
excludes = proto.RepeatedField(proto.STRING, number=5)
exclusive_patches = proto.RepeatedField(proto.STRING, number=6)
class WindowsUpdateSettings(proto.Message):
r"""Windows patching is performed using the Windows Update Agent.
Attributes:
classifications (Sequence[~.gco_patch_jobs.WindowsUpdateSettings.Classification]):
Only apply updates of these windows update
classifications. If empty, all updates are
applied.
excludes (Sequence[str]):
List of KBs to exclude from update.
exclusive_patches (Sequence[str]):
An exclusive list of kbs to be updated. These
are the only patches that will be updated. This
field must not be used with other patch
configurations.
"""
class Classification(proto.Enum):
r"""Microsoft Windows update classifications as defined in [1]
https://support.microsoft.com/en-us/help/824684/description-of-the-standard-terminology-that-is-used-to-describe-micro
"""
CLASSIFICATION_UNSPECIFIED = 0
CRITICAL = 1
SECURITY = 2
DEFINITION = 3
DRIVER = 4
FEATURE_PACK = 5
SERVICE_PACK = 6
TOOL = 7
UPDATE_ROLLUP = 8
UPDATE = 9
classifications = proto.RepeatedField(proto.ENUM, number=1, enum=Classification)
excludes = proto.RepeatedField(proto.STRING, number=2)
exclusive_patches = proto.RepeatedField(proto.STRING, number=3)
class ExecStep(proto.Message):
r"""A step that runs an executable for a PatchJob.
Attributes:
linux_exec_step_config (~.gco_patch_jobs.ExecStepConfig):
The ExecStepConfig for all Linux VMs targeted
by the PatchJob.
windows_exec_step_config (~.gco_patch_jobs.ExecStepConfig):
The ExecStepConfig for all Windows VMs
targeted by the PatchJob.
"""
linux_exec_step_config = proto.Field(
proto.MESSAGE, number=1, message="ExecStepConfig"
)
windows_exec_step_config = proto.Field(
proto.MESSAGE, number=2, message="ExecStepConfig"
)
class ExecStepConfig(proto.Message):
r"""Common configurations for an ExecStep.
Attributes:
local_path (str):
An absolute path to the executable on the VM.
gcs_object (~.gco_patch_jobs.GcsObject):
A Cloud Storage object containing the
executable.
allowed_success_codes (Sequence[int]):
Defaults to [0]. A list of possible return values that the
execution can return to indicate a success.
interpreter (~.gco_patch_jobs.ExecStepConfig.Interpreter):
The script interpreter to use to run the script. If no
interpreter is specified the script will be executed
directly, which will likely only succeed for scripts with
[shebang lines]
(https://en.wikipedia.org/wiki/Shebang_(Unix)).
"""
class Interpreter(proto.Enum):
r"""The interpreter used to execute the a file."""
INTERPRETER_UNSPECIFIED = 0
SHELL = 1
POWERSHELL = 2
local_path = proto.Field(proto.STRING, number=1)
gcs_object = proto.Field(proto.MESSAGE, number=2, message="GcsObject")
allowed_success_codes = proto.RepeatedField(proto.INT32, number=3)
interpreter = proto.Field(proto.ENUM, number=4, enum=Interpreter)
class GcsObject(proto.Message):
r"""Cloud Storage object representation.
Attributes:
bucket (str):
Required. Bucket of the Cloud Storage object.
object (str):
Required. Name of the Cloud Storage object.
generation_number (int):
Required. Generation number of the Cloud
Storage object. This is used to ensure that the
ExecStep specified by this PatchJob does not
change.
"""
bucket = proto.Field(proto.STRING, number=1)
object = proto.Field(proto.STRING, number=2)
generation_number = proto.Field(proto.INT64, number=3)
class PatchInstanceFilter(proto.Message):
r"""A filter to target VM instances for patching. The targeted
VMs must meet all criteria specified. So if both labels and
zones are specified, the patch job targets only VMs with those
labels and in those zones.
Attributes:
all (bool):
Target all VM instances in the project. If
true, no other criteria is permitted.
group_labels (Sequence[~.gco_patch_jobs.PatchInstanceFilter.GroupLabel]):
Targets VM instances matching ANY of these
GroupLabels. This allows targeting of disparate
groups of VM instances.
zones (Sequence[str]):
Targets VM instances in ANY of these zones.
Leave empty to target VM instances in any zone.
instances (Sequence[str]):
Targets any of the VM instances specified. Instances are
specified by their URI in the form
``zones/[ZONE]/instances/[INSTANCE_NAME],``\ projects/[PROJECT_ID]/zones/[ZONE]/instances/[INSTANCE_NAME]\ ``, or``\ https://www.googleapis.com/compute/v1/projects/[PROJECT_ID]/zones/[ZONE]/instances/[INSTANCE_NAME]\`
instance_name_prefixes (Sequence[str]):
Targets VMs whose name starts with one of
these prefixes. Similar to labels, this is
another way to group VMs when targeting configs,
for example prefix="prod-".
"""
class GroupLabel(proto.Message):
r"""Targets a group of VM instances by using their `assigned
labels <https://cloud.google.com/compute/docs/labeling-resources>`__.
Labels are key-value pairs. A ``GroupLabel`` is a combination of
labels that is used to target VMs for a patch job.
For example, a patch job can target VMs that have the following
``GroupLabel``: ``{"env":"test", "app":"web"}``. This means that the
patch job is applied to VMs that have both the labels ``env=test``
and ``app=web``.
Attributes:
labels (Sequence[~.gco_patch_jobs.PatchInstanceFilter.GroupLabel.LabelsEntry]):
Compute Engine instance labels that must be
present for a VM instance to be targeted by this
filter.
"""
labels = proto.MapField(proto.STRING, proto.STRING, number=1)
all = proto.Field(proto.BOOL, number=1)
group_labels = proto.RepeatedField(proto.MESSAGE, number=2, message=GroupLabel)
zones = proto.RepeatedField(proto.STRING, number=3)
instances = proto.RepeatedField(proto.STRING, number=4)
instance_name_prefixes = proto.RepeatedField(proto.STRING, number=5)
__all__ = tuple(sorted(__protobuf__.manifest))
| 6292b4c461667bce1154c5fe9868ef3860344194 | [
"Markdown",
"Python",
"reStructuredText"
] | 8 | reStructuredText | wj-chen/python-os-config | 33f46ba4aa34e066a70a5ad792254574b5985f83 | dba07ef29712df9b537633f42865a7c4cb539939 |
refs/heads/master | <file_sep>#!/bin/bash
IFS=$'\n'
basedir="$HOME/.local/share/Steam"
case "$1" in
"-d"|"--directory") basedir="$2"; shift 2;;
"-h"|"--help") echo 'Usage: steamMove.sh [OPTIONS] [src num] [dest num]
-d --directory Set the base directory
-h --help This help text'|column -ts ' '; exit;;
esac
dirs="$basedir
$(grep -oP "[ ]\"[0-9]+\"[^\"]*\"\K[^\"]*" "$basedir/steamapps/libraryfolders.vdf" | sed 's/\\\\/\//g;s/Z://')"
echo "Detected Libraries:
$(nl -nln <<< "$dirs")"
case $1 in
'')
read -p "Select a source library:
> " srcLibraryNum
srcLibrary=$( sed "${srcLibraryNum}q;d" <<< "$dirs")
;;
*[!0-9]*)
srcLibrary="$1"
;;
*)
srcLibraryNum=$1
srcLibrary=$( sed "${srcLibraryNum}q;d" <<< "$dirs")
;;
esac
case $2 in
'')
read -p "Select a destination library:
> " destLibraryNum
destLibrary=$( sed "${destLibraryNum}q;d" <<< "$dirs")
;;
*[!0-9]*)
destLibrary="$2"
;;
*)
destLibraryNum=$2
destLibrary=$( sed "${destLibraryNum}q;d" <<< "$dirs")
;;
esac
echo "
Source Library: $srcLibrary
Dest Library: $destLibrary
"
if [ "$srcLibraryNum" = "$destLibraryNum" ];then echo "Source and destination are the same!";exit;fi
if [ -z "$srcLibrary" -o ! -d "$srcLibrary" ];then echo "Source library $srcLibrary is not availible or is null";exit;fi
if [ -z "$destLibrary" -o ! -d "$destLibrary" ];then echo "Destination library $destLibrary is not availible or is null";exit;fi
gameNum=1
echo "Games in $srcLibrary:"
games="$(for jj in "$srcLibrary"/steamapps/appmanifest_*
do
echo -n "$gameNum "
grep -m1 -oP 'name"[ ]*"\K[^"]*' "$jj" |tr -d '\n'
echo -n " "
grep -oP 'installdir"[ ]*"\K[^"]*' "$jj" |tr -d '\n'
echo " $jj"
gameNum=$(($gameNum+1))
done)"
echo
echo "$(tput bold)Num Game Directory
$(tput sgr0)$(awk -F " " '{print $1,"\t",$2,"\t",$3}' <<< "$games")" |column -ts ' '
read -p "Enter the number(s) or part of the name of a game to move:
> " input
case $input in #Still rather ugly
*[!0-9\ ]*) input="$(awk "/$input/ {print FNR}" <<< "$games")" && echo "Interpreting as search, $( [ -n "$input" ] && wc -l <<<"$input" || echo -n 0) matches";;&
*[\ ]*) input="$(tr ' ' '\n' <<< "$input")" ;;
*) ;;
esac
for ii in $input
do
echo "Moving \"$(awk -F " " "NR==$ii {print \$2}" <<< "$games")\""
read -p "Move, copy or skip? [m/c/*]: " option
case $option in
M|m)
echo " Directory \"$(awk -F " " "NR==$ii {print \$3}" <<< "$games")\""
rsync -rP "$srcLibrary"/steamapps/common/"$(awk -F " " "NR==$ii {print \$3}" <<< "$games")" "$destLibrary"/steamapps/common
rm -rf "$srcLibrary"/steamapps/common/"$(awk -F " " "NR==$ii {print \$3}" <<< "$games")"
echo " Manifest \"$(awk -F " " "NR==$ii {print \$4}" <<< "$games")\""
mv "$(awk -F " " "NR==$ii {print \$4}" <<< "$games")" "$destLibrary"/steamapps
;;
C|c)
echo " Directory \"$(awk -F " " "NR==$ii {print \$3}" <<< "$games")\""
rsync -rP "$srcLibrary"/steamapps/common/"$(awk -F " " "NR==$ii {print \$3}" <<< "$games")" "$destLibrary"/steamapps/common
echo " Manifest \"$(awk -F " " "NR==$ii {print \$4}" <<< "$games")\""
cp "$(awk -F " " "NR==$ii {print \$4}" <<< "$games")" "$destLibrary"/steamapps
;;
esac
done
<file_sep>#!/bin/bash
interfaces=$(echo "$@" | sed 's/ /\\|/g')
ip=$(ip -4 -o a | grep "$interfaces" | sed 's/^[0-9]*: \([^ ]*\) inet \([0-9.]*\).*/\1:\2/g' | grep -v lo | tr '\n' ' ')
GPing=$(ping -c1 -W1 8.8.8.8 | (grep "bytes from" || echo "<span fgcolor=\"red\">G:Down</span>") | sed 's/.*time=\([0-9\.]*\).*/G:\1ms/')
echo -n "<txt>${ip}$GPing</txt>"
<file_sep>#!/bin/bash
echo -n "WS|"
if [ $# -ne 0 ];then
i3-msg -t get_workspaces | grep -oP '{.*?"output".*?}' | grep $1 | grep -oP '(name":"\K[^"]*)|("visible":true,"focused":[^,]*)' | tr '\n' '|' | sed 's/|"visible":true,"focused":true/★/g;s/|"visible":true,"focused":false/⚫/g'|tr '\n' '|'
else
i3-msg -t get_workspaces | grep -oP '{.*?"output".*?}' | grep -oP '(name":"\K[^"]*)|("visible":true,"focused":[^,]*)' | tr '\n' '|' | sed 's/|"visible":true,"focused":true/★/g;s/|"visible":true,"focused":false/⚫/g'|tr '\n' '|'
fi
<file_sep>#!/usr/bin/python2
import sensors
import subprocess
from glob import glob
import re
sensorsToShow = {'Physical id 0': ["C", 70,100],
'Left side ' : ["RPM", 3000,5000]}
cpuGovernors = { "powersave" : '<span fgcolor="green">s</span>',
"performance": '<span fgcolor="red">p</span>',
"ondemand": '<span fgcolor="yellow">o</span>'}
out = ""
cpuGovernor = ""
sensors.init()
try:
for chip in sensors.iter_detected_chips():
for feature in chip:
if feature.label in sensorsToShow:
color = ("#00B000" if feature.get_value() < sensorsToShow[feature.label][1]
else ("yellow" if feature.get_value() < sensorsToShow[feature.label][2]
else "red"))
out += '<span fgcolor="%s">%.f%s</span> ' % (color, feature.get_value(), sensorsToShow[feature.label][0])
CPUFreq = 0
for line in open("/proc/cpuinfo"):
if "cpu MHz" in line:
speed = float(line.replace("cpu MHz : ", "").replace("\n", ""))
CPUFreq = max(speed, CPUFreq)
print CPUFreq
out += '<span>%.2fGHz</span>' % (CPUFreq/1000)
out += " "
for i in glob("/sys/devices/system/cpu/cpu[0-9]/cpufreq/scaling_governor"):
out += cpuGovernors[open(i).read().replace("\n", "")]
print "<txt>" + out + "</txt>"
finally:
sensors.cleanup()
<file_sep>#!/bin/bash
function getKey(){
grep -o -P "\"$2\": ?\"\K[^\"]*" <<< $1|sed 's/"//g'
}
function printComics(){
IFS=$'\n'
titleNum=1
echo "Enter a selection:"
for i in $(sed 's/},{"viewport/\nviewport/g' index.html)
do
echo "$titleNum. $(getKey "$i" "title")"
((titleNum++))
done
echo -n ">"
}
function getComic(){
echo "Getting $title"
IFS=$'\n'
currentIndex=$(sed 's/},{"viewport/\nviewport/g' index.html|sed "$1q;d")
title=$(getKey "$currentIndex" "title")
mkdir -p temp/$title
cd temp/$title
uuid=$(getKey $currentIndex "book_uuid");
echo "Getting book.tar"
wget -c --load-cookies "$cookieFile" "https://digital.darkhorse.com/api/v5/book/$uuid" -O book.tar --progress=bar:force 2>&1 | tail -f -n +10
tar xf book.tar||exit
echo "sorting images"
x=0
for image in $(grep -oP 'src_image": "\K[^"]*' manifest.json)
do
mv $image $(printf "%03d" $x).jpg
x=$(($x+1))
done
echo "Making cbz"
zip ../../comics/$title.cbz *.jpg manifest.json>/dev/null
rm book.tar
cd ../..
}
while getopts ":o:c:g:" opt; do
case $opt in
o)
dir=$OPTARG
;;
c)
cookieFile=$(readlink -f $OPTARG)
;;
g)
input=$(eval echo $OPTARG)
;;
\?)
echo -e "Invalid option: -$OPTARG\nUsage: @$ -o outputDir [-c cookies.txt] [-g \"number of comic(s)\"]" >&2
exit 1
;;
:)
echo "Option -$OPTARG requires an argument" >&2
exit 1
;;
esac
done
if [ -z "$dir" ]; then echo "Please specify a directory with -o";exit 1;fi
if [ -z "$cookieFile" -a -e ~/cookies.txt ]; then
cookieFile=~/cookies.txt;echo "Note: No cookie.txt specified, using $HOME/cookies.txt"
else
echo "No cookie file specified, and $HOME/cookies.txt does not exist";exit 1
fi
if [ ! -e "$dir/comics" ]; then mkdir -p $dir/comics;fi
cd $dir
wget --load-cookies "$cookieFile" 'https://digital.darkhorse.com/api/v/books/' -O index.html --progress=bar:force 2>&1 | tail -f -n +6||(echo "Error downloading, check network and presence of cookies.txt in working directory and try again.";exit 1)
if [ -z "$input" ]; then
printComics
input=$(read input;eval echo $input)
fi
IFS=' '
for i in $input; do getComic $i;done
<file_sep>#!/bin/bash
IFS=$'\n'
rows=$(cat $1|tr '\n' '~' | grep -zoP "<div class=\"row.*?/div>(?=<div class=\"row)")
DLType="bt" #bt or web
#shortnames=$(grep -oP "class=\"row \K[^\"]*" <<< "$rows")
#names=$(grep -oP "class=\"row $i\" data-human-name=\"\K[^\"]*" <<< "$rows")
#links=$(grep -oP "data-$DLType=\"\K[^\"]*" <<< "$rows" |sed 's/\&/\&/g')
#filenames=$(grep -oP "[^:]*/\K[^?]*" <<< $links |sed 's/ /\n/g')
for i in $rows; do
echo "Getting $(grep -oP "data-human-name=\"\K[^\"]*" <<< $i)"
type=$(grep -oP 'js-platform downloads \K[^"]*' <<< $i)
echo $type
for x in $(grep -oP '<div class="js-platform.*?</div>.*?(?=<div class="js-platform|$)' <<< $i|grep \<a); do
for z in $(grep -oP '<div class="download("| ).*? </div>' <<< "$x");do
link=$(grep -oP "data-$DLType=\"\K[^\"]*" <<< "$z"|sed 's/\&/\&/g')
filename=$(grep -oP "[^:]*/\K[^?]*" <<< $link |sed 's/ /\n/g')
md5=$(grep -oP 'data-md5="\K[^"]*' <<< "$z")
#echo $filename
done
done
done
<file_sep>## DarkHorseSaver.sh ##
Uses a cookie file to get comics from Dark Horse Digital
## i3_workspace.sh ##
Prints the workspaces in i3, adding a star next to active ones, for use with mate-panel (or similar)
## netstatus.sh ##
Prints IP address of a given interface, or all interfaces if none is given. Also pings Google's DNS server (8.8.8.8).
## HumbleBundleSaver.sh ##
An incomplete script that parses the download page of a Humble Bundle and downloads all the files. It will also check whether the file already exists/is correct before it does this.
| 32e7cd02a8d005cc369acd4553246385d5df61d1 | [
"Markdown",
"Python",
"Shell"
] | 7 | Shell | ad1217/usefulScripts | 0a28fe6d07bcdad889238b5570d9dddd2263cc93 | a15856ad99a0975df3f234ab635ac1e25106faa2 |
refs/heads/master | <repo_name>tuxiangxue007/Games<file_sep>/TD_PingPongBalls/TD_PingPongBalls/Classes/Scene/TD_GameScene.swift
//
// TD_GameScene.swift
// TD_Decathlon
//
// Created by mac on 2018/7/9.
// Copyright © 2018年 DAA. All rights reserved.
//
import SpriteKit
class TD_GameScene: TD_BaseScene ,SKSceneDelegate,SKPhysicsContactDelegate{
var allSceneRecordData = [String:NSDictionary]() //关卡通关记录数据
var ballsSprite = SKSpriteNode()
override func didMove(to view: SKView) {
backgroundColor = UIColor.white
// setPhysicsBody();
// createBalls();
let ball = SKSpriteNode(color: UIColor.red, size: CGSize(width: 20, height: 20))
ball.position = CGPoint(x: 100, y: 100)
addChild(ball)
let sp = SKSpriteNode(color: UIColor.red, size: CGSize(width: 80, height: 80))
sp.zPosition = 100
// sp.superScene = self
// sp.tag = 1000 + i
sp.name = "selectScenario"
// sp.data = data as! [String : Any]
sp.position = CGPoint(x: 100, y: 300)
addChild(sp)
}
func setPhysicsBody(){
physicsWorld.gravity = CGVector.init(dx: 0, dy: 0)//重力
physicsWorld.contactDelegate = self
physicsWorld.speed = 1
physicsBody = SKPhysicsBody.init(edgeLoopFrom: self.frame)//物理世界的边界
// physicsBody?.contactTestBitMask = TD_ProtagonistCategory | TD_MonsterCategory //产生碰撞的物理类型
physicsBody?.categoryBitMask = TD_WorldCategory //标记自身的物理类型
physicsBody?.friction = 0 //阻力 为零时完全反弹
}
func createBalls(){
ballsSprite = TD_BallsSprite(color: UIColor.white, size: CGSize(width: 20, height: 20))
addChild(ballsSprite)
(ballsSprite as! TD_BallsSprite).layout(ballsType:"1")
let ball = SKSpriteNode(color: UIColor.red, size: CGSize(width: 20, height: 20))
ball.position = CGPoint(x: 100, y: 100)
addChild(ball)
}
}
<file_sep>/TD_AncientRuins/TD_AncientRuins/Classes/Scene/TD_BaseScene.swift
//
// TD_BaseScene.swift
// TD_WaterMargin
//
// Created by mac on 2018/9/13.
// Copyright © 2018年 DAA. All rights reserved.
//
import SpriteKit
class TD_BaseScene: SKScene {
var viewController = UIViewController()
}
<file_sep>/TD_ Journey/TD_ Journey/Classes/Scene/TD_GameScene.swift
//
// TD_GameScene.swift
// TD_Decathlon
//
// Created by mac on 2018/7/9.
// Copyright © 2018年 DAA. All rights reserved.
//
import SpriteKit
class TD_GameScene: TD_BaseScene ,SKSceneDelegate{
var allSceneData = [String:Any]() //场景布局原始数据
var mapData = [Any]() //记录场景布局转化数据
var scenarioIndex = 1 //当前关卡
override func didMove(to view: SKView) {
allSceneData = TD_AnalyticalDataObject().getFileData(fileName: "Scene") as! [String : NSDictionary]
backgroundColor = UIColor.blue
refreshView();
}
func refreshView() {
removeAllChildren()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// let touch = ((touches as NSSet).anyObject() as AnyObject) //进行类 型转化
// let point = touch.location(in:self)
// let node = self.atPoint(point)
//
// if (node.name != nil) {
// if (node.name == "selectScenario") {//判断是关卡选择按钮
// (viewController as! GameViewController).showScenarioScene(index: (node as! TD_SelectScenarioSprite).tag - 1000 + 1)
// }
// }else{
// }
}
}
<file_sep>/TD_PingPongBalls/TD_PingPongBalls/Classes/Sprite/TD_BallsSprite.swift
//
// TD_MonsterSprite.swift
// TD_WaterMargin
//
// Created by mac on 2018/9/13.
// Copyright © 2018年 DAA. All rights reserved.
//
import SpriteKit
class TD_BallsSprite: TD_BaseSpriteNode {
var monsterType = "1" //怪物种类
func layout(ballsType:String){
initPhysicsBody()
initObject()
}
func initObject(){
self.position = CGPoint(x: 100, y: 200)
let impulse = CGVector(dx: 0, dy: -1)//跳跃
self.physicsBody?.applyImpulse(impulse)
self.physicsBody?.affectedByGravity = true
}
/// 初始化物理属性
func initPhysicsBody(){
physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: size.width / 2.0, height: size.height / 2.0))
// physicsBody?.
// physicsBody?.density = 1 //密度
physicsBody?.mass = 1 //质量
physicsBody?.restitution = 0 //弹性
physicsBody?.friction = 0.0 //摩擦力
physicsBody?.linearDamping = 0 //线性阻力(空气阻力)
physicsBody?.allowsRotation = true
physicsBody?.affectedByGravity = false
physicsBody?.contactTestBitMask = TD_TowerAttackCategory //碰撞检测
physicsBody?.collisionBitMask = 0 //碰撞效果
physicsBody?.categoryBitMask = TD_MonsterCategory
}
}
<file_sep>/TD_PingPongBalls/TD_PingPongBalls/Classes/Lib/TD_AnalyticalDataObject.swift
//
// TD_AnalyticalDataObject.swift
// TD_AttackAndDefence
//
// Created by mac on 2018/8/13.
// Copyright © 2018年 DAA. All rights reserved.
//
import UIKit
class TD_AnalyticalDataObject: NSObject {
var dFilePath = NSHomeDirectory() + "/Library/Caches/"
func getFileData(fileName:String) -> NSDictionary {
var dict = NSDictionary()
let filePath = Bundle.main.path(forResource: fileName, ofType: "plist")
dict = NSDictionary(contentsOfFile: filePath!)!
return dict;
let ud = UserDefaults()
let fileCache = ud.value(forKey: "fileCache")
var fileData = NSMutableDictionary()
if fileCache != nil{
fileData = NSMutableDictionary(dictionary: fileCache as! NSDictionary )
}
let path = dFilePath + fileName
if fileData.value(forKey: fileName) != nil{
dict = NSDictionary.init(contentsOfFile: path)!
}else{
let filePath = Bundle.main.path(forResource: fileName, ofType: "plist")
dict = NSDictionary(contentsOfFile: filePath!)!
NSDictionary(dictionary: dict).write(toFile: path, atomically: true)
fileData.setValue("1", forKey: fileName)
ud.set(fileData, forKey: "fileCache")
}
return dict
}
func saveFileData(fileName:String,data:NSDictionary) {
let path = dFilePath + fileName
NSDictionary(dictionary: data).write(toFile: path, atomically: true)
}
func editRecord(scenarioIndex:Int,starIndex:Int){
let fileName = "SceneRecord"
var dict = NSMutableDictionary()
let ud = UserDefaults()
let fileCache = ud.value(forKey: "fileCache")
var fileData = NSMutableDictionary()
if fileCache != nil{
fileData = NSMutableDictionary(dictionary: fileCache as! NSDictionary )
}
let path = dFilePath + fileName
if fileData.value(forKey: fileName) != nil{
dict = NSMutableDictionary.init(contentsOfFile: path)!
dict.setValue(["isOpen":true,"star":String(starIndex)], forKey: String(format: "Scene_%d", scenarioIndex))
if scenarioIndex < TD_MAX_Scenario{
let d = dict[String(format: "Scene_%d", scenarioIndex + 1)] as! NSMutableDictionary
d["isOpen"] = true
dict.setValue(d, forKey: String(format: "Scene_%d", scenarioIndex + 1))
}
NSDictionary(dictionary: dict).write(toFile: path, atomically: true)
}
}
}
<file_sep>/TD_WaterMargin/TD_WaterMargin/Classes/Scene/TD_ScenarioScene.swift
//
// TD_ScenarioScene.swift
// TD_WaterMargin
//
// Created by mac on 2018/9/13.
// Copyright © 2018年 DAA. All rights reserved.
//
import SpriteKit
import UIKit
class TD_ScenarioScene: TD_BaseScene ,SKPhysicsContactDelegate {
var timer = Timer()
var allSceneData = [String:Any]() //场景布局以及怪物信息数据
var towersData = [String:Any]() //防御塔数据
var scenarioIndex = 0 //当前关卡
var mapData = [Any]() //记录场景布局信息
var monsterData = [String]() //记录关卡出怪顺序以及信息
var startPointList = [CGPoint]() //出怪点数组
var endPointList = [CGPoint]() //怪物目的地数组
var startPoint = CGPoint(); //出怪点
var endPoint = CGPoint(); //怪物目的地
var selClearBlockSprite = SKSpriteNode() //用于标记被选中的空地
var selClearBlock = SKNode()
var towersMenuView = SKSpriteNode()
var isBeingBuilt = false
var selTowerSprite = TD_TowerSprite() //记录正在建造的防御塔
var towersList = [TD_TowerSprite]() //记录防御塔数组
var monsterSpriteList = [TD_MonsterSprite]() //记录场上怪物的数组
var countdown = 10 //出怪倒计时
var countdownLab = SKLabelNode() //出怪倒计时显示控件
var HP = 0.0 //关卡当前血量
var maxHP = 0.0 //关卡最大血量
var hpLab = SKLabelNode() //关卡血量显示控件
var energy = 100.0 //剩余能量
var energyLab = SKLabelNode() //剩余能量显示控件
override func didMove(to view: SKView) {
self.backgroundColor = UIColor.white
allSceneData = TD_AnalyticalDataObject().getFileData(fileName: "Scene") as! [String : NSDictionary]
towersData = TD_AnalyticalDataObject().getFileData(fileName: "TowerList") as! [String : NSDictionary]
creatScene();
}
func goToTheNextLevel(){
}
func refresh() {
for node in children {
node.removeFromParent()
}
countdown = 10
creatScene()
}
func creatScene() {
let data = allSceneData[String(format: "Scene_%d", scenarioIndex)] as! NSDictionary
HP = Double(data["HP"] as! String)!
maxHP = HP
energy = Double(data["Energy"] as! String)!
let sceneData = data["scene"] as! NSArray
monsterData = data["monster"] as! [String]
for i in 0..<sceneData.count {
let lineData = NSMutableArray()
var lineStr = sceneData[i] as! String
let maxNum = lineStr.count
for j in 0..<maxNum {
let blocktype = lineStr.first
lineStr.removeFirst()
var blockSprite = SKSpriteNode()
let position = CGPoint(x: TD_Block_Width / 2.0 + 10 + TD_Block_Width * CGFloat(j), y: TD_Block_Width / 2.0 + TD_Game_TopClearance + TD_Block_Width * CGFloat(i))
lineData.add(blocktype as Any)
switch blocktype {
case "0"://道路
blockSprite = SKSpriteNode(color: UIColor.white, size: CGSize(width: TD_Block_Width, height: TD_Block_Width))
break
case "1"://空地
blockSprite = SKSpriteNode(color: UIColor.lightGray, size: CGSize(width: TD_Block_Width, height: TD_Block_Width))
blockSprite.name = TD_Name_Clearing
break
case "2":
break
case "3":
break
case "4":
break
case "Y":
blockSprite = SKSpriteNode(color: UIColor.green, size: CGSize(width: TD_Block_Width, height: TD_Block_Width))
startPointList.append(position)
break
case "Z":
blockSprite = SKSpriteNode(color: UIColor.red, size: CGSize(width: TD_Block_Width, height: TD_Block_Width))
endPointList.append(position)
break
default:
blockSprite = SKSpriteNode(color: UIColor.lightGray, size: CGSize(width: TD_Block_Width, height: TD_Block_Width))
break
}
blockSprite.position = position
addChild(blockSprite)
}
mapData.append(lineData)
}
selClearBlockSprite = SKSpriteNode(color: UIColor.green, size: CGSize(width: TD_Block_Width, height: TD_Block_Width))
selClearBlockSprite.isHidden = true
addChild(selClearBlockSprite)
startPoint = startPointList.first!
endPoint = endPointList.first!
startCreatMonsterSprite()
setPhysicsBody() //设置物理世界
countdownLab = SKLabelNode(text: String(countdown))
countdownLab.name = TD_Name_CountdownLab
countdownLab.position = CGPoint(x: 50, y: TD_ScreenH - 80)
countdownLab.fontColor = UIColor.blue
addChild(countdownLab)
hpLab = SKLabelNode(text: String(HP))
hpLab.name = TD_Name_HPLab
hpLab.position = CGPoint(x: TD_ScreenW - 80, y: TD_ScreenH - 80)
hpLab.fontColor = UIColor.red
addChild(hpLab)
energyLab = SKLabelNode(text: String(HP))
energyLab.name = TD_Name_EnergyLab
energyLab.position = CGPoint(x: TD_ScreenW / 2.0, y: TD_ScreenH - 80)
energyLab.fontColor = UIColor.red
addChild(energyLab)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = ((touches as NSSet).anyObject() as AnyObject) //进行类 型转化
let point = touch.location(in:self)
let node = self.atPoint(point)
if node.name == nil{
return
}
if isBeingBuilt{
isBeingBuilt = false
if node.name == TD_Name_ConfirmItem{
selTowerSprite.alpha = 1.0
selTowerSprite.isActivate = true
selTowerSprite.hiddenScopeAttack()
selTowerSprite.hiddenConfirmBuild()
let data = towersData[String(format: "Towers_%d_1", selTowerSprite.towerType)] as! NSDictionary
let expenditure = Double(data["Expenditure"] as! String)
energy = energy - expenditure!
energyLab.text = String(energy)
}else if node.name == TD_Name_CancelItem{
destroyed(tower: selTowerSprite)
isBeingBuilt = false
}else if node.name == TD_Name_UpgradeItem{
if selTowerSprite.level < selTowerSprite.maxLevel{
if energy - selTowerSprite.upExpenditure >= 0{
energy = energy - selTowerSprite.upExpenditure
energyLab.text = String(energy)
selTowerSprite.level = selTowerSprite.level + 1
selTowerSprite.refresh()
selTowerSprite.totalValue = selTowerSprite.totalValue + selTowerSprite.upExpenditure
print("selTowerSprite.totalValue:",selTowerSprite.totalValue)
}else{
(viewController as! GameViewController).showMsgbox(_message: "能量不足")
}
}else{
(viewController as! GameViewController).showMsgbox(_message: "该防御塔已经是最顶级")
}
selTowerSprite.hiddenOperationMenuView()
}else if node.name == TD_Name_SellItem{
energy = energy + selTowerSprite.totalValue * 0.5
energyLab.text = String(energy)
selTowerSprite.hiddenOperationMenuView()
destroyed(tower: selTowerSprite)
}else if node.name == TD_Name_ReturnItem{
selTowerSprite.hiddenOperationMenuView()
}else{
isBeingBuilt = true
}
return
}
if node.name == TD_Name_Clearing {//空地
selClearBlock = node
selClearBlockSprite.position = selClearBlock.position
selClearBlockSprite.isHidden = false
showCreatTowersMenu()
}else{
towersMenuView.isHidden = true
selClearBlockSprite.isHidden = true
if (node.name?.hasPrefix("CreatMenu_"))! {//判断是建造菜单按钮
if node.name == "CreatMenu_Cencel"{//建造菜单取消按钮
}else{
let name = node.name! as NSString
let towerType = Int(String(name.substring(from: 17).first!))
let data = towersData[String(format: "Towers_%d_1", towerType!)] as! NSDictionary
let expenditure = Double(data["Expenditure"] as! String)
if energy >= expenditure!{
// let img = name.substring(from: 10)
let towerSprite = TD_TowerSprite(color: UIColor.clear, size: selClearBlockSprite.size)
towerSprite.name = TD_Name_Tower
towerSprite.alpha = 0.4
towerSprite.position = selClearBlockSprite.position
towerSprite.superScene = self
towerSprite.totalValue = expenditure!
addChild(towerSprite)
towerSprite.layout(towerType: Int(String(name.substring(from: 17).first!))!)
towersList.append(towerSprite)
selTowerSprite = towerSprite
isBeingBuilt = true
towerSprite.showScopeAttack()
towerSprite.showConfirmBuild()
}else{//能量不足
(viewController as! GameViewController).showMsgbox(_message: "能量不足")
}
}
}else if node.name == TD_Name_CountdownLab{//点击出怪倒计时
if self.countdown > 3{
self.countdown = 3
}
}else if node.name == TD_Name_TowerSprite{//点击防御塔实例
isBeingBuilt = true
selTowerSprite = getTower(node: node)
selTowerSprite.showOperationMenuView()
}else if node.name == TD_Name_ScopeAttack{
node.isHidden = true
}
}
}
func getTower(node:SKNode) -> TD_TowerSprite{
for tower in towersList {
if tower.towerSprite == node{
return tower
}
}
return TD_TowerSprite()
}
func setPhysicsBody(){
physicsWorld.gravity = CGVector.init(dx: 0, dy: 0)//重力
physicsWorld.contactDelegate = self
physicsWorld.speed = 1
physicsBody = SKPhysicsBody.init(edgeLoopFrom: self.frame)//物理世界的边界
// physicsBody?.contactTestBitMask = TD_ProtagonistCategory | TD_MonsterCategory //产生碰撞的物理类型
physicsBody?.categoryBitMask = TD_WorldCategory //标记自身的物理类型
// physicsBody?.friction = 0 //阻力 为零时完全反弹
}
func startCreatMonsterSprite(){
timer = Timer.init(timeInterval: 1, repeats: true) { (kTimer) in
self.countdown = self.countdown - 1
self.countdownLab.text = String(self.countdown)
if (self.countdown == 0){
let monsterStr = self.monsterData.first
self.monsterData.removeFirst()
self.creatTeamMonsterSprte(monsterStr: monsterStr!)
self.countdown = 60
if self.monsterData.count < 1{
self.timer.invalidate() //停止
}
}
}
RunLoop.current.add(timer, forMode: .defaultRunLoopMode)
// TODO : 启动定时器
timer.fire()
// timer.invalidate() //停止
}
func creatTeamMonsterSprte(monsterStr:String) {
var str = monsterStr
let monster = str.first
creatMonsterSprte(type:String(monster!))
str.removeFirst()
if str.count >= 1 {
let time: TimeInterval = 1.5
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) {
self.creatTeamMonsterSprte(monsterStr: str)
}
}
}
func creatMonsterSprte(type:String){
var monsterSprite = TD_MonsterSprite(imageNamed: String(format: "monster_%@", type));
monsterSprite.size = CGSize(width: TD_Block_Width, height: TD_Block_Width)
monsterSprite.position = startPoint
if type == "1"{
monsterSprite.color = UIColor.purple //着色红色代表怪物城堡
monsterSprite.colorBlendFactor = 0.5 //混合因子
}else if type == "2"{
monsterSprite.color = UIColor.green //着色红色代表怪物城堡
monsterSprite.colorBlendFactor = 0.5 //混合因子
}else if type == "3"{
monsterSprite.color = UIColor.red //着色红色代表怪物城堡
monsterSprite.colorBlendFactor = 0.5 //混合因子
}
monsterSprite.isAggressive = false
monsterSprite.targetPosition = endPoint
monsterSprite.superScene = self
addChild(monsterSprite)
monsterSprite.layout(monsterType: type)
monsterSpriteList.append(monsterSprite)
}
/// 显示建造防御塔菜单
func showCreatTowersMenu() {
if (towersMenuView.name == nil){
towersMenuView = SKSpriteNode(color: UIColor.cyan, size: CGSize(width: TD_ScreenW, height: 60))
towersMenuView.name = "towersMenuView"
towersMenuView.position = CGPoint(x: towersMenuView.size.width / 2.0, y: towersMenuView.size.height / 2.0)
addChild(towersMenuView)
towersMenuView.isHidden = true
for i in 0..<towersData.count+1{
var img = ""
var name = ""
if i<towersData.count{
let data = towersData[String(format: "Towers_%d_1", i + 1)] as! NSDictionary
img = data["Image"] as! String
name = String(format: "CreatMenu_%@", data["Image"] as! String)
}else{
img = "cancel"
name = "CreatMenu_Cencel"
}
let towerMenu = SKSpriteNode(imageNamed: img)
towerMenu.size = CGSize(width: 60, height: 60)
towerMenu.name = name
towerMenu.position = CGPoint(x: CGFloat(60 * i) + towerMenu.size.width / 2.0 - towersMenuView.size.width / 2.0, y: towerMenu.size.height / 2.0 - towersMenuView.size.height / 2.0)
towersMenuView.addChild(towerMenu)
}
}
towersMenuView.isHidden = false
}
func didBegin(_ contact: SKPhysicsContact) {//开始接触碰撞
let bodyA = contact.bodyA
let bodyB = contact.bodyB
if bodyB.categoryBitMask == TD_TowerAttackCategory {//bodyA 进入防御塔攻击范围
let towerSprite = getTowerSprite(body: bodyB)
let monsterSprite = getMonsterSprite(body: bodyA)
towerSprite.attackRange.append(monsterSprite)
}else if bodyB.categoryBitMask == TD_EnergyBallCategory {//bodyA 被能量球攻击
let towerSprite = getTowerSprite(body: bodyB)
let monsterSprite = getMonsterSprite(body: bodyA)
towerSprite.damageToMonster(monster: monsterSprite)
}
}
func didEnd(_ contact: SKPhysicsContact) {//结束碰撞
let bodyA = contact.bodyA
let bodyB = contact.bodyB
if bodyB.categoryBitMask == TD_TowerAttackCategory {//bodyA 离开防御塔攻击范围
let towerSprite = getTowerSprite(body: bodyB)
let monsterSprite = getMonsterSprite(body: bodyA)
let index = towerSprite.attackRange.index(of: monsterSprite)
towerSprite.attackRange.remove(at: index!)
}
}
/// 获取对应的防御塔
///
/// - Parameter body: 检测到的body
/// - Returns: 对应的防御塔
func getTowerSprite(body:SKPhysicsBody) -> TD_TowerSprite {
for towerSprite in towersList {
if (towerSprite.scopeAttack.physicsBody == body){
return towerSprite
}
}
for towerSprite in towersList {
for energyBallSprite in towerSprite.energyBallList{
if (energyBallSprite.physicsBody == body){
return towerSprite
}
}
}
return TD_TowerSprite()
}
/// 获取对应的怪物
///
/// - Parameter body: 检测到的body
/// - Returns: 对应的怪物
func getMonsterSprite(body:SKPhysicsBody) -> TD_MonsterSprite {
for mosterSprite in monsterSpriteList {
if (mosterSprite.physicsBody == body){
return mosterSprite
}
}
return TD_MonsterSprite()
}
/// 摧毁怪物
///
/// - Parameter monster: 被击杀的怪物
func destroyed(monster:TD_MonsterSprite){
monster.removeAllFromParent()
let i = monsterSpriteList.index(of: monster)
if i != nil{
// monster = nil
var m:TD_MonsterSprite? = monsterSpriteList[i!]
monsterSpriteList.remove(at: i!)
m = nil
}
for i in 0..<towersList.count {
let tower = towersList[i]
let index = tower.attackRange.index(of: monster)
if index != nil{
tower.attackRange.remove(at: index!)
}
let index1 = tower.attackTarget.index(of: monster)
if index1 != nil{
tower.attackTarget.remove(at: index1!)
}
}
if monsterSpriteList.count == 0{
if customsClearance(){
print("游戏胜利✌️")
// editRecord
var start = 0
if HP == maxHP {
start = 3
}else if maxHP - HP >= 2{
start = 1
}else{
start = 2
}
TD_AnalyticalDataObject().editRecord(scenarioIndex: scenarioIndex, starIndex: start)
(viewController as! GameViewController).showMsgbox(_message: "开始下一关", _title: "恭喜通关", okTitle: "确定", cancelTitle: "取消", tag: 1)
}else{
print("波次胜利")
}
}
}
/// 摧毁防御塔
///
/// - Parameter tower: 被摧毁的防御塔
func destroyed(tower:TD_TowerSprite){
tower.removeAllFromParent()
let index = towersList.index(of: tower)
if index != nil{
towersList.append(selTowerSprite)
}
}
/// 获得能量
///
/// - Parameter energy: 能量数值
func collectEnergy(energy:Double){
self.energy = self.energy + energy
energyLab.text = String(self.energy)
}
/// 被突破
///
/// - Parameter monster: 突破的怪物
func breakthrough(monster:TD_MonsterSprite){
let harm = monster.harm
HP = HP - harm
hpLab.text = String(HP)
if HP <= 0{
self.timer.invalidate() //停止定时器
(viewController as! GameViewController).showMsgbox(_message: "Game Over")
}
destroyed(monster: monster)
}
func customsClearance() -> Bool {
if self.monsterData.count == 0 {
if monsterSpriteList.count == 0{
return true
}
}
return false
}
func refreshScene(scenarioIndex:Int){
self.scenarioIndex = scenarioIndex
refresh()
}
}
<file_sep>/TD_AncientRuins/TD_AncientRuins/Classes/View/TD_HeroSprite.swift
//
// TD_HeroSprite.swift
// TD_AncientRuins
//
// Created by mac on 2018/10/17.
// Copyright © 2018年 DAA. All rights reserved.
//
import UIKit
class TD_HeroSprite: TD_BaseSpriteNode {
}
<file_sep>/TD_ApisFlorea/TD_ApisFlorea/Classes/Sprite/TD_BaseSpriteNode.swift
//
// TD_BaseSpriteNode.swift
// TD_WaterMargin
//
// Created by mac on 2018/9/13.
// Copyright © 2018年 DAA. All rights reserved.
//
import SpriteKit
class TD_BaseSpriteNode: SKSpriteNode {
var tag = 0
var superScene = SKScene()
func runActionGif(filePath:NSString,isRepeat:Bool,key:NSString){
let coinTextures = load(imagePath: filePath as String)!
runGif(textures: coinTextures, timePerFrame: 0.1,isRepeat: isRepeat, key:key)
}
func runActionGif(fileName:NSString){
let path = Bundle.main.path(forResource: fileName as String, ofType: "gif")!
runActionGif(filePath: path as NSString, isRepeat: false, key:"xxx")
}
func runActionGif(fileName:NSString,isRepeat:Bool,key:NSString){
let path = Bundle.main.path(forResource: fileName as String, ofType: "gif")!
runActionGif(filePath: path as NSString, isRepeat: isRepeat, key:key)
}
func runGif(textures:[SKTexture],timePerFrame:TimeInterval,isRepeat:Bool,key:NSString){
var action = SKAction()
if isRepeat{
action = SKAction.repeatForever(SKAction.animate(with: textures, timePerFrame: timePerFrame))
run(action, withKey: key as String)
}else{
action = SKAction.animate(with: textures, timePerFrame: timePerFrame)
run(action) {
self.removeAction(forKey: "xxx")
}
}
}
func removeAction(key:String){
self.removeAction(forKey: key)
}
func load(imagePath:String)->[SKTexture]?{
guard let imageSource = CGImageSourceCreateWithURL(URL(fileURLWithPath: imagePath) as CFURL, nil) else {
return nil
}
let count = CGImageSourceGetCount(imageSource)
var images:[CGImage] = []
for i in 0..<count{
guard let img = CGImageSourceCreateImageAtIndex(imageSource, i, nil) else {continue}
images.append(img)
}
return images.map {SKTexture(cgImage:$0)}
}
}
<file_sep>/TD_ Journey/TD_ Journey/Classes/View/TD_HeroSprite.swift
//
// TD_HeroSprite.swift
// TD_AncientRuins
//
// Created by mac on 2018/10/17.
// Copyright © 2018年 DAA. All rights reserved.
//
import UIKit
import SpriteKit
class TD_HeroSprite: TD_BaseSpriteNode {
var type = 0
var actualHP = 10
let homeSprite = SKNode()
var enemySpriteList = [TD_CartSprite](){
willSet {
}
didSet {
// if attackTower.count == 1 && oldValue.count == 0{
// self.removeOrScopeAction(key: TD_MoveToTower)
// self.updataAttack()
// }
print("enemySpritnList已经发生改变")
}
}
var ourSpriteList = [TD_CartSprite](){
willSet {
}
didSet {
print("ourSpritnList已经发生改变")
}
}
var playCartData = [Int:TD_CartSprite]() //在战场上的卡片
var actionCartData = [Int:TD_CartSprite]() //需要行动的卡片
func layout(){
initPhysicsBoby()
creatHomeRange()
}
func initPhysicsBoby(){
addChild(homeSprite)
homeSprite.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: TD_Block_Width, height: TD_Block_Height * 5), center: CGPoint(x:0, y: 0))
// physicsBody.colo
homeSprite.physicsBody?.collisionBitMask = 0
// physicsBody?.density = 0 //密度
homeSprite.physicsBody?.mass = 1 //质量
homeSprite.physicsBody?.restitution = 0 //弹性
homeSprite.physicsBody?.friction = 0.0 //摩擦力
homeSprite.physicsBody?.linearDamping = 0.0 //线性阻力(空气阻力)
homeSprite.physicsBody?.allowsRotation = false
homeSprite.physicsBody?.affectedByGravity = false
// if soldierCategory == TD_Soldier1Category {
// physicsBody?.contactTestBitMask = TD_TowerCategory | TD_Soldier2Category//碰撞检测
// }else{
// physicsBody?.contactTestBitMask = TD_TowerCategory | TD_Soldier1Category//碰撞检测
// }
// physicsBody?.contactTestBitMask = TD_TowerCategory | TD_Soldier1Category | TD_Soldier2Category//碰撞检测
if type == 0 {
// physicsBody?.contactTestBitMask = TD_EnemyCartCategory
homeSprite.physicsBody?.categoryBitMask = TD_OurHeroCategory
}else{
// physicsBody?.contactTestBitMask = TD_OurHeroHomeCategory
homeSprite.physicsBody?.categoryBitMask = TD_EnemyHeroCategory
}
// physicsBody?.isDynamic = true
// physicsBody?.isResting = true
self.zPosition = 20
}
func creatHomeRange(){
physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: TD_Block_Width * 4, height: TD_Block_Height * 5), center: CGPoint(x: type == 0 ? TD_Block_Width * 2 + TD_Block_Width * 0.5:-TD_Block_Width * 2 - TD_Block_Width * 0.5, y: 0))
// physicsBody.colo
physicsBody?.collisionBitMask = 0
// physicsBody?.density = 0 //密度
physicsBody?.mass = 1 //质量
physicsBody?.restitution = 0 //弹性
physicsBody?.friction = 0.0 //摩擦力
physicsBody?.linearDamping = 0.0 //线性阻力(空气阻力)
physicsBody?.allowsRotation = false
physicsBody?.affectedByGravity = false
// if soldierCategory == TD_Soldier1Category {
// physicsBody?.contactTestBitMask = TD_TowerCategory | TD_Soldier2Category//碰撞检测
// }else{
// physicsBody?.contactTestBitMask = TD_TowerCategory | TD_Soldier1Category//碰撞检测
// }
// physicsBody?.contactTestBitMask = TD_TowerCategory | TD_Soldier1Category | TD_Soldier2Category//碰撞检测
if type == 0 {
// physicsBody?.contactTestBitMask = TD_EnemyCartCategory
physicsBody?.categoryBitMask = TD_OurHeroHomeCategory
}else{
// physicsBody?.contactTestBitMask = TD_OurHeroHomeCategory
physicsBody?.categoryBitMask = TD_EnemyHeroHomeCategory
}
// physicsBody?.isDynamic = true
// physicsBody?.isResting = true
self.zPosition = 20
}
/// 被攻击
///
/// - Parameters:
/// - attack: 伤害
/// - attackType: 伤害类型 1:物理伤害、1:魔法伤害
/// - Returns: 是否被击杀
func beingAttacked(attack:Int,attackType:Int) -> Bool {
var ar = 0
// if attackType == 0 {
// ar = actualArmor
// }else{
// ar = actualMagicArmor
// }
actualHP = actualHP - max(attack - ar, 0)
let temporaryImgSprite = SKSpriteNode(imageNamed: "beingAttackedTrace")
temporaryImgSprite.size = size
temporaryImgSprite.zPosition = 100;
addChild(temporaryImgSprite)
DispatchQueue.main.asyncAfter(deadline: .now()+0.5, execute:
{
temporaryImgSprite.removeFromParent()
})
if actualHP <= 0 {
print("该英雄被击杀 --");
// (self.superScene as! TD_FightScene).removeSptiye(key: coordinates)
// removeFromParent()
return true
}
return false
}
}
<file_sep>/TD_PingPongBalls/TD_PingPongBalls/PrefixHeader.swift
//
// PrefixHeader.swift
// TD_Decathlon
//
// Created by mac on 2018/7/9.
// Copyright © 2018年 DAA. All rights reserved.
//
import UIKit
let TD_Screen = UIScreen.main.bounds.size
let TD_ScreenW = TD_Screen.width
let TD_ScreenH = TD_Screen.height
let TD_Block_Width = (TD_ScreenW - 10 * 2) / 19.0
let TD_Game_TopClearance = (TD_ScreenH - TD_Block_Width * 9) / 2.0
//let TD_Block_Height = (TD_ScreenH - 10 * 2) / 9.0
let TD_MAX_Scenario = 10
let TD_SpriteName_ZS = "战士"
let TD_SpriteName_GJS = "弓箭手"
let TD_SpriteName_QB = "骑兵"
let TD_SpriteName_KZS = "狂战士"
let TD_SpriteName_TL = "统领"
let TD_SpriteType_ZS = 1
let TD_SpriteType_GJS = 2
let TD_SpriteType_QB = 3
let TD_SpriteType_KZS = 4
let TD_SpriteType_TL = 5
let TD_Block_AspectRatio_Show = 1.6
let TD_Attack_ZS = ["roundness","attack"]
let TD_MoveToTower = "TD_MoveToTower" //移动到指定城堡 action key
let TD_MoveToSprite = "TD_MoveToSprite" //移动到指定士兵 action key
//TD_WorldCategory
let TD_WorldCategory : UInt32 = 0x1 << 1 //屏幕边缘
let TD_TowerCategory : UInt32 = 0x1 << 2 //防御塔
let TD_MonsterCategory : UInt32 = 0x1 << 3 //怪物
let TD_TowerAttackCategory : UInt32 = 0x1 << 4 //防御塔攻击范围
let TD_AlertCategory : UInt32 = 0x1 << 5 //怪物警戒范围
let TD_AttackCategory : UInt32 = 0x1 << 6 //怪物攻击范围
let TD_EnergyBallCategory : UInt32 = 0x1 << 7 //防御塔能量球
//struct PhysicsCategory {
// static let Crocodile: UInt32 = 1
// static let VineHolder: UInt32 = 2
// static let Vine: UInt32 = 4
// static let Prize: UInt32 = 8
//}
<file_sep>/TD_ Journey/TD_ Journey/TD_FightViewController.swift
//
// TD_FightViewController.swift
// TD_ Journey
//
// Created by mac on 2018/10/17.
// Copyright © 2018年 DAA. All rights reserved.
//
import UIKit
import SpriteKit
import GameplayKit
class TD_FightViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let sView = SKView(frame: view.bounds)
view.addSubview(sView)
let gameScene = TD_FightScene(size: view.bounds.size)
gameScene.viewController = self;
gameScene.scaleMode = .aspectFill
sView.presentScene(gameScene)
sView.ignoresSiblingOrder = true
sView.showsFPS = true
sView.showsNodeCount = true
}
}
<file_sep>/TD_AncientRuins/TD_AncientRuins/Classes/Scene/TD_GameScene.swift
//
// TD_GameScene.swift
// TD_Decathlon
//
// Created by mac on 2018/7/9.
// Copyright © 2018年 DAA. All rights reserved.
//
import SpriteKit
class TD_GameScene: TD_BaseScene ,SKSceneDelegate{
var allSceneData = [String:Any]() //场景布局原始数据
var mapData = [Any]() //记录场景布局转化数据
var scenarioIndex = 1 //当前关卡
override func didMove(to view: SKView) {
allSceneData = TD_AnalyticalDataObject().getFileData(fileName: "Scene") as! [String : NSDictionary]
backgroundColor = UIColor.blue
refreshView();
}
func refreshView() {
removeAllChildren()
let data = allSceneData[String(format: "Scene_%d", scenarioIndex)] as! NSDictionary
let sceneData = data["scene"] as! NSArray
for i in 0..<sceneData.count {
// let lineData = NSMutableArray()
var lineStr = sceneData[sceneData.count - i - 1] as! String
let maxNum = lineStr.count
let lineData = NSMutableArray()
for j in 0..<maxNum {
let blocktype = lineStr.first
lineStr.removeFirst()
lineData.add(blocktype as Any)
let blockSprite = TD_SceneElementSprite()
blockSprite.blockType = String(blocktype!)
blockSprite.superScene = self
var indentation = CGFloat(0.0)
if (i % 2 == 1){
indentation = TD_Block_Width * CGFloat(0.5)
}
blockSprite.position = CGPoint(x: TD_Block_Width * CGFloat(Double(j) + 0.5) + indentation, y: TD_Block_Width * TD_Block_AspectRatio_Typography * CGFloat(i) + TD_Block_Width * 0.5)
blockSprite.size = CGSize(width: TD_Block_Width, height: TD_Block_Width)
addChild(blockSprite)
blockSprite.layout()
}
mapData.append(lineData)
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// let touch = ((touches as NSSet).anyObject() as AnyObject) //进行类 型转化
// let point = touch.location(in:self)
// let node = self.atPoint(point)
//
// if (node.name != nil) {
// if (node.name == "selectScenario") {//判断是关卡选择按钮
// (viewController as! GameViewController).showScenarioScene(index: (node as! TD_SelectScenarioSprite).tag - 1000 + 1)
// }
// }else{
// }
}
}
<file_sep>/TD_ApisFlorea/TD_ApisFlorea/Classes/Scene/TD_GameScene.swift
//
// TD_GameScene.swift
// TD_Decathlon
//
// Created by mac on 2018/7/9.
// Copyright © 2018年 DAA. All rights reserved.
// 选择关卡界面
import SpriteKit
class TD_GameScene: TD_BaseScene ,SKSceneDelegate{
var allSceneRecordData = [String:NSDictionary]() //关卡通关记录数据
override func didMove(to view: SKView) {
allSceneRecordData = TD_AnalyticalDataObject().getFileData(fileName: "SceneRecord") as! [String : NSDictionary]
refreshView();
}
func refreshView() {
removeAllChildren()
for i in 0 ..< allSceneRecordData.count {
let data = allSceneRecordData[String(format: "Scene_%d", i + 1)]
let sp = TD_SelectScenarioSprite(color: UIColor.clear, size: CGSize(width: 80, height: 80))
sp.zPosition = 100
sp.superScene = self
sp.tag = 1000 + i
sp.name = "selectScenario"
sp.data = data as! [String : Any]
sp.position = CGPoint(x: 26 + i % 6 * (80 + 27) + 40, y: 30 + (80 + 30) * Int(i / 6) + 40)
addChild(sp)
sp.layout()
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = ((touches as NSSet).anyObject() as AnyObject) //进行类 型转化
let point = touch.location(in:self)
let node = self.atPoint(point)
if (node.name != nil) {
if (node.name == "selectScenario") {//判断是关卡选择按钮
(viewController as! GameViewController).showScenarioScene(index: (node as! TD_SelectScenarioSprite).tag - 1000 + 1)
}
}else{
}
}
}
<file_sep>/TD_AncientRuins/TD_AncientRuins/GameViewController.swift
//
// GameViewController.swift
// TD_AncientRuins
//
// Created by mac on 2018/10/16.
// Copyright © 2018年 DAA. All rights reserved.
//
import UIKit
import SpriteKit
import GameplayKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let view = self.view as! SKView? {
let gameScene = TD_GameScene(size: view.bounds.size)
gameScene.viewController = self;
gameScene.scaleMode = .aspectFill
view.presentScene(gameScene)
view.ignoresSiblingOrder = true
view.showsFPS = true
view.showsNodeCount = true
}
}
}
<file_sep>/TD_AncientRuins/TD_AncientRuins/Classes/Lib/TD_Action.swift
//
// TD_Action.swift
// TD_WaterMargin
//
// Created by mac on 2018/9/28.
// Copyright © 2018年 DAA. All rights reserved.
//
import UIKit
import SpriteKit
class TD_Action: NSObject {
func action(paths:NSArray,startPoint:CGPoint,moveSpeed:CGFloat) -> SKAction{
let bezierPath = UIBezierPath()
for i in 0..<paths.count {
let p = paths[i] as! CGPoint
let center = CGPoint(x: p.x - startPoint.x, y: p.y - startPoint.y)
if i == 0{
bezierPath.move(to: center)
}else{
bezierPath.addLine(to: center)
}
}
let action = SKAction.follow(bezierPath.cgPath, speed: CGFloat(moveSpeed))
return action
}
}
<file_sep>/TD_WaterMargin/TD_WaterMargin/PrefixHeader.swift
//
// PrefixHeader.swift
// TD_Decathlon
//
// Created by mac on 2018/7/9.
// Copyright © 2018年 DAA. All rights reserved.
//
import UIKit
let TD_Screen = UIScreen.main.bounds.size
let TD_ScreenW = TD_Screen.width
let TD_ScreenH = TD_Screen.height
let TD_Block_Width = (TD_ScreenW - 10 * 2) / 19.0
let TD_Game_TopClearance = (TD_ScreenH - TD_Block_Width * 9) / 2.0
//let TD_Block_Height = (TD_ScreenH - 10 * 2) / 9.0
let TD_MAX_Scenario = 10
let TD_SpriteName_ZS = "战士"
let TD_SpriteName_GJS = "弓箭手"
let TD_SpriteName_QB = "骑兵"
let TD_SpriteName_KZS = "狂战士"
let TD_SpriteName_TL = "统领"
let TD_SpriteType_ZS = 1
let TD_SpriteType_GJS = 2
let TD_SpriteType_QB = 3
let TD_SpriteType_KZS = 4
let TD_SpriteType_TL = 5
let TD_Block_AspectRatio_Show = 1.6
let TD_Attack_ZS = ["roundness","attack"]
let TD_MoveToTower = "TD_MoveToTower" //移动到指定城堡 action key
let TD_MoveToSprite = "TD_MoveToSprite" //移动到指定士兵 action key
//TD_WorldCategory
let TD_WorldCategory : UInt32 = 0x1 << 1 //屏幕边缘
let TD_TowerCategory : UInt32 = 0x1 << 2 //防御塔
let TD_MonsterCategory : UInt32 = 0x1 << 3 //怪物
let TD_TowerAttackCategory : UInt32 = 0x1 << 4 //防御塔攻击范围
let TD_AlertCategory : UInt32 = 0x1 << 5 //怪物警戒范围
let TD_AttackCategory : UInt32 = 0x1 << 6 //怪物攻击范围
let TD_EnergyBallCategory : UInt32 = 0x1 << 7 //防御塔能量球
//struct PhysicsCategory {
// static let Crocodile: UInt32 = 1
// static let VineHolder: UInt32 = 2
// static let Vine: UInt32 = 4
// static let Prize: UInt32 = 8
//}
let TD_Name_Clearing = "clearing" //空地
let TD_Name_Tower = "tower" //防御塔整体
let TD_Name_TowerSprite = "towerSprite" //防御塔实例
let TD_Name_ScopeAttack = "scopeAttack" //防御塔攻击范围
let TD_Name_CountdownLab = "countdownLab" //出怪倒计时Lab
let TD_Name_HPLab = "HPLab" //关卡血量显示Lab
let TD_Name_EnergyLab = "energyLab" //出怪倒计时Lab
let TD_Name_ConfirmItem = "confirm" //确认建造按钮
let TD_Name_CancelItem = "cancel" //取消建造按钮
let TD_Name_UpgradeItem = "upgrade" //升级建筑按钮
let TD_Name_SellItem = "sell" //卖出建筑按钮
let TD_Name_ReturnItem = "return" //返回按钮
<file_sep>/TD_ Journey/TD_ Journey/PrefixHeader.swift
//
// PrefixHeader.swift
// TD_Decathlon
//
// Created by mac on 2018/7/9.
// Copyright © 2018年 DAA. All rights reserved.
//
import UIKit
let TD_Screen = UIScreen.main.bounds.size
let TD_ScreenW = TD_Screen.width
let TD_ScreenH = TD_Screen.height
let TD_Scene_OrSoClearance = CGFloat(60.0)
let TD_Block_Width = (TD_ScreenW - TD_Scene_OrSoClearance * 2) / 12.0
let TD_Block_AspectRatio = CGFloat(4.0 / 3)
let TD_Block_Height = TD_Block_Width * TD_Block_AspectRatio
//let TD_topClearance = (TD_ScreenH - CGFloat(maxLine) * TD_Block_Height - 50) / 2.0
let TD_Game_TopClearance = (TD_ScreenH - CGFloat(5) * TD_Block_Height - 50) / 2.0
let TD_MAX_Scenario = 10
let TD_SpriteName_ZS = "战士"
let TD_SpriteName_GJS = "弓箭手"
let TD_SpriteName_QB = "骑兵"
let TD_SpriteName_KZS = "狂战士"
let TD_SpriteName_TL = "统领"
let TD_SpriteType_ZS = 1
let TD_SpriteType_GJS = 2
let TD_SpriteType_QB = 3
let TD_SpriteType_KZS = 4
let TD_SpriteType_TL = 5
let TD_Attack_ZS = ["roundness","attack"]
let TD_MoveToTower = "TD_MoveToTower" //移动到指定城堡 action key
let TD_MoveToSprite = "TD_MoveToSprite" //移动到指定士兵 action key
//TD_WorldCategory
let TD_WorldCategory : UInt32 = 0x1 << 1 //战场边缘
let TD_OurHeroHomeCategory : UInt32 = 0x1 << 2 //我方英雄主场范围
let TD_EnemyHeroHomeCategory : UInt32 = 0x1 << 3 //敌方英雄主场范围
let TD_OurCartCategory : UInt32 = 0x1 << 4 //我方卡片
let TD_EnemyCartCategory : UInt32 = 0x1 << 5 //敌方卡片 32
let TD_OurCartAttackCategory : UInt32 = 0x1 << 6 //我方卡片攻击范围
let TD_EnemyCartAttackCategory : UInt32 = 0x1 << 7 //敌方卡片攻击范围
let TD_OurHeroCategory : UInt32 = 0x1 << 8 //我方英雄 256
let TD_EnemyHeroCategory : UInt32 = 0x1 << 9 //敌方英雄
//let TD_EnergyBallCategory : UInt32 = 0x1 << 7 //敌方卡片攻击范围
//contactTestBitMask
let TD_OurCartContactTestBitMask = TD_EnemyHeroHomeCategory | TD_EnemyCartAttackCategory
let TD_EnemyCartContactTestBitMask = TD_OurHeroHomeCategory | TD_OurCartAttackCategory
//collisionBitMask
let TD_OurCartCollisionBitMask = TD_EnemyCartCategory
let TD_EnemyCartCollisionBitMask = TD_OurCartCategory
//struct PhysicsCategory {
// static let Crocodile: UInt32 = 1
// static let VineHolder: UInt32 = 2
// static let Vine: UInt32 = 4
// static let Prize: UInt32 = 8
//}
let TD_Name_Clearing = "clearing" //空地
let TD_Name_Tower = "tower" //防御塔整体
let TD_Name_TowerSprite = "towerSprite" //防御塔实例
let TD_Name_ScopeAttack = "scopeAttack" //防御塔攻击范围
let TD_Name_CountdownLab = "countdownLab" //出怪倒计时Lab
let TD_Name_HPLab = "HPLab" //关卡血量显示Lab
let TD_Name_EnergyLab = "energyLab" //出怪倒计时Lab
let TD_Name_ConfirmItem = "confirm" //确认建造按钮
let TD_Name_CancelItem = "cancel" //取消建造按钮
let TD_Name_UpgradeItem = "upgrade" //升级建筑按钮
let TD_Name_SellItem = "sell" //卖出建筑按钮
let TD_Name_ReturnItem = "return" //返回按钮
<file_sep>/TD_ Journey/TD_ Journey/Classes/Scene/TD_FightScene.swift
//
// TD_FightScene.swift
// TD_ Journey
//
// Created by mac on 2018/10/17.
// Copyright © 2018年 DAA. All rights reserved.
//
import UIKit
import SpriteKit
class TD_FightScene: TD_BaseScene ,SKPhysicsContactDelegate{
// var maxLine = 5
var actionType = 1
var introView = TD_IntroSprite()
var prepareView = SKSpriteNode()
var selPrepareCardView = SKSpriteNode()
let startSprite = SKSpriteNode(imageNamed: "startBtn")
var selIndex = -1
var prepareCardList = NSMutableArray()
var cardList = NSArray()
var upsetCardList = NSMutableArray()
var playCardData = [Int:TD_CartSprite]()
var ourHeroSprite = TD_HeroSprite() //我方英雄
var enemyHeroSprite = TD_HeroSprite() //敌方英雄
var aiCardGroup = NSMutableArray()
var aiUpsetCardGroup = NSMutableArray()
var aiPrepareCardList = NSMutableArray()
// creatHomeRangeView
override func didMove(to view: SKView) {
backgroundColor = UIColor.lightGray
refreshView();
}
//创建战场UI
func refreshView() {
removeAllChildren()
backgroundColor = UIColor.init(patternImage: UIImage(named: "background1_1")!)
for i in 0..<5 {
for j in 0..<12{
let blockSprite = SKSpriteNode(color: UIColor(displayP3Red: 100, green: 22, blue: 22, alpha: 0.5), size: CGSize(width: TD_Block_Width - 1, height: TD_Block_Height - 1))
blockSprite.position = CGPoint(x: TD_Scene_OrSoClearance + TD_Block_Width * CGFloat(j) + TD_Block_Width / 2.0, y: TD_Game_TopClearance + TD_Block_Height * CGFloat(i) + TD_Block_Height / 2.0 + 50)
addChild(blockSprite)
let tapBlockSprite = SKSpriteNode()
tapBlockSprite.size = blockSprite.size
tapBlockSprite.position = CGPoint(x: TD_Scene_OrSoClearance + TD_Block_Width * CGFloat(j) + TD_Block_Width / 2.0, y: TD_Game_TopClearance + TD_Block_Height * CGFloat(i) + TD_Block_Height / 2.0 + 50)
tapBlockSprite.name = "blockSprite"
tapBlockSprite.zPosition = 1000
addChild(tapBlockSprite)
}
}
creatHeroSprite()
creatPrepareView()
creatIntroView()
setPhysicsBody()
startGame()
}
//创建备战界面
func creatPrepareView(){
prepareView.size = CGSize(width: TD_ScreenW - 100, height: 50)
prepareView.position = CGPoint(x: (TD_ScreenW - 100) / 2.0 + 50 - 20, y: 25)
prepareView.color = UIColor.white
addChild(prepareView)
selPrepareCardView.color = UIColor(displayP3Red: 128, green: 22, blue: 22, alpha: 0.4)
selPrepareCardView.size = CGSize(width: 50 / TD_Block_AspectRatio - 1, height: 50)
selPrepareCardView.isHidden = true
selPrepareCardView.zPosition = 100
prepareView.addChild(selPrepareCardView)
startSprite.position = CGPoint(x: TD_ScreenW - 25, y: 25)
startSprite.size = CGSize(width: 50, height: 50)
startSprite.name = "startBtn"
addChild(startSprite)
}
func creatHeroSprite(){
for i in 0..<2 {
let heroSprite = TD_HeroSprite(color: UIColor.yellow, size: CGSize(width: TD_Block_Width, height: TD_Block_Height))
heroSprite.type = i
// if
heroSprite.position = CGPoint(x: i == 0 ?TD_Scene_OrSoClearance - TD_Block_Width / 2 - 1:TD_ScreenW - (TD_Scene_OrSoClearance - TD_Block_Width / 2 + 1), y: TD_Game_TopClearance + TD_Block_Height / 2.0 + 50 + TD_Block_Height * 2)
addChild(heroSprite)
heroSprite.layout()
if i == 0{
ourHeroSprite = heroSprite
}else{
enemyHeroSprite = heroSprite
}
}
}
func creatIntroView(){
introView.position = CGPoint(x: TD_ScreenW - TD_Block_Width * 2, y: TD_Block_Height + 50)
introView.isHidden = true
introView.layout()
addChild(introView)
}
//刷新备战界面数据
func refreshPrepareView(){
for item in prepareView.children {
if (item.isKind(of: TD_BaseSpriteNode.classForCoder())){
item.removeFromParent()
}
}
for i in 0..<prepareCardList.count {
let data = prepareCardList[i] as! NSDictionary
// let data = NSMutableDictionary(dictionary: d)
let imgName = data.value(forKey: "CardImage") as! String
let blockSprite = TD_BaseSpriteNode(imageNamed: imgName)
blockSprite.tag = 100 + i
blockSprite.name = "prepareCard"
blockSprite.size = CGSize(width: 50 / TD_Block_AspectRatio - 1, height: 50 - 2)
blockSprite.position = CGPoint(x: 50 / TD_Block_AspectRatio * CGFloat(i) - 0.5 * (TD_ScreenW - 100) + blockSprite.size.width * 0.5, y: 0 )
prepareView.addChild(blockSprite)
let remainingPrepareLab = SKLabelNode(text: String(format: "%d", (data.value(forKey: "remainingPrepare1") as! Int)))
remainingPrepareLab.fontColor = UIColor.red
remainingPrepareLab.fontSize = 17.0
remainingPrepareLab.position = CGPoint(x: 10, y: 10)
blockSprite.addChild(remainingPrepareLab)
}
}
func creatCartSprite(type:Int,infoData:NSDictionary) ->TD_CartSprite{
return creatCartSprite(type: type, coordinates: 0, infoData: infoData)
}
func creatCartSprite(type:Int,coordinates:Int,infoData:NSDictionary) ->TD_CartSprite{
let arcX = coordinates % 100
let arcY = coordinates / 100
let position = CGPoint(x: TD_Scene_OrSoClearance + TD_Block_Width * CGFloat(arcX) + TD_Block_Width / 2.0, y: TD_Game_TopClearance + TD_Block_Height * CGFloat(arcY) + TD_Block_Height / 2.0 + 50 + 5)
let selData = infoData
let cartSprite = TD_CartSprite()
cartSprite.type = type
cartSprite.coordinates = coordinates
cartSprite.position = position
cartSprite.size = CGSize(width: TD_Block_Width - 2, height: TD_Block_Width - 2)
cartSprite.name = String(format: "%d", cartSprite.coordinates)
cartSprite.cardInfo = selData as! [String : Any]
cartSprite.superScene = self
addChild(cartSprite)
// playCardList.append(cartSprite)
playCardData[coordinates] = cartSprite
cartSprite.layout()
if type == 0 {
ourHeroSprite.playCartData[coordinates] = cartSprite
}else{
enemyHeroSprite.playCartData[coordinates] = cartSprite
}
return cartSprite
}
//获取卡组
func getCardGroup() -> NSArray{
let data = NSMutableArray()
let dict = NSMutableDictionary()
dict.setValue("2001", forKey: "id")
dict.setValue("1", forKey: "star")
for index in 0..<10 {
dict.setValue(String(format: "index_%d", index), forKey: "key")
data.add(dict)
}
for i in 0..<data.count {
let item = data[i] as! NSDictionary
let cardId = item["id"] as! String
let star = item["star"] as! String
let index = Int(cardId)! / 1000
let data1 = (TD_AnalyticalDataObject().getFileData(fileName: "Card"))["Data"] as! NSArray
let cardRaceData = data1[index - 1] as! [String:NSDictionary]
let cardInfo = cardRaceData[String(format: "Card_%@",cardId)]
let cardInfo1 = NSMutableDictionary(dictionary: cardInfo!)
cardInfo1.setValue(star, forKey: "star")
cardInfo1.setValue(cardInfo?["Prepare"], forKey: "remainingPrepare")
data.replaceObject(at: i, with: cardInfo1)
}
return data
}
//卡组乱序
func getUpsetCardGroup(oldList:NSArray) -> NSArray {
let mList = NSMutableArray(array: oldList)
// for i in 0..<mList.count {
//
// }
return mList
}
//开始游戏
func startGame(){
cardList = getCardGroup()
upsetCardList = NSMutableArray(array: getUpsetCardGroup(oldList: cardList))
aiUpsetCardGroup = NSMutableArray(array: cardList)
// for _ in 0..<3 {
// prepareCardList.add(upsetCardList.firstObject as Any)
// upsetCardList.removeObject(at: 0)
// let item = aiUpsetCardGroup.firstObject as! NSMutableDictionary
// let remainingPrepare = Int(item.value(forKey: "remainingPrepare") as! String)
//
// item.setValue(remainingPrepare! - 1, forKey: "remainingPrepare1")
// aiPrepareCardList.add(aiUpsetCardGroup.firstObject as Any)
// aiUpsetCardGroup.removeObject(at: 0)
// }
// refreshPrepareView()
thatCard(isFirst: true)
}
func thatCard(isFirst:Bool){
for item in prepareCardList {
let remainingPrepare = (item as AnyObject).value(forKey: "remainingPrepare1") as! Int
if remainingPrepare == 0{
(item as AnyObject).setValue(Int((remainingPrepare + 1) / 2), forKey: "remainingPrepare1")
}
}
var number = 1
if isFirst {
number = 3
}
for _ in 0..<number {
prepareCardList.add(upsetCardList.firstObject as Any)
upsetCardList.removeObject(at: 0)
let item = aiUpsetCardGroup.firstObject as! NSMutableDictionary
let remainingPrepare = Int(item.value(forKey: "remainingPrepare") as! String)
item.setValue(remainingPrepare! - 1, forKey: "remainingPrepare1")
aiPrepareCardList.add(aiUpsetCardGroup.firstObject as Any)
aiUpsetCardGroup.removeObject(at: 0)
}
refreshPrepareView()
startSprite.isHidden = false
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = ((touches as NSSet).anyObject() as AnyObject) //进行类 型转化
let point = touch.location(in:self)
let node = self.atPoint(point)
introView.isHidden = true
if (node.name != nil) {
if (node.name == "prepareCard") {//选中备战的卡片
selPrepareCardView.position = node.position
selPrepareCardView.isHidden = false
selIndex = (node as! TD_BaseSpriteNode).tag - 100
// introView.cardInfo =
let selData = prepareCardList[selIndex] as! NSDictionary
introView.cardInfo = selData as! [String : Any]
introView.isHidden = false
}else if (node.name == "blockSprite"){//选中空地
if selIndex >= 0{//已经选中备战卡片
selPrepareCardView.isHidden = true
let selData = prepareCardList[selIndex] as! NSDictionary
let remainingPrepare = selData.value(forKey: "remainingPrepare1") as! Int
if remainingPrepare > 0{//该单位没有准备完成
selIndex = -1
return;
}
prepareCardList.removeObject(at: selIndex)
selIndex = -1
refreshPrepareView()
let x = Int((node.position.x - TD_Scene_OrSoClearance - TD_Block_Width / 2.0) / TD_Block_Width + 0.5)
let y = Int((node.position.y - TD_Game_TopClearance - TD_Block_Height / 2.0 - 50) / TD_Block_Height + 0.5)
_ = creatCartSprite(type: 0, coordinates: y * 100 + x,infoData: selData)
}
}else if(node.name == "startBtn"){
node.isHidden = true
takingAction()
}
}else{
}
}
func takingAction() {
aiLayout()
ourHeroSprite.actionCartData = ourHeroSprite.playCartData
enemyHeroSprite.actionCartData = enemyHeroSprite.playCartData
actionType = 1
pollingAction()
}
//ai布局 战斗开始时调用
func aiLayout(){
// String(format: "Card_%@",cardId)
let screeningList = NSMutableArray()
for i in 0..<aiPrepareCardList.count {
let item = NSMutableDictionary(dictionary: aiPrepareCardList[i] as! NSDictionary)
var remainingPrepare = item.value(forKey: "remainingPrepare1") as! Int
if remainingPrepare > 0{
remainingPrepare = remainingPrepare - 1
item.setValue(remainingPrepare, forKey: "remainingPrepare1")
aiPrepareCardList.replaceObject(at: i, with: item)
}else{
screeningList.add(item)
}
}
/*
Ai出怪规则
1、当我方半场内有敌方卡片存在,优先同一行出怪(在攻击范围内优先放置在最远处)
2、当我方英雄正在被攻击时,带有警戒属性的卡片,需放置在能攻击敌方的位置,优先前方
3、随机出怪
*/
for i in 0..<screeningList.count {
let item = screeningList[i] as! NSDictionary
if ourHeroSprite.enemySpriteList.count == 0 {
randomLayout(infoData: item)
aiPrepareCardList.remove(item)
}else{
for j in 0..<ourHeroSprite.enemySpriteList.count {
let cartSprite = ourHeroSprite.enemySpriteList[j];
if canResist(cartSprite: cartSprite, item: item){
aiPrepareCardList.remove(item)
continue
}
if j == ourHeroSprite.enemySpriteList.count - 1{
randomLayout(infoData: item)
aiPrepareCardList.remove(item)
break
}
}
}
}
}
//判断 是否能攻击到我方主场内的敌人
func canResist(cartSprite:TD_CartSprite,item:NSDictionary) -> Bool {
let newCartSprite = creatCartSprite(type: 1, infoData: item)
var keys = [Int]()
if newCartSprite.isScope == 1 {//警戒属性
keys.append(cartSprite.coordinates + 100 - 1)
keys.append(cartSprite.coordinates + 100)
keys.append(cartSprite.coordinates + 100 + 1)
keys.append(cartSprite.coordinates + 1)
keys.append(cartSprite.coordinates - 100 + 1)
keys.append(cartSprite.coordinates - 100)
keys.append(cartSprite.coordinates - 100 - 1)
keys.append(cartSprite.coordinates - 1)
}else{
for i in 0..<newCartSprite.attackScope {
keys.append(cartSprite.coordinates + newCartSprite.attackScope - i)
}
}
for key in keys {
if key / 100 < 0 || key / 100 > 4{//上下越界
}else if key % 100 < 0 || key % 100 > 11{//左右越界
}else if (playCardData[key] == nil){//有空位
let arcX = key % 100
let arcY = key / 100
_ = creatCartSprite(type: 1, coordinates: Int(arcX+arcY*100),infoData:item )
return true
}
}
return false
}
//随机布置单位
func randomLayout(infoData:NSDictionary){
let number = getRandomCoordinates(type: 1)
let arcX = number % 100
let arcY = number / 100
_ = creatCartSprite(type: 1, coordinates: Int(arcX+arcY*100),infoData:infoData )
}
//随机空闲坐标
func getRandomCoordinates(type:Int) -> Int {
while true {
var arcX = 0
var arcY = 0
if type == 1{//敌方
arcX = Int(11 - arc4random()%4)
arcY = Int(4 - arc4random()%5)
}else{
arcX = Int(arc4random()%4)
arcY = Int(arc4random()%5)
}
let number = arcX + arcY * 100
if (playCardData[number] == nil){
return number
}
}
}
//开始战斗
func pollingAction(){
var type = -1
if actionType == 0{
if enemyHeroSprite.actionCartData.count > 0{
type = 1
actionType = 1
}else if ourHeroSprite.actionCartData.count > 0{
type = 0
actionType = 0
}else{
thatCard(isFirst: false)
return
}
}else if actionType == 1{
if ourHeroSprite.actionCartData.count > 0{
type = 0
actionType = 0
}else if enemyHeroSprite.actionCartData.count > 0{
type = 1
actionType = 1
}else{
thatCard(isFirst: false)
return
}
}
var cartSprite = TD_CartSprite()
var heroSprite = TD_HeroSprite()
if type == 0 {
heroSprite = ourHeroSprite
}else{
heroSprite = enemyHeroSprite
}
for item in heroSprite.actionCartData{
if cartSprite.coordinates == -1{
cartSprite = item.value
}else if type == 0 && item.value.coordinates > cartSprite.coordinates{
cartSprite = item.value
}else if type == 1 && item.value.coordinates < cartSprite.coordinates{
cartSprite = item.value
}
}
if type == 0 {
ourHeroSprite.actionCartData.removeValue(forKey: cartSprite.coordinates)
}else{
enemyHeroSprite.actionCartData.removeValue(forKey: cartSprite.coordinates)
}
// heroSprite.actionCartData.removeValue(forKey: cartSprite.coordinates)
cartSprite.action()
}
//刷新战场布局数据
func refreshData(oldKey:Int,newKey:Int) {
if (playCardData[oldKey] != nil){
let item = playCardData[oldKey]
playCardData.removeValue(forKey: oldKey)
playCardData[newKey] = item
}
if (ourHeroSprite.playCartData[oldKey] != nil){
let item = ourHeroSprite.playCartData[oldKey]
ourHeroSprite.playCartData.removeValue(forKey: oldKey)
ourHeroSprite.playCartData[newKey] = item
}
if (enemyHeroSprite.playCartData[oldKey] != nil){
let item = enemyHeroSprite.playCartData[oldKey]
enemyHeroSprite.playCartData.removeValue(forKey: oldKey)
enemyHeroSprite.playCartData[newKey] = item
}
for item in playCardData {
let cart = item.value
for cartSprite in cart.attackTargetEnemy{
if cartSprite.coordinates == oldKey {
cartSprite.coordinates = newKey
}
}
for cartSprite in cart.attackTargetOur{
if cartSprite.coordinates == oldKey {
cartSprite.coordinates = newKey
}
}
}
}
func removeSptiye(key:Int) {
if (playCardData[key] != nil){
playCardData.removeValue(forKey: key)
}
if (ourHeroSprite.playCartData[key] != nil){
ourHeroSprite.playCartData.removeValue(forKey: key)
}
if (enemyHeroSprite.playCartData[key] != nil){
enemyHeroSprite.playCartData.removeValue(forKey: key)
}
if (enemyHeroSprite.actionCartData[key] != nil){
enemyHeroSprite.actionCartData.removeValue(forKey: key)
}
if (ourHeroSprite.actionCartData[key] != nil){
ourHeroSprite.actionCartData.removeValue(forKey: key)
}
for item in playCardData {
let cart = item.value
for cartSprite in cart.attackTargetEnemy{
if cartSprite.coordinates == key {
let index = cart.attackTargetEnemy.index(of: cartSprite)
if index != nil{
cart.attackTargetEnemy.remove(at: index!)
}
}
}
for cartSprite in cart.attackTargetOur{
if cartSprite.coordinates == key {
let index = cart.attackTargetOur.index(of: cartSprite)
if index != nil{
cart.attackTargetOur.remove(at: index!)
}
}
}
}
}
func thereAreUnits(coordinates:Int) -> Bool {
if (playCardData[coordinates] != nil){
return true
}else{
return false
}
}
//判断时候需要继续前进(判断前方战场在行动力结束之前是否有落脚点)
func performMobile(step:Int,coordinates:Int,mobile:Int) -> Bool {
var key = coordinates
let x = coordinates % 100
var max = 0
if step > 0 {
max = min(11 - x, mobile)
}else{
max = min(x, mobile)
}
for _ in 0..<max {
key = key + step
if playCardData[key] == nil{
return true
}
}
return false
}
//设置物理属性
func setPhysicsBody(){
physicsWorld.gravity = CGVector.init(dx: 0, dy: 0)//重力
physicsWorld.contactDelegate = self
physicsWorld.speed = 1
physicsBody = SKPhysicsBody.init(edgeLoopFrom: self.frame)//物理世界的边界
// physicsBody?.contactTestBitMask = TD_ProtagonistCategory | TD_MonsterCategory //产生碰撞的物理类型
physicsBody?.categoryBitMask = TD_WorldCategory //标记自身的物理类型
// physicsBody?.friction = 0 //阻力 为零时完全反弹
}
//开始接触碰撞
func didBegin(_ contact: SKPhysicsContact) {
let bodyA = contact.bodyA
let bodyB = contact.bodyB
print("bodyA",bodyA.categoryBitMask)
print("bodyB",bodyB.categoryBitMask)
// print("bodyB.name:",bodyA.node?.name)
// print("bodyB.name:",bodyB.node?.name)
if bodyA.categoryBitMask == TD_OurHeroCategory { //我方英雄
if bodyB.categoryBitMask == TD_EnemyCartAttackCategory{//敌方卡片攻击范围
let cartSprite = getCartSprite(body: bodyB)
cartSprite.isArrackHero = true
}
}
else if bodyA.categoryBitMask == TD_EnemyHeroCategory{//敌方英雄
if bodyB.categoryBitMask == TD_OurCartAttackCategory{//敌方卡片攻击范围
let cartSprite = getCartSprite(body: bodyB)
cartSprite.isArrackHero = true
}
}
else if bodyA.categoryBitMask == TD_OurHeroHomeCategory{//我方主场
if bodyB.categoryBitMask == TD_OurCartCategory{//我方方卡片
let cartSpriteB = bodyB.node as! TD_CartSprite
ourHeroSprite.ourSpriteList.append(cartSpriteB)
}
else if bodyB.categoryBitMask == TD_EnemyCartCategory{//敌方卡片
let cartSpriteB = bodyB.node as! TD_CartSprite
ourHeroSprite.enemySpriteList.append(cartSpriteB)
}
}
else if bodyA.categoryBitMask == TD_EnemyHeroHomeCategory{//敌方主场
if bodyB.categoryBitMask == TD_OurCartCategory{//我方卡片
let cartSpriteB = bodyB.node as! TD_CartSprite
enemyHeroSprite.ourSpriteList.append(cartSpriteB)
}
else if bodyB.categoryBitMask == TD_EnemyCartCategory{//敌方卡片
let cartSpriteB = bodyB.node as! TD_CartSprite
enemyHeroSprite.enemySpriteList.append(cartSpriteB)
}
}
else if bodyA.categoryBitMask == TD_OurCartCategory{//我方卡片
let cartSpriteA = bodyA.node as! TD_CartSprite
if bodyB.categoryBitMask == TD_OurCartAttackCategory{//我方卡片
let cartSprite = getCartSprite(body: bodyB)
cartSprite.attackTargetOur.append(cartSpriteA)
}else if bodyB.categoryBitMask == TD_EnemyCartAttackCategory{//敌方卡片攻击范围
let cartSprite = getCartSprite(body: bodyB)
cartSprite.attackTargetEnemy.append(cartSpriteA)
}
}
else if bodyA.categoryBitMask == TD_EnemyCartCategory{//敌方卡片
let cartSpriteA = bodyA.node as! TD_CartSprite
if bodyB.categoryBitMask == TD_OurCartAttackCategory{//我方卡片攻击范围
let cartSprite = getCartSprite(body: bodyB)
cartSprite.attackTargetEnemy.append(cartSpriteA)
}else if bodyB.categoryBitMask == TD_EnemyCartAttackCategory{//敌方卡片攻击范围
let cartSprite = getCartSprite(body: bodyB)
cartSprite.attackTargetOur.append(cartSpriteA)
}
}else if bodyA.categoryBitMask == TD_OurCartAttackCategory{//我方卡片攻击范围
let cartSpriteA = getCartSprite(body: bodyA)
if bodyB.categoryBitMask == TD_OurCartCategory{//我方卡片
let cartSpriteB = bodyB.node as! TD_CartSprite
cartSpriteA.attackTargetOur.append(cartSpriteB)
}else if bodyB.categoryBitMask == TD_EnemyCartCategory{//敌方卡片
let cartSpriteB = bodyB.node as! TD_CartSprite
cartSpriteA.attackTargetEnemy.append(cartSpriteB)
}
}else if bodyA.categoryBitMask == TD_EnemyCartAttackCategory{//敌方卡片攻击范围
let cartSpriteA = getCartSprite(body: bodyA)
if bodyB.categoryBitMask == TD_OurCartCategory{//我方卡片
let cartSpriteB = bodyB.node as! TD_CartSprite
cartSpriteA.attackTargetEnemy.append(cartSpriteB)
}else if bodyB.categoryBitMask == TD_EnemyCartCategory{//敌方卡片
let cartSpriteB = bodyB.node as! TD_CartSprite
cartSpriteA.attackTargetOur.append(cartSpriteB)
}
}
}
//结束碰撞
func didEnd(_ contact: SKPhysicsContact) {
// let bodyA = contact.bodyA
// let bodyB = contact.bodyB
}
/// 根据攻击范围实例获取卡片对象
///
/// - Parameter body: 攻击范围body
/// - Returns: 卡片对象
func getCartSprite(body:SKPhysicsBody) -> TD_CartSprite {
for item in playCardData {
if item.value.attackScopeSprite.physicsBody == body{
return item.value
}
}
return TD_CartSprite()
}
/// 攻击目标
///
/// - Parameters:
/// - attack: 攻击力
/// - cardSprite: 攻击目标
/// - attackType: 伤害类型 1:物理伤害、1:魔法伤害
/// - Returns: 是否击杀目标
func target(attack:Int,cardSprite:TD_CartSprite,attackType:Int) -> Bool {
if cardSprite.beingAttacked(attack: attack, attackType: attackType) {
return true
}
return false
}
}
<file_sep>/TD_WaterMargin/TD_WaterMargin/Classes/Sprite/TD_MonsterSprite.swift
//
// TD_MonsterSprite.swift
// TD_WaterMargin
//
// Created by mac on 2018/9/13.
// Copyright © 2018年 DAA. All rights reserved.
//
import SpriteKit
class TD_MonsterSprite: TD_BaseSpriteNode {
var monsterType = "1" //怪物种类
var soldierName:String = "步兵" //士兵名称
var image = "soldier" //士兵图片名称
var expenditure:Double = 2.0 //召唤消耗
var energy:Double = 2.0 //击杀获得的能量
var maxHP:Double = 0.0 //最大生命值
var armor:Double = 0.0 //基础护甲
var moveSpeed:Double = 50.0 //移动速度
var attackSpeed:Double = 1.0 //攻击速度 x秒/次
var alertScope:Double = 50.0 //警戒范围半径
var attackScope:Double = 20.0 //攻击范围半径
var attackNumber:Int = 1 //单次攻击最大数量
var attackBumberOfTimes:Int = 1 //单次攻击造成伤害次数
var attackGif = "attack" //攻击动画gif
var moveGif = "towerMove" //移动动画gif
var harm:Double = 1.0 //造成伤害值
var isFirst:Bool = true //是否是第一次出现
var intro = "基础近战兵种" //兵种介绍
var HP:Double = 0.0 //单位当前剩余生命
var temporaryDebuffArmor:Double = 0.0 //临时减益护甲 当前护甲等于临时护甲+基础护甲
var temporaryDebufMoveSpeed:Double = 0.0 //临时减益移动速度 当前速度等于临时移动速度+基础移动速度
var temporaryArmorTimer = Timer() //记录临时护甲timer
var temporaryMoveSpeedTimer = Timer() //记录临时移动速度timer
var articleBloodSprite = SKSpriteNode() //血条显示控件
var targetPosition = CGPoint() //目的地坐标
var isAggressive = Bool() //是否有攻击性的(主动攻击)
func layout(monsterType:String){
self.monsterType = monsterType
initSoldierProperty(type: monsterType)
initPhysicsBody()
moveToTargetPosition(targetPosition: targetPosition)
creatView()
}
/// 初始化小兵属性
func initSoldierProperty(type:String){
let data = TD_AnalyticalDataObject().getFileData(fileName: "Monster") as! [NSString : NSDictionary]
let soldierInfo = data[NSString(format: "Monster_%@",type)]
soldierName = soldierInfo!["Name"] as! String
image = soldierInfo!["Image"] as! String
expenditure = Double(soldierInfo!["Expenditure"] as! String)!
energy = Double(soldierInfo!["Energy"] as! String)!
maxHP = Double(soldierInfo!["HP"] as! String)!
armor = Double(soldierInfo!["Armor"] as! String)!
moveSpeed = Double(soldierInfo!["Speed"] as! String)!
attackSpeed = Double(soldierInfo!["AttackSpeed"] as! String)!
alertScope = Double(soldierInfo!["ScopeAlert"] as! String)!
attackScope = Double(soldierInfo!["ScopeAttack"] as! String)!
attackNumber = Int(soldierInfo!["AttackNumber"] as! String)!
attackBumberOfTimes = Int(soldierInfo!["AttackBumberOfTimes"] as! String)!
attackGif = soldierInfo!["AttackGif"] as! String
moveGif = soldierInfo!["MoveGif"] as! String
harm = Double(soldierInfo!["Harm"] as! String)!
isFirst = soldierInfo!["IsFirst"] as! Bool
intro = soldierInfo!["Intro"] as! String
HP = maxHP
}
/// 初始化物理属性
func initPhysicsBody(){
physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: size.width / 2.0, height: size.height / 2.0))
// physicsBody?.
// physicsBody?.density = 1 //密度
physicsBody?.mass = 1 //质量
physicsBody?.restitution = 0 //弹性
physicsBody?.friction = 0.0 //摩擦力
physicsBody?.linearDamping = 0 //线性阻力(空气阻力)
physicsBody?.allowsRotation = true
physicsBody?.affectedByGravity = false
physicsBody?.contactTestBitMask = TD_TowerAttackCategory //碰撞检测
physicsBody?.collisionBitMask = 0 //碰撞效果
physicsBody?.categoryBitMask = TD_MonsterCategory
}
func creatView(){
if articleBloodSprite.name == nil{
articleBloodSprite = SKSpriteNode(color: UIColor.red, size: CGSize(width: TD_Block_Width, height: 5))
articleBloodSprite.position = CGPoint(x: position.x, y: position.y + size.height / 2.0)
articleBloodSprite.name = "articleBloodSprite"
superScene.addChild(articleBloodSprite)
}
}
func moveToTargetPosition(targetPosition:CGPoint){
let pathPlanning = TD_PathPlanning()
pathPlanning.startRect = CGRect(x: position.x - TD_Block_Width / 2.0, y: position.y - TD_Block_Width / 2.0, width: TD_Block_Width, height: TD_Block_Width)
let mapData = (superScene as! TD_ScenarioScene).mapData as! [NSArray]
pathPlanning.mapData = mapData
pathPlanning.endRect = CGRect(x: targetPosition.x - TD_Block_Width / 2.0, y: targetPosition.y - TD_Block_Width / 2.0, width: TD_Block_Width, height: TD_Block_Width)
pathPlanning.mapStartPoint = CGPoint(x: 10, y: TD_Game_TopClearance)
pathPlanning.getPathPlanning { (callBack) in
let paths = NSMutableArray()
for i in 0..<callBack.count {
let point = callBack[i] as! CGPoint
paths.add(CGPoint(x: point.x + TD_Block_Width / 2.0 + 10, y: point.y + TD_Game_TopClearance + TD_Block_Width / 2.0))
}
self.runActionGif(fileName: self.moveGif as NSString, isRepeat: true, key:"move")
self.movePaths(paths: paths, startPoint: CGPoint(x: self.position.x, y: self.position.y), key: "move", runType: 1)
let mPaths = NSMutableArray(array: paths)
mPaths.removeObject(at: 0)
self.moveArticleBloodSprite(paths: mPaths)
}
}
func moveArticleBloodSprite(paths:NSArray) {
let mPaths = NSMutableArray(array: paths)
let point = mPaths.firstObject as! CGPoint
mPaths.removeObject(at: 0)
let action = SKAction.move(to: CGPoint(x: point.x, y: point.y + size.height / 2.0), duration:TimeInterval(TD_Block_Width / CGFloat(moveSpeed)))
articleBloodSprite.run(action) {
if self.articleBloodSprite.name == nil{
return
}
if mPaths.count >= 1{
self.moveArticleBloodSprite(paths: mPaths)
}
}
}
func movePaths(paths:NSArray,startPoint:CGPoint,key:String,runType:Int){
let action = TD_Action().action(paths: paths, startPoint: startPoint, moveSpeed: CGFloat(moveSpeed) * (100.0 - CGFloat(temporaryDebufMoveSpeed)) / 100.0)
runActionWithThisOrScope(action: action, key: key,runType: runType)
}
func runActionWithThisOrScope(action:SKAction,key:String,runType:Int){
if runType == 1 {
self.run(action) {
self.removeAllFromParent()
(self.superScene as! TD_ScenarioScene).breakthrough(monster: self)
}
}else{
run(action, withKey: key)
}
}
func removeAllFromParent(){
removeFromParent()
articleBloodSprite.name = nil
articleBloodSprite.removeFromParent()
}
/// 护甲被改变调用
///
/// - Parameters:
/// - temporaryArmor: 临时改变的护甲
/// - time: 改变持续时间
func setTemporaryArmor(temporaryArmor:Double,time:Double) {
if self.temporaryDebuffArmor > temporaryArmor {
return
}
self.temporaryArmorTimer.invalidate() //停止
self.temporaryDebuffArmor = temporaryArmor
temporaryArmorTimer = Timer.init(timeInterval: time, repeats: true) { (kTimer) in
self.temporaryArmorTimer.invalidate() //停止
self.temporaryDebuffArmor = 0
self.removeAction(key: "move")
self.moveToTargetPosition(targetPosition: self.targetPosition)
}
RunLoop.current.add(temporaryArmorTimer, forMode: .defaultRunLoopMode)
// TODO : 启动定时器
temporaryArmorTimer.fire()
}
/// 速度被改变调用
///
/// - Parameters:
/// - temporaryMoveSpeed: 临时改变的速度
/// - time: 改变持续时间
func setTemporaryMoveSpeed(temporaryMoveSpeed:Double,time:Double){
if self.temporaryDebufMoveSpeed > temporaryMoveSpeed {
return
}
self.temporaryMoveSpeedTimer.invalidate() //停止
self.temporaryDebufMoveSpeed = temporaryMoveSpeed
removeAction(forKey: "move")
// moveToTargetPosition(targetPosition: targetPosition)
temporaryMoveSpeedTimer = Timer.init(timeInterval: time, repeats: true) { (kTimer) in
self.temporaryMoveSpeedTimer.invalidate() //停止
self.temporaryDebufMoveSpeed = 0
self.removeAction(forKey: "move")
// self.moveToTargetPosition(targetPosition: self.targetPosition)
}
RunLoop.current.add(temporaryMoveSpeedTimer, forMode: .defaultRunLoopMode)
// TODO : 启动定时器
temporaryMoveSpeedTimer.fire()
}
/// 被攻击调用
///
/// - Parameter damage: 攻击造成的伤害
/// - Returns: 是否被击杀
func beingAttacked(damage:Double) -> Bool {
HP = HP - actualDamage(damage: damage)
articleBloodSprite.size = CGSize(width: TD_Block_Width * CGFloat(HP / maxHP), height: articleBloodSprite.size.height)
if (HP <= 0){//被击杀
(superScene as! TD_ScenarioScene).destroyed(monster: self)
(superScene as! TD_ScenarioScene).collectEnergy(energy: energy)
return true
}else{
return false
}
}
func actualDamage(damage:Double) -> Double {
let arm = armor + temporaryDebuffArmor
return damage * pow(0.95, arm)
}
// MARK: 类销毁时,通知此方法
deinit {
print("销毁")
}
}
<file_sep>/TD_AncientRuins/TD_AncientRuins/Classes/Lib/TD_PlayMusic.swift
//
// TD_PlayMusic.swift
// TD_KnockIce
//
// Created by mac on 2018/7/19.
// Copyright © 2018年 DAA. All rights reserved.
//
import SpriteKit
import AVFoundation
class TD_PlayMusic: SKNode {
func playMusic(musicName:String){
let backgroundMusicURL = Bundle.main.url(forResource: musicName, withExtension: nil)
let theme = try! AVAudioPlayer(contentsOf: backgroundMusicURL!)
// if !GameScene.backgroundMusicPlayer.isPlaying {
theme.play()
}
}
<file_sep>/TD_PingPongBalls/TD_PingPongBalls/Classes/Sprite/TD_TowerSprite.swift
//
// TD_TowerSprite.swift
// TD_WaterMargin
//
// Created by mac on 2018/9/17.
// Copyright © 2018年 DAA. All rights reserved.
//
import UIKit
import SpriteKit
class TD_TowerSprite: TD_BaseSpriteNode {
var totalValue:Double = 0.0
var soldierName:String = "步兵" //士兵名称
var image = "soldier" //士兵图片名称
var expenditure:Double = 2.0 //召唤消耗
var upExpenditure:Double = 2.0 //升级消耗
var maxHP:Double = 0.0 //最大生命值
var moveSpeed:Double = 50.0 //移动速度
var attackSpeed:Double = 1.0 //攻击速度 x秒/次
var alertScope:Double = 50.0 //警戒范围半径
var attackScope:Double = 20.0 //攻击范围半径
var attackNumber:Int = 1 //单次攻击最大数量
var attackBumberOfTimes:Int = 1 //单次攻击造成伤害次数
var attackGif = "attack" //攻击动画gif
var attackImg = "attack" //攻击能量球图片
var attackType = "1" //攻击类型 1、单体(散射)2、群体(范围)
var attackRadius:Double = 10.0 //伤害范围
var attackSpecialEffects = "0" //攻击特效 0、无特效 1、减速 2、击晕 3、减甲
var specialEffectsNumber:Double = 10.0 //攻击特效效果 例如 减速(击晕)指减速百分比 减甲指减甲数据
var specialEffectsDuration:Double = 1.0 //攻击特效持续时间
var specialEffectsprobability:Double = 0.0 //触发特效概率
var moveGif = "towerMove" //移动动画gif
var harm:Double = 1.0 //造成伤害值
var maxLevel:Int = 1 //可升至最高级别
var isFirst:Bool = true //是否是第一次出现
var intro = "基础近战兵种" //兵种介绍
var HP:Double = 0.0 //单位当前剩余生命
var confirmBuild = SKNode() //用来显示是否确认建造视图
var scopeAttack = SKSpriteNode() //防御塔攻击范围显示
var operationMenuView = SKNode() //防御塔操作视图
var towerType = 0 //防御塔类型
var level = 1 //防御塔级别
var towerSprite = SKSpriteNode() //防御塔实例
var attackTarget = [TD_MonsterSprite]() //防御塔正在攻击的目标
var isActivate = false{ //标记防御塔是否已经激活
willSet {
print("attackRange即将发生改变")
}
didSet {
if oldValue == false{
updataAttack()
}
}
}
var attackRange = [TD_MonsterSprite](){ //攻击范围内的怪物
willSet {
print("attackRange即将发生改变")
}
didSet {
if oldValue.count == 0 {
// isActive = true
updataAttack()
}else if oldValue.count == 1 && attackRange.count == 0{
// isActive = false
attackTarget.removeAll()
}
print("attackRange已经发生改变")
}
}
var energyBallList = [TD_EnergyBallSprite]()
func layout(towerType:Int){
self.towerType = towerType
refresh()
}
/// 初始化小兵属性
func initTowerProperty(type:Int){
let data = TD_AnalyticalDataObject().getFileData(fileName: "Towers") as! [NSString : NSDictionary]
let soldierInfo = data[NSString(format: "Towers_%d_%d",type,level)]
soldierName = soldierInfo!["Name"] as! String
image = soldierInfo!["Image"] as! String
expenditure = Double(soldierInfo!["Expenditure"] as! String)!
upExpenditure = Double(soldierInfo!["UpExpenditure"] as! String)!
maxHP = Double(soldierInfo!["HP"] as! String)!
moveSpeed = Double(soldierInfo!["Speed"] as! String)!
attackSpeed = Double(soldierInfo!["AttackSpeed"] as! String)!
alertScope = Double(soldierInfo!["ScopeAlert"] as! String)!
attackScope = Double(soldierInfo!["ScopeAttack"] as! String)!
attackNumber = Int(soldierInfo!["AttackNumber"] as! String)!
attackBumberOfTimes = Int(soldierInfo!["AttackBumberOfTimes"] as! String)!
attackGif = soldierInfo!["AttackGif"] as! String
attackImg = soldierInfo!["AttackImg"] as! String
attackType = soldierInfo!["AttackType"] as! String
attackRadius = Double(soldierInfo!["AttackRadius"] as! String)!
attackSpecialEffects = soldierInfo!["AttackSpecialEffects"] as! String
specialEffectsNumber = Double(soldierInfo!["SpecialEffectsNumber"] as! String)!
specialEffectsDuration = Double(soldierInfo!["SpecialEffectsDuration"] as! String)!
specialEffectsprobability = Double(soldierInfo!["SpecialEffectsprobability"] as! String)!
intro = soldierInfo!["Intro"] as! String
moveGif = soldierInfo!["MoveGif"] as! String
harm = Double(soldierInfo!["Harm"] as! String)!
maxLevel = Int(soldierInfo!["MaxLevel"] as! String)!
isFirst = soldierInfo!["IsFirst"] as! Bool
intro = soldierInfo!["Intro"] as! String
HP = maxHP
}
func refresh() {
initTowerProperty(type: towerType)
refreshTowerSprite()
}
func refreshTowerSprite(){
if towerSprite.name == TD_Name_TowerSprite{
towerSprite.removeFromParent()
}
towerSprite = SKSpriteNode(imageNamed:image)
towerSprite.name = TD_Name_TowerSprite
towerSprite.position = position
towerSprite.size = size
superScene.addChild(towerSprite)
}
func showConfirmBuild() {
if confirmBuild.name == nil{
confirmBuild.name = "confirmBuild"
confirmBuild.position = CGPoint(x: position.x, y: position.y + size.height + 10)
confirmBuild.zPosition = 11
confirmBuild.isHidden = true
superScene.addChild(confirmBuild)
let confirmItem = SKSpriteNode(imageNamed: "confirm")
confirmItem.position = CGPoint(x: -20, y: -10)
confirmItem.size = CGSize(width: 30, height: 30)
confirmItem.name = TD_Name_ConfirmItem
confirmBuild.addChild(confirmItem)
let cancelItem = SKSpriteNode(imageNamed: "cancel")
cancelItem.position = CGPoint(x: 15, y: -10)
cancelItem.size = CGSize(width: 30, height: 30)
cancelItem.name = TD_Name_CancelItem
confirmBuild.addChild(cancelItem)
}
confirmBuild.isHidden = false
}
func hiddenConfirmBuild(){
confirmBuild.isHidden = true
}
func showScopeAttack(){
if scopeAttack.name == nil{
scopeAttack = SKSpriteNode(imageNamed: "scope_ round")
scopeAttack.size = CGSize(width: CGFloat(attackScope) + size.width, height: CGFloat(attackScope) + size.width)
scopeAttack.name = TD_Name_ScopeAttack
scopeAttack.position = position
superScene.addChild(scopeAttack)
scopeAttack.physicsBody = SKPhysicsBody(circleOfRadius: scopeAttack.size.width / 2.0)
// physicsBody?.density = 0 //密度
scopeAttack.physicsBody?.mass = 1 //质量
scopeAttack.physicsBody?.restitution = 0 //弹性
scopeAttack.physicsBody?.friction = 0.0 //摩擦力
scopeAttack.physicsBody?.linearDamping = 0.0 //线性阻力(空气阻力)
scopeAttack.physicsBody?.allowsRotation = false
scopeAttack.physicsBody?.affectedByGravity = false
// physicsBody?.collisionBitMask = TD_MonsterCategory //碰撞效果
// physicsBody?.contactTestBitMask = TD_MonsterCategory//碰撞检测
scopeAttack.physicsBody?.collisionBitMask = 0 //不会产生被碰撞效果
scopeAttack.physicsBody?.categoryBitMask = TD_TowerAttackCategory
scopeAttack.isHidden = true
scopeAttack.zPosition = 10
}
scopeAttack.isHidden = false
}
func hiddenScopeAttack(){
scopeAttack.isHidden = true
}
func showOperationMenuView(){
if operationMenuView.name == nil{
operationMenuView.name = "operationMenuView"
operationMenuView.position = CGPoint(x: position.x, y: position.y - size.height)
operationMenuView.zPosition = 11
operationMenuView.isHidden = true
superScene.addChild(operationMenuView)
let upgradeItem = SKSpriteNode(imageNamed: "upgrade")
upgradeItem.position = CGPoint(x: -35, y: -10)
upgradeItem.size = CGSize(width: 30, height: 30)
upgradeItem.name = TD_Name_UpgradeItem
operationMenuView.addChild(upgradeItem)
let sellItem = SKSpriteNode(imageNamed: "sell")
sellItem.position = CGPoint(x: 0, y: -10)
sellItem.size = CGSize(width: 30, height: 30)
sellItem.name = TD_Name_SellItem
operationMenuView.addChild(sellItem)
let returnItem = SKSpriteNode(imageNamed: "return")
returnItem.position = CGPoint(x: 35, y: -10)
returnItem.size = CGSize(width: 30, height: 30)
returnItem.name = TD_Name_ReturnItem
operationMenuView.addChild(returnItem)
}
operationMenuView.isHidden = false
}
func hiddenOperationMenuView(){
operationMenuView.isHidden = true
}
func removeAllFromParent(){
removeFromParent()
confirmBuild.removeFromParent()
scopeAttack.removeFromParent()
towerSprite.removeFromParent()
operationMenuView.removeFromParent()
}
func updataAttack(){
if attackRange.count >= 1 && isActivate{
if attackTarget.count != attackNumber && attackRange.count != attackTarget.count{
attackTarget.removeAll()
for i in 0..<attackRange.count {
attackTarget.append(attackRange[i])
if attackTarget.count == attackNumber{
attack()
break;
}
}
}else{
attack()
}
}else{
return
}
let time: TimeInterval = attackSpeed
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) {
self.updataAttack()
}
}
func attack() {
if attackType == "1" {//单体(散射攻击)
for i in 0..<attackTarget.count {
attackToMonster(monster: attackTarget[i])
}
}else if attackType == "2"{//群体攻击(范围攻击)
let energyBallSprite = TD_EnergyBallSprite(imageNamed: "roundness")
energyBallSprite.size = CGSize(width: attackRadius, height: attackRadius)
energyBallSprite.position = position
superScene.addChild(energyBallSprite)
energyBallSprite.layout()
energyBallList.append(energyBallSprite)
let paths = NSMutableArray()
let endPosition = attackTarget[0].position
paths.add(position)
paths.add(CGPoint(x: (endPosition.x + position.x ) / 2.0, y: (endPosition.y + position.y) / 2.0 + (endPosition.y - position.y) * 0.7))
paths.add(endPosition)
let action = TD_Action().action(paths: paths, startPoint: position, moveSpeed: 300)
energyBallSprite.run(action) {
let index = self.energyBallList.index(of: energyBallSprite)
if index != nil{
self.energyBallList.remove(at: index!)
}
energyBallSprite.removeFromParent()
}
}
}
func attackToMonster(monster:TD_MonsterSprite) {
let attackSprite = SKSpriteNode(imageNamed: attackImg)
attackSprite.size = CGSize(width: 10, height: 10)
attackSprite.position = CGPoint(x: position.x, y: position.y + size.height / 2.0)
superScene.addChild(attackSprite)
let action = SKAction.move(to: monster.position, duration: 0.10)
attackSprite.run(action) {
attackSprite.removeFromParent()
if monster.beingAttacked(damage:self.harm) {
}
self.triggerAttackSpecialEffects(monster: monster)
}
}
func damageToMonster(monster:TD_MonsterSprite) {
if monster.beingAttacked(damage:self.harm) {
}
triggerAttackSpecialEffects(monster: monster)
}
func triggerAttackSpecialEffects(monster:TD_MonsterSprite){
if attackSpecialEffects == "0" {//无特效直接跳过
return
}
if (Double)(arc4random() % 100) <= specialEffectsprobability {
if attackSpecialEffects == "1"{//减速
monster.setTemporaryMoveSpeed(temporaryMoveSpeed: specialEffectsNumber, time: specialEffectsDuration)
}else if attackSpecialEffects == "2"{//击晕
monster.setTemporaryMoveSpeed(temporaryMoveSpeed: specialEffectsNumber, time: specialEffectsDuration)
}else if attackSpecialEffects == "3"{//减甲
monster.setTemporaryArmor(temporaryArmor: specialEffectsNumber, time: specialEffectsDuration)
}
}
}
}
<file_sep>/TD_ Journey/TD_ Journey/Classes/Lib/TD_PathPlanning.swift
//
// TD_PathPlanning.swift
// TD_AttackAndDefence
//
// Created by mac on 2018/8/23.
// Copyright © 2018年 DAA. All rights reserved.
//
import UIKit
import SpriteKit
class TD_PathPlanning: NSObject {
var obstaclesRectList = [CGRect]() //障碍物rect数组
var startRect = CGRect()
var endRect = CGRect()
let width = TD_Block_Width
var formattingStartRect = CGRect()
var formattingEndRect = CGRect()
var mapStartPoint = CGPoint()
var mapData = [NSArray]()
//swift中闭包传值
func getPathPlanning(completion: @escaping (_ result : [Any])->()) -> () {
//这里有一个很重要的参数 @escaping,逃逸闭包
//简单来说就是 闭包在这个函数结束前内被调用,就是非逃逸闭包,调用的地方超过了这函数的范围,叫逃逸闭包
//一般网络请求都是请求后一段时间这个闭包才执行,所以都是逃逸闭包。
// 在Swift3.0中所有的闭包都默认为非逃逸闭包,所以需要用@escaping来修饰
DispatchQueue.global().async {
print("耗时操作\(Thread.current)")
if (self.mapData.count < 1){
self.mapData = self.getMapDict(width: self.width)
}
let paths = self.getPathPlanning()
// Thread.sleep(forTimeInterval: 2)
// let json=["1","2"]
DispatchQueue.main.async {
// print("主线程更新\(Thread.current)")
completion(paths as! [Any])
//函数在执行完后俩秒,主线程才回调数据,超过了函数的范围,这里就是属于逃逸闭包,如果不用@escaping,编译器是编译不过的
}
}
}
/// 获取地图数据
///
/// - Parameter width: 前进最小单位
/// - Returns: 地图数据
func getMapDict(width:CGFloat) -> [NSArray] {
let mapData = NSMutableArray()
for index_x in 0..<18 {
let lineData = NSMutableArray()
mapData.add(lineData)
for index_y in 0..<9 {
lineData.add(0)
let rc = CGRect(x: width * CGFloat(index_x) + 10, y: CGFloat(index_y) * width + TD_Game_TopClearance, width: width, height: width)
for index in 0..<obstaclesRectList.count {
let rect = obstaclesRectList[index]
if rc.intersects(rect){
lineData.removeLastObject()
lineData.add(1)
break
}
}
}
}
return mapData as! [NSArray]
}
/// 获取路径规划
///
/// - Returns: 路径数组
func getPathPlanning() -> NSArray {
let startI = Int((startRect.origin.x - mapStartPoint.x) / width + 0.5)
let startJ = Int((startRect.origin.y - mapStartPoint.y) / width + 0.5)
let endI = Int((endRect.origin.x - mapStartPoint.x) / width + 0.5)
let endJ = Int((endRect.origin.y - mapStartPoint.y) / width + 0.5)
formattingStartRect = CGRect(x: width * CGFloat(startI) , y: CGFloat(startJ) * width , width: width, height: width)
formattingEndRect = CGRect(x: width * CGFloat(endI) , y: CGFloat(endJ) * width , width: width, height: width)
let H = getDistance(point1: CGPoint(x: CGFloat(startI) * width, y: CGFloat(startJ) * width), point2: CGPoint(x: CGFloat(endI) * width, y: CGFloat(endJ) * width))
let startData = NSMutableArray()
startData.add([startI * 100 + startJ:["G":0.0,"H":H,"F":H]])
let paths = pathPlanning(openData:startData,closedDict: NSMutableDictionary())
return paths
}
/// 路径规划z递归执行方法
///
/// - Parameters:
/// - openData:算法筛选到的路径数组扩散(closedDict + 周围一层)
/// - closedDict: 算法筛选到的路径数组
/// - Returns: 路径数组
func pathPlanning(openData:NSMutableArray,closedDict:NSMutableDictionary) -> NSArray{
var minData = getDictMinValueList(key: "F", openData: openData as! [[Int : [String : Double]]],closedDict: closedDict as! [Int : Any])
minData = getDictMinValueList(key: "H", openData: minData,closedDict: closedDict as! [Int : Any])
var min_x = 0
var min_y = 0
let data = minData.first
for item in data! {
closedDict[item.key] = item.value
min_x = item.key / 100
min_y = item.key % 100
}
for i in 0..<4 {
var index_i = min_x
var index_j = min_y
var isEffective = true
switch i {
case 0://上
index_j = index_j + 1
if mapData.count <= index_j {
isEffective = false
}
break
case 1://下
index_j = index_j - 1
if index_j < 0 {
isEffective = false
}
break
case 2://左
index_i = index_i - 1
if index_i < 0 {
isEffective = false
}
break
case 3://右
index_i = index_i + 1
if mapData[index_j].count <= index_i {
isEffective = false
}
break
default:
break
}
let point = CGPoint(x: width * CGFloat(index_i), y: CGFloat(index_j) * width)
if point.x == formattingEndRect.origin.x && point.y == formattingEndRect.origin.y{//到达目的地
closedDict[index_i * 100 + index_j] = ["G":0.0,"H":0,"F":0]
return getOptimalPath(closedDict: closedDict)
}else if isEffective && mapData[index_j][index_i] as! Character == "0"{
let G = getDistance(point1: point, point2: CGPoint(x: formattingStartRect.origin.x, y: formattingStartRect.origin.y))
let H = getDistance(point1: point, point2: CGPoint(x: formattingEndRect.origin.x, y: formattingEndRect.origin.y))
let data = [index_i * 100 + index_j:["G":G,"H":H,"F":G+H]]
if openData.contains(data) == false{
openData.add([index_i * 100 + index_j:["G":G,"H":H,"F":G+H]])
}
}
}
if closedDict.count > 200 {
print("openData.count",openData.count)
print("closedDict.count",closedDict.count)
}
return pathPlanning(openData:openData, closedDict:closedDict)
}
/// 得到最优路径
///
/// - Parameter closedDict:算法筛选到的路径数组
/// - Returns: 最优路径
func getOptimalPath(closedDict:NSDictionary) -> NSArray {
let paths = NSMutableArray()
var X = Int(formattingEndRect.origin.x / width)
var Y = Int(formattingEndRect.origin.y / width)
paths.add(100 * X + Y)
for _ in 0..<closedDict.count {
var minF = 1000.0
var type = 0
for i in 0..<4 {
var index_j = Y
var index_i = X
switch i {
case 0://上
index_j = Y + 1
break
case 1://下
index_j = Y - 1
break
case 2://左
index_i = X - 1
break
case 3://右
index_i = X + 1
break
default:
break
}
if closedDict[index_i * 100 + index_j] != nil{
let data = closedDict[index_i * 100 + index_j] as! [String:Double]
if minF - data["G"]! > 0 && !paths.contains( index_i * 100 + index_j){
minF = data["G"]!
type = i
}
}
}
var index_j = Y
var index_i = X
switch type {
case 0://上
index_j = Y + 1
break
case 1://下
index_j = Y - 1
break
case 2://左
index_i = X - 1
break
case 3://右
index_i = X + 1
break
default:
break
}
X = index_i
Y = index_j
paths.add(index_i * 100 + index_j)
let point = CGPoint(x: width * CGFloat(index_i) , y: CGFloat(index_j) * width)
if point.x == formattingStartRect.origin.x && point.y == formattingStartRect.origin.y{
return getPaths(paths: paths)
}
}
return []
}
/// 路径转成实际父视图的坐标路径
///
/// - Parameter paths: 最优路径
/// - Returns: 最优路径数组
func getPaths(paths:NSArray) -> NSArray {
let rcList = NSMutableArray()
// let lastItem = paths.lastObject as! Int
// let startPoint = CGPoint(x: CGFloat(lastItem / 100) * width, y: CGFloat(lastItem % 100) * width)
for index in 0..<paths.count {
let item = paths[paths.count - 1 - index] as! Int
let point = CGPoint(x: CGFloat(item / 100) * width, y: CGFloat(item % 100) * width)
// rcList.add(CGRect(x: point.x, y: point.y, width: width, height: width))
rcList.add(point)
}
return rcList
}
/// 获取2点之间的距离
///
/// - Parameters:
/// - point1: 点1
/// - point2: 点2
/// - Returns: 距离
func getDistance(point1:CGPoint,point2:CGPoint) -> Double {
let distance = sqrt(pow(Double(point1.x - point2.x),2) + pow(Double(point1.y - point2.y),2))
return distance
}
/// 在字典中找到key值最小成员列表
///
/// - Parameters:
/// - key: key
/// - openData: 算法筛选到的路径数组扩散(closedDict + 周围一层)
/// - closedDict: 算法筛选到的路径数组
/// - Returns: key值最小的成员数组
func getDictMinValueList(key:String,openData:[[Int:[String:Double]]],closedDict:[Int:Any]) -> [[Int:[String:Double]]] {
var minValue = 1000.0
var minList = [[Int:[String:Double]]]()
for i in 0..<openData.count {
let dict = openData[i]
for data in dict{
let d = data.value
if closedDict[data.key] == nil {
if minValue - d[key]! > 0{
minValue = d[key]!
}
}
}
}
for i in 0..<openData.count {
let dict = openData[i]
for data in dict{
let d = data.value
if closedDict[data.key] == nil {
if minValue == d[key]!{
minList.append(dict)
}
}
}
}
return minList
}
}
<file_sep>/TD_ Journey/TD_ Journey/Classes/View/TD_IntroSprite.swift
//
// TD_IntroSprite.swift
// TD_ Journey
//
// Created by mac on 2018/11/12.
// Copyright © 2018年 DAA. All rights reserved.
//
import UIKit
import SpriteKit
class TD_IntroSprite:SKNode {
var cardInfo = [String:Any](){
willSet {
}
didSet {
self.refreshView()
print("cardInfo已经发生改变")
}
}
func layout(){
// refreshView()
}
func refreshView(){
removeAllChildren()
let introNode = SKSpriteNode(color: UIColor.black, size: CGSize(width: TD_Block_Width * 2, height: TD_Block_Height * 2))
addChild(introNode)
var attStr = NSMutableAttributedString(string: "人类士兵/精英")
attStr.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.white, range: NSRange(location: 0, length: 7))
let titleText = SKLabelNode(attributedText: attStr)
// titleText.fontColor = UIColor.white
// titleText.fontSize = 13
titleText.position = CGPoint(x: 0, y: TD_Block_Height / 2.0 + 13)
introNode.addChild(titleText)
_ = getInfoAttStr()
// let introStr = String(format: "%@", NSLocalizedString("topic", comment: ""))
attStr = NSMutableAttributedString(string: "警戒1:攻击范围为周围一格。")
// attStr.addAttributes(NSAttributedStringKey.foregroundColor, range: NSRange(location: 0, length: 4))
attStr.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.orange, range: NSRange(location: 0, length: 4))
attStr.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.white, range: NSRange(location: 4, length: 10))
let intrText = SKLabelNode(attributedText: attStr)
intrText.preferredMaxLayoutWidth = TD_Block_Width * 2 - 15
intrText.position = CGPoint(x: 0, y: -10)
intrText.numberOfLines = 0
introNode.addChild(intrText)
}
func getInfoAttStr() -> NSAttributedString {
let relatedSkills = cardInfo["RelatedSkills"] as! [String]
var introStr = ""
for item in relatedSkills {
let data = (TD_AnalyticalDataObject().getFileData(fileName: "Skills"))[item] as! NSDictionary
var key = data["Name"] as! String
let name = NSLocalizedString(key, comment: "default")
key = data["Intro"] as! String
let intro = NSLocalizedString(key, comment: "default")
print("name:",name,"intro:",intro)
// TD_Internationalization_Skills2Name
// NSLocalizedString("topic", comment: "")
// let type = Int(data["Type"] as! String)
// if type! < 10{//属性类技能
// initSkills(attData: data)
// }
// else if type! >= 10 && type! < 20{//动作类技能
//
// }
// else if type! >= 20 && type! < 30{//光环类技能
//
// }
// else if type! == 100{//限制类技能
//
// }
// else if type! == 101{//召唤类技能
//
// }
}
let attStr = NSMutableAttributedString(string: introStr)
return attStr
}
}
<file_sep>/TD_ApisFlorea/TD_ApisFlorea/Classes/Scene/TD_ScenarioScene.swift
//
// TD_ScenarioScene.swift
// TD_WaterMargin
//
// Created by mac on 2018/9/13.
// Copyright © 2018年 DAA. All rights reserved.
// 关卡主场景
import SpriteKit
import UIKit
class TD_ScenarioScene: TD_BaseScene ,SKPhysicsContactDelegate {
var timer = Timer()
var allSceneData = [String:Any]() //场景布局以及怪物信息数据
var towersData = [String:Any]() //防御塔数据
var scenarioIndex = 0 //当前关卡
var mapData = [Any]() //记录场景布局信息
var monsterData = [String]() //记录关卡出怪顺序以及信息
override func didMove(to view: SKView) {
self.backgroundColor = UIColor.white
}
func refreshScene(scenarioIndex:Int){
self.scenarioIndex = scenarioIndex
refresh()
}
func refresh() {
removeAllChildren()
createFlivver()
createFlivver()
}
func createFlivver(){
}
}
<file_sep>/TD_ Journey/TD_ Journey/GameViewController.swift
//
// GameViewController.swift
// TD_ Journey
//
// Created by mac on 2018/10/17.
// Copyright © 2018年 DAA. All rights reserved.
//
import UIKit
import SpriteKit
import GameplayKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
NSLog("self.view,%@", self.view)
NSLog("%@", (view as! SKView))
// if let view = self.view as! SKView? {
// let gameScene = TD_GameScene(size: view.bounds.size)
// gameScene.viewController = self;
// gameScene.scaleMode = .aspectFill
// view.presentScene(gameScene)
// view.ignoresSiblingOrder = true
// view.showsFPS = true
// view.showsNodeCount = true
// }
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.present(TD_CheckpointViewController(), animated: true, completion: nil)
// let vc = [[UIApplication sharedApplication] keyWindow].rootViewController;
// let helpVC = TD_CheckpointViewController(nibName: "HelpViewController", bundle: nil)
// [[HelpViewController alloc]initWithNibName:@"HelpViewController" bundle:nil];
// [vc presentViewController: helpVC animated: YES completion:nil];
}
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return .allButUpsideDown
} else {
return .all
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override var prefersStatusBarHidden: Bool {
return true
}
}
<file_sep>/TD_PingPongBalls/TD_PingPongBalls/Classes/Sprite/TD_SelectScenarioSprite.swift
//
// TD_SelectScenarioSprite.swift
// TD_WaterMargin
//
// Created by mac on 2018/9/13.
// Copyright © 2018年 DAA. All rights reserved.
//
import UIKit
import SpriteKit
class TD_SelectScenarioSprite: TD_BaseSpriteNode {
var data = [String : Any]()
func layout() {
refreshView()
}
func refreshView(){
let img = SKSpriteNode(imageNamed: "sell")
img.size = CGSize(width: 40, height: 40)
img.position = CGPoint(x: position.x, y: position.y + 15)
superScene.addChild(img)
let star = Int(data["star"] as! String)
for i in 0..<star! {
let img = SKSpriteNode(imageNamed: "star")
img.size = CGSize(width: 20, height: 20)
img.position = CGPoint(x: position.x - size.width / 2.0 + 5 + 10 + (20 + 5) * CGFloat(i), y: position.y - 20)
superScene.addChild(img)
}
}
}
<file_sep>/TD_WaterMargin/TD_WaterMargin/Classes/Sprite/TD_DefensiveTowersSprite.swift
//
// TD_DefensiveTowersSprite.swift
// TD_WaterMargin
//
// Created by mac on 2018/9/13.
// Copyright © 2018年 DAA. All rights reserved.
//
import UIKit
class TD_DefensiveTowersSprite: TD_BaseSpriteNode {
}
<file_sep>/TD_AncientRuins/TD_AncientRuins/Classes/View/TD_SceneElementSprite.swift
//
// TD_SceneElement.swift
// TD_AncientRuins
//
// Created by mac on 2018/10/16.
// Copyright © 2018年 DAA. All rights reserved.
//
import UIKit
import SpriteKit
class TD_SceneElementSprite: TD_BaseSpriteNode {
var blockType = "0"
func layout() {
refreshView()
}
func refreshView(){
let showBlock = SKSpriteNode(imageNamed: String(format: "mapElement_%@", blockType))
showBlock.position = CGPoint(x: position.x, y: position.y + (TD_Block_AspectRatio_Show - 1) * TD_Block_Width * 0.5)
showBlock.size = CGSize(width: TD_Block_Width, height: TD_Block_Width * TD_Block_AspectRatio_Show)
superScene.addChild(showBlock)
}
}
<file_sep>/TD_WaterMargin/TD_WaterMargin/GameViewController.swift
//
// GameViewController.swift
// TD_WaterMargin
//
// Created by mac on 2018/9/13.
// Copyright © 2018年 DAA. All rights reserved.
//
import UIKit
import SpriteKit
import GameplayKit
class GameViewController: UIViewController {
var scenarioScene = TD_ScenarioScene()
var selScenarioScene = TD_GameScene()
var scenarioIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
if let view = self.view as! SKView? {
selScenarioScene = TD_GameScene(size: view.bounds.size)
selScenarioScene.viewController = self;
selScenarioScene.scaleMode = .aspectFill
view.presentScene(selScenarioScene)
view.ignoresSiblingOrder = true
view.showsFPS = true
view.showsNodeCount = true
}
scenarioScene = TD_ScenarioScene(size: view.bounds.size) //创建场景
scenarioScene.viewController = self;
}
func showScenarioScene(index:Int){
if let view = self.view as! SKView? {
scenarioIndex = index
scenarioScene.scenarioIndex = index
view.presentScene(scenarioScene)
}
}
func showSelScenarioScene(){
if let view = self.view as! SKView? {
view.presentScene(selScenarioScene)
}
}
func showMsgbox(_message: String, _title: String = "提示"){
let alert = UIAlertController(title: _title, message: _message, preferredStyle: UIAlertControllerStyle.alert)
let btnOK = UIAlertAction(title: "好的", style: .default, handler: nil)
alert.addAction(btnOK)
self.present(alert, animated: true, completion: nil)
}
func showMsgbox(_message: String, _title: String, okTitle:String, cancelTitle:String,tag:Int){
let alert = UIAlertController(title: _title, message: _message, preferredStyle: UIAlertControllerStyle.alert)
let btnOK = UIAlertAction(title: okTitle, style: .default) { (action) in
if tag == 1{
self.scenarioIndex = self.scenarioIndex + 1
self.scenarioScene.scenarioIndex = self.scenarioIndex + 1
self.scenarioScene.refreshScene(scenarioIndex: self.scenarioIndex)
}
}
let btnCancel = UIAlertAction(title: cancelTitle, style: .default){ (action) in
if tag == 1{
self.showSelScenarioScene()
self.selScenarioScene.refreshView()
}
}
alert.addAction(btnOK)
alert.addAction(btnCancel)
self.present(alert, animated: true, completion: nil)
}
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return .allButUpsideDown
} else {
return .all
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override var prefersStatusBarHidden: Bool {
return true
}
}
<file_sep>/TD_ Journey/TD_ Journey/Classes/View/TD_CartSprite.swift
//
// TD_CartSprite.swift
// TD_ Journey
//
// Created by mac on 2018/10/18.
// Copyright © 2018年 DAA. All rights reserved.
//
import UIKit
import SpriteKit
class TD_CartSprite: TD_BaseSpriteNode {
// var cardId = ""
var cardInfo = [String:Any]()
let stateLab = SKLabelNode()
var coordinates = -1
var newCoordinates = -1
var type = -1
var attackScopeSprite = SKSpriteNode()
var imgSprite = TD_BaseSpriteNode()
var isArrackHero = false
var attackTargetEnemy = [TD_CartSprite](){
willSet {
}
didSet {
// if attackTower.count == 1 && oldValue.count == 0{
// self.removeOrScopeAction(key: TD_MoveToTower)
// self.updataAttack()
// }
print("attackTargetEnemy已经发生改变")
}
}
var attackTargetOur = [TD_CartSprite](){
willSet {
}
didSet {
// if attackTower.count == 1 && oldValue.count == 0{
// self.removeOrScopeAction(key: TD_MoveToTower)
// self.updataAttack()
// }
print("attackTargetOur已经发生改变")
}
}
//卡片属性
var cardName:String = "狼" //卡片名称
var image:String = "card_2001_1" //卡片图片(战场图片)
var cardImage:String = "card_2001_2" //卡片图片(卡组图片)
var prepare:Int = 1 //准备回合数
var cardType:Int = 0 //卡片类型(0、普通卡片 1、魔法卡)
var attack:Int = 1 //攻击
var HP:Int = 2 //生命
var mobile:Int = 2 //行动力
var attackNumber:Int = 1 //单次攻击伤害次数
var attackScope:Int = 1 //攻击范围
var attackGif:String = "cardMove_101.gif" //攻击动画
var moveGif:String = "cardMove_101.gif" //移动动画
var attackType:Int = 0 //攻击方式(0、普通近战攻击 1、远程攻击(单体瞄准)2、远程能量攻击(单体瞄准)3、直线伤害(喷火等)ps:0、1为物理伤害 2、3位魔法伤害
var energyBallType:Int = 0 //远程能量球类型(0、无能量球动画 1、直线(弩箭,火枪) 2、抛射(弓箭、投石车)3、直击目标(雷电术等))
var targetType:Int = 0 //攻击目标类型(0、敌方单体 1、敌方全体,2、敌方全体(建筑除外)3、敌方建筑 4、全体人员(不分敌我))
var basisStar:Int = 1 //卡片初始星级
var starAttack:Double = 0.3 //升星增加攻击
var starHP:Double = 0.6 //升星增加血量
// var star:Int = 1 //当前星级
// var isFirst:Bool = true //是否是第一次出现
// var skillsIntro:String = "" //卡片技能介绍(出现在卡片介绍栏)
var relatedSkills = [String]() //卡片技能数组
var intro:String = "步兵" //卡片介绍
var placeholder1:String = "" //缺省关联字段1
var placeholder2:String = "" //缺省关联字段2
var placeholder3:String = "" //缺省关联字段3
var isScope:Int = 0 //警戒属性
var armor:Int = 0 //护甲
var magicArmor:Int = 0 //魔甲
var counterattackType:Int = 1 //反击类型(0:不反击 1、反击近战 2、全部反击(攻击范围内))
var rebound:Int = 1 //反弹伤害(仅限反弹近战,数值为受到攻击反弹的伤害)
var actualAttack:Int = 1 //当前攻击
var actualHP:Int = 2 //当前生命
var actualArmor:Int = 0 //当前护甲
var actualMagicArmor:Int = 0 //当前魔甲
func layout() {
initCartProperty()
initPhysicsBoby()
creatAttackScopeView()
creatView()
name = "cart"
}
/// 初始化小兵属性
func initCartProperty(){
cardName = cardInfo["Name"] as! String
image = cardInfo["Image"] as! String
cardImage = cardInfo["CardImage"] as! String
prepare = Int(cardInfo["Prepare"] as! String)!
cardType = Int(cardInfo["CardType"] as! String)!
attack = Int(cardInfo["Attack"] as! String)!
HP = Int(cardInfo["HP"] as! String)!
// armor = Int(cardInfo["Armor"] as! String)!
// magicArmor = Int(cardInfo["MagicArmor"] as! String)!
mobile = Int(cardInfo["Mobile"] as! String)!
attackNumber = Int(cardInfo["AttackNumber"] as! String)!
// isScope = cardInfo["IsScope"] as! Bool
// counterattackType = Int(cardInfo["CounterattackType"] as! String)!
// rebound = Int(cardInfo["Rebound"] as! String)!
attackScope = Int(cardInfo["AttackScope"] as! String)!
attackGif = cardInfo["AttackGif"] as! String
moveGif = cardInfo["MoveGif"] as! String
attackType = Int(cardInfo["AttackType"] as! String)!
energyBallType = Int(cardInfo["EnergyBallType"] as! String)!
targetType = Int(cardInfo["TargetType"] as! String)!
basisStar = Int(cardInfo["BasisStar"] as! String)!
starAttack = Double(cardInfo["StarAttack"] as! String)!
starHP = Double(cardInfo["StarHP"] as! String)!
// star = Int(cardInfo["Star"] as! String)!
// isFirst = cardInfo["IsFirst"] as! Bool
relatedSkills = cardInfo["RelatedSkills"] as! [String]
intro = cardInfo["Intro"] as! String
placeholder1 = cardInfo["Placeholder1"] as! String
placeholder2 = cardInfo["Placeholder1"] as! String
placeholder3 = cardInfo["Placeholder1"] as! String
initSkillAttributes()
}
func initSkillAttributes(){
for item in relatedSkills {
let data = (TD_AnalyticalDataObject().getFileData(fileName: "Skills"))[item] as! NSDictionary
let type = Int(data["Type"] as! String)
if type! < 10{//属性类技能
initSkills(attData: data)
}
else if type! >= 10 && type! < 20{//动作类技能
}
else if type! >= 20 && type! < 30{//光环类技能
}
else if type! == 100{//限制类技能
}
else if type! == 101{//召唤类技能
}
}
}
/// 初始化技能数据
///
/// - Parameter attData: 属性类技能数据
func initSkills(attData:NSDictionary) {
print("%@",attData)
// attData["AttributeName"]
let attributeName = attData["AttributeName"] as! String
let number = Int(attData["AttributeNumber"] as! String)!
if attributeName == "IsScope" {
isScope = isScope + number
}
else if attributeName == "Armor" {
armor = armor + number
}
// let setSel = Selector.init(String(format: "set%@", attData["AttributeName"] as! String))
// let getSel = Selector.init(String(format: "get%@", attData["AttributeName"] as! String))
// var number = target(forAction: getSel, withSender: nil) as! Int
// number = number + Int(attData["AttributeNumber"] as! String)!
// target(forAction: setSel, withSender: number)
}
/// 初始化技能数据
///
/// - Parameter actionData: 动作类技能数据
func initSkills(actionData:NSDictionary) {
}
/// 初始化技能数据
///
/// - Parameter haloData: 光环类技能数据
func initSkills(haloData:NSDictionary) {
}
/// 初始化技能数据
///
/// - Parameter limitData: 限制类技能数据
func initSkills(limitData:NSDictionary) {
}
/// 初始化技能数据
///
/// - Parameter summonData: 召唤类技能数据
func initSkills(summonData:NSDictionary) {
}
func creatView() {
// let imgName = String(format: "card_%@_2",cardId)
imgSprite = TD_BaseSpriteNode(imageNamed: image)
if type == 1 {//敌方主场卡片imgSprite
imgSprite.size = CGSize(width: -TD_Block_Width, height: TD_Block_Width)
}else{
imgSprite.size = CGSize(width: TD_Block_Width, height: TD_Block_Width)
}
imgSprite.position = CGPoint(x: 0, y: 0)
addChild(imgSprite)
actualAttack = attack
// actualArmor = armor
actualHP = HP
// actualMagicArmor = magicArmor
stateLab.position = CGPoint(x: 0, y: -(TD_Block_Height * 0.5))
stateLab.text = String(format: "%d/%d/%d/%d", actualAttack,actualArmor,actualMagicArmor,actualHP)
stateLab.fontSize = 14.0
stateLab.fontColor = UIColor.red
addChild(stateLab)
}
//初始化物理属性
func initPhysicsBoby(){
physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: TD_Block_Width - 2, height: TD_Block_Width - 2))
// physicsBody.colo
physicsBody?.collisionBitMask = 0
// physicsBody?.density = 0 //密度
physicsBody?.mass = 1 //质量
physicsBody?.restitution = 0 //弹性
physicsBody?.friction = 1.0 //摩擦力
physicsBody?.linearDamping = 0.0 //线性阻力(空气阻力)
physicsBody?.allowsRotation = false
physicsBody?.affectedByGravity = false
if type == 0 {
physicsBody?.contactTestBitMask = TD_EnemyHeroHomeCategory
// physicsBody?.collisionBitMask = TD_EnemyCartCollisionBitMask
physicsBody?.categoryBitMask = TD_OurCartCategory
}else {
physicsBody?.contactTestBitMask = TD_OurHeroHomeCategory
// physicsBody?.collisionBitMask = TD_OurCartCollisionBitMask
physicsBody?.categoryBitMask = TD_EnemyCartCategory
}
}
//初始化攻击范围物理属性
func creatAttackScopeView() {
if isScope == 1{
attackScopeSprite.size = CGSize(width: CGFloat(attackScope * 2 + 1) * TD_Block_Width , height: CGFloat(attackScope * 2 + 1) * TD_Block_Height)
}else{
attackScopeSprite.size = CGSize(width: CGFloat(attackScope) * TD_Block_Width, height: TD_Block_Height)
if type == 0 {
attackScopeSprite.position = CGPoint(x: attackScopeSprite.size.width / 2.0 + TD_Block_Width / 2.0, y: 0)
}else {
attackScopeSprite.position = CGPoint(x: -attackScopeSprite.size.width / 2.0 - TD_Block_Width / 2.0, y: 0)
}
}
addChild(attackScopeSprite)
attackScopeSprite.physicsBody = SKPhysicsBody(rectangleOf: attackScopeSprite.size)
attackScopeSprite.physicsBody?.collisionBitMask = 0
// physicsBody?.density = 0 //密度
attackScopeSprite.physicsBody?.mass = 1 //质量
attackScopeSprite.physicsBody?.restitution = 0 //弹性
attackScopeSprite.physicsBody?.friction = 0.0 //摩擦力
attackScopeSprite.physicsBody?.linearDamping = 0.0 //线性阻力(空气阻力)
attackScopeSprite.physicsBody?.allowsRotation = false
attackScopeSprite.physicsBody?.affectedByGravity = false
if type == 0 {
attackScopeSprite.physicsBody?.contactTestBitMask = TD_EnemyCartCategory | TD_EnemyHeroCategory
attackScopeSprite.physicsBody?.categoryBitMask = TD_OurCartAttackCategory
}else{
attackScopeSprite.physicsBody?.contactTestBitMask = TD_OurCartCategory | TD_OurHeroCategory
attackScopeSprite.physicsBody?.categoryBitMask = TD_EnemyCartAttackCategory
}
self.zPosition = 20
}
func action() {
newCoordinates = coordinates
if attackTargetEnemy.count > 0{
attackEnemy(targetType: 1)
}else if(isArrackHero){
attackEnemy(targetType: 2)
}else{
move(mobile: mobile)
}
}
func move(mobile:Int){
var w = TD_Block_Width
var step = 1
if type == 1{
w = -TD_Block_Width
step = -1
if newCoordinates % 100 == 0{//在最左方
(superScene as! TD_FightScene).pollingAction()
return
}
}else{
if newCoordinates % 100 == 11{//在最右方
(superScene as! TD_FightScene).pollingAction()
return
}
}
if !(superScene as! TD_FightScene).performMobile(step: step, coordinates: newCoordinates, mobile: mobile){//前方没有落脚点
(superScene as! TD_FightScene).pollingAction()
return
}
imgSprite.runActionGif(fileName: moveGif, isRepeat: true, key: "move")
let action = SKAction.move(to: CGPoint(x: position.x + w, y: position.y), duration: TimeInterval(TD_Block_Width / 100))
self.run(action) {
if self.type == 0 {
self.newCoordinates = self.newCoordinates + 1
}else{
self.newCoordinates = self.newCoordinates - 1
}
if (self.superScene as! TD_FightScene).thereAreUnits(coordinates: self.newCoordinates) == false{
(self.superScene as! TD_FightScene).refreshData(oldKey: self.coordinates, newKey: self.newCoordinates)
self.coordinates = self.newCoordinates
if self.attackTargetEnemy.count > 0{
self.imgSprite.removeAction(key: "move")
self.attackEnemy(targetType: 1)
}else if(self.isArrackHero){
self.imgSprite.removeAction(key: "move")
self.attackEnemy(targetType: 2)
}else if (mobile > 0){
self.imgSprite.removeAction(key: "move")
self.move(mobile: mobile - 1)
}else{
self.imgSprite.removeAction(key: "move")
(self.superScene as! TD_FightScene).pollingAction()
}
}else{
if (mobile > 0){
self.imgSprite.removeAction(key: "move")
self.move(mobile: mobile - 1)
}
}
}
}
/// 攻击敌军,处理逻辑
///
/// - Parameter targetType: 1、卡片 2、英雄
func attackEnemy(targetType:Int) {
switch attackType {
case 0://普通近战攻击
meleeAttack(targetType:targetType)
break
case 1://远程能量攻击(单体瞄准)
remoteAttack()
break
case 2://直线攻击
straightLineAttack()
break
default:
break
}
}
/// 普通近战攻击,有攻击动作,目标直接受到伤害
///
/// - Parameter targetType: 1、卡片 2、英雄
func meleeAttack(targetType:Int) {
DispatchQueue.main.asyncAfter(deadline: .now()+0.5, execute:
{
if (targetType == 1){
let target = self.getMonomerTarget()
self.attackked(sprites: [target])
}else{
self.attackkedHero()
}
})
imgSprite.runActionGif(fileName: attackGif) { (results) in
(self.superScene as! TD_FightScene).pollingAction()
}
}
/// 远程攻击方式
func remoteAttack(){
switch energyBallType {
case 0://无能量球动画
// meleeAttack()
break
case 1://直线(弩箭,火枪)
// remoteAttack()
break
case 2://抛射(弓箭、投石车)
// meleeAttack()
break
case 3://直击目标(雷电术、突刺)
// meleeAttack()
break
default:
break
}
}
/// 直线攻击(喷火等)
func straightLineAttack(){
switch targetType {
case 0://敌方单体
break
case 1://敌方全体
break
case 2://敌方全体(建筑除外)
break
case 3://敌方建筑
break
case 4://全体人员(不分敌我)
break
default:
break
}
}
/// 获取攻击目标(单体)
///
/// - Returns: 攻击目标
func getMonomerTarget() -> TD_CartSprite {
var cartSprite = TD_CartSprite()
for item in attackTargetEnemy {
if cartSprite.type == -1{
cartSprite = item
}else{
if type == 0{
if item.coordinates < cartSprite.coordinates{
cartSprite = item
}
}else{
if item.coordinates > cartSprite.coordinates{
cartSprite = item
}
}
}
}
return cartSprite
}
/// 攻击英雄
func attackkedHero(){
}
/// 攻击目标(卡片单位)
///
/// - Parameter sprites:被攻击的卡片单位数组
func attackked(sprites:[TD_CartSprite]){
var type = 0;
if self.attackType > 1{
type = 1
}
for item in sprites {
// let isKill=(superScene as! TD_FightScene).target(attack: actualAttack, cardSprite: item, attackType: type)
if (superScene as! TD_FightScene).target(attack: actualAttack, cardSprite: item, attackType: type){//击杀目标
let iEnemy = attackTargetEnemy.index(of: item)
if (iEnemy != nil){
attackTargetEnemy.remove(at: iEnemy!)
continue
}
if targetType == 4{
let iOur = attackTargetOur.index(of: item)
if (iOur != nil){
attackTargetEnemy.remove(at: iOur!)
}
}
}
}
}
/// 被攻击
///
/// - Parameters:
/// - attack: 伤害
/// - attackType: 伤害类型 1:物理伤害、1:魔法伤害
/// - Returns: 是否被击杀
func beingAttacked(attack:Int,attackType:Int) -> Bool {
var ar = 0
if attackType == 0 {
ar = actualArmor
}else{
ar = actualMagicArmor
}
actualHP = actualHP - max(attack - ar, 0)
let temporaryImgSprite = SKSpriteNode(imageNamed: "beingAttackedTrace")
temporaryImgSprite.size = size
temporaryImgSprite.zPosition = 100;
addChild(temporaryImgSprite)
DispatchQueue.main.asyncAfter(deadline: .now()+0.5, execute:
{
temporaryImgSprite.removeFromParent()
})
if actualHP <= 0 {
print("该单位被击杀 -- %d -- %@",coordinates,cardName);
(self.superScene as! TD_FightScene).removeSptiye(key: coordinates)
removeFromParent()
return true
}
return false
}
}
<file_sep>/TD_ Journey/TD_ Journey/TD_CheckpointViewController.swift
//
// TD_ CheckpointViewController.swift
// TD_ Journey
//
// Created by mac on 2018/10/17.
// Copyright © 2018年 DAA. All rights reserved.
//
import UIKit
import SpriteKit
import GameplayKit
class TD_CheckpointViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// self.view.backgroundColor = UIColor.yellow
// Do any additional setup after loading the view.
// NSLog("self.view,%@", self.view)
// if let view = self.view as! SKView? {
// let gameScene = TD_GameScene(size: view.bounds.size)
// gameScene.viewController = self;
// gameScene.scaleMode = .aspectFill
// view.presentScene(gameScene)
// view.ignoresSiblingOrder = true
// view.showsFPS = true
// view.showsNodeCount = true
// }
// self.view.add
// (view as! SKView).presentScene(<#T##scene: SKScene?##SKScene?#>)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// let helpVC = TD_FightViewController(nibName: "TD_FightViewController", bundle: nil);
self.present(TD_FightViewController(), animated: true, completion: nil)
}
}
<file_sep>/TD_PingPongBalls/TD_PingPongBalls/Classes/Sprite/TD_EnergyBallSprite.swift
//
// TD_EnergyBallSprite.swift
// TD_WaterMargin
//
// Created by mac on 2018/9/28.
// Copyright © 2018年 DAA. All rights reserved.
//
import SpriteKit
class TD_EnergyBallSprite: TD_BaseSpriteNode {
func layout(){
physicsBody = SKPhysicsBody(circleOfRadius:size.width / 2.0)
physicsBody?.collisionBitMask = 0
// physicsBody?.density = 0 //密度
physicsBody?.mass = 1 //质量
physicsBody?.restitution = 0 //弹性
physicsBody?.friction = 0.0 //摩擦力
physicsBody?.linearDamping = 0.0 //线性阻力(空气阻力)
physicsBody?.allowsRotation = false
physicsBody?.affectedByGravity = false
physicsBody?.contactTestBitMask = TD_MonsterCategory
physicsBody?.categoryBitMask = TD_EnergyBallCategory
}
}
| 6703d9bdb50dd2bcff4f24c325212da831e2b2ac | [
"Swift"
] | 32 | Swift | tuxiangxue007/Games | fa8c02c71a4d7fee3d989cf6d2160943b80ad434 | 08232c446ae3b18f621af6b86834baea186408bf |
refs/heads/master | <repo_name>Sujittrapa6337/Camp-Maejo-University<file_sep>/Camp.sql
create table Student (
idCard varchar(13) not null,
fullName varchar(255) not null,
birthday date not null,
tel varchar(10) not null,
email varchar(255) not null,
years integer not null,
eduProgram varchar(100) not null,
school varchar(100) not null,
username varchar(45) not null,
passwords varchar(45) not null,
primary key(idCard)
);
create table CampType (
campTypeId integer ,
campTypeName varchar(45) not null,
primary key(campTypeId)
);
create table Major (
majorId integer ,
majorName varchar(45) not null,
primary key(majorId)
);
create table Camp (
campId integer not null,
campName varchar(255) not null,
property varchar(255) not null,
document varchar(255) ,
price integer,
quantity integer not null,
applyDate date,
majorId integer not null,
campTypeId integer not null,
primary key(campId),
foreign key(majorId) references Major(majorId),
foreign key(campTypeId) references CampType(campTypeId)
);
create table Staff (
idCard varchar(13) not null,
fullName varchar(45) not null,
majorId integer not null,
primary key(idCard),
foreign key(majorId) references Major(majorId)
);
create table Register(
registerId integer not null,
statuses varchar(45),
idCard varchar(13),
campId integer,
primary key(registerId),
foreign key(idCard) references Student(idCard),
foreign key(campId) references Camp(campId)
);
create table Schedules(
applyDate date not null,
closeDate date,
announcedDate date,
startDate date,
endDate date,
payStartDate date,
payEndDate date,
campId integer,
primary key(applyDate),
foreign key(campId) references Camp(campId)
);
create table Management(
managementId integer,
detail varchar(45),
campId integer,
idCard varchar(13),
primary key(managementId),
foreign key(campId) references Camp(campId),
foreign key(idCard) references Staff(idCard)
);
create table Bill(
billNo varchar(10),
datePayment date,
modeOfPayment varchar(45),
price integer,
statuses varchar(45),
registerId integer,
primary key(billNo),
foreign key(registerId) references Register(registerId)
);
/*student*/
insert into Student values('1500703287416','กนกนิภา ยาธิดา','2000-01-01','0932276418','<EMAIL>',5,'วิทย์-คณิต','โรงเรียนจอมทอง','kanoknipa','kanoknipa18');
insert into Student values('1500794512748','กชนิภา ศิลปการสกุล','2000-01-12','0903754185','<EMAIL>',5,'วิทย์-คณิต','โรงเรียนจอมทอง','koodnipa','koodnipa11');
insert into Student values('1500794762184','กชนุช ปริยากรโสภณ','2000-01-23','0973217532','<EMAIL>',5,'วิทย์-คณิต','โรงเรียนจอมทอง','koodnud','koodnud32');
insert into Student values('1500707423845','กนก ธนาภูวนัตถ์','2000-01-30','0984327515','<EMAIL>',5,'วิทย์-คณิต','โรงเรียนจอมทอง','kanook','kanook15');
insert into Student values('1845174329717','กันตาภา วรโชติวาทิน','2000-02-20','0984628451','<EMAIL>',5,'วิทย์-คณิต','โรงเรียนจอมทอง','kantapon','kantapon51');
insert into Student values('1845923257330','กาญจนา วรโชติโภคิน','2000-02-11','0947285471','<EMAIL>',5,'วิทย์-คณิต','โรงเรียนจอมทอง','kanjana','kanjana71');
insert into Student values('1845129534011','กานดา วรโชติธนัน','2000-02-14','0963218562','<EMAIL>',5,'วิทย์-คณิต','โรงเรียนจอมทอง','kanta','kanta62');
insert into Student values('1845011231842','กานติมา อัคคเดชโภคิน','2000-02-20','0974317528','<EMAIL>',5,'ศิลป์-คำนวน','โรงเรียนจอมทอง','kantima','kantima28');
insert into Student values('1513957328573','กิตติญา พิชญเดชา','2000-02-21','0985632185','<EMAIL>',5,'ศิลป์-คำนวน','โรงเรียนจอมทอง','kittiya','kittiya85');
insert into Student values('1513854948439','เขมิกา กิจสุพัฒน์ภาคิน','2000-03-20','0986317432','<EMAIL>',5,'ศิลป์-คำนวน','โรงเรียนช่องฟ้าซินเซิงวาณิชบำรุง','kamika','kamika32');
insert into Student values('1513859395773','คำนึง ชนาภัทรวรโชติ','2000-03-19','0986573218','<EMAIL>',5,'ศิลป์-คำนวน','โรงเรียนช่องฟ้าซินเซิงวาณิชบำรุง','kumnung','kumnung18');
insert into Student values('1513954939563','จอมใจ ปิติโชคโภคิน','2000-03-03','0987321754','<EMAIL>',5,'ศิลป์-คำนวน','โรงเรียนช่องฟ้าซินเซิงวาณิชบำรุง','jomjai','jomjai54');
insert into Student values('1781492758389','จันจิมา วรโชติอิงคนันท์','2000-03-01','0947281453','<EMAIL>',5,'ศิลป์-ภาษา','โรงเรียนช่องฟ้าซินเซิงวาณิชบำรุง','janjima','janjima53');
insert into Student values('1781753884281','จันทกานต์ วรโชติเมธี','2000-03-30','0974317532','<EMAIL>',5,'ศิลป์-ภาษา','โรงเรียนช่องฟ้าซินเซิงวาณิชบำรุง','jantakan','jantakan32');
insert into Student values('1781493285783','จันทิมา ธนภูดินันท์','2000-03-22','0973416438','<EMAIL>',5,'ศิลป์-ภาษา','โรงเรียนดาราวิทยาลัย','jantima','jantima38');
insert into Student values('1781958893916','จิดาภา เจนกิจโสภณ','2000-04-02','0971354738','<EMAIL>',5,'ศิลป์-ภาษา','โรงเรียนดาราวิทยาลัย','jidapa','jidapa37');
insert into Student values('1284872756288','จิตตา กรภัควัฒน์','2000-04-19','0974673512','jit<EMAIL>',5,'ศิลป์สังคม','โรงเรียนดาราวิทยาลัย','jitta','jitta12');
insert into Student values('1284869395831','จินดา จรัสพุฒิพงศ์','2000-04-27','0974673851','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนดาราวิทยาลัย','jinda','jinda51');
insert into Student values('1284869813424','ชนัดดา ภูสิทธ์อุดม','2000-04-21','0973552742','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนดาราวิทยาลัย','chanidda','chanidda42');
insert into Student values('1284857688391','ชนากานต์ นนท์สัจทัศน์','2000-04-20','0965732185','<EMAIL>',5,'ศิลป์-ภาษา','โรงเรียนดาราวิทยาลัย','chanakan','chanakan85');
insert into Student values('1284857676371','ชนิกา กสิณภพสกุล','2000-04-17','0937561274','<EMAIL>',5,'ศิลป์-ภาษา','โรงเรียนเทพบดินทร์วิทยาเชียงใหม่','chanika','chanika74');
insert into Student values('1610858599223','ชนิตา เดชพิพัฒน์โชติ','1999-05-20','0963218466','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนเทพบดินทร์วิทยาเชียงใหม่','chanita','chanita66');
insert into Student values('1610857738462','ชมพูนุช มหาเจริญศิลป์','1999-05-12','0836521745','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนเทพบดินทร์วิทยาเชียงใหม่','chompunut','chompunut45');
insert into Student values('1610858365839','ชามา ปัทมชัยวิวัฒน์','1999-05-15','0836572813','<EMAIL>',6,'ศิลป์สังคม','โรงเรียนเทพบดินทร์วิทยาเชียงใหม่','chama','chama13');
insert into Student values('1610847768391','ชุดา โรจนเมธีพงศ์','1999-05-20','0865647357','<EMAIL>',6,'ศิลป์สังคม','โรงเรียนเทพบดินทร์วิทยาเชียงใหม่','chuda','chuda57');
insert into Student values('1610857365839','ชุติมา อัศวบุญโชค','1999-05-21','0826465732','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนบ้านแม่โต๋','chutama','chutama32');
insert into Student values('1453847678385','ฐานิกา ศิริกรโสภณ','1999-05-28','0826656372','<EMAIL>',6,'ศิลป์สังคม','โรงเรียนบ้านแม่โต๋','tanida','tanida72');
insert into Student values('1453957567819','ฐานิดา มหัทธนธรรม','1999-06-11','0836466731','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนบ้านแม่โต๋','tanika','tanika31');
insert into Student values('1453875646381','ณิชกมล เชาวกรกุล','1999-06-8','08263657382','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนฝางชนูปถัมภ์','nitkamon','nitkamon82');
insert into Student values('1453718467381','ต้องใจ โอภาโพธิวัฒน์','1999-06-10','083662741','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนฝางชนูปถัมภ์','thongjai','thongjai41');
insert into Student values('1914865737274','เตชินี ชัยเดชวรโชติ','1999-06-23','0836657381','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนฝางชนูปถัมภ์','tachinee','tachinee81');
insert into Student values('1914285646284','ทัตพิชา โชคสุทธิสวัสดิ์','1999-06-27','0846563724','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนฝางชนูปถัมภ์','tutpicha','tutpicha24');
insert into Student values('1914284657843','ทิพนาถ มหาวีรเศรษฐ์','1999-06-24','0836462843','<EMAIL>',6,'วิทย์-คณิต','โรงเรียนรังษีวิทยา','thipnad','thipnad43');
insert into Student values('1914836536411','ทิพปภา วรเกียรติ์สกุล','1999-07-21','0836472845','<EMAIL>',6,'วิทย์-คณิต','โรงเรียนรังษีวิทยา','thipapa','thipapa45');
insert into Student values('1314865743951','ธนาภา ยศวรรังสรรค์','1999-07-20','0826465732','<EMAIL>',6,'วิทย์-คณิต','โรงเรียนรังษีวิทยา','tanapa','tanapa32');
insert into Student values('1314856478471','ธนิดา กิตติรัตน์โสธร','1999-07-12','0836465732','<EMAIL>',6,'วิทย์-คณิต','โรงเรียนรังษีวิทยา','tanipa','tanipa32');
insert into Student values('1314485767483','ธมน ชัยพัฒน์ภูวดล','1999-07-16','0846585639','<EMAIL>',6,'ศิลป์สังคม','โรงเรียนรังษีวิทยา','tamon','tamon39');
insert into Student values('1314847657483','ธัญญา ชัยภูริจิรนนท์','1999-07-17','0836492645','<EMAIL>',6,'ศิลป์สังคม','โรงเรียนรังษีวิทยา','tunya','tunya45');
insert into Student values('1173857265719','ธัญชนก วิโรจนพิมุกข์','1999-07-19','0892646572','<EMAIL>',6,'วิทย์-คณิต','โรงเรียนรังษีวิทยา','tunchanook','tunchanook72');
insert into Student values('1173858737562','ธิติมา วรจักรสีหสกุล','1999-08-25','0826475128','<EMAIL>',6,'วิทย์-คณิต','โรงเรียนรังษีวิทยา','titima','titima28');
insert into Student values('1173745538381','นงนุช พงศ์โชติ','1999-08-21','0846565738','<EMAIL>',6,'ศิลป์สังคม','โรงเรียนจอมทอง','nongnud','nongnud38');
insert into Student values('1173856738758','นพิน กิจศิริวัชรโชติ','1999-08-20','0892651322','<EMAIL>',6,'ศิลป์สังคม','โรงเรียนจอมทอง','napin','napin22');
insert into Student values('1747838829571','นัชชา ภัททนิธิโภคิน','1999-08-22','0863657201','<EMAIL>',6,'ศิลป์สังคม','โรงเรียนจอมทอง','nudcha','nudcha01');
insert into Student values('1747284758296','นันทิตา มงคลวัชรกุล','1999-01-20','0948348453','<EMAIL>',6,'ศิลป์สังคม','โรงเรียนจอมทอง','nuntita','nuntita53');
insert into Student values('1747628468385','นันทินี ธัญญนิธิเกษม','1999-01-20','0918475737','<EMAIL>',6,'ศิลป์สังคม','โรงเรียนจอมทอง','nuntinee','nuntinee37');
insert into Student values('1747298479362','นันทิมา โชติภัทรอัศวิน','1999-01-20','0988375835','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนจอมทอง','nuntima','nuntima35');
insert into Student values('1622846583957','นิชา วาทิน','1999-01-20','0984753783','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนจอมทอง','nicha','nicha83');
insert into Student values('1622847567583','นิดานุช ถิรัตกาญจนกุล','1999-01-20','0902746302','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนจอมทอง','nidanud','nidanud02');
insert into Student values('1622746547572','นิพาดา อุดมวัฒนวิเศษ','1999-01-20','0902765737','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนจอมทอง','nipada','nipada37');
insert into Student values('1622846573881','บงกช โชคกาญจนกวี','1999-01-20','0926704563','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนจอมทอง','bongkod','bongkod63');
insert into Student values('1485763828747','วรดร จิราธิวัฒน์','2001-01-16','0927468375','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนสันป่าตองวิทยาคม','woradon','woradon75');
insert into Student values('1747657839857','กีรติ สิริวัฒนภักดี','2001-01-12','0947385837','keerati<EMAIL>',4,'วิทย์-คณิต','โรงเรียนสันป่าตองวิทยาคม','keerati','keerati37');
insert into Student values('1847758397589','มานิน เจียรวนนท์','2001-01-19','0937758837','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนสันป่าตองวิทยาคม','manin','manin37');
insert into Student values('1846784967389','ฐิติ อยู่วิทยา','2001-01-11','0947737473','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนสันป่าตองวิทยาคม','thiti','thiti73');
insert into Student values('1846658395839','ชัญญา วัชรพล','2001-01-16','0947371836','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนสันป่าตองวิทยาคม','chaiya','chaiya36');
insert into Student values('1047657304637','กันติชา รัตนรักษ์','2001-01-15','0937462817','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนสันป่าตองวิทยาคม','kanticha','kanticha17');
insert into Student values('1745573840375','มนายุ ภิรมย์ภักดี','2001-01-14','0947766372','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนสันป่าตองวิทยาคม','manayu','manayu72');
insert into Student values('1046673403633','ศิวนาถ มาลีนนท์','2001-02-13','0976318463','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนสันป่าตองวิทยาคม','siwanad','siwanad63');
insert into Student values('1736503756377','ธมน เชาวน์วิวัฒน์','2001-02-18','0945527382','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนสันป่าตองวิทยาคม','tamanon','tamanon82');
insert into Student values('1746743676427','ีภพ อัศวโภคิน','2001-01-21','0836462843','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนสันป่าตองวิทยาคม','tipob','tipob43');
insert into Student values('1046673773468','เวธณี จุรางกูล','2001-02-28','0836472845','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนมงฟอร์ตวิทยาลัย','watanee','watanee45');
insert into Student values('1764767387680','ปราธีดา มหากิจศิริ','2001-02-14','0963218466','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนมงฟอร์ตวิทยาลัย','prateeda','prateeda66');
insert into Student values('2874668830738','ภาวิดา เบญจรงคกุล','2001-02-17','0926704563','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนมงฟอร์ตวิทยาลัย','pawida','pawida63');
insert into Student values('2658872107647','รุจาภา วงศ์กุศลกิจ','2001-02-23','085682647','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนมงฟอร์ตวิทยาลัย','rujapa','rujapa47');
insert into Student values('2875668278650','นิพาดา วิลเลียม','2001-02-22','0863417453','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนมงฟอร์ตวิทยาลัย','nipada','nipada53');
insert into Student values('2734674238840','ผริตา อครวัตนนท์ ','2001-03-29','0986357162','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนมงฟอร์ตวิทยาลัย','prita','prita62');
insert into Student values('2746658737992','วราลี เปรมปรีดิ์','2001-03-30','0974673512','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนมงฟอร์ตวิทยาลัย','pawaree','pawaree12');
insert into Student values('2876583975924','ธนิสร ไชยวรรณ','2001-03-25','0845271845','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนมงฟอร์ตวิทยาลัย','tanison','tanison45');
insert into Student values('2877658945693','พสุชา วิจิตรพงศ์พันธุ์','2001-03-26','0985378283','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนมงฟอร์ตวิทยาลัย','pasucha','pasucha83');
insert into Student values('2847765764865','มธุรา ชาห์','2001-03-28','0853718234','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนมงฟอร์ตวิทยาลัย','natura','natura34');
insert into Student values('2846583479570','ปูริดา กลิ่นประทุม','2001-03-29','0853621864','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนรังษีวิทยา','purida','purida64');
insert into Student values('2836583975389','ชัยสงค์ คำประกอบ','2001-03-27','0926704563','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนรังษีวิทยา','chaisong','chaisong63');
insert into Student values('2834865875630','กานดิศ คุณปลื้ม','2001-03-25','0836462843','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนรังษีวิทยา','kandit','kandit43');
insert into Student values('2765886583850','ศาสะ ฉายแสง','2001-03-24','0863748283','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนรังษีวิทยา','sasi','sasi83');
insert into Student values('2658373187485','ปยุต ไชยนนทน์','2001-03-21','0836472845','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนรังษีวิทยา','payut','payut45');
insert into Student values('2783819758803','ภคิน ชินวัตร','2001-03-20','0974673512','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนรังษีวิทยา','pakin','pakin12');
insert into Student values('2865869897941','พนิต ชุณหะวัณ','2001-03-01','0863518388','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนรังษีวิทยา','panit','panit88');
insert into Student values('2875876939903','ธรรศ เตชะไพบูลย์','2001-03-02','0974317528','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนรังษีวิทยา','tus','tus28');
insert into Student values('2884581876835','นิธิป ตันเจริญ','2001-04-03','0963218466','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนรังษีวิทยา','nitib','nitib66');
insert into Student values('2186468247689','ธาวิน เทียนมอง','2001-04-04','0836657381','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนรังษีวิทยา','tawin','tawin81');
insert into Student values('2658466186275','กรรณารา เทือกสุบรรณ','2001-04-05','0826475128','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนรังษีวิทยา','kannara','kannara28');
insert into Student values('2567810475728','พิมพ์พิลาวัลย์ บูรณุปกรณ์','2001-04-06','0874631274','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนเชิดเจิมศิลป์','pimpirawon','pimpirawon74');
insert into Student values('2176573850734','พิมพ์ประพาย ปริศนานันทกุล','2001-04-07','0865311863','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนเชิดเจิมศิลป์','pimprapay','pimprapay63');
insert into Student values('2747578375789','พิมพ์พลอย ปุณณกันต์','2001-04-08','0863821938','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนเชิดเจิมศิลป์','pimploy','pimploy38');
insert into Student values('2765573829024','พรรณารักษ์ พร้อมพันธุ์','2001-04-09','0985437281','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนเชิดเจิมศิลป์','pannaruk','pannaruk81');
insert into Student values('2746684937582','พรรณประพาย มาศดิตถ์','2001-04-10','0942746532','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนเชิดเจิมศิลป์','panprakay','panprakay32');
insert into Student values('2476584888203','อรัญญา โล่ห์สุนทร','2001-04-11','0985638219','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนเชิดเจิมศิลป์','arunya','arunya19');
insert into Student values('2746748593757','อรัญญานี วงศ์สวัสดิ์','2001-04-23','0974657382','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนเชิดเจิมศิลป์','arunyane','arunyane82');
insert into Student values('3747582987583','ดาริน เวชชาชีวะ','2001-04-24','0967273647','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนเชิดเจิมศิลป์','darin','darin47');
insert into Student values('3747881047849','เมยานี ศิลปอาชา','2001-04-26','0962737282','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนเชิดเจิมศิลป์','meyanee','meyanee82');
insert into Student values('3647828567289','ประกายกาญนจ์ พงษ์พาณิช','2001-04-13','0963728453','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนเชิดเจิมศิลป์','prakaykan','prakaykan53');
insert into Student values('3747658939940','ประกายวรรณ สุนทรเวช','2001-04-10','0974673512','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนเชิดเจิมศิลป์','prakaywan','prakaywan12');
insert into Student values('3742884627857','ปานวาด สารสิน','2001-04-19','0862672782','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนพรตพิทยพยัต','panwad','panwad82');
insert into Student values('3747759284790','ครองขวัญ สุวรรณคีรี','2001-04-22','0845727372','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนพรตพิทยพยัต','chongwan','chongwan72');
insert into Student values('1737465838574','อิงกาญจน์ อังกินันทน์','2001-04-20','0863828638','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนพรตพิทยพยัต','aingkan','aingkan38');
insert into Student values('3755882658386','เมธาวารี สารสิน','2001-04-28','0953782641','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนพรตพิทยพยัต','matawaree','matawaree41');
insert into Student values('3758947694985','งามศิริ อัตถากร','2001-04-23','0835062402','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนพรตพิทยพยัต','ngamsiri','ngamsiri02');
insert into Student values('3737586982097','เลิศหล้า อับดุลบุตร','2001-04-11','0906488293','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนพรตพิทยพยัต','rodra','rodra93');
insert into Student values('3857682927583','ไลลา ไกรฤกษ์','2001-04-10','0926704563','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนพรตพิทยพยัต','lila','lila63');
insert into Student values('3847679321950','กุสลา ชินวัตร','2001-04-19','0836462843','<EMAIL>',4,'วิทย์-คณิต','โรงเรียนพรตพิทยพยัต','kussara','kussara43');
insert into Student values('3775688331045','อิงดาว ภิรมย์ภักดี','2000-05-11','0836472845','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนพรตพิทยพยัต','aingdaw','aingdaw45');
insert into Student values('1874658428847','อารยา ล่ำซำ','2000-05-13','0934642134','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนพรตพิทยพยัต','araya','araya34');
insert into Student values('2846583347742','ปัญญาพร จาติกวณิช','2000-05-16','0926704563','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนพรตพิทยพยัต','panyapon','panyapon12');
insert into Student values('8236582494280','ไพริน โชควัฒนา','2000-05-19','0974673512','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนพรตพิทยพยัต','pirin','pirin12');
insert into Student values('1263668364838','กษิณีย์ นิมมานเหมินท์','2000-05-10','0963218466','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนพรตพิทยพยัต','kasinee','kasinee66');
insert into Student values('4656828428328','ภูพิงค์ มาลีนนท์','2000-05-12','0974317528','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนศรียาภัย','puping','puping28');
insert into Student values('7648264682664','ดาวิกา วัชรพล','2000-05-13','0836657381','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนศรียาภัย','dawika','dawika81');
insert into Student values('1726682468248','แสงเดือน เศรษฐบุตร','2000-05-14','0963547281','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนศรียาภัย','sangdun','sangdun81');
insert into Student values('1846688488772','แสงอุษา โสภณพนิช','2000-05-15','0906383627','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนศรียาภัย','sangauti','sangauti27');
insert into Student values('3783647278582','บัณฑา โอสถานนท์','2000-05-17','0826475128','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนศรียาภัย','bunda','bunda28');
insert into Student values('2874656883468','<NAME>์','2000-05-10','0863577372','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนศรียาภัย','kanokpon','kanokpon72');
insert into Student values('2665883462803','สิริยากร กัลยาณมิตร','2000-05-09','0982846183','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนศรียาภัย','siriyakon','siriyakon83');
insert into Student values('3462372842907','วทิยาพัทร์ คชเสนี','2000-06-08','0867336547','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนศรียาภัย','watiyapod','watiyapod47');
insert into Student values('2864672646284','สุริยัน จันทรางศุ','2000-06-07','0946582913','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนศรียาภัย','suriyan','suriyan13');
insert into Student values('4647886488280','วาริใส ชูโต','2000-06-06','0983462138','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนศรียาภัย','warisai','warisai38');
insert into Student values('1766483864682','นภากาฬ โชติกเสถียร','2000-06-05','0864328761','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนศรียาภัย','napakan','napakan61');
insert into Student values('4763628646829','พัฒนากรณ์ บุญหลง ','2000-06-04','0863219743','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนศรียาภัย','pantanakon','pantanakon43');
insert into Student values('2766884819083','วชิริน โปษยานนท์','2000-06-03','0963117383','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนศรียาภัย','wachirin','wachirin83');
insert into Student values('7636788468832','ปทุมวิไล เพ็ญกุล','2000-06-02','0865217543','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนศรียาภัย','patumwiri','patumwiri43');
insert into Student values('6466846882379','นิราภัทร โรจนกุล','2000-06-01','0826465732','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนศรียาภัย','nopaput','nopaput32');
insert into Student values('1776488669297','ภัทรพร โรจนดิศ','2000-06-22','0956438219','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนศรียาภัย','padtarapon','padtarapon19');
insert into Student values('7663648828663','นฤณีย์ วัชโรทัย','2000-06-21','0904538197','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนสอาดเผดิมวิทยา','narunee','narunee97');
insert into Student values('6266428848846','กานต์ เวชชาชีวะ','2000-06-29','0807563421','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนสอาดเผดิมวิทยา','kan','kan21');
insert into Student values('1636886599289','กริช ศิริสัมพันธ์','2000-06-20','0875473821','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนสอาดเผดิมวิทยา','krit','krit21');
insert into Student values('1276486588648','กช สุรคุปต์','2000-07-28','0836462843','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนสอาดเผดิมวิทยา','kod','kod43');
insert into Student values('1636747582668','กัญจน์ มหายศปัญญา','2000-07-27','0986553819','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนสอาดเผดิมวิทยา','kan','kan19');
insert into Student values('1764766883648','กันต์ สุขุม','2000-07-26','0974673512','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนสอาดเผดิมวิทยา','kan1','kan11');
insert into Student values('1776468364960','กฤษฎิ์ สุนทรเวช','2000-07-25','0826465732','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนสอาดเผดิมวิทยา','krite','krite32');
insert into Student values('7736488583785','เขม สิงหเสนี','2000-07-24','0836472845','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนสอาดเผดิมวิทยา','khem','khem45');
insert into Student values('6346827834963','เจตน์ สุวรรณทัต','2000-07-23','0926704563','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนสอาดเผดิมวิทยา','jad','jad62');
insert into Student values('7682768492664','จิณณ์ เจษฎางกูร','2000-07-22','0836462843','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนสอาดเผดิมวิทยา','jin','jin43');
insert into Student values('3648927883668','ณัฏฐ์ ดารากร','2000-07-19','0832765439','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนสอาดเผดิมวิทยา','nut','nut39');
insert into Student values('1764658826399','ณิช นรินทรกูล','2000-07-18','0836462843','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนสอาดเผดิมวิทยา','nit','nit43');
insert into Student values('1763455868237','ดนตร์ มนตรีกุล','2000-07-17','0963218466','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนสอาดเผดิมวิทยา','don','don66');
insert into Student values('1755757488236','ดรณ์ ฉัตรกุล','2000-07-16','0974317528','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนท่าวังผาพิทยาคม','donn','donn28');
insert into Student values('2723658286488','ดิษย์ เทพหัสดิน','2000-07-15','0836657381','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนท่าวังผาพิทยาคม','dit','dit81');
insert into Student values('4688873668842','ติณณ์ ปาลกะวงศ์','2000-07-14','0907545132','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนท่าวังผาพิทยาคม','tin','tin32');
insert into Student values('2766488238490','ตาณ พึ่งบุญ','2000-07-13','0832018927','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนท่าวังผาพิทยาคม','tan','tan27');
insert into Student values('1646856846588','ทัพพ์ เสนีวงศ์','2000-07-12','0963217546','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนท่าวังผาพิทยาคม','tub','tub46');
insert into Student values('3785892734992','ทีปต์ อิศรางกูล','2000-07-12','0826475128','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนท่าวังผาพิทยาคม','tip','tip28');
insert into Student values('8756823972939','ธรณ์ พนมวัน','2000-07-11','0864532108','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนท่าวังผาพิทยาคม','ton','ton08');
insert into Student values('6368237954677','ธาม กปิตถา','2000-08-10','0954318276','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนท่าวังผาพิทยาคม','tam','tam76');
insert into Student values('7683479764823','ธรรศ กุญชร','2000-08-01','0826465732','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนท่าวังผาพิทยาคม','tus','tus32');
insert into Student values('3472974786539','บุษย์ ชุมแสง','2000-08-02','0874531298','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนท่าวังผาพิทยาคม','bud','bud98');
insert into Student values('3477592479479','ปัณณ์ เดชาติวงศ์','2000-08-08','0807545132','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนท่าวังผาพิทยาคม','bun','bun32');
insert into Student values('2374668490064','ปริชญ์ ทินกร','2000-08-05','0964739274','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนท่าวังผาพิทยาคม','prit','prit73');
insert into Student values('2687479296694','ปัถย์ กุญชร','2000-08-09','0974673512','pud<EMAIL>',5,'ศิลป์สังคม','โรงเรียนท่าวังผาพิทยาคม','pud','pud12');
insert into Student values('1648379479404','พิชญ์ ชุมแสง','2000-08-10','0826465732','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนบ่อเกลือ','pit','pit32');
insert into Student values('1637837647792','พิมพ์ ปราโมช','2000-08-13','0869563024','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนบ่อเกลือ','pim','pim25');
insert into Student values('3648237548293','พล มาลากุล','2000-08-19','0923659087','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนบ่อเกลือ','pon','pon87');
insert into Student values('3664892974993','พฤกษ์ สนิทวงศ์','1999-08-19','0943218765','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนบ่อเกลือ','pruk','pruk65');
insert into Student values('2636492387923','ภูมิ อิศรเสนา','1999-08-11','0897651231','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนบ่อเกลือ','pum','pum31');
insert into Student values('3628488263640','ภาม กำภู','1999-08-17','0826465732','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนบ่อเกลือ','pam','pam32');
insert into Student values('6364827481366','รัญชน์ คเนจร','1999-08-13','0954321876','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนบ่อเกลือ','run','run76');
insert into Student values('6348137649236','รุจ ชุมสาย','1999-08-16','0926704563','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนบ่อเกลือ','rut','rut63');
insert into Student values('6366348279369','วิชญ์ ลดาวัลล์','1999-08-10','0836472845','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนบ่อเกลือ','wit','wit54');
insert into Student values('2365482304672','วีร์ ศิริวงศ์','1999-08-13','0974673512','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนบ่อเกลือ','wee','wee12');
insert into Student values('2365482376824','ศรณ์ ทองแถม','1999-08-11','0807634912','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนบ่อเกลือ','son','son12');
insert into Student values('2364823764237','เศรษฐ์ จันทรทัต','1999-08-10','0836462843','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนบ่อเกลือ','sad','sad43');
insert into Student values('6348283580743','อัฑฒ์ ชยางกูร','1999-08-15','0836462843','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนบ่อเกลือ','aut','aut43');
insert into Student values('3454136488368','อาชว์ ทวีวงศ์','1999-08-16','0906210389','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนบ่อเกลือ','ach','ach89');
insert into Student values('3723548237649','ไอริน กฤดากร','1999-08-13','0974317528','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนบ่อเกลือ','airin','airin28');
insert into Student values('5354237682366','อารียา เกษมศรี','1999-09-16','0942474834','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนบ่อเกลือ','areya','areya34');
insert into Student values('1626648366489','อลิชา เกษมสันต์','1999-09-21','0963218466','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนแม่สันวิทยา','aricha','aricha66');
insert into Student values('2766824658936','อมรา คณางค์','1999-09-22','0826475128','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนแม่สันวิทยา','amarin','amarin28');
insert into Student values('2646823649030','อลินดา จักรพันธ์','1999-09-27','0836657381','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนแม่สันวิทยา','arinda','arinda81');
insert into Student values('1636264699468','อลิส จิตรพงษ์','1999-09-26','0845203648','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนแม่สันวิทยา','aris','aris48');
insert into Student values('1636528368932','อลิสา ไชยันต์','1999-09-30','0826386572','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนแม่สันวิทยา','arisa','arisa72');
insert into Student values('2672654823046','อัญญา ชุมพล','1999-09-06','0925174536','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนแม่สันวิทยา','aunya','aunya36');
insert into Student values('2537548230046','โบนิตา ดิศกุล','1999-09-23','0954628183','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนแม่สันวิทยา','bonita','bonita83');
insert into Student values('2635482648232','โบ เทวกุล','1999-09-27','0962647345','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนแม่สันวิทยา','boo','boo45');
insert into Student values('3545728554283','ชนา ทองใหญ่','1999-09-29','0956324867','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนแม่สันวิทยา','chana','chana67');
insert into Student values('2454824868200','ชาลิสา นพวงศ์','1999-09-26','0873218657','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนแม่สันวิทยา','chalisa','chalisa57');
insert into Student values('5354827548683','ชายา ภาณุพันธุ์','1999-09-28','0826465732','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนแม่สันวิทยา','chaya','chaya32');
insert into Student values('2654237648939','ันดา วรวรรณ','1999-09-27','0826475128','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนแม่สันวิทยา','junda','junda28');
insert into Student values('2345423793692','จันทรา ศรีธวัช','1997-10-20','0964589394','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนแม่สันวิทยา','juntra','juntra94');
insert into Student values('3472839936900','ดาริน ศุขสวัสดิ์','1999-10-21','0865473824','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนแม่สันวิทยา','darin','darin24');
insert into Student values('3548375823686','ดานิกา สวัสดิวัฒน์','1999-10-19','0964300213','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนแม่สันวิทยา','danika','danika13');
insert into Student values('3465823692369','ดาหลา โสณกุล','1999-10-12','0974657231','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนแม่สันวิทยา','dala','dala31');
insert into Student values('2635483986590','เอริกา สวัสดิกุล','1999-10-11','0989076823','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนแม่สันวิทยา','arika','arika23');
insert into Student values('6582387852922','เอมมาลิน สุประดิษย์','1999-10-01','0906541856','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนอัสสัมชัญลำปาง','ammarin','ammarin56');
insert into Student values('5549248599372','เอมมาลี จิรประวัติ','1999-10-17','0826465732','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนอัสสัมชัญลำปาง','ammare','ammare32');
insert into Student values('2638495036600','จินา เพ็ญพัฒน์','1999-11-06','0926704563','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนอัสสัมชัญลำปาง','jina','jina63');
insert into Student values('2365935917738','จีน กิติยากร','1999-11-09','0836472845','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนอัสสัมชัญลำปาง','jeen','jeen34');
insert into Student values('2635836489239','อิสรินทร์ จักรพงศ์','1999-11-03','0974673512','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนอัสสัมชัญลำปาง','aisarin','aisarin12');
insert into Student values('2665924695629','ไอรา จุธาธุช','1999-11-02','0836462843','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนอัสสัมชัญลำปาง','aira','aira32');
insert into Student values('4658236197404','จันทร์นิล ฉัตรไชย','1999-11-05','0903765412','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนอัสสัมชัญลำปาง','junnin','junnin12');
insert into Student values('2135548235823','เจนนินทร์ บริพัตร','1999-11-06','0836462843','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนอัสสัมชัญลำปาง','jannin','jannin34');
insert into Student values('2135548236583','เจนอารี ประวิตร','1999-11-10','0873009832','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนอัสสัมชัญลำปาง','janare','janare32');
insert into Student values('3826465283593','เจนเนตร โพธิ์คำทอง','1999-11-01','0974317528','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนอัสสัมชัญลำปาง','jannat','jannat28');
insert into Student values('7254583759230','เกวลิน ยุคล','1999-11-08','0826475128','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนอัสสัมชัญลำปาง','kawwarin','kawwarin28');
insert into Student values('1664865829357','คัทลิน พีพัฒน์','1999-11-14','0836657381','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนอัสสัมชัญลำปาง','kudrin','kudrin81');
insert into Student values('2646582975931','กะทิ รังสิต','1999-11-19','0963218466','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนอัสสัมชัญลำปาง','kati','kati66');
insert into Student values('3746923764919','ไลลา นวรัตน์','1999-11-13','0894318765','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนอัสสัมชัญลำปาง','lila','lila65');
insert into Student values('3864659237397','ลินา รัชนี','1999-11-12','0904521832','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนอัสสัมชัญลำปาง','lina','lina32');
insert into Student values('8236659264629','หลิน วุฒิชัย','1999-11-16','0946553829','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนอัสสัมชัญลำปาง','rin','rin32');
insert into Student values('3846652799379','ลลิสา สุริยง','1999-12-19','0904657023','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนลำปางกัลยาณี','lalisa','lalisa23');
insert into Student values('1766486569664','ลาทิชา อาภากร','1999-12-10','0934673828','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนลำปางกัลยาณี','laracha','laracha28');
insert into Student values('2376827086231','มีนา สีสังข์','1999-12-15','0853748284','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนลำปางกัลยาณี','meena','meena84');
insert into Student values('2876589387202','มาริสา ไกรฤกษ์','1999-12-13','0842618468','<EMAIL>',6,'ศิลป์-คำนวน','โรงเรียนลำปางกัลยาณี','marisa','marisa68');
insert into Student values('8264658273653','มาริน กัลยาณมิตร','1999-01-13','0863657201','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนลำปางกัลยาณี','marin','marin01');
insert into Student values('1836587492379','มิรา กิตติขจร','1999-01-12','0892651322','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนลำปางกัลยาณี','mira','mira22');
insert into Student values('2837659276492','มาลาริน คชเสนี','1999-01-16','0897564128','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนลำปางกัลยาณี','mararin','mararin28');
insert into Student values('1826483949900','นานา ชูกระมล','1999-01-18','0907453218','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนลำปางกัลยาณี','nana','nana18');
insert into Student values('8264659273649','ณัฐชา ทองเจือ','1999-01-15','0826465732','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนลำปางกัลยาณี','nutcha','nutcha32');
insert into Student values('7646839992366','เนตรา พิบูลสงคราม','1999-01-13','0978423256','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนลำปางกัลยาณี','natra','natra56');
insert into Student values('2646527359377','รสสินา ภิรมย์ภักดี','1999-01-19','0896412312','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนลำปางกัลยาณี','rotsine','rotsine12');
insert into Student values('2653789368292','รชิดา เสรีเริงฤทธิ์','1999-01-10','0809786756','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนลำปางกัลยาณี','rachida','rachida56');
insert into Student values('8364893569236','เรนิตา เสนาณรงค์','1999-01-11','0974673512','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนลำปางกัลยาณี','ranita','ranita12');
insert into Student values('6354823794781','รสลิน สารสาส','1999-01-01','0826465732','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนลำปางกัลยาณี','rotsarin','rotsarin32');
insert into Student values('2635829382937','รสมาลี เวชชะพันธ์','1999-01-05','0926704563','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนลำปางกัลยาณี','rotmare','rotmare63');
insert into Student values('2635489182902','แสนดี บุณยรัตพันธุ์','1999-01-09','0836462843','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนลำปางกัลยาณี','sandee','sandee43');
insert into Student values('2837652983502','ศรา บุนนาค','1999-01-03','0863657201','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนลำปางกัลยาณี','sara','sara01');
insert into Student values('2636828959792','สลิณา เพ็ญกุล','1999-02-06','0836472845','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนอันนาลัย','sarina','sarina45');
insert into Student values('1862659659238','ธัญญา พนมยงค์','1999-02-07','0974673512','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนอันนาลัย','tunya','tunya12');
insert into Student values('7658293879203','ธิดา พลางกูร','1999-02-08','0836462843','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนอันนาลัย','tida','tida43');
insert into Student values('1764659347292','ธิชา เฟื่องอารมย์','1999-02-01','0908978675','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนอันนาลัย','ticha','ticha75');
insert into Student values('2164985700433','ธารา ภมรมนตรี','1999-02-02','0826475128','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนอันนาลัย','tira','tira28');
insert into Student values('2763659366385','เวนิตา ภิรมย์ภักดี','1999-02-09','0974317528','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนอันนาลัย','wanita','wanita28');
insert into Student values('8664992374902','วีรา วัชโรทัย','1999-02-22','0963218466','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนอันนาลัย','wara','wara66');
insert into Student values('8236659237283','วนิษศา เศวตศิลา','1999-02-21','0836657381','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนอันนาลัย','wanissa','wanissa81');
insert into Student values('2664927369138','วิศนี อมรวิวัฒน์','1999-02-27','0863657201','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนอันนาลัย','wissane','wissane01');
insert into Student values('8736492087200','อรัญ สิงหเสนี','1999-02-20','0892651322','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนอันนาลัย','arun','arun22');
insert into Student values('6482736927369','อานนท์ สุจริตกุล','1999-02-25','0812233445','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนอันนาลัย','arnon','arnon45');
insert into Student values('2876465982409','อชิรา สุวรรณทัต','1999-02-27','0845566778','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนอันนาลัย','achira','achira78');
insert into Student values('8768379830203','อาชา สุวรรณรัฐ','1999-02-28','0889344321','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนอันนาลัย','acha','acha21');
insert into Student values('2837659874032','อามันต์ หลักภัย','1999-10-22','0921324354','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนอันนาลัย','amun','amun54');
insert into Student values('7592830107803','อดิรัตน์ อภัยวงศ์','1999-03-28','0954657687','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนอันนาลัย','adirut','adirut87');
insert into Student values('8237698800766','บุญ อมาตยกุล','1999-03-21','0998786756','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนอันนาลัย','boon','boon56');
insert into Student values('2692375938003','เบญจมินทร์ โอสถานนท์','1999-03-20','0945342312','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนอนุสรณ์ศุภมาศ','banjamin','banjamin12');
insert into Student values('2836483799367','ชาญ พลาธร','1999-03-13','0826465732','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนอนุสรณ์ศุภมาศ','chan','chan32');
insert into Student values('8366489297959','เชษฐ์ กะรัต','1999-03-17','0907060504','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนอนุสรณ์ศุภมาศ','chad','chad04');
insert into Student values('4489274742938','กฤษณ์ เทพรัต','1999-03-12','0809080706','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนอนุสรณ์ศุภมาศ','kritn','kritn06');
insert into Student values('2876497429993','ดิเรก อดิศวร','1999-03-19','0926704563','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนอนุสรณ์ศุภมาศ','dirak','dirak63');
insert into Student values('6635697293672','ดลธี วงเศวต','1999-03-16','0945342376','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนอนุสรณ์ศุภมาศ','donte','donte76');
insert into Student values('7466592937923','แดน สมุทรเทวา','1997-03-15','0978125434','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนอนุสรณ์ศุภมาศ','dan','dan34');
insert into Student values('2768376492479','ดวิน ตรีอัปสร','1999-03-18','0826465732','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนอนุสรณ์ศุภมาศ','dawin','dawin32');
insert into Student values('2635493773669','ดอน พัชรกานต์กุล','1999-03-14','0967543123','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนอนุสรณ์ศุภมาศ','donn','donn23');
insert into Student values('6354912693779','กวินทร์ อภิรมย์ฤดี','1999-03-12','0989612387','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนอนุสรณ์ศุภมาศ','kawin','kawin87');
insert into Student values('2736928692377','กาย รัตนชาติ','1999-03-19','0836462843','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนอนุสรณ์ศุภมาศ','kay','kay43');
insert into Student values('8365997364913','หรัญญ์ พัลลภ','1999-03-11','0974673512','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนอนุสรณ์ศุภมาศ','krin','krin12');
insert into Student values('8369238665992','จักรี อรุณรัศมี','1999-03-10','0836472845','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนอนุสรณ์ศุภมาศ','jukre','jukre45');
insert into Student values('8469237695822','จอน เทวพรหม','1999-03-01','0836462843','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนอนุสรณ์ศุภมาศ','john','john43');
insert into Student values('2866429983746','เจษฏ์ โยธาบดี','1999-04-06','0963218466','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนอนุสรณ์ศุภมาศ','jad','jad66');
insert into Student values('8736482837792','เคน สุวรรณเวช','1999-04-09','0974317528','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนอนุสรณ์ศุภมาศ','ken','ken28');
insert into Student values('2837649759233','กฤษณ์ อนันต์ไพศาล','1999-04-03','0826475128','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนวัดคลองตันราษฎร์บำรุง','kritm','kritm28');
insert into Student values('8646582765923','มรรค อัครมหึมาสกุล','1999-04-07','0934218756','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนวัดคลองตันราษฎร์บำรุง','nuuk','nuuk56');
insert into Student values('2635923765934','มิตร พัชรกานต์กุล','1999-04-21','0836657381','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนวัดคลองตันราษฎร์บำรุง','mit','mit81');
insert into Student values('4658374923993','โนรา เจริญโภคทรัพย์','1999-04-17','0892651322','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนวัดคลองตันราษฎร์บำรุง','nora','nora22');
insert into Student values('2736493949200','โอฬาร ศิริรัฐภาค','1999-04-14','0863657201','<EMAIL>',6,'ศิลป์-ภาษา','โรงเรียนวัดคลองตันราษฎร์บำรุง','aoran','aoran01');
insert into Student values('2377592365949','ภาริช ปริศนา','2001-01-16','0963218466','<EMAIL>',4,'ศิลป์-คำนวน','โรงเรียนวัดคลองตันราษฎร์บำรุง','pakin','pakin66');
insert into Student values('2366923765923','ภัทร สุทธากุล','2001-01-14','0892651322','<EMAIL>',4,'ศิลป์-คำนวน','โรงเรียนวัดคลองตันราษฎร์บำรุง','pad','pad22');
insert into Student values('8136649247599','ฤทธิ์ชาติ จุฑาเทพ','2001-01-17','0863657201','<EMAIL>',4,'ศิลป์-คำนวน','โรงเรียนวัดคลองตันราษฎร์บำรุง','ridchad','ridchad01');
insert into Student values('2823656823923','รุธ สุทรกานต์','2001-01-06','0856412098','<EMAIL>',4,'ศิลป์-คำนวน','โรงเรียนวัดคลองตันราษฎร์บำรุง','ruth','ruth98');
insert into Student values('2386649197792','โฬม ศรายุทรพิชัย','2001-01-16','0956312454','<EMAIL>',4,'ศิลป์-คำนวน','โรงเรียนวัดคลองตันราษฎร์บำรุง','rom','rom54');
insert into Student values('2817346923791','ฌอน พิชัย','2001-01-19','0945841365','<EMAIL>',4,'ศิลป์-คำนวน','โรงเรียนวัดคลองตันราษฎร์บำรุง','non','non65');
insert into Student values('2937694600482','เชน วิทยาธร','2001-01-10','0956413209','<EMAIL>',4,'ศิลป์-คำนวน','โรงเรียนวัดคลองตันราษฎร์บำรุง','chan','chan09');
insert into Student values('2364659236492','เทวิน อมราภรณ์','2001-11-11','0674523187','<EMAIL>',4,'ศิลป์-คำนวน','โรงเรียนวัดคลองตันราษฎร์บำรุง','tewin','tewin87');
insert into Student values('1745923592830','ธาวิศ สมุทรเทวา','2001-11-12','0967532412','<EMAIL>',4,'ศิลป์-คำนวน','โรงเรียนวัดคลองตันราษฎร์บำรุง','tawin','tawin12');
insert into Student values('2736639729774','วิทย์ สุทรกานต์','2001-11-13','0826465732','<EMAIL>',4,'ศิลป์-คำนวน','โรงเรียนวัดคลองตันราษฎร์บำรุง','wit','wit32');
insert into Student values('1746569268273','วัฒน์ พัชราภรณ์','2001-11-15','0965745342','<EMAIL>',4,'ศิลป์-คำนวน','โรงเรียนวัดคลองตันราษฎร์บำรุง','wat','wat42');
insert into Student values('4665287486442','ปิญชาน์ การุณวงศ์','2001-11-14','0926704563','<EMAIL>',4,'ศิลป์-ภาษา','โรงเรียนวัดคลองตันราษฎร์บำรุง','pitcha','pitcha63');
insert into Student values('2866599739347','อัญญา ไทยแท้','2000-06-04','0813243546','<EMAIL>',5,'ศิลป์-ภาษา','โรงเรียนวัดคลองตันราษฎร์บำรุง','aunya','aunya56');
insert into Student values('1866392649366','อุภัยภัทร ณรงค์ฤทธิ์','2000-06-03','0846576879','<EMAIL>',5,'ศิลป์-ภาษา','โรงเรียนวัดคลองตันราษฎร์บำรุง','autaypat','autaypat79');
insert into Student values('1863659266996','อนุภัทร ศิริสวัสดิ์','2000-06-08','0913243546','<EMAIL>',5,'ศิลป์-ภาษา','โรงเรียนวัดคลองตันราษฎร์บำรุง','anupan','anupan46');
insert into Student values('6656236619643','สมิทธ์ พืทยเสถียร','2000-06-09','0863657201','<EMAIL>',5,'ศิลป์-ภาษา','โรงเรียนรัตนราษฎร์บำรุง','samit','samit01');
insert into Student values('1665823764822','ชาคริต สุทธากุล','2000-06-10','0946575768','<EMAIL>',5,'ศิลป์-ภาษา','โรงเรียนรัตนราษฎร์บำรุง','chakrit','chakrit68');
insert into Student values('6368383466523','ภูพิงค์ วราฤทธิ์','2000-06-13','0836472845','<EMAIL>',5,'ศิลป์-ภาษา','โรงเรียนรัตนราษฎร์บำรุง','puping','puping45');
insert into Student values('2734689793950','อรินทร์ แสงอาทิตย์','2000-06-05','0974673512','<EMAIL>',5,'ศิลป์-ภาษา','โรงเรียนรัตนราษฎร์บำรุง','arin','arin12');
insert into Student values('1263346599272','รวินทร์ วิชชากร','2000-06-06','0836462843','<EMAIL>',5,'ศิลป์-ภาษา','โรงเรียนรัตนราษฎร์บำรุง','rarin','rarin43');
insert into Student values('2746593719734','ดนัย ธราธร','2000-06-30','0908967563','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนรัตนราษฎร์บำรุง','danuy','danuy63');
insert into Student values('2874659491974','ณัฐดนัย ปวรรุจ','2000-06-21','0826475128','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนรัตนราษฎร์บำรุง','nutdanuy','nutdanuy28');
insert into Student values('3465923794757','ฉัตร พุฒิภัทร','2000-06-25','0974317528','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนรัตนราษฎร์บำรุง','chat','chat28');
insert into Student values('1823468239669','อมรเทพ รัชชานนท์','2000-06-26','0901324254','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนรัตนราษฎร์บำรุง','amontab','amontab54');
insert into Student values('1863562469239','เทพประทาน รณพีร์','2000-06-17','0892651322','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนรัตนราษฎร์บำรุง','tabpratan','tabpratan22');
insert into Student values('2648623687782','วิสิทธิ์ อนวัช','2000-06-18','0836657381','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนรัตนราษฎร์บำรุง','isit','wisit81');
insert into Student values('2734659937407','วินท์สันต์ พัชรพจนารถ','2000-06-21','0857645342','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนรัตนราษฎร์บำรุง','winson','winson42');
insert into Student values('2366923684682','มรรค วิทยบำรุง','2000-06-20','0963218466','<EMAIL>',5,'ศิลป์สังคม','โรงเรียนรัตนราษฎร์บำรุง','nook','nook66');
insert into Student values('2265917746920','อาวัล บุนนาค','2001-12-24','0863657201','<EMAIL>',4,'ศิลป์สังคม','โรงเรียนรัตนราษฎร์บำรุง','arun','arun01');
insert into Student values('7364823663856','จักรสันต์ วัชโรทัย','2001-12-16','0892651322','<EMAIL>',4,'ศิลป์สังคม','โรงเรียนรัตนราษฎร์บำรุง','juksin','juksin22');
insert into Student values('2371977469230','อดิรันทร์ สุจริตกุล','2001-12-15','0967463524','<EMAIL>',4,'ศิลป์สังคม','โรงเรียนสารสิทธิ์พิทยาลัย','adirun','adirun24');
insert into Student values('3641927748365','ไอดิน โรจนกุล','2001-12-11','0918723764','<EMAIL>',4,'ศิลป์สังคม','โรงเรียนสารสิทธิ์พิทยาลัย','airin','airin64');
insert into Student values('1882636491307','เทวิน อมาตยกุล','2001-12-19','0836462843','<EMAIL>',4,'ศิลป์สังคม','โรงเรียนสารสิทธิ์พิทยาลัย','tawin','tawin43');
insert into Student values('2736992634923','หรัณย์ บุรณศิริ','2001-12-17','0891276345','<EMAIL>',4,'ศิลป์สังคม','โรงเรียนสารสิทธิ์พิทยาลัย','hrun','hrun45');
insert into Student values('8237649102874','ฤทธิชาติ ดำพา','2001-12-18','0826475128','<EMAIL>',4,'ศิลป์สังคม','โรงเรียนสารสิทธิ์พิทยาลัย','rittivhat','rittivhat28');
insert into Student values('2192764927420','อัทธนีย์ ธนิกกุล','2001-12-13','0897109234','<EMAIL>',4,'ศิลป์สังคม','โรงเรียนสารสิทธิ์พิทยาลัย','auttane','auttane43');
insert into Student values('2649176423770','นลิน อัครสุนทร','2001-12-14','0974317528','<EMAIL>',4,'ศิลป์สังคม','โรงเรียนสารสิทธิ์พิทยาลัย','narin','narin28');
insert into Student values('2646912649238','มินตรา อรรครัตนมณี','2001-1-15','0826465732','<EMAIL>',4,'ศิลป์สังคม','โรงเรียนสารสิทธิ์พิทยาลัย','mintra','mintra32');
insert into Student values('7364927642900','เอรินทร์ เดชพรหม','1999-11-23','0926704563','<EMAIL>',6,'วิทย์-คณิต','โรงเรียนสารสิทธิ์พิทยาลัย','arin','arin63');
insert into Student values('2197264294722','แพรวา วิทรากุล','1999-11-21','0956413278','<EMAIL>',6,'วิทย์-คณิต','โรงเรียนสารสิทธิ์พิทยาลัย','prawa','prawa78');
insert into Student values('3764938499636','น้ำเพชร อีทรารัตน์','1999-11-27','0934523567','<EMAIL>',6,'วิทย์-คณิต','โรงเรียนโพธาวัฒนาเสนี','oum','oum67');
insert into Student values('2749274692374',' มิรินทร์ ศรีสุริยะกุล','1999-11-28','0836657381','<EMAIL>',6,'วิทย์-คณิต','โรงเรียนโพธาวัฒนาเสนี','mirin','mirin81');
insert into Student values('1927639172692','ธารา ทราวรสัตย์','1999-11-29','0872341237','<EMAIL>',6,'วิทย์-คณิต','โรงเรียนโพธาวัฒนาเสนี','tara','tara67');
insert into Student values('9376493764991','ลลิล ธราภิรมย์','1999-11-12','0983456732','<EMAIL>',6,'วิทย์-คณิต','โรงเรียนโพธาวัฒนาเสนี','lalin','lalin12');
insert into Student values('2793693740377','นิศา ตะวันวาด','1999-11-15','0963218466','<EMAIL>',6,'วิทย์-คณิต','โรงเรียนโพธาวัฒนาเสนี','nisa','nisa66');
insert into Student values('8234591726392','เภตรา รัตนาศิริเพ็ชรา','1999-11-13','0836462843','<EMAIL>',6,'วิทย์-คณิต','โรงเรียนโพธาวัฒนาเสนี','patra','patra43');
insert into Student values('8736491634232','ตะวัน รุจิกาน','1999-11-19','0974673512','<EMAIL>',6,'วิทย์-คณิต','โรงเรียนโพธาวัฒนาเสนี','tawan','tawan12');
insert into Student values('6461276936913','ณิชชา วิริยะ','1999-11-13','0836472845','n<EMAIL>',6,'วิทย์-คณิต','โรงเรียนโพธาวัฒนาเสนี','nitcha','nitcha45');
insert into Student values('8746193874927','ณภัทร ชาลินี ','1999-11-09','0945312456','<EMAIL>',6,'วิทย์-คณิต','โรงเรียนโพธาวัฒนาเสนี','napad','napad56');
insert into Student values('9173641374992','น้ำมนต์ ตั้งธนากิจ','1999-11-03','0954132567','<EMAIL>',6,'วิทย์-คณิต','โรงเรียนโพธาวัฒนาเสนี','nummon','nummon67');
/*camptype*/
insert into CampType values (1,'ค่ายคอมพิวเตอร์'),
(2,'ค่ายเกษตร'),
(3,'ค่ายวิทยาศาสตร์'),
(4,'ค่ายรัฐศาตร์'),
(5,'ค่ายวิศวะ'),
(6,'ค่ายบัญชีและการเงิน'),
(7,'ค่ายคณิตศาสตร์');
/*major*/
insert into Major values(1,'ส่งเสริมการเกษตร'),
(2,'พืชศาสตร์'),
(3,'พืชไร่'),
(4,'ปฐพีศาสตร์'),
(5,'เกษตรเคมี'),
(6,'วิศวกรรมอาหาร'),
(7,'วิศวกรรมเกษตร'),
(8,'วิทยาศาสตร์และเทคโนโลยีการอาหาร'),
(9,'วิทยาการคอมพิวเตอร์'),
(10,'เทคโนโลยีชีวภาพ'),
(11,'เคมี'),
(12,'สถิติ'),
(13,'เทคโนโลยีสารสนเทศ'),
(14,'คณิตศาสตร์'),
(15,'วัสดุศาสตร์'),
(16,'เคมีอุตสาหกรรมและเทคโนโลยีสิ่งทอ'),
(17,'ฟิสิกส์ประยุกต์'),
(18,'รัฐศาสตร์'),
(19,'บัญชี'),
(20,'การเงิน');
/*camp*/
insert into Camp values(1,'ITCAMP MAEJO 2018','ค่ายกิจกรรมของสาขาเทคโนโลยีสารสนเทศ สำหรับนักเรียนชั้นมัธยมศึกษาปี ที่ 5 –6 สายการเรียน วิทยาศาสตร์-คณิตฯ และ ศิลป์ –คำนวณ',null,800,40,13,1),
(2,'ค่ายยุวชนคอมพิวเตอร์ครั้งที่ 16','ค่ายยุวชนคอมพิวเตอร์ครั้งที่ 16 สำหรับนักเรียนชั้นมัธยมศึกษาปี ที่ 5 –6 สายการเรียน วิทยาศาสตร์-คณิตฯ และ ศิลป์ –คำนวณ',null,1000,70,9,1),
(3,'ค่าย BIOTECH’S CAMP 18','ค่ายสำหรับนักเรียนมัธยมศึกษาตอนปลาย (ไม่รับสายอาชีวะ)',null,700,80,10,3),
(4,'ค่าย Youth Industrial Chem Camp นักเคมีอุตสาหกรรมรุ่นเยาว์ ครั้งที่ 1','สำหรับนักเรียนชั้นมัธยมศึกษาปีที่ 5-6 สายวิทย์-คณิต',null,500,60,16,3),
(5,'Chem Camp #19','ค่ายเคมีกับอาชญวิทยา สำหรับนักเรียนชั้นมัธยมศึกษาปี ที่ 5 –6 สายการเรียน วิทยาศาสตร์-คณิตฯ',null,100,60,14,3),
(6,'Summation Camp 15','ค่ายสำหรับนักเรียน ม.ปลาย สายวิทย์-คณิต เข้าร่วมค่ายเตรียมความพร้อมเข้าสู่การเป็นนักสถิติในอนาคต',null,250,50,12,7),
(7,'ค่ายพัฒนาทักษะและเทคนิคปฏิบัติการทางวิทยาศาสตร์','ค่ายพัฒนาทักษะและเทคนิคปฏิบัติการทางวิทยาศาสตร์ โดยสาขาวัสดุศาสตร์ สำหรับนักเรียนที่สนใจ ระดับมัธยมศึกษา',null,0,30,15,3),
(8,'MATH Camp #5','ค่ายคณิตศาสตร์ เพื่อปรับทัศนคติที่ดีต่อการเรียนวิชาคณิตศาสตร์ของนักเรียน สำหรับนักเรียน ม.ปลาย',null,2000,60,14,7),
(9,'ค่ายฟิสิกส์ประยุกต์','ค่ายสำหรับนักเรียน ม.ปลาย สายวิทย์-คณิต ที่มีความสนใจและต้องการเรียนรู้เกี่ยวกับฟิสิกส์',null,500,40,17,3),
(10,'ค่ายเทคโนโลยีอาหาร','เปิดรับนักเรียนม.ปลาย สายวิทย์-คณิต',null,500,70,8,3),
(11,'Food Gear','เปิดรับนักเรียนม.ปลาย สายวิทย์-คณิต',null,450,100,6,5),
(12,'ค่ายยุวชนคนรัฐศาสตร์','ค่ายที่เปิดโอกาสให้น้องๆ มัธยมศึกษาตอนปลาย ได้มาค้นหาตนเอง',null,500,77,18,4),
(13,'ค่าย Acc-BA Summer Camp','กิจกรรมที่จัดขึ้นเพื่อให้ความรู้ สร้างแรงบันดาลใจและทัศนคติที่ดีต่อ คณะบริหารธุรกิจ รับเฉพาะ ม.5',null,0,100,19,6);
/*staff*/
insert into Staff values('1846277371325','จักรายุทธ์ กลิ่นจันทร์',5),
('1742388347123','รัตติกา ชัยสวัสดิ์',8),
('1452845197432','อรอุษา ต๊ะวิโล',10),
('1752635198613','สราวุธ สอนใจ',8),
('1759375274627','รักษ์พิกุล วงศ์จักร',4),
('1745482654729','นฤมล คงขุนเทียน',17),
('1047637573502','ธันวดี กรีฑาเวทย์',5),
('1736375846309','ฐิตารีย์ พรหมเศรษฐการ',2),
('1764658377382','ศรุดา ทองหลอม',14),
('1835463853674','พงษ์ศักดิ์ มังมติ',15),
('1635430364727','สิริประภา วิรัชเจริญพันธ์',16),
('1634734026462','พิญชดา พงษ์พานิช',9),
('1735037492642','สุพจน์ บุญเรือง',1),
('1365730573942','ทวี สุวรรณ',12),
('1366483756783','วีระยุทธ ยะอินต๊ะ',6),
('1768385830679','เดชา ผิวผ่อง',13),
('1785937583903','จักรกฤษณ์ ธงแดง',7),
('1836658383863','นิ่มนภา กาบจันทร์',20),
('1837683738750','หทัยชนก งามอินทร์',3),
('1347753893521','ศิริพร หนูหล่อ',11),
('1763757364868','อัจฉรา บุญเกิด',1),
('1734753863880','พรินทร บุญเรือง',10),
('1763486868288','ธีรพล สุวรรณ',2),
('1658429665822','นิวัติ ช่างซอ',19),
('1648626486824','เบญจมาภรณ์ วิริยา',6),
('1748864946294','ปิยวรรณ สงวนศักดิ์',7),
('1689364026480','อรรถพงศ์ วภักดิ์เพชร',18),
('1864868606523','อาทิตยา ธรรมตา',4),
('1764205683936','ณัฐพล เลาห์รอดพันธุ์',3),
('1683603783502','รัชดาภรณ์ ปันทะรส',19),
('3100843238123','รัชดาภรณ์ ผิวผ่อง',19);
/*register*/
insert into Register values (1001,'ผ่าน','1500703287416',1),
(1002,'ผ่าน','1500794512748',7),
(1003,'ผ่าน','9173641374992',4),
(1004,'ผ่าน','1500707423845',10),
(1005,'ไม่ผ่าน','9173641374992',13),
(1006,'ผ่าน','1500703287416',2),
(1007,'ไม่ผ่าน','1845174329717',5),
(1008,'ไม่ผ่าน','9173641374992',8),
(1009,'ไม่ผ่าน','1500794762184',9),
(1010,'ผ่าน','9173641374992',2),
(1011,'ไม่ผ่าน','1845174329717',1),
(1012,'ไม่ผ่าน','1500703287416',11),
(1013,'ผ่าน','8746193874927',7),
(1014,'ผ่าน','1500794762184',12),
(1015,'ไม่ผ่าน','8746193874927',6),
(1016,'ผ่าน','8746193874927',8),
(1017,'ผ่าน','6461276936913',9),
(1018,'ผ่าน','8736491634232',3),
(1019,'ไม่ผ่าน','8234591726392',10),
(1020,'ผ่าน','1500794512748',13),
(1021,'ผ่าน','8234591726392',12),
(1022,'ไม่ผ่าน','1845174329717',4),
(1023,'ไม่ผ่าน','1500707423845',9),
(1024,'ไม่ผ่าน','2793693740377',5),
(1025,'ผ่าน','8234591726392',7),
(1026,'ผ่าน','1500794512748',3),
(1027,'ผ่าน','9376493764991',2),
(1028,'ไม่ผ่าน','1927639172692',4),
(1029,'ไม่ผ่าน','2749274692374',2),
(1030,'ผ่าน','6461276936913',1),
(1031,'ไม่ผ่าน','3764938499636',6),
(1032,'ผ่าน','2197264294722',6),
(1033,'ไม่ผ่าน','1845174329717',7),
(1034,'ไม่ผ่าน','7364927642900',8),
(1035,'ผ่าน','3764938499636',3),
(1036,'ไม่ผ่าน','9376493764991',4),
(1037,'ผ่าน','2793693740377',9),
(1038,'ผ่าน','7364927642900',13),
(1039,'ไม่ผ่าน','2646912649238',4),
(1040,'ผ่าน','8736491634232',10),
(1041,'ผ่าน','2749274692374',4),
(1042,'ผ่าน','3764938499636',2),
(1043,'ไม่ผ่าน','2646912649238',12),
(1044,'ผ่าน','2197264294722',5),
(1045,'ผ่าน','1927639172692',8),
(1046,'ไม่ผ่าน','2197264294722',9),
(1047,'ผ่าน','2649176423770',7),
(1048,'ไม่ผ่าน','2192764927420',6),
(1049,'ผ่าน','2192764927420',10);
insert into Register values (1050,'ผ่าน','8237649102874',4),
(1051,'ไม่ผ่าน','2749274692374',1),
(1052,'ไม่ผ่าน','8237649102874',9),
(1053,'ผ่าน','2736992634923',4),
(1054,'ไม่ผ่าน','1882636491307',2),
(1055,'ไม่ผ่าน','3641927748365',9),
(1056,'ผ่าน','2192764927420',11),
(1057,'ไม่ผ่าน','2192764927420',13),
(1058,'ไม่ผ่าน','2371977469230',12),
(1059,'ผ่าน','7364823663856',8),
(1060,'ไม่ผ่าน','2649176423770',1),
(1061,'ผ่าน','2265917746920',9),
(1062,'ไม่ผ่าน','2366923684682',3),
(1063,'ผ่าน','2734659937407',2),
(1064,'ไม่ผ่าน','8237649102874',7),
(1065,'ผ่าน','2648623687782',6),
(1066,'ไม่ผ่าน','2649176423770',10),
(1067,'ผ่าน','7364823663856',13),
(1068,'ไม่ผ่าน','2371977469230',2),
(1069,'ผ่าน','8237649102874',5),
(1070,'ไม่ผ่าน','2648623687782',4),
(1071,'ไม่ผ่าน','3641927748365',2),
(1072,'ผ่าน','2265917746920',8),
(1073,'ไม่ผ่าน','8237649102874',1),
(1074,'ไม่ผ่าน','2648623687782',9),
(1075,'ผ่าน','8237649102874',10),
(1076,'ไม่ผ่าน','1863562469239',12),
(1077,'ผ่าน','2366923684682',13),
(1078,'ไม่ผ่าน','2736992634923',5),
(1079,'ไม่ผ่าน','1882636491307',3),
(1080,'ไม่ผ่าน','1823468239669',7),
(1081,'ผ่าน','3465923794757',8),
(1082,'ไม่ผ่าน','2366923684682',1),
(1083,'ไม่ผ่าน','2192764927420',10),
(1084,'ผ่าน','1863562469239',13),
(1085,'ไม่ผ่าน','3465923794757',11),
(1086,'ไม่ผ่าน','2734659937407',3),
(1087,'ไม่ผ่าน','2734659937407',5),
(1088,'ผ่าน','2736992634923',6),
(1089,'ไม่ผ่าน','3465923794757',2),
(1090,'ไม่ผ่าน','2371977469230',7),
(1091,'ผ่าน','2874659491974',8),
(1092,'ไม่ผ่าน','3465923794757',1),
(1093,'ไม่ผ่าน','3641927748365',11),
(1094,'ผ่าน','1823468239669',13),
(1095,'ไม่ผ่าน','2874659491974',3),
(1096,'ไม่ผ่าน','1882636491307',7),
(1097,'ไม่ผ่าน','1863562469239',2),
(1098,'ผ่าน','7364823663856',7),
(1099,'ไม่ผ่าน','1863562469239',9),
(1100,'ผ่าน','2371977469230',4);
insert into Register values (1101,'ไม่ผ่าน','2874659491974',1),
(1102,'ไม่ผ่าน','2746593719734',9),
(1103,'ผ่าน','1263346599272',3),
(1104,'ไม่ผ่าน','2734689793950',2),
(1105,'ไม่ผ่าน','1823468239669',9),
(1106,'ผ่าน','6368383466523',10),
(1107,'ไม่ผ่าน','6656236619643',13),
(1108,'ไม่ผ่าน','1863659266996',2),
(1109,'ไม่ผ่าน','1866392649366',1),
(1110,'ไม่ผ่าน','1263346599272',6),
(1111,'ผ่าน','2866599739347',4),
(1112,'ไม่ผ่าน','4665287486442',1),
(1113,'ไม่ผ่าน','1823468239669',8),
(1114,'ผ่าน','6656236619643',10),
(1115,'ไม่ผ่าน','4665287486442',3),
(1116,'ไม่ผ่าน','2866599739347',9),
(1117,'ผ่าน','2746593719734',1),
(1118,'ไม่ผ่าน','6656236619643',3),
(1119,'ผ่าน','2734689793950',8),
(1120,'ไม่ผ่าน','6368383466523',4),
(1121,'ผ่าน','1866392649366',5),
(1122,'ผ่าน','2746593719734',10),
(1123,'ไม่ผ่าน','1866392649366',12),
(1124,'ไม่ผ่าน','1863659266996',11),
(1125,'ผ่าน','1263346599272',13),
(1126,'ไม่ผ่าน','1866392649366',2),
(1127,'ผ่าน','6368383466523',1),
(1128,'ไม่ผ่าน','6368383466523',5),
(1129,'ผ่าน','2734689793950',6),
(1130,'ไม่ผ่าน','2734689793950',4),
(1131,'ไม่ผ่าน','2866599739347',3),
(1132,'ผ่าน','4665287486442',9),
(1133,'ไม่ผ่าน','1863659266996',1),
(1134,'ไม่ผ่าน','1863659266996',4),
(1135,'ผ่าน','1746569268273',1),
(1136,'ไม่ผ่าน','2866599739347',2),
(1137,'ไม่ผ่าน','2736639729774',6),
(1138,'ผ่าน','1745923592830',7),
(1139,'ไม่ผ่าน','1745923592830',1),
(1140,'ไม่ผ่าน','1745923592830',2),
(1141,'ผ่าน','2736639729774',3),
(1142,'ไม่ผ่าน','2364659236492',1),
(1143,'ไม่ผ่าน','1745923592830',9),
(1144,'ผ่าน','2364659236492',10),
(1145,'ผ่าน','1746569268273',13),
(1146,'ผ่าน','2364659236492',12),
(1147,'ไม่ผ่าน','2736639729774',11),
(1148,'ผ่าน','2364659236492',6),
(1149,'ไม่ผ่าน','2937694600482',6),
(1150,'ไม่ผ่าน','2386649197792',1);
insert into Register values (1151,'ไม่ผ่าน','2736639729774',7),
(1152,'ผ่าน','2937694600482',8),
(1153,'ไม่ผ่าน','1746569268273',3),
(1154,'ไม่ผ่าน','2386649197792',2),
(1155,'ไม่ผ่าน','2386649197792',4),
(1156,'ผ่าน','2937694600482',1),
(1157,'ไม่ผ่าน','2823656823923',1),
(1158,'ไม่ผ่าน','1746569268273',7),
(1159,'ผ่าน','2937694600482',4),
(1160,'ไม่ผ่าน','2817346923791',1),
(1161,'ไม่ผ่าน','2386649197792',12),
(1162,'ไม่ผ่าน','2823656823923',11),
(1163,'ผ่าน','8136649247599',6),
(1164,'ไม่ผ่าน','2366923765923',7),
(1165,'ไม่ผ่าน','2366923765923',1),
(1166,'ผ่าน','8136649247599',3),
(1167,'ไม่ผ่าน','2366923765923',9),
(1168,'ไม่ผ่าน','2817346923791',3),
(1169,'ผ่าน','2817346923791',6),
(1170,'ไม่ผ่าน','2377592365949',2),
(1171,'ผ่าน','2377592365949',9),
(1172,'ไม่ผ่าน','2377592365949',10),
(1173,'ผ่าน','2377592365949',1),
(1174,'ไม่ผ่าน','8136649247599',11),
(1175,'ไม่ผ่าน','2823656823923',13),
(1176,'ไม่ผ่าน','2817346923791',12),
(1177,'ไม่ผ่าน','2736493949200',4),
(1178,'ไม่ผ่าน','8136649247599',2),
(1179,'ผ่าน','4658374923993',5),
(1180,'ผ่าน','2635923765934',6),
(1181,'ไม่ผ่าน','2837649759233',2),
(1182,'ผ่าน','2837649759233',4),
(1183,'ไม่ผ่าน','2736493949200',1),
(1184,'ผ่าน','8736482837792',2),
(1185,'ไม่ผ่าน','2736493949200',8),
(1186,'ผ่าน','8646582765923',3),
(1187,'ไม่ผ่าน','2837649759233',5),
(1188,'ไม่ผ่าน','2837649759233',1),
(1189,'ไม่ผ่าน','8736482837792',3),
(1190,'ผ่าน','2635923765934',5),
(1191,'ไม่ผ่าน','2635923765934',1),
(1192,'ผ่าน','4658374923993',8),
(1193,'ไม่ผ่าน','4658374923993',1),
(1194,'ไม่ผ่าน','8736482837792',9),
(1195,'ผ่าน','8736482837792',4),
(1196,'ผ่าน','2635923765934',3),
(1197,'ไม่ผ่าน','8469237695822',2),
(1198,'ผ่าน','2736493949200',10),
(1199,'ไม่ผ่าน','8469237695822',11),
(1200,'ไม่ผ่าน','4658374923993',12);
insert into Register values (1201,'ไม่ผ่าน','2866429983746',1),
(1202,'ผ่าน','8646582765923',13),
(1203,'ผ่าน','8646582765923',4),
(1204,'ไม่ผ่าน','8469237695822',6),
(1205,'ไม่ผ่าน','8369238665992',2),
(1206,'ไม่ผ่าน','8369238665992',7),
(1207,'ไม่ผ่าน','8369238665992',3),
(1208,'ไม่ผ่าน','2866429983746',8),
(1209,'ไม่ผ่าน','8369238665992',9),
(1210,'ผ่าน','8365997364913',1),
(1211,'ไม่ผ่าน','6354912693779',6),
(1212,'ผ่าน','2635493773669',7),
(1213,'ไม่ผ่าน','2768376492479',5),
(1214,'ไม่ผ่าน','2768376492479',4),
(1215,'ผ่าน','2866429983746',11),
(1216,'ไม่ผ่าน','2768376492479',1),
(1217,'ไม่ผ่าน','2768376492479',6),
(1218,'ไม่ผ่าน','2635493773669',3),
(1219,'ผ่าน','7466592937923',2),
(1220,'ผ่าน','8365997364913',10),
(1221,'ไม่ผ่าน','7466592937923',11),
(1222,'ผ่าน','6354912693779',13),
(1223,'ไม่ผ่าน','7466592937923',4),
(1224,'ผ่าน','7466592937923',3),
(1225,'ไม่ผ่าน','8365997364913',7),
(1226,'ไม่ผ่าน','2635493773669',8),
(1227,'ไม่ผ่าน','8365997364913',2),
(1228,'ไม่ผ่าน','6635697293672',6),
(1229,'ผ่าน','2876497429993',9),
(1230,'ผ่าน','6354912693779',8),
(1231,'ไม่ผ่าน','2876497429993',4),
(1232,'ไม่ผ่าน','6354912693779',1),
(1233,'ผ่าน','4489274742938',9),
(1234,'ไม่ผ่าน','2876497429993',10),
(1235,'ผ่าน','6635697293672',4),
(1236,'ไม่ผ่าน','2876497429993',5),
(1237,'ผ่าน','4489274742938',1),
(1238,'ไม่ผ่าน','4489274742938',8),
(1239,'ผ่าน','3648927883668',9),
(1240,'ไม่ผ่าน','4489274742938',2),
(1241,'ไม่ผ่าน','3648927883668',1),
(1242,'ผ่าน','2836483799367',1),
(1243,'ไม่ผ่าน','3648927883668',4),
(1244,'ผ่าน','6635697293672',8),
(1245,'ไม่ผ่าน','3648927883668',7),
(1246,'ไม่ผ่าน','2692375938003',1),
(1247,'ผ่าน','3648927883668',6),
(1248,'ไม่ผ่าน','2836483799367',3),
(1249,'ผ่าน','8768379830203',1),
(1250,'ไม่ผ่าน','2836483799367',4);
insert into Register values (1251,'ไม่ผ่าน','6635697293672',4),
(1252,'ผ่าน','2876465982409',1),
(1253,'ไม่ผ่าน','2692375938003',7),
(1254,'ผ่าน','2692375938003',8),
(1255,'ผ่าน','8768379830203',2),
(1256,'ไม่ผ่าน','2837659874032',4),
(1257,'ไม่ผ่าน','7592830107803',7),
(1258,'ไม่ผ่าน','8768379830203',3),
(1259,'ผ่าน','7592830107803',1),
(1260,'ผ่าน','2876465982409',8),
(1261,'ไม่ผ่าน','2876465982409',9),
(1262,'ผ่าน','7592830107803',10),
(1263,'ไม่ผ่าน','2876465982409',11),
(1264,'ไม่ผ่าน','8237698800766',12),
(1265,'ผ่าน','6482736927369',13),
(1266,'ไม่ผ่าน','8736492087200',4),
(1267,'ผ่าน','2664927369138',7),
(1268,'ไม่ผ่าน','2664927369138',2),
(1269,'ไม่ผ่าน','8237698800766',8),
(1270,'ผ่าน','2837659874032',3),
(1271,'ไม่ผ่าน','6482736927369',9),
(1272,'ไม่ผ่าน','6482736927369',4),
(1273,'ผ่าน','2837659874032',5),
(1274,'ไม่ผ่าน','2664927369138',1),
(1275,'ผ่าน','8664992374902',4),
(1276,'ผ่าน','8237698800766',9),
(1277,'ไม่ผ่าน','2763659366385',8),
(1278,'ไม่ผ่าน','8664992374902',6),
(1279,'ไม่ผ่าน','2763659366385',4),
(1280,'ไม่ผ่าน','2164985700433',5),
(1281,'ผ่าน','8736492087200',6),
(1282,'ผ่าน','8736492087200',10),
(1283,'ผ่าน','1764659347292',5),
(1284,'ไม่ผ่าน','2164985700433',13),
(1285,'ไม่ผ่าน','1764659347292',12),
(1286,'ไม่ผ่าน','8236659237283',11),
(1287,'ผ่าน','7658293879203',6),
(1288,'ไม่ผ่าน','7658293879203',4),
(1289,'ผ่าน','7658293879203',5),
(1290,'ผ่าน','1862659659238',3),
(1291,'ไม่ผ่าน','3746923764919',3),
(1292,'ไม่ผ่าน','3746923764919',2),
(1293,'ผ่าน','8236659237283',7),
(1294,'ไม่ผ่าน','1862659659238',5),
(1295,'ไม่ผ่าน','3746923764919',4),
(1296,'ผ่าน','2365935917738',10),
(1297,'ไม่ผ่าน','2365935917738',11),
(1298,'ผ่าน','1862659659238',12),
(1299,'ผ่าน','2365935917738',12),
(1300,'ไม่ผ่าน','2365935917738',13);
/*schedule*/
insert into Schedules values('2017-10-23','2017-12-10','2017-12-11','2018-01-12','2018-01-14','2017-12-11','2017-12-18',1);
insert into Schedules values('2017-12-16','2018-01-07','2018-01-20','2018-01-24','2018-01-27','2018-01-20','2018-01-23',2);
insert into Schedules values('2017-12-13','2017-12-30','2018-01-04','2018-01-19','2018-01-21','2018-01-04','2018-01-10',3);
insert into Schedules values('2017-08-25','2017-09-10','2017-09-11','2017-10-16','2017-10-18','2017-09-11','2017-09-18',4);
insert into Schedules values('2017-10-12','2017-10-31','2017-11-02','2017-11-17','2017-11-19','2017-11-17','2017-11-17',5);
insert into Schedules values('2017-07-04','2017-08-22','2017-08-23','2017-08-25','2017-08-26','2017-08-25','2017-08-25',6);
insert into Schedules values('2017-06-18','2017-06-30','2017-07-02','2017-07-15','2017-07-15',null,null,7);
insert into Schedules values('2017-05-31','2017-06-26','2017-06-28','2017-07-13','2017-07-17','2017-06-28','2017-07-07',8);
insert into Schedules values('2018-01-03','2018-01-18','2018-01-19','2018-02-02','2018-02-04','2018-01-19','2018-01-24',9);
insert into Schedules values('2017-05-19','2017-06-10','2017-06-11','2017-06-20','2017-06-22','2017-06-11','2017-06-18',10);
insert into Schedules values('2017-02-01','2017-03-04','2017-04-04','2017-06-02','2017-06-04','2017-04-04','2017-04-12',11);
insert into Schedules values('2017-11-25','2017-12-26','2018-01-05','2018-01-12','2018-01-14','2018-01-05','2018-01-10',12);
insert into Schedules values('2018-03-20','2018-04-05','2018-04-06','2018-04-21','2018-04-23',null,null,13);
/*management*/
insert into Management values(1,'insert',1,'1735037492642'),
(2,'insert',7,'1759375274627'),
(3,'insert',4,'1864868606523'),
(4,'insert',2,'1735037492642'),
(5,'insert',9,'1745482654729'),
(6,'insert',12,'1836658383863'),
(7,'insert',5,'1846277371325'),
(8,'insert',6,'1365730573942'),
(9,'insert',10,'1658429665822'),
(10,'insert',3,'1745482654729'),
(11,'delete',7,'1748864946294'),
(12,'insert',4,'1835463853674'),
(13,'update',1,'1365730573942'),
(14,'insert',13,'1864868606523'),
(15,'insert',11,'1047637573502'),
(16,'delete',1,'1735037492642'),
(17,'insert',6,'1759375274627'),
(18,'update',5,'1047637573502'),
(19,'insert',8,'1752635198613'),
(20,'delete',13,'1635430364727'),
(21,'insert',2,'1736375846309'),
(22,'insert',7,'1748864946294'),
(23,'update',11,'1366483756783'),
(24,'insert',9,'1658429665822'),
(25,'delete',10,'1836658383863'),
(26,'insert',3,'1835463853674'),
(27,'insert',5,'1864868606523'),
(28,'update',12,'1752635198613'),
(29,'insert',1,'1736375846309'),
(30,'insert',6,'1864868606523');
/*bill*/
insert into Bill values ('1597364820','2017-12-11','ชำระเงินผ่านธนาคาร',800,'paid',1001),
('2468159370','2017-12-15','ชำระเงินผ่านธนาคาร',800,'paid',1117),
('3698520147','2017-12-11','ชำระเงินผ่านธนาคาร',800,'paid',1127),
('7082385780','2017-12-12','ชำระเงินผ่านธนาคาร',800,'paid',1135),
('6781929274','2017-12-17','ชำระเงินผ่านธนาคาร',800,'paid',1156),
('7423693133','2017-12-18','ชำระเงินผ่านธนาคาร',800,'paid',1173),
('4296016754','2017-12-13','ชำระเงินผ่านธนาคาร',800,'paid',1210),
('2761148788','2017-12-14','ชำระเงินผ่านธนาคาร',800,'paid',1237),
('4117060956','2017-12-16','ชำระเงินผ่านธนาคาร',800,'paid',1242),
('8675471731','2017-12-11','ชำระเงินผ่านธนาคาร',800,'paid',1249),
('2708908028','2017-12-14','ชำระเงินผ่านธนาคาร',800,'paid',1252),
('3502873816','2017-12-18','ชำระเงินผ่านธนาคาร',800,'paid',1259),
('2859911137','2018-01-22','ชำระเงินผ่านธนาคาร',1000,'paid',1006),
('4329360673','2018-01-23','ชำระเงินผ่านธนาคาร',1000,'paid',1010),
('2606740986','2010-01-20','ชำระเงินผ่านธนาคาร',1000,'paid',1027),
('4358032491','2018-01-21','ชำระเงินผ่านธนาคาร',1000,'paid',1042),
('4635133055','2018-01-20','ชำระเงินผ่านธนาคาร',1000,'paid',1063),
('1307734033','2018-01-23','ชำระเงินผ่านธนาคาร',1000,'paid',1184),
('1885183845','2018-01-21','ชำระเงินผ่านธนาคาร',1000,'paid',1219),
('2427924495','2018-01-20','ชำระเงินผ่านธนาคาร',1000,'paid',1255),
('1957681697','2018-01-04','ชำระเงินผ่านธนาคาร',700,'paid',1018),
('4778071587','2018-01-10','ชำระเงินผ่านธนาคาร',700,'paid',1026),
('8618961629','2018-01-05','ชำระเงินผ่านธนาคาร',700,'paid',1035),
('8998376709','2018-01-06','ชำระเงินผ่านธนาคาร',700,'paid',1103),
('5969825024','2018-01-07','ชำระเงินผ่านธนาคาร',700,'paid',1141),
('3804559634','2018-01-09','ชำระเงินผ่านธนาคาร',700,'paid',1166),
('6441475708','2018-01-10','ชำระเงินผ่านธนาคาร',700,'paid',1186),
('8470669217','2018-01-05','ชำระเงินผ่านธนาคาร',700,'paid',1196),
('9534919360','2018-01-04','ชำระเงินผ่านธนาคาร',700,'paid',1224),
('3189658062','2018-01-06','ชำระเงินผ่านธนาคาร',700,'paid',1270),
('3023875258','2018-01-07','ชำระเงินผ่านธนาคาร',700,'paid',1290),
('6022392102','2017-09-11','ชำระเงินผ่านธนาคาร',500,'paid',1275),
('8682566835','2017-09-18','ชำระเงินผ่านธนาคาร',500,'paid',1235),
('3611642919','2017-09-12','ชำระเงินผ่านธนาคาร',500,'paid',1203),
('4106565500','2017-09-16','ชำระเงินผ่านธนาคาร',500,'paid',1195),
('1248193225','2017-09-13','ชำระเงินผ่านธนาคาร',500,'paid',1182),
('6192339971','2017-09-15','ชำระเงินผ่านธนาคาร',500,'paid',1159),
('4423732721','2017-09-14','ชำระเงินผ่านธนาคาร',500,'paid',1111),
('9416225609','2017-09-16','ชำระเงินผ่านธนาคาร',500,'paid',1100),
('8576635626','2017-09-11','ชำระเงินผ่านธนาคาร',500,'paid',1053),
('3482257319','2017-09-18','ชำระเงินผ่านธนาคาร',500,'paid',1050),
('6590136150','2017-09-14','ชำระเงินผ่านธนาคาร',500,'paid',1041),
('1944675311','2017-09-17','ชำระเงินผ่านธนาคาร',500,'paid',1003),
('2013609754','2017-11-17','ชำระเงินหน้างาน',100,'paid',1044),
('5059873811','2017-11-17','ชำระเงินหน้างาน',100,'paid',1069),
('8155386136','2017-11-17','ชำระเงินหน้างาน',100,'paid',1121),
('3069922715','2017-11-17','ชำระเงินหน้างาน',100,'paid',1179),
('1350343796','2017-11-17','ชำระเงินหน้างาน',100,'paid',1190),
('8589086063','2017-11-17','ชำระเงินหน้างาน',100,'paid',1273),
('1932102815','2017-11-17','ชำระเงินหน้างาน',100,'paid',1283),
('5913667353','2017-11-17','ชำระเงินหน้างาน',100,'paid',1289),
('1983243470','2017-08-25','ชำระเงินหน้างาน',250,'paid',1287),
('5455319160','2017-08-25','ชำระเงินหน้างาน',250,'paid',1281),
('5007033879','2017-08-25','ชำระเงินหน้างาน',250,'paid',1247),
('7400196540','2017-08-25','ชำระเงินหน้างาน',250,'paid',1180),
('1641249797','2017-08-25','ชำระเงินหน้างาน',250,'paid',1169),
('5585866492','2017-08-25','ชำระเงินหน้างาน',250,'paid',1163),
('3747959245','2017-08-25','ชำระเงินหน้างาน',250,'paid',1148),
('1592726121','2017-08-25','ชำระเงินหน้างาน',250,'paid',1129),
('1371374704','2017-08-25','ชำระเงินหน้างาน',250,'paid',1088),
('3158448695','2017-08-25','ชำระเงินหน้างาน',250,'paid',1065),
('9147174680','2017-08-25','ชำระเงินหน้างาน',250,'paid',1032),
('4147352111','2017-06-28','ชำระเงินผ่านธนาคาร',2000,'paid',1016),
('3521178891','2017-06-28','ชำระเงินผ่านธนาคาร',2000,'paid',1045),
('6722492035','2017-06-28','ชำระเงินผ่านธนาคาร',2000,'paid',1059),
('7816886161','2017-06-28','ชำระเงินผ่านธนาคาร',2000,'paid',1072),
('7693262878','2017-07-07','ชำระเงินผ่านธนาคาร',2000,'paid',1081),
('3630889841','2017-07-01','ชำระเงินผ่านธนาคาร',2000,'paid',1091),
('7206507666','2017-06-30','ชำระเงินผ่านธนาคาร',2000,'paid',1119),
('6320863534','2017-07-02','ชำระเงินผ่านธนาคาร',2000,'paid',1152),
('9164746767','2017-06-29','ชำระเงินผ่านธนาคาร',2000,'paid',1192),
('3784315172','2017-07-03','ชำระเงินผ่านธนาคาร',2000,'paid',1230),
('7585525406','2017-07-06','ชำระเงินผ่านธนาคาร',2000,'paid',1244),
('4444392124','2017-06-29','ชำระเงินผ่านธนาคาร',2000,'paid',1254),
('7372596101','2017-07-04','ชำระเงินผ่านธนาคาร',2000,'paid',1260),
('7093222938','2018-01-19','ชำระเงินผ่านธนาคาร',500,'paid',1017),
('9967444083','2018-01-24','ชำระเงินผ่านธนาคาร',500,'paid',1061),
('1342669391','2018-01-20','ชำระเงินผ่านธนาคาร',500,'paid',1132),
('9085941916','2018-01-21','ชำระเงินผ่านธนาคาร',500,'paid',1171),
('9089687618','2018-01-22','ชำระเงินผ่านธนาคาร',500,'paid',1229),
('8524834198','2018-01-23','ชำระเงินผ่านธนาคาร',500,'paid',1233),
('7061597072','2018-01-19','ชำระเงินผ่านธนาคาร',500,'paid',1239),
('9131122819','2018-01-23','ชำระเงินผ่านธนาคาร',500,'paid',1276),
('7779918719','2017-06-11','ชำระเงินผ่านธนาคาร',500,'paid',1296),
('7162549305','2017-06-18','ชำระเงินผ่านธนาคาร',500,'paid',1282),
('7922623265','2017-06-15','ชำระเงินผ่านธนาคาร',500,'paid',1262),
('3861361007','2017-06-17','ชำระเงินผ่านธนาคาร',500,'paid',1220),
('1414354793','2017-06-12','ชำระเงินผ่านธนาคาร',500,'paid',1198),
('2215898373','2017-06-16','ชำระเงินผ่านธนาคาร',500,'paid',1144),
('4450428044','2017-06-14','ชำระเงินผ่านธนาคาร',500,'paid',1122),
('7231665227','2017-06-17','ชำระเงินผ่านธนาคาร',500,'paid',1114),
('7384962719','2017-06-18','ชำระเงินผ่านธนาคาร',500,'paid',1106),
('1224384965','2017-06-18','ชำระเงินผ่านธนาคาร',500,'paid',1075),
('2868279573','2017-06-11','ชำระเงินผ่านธนาคาร',500,'paid',1049),
('3118839325','2017-06-12','ชำระเงินผ่านธนาคาร',500,'paid',1040),
('5315072351','2017-06-13','ชำระเงินผ่านธนาคาร',500,'paid',1004),
('9454786024','2017-04-04','ชำระเงินผ่านธนาคาร',450,'paid',1056),
('2031672122','2017-04-14','ชำระเงินผ่านธนาคาร',450,'paid',1215),
('6269195104','2018-01-05','ชำระเงินผ่านธนาคาร',500,'paid',1014),
('1877431344','2018-01-08','ชำระเงินผ่านธนาคาร',500,'paid',1021),
('7336331928','2018-01-10','ชำระเงินผ่านธนาคาร',500,'paid',1146),
('5202213638','2018-01-06','ชำระเงินผ่านธนาคาร',500,'paid',1298),
('9254005375','2018-01-17','ชำระเงินผ่านธนาคาร',500,'paid',1299);
<file_sep>/README.md
# Camp-Maejo-University
ฐานข้อมูลค่ายภายในมหาวิทยาลัยแม่โจ้
| f39080f260feb58d0ad10fde60b94bcb93215fbc | [
"Markdown",
"SQL"
] | 2 | SQL | Sujittrapa6337/Camp-Maejo-University | 5fc4f0bc30d20d508354bc49543ad9f4a80349e6 | 68230fc60f79eb5e1267c2ba038cbf06ba239660 |
refs/heads/master | <repo_name>glucena/ng-progressbar-directive<file_sep>/README.md
# Progressbar directive
Diretive to use [Progress Bar JS](https://kimmobrunfeldt.github.io/progressbar.js/) in angular apps.
## Usage
Install the progressbar library
```
npm install progressbar.js
```
Add the library to the angular-cli
```json
...
"scripts": [
"../node_modules/progressbar.js/dist/progressbar.min.js",
...
],
...
```
Put the directive somewhere in your app and import the directive into the module
```typescript
import { ProgressBarDirective } from './directives/progressbar.directive';
@NgModule({
declarations: [,
ProgressBarDirective,
...
],
...
exports: [
MyModule
]
})
export class MyModule {}
```
And use it in the HTML as follow
```html
<div id="circularProgressBar"
[progressBar]="'circle'"
[progressBarColor]="'#fff'"
[progressBarTrailColor]="'#fff'"
[progressBarFrom]='{"color": "#3498db", "width": 4}'
[progressBarTo]='{"color": "#ffd200", "width": 4}'
[progressBarValue]="42">
</div>
```
# Progress bar parameters
| Name | Description
| --- | ---
progressBar | The bar type. Could be circle, semicircle or line
progressBarColor | The bar color
progressBarTrailColor |
progressBarTrailwidth |
progressBarStrokewidth | Stronke width
progressBarFrom | Progress bar initial color
progressBarTo | Progress bar final color
progressBarValue | The progress bar value
progressBarEasing | Easing function: linear, easeIn, easeOut, easeInOut
progressBarDuration | Animation duration<file_sep>/progressbar.module.ts
/*
* @Author: <NAME>
* @Date: 2018-01-10 18:32:45
* @Last Modified by: <NAME>
* @Last Modified time: 2018-01-10 18:32:45
*/
import { NgModule } from '@angular/core';
// Directive
import { ProgressBarDirective } from './progressbar.directive';
@NgModule({
declarations: [
ProgressBarDirective
],
exports: [
// exporting root module
ProgressBarDirective
]
})
export class ProgressBarModule {}
| dbb2f501a87f4fed4ab7e1bc3bc8c8a4dd0278f0 | [
"Markdown",
"TypeScript"
] | 2 | Markdown | glucena/ng-progressbar-directive | 89750e200b8e7436003f104a697238f16f9751be | d09a2c00ef96f41d55b2d69c589c51029571bb16 |
refs/heads/master | <file_sep><?php
class Dates {
/**
* Todays Date
*/
private static $today;
private static $tomorrow;
/**
* Getter for todays date
*
* @return Todays date in DateTime Format
*/
public static function getToday() {
return self::$today;
}
/**
* Getter for tomorrows date
*
* @return Todays date in DateTime Format
*/
public static function getTomorrow() {
return self::$tomorrow;
}
/**
* Setter for todays date
*
*/
public static function setToday() {
self::$today= new DateTime();
}
/**
* Setter for tomorrows date
*
*/
public static function setTomorrow() {
self::$tomorrow= new DateTime('tomorrow');
}
/**
* Adjust input date by a date interval
*
* @param $date - Input date in DateTime format
* @param $dateInterval - Interval to adjust date by.
* @param $direction - past or future depending if you want to go forward or back
*
* @return the adjusted date
*/
public static function dateAdjust($date, $dateInterval, $direction="future") {
$tempDate= new DateTime($date->format('Y-m-d'));
if ($direction == "future") {
$tempDate->add(new DateInterval($dateInterval));
} else {
$tempDate->sub(new DateInterval($dateInterval));
}
return $tempDate;
}
/**
* Creates a DateTime object from the user input date
*
* @param Date in dd/mm/yyyy format as input by user
*
* @return DateTime object OR false if the input date is invalid
*
*
*/
public static function createDTFromInput($inputDate) {
$dateArray=explode('/', $inputDate);
if (count($dateArray) != 3) {
return false;
}
$valid=checkdate($dateArray[1], $dateArray[0], $dateArray[2]);
if ($valid) {
$dtInputDate = implode('-', [$dateArray[2], $dateArray[1], $dateArray[0]]);
return new DateTime($dtInputDate);
} else {
return false;
}
}
/**
* Convert date from input DD/MM/YYYY format to YYYY-MM-DD
* Date is assumed to be valid.
*
* @param string representing date in dd/mm/yyyy format
* @return string representing date in yyyy-mm-dd format
*/
public static function convInpToSQLDate($inputDate) {
$dateArray=explode('/', $inputDate);
return implode('-', [$dateArray[2], $dateArray[1], $dateArray[0]]);
}
/**
* Convert date from input YYYY-MM-DD format to DD/MM/YYYY
* Date is assumed to be valid.
*
* @param string representing date in yyyy-mm-dd format
* @return string representing date in dd/mm/yyyy format
*
*/
function convSQLDateToOutput($inputDate) {
$dateArray=explode('-', $inputDate);
return implode('/', [$dateArray[2], $dateArray[1], $dateArray[0]]);
}
}<file_sep><?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require_once SITEROOT.'/vendor/autoload.php';
require_once APPROOT.'/config/emailParams.php';
class Errors {
/**
* method reportAndRedirect
*
* Redirect to home page for un-recoverable errors, invoke errorEmail method to send email to programmer
* with debugging information. Produce general flash message for user and set error flag so session
* variables are destroyed by home controller.
*
*/
public static function reportAndRedirect($emailMessage, $userMessage) {
self::errorEmail($emailMessage);
$_SESSION['flash'] = $userMessage;
$_SESSION['error'] = true;
header('location: '.URLROOT);
exit;
}
/**
* method errorEmail
*
* Send an email to the developer if a serious error has occurred via PHP Mailer
*
* @param String representing the text of the message to be sent
*
*/
private static function errorEmail($message) {
$mail = new PHPMailer(true); // Passing `true` enables exceptions
$mail->SMTPDebug = 0; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = EmailParams::getAddressFrom(); // SMTP username
$mail->Password = EmailParams::getPassword(); // SMTP password
$mail->SMTPSecure = 'ssl'; // Secure transfer enabled required for gmail
$mail->Port = 465; // TCP port to connect to
$mail->SMTPKeepAlive = true;
$mail->Mailer = "smtp";
$mail->IsHTML(true);
//Recipients
$mail->setFrom(EmailParams::getAddressFrom(), 'Sunnyside Cottage Application'); //set 'to' address
$mail->addAddress(EmailParams::getAddressTo(), 'Marianne Porter'); //set 'from' address
//Content
$mail->Subject = 'Error:: Sunnyside Cottage Application';
$body="<p><strong>$message</strong></p>";
$mail->Body = $body;
$mail->AltBody = strip_tags($body);
$mail->send();
}
}<file_sep><?php
class User {
protected $db;
public function __construct() {
$this->db = new Database();
}
public function getUserByEmail($email) {
$query = 'SELECT * FROM users ';
$query .= 'WHERE email= :email ';
$this->db->prepare($query);
$this->db->bind('email', $email);
return $this->db->fetchSingleRow();
}
}<file_sep><?php
require_once APPROOT.'/config/database.php';
class Database extends DB_connect {
/**
* instance variables
*/
//PDO prepared statement
private $stmt;
/**
* Constructor for the dbProcess class
*
*/
public function __construct() {
parent::__construct();
}
/**
* call pdo prepare method to prepare SQL statement for execution.
* Sets up $stmt object in private instance variable
*
*/
public function prepare($query) {
$this->stmt=$this->pdo->prepare($query);
}
/**
* begin a PDO transaction
*
*/
public function beginTransaction() {
$this->pdo->beginTransaction();
}
/**
* commit a pdo transaction
*/
public function commitTransaction() {
$this->pdo->commit();
}
/**
* rollback a pdo transaction *
*/
public function rollback() {
$this->pdo->rollback();
}
/**
* returns the last id inserted into the database
*
*/
public function getLastInsertedId() {
return $this->pdo->lastInsertId();
}
/**
* Bind a parameter to the prepared statement object
*
* @param $param name of the parameter in prepared statement
* @param $value value to set the parameter to
* @param $type data type of parameter
*/
public function bind($param, $value, $type = null) {
if (is_null($type)) {
switch(true) {
case is_int($value) :
$type = PDO::PARAM_INT;
break;
case is_bool($value) :
$type = PDO::PARAM_BOOL;
break;
case is_null($value) :
$type = PDO::PARAM_NULL;
break;
default :
$type= PDO::PARAM_STR;
}
}
$this->stmt->bindValue($param, $value, $type );
}
/**
* Execute prepared statement
*
* @return true or false to indicate success or failure
*/
public function execute() {
return $this->stmt->execute();
}
/**
* PDO fetch for when just a single value is required
*
*/
public function fetchSingleValue() {
$row=$this->stmt->fetch(PDO::FETCH_NUM);
return $row[0];
}
/**
* Get a complete result set
*
* @return array of objects
*
*/
public function fetchResultSet() {
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_OBJ);
}
/*
public function fetchNextRow() {
return $this->stmt->fetch(PDO::FETCH_OBJ);
}
*/
/**
* Execute PDO prepared statement that gets a single db row and return that row
*
* @return object
*/
public function fetchSingleRow() {
$this->execute();
return $this->stmt->fetch(PDO::FETCH_OBJ);
}
/**
* fetch next row from PDO result set
*
*/
public function fetchResultSetRow() {
return $this->stmt->fetch(PDO::FETCH_OBJ);
}
}<file_sep><?php
/**
* Set up constants used across the application and invokes Dates class to set up todays date.
*
*/
define('APPROOT', '/app/app');
define('SITEROOT', dirname(APPROOT));
define('URLROOT', '/');
require_once APPROOT.'/utilities/Dates.php';
Dates::setToday();
Dates::setTomorrow();
<file_sep># Sunnyside Cottage
## Purpose of Application
Educational and to provide a demonstration of my skills to potential employers
## Description
PHP/mySQL application. Uses the MVC design pattern.
The application is a very simplistic booking system for a holiday cottage.
Admin users can add new dates for booking and make bookings.
Customers can check availability and make bookings.
The website is designed to be responsive and mobile friendly.<file_sep><?php
class EmailParams {
public static function getAddressFrom() {
return getenv('EMAIL_ADDRESS_FROM');
}
public static function getAddressTo() {
return getenv('EMAIL_ADDRESS_TO');
}
public static function getPassword() {
return getenv('EMAIL_PASSWORD');
}
}
<file_sep><div class="col-md-5 offset-md-1 mt-4">
<div id="availability-cal">
<h4>Availability</h4>
<div class="text-center">
<form method="post" action="<?php echo $data['formURL'] ?>" class="inline-form">
<input type="hidden" name="chkBackResub" value="<?php echo $data['chkBackResub']; ?>">
<button name="back-calendar" <?php echo ($data['disableBack']) ? ' disabled' : ''; ?>>
<i class="fas fa-angle-left"></i></button>
</form>
<span><?php echo $data['currMonthAndYear']; ?></span>
<form method="post" action="<?php echo $data['formURL'] ?>" class="inline-form">
<input type="hidden" name="chkFwdResub" value="<?php echo $data['chkFwdResub']; ?>">
<button name="forward-calendar" <?php echo ($data['disableForward']) ? ' disabled' : ''; ?>>
<i class="fas fa-angle-right"></i></button>
</form>
</div>
<table class="table table-sm table-bordered text-center mt-1">
<tr>
<th>Sun</th>
<th>Mon</th>
<th>Tue</th>
<th>Wed</th>
<th>Thur</th>
<th>Fri</th>
<th>Sat</th>
</tr>
<?php foreach ($data['calendar'] as $week) : ?>
<tr>
<?php foreach ($week as $day) :?>
<?php if ($day['status'] == 'Available' ) : ?>
<td class="bg-success">
<?php elseif ($day['status'] == 'Booked') : ?>
<td class="bg-danger">
<?php elseif ($day['status'] == 'NotAlloc') : ?>
<td class="bg-warning">
<?php else : ?>
<td class="text-muted bg-light">
<?php endif; ?>
<?php echo $day['dayNo'] ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>
<ul class="list-inline text-center">
<li class="list-inline-item"><i class="fas fa-circle text-success"></i><span class="ml-1">Available</span></li>
<li class="list-inline-item"><i class="fas fa-circle text-danger"></i><span class= "ml-1">Booked</span></li>
<li class="list-inline-item"><i class="fas fa-circle text-warning"></i><span class="ml-1">Not yet released</span></li>
<li class="list-inline-item"><i class="far fa-circle"></i></i><span class="ml-1">Not available for hire</span></li>
</ul>
</div>
</div>
<file_sep><?php
/**
* Sunnyside Cottage MVC Application
*
* Guests controller - handles all Guest bookings and is available for both Admin and Guest users
*
* Inherits from Bookings controller.
*
* Written by <NAME> June 2018
*
*/
require_once APPROOT.'/utilities/Errors.php';
require_once 'Bookings.php';
class Guests extends Bookings {
/**
* date of holiday start as selected by user
*/
private $holidayStartDate;
/**
* date of holiday end as selected by user
*/
private $holidayEndDate;
public function __construct() {
$this->bookingsModel=$this->model('BookHoliday');
}
/**
* selectDates Method
*
* processing which enables the user to select some holiday dates. Makes
* use of the calendar generated by parent class to aid the user's selection
*
*/
public function selectDates() {
session_start();
$this->viewData=[];
if ($_SERVER['REQUEST_METHOD'] == "POST") {
// set calendar max and minimum date
$this->calendarMinDate = new DateTime($_SESSION['calendarMinDate']);
$this->calendarMaxDate = new DateTime($_SESSION['calendarMaxDate']);
// submission of main form
if (isset($_POST['select-submit'])) {
$this->selectDatesProcess();
} else { // POST request is from the forward or back calendar buttons
$this->postRequestChangeCalMonth();
}
} else {
if (!isset($_SESSION['calendarMinDate'])) {
if (!$this->calendarInitialSetUp()) {
Errors::reportAndRedirect("Error occurred in Guests Controller - No rows found in bookings table",
"Your enquiry cannot be accepted at this time - please try again later");
}
} else {
$this->changeCalMonth('stay');
}
}
//All requests including GET and POST
$this->calendarProcessAllRequests();
$this->viewData['start_date'] = isset ($_SESSION['inputStartDate']) ? $_SESSION['inputStartDate'] : '';
$this->viewData['end_date'] = isset ($_SESSION['inputEndDate']) ? $_SESSION['inputEndDate'] : '';
$this->viewData['formURL'] = URLROOT.'guests/selectDates';
$this->view('guest/selectDates', $this->viewData);
}
/**
* confirm method
*
* process data input by select dates, reroutes to Users controller if user is not logged in,
* otherwise accesses the bookings model so the user can be given the price of the holiday they have selected
*
*/
public function confirm() {
session_start();
if (!isset($_SESSION['userId'])) {
header('location: '.URLROOT.'users/login/book');
exit;
}
$_SESSION['holidayCost'] =$this->bookingsModel->getCostForPeriod(Dates::convInpToSQLDate($_SESSION['inputStartDate']),
Dates::convInpToSQLDate($_SESSION['inputEndDate']));
$this->view('guest/confirm');
}
/**
* addBooking method
*
* accesses the BookHolidays model to reserve the holiday dates in the bookings table and to create
* a holiday row in the holidays table
*
*/
public function addBooking() {
session_start();
$bookingComplete = $this->bookingsModel->addHolidayBooking(Dates::convInpToSQLDate($_SESSION['inputStartDate']),
Dates::convInpToSQLDate($_SESSION['inputEndDate']),
$_SESSION['holidayCost'],
$_SESSION['userId'] );
$this->clearBookingSessionVariables();
if ($bookingComplete) {
$_SESSION['flash'] = "booking added successfully - enjoy your holiday";
} else {
Errors::reportAndRedirect("Transaction to add booking could not be completed in Guests Controller",
"Booking cannot be completed at this time - please try later");
}
header('location: '.URLROOT);
exit;
}
/**
* method : selectDatesProcess
*
* Controls validation and processing of a submitted selectDates form
* If valid the user is redirected to the checkConfirm form.
*
*
*/
private function selectDatesProcess() {
$this->viewData['start_date'] = trim($_POST['start-date']);
$this->viewData['end_date'] = trim($_POST['end-date']);
$this->viewData['start_date_err'] = '';
$this->viewData['end_date_err'] = '';
if ($this->valid()) {
$_SESSION['inputStartDate'] = $this->viewData['start_date'];
$_SESSION['inputEndDate'] = $this->viewData['end_date'];
header('location: '.URLROOT.'guests/confirm');
exit;
} else {
// invalid data, set calendar up for same month ready to redisplay page
$this->changeCalMonth('stay');
// save input data and error fields in session so these can stay unchanged
// if user changes calendar month
$_SESSION['inputStartDate'] = $this->viewData['start_date'];
$_SESSION['inputEndDate'] = $this->viewData['end_date'];
$_SESSION['inputStartDateErr'] = $this->viewData['start_date_err'];
$_SESSION['inputEndDateErr'] = $this->viewData['end_date_err'];
}
}
/**
* Used by the selectDates method for validation of input
*
* If valid instance variables for holiday start and end dates are set up for further processing
*
* @return true if input is valid false otherwise
*
*/
private function valid() {
$validData=true;
// validate individual fields
if (empty($this->viewData['start_date'])) {
$this->viewData['start_date_err'] = "Please enter start date of period";
$validData=false;
} else {
$this->holidayStartDate = Dates::createDTFromInput($this->viewData['start_date']);
if (!$this->holidayStartDate) {
$this->viewData['start_date_err'] = 'Please enter a valid date - format DD/MM/YYYY';
$validData=false;
} elseif (( $this->holidayStartDate < Dates::getToday()) || ($this->holidayStartDate > $this->calendarMaxDate)) {
$this->viewData['start_date_err']
= 'Please enter available date between '.Dates::getToday()->format('d/m/Y').' and '.$this->calendarMaxDate->format('d/m/Y');
$validData=false;
}
}
if (empty($this->viewData['end_date'])) {
$this->viewData['end_date_err'] = "Please enter end date of period";
$validData=false;
} else {
$this->holidayEndDate=Dates::createDTFromInput($this->viewData['end_date']);
if (!$this->holidayEndDate) {
$this->viewData['end_date_err'] = 'Please enter a valid date - format DD/MM/YYYY';
$validData=false;
} elseif ( ( $this->holidayEndDate < Dates::getToday()) || ( $this->holidayEndDate > $this->calendarMaxDate)) {
$this->viewData['end_date_err']
= 'Please enter available date between '.Dates::getToday()->format('d/m/Y').' and '.$this->calendarMaxDate->format('d/m/Y');
$validData=false;
}
}
// return value of false if individual input fields are invalid
if (!$validData) {
return false;
}
//All input fields valid individually - check end date is after start date
if ($this->holidayStartDate > $this->holidayEndDate) {
$this->viewData['start_date_err'] = 'Start Date must be before or the same as End Date';
$this->viewData['end_date_err'] = 'Start Date must be before or the same as End Date';
return false;
}
// access database to check dates are available
// check how many days the user has requested
$daysRequested=$this->holidayStartDate->diff($this->holidayEndDate)->days+1;
//do database access to check all dates in this period are available (check counts at this stage)
$daysAvailable=$this->bookingsModel->countAvailableDays($this->holidayStartDate->format('Y-m-d'),
$this->holidayEndDate->format('Y-m-d'));
if (!($daysAvailable == $daysRequested)) {
$this->viewData['start_date_err'] = 'Holiday not available - one or more booking days is reserved/unavailable';
$this->viewData['end_date_err'] = 'Holiday not available - one or more booking days is reserved/unavailable';
return false;
}
return $validData;
}
/**
* unset session variable that were used for selectdates and confirm processing
*
*/
private function clearBookingSessionVariables () {
unset ($_SESSION['inputStartDate'],
$_SESSION['inputStartDateErr'],
$_SESSION['inputEndDate'],
$_SESSION['inputEndDateErr'],
$_SESSION['holidayCost'],
$_SESSION['calendarMinDate'],
$_SESSION['calendarMaxDate'],
$_SESSION['currentFirstOfMonth'],
$_SESSION['currentLastOfMonth'],
$_SESSION['chkBackResub'],
$_SESSION['chkFwdResub'] );
}
}
<file_sep><?php
/**
* Sunnyside Cottage MVC Application
*
* Booking model - handles various accesses that are required to the bookings table
*
* Written by <NAME> June 2018
*
*/
class Booking {
/**
* Instance of the database class that handles the PDO database accesses
*/
protected $db;
/**
* constructor for booking class
*/
public function __construct() {
$this->db = new Database();
}
/**
* Check if booking dates exist for a period
*
* @param $startDate String in yyyy-mm-dd format
* @param $endDate String in yyyy-mm-dd format
*
* @return true if any rows exist between the two dates, false otherwise
*/
public function datesExist($startDate, $endDate) {
$query = 'SELECT COUNT(bookable_date) FROM bookings ';
$query .= ' WHERE bookable_date BETWEEN :start_date AND :end_date ';
$this->db->prepare($query);
$this->db->bind(':start_date', $startDate);
$this->db->bind(':end_date', $endDate);
$this->db->execute();
return $this->db->fetchSingleValue() > 0;
}
/**
* method: addDates
*
* Add rows to bookings table representing new dates available for booking between start and end date.
*
* @param $startDate String representing date in dd-mm-yyyy format
* @param $endDate String representing date in dd-mm-yyyy format
* @param $rate Integer representing amount charged per night for the cottage in pounds
*
* @return true if rows inserted successfully, false otherwise.
*/
public function addDates($startDate, $endDate, $rate) {
$currDBDate=$startDate;
$currDateTime=new DateTime($startDate);
$this->db->beginTransaction();
try {
do {
$query ="INSERT INTO bookings (bookable_date, cost_per_night, status, hol_id) ";
$query .=" VALUES ( :bookable_date, :cost_per_night, 'Available', 0)";
$this->db->prepare($query);
$this->db->bind(':bookable_date', $currDBDate);
$this->db->bind(':cost_per_night', $rate);
$this->db->execute($query);
$currDateTime=Dates::dateAdjust($currDateTime,'P1D');
$currDBDate=$currDateTime->format('Y-m-d');
} while ($currDBDate <= $endDate) ;
} catch (PDOException $e) {
// Error has occurred with an insert so rollback the whole transaction
$this->db->rollback();
return false;
}
//Rows inserted successfully
$this->db->commitTransaction();
return true;
}
/**
* method: findNextBookingDate
* Finds the next bookable_date in the bookings table after the input date
*
* @param $date String in YYYY-MM-DD format
* @return String representing date in YYYY-MM-DD
*
*/
public function findNextBookingDate($date) {
$query = "SELECT bookable_date FROM bookings " ;
$query .= "WHERE bookable_date > :date " ;
$query .= "LIMIT 1";
$this->db->prepare($query);
$this->db->bind(':date', $date);
$row=$this->db->fetchSingleRow();
return $row->bookable_date;
}
/**
* method : getLastBookableDate
*
* Get the final bookable_date on the bookings table
*
* @return String representing date in YYYY-MM-DD format
*
*/
public function getLastBookableDate() {
$query = "SELECT MAX(bookable_date) FROM bookings";
$this->db->prepare($query);
$retVal=$this->db->execute($query);
$bookable_date=$this->db->fetchSingleValue();
return $bookable_date;
}
/**
* method: getDataInDateRange
*
* Get all rows from bookings table that have dates between the two input parameters
*
* @param $startDate String YYYY-MM-DD format
* @param $endDate String YYYY-MM-DD format
*
* @return PDO result set consisting of array of objects from the selected rows
*/
public function getDataInDateRange($startDate, $endDate) {
$query = 'SELECT * FROM bookings ';
$query .= 'WHERE bookable_date BETWEEN :startDate AND :endDate';
$this->db->prepare($query);
$this->db->bind(':startDate', $startDate);
$this->db->bind(':endDate', $endDate);
$this->db->execute($query);
$dateRangeRows=$this->db->fetchResultSet();
return $dateRangeRows;
}
/**
* method: countBookableDatesAfter
*
* Counts how many rows thereare after the parameter date
*
* @param String in YYYY-MM-DD format
* @return integer representing the number of rows that meet the criteria
*
*/
public function countBookableDaysAfter($date) {
$query = 'SELECT COUNT(bookable_date) FROM bookings ';
$query .= 'WHERE bookable_date >:date';
$this->db->prepare($query);
$this->db->bind(':date', $date);
$this->db->execute($query);
return $this->db->fetchSingleValue();
}
/**
* method: selectBookableDatesAfter
*
* Select all rows from the bookings table after the parameter date. These are then stored in the Database class
* for later fetch/fetchall operations
*
* @param String in YYYY-MM-DD format
*
*/
public function selectBookableDetailsAfter($date) {
$query = 'SELECT * FROM bookings ';
$query .= 'WHERE bookable_date >:date';
$this->db->prepare($query);
$this->db->bind(':date', $date);
$this->db->execute($query);
}
/**
* method getBookableDetailsForDay
*
* get the booking table details fot the next row stored in the Db result set for bookings
*
*/
public function getBookableDetailsForDay() {
$currDayDetails=$this->db->fetchResultSetRow();
return $currDayDetails;
}
/**
* method countAvailableDays
*
* Count how many dates there are that have an Available status between the two input dates
*
* @param $startDate String in format YYYY-MM-DD
* @param $endDate String in format YYYY-MM-DD
*/
public function countAvailableDays($startDate, $endDate) {
$query = "SELECT COUNT(bookable_date) FROM bookings ";
$query .= " WHERE bookable_date BETWEEN :start_date AND :end_date ";
$query .= " AND status='Available' ";
$this->db->prepare($query);
$this->db->bind(':start_date', $startDate);
$this->db->bind(':end_date', $endDate);
$this->db->execute();
return $this->db->fetchSingleValue();
}
/**
* method: getCostForPeriod
*
* Works out sum of cost_per_night for all nights between the input dates
*
* @param $startDate String YYYY-MM-DD
* @param $endDate Sring YYYY-MM-DD
*
*/
public function getCostForPeriod($startDate, $endDate) {
$query = "SELECT SUM(cost_per_night) FROM bookings ";
$query .= " WHERE bookable_date BETWEEN :start_date AND :end_date ";
$query .= " AND status='Available' ";
$this->db->prepare($query);
$this->db->bind(':start_date', $startDate);
$this->db->bind(':end_date', $endDate);
$this->db->execute();
return $this->db->fetchSingleValue();
}
}<file_sep><?php
/**
* DB connection class for sunnyside_cottage database using PDO
*
*
*/
require_once APPROOT.'/utilities/Errors.php';
class DB_Connect {
/** @var \PDO $pdo database object for connecting to database */
protected $pdo;
/** Constructor for DB_Connect class */
protected function __construct() {
$this->CreatePDO();
}
/**
* Create PDO object and connect to DB and check if connection was successful.
* Handle error if necessary using try-catch block.
*
*/
protected function CreatePDO() {
$db_url = parse_url(getenv("CLEARDB_DATABASE_URL"));
$db_host = $db_url["host"];
$db_username = $db_url["user"];
$db_password = $<PASSWORD>["<PASSWORD>"];
$db_name = substr($db_url["path"], 1);
// Set DSN
$dsn='mysql:host='.$db_host.';dbname='.$db_name;
try {
$this->pdo=new \PDO($dsn, $db_username, $db_password);
$this->pdo->setAttribute( \PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION );
$this->pdo->setAttribute( \PDO::ATTR_EMULATE_PREPARES, false );
}
catch (PDOException $e) {
Errors::reportAndRedirect('Could not establish database connection',
'Your request cannot be completed at present - please try later');
}
}
}<file_sep><?php
class Users extends Controller {
/**
* Sunnyside Cottage MVC Application
*
* Users controller - handles all User functionality
* currently (June 2018) for login and logout only
*
* Inherits from Bookings controller.
*
* Written by <NAME> June 2018
*
*/
/**
* Row from user db corresponding to email entered
*/
private $user;
/**
* Constructor for Users controller
*
*/
public function __construct() {
$this->userModel=$this->model('User');
}
/**
* login method
*
* @param $source is a string which defaults to home to specify which page
* the user has come from so that they can be redirected back to the
* same place if necessary
*
*/
public function login($source='home') {
session_start();
$data=[
'email' => '',
'password' => '',
'email_err' => '',
'password_err' => '',
'source' => $source
];
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if ($this->valid($data)) {
$_SESSION['userId'] = $this->user->id;
$_SESSION['userFirstName']= $this->user->first_name;
$_SESSION['userLastName'] = $this->user->last_name;
$_SESSION['access'] = $this->user->access;
if ($source == 'book') {
header('location: '.URLROOT.'guests/confirm');
exit;
} else {
header('location: '.URLROOT);
exit;
}
}
}
$this->view('users/login', $data);
}
/**
* Validation of email and password for login
*
* @param $data reference variable for associative array, holds trimmed copies of input fields
* and any errors that need to be displayed in associated view
*
* @return boolean value true if data is valid false otherwise
*
*/
private function valid(&$data) {
$validData=true;
$data['email'] = trim($_POST['email']);
$data['password'] = trim($_POST['password']);
if (empty($data['email'])) {
$data['email_err'] = 'Please enter your email address';
$validData=false;
} elseif (filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
$this->user=$this->userModel->getUserByEmail($data['email']);
if (!$this->user) {
$data['email_err'] = 'Email not registered - please contact us to register';
$validData=false;
}
}
if (empty($data['password'])) {
$data['password_err'] = 'Please enter your password';
$validData=false;
}
if ($validData) {
if (!password_verify($data['password'], $this->user->password)) {
$data['password_err'] = 'User Id/Password combination not known';
$validData=false;
}
}
return $validData;
}
/**
* logout method
*
* destroys session and routes to main home page
*
*
*/
public function logout() {
session_start();
session_unset();
session_destroy();
header('location: '.URLROOT);
exit();
}
}<file_sep><?php require_once ( APPROOT.'/views/inc/header.php') ?>
<?php require_once ( APPROOT.'/views/inc/nav.php') ?>
<div class="card w-75 mx-auto">
<div class="container mt-3 mb-3 ml-1">
<h3>Sunnyside Cottage Website</h3>
<p>This website was written by <NAME> to demonstrate the skills I have learned on
my Open University courses and also from the many courses and tutorials available online</p>
<p>It is written based on the MVC design pattern. Skills in object oriented PHP, mySQL and also
front end skills are demonstrated.</p>
<p>There are more details about the design and structure of the website on Github</p>
</div>
</div>
<?php require_once ( APPROOT.'/views/inc/footer.php') ?><file_sep>/**
* Javascript and jQuery to be executed once page loaded
*
*/
$(document).ready( function() {
highlightActive();
});
/**
* Highlight the active nav option based on url
*
*/
function highlightActive() {
var url = window.location.pathname;
var selected='';
selected=findId(url);
$(selected).addClass("active");
}
/**
* findId function
*
* helper function for highlightActive
* finds the id of active element as determined by url so that it can be highlighted
*
* @param url
* @return id of selected element
*
*/
function findId(url) {
var fileName = url.split('/').reverse()[0];
switch (fileName) {
case 'selectDates' :
case 'confirm' :
selected = "#bookOption";
break;
case 'addDates' :
selected = "#addDatesOption";
break;
case 'show' :
selected = "#showPrices";
break;
case 'about' :
selected = "#aboutOption";
break;
default :
selected = "#homeOption";
}
return selected;
}<file_sep><div class="container">
<nav class="navbar navbar-expand-md navbar-dark bg-dark mb-3">
<button class="navbar-toggler order-1" data-toggle="collapse" data-target="#mainNav">
<span class="navbar-toggler-icon"></span>
</button>
<div id="mainNav" class="collapse navbar-collapse order-md-1 order-3">
<ul class="navbar-nav mr-auto">
<li class="nav-item" id="homeOption">
<a class="nav-link" href="<?php echo URLROOT; ?>">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item" id="bookOption">
<a class="nav-link" href="<?php echo URLROOT; ?>guests/selectDates">Book</a>
</li>
<?php if (isset($_SESSION['userId']) && $_SESSION['access'] == 'Admin') : ?>
<li class="nav-item" id="addDatesOption">
<a class="nav-link" href="<?php echo URLROOT; ?>admins/addDates">Add More Dates</a>
</li>
<?php endif; ?>
<li class="nav-item" id="showPrices">
<a class="nav-link" href="<?php echo URLROOT; ?>prices/show">Pricing</a>
</li>
<li class="nav-item">
<a class="nav-link" id="aboutOption" href="<?php echo URLROOT; ?>home/about">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Contact Us</a>
</li>
</ul>
</div>
<ul class="navbar-nav ml-auto order-2">
<?php if (isset($_SESSION['userId'])) : ?>
<!--user logged in -->
<li class="nav-item">
<a class="nav-link" href="#">Hello <?php echo $_SESSION['userFirstName']; ?></a>
</li>
<li class="nav-item">
<a class="nav-link" href="<?php echo URLROOT; ?>users/logout">Logout</a>
</li>
<?php else : ?>
<!--user not logged in -->
<li class="nav-item">
<a class="nav-link" href="<?php echo URLROOT; ?>users/login/home">Login</a>
</li>
<?php endif; ?>
</ul>
</div>
</nav> <file_sep><?php
/**
* Sunnyside Cottage MVC Application
*
* Admins controller - handles all Admin only processing
*
* Inherits from Bookings controller.
*
* Written by <NAME> 2018
*
*/
require_once 'Bookings.php';
require_once APPROOT.'/utilities/Errors.php';
class Admins extends Bookings {
/**
* Date of start of booking period
* DateTime format
*
*/
private $startDate;
/**
* Date of end of booking period
* DateTime format
*
*/
private $endDate;
/**
* Constructor for Admins class
*/
public function __construct() {
$this->bookingsModel=$this->model('Booking');
}
/**
* method to make new dates available on the bookings table
*
* In conjunction with the parent class Bookings, this method has to handle requests which
* will be one or three things
* 1. New dates submitted, in which case these need to validated an db updated if they are valid
* 2. Move calendar forwards
* 3. Move calendar backwards
*
* Session variables need to be updated as appropriate to enable the multiple types of request to be
* handled.
*/
public function addDates() {
session_start();
if (!isset($_SESSION['userId']) || ($_SESSION['access'] != 'Admin')) {
$_SESSION['flash'] = "Function Not Available - please login as Administrator";
header('location: '.URLROOT);
exit;
}
$this->viewData=[];
if ($_SERVER['REQUEST_METHOD'] == "POST") {
// set calendar max and minimum date
$this->calendarMinDate = new DateTime($_SESSION['calendarMinDate']);
$this->calendarMaxDate = new DateTime($_SESSION['calendarMaxDate']);
// submission of main form
if (isset($_POST['add-submit'])) {
$this->addDatesProcess();
} else { // POST request is from the forward or back calendar buttons
$this->postRequestChangeCalMonth();
$this->calendarProcessAllRequests();
}
} else { // get request
if ($this->calendarInitialSetUp()) {
$this->calendarProcessAllRequests();
}
}
$this->viewData['formURL'] = URLROOT.'admins/addDates';
$this->view('admin/addDates', $this->viewData);
}
/**
* method addDatesProcess
*
* Handle validation and processing of the Add dates form
* If valid the dates are added to the bookings table and the application redirected to
* the home page. If not valid erros are reported and calendar is regenerated to stay at
* the current month.
*
*/
private function addDatesProcess() {
$this->viewData['start_date'] = trim($_POST['start-date']);
$this->viewData['end_date'] = trim($_POST['end-date']);
$this->viewData['rate'] = trim($_POST['daily-rate']);
$this->viewData['start_date_err'] = '';
$this->viewData['end_date_err'] = '';
$this->viewData['rate_err'] = '';
if ($this->valid()) {
$this->unsetSessionAddVariables();
if ($this->bookingsModel->addDates($this->startDate->format('Y-m-d'),
$this->endDate->format('Y-m-d'),
$this->viewData['rate'])) {
$_SESSION['flash'] = "new dates added to database";
header('location: '.URLROOT);
exit;
} else {
Errors::reportAndRedirect('Error occurred in Admins Controller - Dates could not be added to bookings table',
'Dates cannot be added at present - please try later' );
}
} else {
// invalid data, set calendar up for same month ready to redisplay page
$this->changeCalMonth('stay');
// save input data and error fields in session so these can stay unchanged
// if user changes calendar month
$_SESSION['inputStartDate'] = $this->viewData['start_date'];
$_SESSION['inputEndDate'] = $this->viewData['end_date'];
$_SESSION['inputStartDateErr'] = $this->viewData['start_date_err'];
$_SESSION['inputEndDateErr'] = $this->viewData['end_date_err'];
$_SESSION['inputRate'] = $this->viewData['rate'];
$_SESSION['inputRateErr'] = $this->viewData['rate_err'];
$this->calendarProcessAllRequests();
}
}
/**
* Set up rate details for view from session variables where POST request has come from the calendar arrows,
* then invoke parent method of the same name to set up details for start and end dates.
*
* @param $data reference parameter, associative array containing data to be used by the view.
*
*/
public function postRequestChangeCalMonth() {
$data['rate'] = (isset($_SESSION['rate'])) ? $_SESSION['inputRate'] : '';
$data['rate_err'] = (isset($_SESSION['rate_err'])) ? $_SESSION['inputRateErr'] : '';
parent::postRequestChangeCalMonth();
}
/**
* method validates the input on the addDates page
*
* @return true if data is valid, false otherwise
*/
private function valid() {
$this->viewData['start_date'] = trim($_POST['start-date']);
$this->viewData['end_date'] = trim($_POST['end-date']);
$this->viewData['rate'] = trim($_POST['daily-rate']);
$this->viewData['start_date_err'] = '';
$this->viewData['end_date_err'] = '';
$this->viewData['rate_err'] = '';
$validData=true;
if (empty($this->viewData['start_date'])) {
$this->viewData['start_date_err'] = "Please enter start date of period";
$validData=false;
} else {
$this->startDate=Dates::createDTFromInput($this->viewData['start_date']);
if (!$this->startDate) {
$this->viewData['start_date_err'] = "Please enter a valid start date";
$validData=false;
} else {
$todayPlus11Mths=Dates::dateAdjust(Dates::getToday(), 'P11M');
if ($this->startDate < Dates::getTomorrow() || $this->startDate > $todayPlus11Mths) {
$this->viewData['start_date_err']
= 'Please enter a start date between '.Dates::getTomorrow()->format('d/m/Y').' and '.$todayPlus11Mths->format('d/m/Y');
$validData=false;
}
}
}
if (empty($this->viewData['end_date'])) {
$this->viewData['end_date_err'] = "Please enter end date of period";
$validData=false;
} else {
$this->endDate=Dates::createDTFromInput($this->viewData['end_date']);
if (!$this->endDate) {
$this->viewData['end_date_err'] = "Please enter a valid end date";
$validData=false;
} else {
$todayPlus1Year=Dates::dateAdjust(Dates::getToday(), 'P1Y');
if ( $this->startDate && ($this->startDate < Dates::getTomorrow() || $this->startDate > $todayPlus1Year) ) {
$this->viewData['end_date_err']
= 'Please enter a end date between '.Dates::getTomorrow()->format('d/m/Y').' and '.$todayPlus1Year->format('d/m/Y');
$validData=false;
}
}
}
// if start and end date are both valid, check end date is the same or later than start date
// and that dates have not already been allocated.
if ($this->startDate && $this->endDate) {
if ($this->endDate < $this->startDate) {
$this->viewData['end_date_err']
= 'Please enter a end date between '.$this->startDate->format('d/m/Y').' and '.$todayPlus1Year->format('d/m/Y');
$validData=false;
} elseif ($this->bookingsModel->datesExist($this->startDate->format('Y-m-d'), $this->endDate->format('Y-m-d'))) {
$this->viewData['start_date_err'] = 'Dates/Rates already allocated ';
$this->viewData['end_date_err'] = 'Dates/Rates already allocated ';
$validData=false;
}
}
if (empty($this->viewData['rate'])) {
$this->viewData['rate_err'] = "Please enter rate per day for period";
$validData=false;
} elseif (!preg_match('/^[0-9]+(\.[0-9]{2})?$/', $this->viewData['rate'])) {
$this->viewData['rate_err'] = "Rate per day must be a valid money value";
$validData=false;
} elseif ($this->viewData['rate'] < 20 || $this->viewData['rate'] > 150) {
$this->viewData['rate_err'] = "Rate per day must be between 20 and 150";
$validData=false;
}
return $validData;
}
/**
* method to unset the session variables after new dates have been added to the bookings table
*
*/
private function unsetSessionAddVariables() {
unset ( $_SESSION['inputStartDate'],
$_SESSION['inputStartDateErr'],
$_SESSION['inputEndDate'],
$_SESSION['inputEndDateErr'],
$_SESSION['inputRate'],
$_SESSION['inputRateErr'],
$_SESSION['calendarMinDate'],
$_SESSION['calendarMaxDate'],
$_SESSION['currentFirstOfMonth'],
$_SESSION['currentLastOfMonth'],
$_SESSION['chkBackResub'],
$_SESSION['chkFwdResub'] );
}
}
<file_sep><?php
/**
* Sunnyside Cottage MVC Application
*
* Bookings controller
*
* Parent class for those classes that need to check availability via the calendar
*
* Written by <NAME> June 2018
*
*/
class Bookings extends Controller {
/**
* Three dimensional array comprising weeks, days within each week and booking status for each day
*/
protected $calendarForMonth;
/**
* Latest Date that will be displayed by application (last month where there are bookable_dates)
*/
protected $calendarMaxDate;
/**
* Earliest Date that will be displayed by application (first month where there are bookable_dates)
*/
protected $calendarMinDate;
/**
* 1st of the month that will be displayed in the view
*/
protected $monthStartDate;
/**
* last date for the month that will be dispalyed in the view
*/
protected $monthEndDate;
/**
* Data from booking table giving availability for current month
*/
private $dataForMonth;
/**
* Current Month and Year for Calendar
*
*/
protected $currMonthAndYear;
/**
* Data and Error messages to be output in the view
*
*/
protected $viewData;
/**
* Constructor for the Bookings class
*/
public function __construct() {
$this->bookingsModel=$this->model('Booking');
}
/**
* Initial setup of calendar and calendar SESSION variables
*
* 1. Invoke getDatesForInitialCalendar to set up start and end dates for the initial calendar month
*
* 2. Sets up session calendar variables to earliest and latest possible dates for the whole calendar and first of current calendar month
*
* 3. Invokes makeCalendar() to make the 3 dimensional calendar array for display
*
* @return 3 dimensional array giving weeks, days within weeks and the booking status for each day within the week
* OR false if no dates on the bookings table
*
*/
protected function calendarInitialSetup() {
$lastBookingDate=$this->bookingsModel->getLastBookableDate();
if ($lastBookingDate) {
$this->calendarMaxDate= (new DateTime ($lastBookingDate))->modify('last day of this month');
} else {
return false;
}
$this->calendarMinDate = Dates::getTomorrow()->modify('first day of this month');
$_SESSION['calendarMinDate'] = $this->calendarMinDate->format('Y-m-d');
$_SESSION['calendarMaxDate'] = $this->calendarMaxDate->format('Y-m-d');
$this->getDatesForInitialMonth();
$this->calendarForMonth = $this->makeCalendar();
// initial calendar set up successfully so return true
return true;
}
/**
* set month start and month end instance variable for the first time the page is displayed
*
* this will normally be first and last day of the current month, however if no bookable dates exist in the current
* month the initial calendar month will be the first month for which dates do exist.
*
*/
private function getDatesForInitialMonth() {
// Set start and end dates for calendar to first and last day of current month
$this->monthStartDate = clone $this->calendarMinDate;
$this->monthEndDate = clone $this->calendarMinDate;
$this->monthEndDate->modify('last day of this month');
// Test if bookable dates exist in the current month. If not find first month where bookable dates do exist
// and set start and end dates to first and last days of that month
if (!$this->bookingsModel->datesExist($this->monthStartDate->format('Y-m-d'), $this->monthEndDate->format('Y-m-d'))) {
$nextBookingDate=$this->bookingsModel->findNextBookingDate($this->monthEndDate->format('Y-m-d'));
// Change start and end dates to first month where bookable dates exist if no dates exist in the current month
$this->monthStartDate = new DateTime($nextBookingDate);
$this->monthStartDate->modify('first day of this month');
$this->monthEndDate = clone $this->monthStartDate;
$this->monthEndDate->modify('last day of this month');
}
}
/**
* Alter month displayed on calendar if forward or back arrows pressed
*
* @param $data associative array - reference parameter for $data array which holds variables to be used in the view
*/
protected function postRequestChangeCalMonth() {
$this->viewData['start_date'] = (isset($_SESSION['inputStartDate'])) ? $_SESSION['inputStartDate'] : '';
$this->viewData['end_date'] = (isset($_SESSION['inputEndDate'])) ? $_SESSION['inputEndDate'] : '';
$this->viewData['start_date_err'] = (isset($_SESSION['inputStartDateErr'])) ? $_SESSION['inputStartDateErr'] : '';
$this->viewData['end_date_err'] = (isset($_SESSION['inputEndDateErr'])) ? $_SESSION['inputEndDateErr'] : '';
if (isset($_POST['back-calendar'])) {
if ($_POST['chkBackResub'] == $_SESSION['chkBackResub']) {
$this->changeCalMonth('back');
} else {
$this->changeCalMonth('stay');
}
} else {
if ($_POST['chkFwdResub'] == $_SESSION['chkFwdResub']) {
$this->changeCalMonth('forward');
} else {
$this->changeCalMonth('stay');
}
}
}
/**
* For all post and get requests: prepare calendar for output and set up Session variables to
* record first and last of this month
*
*/
protected function calendarProcessAllRequests() {
$_SESSION['currentFirstOfMonth'] = $this->monthStartDate->format('Y-m-d');
$_SESSION['currentLastOfMonth'] = $this->monthEndDate->format('Y-m-d');
$this->viewData['calendar'] = $this->calendarForMonth;
$this->viewData['currMonthAndYear']=$this->currMonthAndYear;
$this->viewData['disableBack'] =($this->calendarMinDate == $this->monthStartDate);
$this->viewData['disableForward']=($this->calendarMaxDate == $this->monthEndDate);
// set up random number in session and in form so that application can check if either
// back or forward buttons have been pressed
$random=rand();
$this->viewData['chkBackResub'] = $random;
$_SESSION['chkBackResub'] = $random;
$random=rand();
$this->viewData['chkFwdResub'] = $random;
$_SESSION['chkFwdResub'] = $random;
}
/**
* Move Calendar forward or backwards by one month or stay in the same place as specified by session variables
*
* @param $direction a string containing back forward or stay depending on which calendar month is required next
*
*/
protected function changeCalMonth($direction) {
$this->monthStartDate = new DateTime($_SESSION['currentFirstOfMonth']);
$this->monthEndDate = new DateTime($_SESSION['currentLastOfMonth']);
if ($direction == 'back') {
$this->monthStartDate->modify('first day of last month');
$this->monthEndDate->modify('last day of last month');
} elseif ($direction == 'forward') {
$this->monthStartDate->modify('first day of next month');
$this->monthEndDate->modify('last day of next month');
}
$this->calendarForMonth = $this->makeCalendar();
}
/**
* Create the 3 dimensional array to represent the calendar.
*
* Arrays contains standard 2 dimensional calendar with weeks and days with the third dimension
* giving availability for each individual day.
*
*
*/
private function makeCalendar() {
$this->dataForMonth=$this->bookingsModel->getDataInDateRange($this->monthStartDate->format('Y-m-d'),
$this->monthEndDate->format('Y-m-d'));
$this->currMonthAndYear=date('F', $this->monthStartDate->getTimestamp()).' '.substr($this->monthStartDate->format('Y-m-d'),0,4);
$firstDayOfMonth = date('w', $this->monthStartDate->getTimestamp());
$daysInMonth= date('t', $this->monthStartDate->getTimestamp());
$monthArray=array();
$monthArray[0]=array();
// set spare entries at start of calendar to '-'
for ($i=0; $i<$firstDayOfMonth; $i++) {
$monthArray[0][$i]=[];
$monthArray[0][$i]["dayNo"] = '-';
$monthArray[0][$i]["status"] = 'NotApplic';
}
//put dates into the array
$colSub=$firstDayOfMonth;
$rowSub=0;
$currDate= clone $this->monthStartDate;
for ($i=0; $i<$daysInMonth; $i++) {
$dayOfMonth=$i+1;
$monthArray[$rowSub][$colSub]=[];
$monthArray[$rowSub][$colSub]["dayNo"]=$dayOfMonth;
if ($currDate > Dates::getToday()) {
$monthArray[$rowSub][$colSub]["status"]=$this->findStatusForDay($currDate->format('Y-m-d'));
} else {
$monthArray[$rowSub][$colSub]["status"]="NotApplic";
}
$colSub++;
if ($colSub==7) {
$rowSub++;
$monthArray['rowSub']=array();
$colSub=0;
}
$currDate->modify('+1 day');
}
// set spare entries at end of calendar to '-'
if ($colSub != 0) {
for ($i=$colSub; $i<7; $i++) {
$monthArray[$rowSub][$i]=[];
$monthArray[$rowSub][$i]["dayNo"]='-';
$monthArray[$rowSub][$i]["status"]='NotApplic';
}
}
return $monthArray;
}
/**
* Gets bookings table status for the date passed as parameter
*
* @param date in YYYY-MM-DD format
*
* @return db enum as string for Booked, Available or Owner Use or alternatively NotAlloc if date is
* not in the database table
*/
private function findStatusForDay($currDate) {
$status="NotAlloc";
foreach ($this->dataForMonth as $bookingRow) {
if ($bookingRow->bookable_date == $currDate) {
$status=$bookingRow->status;
break;
}
}
return $status;
}
}
<file_sep><?php require_once ( APPROOT.'/views/inc/header.php') ?>
<?php require_once ( APPROOT.'/views/inc/nav.php') ?>
<?php require_once ( APPROOT.'/views/inc/flash.php') ?>
<div class="card w-75 mx-auto mt-3">
<div class="container mt-2 mb-3 ml-1">
<h3>Sunnyside Cottage Website</h3>
<p>Designed as an example application to demonstrate a PHP MVC Application</p>
<p>There is a little more detail about the application on the about page and a lot more on Github.</p>
</div>
</div>
<?php require_once ( APPROOT.'/views/inc/footer.php') ?>
<file_sep><?php
class SessionProcess {
public static function destroy() {
session_unset();
session_destroy();
}
}<file_sep><?php
class App {
/**
* handles routing to required method and controller as specified in the URL
* including setting up of parameter array if necessary
*
*/
//default controller, method and parameters
protected $controller;
protected $method;
protected $params = [];
protected $defaultControllerName = "Home";
protected $defaultMethod="index";
//exploded url
private $url;
public function __construct() {
//check if there is a url and if so explode into an array of component parts
$this->url=$this->parseUrl();
if ($this->url && isset($this->url[1])) {
// url processing where controller and method are specified
$this->processURL();
} else {
// load and instantiate default controller if not supplied in url
require_once APPROOT.'/controllers/'.$this->defaultControllerName.'.php';
$this->controller = new $this->defaultControllerName();
$this->method = $this->defaultMethod;
}
// invoke chosen controller and method
call_user_func_array([$this->controller, $this->method], $this->params);
}
/**
* explode and trim sanitised URL
*
*/
private function parseUrl() {
if (isset($_GET['url'])) {
return $url= explode('/',filter_var(rtrim($_GET['url'], '/'), FILTER_SANITIZE_URL));
} else {
return false;
}
}
/**
* Process URL query string where one exists
* Instantiate chosen controller for valid query strings or the default controller and method otherwise.
*
*/
private function processURL() {
//Check file exists corresponding to the name of controller
$controllerName=ucwords($this->url[0]);
if (file_exists(APPROOT.'/controllers/'.$controllerName.'.php')) {
$this->controller=$controllerName;
unset($this->url[0]);
} else {
$this->controller=$this->defaultControllerName;
unset($this->url[0]);
}
require_once APPROOT.'/controllers/'.$this->controller.'.php';
// instantiate new instance of chosen controller
$this->controller = new $this->controller();
// check method exists within controller
if (method_exists($this->controller, $this->url[1])) {
$this->method=$this->url[1];
unset($this->url[1]);
} else {
// load and instantiate default controller if method not found in url controller
unset($this->controller);
require_once APPROOT.'/controllers/'.$this->defaultControllerName.'.php';
$this->controller = new $this->defaultControllerName();
$this->method = $this->defaultMethod;
return;
}
// store parameteres from url
$this->params = $this->url ? array_values($this->url) : [];
}
}
<file_sep><?php if (isset($data['flash'])) : ?>
<div class="alert alert-success">
<?php echo (isset($data['flash'])) ? $data['flash'] : ''; ?>
</div>
<?php endif; ?><file_sep><?php
/**
* Sunnyside Cottage MVC Application
*
* BookHoliday model - handles data accesses involving both holidays and bookings tables
*
* Inherits from Booking model.
*
* Written by <NAME> June 2018
*
*/
require_once 'Booking.php';
class BookHoliday extends Booking {
protected $db;
public function __construct() {
$this->db = new Database();
}
/**
* Controls PDO transaction processing for a new holiday booking.
* Adds a new row to the holidays table to record the holiday that has been booked and
* then changes the status of the dates to booked in the booking table.
* If any errors occur the whole transaction is rolled back
*
* @param $startDate 1st date in holiday
* @param $endDate Last date in holiday
*
*/
public function addHolidayBooking($startDate, $endDate, $totalCost, $userId) {
$success=true;
try {
$this->db->beginTransaction();
$query="INSERT INTO holidays ";
$query .= "( user_id, start_date, end_date, total_cost, amount_paid )";
$query .= "VALUES( :user_id, :start_date, :end_date, :total_cost, :amount_paid )";
$this->db->prepare($query);
$this->db->bind(':user_id', $userId);
$this->db->bind(':start_date', $startDate);
$this->db->bind(':end_date', $endDate);
$this->db->bind(':total_cost', $totalCost);
$this->db->bind(':amount_paid', 0);
$success=$this->db->execute($query);
$holidayId=$this->db->getLastInsertedId();
$query = " UPDATE bookings ";
$query .= " SET status = :booked, hol_id = :hol_id ";
$query .= " WHERE bookable_date BETWEEN :start_date AND :end_date";
$this->db->prepare($query);
$booked='Booked';
$this->db->bind(':booked', $booked);
$this->db->bind(':start_date', $startDate);
$this->db->bind(':end_date', $endDate);
$success=$this->db->bind(':hol_id', $holidayId);
$success=$this->db->execute($query);
$this->db->commitTransaction();
}
catch (PDOException $e){
$success=false;
$this->db->rollback();
}
return $success;
}
}<file_sep><?php
/**
* Sunnyside Cottage MVC Application
*
* Home controller - handles Main Home page
* default controller for the website
*
*
* Written by <NAME> 2018
*
*/
require_once APPROOT.'/utilities/Session.php';
class Home extends Controller {
/**
* index method or the home controller. default method for the website
*
*/
public function index() {
session_start();
$data = [];
if (isset($_SESSION['flash'])) {
$data['flash'] = $_SESSION['flash'];
unset($_SESSION['flash']);
}
if (isset($_SESSION['error'])) {
SessionProcess::destroy();
}
$this->view('home/index', $data);
}
public function about() {
session_start();
$this->view('home/about');
}
}
<file_sep><?php require APPROOT.'/views/inc/header.php'; ?>
<div class="row">
<div class="col-10 offset-1 col-md-6 offset-md-3">
<div class="card mt-5">
<div class="card-header">
Login
</div>
<div class="card-body" id="login-form">
<form action="<?php echo URLROOT; ?>users/login/<?php echo $data['source'] ?>" method="post">
<div class="form-group">
<label for="email">Email</label>
<input type="email" name="email"
class="form-control form-control-lg <?php echo (!empty($data['email_err'])) ? ' is-invalid' : ''?>"
value= "<?php echo $data['email']; ?>">
<span class="invalid-feedback"><?php echo isset($data['email_err']) ? $data['email_err'] : ''; ?></span>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="<PASSWORD>" name="password"
class="form-control form-control-lg <?php echo (!empty($data['password_err'])) ? ' is-invalid' : ''?>"
value="<?php echo $data['password']?>">
<span class="invalid-feedback"><?php echo isset($data['password_err']) ? $data['password_err'] : ''; ?></span>
</div>
<input type="submit" class="btn btn-success" value="Submit">
</form>
</div>
</div>
</div>
</div>
<?php require APPROOT.'/views/inc/footer.php'; ?>
<file_sep><?php require APPROOT.'/views/inc/header.php'; ?>
<div class="row">
<div class="col-12 col-md-10 offset-md-1 col-lg-8 offset-lg-2">
<div class="card mt-5">
<div class="card-header">
<h5>Holiday Quotation for <?php echo $_SESSION['userFirstName'].' '.$_SESSION['userLastName'] ?></h5>
</div>
<div class="card-body">
<p class="lead text-center"> Dates: <?php echo $_SESSION['inputStartDate'].' to '.$_SESSION['inputEndDate'] ?> </p>
<p class="lead text-center"> Total Price is <?php echo '£'.number_format($_SESSION['holidayCost'],2) ?> </p>
<!-- buttons area -->
<div class="row"> <!-- extra small screens -->
<div class="d-sm-none col-6">
<a href="<?php echo URLROOT; ?>guests/selectDates"
class="btn btn-sm btn-secondary btn-block " role="button" ><i class="fa fa-backward fa-fw"></i>  Back/Cancel</a>
</div>
<div class="d-sm-none col-6">
<a href="<?php echo URLROOT; ?>guests/addBooking" class="btn btn-sm btn-success btn-block" role="button" >Confirm Booking</a>
</div>
</div>
<div class="row"> <!-- small and medium screens -->
<div class="d-none d-sm-block col-sm-6 d-lg-none">
<a href="<?php echo URLROOT; ?>guests/selectDates"
class="btn btn-secondary btn-block " role="button" ><i class="fa fa-backward fa-fw"></i>  Back to Select dates</a>
</div>
<div class="d-none d-sm-block col-sm-6 d-lg-none">
<a href="<?php echo URLROOT; ?>guests/addBooking" class="btn btn-success btn-block" role="button" >Confirm Booking</a>
</div>
</div>
<div class="row"> <!--large and extra large screens -->
<div class="d-none d-lg-block col-lg-5 offset-lg-1">
<a href="<?php echo URLROOT; ?>guests/selectDates"
class="btn btn-secondary btn-block " role="button" ><i class="fa fa-backward fa-fw"></i>  Back to Select dates</a>
</div>
<div class="d-none d-lg-block col-lg-5 offset-lg-1">
<a href="<?php echo URLROOT; ?>guests/addBooking" class="btn btn-success btn-block" role="button" >Confirm Booking</a>
</div>
</div>
</div>
</div>
</div>
</div>
<?php require APPROOT.'/views/inc/footer.php'; ?><file_sep><?php
require_once APPROOT.'/utilities/Errors.php';
/**
* Sunnyside Cottage MVC Application
*
* Prices controller - handles creation of the Prices page
*
* Written by <NAME> June 2018
*
*/
class Prices extends Controller {
public function __construct() {
$this->bookingsModel=$this->model('Booking');
}
/**
* show method
*
* Handles creation of Prices page
*
* Gets data from the bookings model and then organises this into an array so that the booking period
* can be seen along with the associated rates. This array is then used by the view.
*
*/
public function show() {
session_start();
$prices = [];
$prices[0] = [];
$pricesSub= 0;
$rowsExistOnBookings=($this->bookingsModel->countBookableDaysAfter(Dates::getToday()->format('Y-m-d')) > 0);
if (!$rowsExistOnBookings) {
Errors::reportAndRedirect("No rows exist on bookings table after todays date in Prices controller",
"Function not Currently Available");
}
$allBookableDays = $this->bookingsModel->selectBookableDetailsAfter(Dates::getToday()->format('Y-m-d'));
$day = $this->bookingsModel->getBookableDetailsForDay();
if ($day) {
$prices[0]['start_date'] = Dates::convSQLDateToOutput($day->bookable_date);
$prices[0]['rate'] = $day->cost_per_night;
}
while ($day) {
if ($day->cost_per_night != $prices[$pricesSub]['rate']) {
$prices[$pricesSub]['end_date'] = $prevDate;
$pricesSub++;
$prices[$pricesSub] = [];
$prices[$pricesSub]['start_date']=Dates::convSQLDateToOutput($day->bookable_date);
$prices[$pricesSub]['rate'] =$day->cost_per_night;
}
$prevDate=Dates::convSQLDateToOutput($day->bookable_date);
$day = $this->bookingsModel->getBookableDetailsForDay();
}
$prices[$pricesSub]['end_date'] = $prevDate;
$data['prices'] = $prices;
$this->view('prices/show', $data);
}
}
<file_sep><?php require APPROOT.'/views/inc/header.php'; ?>
<div class="row">
<div class="col-md-6">
<div class="card">
<h1 class="card-header">Add new Booking Period</i></h1>
<div class="card-body">
<form action="<?php echo URLROOT; ?>admins/addDates" method="post">
<div class="form-group">
<label for="start-date">Start Date</label>
<input type="text" name="start-date" placeholder="DD/MM/YYYY"
class="form-control form-control-lg <?php echo (!empty($data['start_date_err'])) ? ' is-invalid' : '' ?>"
value= "<?php echo (isset($data['start_date'])) ? $data['start_date'] : '' ?>">
<span class="invalid-feedback"><?php if (isset($data['start_date_err'])) echo $data['start_date_err'] ?></span>
</div>
<div class="form-group">
<label for="end-date">End Date</label>
<input type="text" name="end-date" placeholder="DD/MM/YYYY"
class="form-control form-control-lg <?php echo (!empty($data['end_date_err'])) ? ' is-invalid' : ''?>"
value= "<?php echo (isset($data['end_date'])) ? $data['end_date'] : '' ?>">
<span class="invalid-feedback"><?php if (isset($data['end_date_err'])) echo $data['end_date_err'] ?></span>
</div>
<div class="form-group">
<label for="daily-rate">Daily rate</label>
<input type="text" name="daily-rate"
class="form-control form-control-lg <?php echo (!empty($data['rate_err'])) ? ' is-invalid' : ''?>"
value="<?php echo (isset($data['rate'])) ? $data['rate'] : '' ?>" >
<span class="invalid-feedback"><?php echo isset($data['rate_err']) ? $data['rate_err'] : ''; ?></span>
</div>
<input type="submit" class="btn btn-success" name="add-submit" value="Submit">
</form>
</div>
</div>
</div>
<?php if (isset($data['currMonthAndYear'])) { require APPROOT.'/views/inc/calendar.php'; } ?>
</div>
<?php require APPROOT.'/views/inc/footer.php'; ?>
<file_sep><?php require_once (APPROOT.'/views/inc/header.php'); ?>
<?php require_once (APPROOT.'/views/inc/nav.php') ?>
<div class="row">
<div class="col-10 offset-1 col-md-6 offset-md-3">
<div class="card mt-2">
<div class="card-header">
<h1>Prices</h1>
</div>
<div class="card-body">
<table class="table" id="prices-table">
<tr><th>Cost per Night in pounds</th></tr>
<?php foreach ($data['prices'] as $price) : ?>
<tr>
<td><?php echo $price['start_date'].'-'.$price['end_date']; ?></td>
<td><?php echo $price['rate'] ?></td>
</tr>
<?php endforeach ?>
</table>
</div>
</div>
</div>
</div>
<?php require_once (APPROOT.'/views/inc/footer.php'); ?><file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"
integrity="<KEY>" crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css"
integrity="<KEY>" crossorigin="anonymous">
<link rel="stylesheet" href="<?php echo URLROOT ?>css/style.css">
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<script type="text/javascript" src="<?php echo URLROOT ?>js/main.js"></script>
<title>Sunnyside Cottage</title>
</head>
<body>
<div class="container">
<div class="row no-gutters" id="header">
<div class="col-6 col-md-3 order-1">
<img class="img-sizing" src="<?php echo URLROOT;?>images/SunnysideCottage.jpg" alt="Cottage photo">
</div>
<div class="col-12 order-3 col-md-6 order-md-2">
<h1 class="float-left">Sunnyside Cottage</h1>
<h2 class="float-right">Book your holiday today!!</h2>
</div>
<div class="col-6 order-2 col-md-3 order-md-3">
<img class="img-sizing float-right" src="<?php echo URLROOT;?>images/sunshine.png" alt="Sunshine photo">
</div>
</div>
</div>
<?php require APPROOT.'/views/inc/nav.php'; ?>
<div class="container"> | 56029079b666e44fc4b3ca1f28a030b565596283 | [
"Markdown",
"JavaScript",
"PHP"
] | 29 | PHP | marianneporter/SunnysideCottage | 6b15f957f42f4a98ca73454ddc7e071720dd493f | 616d1d83f10fc47c9bd66d0e4b691350669310cb |
refs/heads/master | <file_sep>/**
* Module dependencies
*/
var react = require('react');
var navbar = require('../../modules/navbar/navbar');
/**
* 'Home' view
*/
module.exports = react.createClass({
displayName: 'settings',
render: function() {
return react.DOM.div(null,
react.DOM.p(
{style: {color: 'white'}},
'settings'
),
navbar()
);
}
});<file_sep>/**
* Module dependencies
*/
var react = require('react');
var dispatcher = require('../../dispatcher/dispatcher');
/**
* Render a sidebar.
*
* @api public
*/
module.exports = react.createClass({
displayName: 'sidebar',
render: render
});
/**
* Render DOM.
*
* @return {ReactComponent}
* @api private
*/
function render() {
return react.DOM.div({className: 'sidebar'});
}<file_sep>/**
* Module dependencies
*/
var react = require('react');
var loginForm = require('../../modules/form/login');
/**
* 'Home' view
*/
module.exports = react.createClass({
displayName: 'login',
render: function() {
return react.DOM.div(null,
react.DOM.p({style: {color: 'black'}},
'login'
),
loginForm()
);
}
});<file_sep>/**
* Module dependencies
*/
var pathStore = require('../stores/path');
/**
* Initialize the 'path' store
*
* @param {Object} path
* @api public
*/
exports.initialize = function initialize(path) {
pathStore.add({path: path});
};
/**
* Update the 'path' store
*
* @param {String} path
* @api public
*/
exports.update = function update(path) {
pathStore.update({cid: 0, path: path});
};<file_sep># This is the first code kata
```js
with a nice javascript block
function() {
hello fools
}
```
- and
- a
- list
<file_sep>/**
* Module dependencies
*/
var react = require('react');
/**
* Render a sidebar.
*
* @api public
*/
module.exports = react.createClass({
displayName: 'course',
render: render
});
/**
* Render DOM.
*
* @return {ReactComponent}
* @api private
*/
function render() {
return react.DOM.section({className: 'section-course'});
}
<file_sep>/**
* Module dependencies
*/
var world = require("../support/world.js");
/**
* Step definitions
*/
module.exports = function () {
this.World = world;
this.Given('I am on the timeline page', function(callback) {
this.visit('http://localhost:8000', callback);
});
this.When(/^I do bla bla$/, function(callback) {
callback.pending();
});
this.Then(/^I should see "(.*)" as the page title$/, function(title, callback) {
var pageTitle = this.browser.text('title');
if (title === pageTitle) {
callback();
} else {
callback.fail(new Error("Expected to be on page with title " + title));
}
});
}; <file_sep>/**
* Module dependencies
*/
var usersStore = require('../stores/users');
/**
* Add a user to 'users'
*
* @param {Object} user
* @api public
*/
exports.add = function(user) {
usersStore.add(user);
};
/**
* Validate a target against the .
*/
exports.validate = function() {
usersStore.validate();
};<file_sep>/**
* Module dependencies
*/
var source = require('vinyl-source-stream');
var livereload = require('gulp-livereload');
var spawn = require('child_process').spawn;
var browserify = require('browserify');
var envify = require('envify/custom');
var eslint = require('gulp-eslint');
var concat = require('gulp-concat');
var myth = require('gulp-myth');
var gulp = require('gulp');
var path = require('path');
/**
* Exports
*/
module.exports = gulp;
/**
* Variables
*/
var ENV = process.env.NODE_ENV || 'development';
/**
* Compile CSS
*
* Includes css files in the following order
* /base/reset.css > /base/vars.css > /base/*.css > all other css files.
*/
gulp.task('styles', function() {
gulp
.src(['client/modules/index/reset.css',
'client/modules/index/vars.css',
'client/modules/index/!(reset, vars)*.css',
'client/modules/!(index)**/*.css'
])
.pipe(concat('build.css'))
.pipe(myth())
.pipe(gulp.dest(path.join(__dirname, '/build/')));
});
/**
* Compile JS
*
* Minifies only in production mode, makes bug tracking a lot easier while
* developing.
*/
gulp.task('modules', function() {
if ('development' != ENV) {
browserify(path.join(__dirname, '/client/modules/index/build.js'))
.transform('browserify-shim')
.transform(envify({NODE_ENV: ENV}))
.transform({global: true}, 'uglifyify')
.bundle({debug: true})
.pipe(source('build.js'))
.pipe(gulp.dest(path.join(__dirname, '/build/')));
}
if ('development' == ENV) {
browserify(path.join(__dirname, '/client/modules/index/build.js'))
//.transform('browserify-shim')
.transform(envify({NODE_ENV: ENV}))
.bundle({debug: true})
.pipe(source('build.js'))
.pipe(gulp.dest(path.join(__dirname, '/build/')));
}
});
/**
* Copy assets
*/
gulp.task('assets', function() {
gulp
.src(['client/modules/index/*.ttf'])
.pipe(gulp.dest(path.join(__dirname, '/build/fonts')));
});
/**
* Lint files
*/
gulp.task('lint', function() {
gulp
.src(['*.js', 'client/**/**/*.js', 'data/*.js', 'test/**/*.js'])
.pipe(eslint())
.pipe(eslint.format());
});
/**
* Run test
*/
gulp.task('test', function() {
var childProcess = Object.create(process);
childProcess.env.NODE_ENV = 'test';
var args = [
path.join(__dirname, './node_modules/mocha/bin/mocha'),
'--harmony',
'--recursive',
'-R',
'dot'
];
spawn(process.argv[0], args, {stdio: [0,1,2], env: childProcess.env});
var childProcessC = Object.create(process);
childProcessC.env.NODE_ENV = 'test';
var argsC = [
'--harmony',
path.join(__dirname, './node_modules/cucumber/bin/cucumber'),
'./test',
'-f',
'summary'
];
spawn(process.argv[0], argsC, {stdio: [0,1,2], env: childProcessC.env});
});
/**
* Watch for file changes
*/
gulp.task('watch', function() {
livereload.listen();
gulp.watch(['client/**/**/*.js', 'client/**/**/**/*.js'], ['modules']);
gulp.watch('client/modules/**/*.css', ['styles']);
gulp.watch(['*.js', 'client/**/**/*.js', 'data/*.js', 'test/**/*.js'], ['lint']);
gulp.watch('client/modules/**/*.tff', ['assets']);
gulp.watch(['/build/**']).on('change', livereload.changed);
});
/**
* Default
*/
gulp.task('default', [
'styles',
'modules',
'assets',
'lint',
'watch'
]);<file_sep>/**
* Module dependencies.
*/
var assert = require('assert');
var react = require('react');
/**
* Validation mixin.
*
* Expects an `{Object} validators` to be present with validation
* functions.
*
* Example:
*
* var form = react.createClass({
* validators: {
* userName: myModel.name.validate,
* gender: myModel.gender.validate
* }
* })
*
*
* The available states for objects are:
*
* │==============================│
* │ ACTION │ STATE │
* │==============================│
* │ initialized │ pristine │
* │ field is valid │ valid │
* │ field is invalid │ invalid │
* │==============================│
*
* The available states for the form are:
* │====================================│
* │ ACTION │ STATE │
* │====================================│
* │ allformsValidated │ false │
* │ submitted │ false │
* │ success │ false │
* │====================================│
*
*
* (1): If a field is invalid, the field should handle the error. Until
* all fields are valid, the form will remain 'editable'.
*/
module.exports = {
componentWillMount: componentWillMount,
updateFormString: updateFormString,
hasError: hasError,
resetError: resetError,
validateInputField: validateInputField,
allFormsValidated: allFormsValidated
};
/**
* Lifecycle: componentWillMount.
*/
function componentWillMount() {
assert(this.validators, 'this.validators should be an Object.');
this.setState({
// Check if all form fields are validated.
allFormsValidated: false,
// Check if the contents of the form have been submitted to the server.
submitted: false,
// Check if the form has been succesfully submitted.
succes: false,
// Hold the names of the forms that have an invalid input.
errors: []
});
Object.keys(this.validators)
.forEach(function(key) {
assert('function' == typeof this.validators[key], 'Validator should be a function.');
var obj = {};
obj[key] = {};
obj[key].isValid = 'pristine';
obj[key].value = '';
this.setState(obj);
}.bind(this));
}
/**
* Run validation on field, push 'key' to 'errors' array if failed.
*
* @param {String} key
* @api public
*/
function validateInputField(key) {
// Initialize empty obj.
var obj = {};
// Check if the validator[key] validates the formField value.
if (!this.validators[key].bind(this, this.state[key].value)) {
// If the error hasn't been bound yet, push the error.
if (!hasError.bind(this, key)) obj.errors = this.state.errors.push(key);
// Set invalid state on field.
obj[key] = {};
obj[key].isValid = 'invalid';
this.setState(obj);
return;
}
// Reset any errors.
if (hasError.bind(this, key)) resetError.bind(this, key);
// Set valid state on field.
obj[key] = {};
obj[key].isValid = 'valid';
this.setState(obj);
}
/**
* Update the form string.
*
* @param {String} key
* @param {KeyboardEvent} e
* @api public
*/
function updateFormString(key, e) {
this.state[key].value = e.target.value;
}
/**
* Check if all forms are filled in, set 'state.allFormsValidated'.
*
* @return {Boolean}
* @api public
*/
function allFormsValidated() {
return Object.keys(this.validators)
.every(function(validator) {
return !!this.state[validator];
}.bind(this));
}
/**
* Check if the component at 'key' has an error registered in 'errors'.
*
* @param {String} key
* @return {Boolean}
* @api private
*/
function hasError(key) {
return this.state.errors.any(function(error) {
return error == key;
});
}
/**
* Remove an error from the 'errors' array.
*
* @param {String} key
* @api private
*/
function resetError(key) {
this.setState({errors: this.state.errors.splice(key, 1)});
}<file_sep>/**
* Module dependencies
*/
var Dispatcher = require('barracks');
var users = require('./users');
var path = require('./path');
/**
* Initialize 'Dispatcher'
*/
var dispatcher = Dispatcher();
/**
* Expose 'Dispatcher()'.
*/
module.exports = dispatcher;
/**
* Register callbacks.
*/
dispatcher
.register('users_add', users.add)
.register('path_initialize', path.initialize)
.register('path_update', path.update);<file_sep>/* global window*/
/**
* Module dependencies
*/
var debug = require('debug')('versity:router');
var wayfarer = require('wayfarer');
var react = require('react');
var dispatcher = require('../../dispatcher/dispatcher');
var notFound = require('../../views/404/404');
var pathStore = require('../../stores/path');
var course = require('../../views/course');
var home = require('../../views/home');
var router = wayfarer();
/**
* Manage routes.
*/
module.exports = react.createClass({
displayName: 'router',
render: render,
propTypes: {
path: react.PropTypes.string.isRequired
}
});
/**
* Render DOM.
*/
function render() {
return course();
}
<file_sep>/* global window*/
/**
* Module dependencies
*/
var react = require('react');
var index = require('./index');
/**
* Variables
*/
var ENV = process.env.NODE_ENV;
var PORT = process.env.port || 1337;
var HOST = process.env.NODE_ENV == 'production' ? 'versity.co'
: 'versity.dev:' + PORT;
/**
* Render component on the client.
*
* This is the entry point for the build task (gulp), once all dependencies are
* loaded on the client `renderComponent()` gets triggered and makes all
* elements dynamic.
*/
module.exports = react.renderComponent(
index({
path: window.location.pathname,
host: HOST,
env: ENV
}),
window.document
);<file_sep>/**
* Module dependencies
*/
var router = require('koa-router');
var react = require('react');
var koa = require('koa');
var index = require('../../client/modules/index/index');
/**
* Variables
*/
var ENV = process.env.NODE_ENV;
var PORT = process.env.port || 1337;
var host = process.env.NODE_ENV == 'production'
? 'versity.co'
: 'versity.dev:' + PORT;
/**
* Initialize 'app'.
*/
var app = koa();
app.use(router(app));
/**
* Export 'app'.
*/
module.exports = app;
/**
* because fuck the favicon, that's why.
*/
app.get('/favicon.ico', function*(next) {})
/**
* Render
*/
app.get('*', function*(next) {
this.body = react.renderComponentToString(index({
path: this.path,
host: host,
env: ENV
}));
});
<file_sep>/**
* Module dependencies
*/
var store = require('dad');
/**
* Initialize 'users' store.
*/
var users = store('users');
/**
* Expose 'users';
*/
module.exports = users;
/**
* Define properties
*/
users
.attr('userName', {type: 'string', required: true})
.attr('firstName', {type: 'string', required: true})
.attr('lastName', {type: 'string', required: true})
.attr('email', {type: /^.+@.+\..+$/, required: true})
.attr('gender', {type: 'string'})
.attr('password', {type: 'string'});
<file_sep># Versity
Social learning
## Notice
This repo is deprecated. It only exists because publishing beats deleting.
Laughing at design decisions made by past me is encouraged; I laugh at 'em too.
## Installation
1. Git clone the repository
2. `npm link`
## Usage
````
Usage: versity [options] [command]
Commands:
start start server
build build assets
Options:
-h, --help output usage information
-p, --port <port> specify the server port [1337]
-t, --task <task> specify the build task [default]
-e, --environment <env> specify the environment [development]
-d, --debug <process> enable debug mode on a process
````
## Development
Enable the following paths in your `hosts` file:
```
127.0.0.1 versity.dev
127.0.0.1 api.versity.dev
127.0.0.1 assets.versity.dev
```
Enable debug mode in the browser console:
```js
localStorage.debug = '*'
```
## License
All rights reserved © [<NAME>](yoshawuyts.com)
<file_sep>/**
* Module dependencies
*/
var react = require('react');
var dispatcher = require('../../dispatcher/dispatcher');
var livereload = require('./livereload');
var router = require('../router/router');
/**
* Initialize ENV variables.
*/
var reactCDN = process.env.NODE_ENV == 'production'
? 'http://fb.me/react-0.10.0.min.js'
: 'http://assets.versity.dev:1337/react.js';
/**
* Define react class.
*
* @return {ReactView}
* @api public
*/
module.exports = react.createClass({
displayName: 'Index',
render: render,
componentDidMount: componentDidMount
});
/**
* Render DOM.
*
* @props {String} host
* @props {String} path
* @return {ReactView}
* @api private
*/
function render() {
return react.DOM.html({className: 'no-js'},
react.DOM.head(null,
react.DOM.meta({charSet: 'utf-8'}),
react.DOM.meta({httpEquiv: 'X-UA-Compatible', content: 'IE=edge'}),
react.DOM.title(null, 'Versity'),
react.DOM.meta({
name: 'viewport',
content: 'width=device-width, initial-scale=1'
}),
//livereload(),
react.DOM.link({rel: 'stylesheet', href:'http://assets.' + this.props.host + '/build.css'}),
react.DOM.link({rel: 'shortcut icon', href: 'http://assets.' + this.props.host + '/favicon.ico'}),
react.DOM.script({src: 'http://assets.versity.dev:1337/react.js'}),
react.DOM.script({src:'http://assets.' + this.props.host + '/build.js'})
),
// router gets rendered directly on the <body> tag.
router({path: this.props.path})
);
}
/**
* Lifecycle: component did mount.
*
* @props {String} path
* @api private
*/
function componentDidMount() {
dispatcher.dispatch('path_initialize', this.props.path);
}<file_sep>#!/usr/bin/env node
/**
* Module dependencies
*/
var spawn = require('child_process').spawn;
var program = require('commander');
var path = require('path');
var fs = require('fs');
/**
* Options.
*/
program
.option('-p, --port <port>', 'specify the server port [1337]', '1337')
.option('-t, --task <task>', 'specify the build task [default]', 'default')
.option('-e, --environment <env>', 'specify the environment [development]', 'development')
.option('-d, --debug <process>', 'enable debug mode on a process');
program.name = 'versity';
/**
* Start 'versity'.
*/
program
.command('start')
.description('start server')
.action(function() {
process.env.NODE_ENV = program.environment;
process.env.DEBUG = program.debug;
var args = [
'--harmony',
path.join(__dirname, '/../server/index/index.js')
]
.concat(process.argv.slice(2));
spawn('node', args, {
env: process.env,
stdio: [0,1,2]
});
});
/**
* Build packages.
*/
program
.command('build')
.description('build assets')
.action(function() {
process.env.NODE_ENV = program.environment;
process.env.DEBUG = program.debug;
var args = [
'--harmony',
path.join(__dirname, '/../node_modules/gulp/bin/gulp.js')
]
.concat(program.task);
spawn(process.argv[0], args, {
env: process.env,
stdio: [0,1,2]
});
});
/**
* Parse arguments.
*/
program.parse(process.argv);
/**
* Log help if no commands specified.
*/
if (!process.argv[2]) {
program.help();
}<file_sep>/**
* Module dependencies
*/
var react = require('react');
var navbar = require('../../modules/navbar/navbar');
/**
* 'Home' view
*/
module.exports = react.createClass({
displayName: 'course',
render: function() {
return react.DOM.div(null, '404: page not found');
}
});<file_sep>/**
* Form mixin
*/
module.exports = {
componentWillMount: componentWillMount,
updateFormString: updateFormString
};
/**
* Lifecycle: componentWillMount.
*
* │====================================================│
* │ ACTION │ STATE │
* │====================================================│
* │ initialized │ editable │
* │ any field invalidated(1) │ editable │
* │ all fields validated │ valid │
* │ submitted to server, no response yet │ pending │
* │ submitted to server, success │ success │
* │ submitted to server, error │ error │
* │====================================================│
*
* (1): If a field is invalid, the field should handle the error. Until
* all fields are valid, the form will remain 'editable'.
*
* @api public
*/
function componentWillMount() {
this.setState({
submitted: false,
succes: false
});
}
/**
* Update the form string.
*
* @param {String} key
* @param {KeyboardEvent} e
* @api public
*/
function updateFormString(key, e) {
this.state[key].value = e.target.value;
}<file_sep>/**
* Module dependencies.
*/
var react = require('react');
var validationMixin = require('../../mixins/validation');
var dispatcher = require('../../dispatcher/dispatcher');
var userValidate = require('../../stores/users').validate;
var formMixin = require('../../mixins/form');
/**
* React form view.
*/
module.exports = react.createClass({
mixins: [validationMixin],
render: render,
validators: {
lastName: userValidate.bind(userValidate, 'lastName'),
firstName: userValidate.bind(userValidate, 'firstName'),
userName: userValidate.bind(userValidate, 'userName'),
password: userValidate.bind(userValidate, 'password')
}
});
/**
* Lifecycle: Render the DOM
*/
function render() {
var submitButton = {
onClick: handleSubmit.bind(this),
className: this.state.allFormsValidated
};
return react.DOM.div(null,
react.DOM.button(null, 'continue with facebook'),
react.DOM.hr(),
react.DOM.form({className: this.state.allFormsValidated},
react.DOM.section({className: 'firstName ' + this.state.firstName.isValid},
react.DOM.p(null, 'first name'),
react.DOM.input(createField.call(this, 'firstName')),
react.DOM.label()
),
react.DOM.section({className: 'lastName ' + this.state.lastName.isValid},
react.DOM.p(null, 'last name'),
react.DOM.input(createField.call(this, 'lastName')),
react.DOM.label()
),
react.DOM.section({className: 'userName ' + this.state.userName.isValid},
react.DOM.p(null, 'user name'),
react.DOM.input(createField.call(this, 'userName')),
react.DOM.label()
),
react.DOM.section({className: 'password ' + this.state.password.isValid},
react.DOM.p(null, 'password'),
react.DOM.input(createField.call(this, 'password')),
react.DOM.label(),
react.DOM.input({type: 'checkbox'}),
react.DOM.label(null, 'show password')
),
react.DOM.button(submitButton, 'submit')
)
);
}
/**
* Create a field.
*
* @param {String} name
* @api private
*/
function createField(name) {
var obj = {};
obj.className = this.state[name].isValid;
obj.onKeyDown = handleKeyDown.bind(this, name);
obj.onBlur = this.resetError.bind(this, 'password');
return obj;
}
/**
* Handle keydown.
*
* @param {String} key
* @param {KeyboardEvent} e
* @api private
*/
function handleKeyDown(key, e) {
this.updateFormString(key, e);
this.validateInputField(key);
this.setState({allFormsValidated: this.allFormsValidated()});
}
/**
* Handle submit.
*
* @param {KeyboardEvent} event
* @api private
*/
function handleSubmit(event) {
event.preventDefault();
if (!this.state.allFormsValidated) return;
this.setState({submitted: true});
}<file_sep>all:
versity start
assets:
versity build
.Phony: all assets
| 1f15a09171d5975e9bfb1ee5029f3381c44aaee1 | [
"JavaScript",
"Makefile",
"Markdown"
] | 22 | JavaScript | yoshuawuyts/versity-legacy | 94702aa1bb00673bc3000967cc08b3908b3844aa | c5643c32599a74e1ad8fafc453fefec0f0bd6bf1 |
refs/heads/master | <repo_name>adamblank/bitnami-wordpress-backup<file_sep>/README.md
Bitnami WordPress Backup
========================
## Summary
A simple script for creating a local backup of a Bitnami Wordpress
(both [application files][0] and [DB)][1].)
Backups are automatically timestamped & created under `/var/backups/wordpress`.
## Running
Simply make `bitnami_wordpress_backup.sh` executable and then run on from inside your Bitnami
WordPress instance:
```bash
chmod +x bitnami_wordpress_backup.sh
sudo ./bitnami_wordpress_backup.sh
```
Enjoy! 🎉
[0]: https://docs.bitnami.com/aws/apps/wordpress/administration/backup-restore/
[1]: https://docs.bitnami.com/aws/apps/wordpress/administration/backup-restore-mysql-mariadb/
<file_sep>/bitnami_wordpress_backup.sh
#!/usr/bin/env bash
# A simple script to backup Bitnami WordPress application files and database
# See Bitnami documentation for details https://docs.bitnami.com/aws/apps/wordpress
set -e
start_server() {
/opt/bitnami/ctlscript.sh start
}
on_error() {
start_server
popd
}
trap on_error ERR
backup_time=$(date +"%Y-%m-%d-%H%M%S")
echo "Starting application backup..."
# run backups from proper directory
mkdir -p /var/backups/wordpress
pushd /var/backups/wordpress
echo "Stopping all servers"
/opt/bitnami/ctlscript.sh stop
echo "Compressing directory /opt/bitnami"
tar -pczvf application-backup-${backup_time}.tar.gz /opt/bitnami
echo "Restarting all servers"
start_server
echo "Application backup complete! Starting database backup..."
echo "You will be prompted for your root database password shortly"
mysqldump -A -u root -p > database-backup-${backup_time}.sql
echo "Database backup complete!"
popd | 2299fc8e38deed8e949ec6637744da870d57ea9c | [
"Markdown",
"Shell"
] | 2 | Markdown | adamblank/bitnami-wordpress-backup | 5765e9a34af044a16e4fa6fbea08daea55b28d97 | 68aedf7bb7279293dffae727370d33c50c816865 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.