branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/main
<repo_name>KFYakusa/ServicosWebDaniel<file_sep>/README.md # Express API developed in College This repository was developed for Web Service subject of Computer Science Bacharelor ## Instructions to run the project First add the `nodemon.json` file in root of project, this file only has a `"env":{}` that is a environment config used inside this server application (e.g: `server.js`) Since this file may contain ( not in this case ) sensitive info (like IPs or database access credentials) is better to not upload it into a public project. ```json { "env":{ "PORT":4435 } } ``` Then you just have to download all the modules listed into `package.json` with the command `yarn` and finally run the project with `yarn start`. Since I use nodemon, when you change the code and save, the code automatically will be interpreted will run again. Happy coding! <file_sep>/api/controllers/livros.js const { sql } = require('@databases/pg') const { query } = require('express') const { reset, restart } = require('nodemon') // const bcrypt = require('bcrypt') // const jwt = require('jsonwebtoken') const db = require('../../dbConfig') exports.createLivro = (req, res, next) => { const { nome, autor, editora } = req.body if (!isValid(nome, autor, editora)) res.status(406).json({ message: "error in input variables" }) db.query(sql`INSERT INTO livros(book_name,book_author, book_publisher) VALUES(${nome},${autor},${editora})`) .then(result => res.status(201).json({ message: "created with success"})) .catch(error => res.status(500).json({ error })) } exports.editLivro = (req, res, next) => { const id = req.params.id const { nome, autor, editora } = req.body if (!isValid(nome, autor, editora)) { if (!isNaN(parseInt(id))) { db.query(sql`UPDATE livros SET book_name=${nome}, book_author=${autor}, book_publisher=${editora} WHERE id=${id};`).then(result => { console.log(result) res.status(200).json(result) }).catch(error => { console.log(error); res.status(500).json(error) }) }else res.status(406).json({message:"ID not valid"}) }else if (!isNaN(parseInt(id))) { db.query(sql`UPDATE * from livros SET ` + ` if(nome!= null) book_name=${nome}, book_author=${autor}, book_publisher=${editora} WHERE id=${id};`).then(result=>{ console.log(result); res.status(200).json(result) }).catch(error=>{ console.log(error); res.status(500).json(error) }) }else res.status(406).json({message:"ID not valid"}) //have req.params } exports.deleteLivro = (req, res, next) => { const id = req.params.id if(isNaN(parseInt(id))){ res.status(406).json({message:"ID not Valid"}) }else{ db.query(sql` DELETE FROM livros where id=${id};`).then(result=>{ console.log(result); res.status(200).json(result) }).catch(error=>{ console.log(error); res.status(500).json(error) }) } } exports.getLivro = (req, res, next) => { const id = req.params.id if (!isNaN(parseInt(id))) { db.query(sql`SELECT * from livros where id=${id};`).then(result => { console.log(result) res.status(200).json(result) }).catch((error) => { console.log(error) res.status(500).json({message:" error getting "}) }) } else res.status() } exports.getAllLivros = (req, res, next) => { db.query(sql`SELECT * FROM livros;`) .then((resultado) => res.status(200).json(resultado)) } isValid = (n, a, e) => { if (!n || !a || !e || !n.match(/^([a-zA-Z0-9\u0600-\u06FF\u0660-\u0669\u06F0-\u06F9 _.]+)$/) || !a.match(/^([a-zA-Z0-9\u0600-\u06FF\u0660-\u0669\u06F0-\u06F9 _.]+)$/) || !e.match(/^([a-zA-Z0-9\u0600-\u06FF\u0660-\u0669\u06F0-\u06F9 _.]+)$/) ) return false return true } <file_sep>/api/controllers/role.js exports.getRoles=(req,res,next)=>{ } exports.createRole=(req,res,next)=>{ } exports.editRole=(req,res,next)=>{ } exports.deleteRole=(req,res,next)=>{ }<file_sep>/api/routes/aula1.js const express = require('express') const router = express.Router() const Aula1Controller = require('../controllers/aula1') router.post('/pessoa', Aula1Controller.idadeCalculator) router.get('/daniel', Aula1Controller.retornoDaniel) // router.get('/:nome',Aula1Controller.retornoNome) module.exports = router<file_sep>/api/controllers/aula2.js exports.tempConverter = (req,res,next) =>{ if(req.body.scale == 'c'){ let result = ((req.body.number -32)/ 1.8) res.status(200).json({message: "Fahrenheit to Celsius", answer: result}) }else if(req.body.scale =='f'){ let result = (req.body.number * 1.8 ) + 32 res.status(200).json({message: "Celsius to Fahrenheit", answer: result}) } }<file_sep>/api/controllers/aula1.js exports.idadeCalculator = (req,res,next)=>{ let msgRetorno = "BEM VINDO" let status = 200 if(req.body.idade >= 65){ msgRetorno += ", Acesso Preferencial, (todos os status deveriam ser 201 se eu estou criando)" status = 201 } res.status(status).json({ id: req.body.id, nome: req.body.nome, idade: req.body.idade, message: msgRetorno, }) } exports.retornoDaniel = (req,res,next)=>{ res.status(200).json({ nome: "daniel" }) } // exports.retornoNome = (req,res,next)=>{ // res.status(200).json({entrada: req.params.nome}) // } <file_sep>/api/routes/usuario.js const express =require('express') const router = express.Router() const ControladorUsuario = require('../controllers/usuario') const isAuth = require('../middleware/isAuth') router.get('/all',ControladorUsuario.getALl) router.post('/singup', ControladorUsuario.singUp) router.post('/login',ControladorUsuario.Login) router.delete('/', isAuth, ControladorUsuario.delete_user) router.put('/',isAuth, ControladorUsuario.edit_user) module.exports=router<file_sep>/dbConfig.js const createConnectionPool = require("@databases/pg") const db = createConnectionPool( `postgres://${process.env.DB_USER}:${process.env.DB_PASSWORD}@${process.env.DB_HOST}:${process.env.DB_PORT}/${process.env.DB_DATABASE}` ); module.exports = db /** { "env":{ "PORT":, "DB_USER":"", "DB_PASSWORD":"", "DB_HOST":"", "DB_PORT":, "DB_DATABASE":"", "JWT_KEY": "" } } * * ********************************************** * ABAIXO CÓDIGO PRA CRIAÇÃO DAS TABELAS DO BANCO * ********************************************** **/ /* ! DROP TABLE users; ! DROP TABLE roles; ? create table roles ( ? id SERIAL PRIMARY KEY, ? role_name varchar(20) not null ? ); ? create table users ( ? id SERIAL PRIMARY KEY, ? user_role INT NOT NULL, ? user_email varchar(50) UNIQUE not null, ? user_name varchar(50) not null, ? user_password varchar(100) NOT NULL, ? CONSTRAINT fk_role FOREIGN KEY(user_role) REFERENCES roles(id) ? ); ? * INSERT INTO roles(role_name) VALUES('admin'), ('customer'); ? ? * INSERT INTO users(user_role,user_email,user_name,user_password) VALUES(1,'<EMAIL>','<PASSWORD>','<PASSWORD>'); * SELECT user_email,role_name,user_name FROM users INNER JOIN roles ON user_role=roles.id WHERE user_email='<EMAIL>'; -- INSERT INTO users(user_role,user_email,user_name,user_password) VALUES(1,'<EMAIL>','<PASSWORD>','<PASSWORD>'); -- ','',''); DROP DATABASE; -- '; SELECT * FROM sysobjects ;-- */<file_sep>/app.js const express = require('express') const cors = require('cors') const morgan = require('morgan') const app = express() const aula1Rotas = require('./api/routes/aula1') const userRotas = require('./api/routes/usuario') const rolesRoutes = require('./api/routes/role') const aula2Rotas = require('./api/routes/aula2') const livrosRotas = require('./api/routes/livros') app.use(cors()) app.use(morgan('dev')) app.use(express.urlencoded({extended:true})) app.use(express.json()) app.use((req,res,next)=>{ res.header('Access-Control-Allow-Origin','*') res.header('Access-Control-Allow-Headers','Origin, X-Requested-With, Accept, Authorization') if(req.method === 'OPTIONS'){ res.header('Access-Control-Allow-Methods','PUT, POST, PATCH, DELETE, GET') return res.status(200).json({}) } next() }) app.use('/aula1',aula1Rotas) app.use('/user',userRotas) app.use('/roles',rolesRoutes) app.use('/aula2',aula2Rotas) app.use('/livros',livrosRotas) app.use((req,res,next)=>{ const error = new Error('Not found / Não encontrado') error.status = 404 next(error) }) app.use((error,req,res,next)=>{ res.status(error.status||500) res.json({ error:{ message : error.message } }) }) module.exports = app
c233842b7e18588b9e98147c058eb699586f1081
[ "Markdown", "JavaScript" ]
9
Markdown
KFYakusa/ServicosWebDaniel
1120561d35885537d47e4d9915d6aaa0fe9e35d3
c4140ad823872c64b7d5798609a7434dc9bd786f
refs/heads/master
<file_sep>using System; using System.Drawing; namespace HF_490 { public class Bow:Weapon { public Bow(Game game, Point location):base(game, location) { } public override string Name { get { return "Łuk"; } } public override void Attack(Direction direction, Random random) { DamageEnemy(direction, 50, 10, random); } } }<file_sep>using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; namespace HF_490 { public class Player:Mover { public Weapon equippedWeapon { get; private set; } public int HitPoints { get; private set; } private List<Weapon> inventory = new List<Weapon>(); public Size SpriteSize { get; private set; } public IEnumerable<string> Weapons { get { List<string> names = new List<string>(); foreach (Weapon weapon in inventory) names.Add(weapon.Name); return names; } } public Player(Game game, Point location, Size spriteSize):base(game, location) { HitPoints = 50; SpriteSize = spriteSize; } public void Hit(int maxDamage, Random random) { HitPoints -= random.Next(1, maxDamage); } public void IncreaseHealth(int health, Random random) { HitPoints += random.Next(1, health); } public void Equip(string weaponName) { foreach (Weapon weapon in inventory) { if (weapon.Name == weaponName) equippedWeapon = weapon; } } public void Move(Direction direction) { base.location = Move(direction, game.Boundaries); if (!game.WeaponInRoom.PickedUp) { if (Nearby(game.WeaponInRoom.Location, 10)) { game.WeaponInRoom.PickUpWeapon(); inventory.Add(game.WeaponInRoom); if (equippedWeapon == null) Equip(game.WeaponInRoom.Name); } } } public bool CheckPotion(string potionName) { foreach (Weapon potion in inventory) { if(potion is IPotion) if (potion.Name == potionName) { IPotion obj = potion as IPotion; if (obj.Used == true) return true; } } return false; } public void Attack(Direction direction, Random random) { if (equippedWeapon != null) { Debug.WriteLine("Mam broń"); equippedWeapon.Attack(direction, random); } } } }<file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Media; using System.Runtime.Remoting.Activation; using System.Windows.Forms; namespace HF_490 { using System.Drawing; public class Game { public List<Enemy> Enemies; public Weapon WeaponInRoom { get; private set; } private Player player; public Point PlayerLocation { get { return player.Location; } } public int PlayerHitPoints { get { return player.HitPoints; } } public Size PlayerSpriteSize { get { return player.SpriteSize; } } public IEnumerable<string> PlayerWeapons { get { return player.Weapons; } } private int level = 0; public int Level { get { return level; } } private Rectangle boundaries; public Rectangle Boundaries { get { return boundaries; } } public Game(Rectangle boundaries) { this.boundaries = boundaries; player = new Player(this,new Point(boundaries.Left + 10, boundaries.Top + 70), new Size(30, 30)); } public void Move(Direction direction, Random random) { player.Move(direction); foreach (Enemy enemy in Enemies) enemy.Move(random); } public void Equip(string weaponName) { player.Equip(weaponName); } public bool CheckPlayerInventory(string weaponName) { return player.Weapons.Contains(weaponName); } public string CheckActualWeapon() { if (player.equippedWeapon != null) return player.equippedWeapon.Name; else return null; } public bool CheckIfPotionUsed(string potionName) { return player.CheckPotion(potionName); } public void HitPlayer(int maxDamage, Random random) { player.Hit(maxDamage, random); } public void IncreasePlayerHealth(int health, Random random) { player.IncreaseHealth(health, random); } public void Attack(Direction direction, Random random) { player.Attack(direction, random); foreach (Enemy enemy in Enemies) enemy.Move(random); } private Point GetRandomLocation(Random random) { return new Point(boundaries.Left + random.Next(boundaries.Right/10-boundaries.Left/10)*5,boundaries.Top+random.Next(boundaries.Bottom/10+boundaries.Top/10)*5); } public void NewLevel(Random random) { level++; switch(level) { case 1: Enemies = new List<Enemy>(); Enemies.Clear(); Enemies.Add(new Bat(this, GetRandomLocation(random),PlayerSpriteSize)); Point swordLocation = new Point(player.Location.X+random.Next(20), PlayerLocation.Y+random.Next(20)); WeaponInRoom = new Sword(this, swordLocation); break; case 2: Enemies = new List<Enemy>(); Enemies.Clear(); Enemies.Add(new Ghost(this, GetRandomLocation(random), PlayerSpriteSize)); WeaponInRoom = new BluePotion(this, GetRandomLocation(random)); WeaponInRoom = new Bow(this, GetRandomLocation(random)); break; case 3: Enemies = new List<Enemy>(); Enemies.Clear(); Enemies.Add(new Ghoul(this, GetRandomLocation(random), PlayerSpriteSize)); WeaponInRoom = new Bow(this, GetRandomLocation(random)); break; case 4: Enemies = new List<Enemy>(); Enemies.Clear(); Enemies.Add(new Ghost(this, GetRandomLocation(random), PlayerSpriteSize)); Enemies.Add(new Bat(this, GetRandomLocation(random), PlayerSpriteSize)); //if (CheckPlayerInventory("Niebieski napój") == true) WeaponInRoom = new BluePotion(this, GetRandomLocation(random)); break; case 5: Enemies = new List<Enemy>(); Enemies.Clear(); Enemies.Add(new Ghoul(this, GetRandomLocation(random), PlayerSpriteSize)); Enemies.Add(new Bat(this, GetRandomLocation(random), PlayerSpriteSize)); WeaponInRoom = new RedPotion(this, GetRandomLocation(random)); break; case 6: Enemies = new List<Enemy>(); Enemies.Clear(); Enemies.Add(new Ghoul(this, GetRandomLocation(random), PlayerSpriteSize)); Enemies.Add(new Bat(this, GetRandomLocation(random), PlayerSpriteSize)); WeaponInRoom = new Mace(this, GetRandomLocation(random)); break; case 7: Enemies = new List<Enemy>(); Enemies.Clear(); Enemies.Add(new Ghoul(this, GetRandomLocation(random), PlayerSpriteSize)); Enemies.Add(new Ghost(this, GetRandomLocation(random), PlayerSpriteSize)); Enemies.Add(new Bat(this, GetRandomLocation(random), PlayerSpriteSize)); WeaponInRoom = new RedPotion(this, GetRandomLocation(random)); break; case 8: Application.Exit(); break; } } } }<file_sep>using System; using System.Drawing; namespace HF_490 { public class Mace:Weapon { public Mace(Game game, Point location):base(game, location) { } public override string Name { get { return "Buława"; } } public override void Attack(Direction direction, Random random) { DamageEnemy(Direction.Down, 50, 3, random); DamageEnemy(Direction.Left, 50, 3, random); DamageEnemy(Direction.Up, 50, 3, random); DamageEnemy(Direction.Right, 50, 3, random); } } }<file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace HF_490 { public partial class Form1 : Form { private Game game; private Random random = new Random(); private void Form1_Load(object sender, EventArgs e) { game = new Game(new Rectangle(70,50,410,140)); game.NewLevel(random); UpdateCharacters(); } private void UpdateCharacters() { player.Location = game.PlayerLocation; playerHitPoints.Text = game.PlayerHitPoints.ToString(); bool showBat = false; bool showGhost = false; bool showGhoul = false; int enemiesShown = 0; //Reszta foreach (Enemy enemy in game.Enemies) { if (enemy is Bat) { bat.Location = enemy.Location; batHitPoints.Text = enemy.HitPoints.ToString(); if (enemy.HitPoints > 0) { showBat = true; enemiesShown++; } } if (enemy is Ghost) { ghost.Location = enemy.Location; ghostHitPoints.Text = enemy.HitPoints.ToString(); if (enemy.HitPoints > 0) { showGhost = true; enemiesShown++; } } if (enemy is Ghoul) { ghoul.Location = enemy.Location; ghoulHitPoints.Text = enemy.HitPoints.ToString(); if (enemy.HitPoints > 0) { showGhoul = true; enemiesShown++; } } } //Dalej sword.Visible = false; bow.Visible = false; redPotion.Visible = false; bluePotion.Visible = false; mace.Visible = false; bat.Visible = showBat; ghoul.Visible = showGhoul; ghost.Visible = showGhost; //Do dokończenia Control weaponControl = null; switch (game.WeaponInRoom.Name) { case "Miecz": weaponControl = sword; break; case "Buława": weaponControl = mace; break; case "Łuk": weaponControl = bow; break; case "Czerwony napój": weaponControl = redPotion; break; case "Niebieski napój": weaponControl = bluePotion; break; } //Dalej foreach(String weapon in game.PlayerWeapons) switch (weapon) { case "Miecz": equipSword.Visible = true; break; case "Łuk": equipBow.Visible = true; break; case "Buława": equipMace.Visible = true; break; case "Niebieski napój": if (!game.CheckIfPotionUsed("Niebieski napój")) equipBluePotion.Visible = true; else equipBluePotion.Visible = false; break; case "Czerwony napój": if (!game.CheckIfPotionUsed("Czerwony napój")) equipRedPotion.Visible = true; else equipRedPotion.Visible = false; break; } /*equipMace.BackColor = Color.Black; equipBow.BackColor = Color.Transparent; equipSword.BackColor = Color.Transparent;*/ switch (game.CheckActualWeapon()) { case null: break; case "Miecz": equipMace.BackColor = Color.Transparent; equipBow.BackColor = Color.Transparent; equipSword.BackColor = Color.Black; break; case "Łuk": equipMace.BackColor = Color.Transparent; equipBow.BackColor = Color.Black; equipSword.BackColor = Color.Transparent; break; case "Buława": equipMace.BackColor = Color.Black; equipBow.BackColor = Color.Transparent; equipSword.BackColor = Color.Transparent; break; } //Dalej weaponControl.Location = game.WeaponInRoom.Location; if (game.WeaponInRoom.PickedUp) weaponControl.Visible = false; else weaponControl.Visible = true; if (game.PlayerHitPoints <= 0) { MessageBox.Show("Zostałeś zabity"); Application.Exit(); } if (enemiesShown < 1) { MessageBox.Show("Pokonałeś przeciwników na tym poziomie!"); game.NewLevel(random); UpdateCharacters(); } } public Form1() { InitializeComponent(); } private void pictureBox2_Click(object sender, EventArgs e) { string actualweapon = game.CheckActualWeapon(); game.Equip("Czerwony napój"); game.Attack(Direction.Down, random); game.Equip(actualweapon); UpdateCharacters(); } private void pictureBox3_Click(object sender, EventArgs e) { //Niebieski napój string actualweapon=game.CheckActualWeapon(); game.Equip("Niebieski napój"); game.Attack(Direction.Down, random); game.Equip(actualweapon); UpdateCharacters(); } private void pictureBox4_Click(object sender, EventArgs e) { game.Equip("Buława"); UpdateCharacters(); } private void pictureBox5_Click(object sender, EventArgs e) { game.Equip("Łuk"); UpdateCharacters(); } private void pictureBox1_Click(object sender, EventArgs e) { game.Equip("Miecz"); UpdateCharacters(); } private void moveRight_Click(object sender, EventArgs e) { game.Move(Direction.Right, random); UpdateCharacters(); } private void moveLeft_Click(object sender, EventArgs e) { game.Move(Direction.Left, random); UpdateCharacters(); } private void moveUp_Click(object sender, EventArgs e) { game.Move(Direction.Up, random); UpdateCharacters(); } private void moveDown_Click(object sender, EventArgs e) { game.Move(Direction.Down, random); UpdateCharacters(); } private void attackUp_Click(object sender, EventArgs e) { game.Attack(Direction.Up, random); UpdateCharacters(); } private void attackDown_Click(object sender, EventArgs e) { game.Attack(Direction.Down, random); UpdateCharacters(); } private void attackLeft_Click(object sender, EventArgs e) { game.Attack(Direction.Left, random); UpdateCharacters(); } private void attackRight_Click(object sender, EventArgs e) { game.Attack(Direction.Right, random); UpdateCharacters(); } private void Form1_KeyDown(object sender, KeyEventArgs e) { switch (e.KeyCode) { case Keys.W: { game.Attack(Direction.Up, random); UpdateCharacters(); break; } case Keys.A: { game.Attack(Direction.Left, random); UpdateCharacters(); break; } case Keys.D: { game.Attack(Direction.Right, random); UpdateCharacters(); break; } case Keys.S: { game.Attack(Direction.Down, random); UpdateCharacters(); break; } } } protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { //capture up arrow key if (keyData == Keys.Up) { game.Move(Direction.Up, random); UpdateCharacters(); return true; } //capture down arrow key if (keyData == Keys.Down) { game.Move(Direction.Down, random); UpdateCharacters(); return true; } //capture left arrow key if (keyData == Keys.Left) { game.Move(Direction.Left, random); UpdateCharacters(); return true; } //capture right arrow key if (keyData == Keys.Right) { game.Move(Direction.Right, random); UpdateCharacters(); return true; } return base.ProcessCmdKey(ref msg, keyData); } } } <file_sep>using System; using System.Collections.Generic; using System.Drawing; namespace HF_490 { public class Sword:Weapon { public Sword(Game game,Point location) : base(game, location) { } public override string Name { get { return "Miecz"; } } private const int dmg = 3; public override void Attack(Direction direction, Random random) { DamageEnemy(direction, 50, 3, random); } } }<file_sep>using System; using System.Diagnostics; using System.Drawing; namespace HF_490 { public abstract class Weapon : Mover { public bool PickedUp { get; private set; } public Weapon(Game game, Point location): base(game, location) { PickedUp = false; } public void PickUpWeapon() { PickedUp = true; } public abstract string Name { get; } public abstract void Attack(Direction direction, Random random); protected bool DamageEnemy(Direction direction, int radius, int damage, Random random) { Point target = game.PlayerLocation; for (int distance = 0; distance < radius; distance++){ foreach (Enemy enemy in game.Enemies){ if (Nearby(target, distance, direction, enemy)) { enemy.Hit(damage, random); if(!enemy.Dead) return true; } } target = Move(direction, game.Boundaries); } return false; } private bool Nearby(Point playerLocation, int distance, Direction direction, Enemy enemy) { bool isNearby = false; Rectangle enemySpriteBoundary = new Rectangle(enemy.Location, enemy.SpriteSize); Rectangle playerAttackArea = new Rectangle(); switch (direction) { case Direction.Up: playerAttackArea.Location = new Point(playerLocation.X, playerLocation.Y - distance); playerAttackArea.Width = game.PlayerSpriteSize.Width; playerAttackArea.Height = distance; break; case Direction.Right: playerAttackArea.Location = new Point(playerLocation.X + game.PlayerSpriteSize.Width, playerLocation.Y); playerAttackArea.Width = distance; playerAttackArea.Height = game.PlayerSpriteSize.Height; break; case Direction.Down: playerAttackArea.Location = new Point(playerLocation.X, playerLocation.Y + game.PlayerSpriteSize.Height); playerAttackArea.Width = game.PlayerSpriteSize.Width; playerAttackArea.Height = distance; break; case Direction.Left: playerAttackArea.Location = new Point(playerLocation.X + distance, playerLocation.Y); playerAttackArea.Width = distance; playerAttackArea.Height = game.PlayerSpriteSize.Height; break; } if (playerAttackArea.IntersectsWith(enemySpriteBoundary)) { isNearby = true; } return isNearby; } } }<file_sep>using System; using System.Drawing; namespace HF_490 { public class RedPotion:Weapon,IPotion { public RedPotion(Game game, Point location) : base(game, location) { } public override string Name { get { return "<NAME>"; } } public override void Attack(Direction direction, Random random) { Used = true; game.IncreasePlayerHealth(50, random); } public bool Used { get; private set; } } }<file_sep>using System; using System.Drawing; namespace HF_490 { public class BluePotion : Weapon,IPotion { public BluePotion(Game game, Point location) : base(game, location) { } public override string Name { get { return "<NAME>"; } } public override void Attack(Direction direction, Random random) { Used = true; game.IncreasePlayerHealth(20,random); } public bool Used { get; private set; } } }
a365d3ddcd2f06a87185a7bfea368b309d68c39a
[ "C#" ]
9
C#
Witold45/TheGame
f045c4ddd416a1dfaa1fb9924df7ee83b52316bf
70511ae5d52f6260a01584fc28b92742daa3c44e
refs/heads/master
<file_sep>## copy-tuner-test raise error "undefined method 'bytesize' for nil:NilClass" copy-tunerを追加すると、CGI.escape(t('test'))のような書き方をしてある部分がエラーになる。 * app/views/users/show.html.erb * app/helpers/application_helper.rb <file_sep>module ApplicationHelper def translate foo = t('text') end def cgi_test url = CGI.escape(t('text')) end end
d167ca7273573a6de165d055819b4f1af9cd3874
[ "Markdown", "Ruby" ]
2
Markdown
yakushiji/copy-tuner-test
0f2d58287cc7baf9969f2fd455d49a2f588455ec
d9b32f6c236fabdb6f9cc40cbff5c3dd93121047
refs/heads/master
<file_sep>API responses are in JSON format. When there are exceptions to this rule, the documentation for the endpoint will make this clear.<file_sep>/* tslint:disable */ /* eslint-disable */ /** * Collins API * This site provides details on the various ways that you can integrate with Collins. Not sure you want to be here after all? Check out what’s new on the [London Bar Scene](https://www.designmynight.com/london/new-bar-spy) instead. * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { exists, mapValues } from '../runtime'; import { MoneyResponse, MoneyResponseFromJSON, MoneyResponseFromJSONTyped, MoneyResponseToJSON, } from './'; /** * * @export * @interface ViewDeposit */ export interface ViewDeposit { /** * The ID of the deposit. * @type {string} * @memberof ViewDeposit */ id?: string; /** * * @type {MoneyResponse} * @memberof ViewDeposit */ amount?: MoneyResponse; /** * Describes how the deposit was paid for. * @type {string} * @memberof ViewDeposit */ paidType?: string | null; /** * The status which the deposit is in. * @type {string} * @memberof ViewDeposit */ status?: ViewDepositStatusEnum; /** * The type of deposit. * @type {string} * @memberof ViewDeposit */ type?: ViewDepositTypeEnum; /** * Any notes that are attached to this deposit. * @type {string} * @memberof ViewDeposit */ notes?: string | null; /** * The Stripe payment reference for this deposit. * @type {string} * @memberof ViewDeposit */ paymentRef?: string | null; /** * The date when the deposit was created. * @type {Date} * @memberof ViewDeposit */ date?: Date; /** * An array of refund IDs relating to this deposit. These IDs relate to the `refunds` array within a booking. * @type {Array<string>} * @memberof ViewDeposit */ refundIds?: Array<string>; } /** * @export * @enum {string} */ export enum ViewDepositStatusEnum { Pending = 'pending', Paid = 'paid' }/** * @export * @enum {string} */ export enum ViewDepositTypeEnum { RequestAuth = 'request_auth', ManualAuth = 'manual_auth', RequestPayment = 'request_payment', ManualPayment = 'manual_payment', CustomerPreorder = 'customer_preorder' } export function ViewDepositFromJSON(json: any): ViewDeposit { return ViewDepositFromJSONTyped(json, false); } export function ViewDepositFromJSONTyped(json: any, ignoreDiscriminator: boolean): ViewDeposit { if ((json === undefined) || (json === null)) { return json; } return { 'id': !exists(json, 'id') ? undefined : json['id'], 'amount': !exists(json, 'amount') ? undefined : MoneyResponseFromJSON(json['amount']), 'paidType': !exists(json, 'paid_type') ? undefined : json['paid_type'], 'status': !exists(json, 'status') ? undefined : json['status'], 'type': !exists(json, 'type') ? undefined : json['type'], 'notes': !exists(json, 'notes') ? undefined : json['notes'], 'paymentRef': !exists(json, 'payment_ref') ? undefined : json['payment_ref'], 'date': !exists(json, 'date') ? undefined : (new Date(json['date'])), 'refundIds': !exists(json, 'refund_ids') ? undefined : json['refund_ids'], }; } export function ViewDepositToJSON(value?: ViewDeposit | null): any { if (value === undefined) { return undefined; } if (value === null) { return null; } return { 'id': value.id, 'amount': MoneyResponseToJSON(value.amount), 'paid_type': value.paidType, 'status': value.status, 'type': value.type, 'notes': value.notes, 'payment_ref': value.paymentRef, 'date': value.date === undefined ? undefined : (value.date.toISOString()), 'refund_ids': value.refundIds, }; } <file_sep>/* tslint:disable */ /* eslint-disable */ /** * Collins API * This site provides details on the various ways that you can integrate with Collins. Not sure you want to be here after all? Check out what’s new on the [London Bar Scene](https://www.designmynight.com/london/new-bar-spy) instead. * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { exists, mapValues } from '../runtime'; /** * * @export * @interface ViewAssignedArea */ export interface ViewAssignedArea { /** * The ID of the area. * @type {string} * @memberof ViewAssignedArea */ id?: string; /** * The name of the area. * @type {string} * @memberof ViewAssignedArea */ name?: string; /** * The ID of the zone which this area belongs to, or `null` if it doesn't belong to a zone. * @type {string} * @memberof ViewAssignedArea */ zone?: string | null; } export function ViewAssignedAreaFromJSON(json: any): ViewAssignedArea { return ViewAssignedAreaFromJSONTyped(json, false); } export function ViewAssignedAreaFromJSONTyped(json: any, ignoreDiscriminator: boolean): ViewAssignedArea { if ((json === undefined) || (json === null)) { return json; } return { 'id': !exists(json, 'id') ? undefined : json['id'], 'name': !exists(json, 'name') ? undefined : json['name'], 'zone': !exists(json, 'zone') ? undefined : json['zone'], }; } export function ViewAssignedAreaToJSON(value?: ViewAssignedArea | null): any { if (value === undefined) { return undefined; } if (value === null) { return null; } return { 'id': value.id, 'name': value.name, 'zone': value.zone, }; } <file_sep>/* tslint:disable */ /* eslint-disable */ /** * Collins API * This site provides details on the various ways that you can integrate with Collins. Not sure you want to be here after all? Check out what’s new on the [London Bar Scene](https://www.designmynight.com/london/new-bar-spy) instead. * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { exists, mapValues } from '../runtime'; import { ViewVenueAddress, ViewVenueAddressFromJSON, ViewVenueAddressFromJSONTyped, ViewVenueAddressToJSON, } from './'; /** * * @export * @interface ViewVenue */ export interface ViewVenue { /** * The ID of the venue. * @type {string} * @memberof ViewVenue */ id?: string; /** * The name of the venue. * @type {string} * @memberof ViewVenue */ title?: string | null; /** * The ID of the venue group which this venue belongs to. * @type {string} * @memberof ViewVenue */ venueGroup?: string; /** * Whether this venue is responsible for managing it's own bookings * @type {boolean} * @memberof ViewVenue */ manageOwnBookings?: boolean; /** * The visibility of this venue on the DesignMyNight website * @type {string} * @memberof ViewVenue */ status?: ViewVenueStatusEnum; /** * A customisable venue identifier * @type {string} * @memberof ViewVenue */ storeCode?: string; /** * * @type {ViewVenueAddress} * @memberof ViewVenue */ address?: ViewVenueAddress; /** * An array of tag IDs which this venue is associated with. Tag IDs correspond to tags defined on the venue group. * @type {Array<string>} * @memberof ViewVenue */ tags?: Array<string>; /** * The date and time the venue was created. * @type {Date} * @memberof ViewVenue */ createdDate?: Date; /** * The date and time the venue was last updated. * @type {Date} * @memberof ViewVenue */ lastUpdated?: Date; } /** * @export * @enum {string} */ export enum ViewVenueStatusEnum { Public = 'public', Private = 'private', Inactive = 'inactive' } export function ViewVenueFromJSON(json: any): ViewVenue { return ViewVenueFromJSONTyped(json, false); } export function ViewVenueFromJSONTyped(json: any, ignoreDiscriminator: boolean): ViewVenue { if ((json === undefined) || (json === null)) { return json; } return { 'id': !exists(json, 'id') ? undefined : json['id'], 'title': !exists(json, 'title') ? undefined : json['title'], 'venueGroup': !exists(json, 'venue_group') ? undefined : json['venue_group'], 'manageOwnBookings': !exists(json, 'manage_own_bookings') ? undefined : json['manage_own_bookings'], 'status': !exists(json, 'status') ? undefined : json['status'], 'storeCode': !exists(json, 'store_code') ? undefined : json['store_code'], 'address': !exists(json, 'address') ? undefined : ViewVenueAddressFromJSON(json['address']), 'tags': !exists(json, 'tags') ? undefined : json['tags'], 'createdDate': !exists(json, 'created_date') ? undefined : (new Date(json['created_date'])), 'lastUpdated': !exists(json, 'last_updated') ? undefined : (new Date(json['last_updated'])), }; } export function ViewVenueToJSON(value?: ViewVenue | null): any { if (value === undefined) { return undefined; } if (value === null) { return null; } return { 'id': value.id, 'title': value.title, 'venue_group': value.venueGroup, 'manage_own_bookings': value.manageOwnBookings, 'status': value.status, 'store_code': value.storeCode, 'address': ViewVenueAddressToJSON(value.address), 'tags': value.tags, 'created_date': value.createdDate === undefined ? undefined : (value.createdDate.toISOString()), 'last_updated': value.lastUpdated === undefined ? undefined : (value.lastUpdated.toISOString()), }; } <file_sep>FROM node:11-alpine WORKDIR /app VOLUME /app RUN npm install -g live-server EXPOSE 5050 ENTRYPOINT [ "live-server", "--port=5050" ]<file_sep>/* tslint:disable */ /* eslint-disable */ /** * Collins API * This site provides details on the various ways that you can integrate with Collins. Not sure you want to be here after all? Check out what’s new on the [London Bar Scene](https://www.designmynight.com/london/new-bar-spy) instead. * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { exists, mapValues } from '../runtime'; /** * * @export * @interface PreferenceResponse */ export interface PreferenceResponse { /** * The ID of this marketing preference * @type {string} * @memberof PreferenceResponse */ id?: string; /** * The name of this marketing preference * @type {string} * @memberof PreferenceResponse */ name?: string; /** * A description of this marketing preference * @type {string} * @memberof PreferenceResponse */ description?: string; /** * The date when this marketing preference was created * @type {Date} * @memberof PreferenceResponse */ createdDate?: Date; } export function PreferenceResponseFromJSON(json: any): PreferenceResponse { return PreferenceResponseFromJSONTyped(json, false); } export function PreferenceResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): PreferenceResponse { if ((json === undefined) || (json === null)) { return json; } return { 'id': !exists(json, 'id') ? undefined : json['id'], 'name': !exists(json, 'name') ? undefined : json['name'], 'description': !exists(json, 'description') ? undefined : json['description'], 'createdDate': !exists(json, 'created_date') ? undefined : (new Date(json['created_date'])), }; } export function PreferenceResponseToJSON(value?: PreferenceResponse | null): any { if (value === undefined) { return undefined; } if (value === null) { return null; } return { 'id': value.id, 'name': value.name, 'description': value.description, 'created_date': value.createdDate === undefined ? undefined : (value.createdDate.toISOString().substr(0,10)), }; } <file_sep>/* tslint:disable */ /* eslint-disable */ /** * Collins API * This site provides details on the various ways that you can integrate with Collins. Not sure you want to be here after all? Check out what’s new on the [London Bar Scene](https://www.designmynight.com/london/new-bar-spy) instead. * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import * as runtime from '../runtime'; import { CustomerListResponse, CustomerListResponseFromJSON, CustomerListResponseToJSON, CustomerResponse, CustomerResponseFromJSON, CustomerResponseToJSON, InlineResponse401, InlineResponse401FromJSON, InlineResponse401ToJSON, InlineResponse404, InlineResponse404FromJSON, InlineResponse404ToJSON, InlineResponse429, InlineResponse429FromJSON, InlineResponse429ToJSON, NewCustomerRequest, NewCustomerRequestFromJSON, NewCustomerRequestToJSON, ViewCustomer, ViewCustomerFromJSON, ViewCustomerToJSON, } from '../models'; export interface CreateCustomerRequest { newCustomerRequest: NewCustomerRequest; } export interface DeleteCustomerRequest { customerId: string; } export interface GetAllCustomersRequest { associatedVenues?: Array<string>; bookingDate?: Date; bookingDateFrom?: Date; bookingDateTo?: Date; createdDate?: Date; createdDateFrom?: Date; createdDateTo?: Date; dobMonth?: number; email?: Array<string>; fullName?: string; labels?: Array<string>; lastUpdated?: Date; lastUpdatedFrom?: Date; lastUpdatedTo?: Date; optedIn?: Array<string>; optedInDate?: Date; optedInDateFrom?: Date; optedInDateTo?: Date; optedOut?: Array<string>; optedOutDate?: Date; optedOutDateFrom?: Date; optedOutDateTo?: Date; query?: string; limit?: number; sort?: Array<string>; page?: string; } export interface GetCustomerRequest { customerId: string; } export interface UpdateCustomerRequest { customerId: string; viewCustomer: ViewCustomer; } /** * */ export class CustomersApi extends runtime.BaseAPI { /** * Creates a new customer * Create a customer */ async createCustomerRaw(requestParameters: CreateCustomerRequest): Promise<runtime.ApiResponse<CustomerResponse>> { if (requestParameters.newCustomerRequest === null || requestParameters.newCustomerRequest === undefined) { throw new runtime.RequiredError('newCustomerRequest','Required parameter requestParameters.newCustomerRequest was null or undefined when calling createCustomer.'); } const queryParameters: any = {}; const headerParameters: runtime.HTTPHeaders = {}; headerParameters['Content-Type'] = 'application/json'; if (this.configuration && this.configuration.accessToken) { const token = this.configuration.accessToken; const tokenString = typeof token === 'function' ? token("BearerAuth", []) : token; if (tokenString) { headerParameters["Authorization"] = `Bearer ${tokenString}`; } } const response = await this.request({ path: `/customers`, method: 'POST', headers: headerParameters, query: queryParameters, body: NewCustomerRequestToJSON(requestParameters.newCustomerRequest), }); return new runtime.JSONApiResponse(response, (jsonValue) => CustomerResponseFromJSON(jsonValue)); } /** * Creates a new customer * Create a customer */ async createCustomer(requestParameters: CreateCustomerRequest): Promise<CustomerResponse> { const response = await this.createCustomerRaw(requestParameters); return await response.value(); } /** * Deletes an existing customer * Delete a customer */ async deleteCustomerRaw(requestParameters: DeleteCustomerRequest): Promise<runtime.ApiResponse<void>> { if (requestParameters.customerId === null || requestParameters.customerId === undefined) { throw new runtime.RequiredError('customerId','Required parameter requestParameters.customerId was null or undefined when calling deleteCustomer.'); } const queryParameters: any = {}; const headerParameters: runtime.HTTPHeaders = {}; if (this.configuration && this.configuration.accessToken) { const token = this.configuration.accessToken; const tokenString = typeof token === 'function' ? token("BearerAuth", []) : token; if (tokenString) { headerParameters["Authorization"] = `Bearer ${tokenString}`; } } const response = await this.request({ path: `/customers/{customerId}`.replace(`{${"customerId"}}`, encodeURIComponent(String(requestParameters.customerId))), method: 'DELETE', headers: headerParameters, query: queryParameters, }); return new runtime.VoidApiResponse(response); } /** * Deletes an existing customer * Delete a customer */ async deleteCustomer(requestParameters: DeleteCustomerRequest): Promise<void> { await this.deleteCustomerRaw(requestParameters); } /** * Returns an array of all customers which the authenticated user is authorised to view. The response will be [paginated](/#tag/Pagination). * Get customers */ async getAllCustomersRaw(requestParameters: GetAllCustomersRequest): Promise<runtime.ApiResponse<CustomerListResponse>> { const queryParameters: any = {}; if (requestParameters.associatedVenues) { queryParameters['associated_venues'] = requestParameters.associatedVenues.join(runtime.COLLECTION_FORMATS["csv"]); } if (requestParameters.bookingDate !== undefined) { queryParameters['booking_date'] = (requestParameters.bookingDate as any).toISOString().substr(0,10); } if (requestParameters.bookingDateFrom !== undefined) { queryParameters['booking_date_from'] = (requestParameters.bookingDateFrom as any).toISOString().substr(0,10); } if (requestParameters.bookingDateTo !== undefined) { queryParameters['booking_date_to'] = (requestParameters.bookingDateTo as any).toISOString().substr(0,10); } if (requestParameters.createdDate !== undefined) { queryParameters['created_date'] = (requestParameters.createdDate as any).toISOString().substr(0,10); } if (requestParameters.createdDateFrom !== undefined) { queryParameters['created_date_from'] = (requestParameters.createdDateFrom as any).toISOString().substr(0,10); } if (requestParameters.createdDateTo !== undefined) { queryParameters['created_date_to'] = (requestParameters.createdDateTo as any).toISOString().substr(0,10); } if (requestParameters.dobMonth !== undefined) { queryParameters['dob_month'] = requestParameters.dobMonth; } if (requestParameters.email) { queryParameters['email'] = requestParameters.email.join(runtime.COLLECTION_FORMATS["csv"]); } if (requestParameters.fullName !== undefined) { queryParameters['full_name'] = requestParameters.fullName; } if (requestParameters.labels) { queryParameters['labels'] = requestParameters.labels.join(runtime.COLLECTION_FORMATS["csv"]); } if (requestParameters.lastUpdated !== undefined) { queryParameters['last_updated'] = (requestParameters.lastUpdated as any).toISOString().substr(0,10); } if (requestParameters.lastUpdatedFrom !== undefined) { queryParameters['last_updated_from'] = (requestParameters.lastUpdatedFrom as any).toISOString().substr(0,10); } if (requestParameters.lastUpdatedTo !== undefined) { queryParameters['last_updated_to'] = (requestParameters.lastUpdatedTo as any).toISOString().substr(0,10); } if (requestParameters.optedIn) { queryParameters['opted_in'] = requestParameters.optedIn.join(runtime.COLLECTION_FORMATS["csv"]); } if (requestParameters.optedInDate !== undefined) { queryParameters['opted_in_date'] = (requestParameters.optedInDate as any).toISOString().substr(0,10); } if (requestParameters.optedInDateFrom !== undefined) { queryParameters['opted_in_date_from'] = (requestParameters.optedInDateFrom as any).toISOString().substr(0,10); } if (requestParameters.optedInDateTo !== undefined) { queryParameters['opted_in_date_to'] = (requestParameters.optedInDateTo as any).toISOString().substr(0,10); } if (requestParameters.optedOut) { queryParameters['opted_out'] = requestParameters.optedOut.join(runtime.COLLECTION_FORMATS["csv"]); } if (requestParameters.optedOutDate !== undefined) { queryParameters['opted_out_date'] = (requestParameters.optedOutDate as any).toISOString().substr(0,10); } if (requestParameters.optedOutDateFrom !== undefined) { queryParameters['opted_out_date_from'] = (requestParameters.optedOutDateFrom as any).toISOString().substr(0,10); } if (requestParameters.optedOutDateTo !== undefined) { queryParameters['opted_out_date_to'] = (requestParameters.optedOutDateTo as any).toISOString().substr(0,10); } if (requestParameters.query !== undefined) { queryParameters['query'] = requestParameters.query; } if (requestParameters.limit !== undefined) { queryParameters['limit'] = requestParameters.limit; } if (requestParameters.sort) { queryParameters['sort'] = requestParameters.sort.join(runtime.COLLECTION_FORMATS["csv"]); } if (requestParameters.page !== undefined) { queryParameters['page'] = requestParameters.page; } const headerParameters: runtime.HTTPHeaders = {}; if (this.configuration && this.configuration.accessToken) { const token = this.configuration.accessToken; const tokenString = typeof token === 'function' ? token("BearerAuth", []) : token; if (tokenString) { headerParameters["Authorization"] = `Bearer ${tokenString}`; } } const response = await this.request({ path: `/customers`, method: 'GET', headers: headerParameters, query: queryParameters, }); return new runtime.JSONApiResponse(response, (jsonValue) => CustomerListResponseFromJSON(jsonValue)); } /** * Returns an array of all customers which the authenticated user is authorised to view. The response will be [paginated](/#tag/Pagination). * Get customers */ async getAllCustomers(requestParameters: GetAllCustomersRequest): Promise<CustomerListResponse> { const response = await this.getAllCustomersRaw(requestParameters); return await response.value(); } /** * Returns details about a specific customer * Get a customer */ async getCustomerRaw(requestParameters: GetCustomerRequest): Promise<runtime.ApiResponse<CustomerResponse>> { if (requestParameters.customerId === null || requestParameters.customerId === undefined) { throw new runtime.RequiredError('customerId','Required parameter requestParameters.customerId was null or undefined when calling getCustomer.'); } const queryParameters: any = {}; const headerParameters: runtime.HTTPHeaders = {}; if (this.configuration && this.configuration.accessToken) { const token = this.configuration.accessToken; const tokenString = typeof token === 'function' ? token("BearerAuth", []) : token; if (tokenString) { headerParameters["Authorization"] = `Bearer ${tokenString}`; } } const response = await this.request({ path: `/customers/{customerId}`.replace(`{${"customerId"}}`, encodeURIComponent(String(requestParameters.customerId))), method: 'GET', headers: headerParameters, query: queryParameters, }); return new runtime.JSONApiResponse(response, (jsonValue) => CustomerResponseFromJSON(jsonValue)); } /** * Returns details about a specific customer * Get a customer */ async getCustomer(requestParameters: GetCustomerRequest): Promise<CustomerResponse> { const response = await this.getCustomerRaw(requestParameters); return await response.value(); } /** * Updates an existing customer * Update a customer */ async updateCustomerRaw(requestParameters: UpdateCustomerRequest): Promise<runtime.ApiResponse<CustomerResponse>> { if (requestParameters.customerId === null || requestParameters.customerId === undefined) { throw new runtime.RequiredError('customerId','Required parameter requestParameters.customerId was null or undefined when calling updateCustomer.'); } if (requestParameters.viewCustomer === null || requestParameters.viewCustomer === undefined) { throw new runtime.RequiredError('viewCustomer','Required parameter requestParameters.viewCustomer was null or undefined when calling updateCustomer.'); } const queryParameters: any = {}; const headerParameters: runtime.HTTPHeaders = {}; headerParameters['Content-Type'] = 'application/json'; if (this.configuration && this.configuration.accessToken) { const token = this.configuration.accessToken; const tokenString = typeof token === 'function' ? token("BearerAuth", []) : token; if (tokenString) { headerParameters["Authorization"] = `Bearer ${tokenString}`; } } const response = await this.request({ path: `/customers/{customerId}`.replace(`{${"customerId"}}`, encodeURIComponent(String(requestParameters.customerId))), method: 'PUT', headers: headerParameters, query: queryParameters, body: ViewCustomerToJSON(requestParameters.viewCustomer), }); return new runtime.JSONApiResponse(response, (jsonValue) => CustomerResponseFromJSON(jsonValue)); } /** * Updates an existing customer * Update a customer */ async updateCustomer(requestParameters: UpdateCustomerRequest): Promise<CustomerResponse> { const response = await this.updateCustomerRaw(requestParameters); return await response.value(); } } <file_sep>/* tslint:disable */ /* eslint-disable */ /** * Collins API * This site provides details on the various ways that you can integrate with Collins. Not sure you want to be here after all? Check out what’s new on the [London Bar Scene](https://www.designmynight.com/london/new-bar-spy) instead. * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { exists, mapValues } from '../runtime'; /** * The address of the venue. * @export * @interface ViewVenueAddress */ export interface ViewVenueAddress { /** * * @type {string} * @memberof ViewVenueAddress */ buildingName?: string; /** * * @type {string} * @memberof ViewVenueAddress */ street?: string; /** * * @type {string} * @memberof ViewVenueAddress */ city?: string; /** * * @type {string} * @memberof ViewVenueAddress */ postcode?: string; } export function ViewVenueAddressFromJSON(json: any): ViewVenueAddress { return ViewVenueAddressFromJSONTyped(json, false); } export function ViewVenueAddressFromJSONTyped(json: any, ignoreDiscriminator: boolean): ViewVenueAddress { if ((json === undefined) || (json === null)) { return json; } return { 'buildingName': !exists(json, 'building_name') ? undefined : json['building_name'], 'street': !exists(json, 'street') ? undefined : json['street'], 'city': !exists(json, 'city') ? undefined : json['city'], 'postcode': !exists(json, 'postcode') ? undefined : json['postcode'], }; } export function ViewVenueAddressToJSON(value?: ViewVenueAddress | null): any { if (value === undefined) { return undefined; } if (value === null) { return null; } return { 'building_name': value.buildingName, 'street': value.street, 'city': value.city, 'postcode': value.postcode, }; } <file_sep>/* tslint:disable */ /* eslint-disable */ /** * Collins API * This site provides details on the various ways that you can integrate with Collins. Not sure you want to be here after all? Check out what’s new on the [London Bar Scene](https://www.designmynight.com/london/new-bar-spy) instead. * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { exists, mapValues } from '../runtime'; /** * * @export * @interface InlineObject2 */ export interface InlineObject2 { /** * The status of the message. Unread messages have the status `new` and read messages have the status `read`. * @type {string} * @memberof InlineObject2 */ status?: InlineObject2StatusEnum; } /** * @export * @enum {string} */ export enum InlineObject2StatusEnum { New = 'new', Read = 'read' } export function InlineObject2FromJSON(json: any): InlineObject2 { return InlineObject2FromJSONTyped(json, false); } export function InlineObject2FromJSONTyped(json: any, ignoreDiscriminator: boolean): InlineObject2 { if ((json === undefined) || (json === null)) { return json; } return { 'status': !exists(json, 'status') ? undefined : json['status'], }; } export function InlineObject2ToJSON(value?: InlineObject2 | null): any { if (value === undefined) { return undefined; } if (value === null) { return null; } return { 'status': value.status, }; } <file_sep>/* tslint:disable */ /* eslint-disable */ /** * Collins API * This site provides details on the various ways that you can integrate with Collins. Not sure you want to be here after all? Check out what’s new on the [London Bar Scene](https://www.designmynight.com/london/new-bar-spy) instead. * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { exists, mapValues } from '../runtime'; /** * * @export * @interface InlineResponse401 */ export interface InlineResponse401 { /** * A description of the error * @type {string} * @memberof InlineResponse401 */ error?: string; } export function InlineResponse401FromJSON(json: any): InlineResponse401 { return InlineResponse401FromJSONTyped(json, false); } export function InlineResponse401FromJSONTyped(json: any, ignoreDiscriminator: boolean): InlineResponse401 { if ((json === undefined) || (json === null)) { return json; } return { 'error': !exists(json, 'error') ? undefined : json['error'], }; } export function InlineResponse401ToJSON(value?: InlineResponse401 | null): any { if (value === undefined) { return undefined; } if (value === null) { return null; } return { 'error': value.error, }; } <file_sep># Collins SDK ## Introduction This package contains the CollinsBookings SDK available at https://docs.collinsbookings.com. ## Reporting Issues If you have any issues using this SDK then please raise and issue https://github.com/designmynight/collins-api-docs.<file_sep>/* tslint:disable */ /* eslint-disable */ /** * Collins API * This site provides details on the various ways that you can integrate with Collins. Not sure you want to be here after all? Check out what’s new on the [London Bar Scene](https://www.designmynight.com/london/new-bar-spy) instead. * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { exists, mapValues } from '../runtime'; /** * * @export * @interface BookingLinksResponse */ export interface BookingLinksResponse { /** * Link to download a calendar (.ics) attachment for a booking * @type {string} * @memberof BookingLinksResponse */ calendar?: string; /** * Link for a customer to cancel their booking * @type {string} * @memberof BookingLinksResponse */ cancel?: string; /** * Link for a customer to change their booking * @type {string} * @memberof BookingLinksResponse */ change?: string; /** * Link for a customer to pre-order for their booking (if enabled) * @type {string} * @memberof BookingLinksResponse */ preorder?: string; /** * Link for a customer to manage pre-orders for their booking (if enabled) * @type {string} * @memberof BookingLinksResponse */ managePreorder?: string; /** * Link for a customer to pay any outstanding deposits for their booking * @type {string} * @memberof BookingLinksResponse */ payment?: string; /** * Link for a customer to sign the contract attached to their booking * @type {string} * @memberof BookingLinksResponse */ signContract?: string; } export function BookingLinksResponseFromJSON(json: any): BookingLinksResponse { return BookingLinksResponseFromJSONTyped(json, false); } export function BookingLinksResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): BookingLinksResponse { if ((json === undefined) || (json === null)) { return json; } return { 'calendar': !exists(json, 'calendar') ? undefined : json['calendar'], 'cancel': !exists(json, 'cancel') ? undefined : json['cancel'], 'change': !exists(json, 'change') ? undefined : json['change'], 'preorder': !exists(json, 'preorder') ? undefined : json['preorder'], 'managePreorder': !exists(json, 'manage_preorder') ? undefined : json['manage_preorder'], 'payment': !exists(json, 'payment') ? undefined : json['payment'], 'signContract': !exists(json, 'sign_contract') ? undefined : json['sign_contract'], }; } export function BookingLinksResponseToJSON(value?: BookingLinksResponse | null): any { if (value === undefined) { return undefined; } if (value === null) { return null; } return { 'calendar': value.calendar, 'cancel': value.cancel, 'change': value.change, 'preorder': value.preorder, 'manage_preorder': value.managePreorder, 'payment': value.payment, 'sign_contract': value.signContract, }; } <file_sep>/* tslint:disable */ /* eslint-disable */ /** * Collins API * This site provides details on the various ways that you can integrate with Collins. Not sure you want to be here after all? Check out what’s new on the [London Bar Scene](https://www.designmynight.com/london/new-bar-spy) instead. * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { exists, mapValues } from '../runtime'; /** * The address of the company for the booking. * @export * @interface ViewBookingCompanyAddress */ export interface ViewBookingCompanyAddress { /** * The street name of the company * @type {string} * @memberof ViewBookingCompanyAddress */ street?: string; /** * The city which the company is located * @type {string} * @memberof ViewBookingCompanyAddress */ city?: string; /** * The post code of the company * @type {string} * @memberof ViewBookingCompanyAddress */ postCode?: string; } export function ViewBookingCompanyAddressFromJSON(json: any): ViewBookingCompanyAddress { return ViewBookingCompanyAddressFromJSONTyped(json, false); } export function ViewBookingCompanyAddressFromJSONTyped(json: any, ignoreDiscriminator: boolean): ViewBookingCompanyAddress { if ((json === undefined) || (json === null)) { return json; } return { 'street': !exists(json, 'street') ? undefined : json['street'], 'city': !exists(json, 'city') ? undefined : json['city'], 'postCode': !exists(json, 'post_code') ? undefined : json['post_code'], }; } export function ViewBookingCompanyAddressToJSON(value?: ViewBookingCompanyAddress | null): any { if (value === undefined) { return undefined; } if (value === null) { return null; } return { 'street': value.street, 'city': value.city, 'post_code': value.postCode, }; } <file_sep>This site provides details on the various ways that you can integrate with Collins. Not sure you want to be here after all? Check out what’s new on the [London Bar Scene](https://www.designmynight.com/london/new-bar-spy) instead.<file_sep>/* tslint:disable */ /* eslint-disable */ /** * Collins API * This site provides details on the various ways that you can integrate with Collins. Not sure you want to be here after all? Check out what’s new on the [London Bar Scene](https://www.designmynight.com/london/new-bar-spy) instead. * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import * as runtime from '../runtime'; import { BookingAssignedAreasResponse, BookingAssignedAreasResponseFromJSON, BookingAssignedAreasResponseToJSON, BookingLinksResponse, BookingLinksResponseFromJSON, BookingLinksResponseToJSON, BookingListResponse, BookingListResponseFromJSON, BookingListResponseToJSON, InlineObject, InlineObjectFromJSON, InlineObjectToJSON, InlineObject1, InlineObject1FromJSON, InlineObject1ToJSON, InlineObject2, InlineObject2FromJSON, InlineObject2ToJSON, InlineResponse401, InlineResponse401FromJSON, InlineResponse401ToJSON, InlineResponse404, InlineResponse404FromJSON, InlineResponse404ToJSON, InlineResponse429, InlineResponse429FromJSON, InlineResponse429ToJSON, NotificationResponse, NotificationResponseFromJSON, NotificationResponseToJSON, NotificationsListResponse, NotificationsListResponseFromJSON, NotificationsListResponseToJSON, } from '../models'; export interface AppendAssignedAreasRequest { bookingId: string; inlineObject: InlineObject; } export interface GetAllBookingsRequest { actualGuests?: string; assignedArea?: Array<string>; assignedTo?: Array<string>; reference?: number; createdDate?: Date; createdDateFrom?: Date; createdDateTo?: Date; currentStage?: string; date?: Date; dateFrom?: Date; dateTo?: Date; email?: string; autoConfirmed?: boolean; walkIn?: boolean; followUp?: Date; followUpFrom?: Date; followUpTo?: Date; hasPreorders?: boolean; labels?: Array<string>; lastUpdated?: Date; lastUpdatedFrom?: Date; lastUpdatedTo?: Date; notifications?: Array<string>; numPeople?: string; offer?: Array<string>; partnerSource?: string; pendingDeposits?: Array<GetAllBookingsPendingDepositsEnum>; phone?: string; preordersStatus?: GetAllBookingsPreordersStatusEnum; privateHire?: boolean; query?: string; startTime?: string; statusChangedDate?: Date; statusChangedDateFrom?: Date; statusChangedDateTo?: Date; status?: Array<GetAllBookingsStatusEnum>; time?: string; type?: Array<string>; customerId?: Array<string>; venueId?: Array<string>; waitlisted?: boolean; zone?: string; limit?: number; sort?: Array<string>; page?: string; } export interface GetAllNotificationsRequest { status?: string; type?: string; } export interface GetAssignedAreasRequest { bookingId: string; } export interface GetBookingRequest { bookingId: string; } export interface GetBookingLinksRequest { bookingId: string; } export interface ReplaceAssignedAreasRequest { bookingId: string; inlineObject1: InlineObject1; } export interface UnassignAllAreasRequest { bookingId: string; } export interface UnassignOneAreaRequest { bookingId: string; assignedAreaId: string; } export interface UpdateNotificationRequest { inlineObject2?: InlineObject2; } /** * */ export class BookingsApi extends runtime.BaseAPI { /** * Assigns the given areas to the booking, whilst keeping the areas which are already assigned. This request accepts an array of bookable area IDs, which you can retrieve using the Venues endpoint. A validation error will be returned if you attempt to assign area(s) to a booking which doesn\'t have a venue, or if you attempt to assign area(s) which don\'t belong to the attached venue. Keep in mind that the request *won\'t* return an error response if you attempt to assign an area which is already assigned to the booking. * Appends to the assigned areas of the booking */ async appendAssignedAreasRaw(requestParameters: AppendAssignedAreasRequest): Promise<runtime.ApiResponse<BookingAssignedAreasResponse>> { if (requestParameters.bookingId === null || requestParameters.bookingId === undefined) { throw new runtime.RequiredError('bookingId','Required parameter requestParameters.bookingId was null or undefined when calling appendAssignedAreas.'); } if (requestParameters.inlineObject === null || requestParameters.inlineObject === undefined) { throw new runtime.RequiredError('inlineObject','Required parameter requestParameters.inlineObject was null or undefined when calling appendAssignedAreas.'); } const queryParameters: any = {}; const headerParameters: runtime.HTTPHeaders = {}; headerParameters['Content-Type'] = 'application/json'; if (this.configuration && this.configuration.accessToken) { const token = this.configuration.accessToken; const tokenString = typeof token === 'function' ? token("BearerAuth", []) : token; if (tokenString) { headerParameters["Authorization"] = `Bearer ${tokenString}`; } } const response = await this.request({ path: `/bookings/{bookingId}/assigned-areas`.replace(`{${"bookingId"}}`, encodeURIComponent(String(requestParameters.bookingId))), method: 'PUT', headers: headerParameters, query: queryParameters, body: InlineObjectToJSON(requestParameters.inlineObject), }); return new runtime.JSONApiResponse(response, (jsonValue) => BookingAssignedAreasResponseFromJSON(jsonValue)); } /** * Assigns the given areas to the booking, whilst keeping the areas which are already assigned. This request accepts an array of bookable area IDs, which you can retrieve using the Venues endpoint. A validation error will be returned if you attempt to assign area(s) to a booking which doesn\'t have a venue, or if you attempt to assign area(s) which don\'t belong to the attached venue. Keep in mind that the request *won\'t* return an error response if you attempt to assign an area which is already assigned to the booking. * Appends to the assigned areas of the booking */ async appendAssignedAreas(requestParameters: AppendAssignedAreasRequest): Promise<BookingAssignedAreasResponse> { const response = await this.appendAssignedAreasRaw(requestParameters); return await response.value(); } /** * Returns an array of all bookings which the authenticated user is authorised to view. The response will be [paginated](/#tag/Pagination). * Get bookings */ async getAllBookingsRaw(requestParameters: GetAllBookingsRequest): Promise<runtime.ApiResponse<BookingListResponse>> { const queryParameters: any = {}; if (requestParameters.actualGuests !== undefined) { queryParameters['actual_guests'] = requestParameters.actualGuests; } if (requestParameters.assignedArea) { queryParameters['assigned_area'] = requestParameters.assignedArea.join(runtime.COLLECTION_FORMATS["csv"]); } if (requestParameters.assignedTo) { queryParameters['assigned_to'] = requestParameters.assignedTo.join(runtime.COLLECTION_FORMATS["csv"]); } if (requestParameters.reference !== undefined) { queryParameters['reference'] = requestParameters.reference; } if (requestParameters.createdDate !== undefined) { queryParameters['created_date'] = (requestParameters.createdDate as any).toISOString().substr(0,10); } if (requestParameters.createdDateFrom !== undefined) { queryParameters['created_date_from'] = (requestParameters.createdDateFrom as any).toISOString().substr(0,10); } if (requestParameters.createdDateTo !== undefined) { queryParameters['created_date_to'] = (requestParameters.createdDateTo as any).toISOString().substr(0,10); } if (requestParameters.currentStage !== undefined) { queryParameters['current_stage'] = requestParameters.currentStage; } if (requestParameters.date !== undefined) { queryParameters['date'] = (requestParameters.date as any).toISOString().substr(0,10); } if (requestParameters.dateFrom !== undefined) { queryParameters['date_from'] = (requestParameters.dateFrom as any).toISOString().substr(0,10); } if (requestParameters.dateTo !== undefined) { queryParameters['date_to'] = (requestParameters.dateTo as any).toISOString().substr(0,10); } if (requestParameters.email !== undefined) { queryParameters['email'] = requestParameters.email; } if (requestParameters.autoConfirmed !== undefined) { queryParameters['auto_confirmed'] = requestParameters.autoConfirmed; } if (requestParameters.walkIn !== undefined) { queryParameters['walk_in'] = requestParameters.walkIn; } if (requestParameters.followUp !== undefined) { queryParameters['follow_up'] = (requestParameters.followUp as any).toISOString().substr(0,10); } if (requestParameters.followUpFrom !== undefined) { queryParameters['follow_up_from'] = (requestParameters.followUpFrom as any).toISOString().substr(0,10); } if (requestParameters.followUpTo !== undefined) { queryParameters['follow_up_to'] = (requestParameters.followUpTo as any).toISOString().substr(0,10); } if (requestParameters.hasPreorders !== undefined) { queryParameters['has_preorders'] = requestParameters.hasPreorders; } if (requestParameters.labels) { queryParameters['labels'] = requestParameters.labels.join(runtime.COLLECTION_FORMATS["csv"]); } if (requestParameters.lastUpdated !== undefined) { queryParameters['last_updated'] = (requestParameters.lastUpdated as any).toISOString().substr(0,10); } if (requestParameters.lastUpdatedFrom !== undefined) { queryParameters['last_updated_from'] = (requestParameters.lastUpdatedFrom as any).toISOString().substr(0,10); } if (requestParameters.lastUpdatedTo !== undefined) { queryParameters['last_updated_to'] = (requestParameters.lastUpdatedTo as any).toISOString().substr(0,10); } if (requestParameters.notifications) { queryParameters['notifications'] = requestParameters.notifications.join(runtime.COLLECTION_FORMATS["csv"]); } if (requestParameters.numPeople !== undefined) { queryParameters['num_people'] = requestParameters.numPeople; } if (requestParameters.offer) { queryParameters['offer'] = requestParameters.offer.join(runtime.COLLECTION_FORMATS["csv"]); } if (requestParameters.partnerSource !== undefined) { queryParameters['partner_source'] = requestParameters.partnerSource; } if (requestParameters.pendingDeposits) { queryParameters['pending_deposits'] = requestParameters.pendingDeposits.join(runtime.COLLECTION_FORMATS["csv"]); } if (requestParameters.phone !== undefined) { queryParameters['phone'] = requestParameters.phone; } if (requestParameters.preordersStatus !== undefined) { queryParameters['preorders_status'] = requestParameters.preordersStatus; } if (requestParameters.privateHire !== undefined) { queryParameters['private_hire'] = requestParameters.privateHire; } if (requestParameters.query !== undefined) { queryParameters['query'] = requestParameters.query; } if (requestParameters.startTime !== undefined) { queryParameters['start_time'] = requestParameters.startTime; } if (requestParameters.statusChangedDate !== undefined) { queryParameters['status_changed_date'] = (requestParameters.statusChangedDate as any).toISOString().substr(0,10); } if (requestParameters.statusChangedDateFrom !== undefined) { queryParameters['status_changed_date_from'] = (requestParameters.statusChangedDateFrom as any).toISOString().substr(0,10); } if (requestParameters.statusChangedDateTo !== undefined) { queryParameters['status_changed_date_to'] = (requestParameters.statusChangedDateTo as any).toISOString().substr(0,10); } if (requestParameters.status) { queryParameters['status'] = requestParameters.status.join(runtime.COLLECTION_FORMATS["csv"]); } if (requestParameters.time !== undefined) { queryParameters['time'] = requestParameters.time; } if (requestParameters.type) { queryParameters['type'] = requestParameters.type.join(runtime.COLLECTION_FORMATS["csv"]); } if (requestParameters.customerId) { queryParameters['customer_id'] = requestParameters.customerId.join(runtime.COLLECTION_FORMATS["csv"]); } if (requestParameters.venueId) { queryParameters['venue_id'] = requestParameters.venueId.join(runtime.COLLECTION_FORMATS["csv"]); } if (requestParameters.waitlisted !== undefined) { queryParameters['waitlisted'] = requestParameters.waitlisted; } if (requestParameters.zone !== undefined) { queryParameters['zone'] = requestParameters.zone; } if (requestParameters.limit !== undefined) { queryParameters['limit'] = requestParameters.limit; } if (requestParameters.sort) { queryParameters['sort'] = requestParameters.sort.join(runtime.COLLECTION_FORMATS["csv"]); } if (requestParameters.page !== undefined) { queryParameters['page'] = requestParameters.page; } const headerParameters: runtime.HTTPHeaders = {}; if (this.configuration && this.configuration.accessToken) { const token = this.configuration.accessToken; const tokenString = typeof token === 'function' ? token("BearerAuth", []) : token; if (tokenString) { headerParameters["Authorization"] = `Bearer ${tokenString}`; } } const response = await this.request({ path: `/bookings`, method: 'GET', headers: headerParameters, query: queryParameters, }); return new runtime.JSONApiResponse(response, (jsonValue) => BookingListResponseFromJSON(jsonValue)); } /** * Returns an array of all bookings which the authenticated user is authorised to view. The response will be [paginated](/#tag/Pagination). * Get bookings */ async getAllBookings(requestParameters: GetAllBookingsRequest): Promise<BookingListResponse> { const response = await this.getAllBookingsRaw(requestParameters); return await response.value(); } /** * Returns an array of all notifications for this booking. This includes read notifications. If you only want to see unread notifications, you can use the `status` filter. * Get notifications */ async getAllNotificationsRaw(requestParameters: GetAllNotificationsRequest): Promise<runtime.ApiResponse<NotificationsListResponse>> { const queryParameters: any = {}; if (requestParameters.status !== undefined) { queryParameters['status'] = requestParameters.status; } if (requestParameters.type !== undefined) { queryParameters['type'] = requestParameters.type; } const headerParameters: runtime.HTTPHeaders = {}; if (this.configuration && this.configuration.accessToken) { const token = this.configuration.accessToken; const tokenString = typeof token === 'function' ? token("BearerAuth", []) : token; if (tokenString) { headerParameters["Authorization"] = `Bearer ${tokenString}`; } } const response = await this.request({ path: `/bookings/{bookingId}/notifications`, method: 'GET', headers: headerParameters, query: queryParameters, }); return new runtime.JSONApiResponse(response, (jsonValue) => NotificationsListResponseFromJSON(jsonValue)); } /** * Returns an array of all notifications for this booking. This includes read notifications. If you only want to see unread notifications, you can use the `status` filter. * Get notifications */ async getAllNotifications(requestParameters: GetAllNotificationsRequest): Promise<NotificationsListResponse> { const response = await this.getAllNotificationsRaw(requestParameters); return await response.value(); } /** * Returns an array of areas which the booking is assigned to * Get assigned areas (tables) for a booking */ async getAssignedAreasRaw(requestParameters: GetAssignedAreasRequest): Promise<runtime.ApiResponse<BookingAssignedAreasResponse>> { if (requestParameters.bookingId === null || requestParameters.bookingId === undefined) { throw new runtime.RequiredError('bookingId','Required parameter requestParameters.bookingId was null or undefined when calling getAssignedAreas.'); } const queryParameters: any = {}; const headerParameters: runtime.HTTPHeaders = {}; if (this.configuration && this.configuration.accessToken) { const token = this.configuration.accessToken; const tokenString = typeof token === 'function' ? token("BearerAuth", []) : token; if (tokenString) { headerParameters["Authorization"] = `Bearer ${tokenString}`; } } const response = await this.request({ path: `/bookings/{bookingId}/assigned-areas`.replace(`{${"bookingId"}}`, encodeURIComponent(String(requestParameters.bookingId))), method: 'GET', headers: headerParameters, query: queryParameters, }); return new runtime.JSONApiResponse(response, (jsonValue) => BookingAssignedAreasResponseFromJSON(jsonValue)); } /** * Returns an array of areas which the booking is assigned to * Get assigned areas (tables) for a booking */ async getAssignedAreas(requestParameters: GetAssignedAreasRequest): Promise<BookingAssignedAreasResponse> { const response = await this.getAssignedAreasRaw(requestParameters); return await response.value(); } /** * Returns details about a specific booking * Get a booking */ async getBookingRaw(requestParameters: GetBookingRequest): Promise<runtime.ApiResponse<void>> { if (requestParameters.bookingId === null || requestParameters.bookingId === undefined) { throw new runtime.RequiredError('bookingId','Required parameter requestParameters.bookingId was null or undefined when calling getBooking.'); } const queryParameters: any = {}; const headerParameters: runtime.HTTPHeaders = {}; if (this.configuration && this.configuration.accessToken) { const token = this.configuration.accessToken; const tokenString = typeof token === 'function' ? token("BearerAuth", []) : token; if (tokenString) { headerParameters["Authorization"] = `Bearer ${tokenString}`; } } const response = await this.request({ path: `/bookings/{bookingId}`.replace(`{${"bookingId"}}`, encodeURIComponent(String(requestParameters.bookingId))), method: 'GET', headers: headerParameters, query: queryParameters, }); return new runtime.VoidApiResponse(response); } /** * Returns details about a specific booking * Get a booking */ async getBooking(requestParameters: GetBookingRequest): Promise<void> { await this.getBookingRaw(requestParameters); } /** * Returns an array of URLs for customer-facing actions relating to a booking * Get links for a booking */ async getBookingLinksRaw(requestParameters: GetBookingLinksRequest): Promise<runtime.ApiResponse<BookingLinksResponse>> { if (requestParameters.bookingId === null || requestParameters.bookingId === undefined) { throw new runtime.RequiredError('bookingId','Required parameter requestParameters.bookingId was null or undefined when calling getBookingLinks.'); } const queryParameters: any = {}; const headerParameters: runtime.HTTPHeaders = {}; if (this.configuration && this.configuration.accessToken) { const token = this.configuration.accessToken; const tokenString = typeof token === 'function' ? token("BearerAuth", []) : token; if (tokenString) { headerParameters["Authorization"] = `Bearer ${tokenString}`; } } const response = await this.request({ path: `/bookings/{bookingId}/links`.replace(`{${"bookingId"}}`, encodeURIComponent(String(requestParameters.bookingId))), method: 'GET', headers: headerParameters, query: queryParameters, }); return new runtime.JSONApiResponse(response, (jsonValue) => BookingLinksResponseFromJSON(jsonValue)); } /** * Returns an array of URLs for customer-facing actions relating to a booking * Get links for a booking */ async getBookingLinks(requestParameters: GetBookingLinksRequest): Promise<BookingLinksResponse> { const response = await this.getBookingLinksRaw(requestParameters); return await response.value(); } /** * Returns the notification by the given ID. * Get a notification */ async getNotificationRaw(): Promise<runtime.ApiResponse<NotificationResponse>> { const queryParameters: any = {}; const headerParameters: runtime.HTTPHeaders = {}; if (this.configuration && this.configuration.accessToken) { const token = this.configuration.accessToken; const tokenString = typeof token === 'function' ? token("BearerAuth", []) : token; if (tokenString) { headerParameters["Authorization"] = `Bearer ${tokenString}`; } } const response = await this.request({ path: `/bookings/{bookingId}/notifications/{notificationId}`, method: 'GET', headers: headerParameters, query: queryParameters, }); return new runtime.JSONApiResponse(response, (jsonValue) => NotificationResponseFromJSON(jsonValue)); } /** * Returns the notification by the given ID. * Get a notification */ async getNotification(): Promise<NotificationResponse> { const response = await this.getNotificationRaw(); return await response.value(); } /** * Unassigns all areas from the booking and assigns the given ones. This request accepts an array of bookable area IDs, which you can retrieve using the Venues endpoint. A validation error will be returned if you attempt to assign area(s) to a booking which doesn\'t have a venue, or if you attempt to assign area(s) which don\'t belong to the attached venue. Keep in mind that the request *won\'t* return an error response if you attempt to assign an area which is already assigned to the booking. If you\'re looking to append assigned areas rather than replace, see [Appending assigned areas](#operation/AppendAssignedAreas). * Replaces the assigned areas of the booking */ async replaceAssignedAreasRaw(requestParameters: ReplaceAssignedAreasRequest): Promise<runtime.ApiResponse<BookingAssignedAreasResponse>> { if (requestParameters.bookingId === null || requestParameters.bookingId === undefined) { throw new runtime.RequiredError('bookingId','Required parameter requestParameters.bookingId was null or undefined when calling replaceAssignedAreas.'); } if (requestParameters.inlineObject1 === null || requestParameters.inlineObject1 === undefined) { throw new runtime.RequiredError('inlineObject1','Required parameter requestParameters.inlineObject1 was null or undefined when calling replaceAssignedAreas.'); } const queryParameters: any = {}; const headerParameters: runtime.HTTPHeaders = {}; headerParameters['Content-Type'] = 'application/json'; if (this.configuration && this.configuration.accessToken) { const token = this.configuration.accessToken; const tokenString = typeof token === 'function' ? token("BearerAuth", []) : token; if (tokenString) { headerParameters["Authorization"] = `Bearer ${tokenString}`; } } const response = await this.request({ path: `/bookings/{bookingId}/assigned-areas`.replace(`{${"bookingId"}}`, encodeURIComponent(String(requestParameters.bookingId))), method: 'POST', headers: headerParameters, query: queryParameters, body: InlineObject1ToJSON(requestParameters.inlineObject1), }); return new runtime.JSONApiResponse(response, (jsonValue) => BookingAssignedAreasResponseFromJSON(jsonValue)); } /** * Unassigns all areas from the booking and assigns the given ones. This request accepts an array of bookable area IDs, which you can retrieve using the Venues endpoint. A validation error will be returned if you attempt to assign area(s) to a booking which doesn\'t have a venue, or if you attempt to assign area(s) which don\'t belong to the attached venue. Keep in mind that the request *won\'t* return an error response if you attempt to assign an area which is already assigned to the booking. If you\'re looking to append assigned areas rather than replace, see [Appending assigned areas](#operation/AppendAssignedAreas). * Replaces the assigned areas of the booking */ async replaceAssignedAreas(requestParameters: ReplaceAssignedAreasRequest): Promise<BookingAssignedAreasResponse> { const response = await this.replaceAssignedAreasRaw(requestParameters); return await response.value(); } /** * Unassigns all areas from the booking. This request *won\'t* return an error response if the booking doesn\'t have any assigned areas. If you\'re looking to unassign a particular area, see [Unassigning an area](#operation/UnassignOneArea) * Unassigns all areas from the booking */ async unassignAllAreasRaw(requestParameters: UnassignAllAreasRequest): Promise<runtime.ApiResponse<BookingAssignedAreasResponse>> { if (requestParameters.bookingId === null || requestParameters.bookingId === undefined) { throw new runtime.RequiredError('bookingId','Required parameter requestParameters.bookingId was null or undefined when calling unassignAllAreas.'); } const queryParameters: any = {}; const headerParameters: runtime.HTTPHeaders = {}; if (this.configuration && this.configuration.accessToken) { const token = this.configuration.accessToken; const tokenString = typeof token === 'function' ? token("BearerAuth", []) : token; if (tokenString) { headerParameters["Authorization"] = `Bearer ${tokenString}`; } } const response = await this.request({ path: `/bookings/{bookingId}/assigned-areas`.replace(`{${"bookingId"}}`, encodeURIComponent(String(requestParameters.bookingId))), method: 'DELETE', headers: headerParameters, query: queryParameters, }); return new runtime.JSONApiResponse(response, (jsonValue) => BookingAssignedAreasResponseFromJSON(jsonValue)); } /** * Unassigns all areas from the booking. This request *won\'t* return an error response if the booking doesn\'t have any assigned areas. If you\'re looking to unassign a particular area, see [Unassigning an area](#operation/UnassignOneArea) * Unassigns all areas from the booking */ async unassignAllAreas(requestParameters: UnassignAllAreasRequest): Promise<BookingAssignedAreasResponse> { const response = await this.unassignAllAreasRaw(requestParameters); return await response.value(); } /** * Unassigns the given area from the booking. This request will return an error response if you attempt to unassign an area which is not assigned to the booking. If you\'re looking to unassign *all* areas, see [Unassigning all areas](#operation/UnassignAllAreas) * Unassigns an area from the booking */ async unassignOneAreaRaw(requestParameters: UnassignOneAreaRequest): Promise<runtime.ApiResponse<BookingAssignedAreasResponse>> { if (requestParameters.bookingId === null || requestParameters.bookingId === undefined) { throw new runtime.RequiredError('bookingId','Required parameter requestParameters.bookingId was null or undefined when calling unassignOneArea.'); } if (requestParameters.assignedAreaId === null || requestParameters.assignedAreaId === undefined) { throw new runtime.RequiredError('assignedAreaId','Required parameter requestParameters.assignedAreaId was null or undefined when calling unassignOneArea.'); } const queryParameters: any = {}; const headerParameters: runtime.HTTPHeaders = {}; if (this.configuration && this.configuration.accessToken) { const token = this.configuration.accessToken; const tokenString = typeof token === 'function' ? token("BearerAuth", []) : token; if (tokenString) { headerParameters["Authorization"] = `Bearer ${tokenString}`; } } const response = await this.request({ path: `/bookings/{bookingId}/assigned-areas/{assignedAreaId}`.replace(`{${"bookingId"}}`, encodeURIComponent(String(requestParameters.bookingId))).replace(`{${"assignedAreaId"}}`, encodeURIComponent(String(requestParameters.assignedAreaId))), method: 'DELETE', headers: headerParameters, query: queryParameters, }); return new runtime.JSONApiResponse(response, (jsonValue) => BookingAssignedAreasResponseFromJSON(jsonValue)); } /** * Unassigns the given area from the booking. This request will return an error response if you attempt to unassign an area which is not assigned to the booking. If you\'re looking to unassign *all* areas, see [Unassigning all areas](#operation/UnassignAllAreas) * Unassigns an area from the booking */ async unassignOneArea(requestParameters: UnassignOneAreaRequest): Promise<BookingAssignedAreasResponse> { const response = await this.unassignOneAreaRaw(requestParameters); return await response.value(); } /** * Updates the given booking notification * Update a notification */ async updateNotificationRaw(requestParameters: UpdateNotificationRequest): Promise<runtime.ApiResponse<NotificationResponse>> { const queryParameters: any = {}; const headerParameters: runtime.HTTPHeaders = {}; headerParameters['Content-Type'] = 'application/json'; if (this.configuration && this.configuration.accessToken) { const token = this.configuration.accessToken; const tokenString = typeof token === 'function' ? token("BearerAuth", []) : token; if (tokenString) { headerParameters["Authorization"] = `Bearer ${tokenString}`; } } const response = await this.request({ path: `/bookings/{bookingId}/notifications/{notificationId}`, method: 'PUT', headers: headerParameters, query: queryParameters, body: InlineObject2ToJSON(requestParameters.inlineObject2), }); return new runtime.JSONApiResponse(response, (jsonValue) => NotificationResponseFromJSON(jsonValue)); } /** * Updates the given booking notification * Update a notification */ async updateNotification(requestParameters: UpdateNotificationRequest): Promise<NotificationResponse> { const response = await this.updateNotificationRaw(requestParameters); return await response.value(); } } /** * @export * @enum {string} */ export enum GetAllBookingsPendingDepositsEnum { RequestAuth = 'request_auth', ManualAuth = 'manual_auth', RequestPayment = 'request_payment', ManualPayment = 'manual_payment', CustomerPreorder = 'customer_preorder', Paid = 'paid' } /** * @export * @enum {string} */ export enum GetAllBookingsPreordersStatusEnum { Open = 'open', Complete = 'complete' } /** * @export * @enum {string} */ export enum GetAllBookingsStatusEnum { New = 'new', InProgress = 'in_progress', Complete = 'complete', Rejected = 'rejected', Deleted = 'deleted', Lost = 'lost' } <file_sep>/* tslint:disable */ /* eslint-disable */ /** * Collins API * This site provides details on the various ways that you can integrate with Collins. Not sure you want to be here after all? Check out what’s new on the [London Bar Scene](https://www.designmynight.com/london/new-bar-spy) instead. * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { exists, mapValues } from '../runtime'; /** * * @export * @interface InlineObject */ export interface InlineObject { /** * Array of bookable area IDs * @type {Array<string>} * @memberof InlineObject */ areas?: Array<string>; } export function InlineObjectFromJSON(json: any): InlineObject { return InlineObjectFromJSONTyped(json, false); } export function InlineObjectFromJSONTyped(json: any, ignoreDiscriminator: boolean): InlineObject { if ((json === undefined) || (json === null)) { return json; } return { 'areas': !exists(json, 'areas') ? undefined : json['areas'], }; } export function InlineObjectToJSON(value?: InlineObject | null): any { if (value === undefined) { return undefined; } if (value === null) { return null; } return { 'areas': value.areas, }; } <file_sep>The API is accessible through the domain `api.collinsbookings.com`, and all API endpoints are prefixed with `/api`. All requests should be made over HTTPS. Requests to the playpen environment can be made using the domain `api-playpen.collinsbookings.com`. You'll need separate credentials to connect to playpen which your account manager will be able to provide you with.<file_sep>/* tslint:disable */ /* eslint-disable */ /** * Collins API * This site provides details on the various ways that you can integrate with Collins. Not sure you want to be here after all? Check out what’s new on the [London Bar Scene](https://www.designmynight.com/london/new-bar-spy) instead. * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { exists, mapValues } from '../runtime'; /** * * @export * @interface MoneyResponse */ export interface MoneyResponse { /** * The currency which this is in, in ISO-4217 format. * @type {string} * @memberof MoneyResponse */ currency?: string; /** * The amount in pence. * @type {string} * @memberof MoneyResponse */ amount?: string; } export function MoneyResponseFromJSON(json: any): MoneyResponse { return MoneyResponseFromJSONTyped(json, false); } export function MoneyResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): MoneyResponse { if ((json === undefined) || (json === null)) { return json; } return { 'currency': !exists(json, 'currency') ? undefined : json['currency'], 'amount': !exists(json, 'amount') ? undefined : json['amount'], }; } export function MoneyResponseToJSON(value?: MoneyResponse | null): any { if (value === undefined) { return undefined; } if (value === null) { return null; } return { 'currency': value.currency, 'amount': value.amount, }; } <file_sep>/* tslint:disable */ /* eslint-disable */ /** * Collins API * This site provides details on the various ways that you can integrate with Collins. Not sure you want to be here after all? Check out what’s new on the [London Bar Scene](https://www.designmynight.com/london/new-bar-spy) instead. * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { exists, mapValues } from '../runtime'; import { ViewAssignedArea, ViewAssignedAreaFromJSON, ViewAssignedAreaFromJSONTyped, ViewAssignedAreaToJSON, } from './'; /** * * @export * @interface BookingAssignedAreasResponse */ export interface BookingAssignedAreasResponse { /** * An array of the areas which this booking is assigned to. * @type {Array<ViewAssignedArea>} * @memberof BookingAssignedAreasResponse */ assignedAreas?: Array<ViewAssignedArea>; } export function BookingAssignedAreasResponseFromJSON(json: any): BookingAssignedAreasResponse { return BookingAssignedAreasResponseFromJSONTyped(json, false); } export function BookingAssignedAreasResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): BookingAssignedAreasResponse { if ((json === undefined) || (json === null)) { return json; } return { 'assignedAreas': !exists(json, 'assigned_areas') ? undefined : ((json['assigned_areas'] as Array<any>).map(ViewAssignedAreaFromJSON)), }; } export function BookingAssignedAreasResponseToJSON(value?: BookingAssignedAreasResponse | null): any { if (value === undefined) { return undefined; } if (value === null) { return null; } return { 'assigned_areas': value.assignedAreas === undefined ? undefined : ((value.assignedAreas as Array<any>).map(ViewAssignedAreaToJSON)), }; } <file_sep>/* tslint:disable */ /* eslint-disable */ /** * Collins API * This site provides details on the various ways that you can integrate with Collins. Not sure you want to be here after all? Check out what’s new on the [London Bar Scene](https://www.designmynight.com/london/new-bar-spy) instead. * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { exists, mapValues } from '../runtime'; /** * The address of the customer's company * @export * @interface NewCustomerRequestCompanyAddress */ export interface NewCustomerRequestCompanyAddress { /** * The street name of the customer's company * @type {object} * @memberof NewCustomerRequestCompanyAddress */ street?: object; /** * The city of the customer's company * @type {object} * @memberof NewCustomerRequestCompanyAddress */ city?: object; /** * The post code of the customer's company * @type {object} * @memberof NewCustomerRequestCompanyAddress */ postCode?: object; } export function NewCustomerRequestCompanyAddressFromJSON(json: any): NewCustomerRequestCompanyAddress { return NewCustomerRequestCompanyAddressFromJSONTyped(json, false); } export function NewCustomerRequestCompanyAddressFromJSONTyped(json: any, ignoreDiscriminator: boolean): NewCustomerRequestCompanyAddress { if ((json === undefined) || (json === null)) { return json; } return { 'street': !exists(json, 'street') ? undefined : json['street'], 'city': !exists(json, 'city') ? undefined : json['city'], 'postCode': !exists(json, 'post_code') ? undefined : json['post_code'], }; } export function NewCustomerRequestCompanyAddressToJSON(value?: NewCustomerRequestCompanyAddress | null): any { if (value === undefined) { return undefined; } if (value === null) { return null; } return { 'street': value.street, 'city': value.city, 'post_code': value.postCode, }; } <file_sep>/* tslint:disable */ /* eslint-disable */ /** * Collins API * This site provides details on the various ways that you can integrate with Collins. Not sure you want to be here after all? Check out what’s new on the [London Bar Scene](https://www.designmynight.com/london/new-bar-spy) instead. * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { exists, mapValues } from '../runtime'; /** * * @export * @interface ViewNotification */ export interface ViewNotification { /** * The ID of the notification. * @type {string} * @memberof ViewNotification */ id?: string; /** * The status of the notification * @type {string} * @memberof ViewNotification */ status?: ViewNotificationStatusEnum; /** * The type of notification * @type {string} * @memberof ViewNotification */ type?: ViewNotificationTypeEnum; } /** * @export * @enum {string} */ export enum ViewNotificationStatusEnum { New = 'new', Unread = 'unread' }/** * @export * @enum {string} */ export enum ViewNotificationTypeEnum { EmailDeliveryFailed = 'email_delivery_failed', ContractSigned = 'contract_signed', CustomerCancelled = 'customer_cancelled', CustomerNotes = 'customer_notes' } export function ViewNotificationFromJSON(json: any): ViewNotification { return ViewNotificationFromJSONTyped(json, false); } export function ViewNotificationFromJSONTyped(json: any, ignoreDiscriminator: boolean): ViewNotification { if ((json === undefined) || (json === null)) { return json; } return { 'id': !exists(json, 'id') ? undefined : json['id'], 'status': !exists(json, 'status') ? undefined : json['status'], 'type': !exists(json, 'type') ? undefined : json['type'], }; } export function ViewNotificationToJSON(value?: ViewNotification | null): any { if (value === undefined) { return undefined; } if (value === null) { return null; } return { 'id': value.id, 'status': value.status, 'type': value.type, }; } <file_sep>Some API responses are paginated. If a response contains paginated data, this will be clearly marked in these docs. You should check the headers for details about the pagination: Header Name | Description --- | --- `X-Pagination-Page` | The page number for the current set of results `X-Pagination-Per-Page` | The total number of resources that will be returned per page `X-Pagination-Total-Pages` | The total number of pages `X-Pagination-Total-Results` | The total number of resources that the search query returned To specify the page you want to retrieve results for, you should use the `page` URL parameter. For example, if you made the following request: ```shell $ curl https://api.collinsbookings.com/api/customers?query=<EMAIL> ``` and the following headers were sent back: ``` X-Pagination-Page 1 X-Pagination-Per-Page 30 X-Pagination-Total-Pages 4 X-Pagination-Total-Results 100 ``` The query returned 100 results, but each request will only show 30 at a time. To grab the next 30, you will need to make an additional request with the `page` URL parameter and increment this for the number of pages (`X-Pagination-Total-Pages`), like so: ```shell $ curl https://api.collinsbookings.com/api/customers?query=<EMAIL>&page=2 $ curl https://api.collinsbookings.com/api/customers?query=<EMAIL>&page=3 $ curl https://api.collinsbookings.com/api/customers?query=<EMAIL>&page=4 ``` <file_sep>/* tslint:disable */ /* eslint-disable */ /** * Collins API * This site provides details on the various ways that you can integrate with Collins. Not sure you want to be here after all? Check out what’s new on the [London Bar Scene](https://www.designmynight.com/london/new-bar-spy) instead. * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import * as runtime from '../runtime'; import { PreferenceResponse, PreferenceResponseFromJSON, PreferenceResponseToJSON, } from '../models'; export interface GetVenueGroupMarketingPreferencesRequest { venueGroupId: string; } /** * */ export class VenueGroupsApi extends runtime.BaseAPI { /** * Returns an array of marketing preferences which have been set up for the given venue group. * Get marketing preferences */ async getVenueGroupMarketingPreferencesRaw(requestParameters: GetVenueGroupMarketingPreferencesRequest): Promise<runtime.ApiResponse<Array<PreferenceResponse>>> { if (requestParameters.venueGroupId === null || requestParameters.venueGroupId === undefined) { throw new runtime.RequiredError('venueGroupId','Required parameter requestParameters.venueGroupId was null or undefined when calling getVenueGroupMarketingPreferences.'); } const queryParameters: any = {}; const headerParameters: runtime.HTTPHeaders = {}; if (this.configuration && this.configuration.accessToken) { const token = this.configuration.accessToken; const tokenString = typeof token === 'function' ? token("BearerAuth", []) : token; if (tokenString) { headerParameters["Authorization"] = `Bearer ${tokenString}`; } } const response = await this.request({ path: `/venue-groups/{venueGroupId}/marketing-preferences`.replace(`{${"venueGroupId"}}`, encodeURIComponent(String(requestParameters.venueGroupId))), method: 'GET', headers: headerParameters, query: queryParameters, }); return new runtime.JSONApiResponse(response, (jsonValue) => jsonValue.map(PreferenceResponseFromJSON)); } /** * Returns an array of marketing preferences which have been set up for the given venue group. * Get marketing preferences */ async getVenueGroupMarketingPreferences(requestParameters: GetVenueGroupMarketingPreferencesRequest): Promise<Array<PreferenceResponse>> { const response = await this.getVenueGroupMarketingPreferencesRaw(requestParameters); return await response.value(); } } <file_sep>/* tslint:disable */ /* eslint-disable */ /** * Collins API * This site provides details on the various ways that you can integrate with Collins. Not sure you want to be here after all? Check out what’s new on the [London Bar Scene](https://www.designmynight.com/london/new-bar-spy) instead. * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { exists, mapValues } from '../runtime'; /** * The address of the customer's company * @export * @interface ViewCustomerCompanyAddress */ export interface ViewCustomerCompanyAddress { /** * The street name of the company * @type {string} * @memberof ViewCustomerCompanyAddress */ street?: string; /** * The city which the company is located * @type {string} * @memberof ViewCustomerCompanyAddress */ city?: string; /** * The post code of the company * @type {string} * @memberof ViewCustomerCompanyAddress */ postCode?: string; } export function ViewCustomerCompanyAddressFromJSON(json: any): ViewCustomerCompanyAddress { return ViewCustomerCompanyAddressFromJSONTyped(json, false); } export function ViewCustomerCompanyAddressFromJSONTyped(json: any, ignoreDiscriminator: boolean): ViewCustomerCompanyAddress { if ((json === undefined) || (json === null)) { return json; } return { 'street': !exists(json, 'street') ? undefined : json['street'], 'city': !exists(json, 'city') ? undefined : json['city'], 'postCode': !exists(json, 'post_code') ? undefined : json['post_code'], }; } export function ViewCustomerCompanyAddressToJSON(value?: ViewCustomerCompanyAddress | null): any { if (value === undefined) { return undefined; } if (value === null) { return null; } return { 'street': value.street, 'city': value.city, 'post_code': value.postCode, }; } <file_sep>/* tslint:disable */ /* eslint-disable */ /** * Collins API * This site provides details on the various ways that you can integrate with Collins. Not sure you want to be here after all? Check out what’s new on the [London Bar Scene](https://www.designmynight.com/london/new-bar-spy) instead. * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { exists, mapValues } from '../runtime'; import { NewCustomerRequestCompanyAddress, NewCustomerRequestCompanyAddressFromJSON, NewCustomerRequestCompanyAddressFromJSONTyped, NewCustomerRequestCompanyAddressToJSON, } from './'; /** * * @export * @interface NewCustomerRequest */ export interface NewCustomerRequest { /** * The customer's email address * @type {string} * @memberof NewCustomerRequest */ email?: string; /** * The customer's first name * @type {string} * @memberof NewCustomerRequest */ firstName?: string; /** * The customer's last name * @type {string} * @memberof NewCustomerRequest */ lastName?: string; /** * The customer's phone number * @type {string} * @memberof NewCustomerRequest */ phone?: string; /** * The name of the customer's company * @type {string} * @memberof NewCustomerRequest */ company?: string; /** * * @type {NewCustomerRequestCompanyAddress} * @memberof NewCustomerRequest */ companyAddress?: NewCustomerRequestCompanyAddress; /** * The customer's date of birth in the YYYY-MM-DD format * @type {Date} * @memberof NewCustomerRequest */ dob?: Date; /** * The value given for the custom field * @type {object} * @memberof NewCustomerRequest */ customFieldValue?: object; /** * An array of venue IDs this customer should be associated with * @type {Array<string>} * @memberof NewCustomerRequest */ associatedVenues?: Array<string>; /** * An array of marketing preference IDs which the user should be opted in to. * @type {Array<string>} * @memberof NewCustomerRequest */ marketingPreferenceIds?: Array<string>; /** * An object of marketing preference IDs as the key, and whether or not the user should be opted in or out of as the value. * @type {object} * @memberof NewCustomerRequest */ marketingPreferences?: object; /** * An array of labels which should be set on the customer * @type {Array<string>} * @memberof NewCustomerRequest */ labels?: Array<string>; /** * Any additional notes to make about the customer * @type {string} * @memberof NewCustomerRequest */ notes?: string; } export function NewCustomerRequestFromJSON(json: any): NewCustomerRequest { return NewCustomerRequestFromJSONTyped(json, false); } export function NewCustomerRequestFromJSONTyped(json: any, ignoreDiscriminator: boolean): NewCustomerRequest { if ((json === undefined) || (json === null)) { return json; } return { 'email': !exists(json, 'email') ? undefined : json['email'], 'firstName': !exists(json, 'first_name') ? undefined : json['first_name'], 'lastName': !exists(json, 'last_name') ? undefined : json['last_name'], 'phone': !exists(json, 'phone') ? undefined : json['phone'], 'company': !exists(json, 'company') ? undefined : json['company'], 'companyAddress': !exists(json, 'company_address') ? undefined : NewCustomerRequestCompanyAddressFromJSON(json['company_address']), 'dob': !exists(json, 'dob') ? undefined : (new Date(json['dob'])), 'customFieldValue': !exists(json, 'custom_field_value') ? undefined : json['custom_field_value'], 'associatedVenues': !exists(json, 'associated_venues') ? undefined : json['associated_venues'], 'marketingPreferenceIds': !exists(json, 'marketing_preference_ids') ? undefined : json['marketing_preference_ids'], 'marketingPreferences': !exists(json, 'marketing_preferences') ? undefined : json['marketing_preferences'], 'labels': !exists(json, 'labels') ? undefined : json['labels'], 'notes': !exists(json, 'notes') ? undefined : json['notes'], }; } export function NewCustomerRequestToJSON(value?: NewCustomerRequest | null): any { if (value === undefined) { return undefined; } if (value === null) { return null; } return { 'email': value.email, 'first_name': value.firstName, 'last_name': value.lastName, 'phone': value.phone, 'company': value.company, 'company_address': NewCustomerRequestCompanyAddressToJSON(value.companyAddress), 'dob': value.dob === undefined ? undefined : (value.dob.toISOString().substr(0,10)), 'custom_field_value': value.customFieldValue, 'associated_venues': value.associatedVenues, 'marketing_preference_ids': value.marketingPreferenceIds, 'marketing_preferences': value.marketingPreferences, 'labels': value.labels, 'notes': value.notes, }; } <file_sep><p align="center"> <img width="200px" src="https://static.designmynight.com/uploads/2017/01/DesignMyNight-Logo.png"> </p> # Collins API Documentation This repository contains the documentation for the Collins API. ## Viewing the docs You can find the docs using the following URL: https://docs.collinsbookings.com ## Developing locally To make local changes to the documentation, first clone the repository. ```shell $ git clone https://github.com/designmynight/collins-api-docs $ cd collins-api-docs ``` You can use Docker to host a local development environment of the documentation. ```shell $ docker-compose up ``` The documentation will be served on localhost at port 8080 - http://localhost:8080 ## Publishing ### Publishing the docs The latest docs are generated on a push to master ### Publishing the SDK On commit to master SDK is automatically published to NPM: https://www.npmjs.com/package/collins-js-sdk. you must increment the version in package.json otherwise the package will not be replaced. <file_sep>/* tslint:disable */ /* eslint-disable */ /** * Collins API * This site provides details on the various ways that you can integrate with Collins. Not sure you want to be here after all? Check out what’s new on the [London Bar Scene](https://www.designmynight.com/london/new-bar-spy) instead. * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { exists, mapValues } from '../runtime'; /** * * @export * @interface ViewCustomerMarketingPreferences */ export interface ViewCustomerMarketingPreferences { /** * The ID of the marketing preference * @type {string} * @memberof ViewCustomerMarketingPreferences */ id?: string; /** * The date the customer last opted into this preference * @type {Date} * @memberof ViewCustomerMarketingPreferences */ optInDate?: Date; /** * The date the customer last opted out of this preference * @type {Date} * @memberof ViewCustomerMarketingPreferences */ optOutDate?: Date; /** * Whether or not the customer is currently opted into this preference * @type {boolean} * @memberof ViewCustomerMarketingPreferences */ optedIn?: boolean; } export function ViewCustomerMarketingPreferencesFromJSON(json: any): ViewCustomerMarketingPreferences { return ViewCustomerMarketingPreferencesFromJSONTyped(json, false); } export function ViewCustomerMarketingPreferencesFromJSONTyped(json: any, ignoreDiscriminator: boolean): ViewCustomerMarketingPreferences { if ((json === undefined) || (json === null)) { return json; } return { 'id': !exists(json, 'id') ? undefined : json['id'], 'optInDate': !exists(json, 'opt_in_date') ? undefined : (new Date(json['opt_in_date'])), 'optOutDate': !exists(json, 'opt_out_date') ? undefined : (new Date(json['opt_out_date'])), 'optedIn': !exists(json, 'opted_in') ? undefined : json['opted_in'], }; } export function ViewCustomerMarketingPreferencesToJSON(value?: ViewCustomerMarketingPreferences | null): any { if (value === undefined) { return undefined; } if (value === null) { return null; } return { 'id': value.id, 'opt_in_date': value.optInDate === undefined ? undefined : (value.optInDate.toISOString()), 'opt_out_date': value.optOutDate === undefined ? undefined : (value.optOutDate.toISOString()), 'opted_in': value.optedIn, }; } <file_sep>export * from './BookingsApi'; export * from './CustomersApi'; export * from './VenueGroupsApi'; export * from './VenuesApi'; <file_sep>/* tslint:disable */ /* eslint-disable */ /** * Collins API * This site provides details on the various ways that you can integrate with Collins. Not sure you want to be here after all? Check out what’s new on the [London Bar Scene](https://www.designmynight.com/london/new-bar-spy) instead. * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { exists, mapValues } from '../runtime'; import { MoneyResponse, MoneyResponseFromJSON, MoneyResponseFromJSONTyped, MoneyResponseToJSON, } from './'; /** * * @export * @interface ViewRefund */ export interface ViewRefund { /** * The ID of the refund. * @type {string} * @memberof ViewRefund */ id?: string; /** * * @type {MoneyResponse} * @memberof ViewRefund */ amount?: MoneyResponse; /** * Any notes that are attached to this refund. * @type {string} * @memberof ViewRefund */ notes?: string | null; /** * The date when the deposit was created. * @type {Date} * @memberof ViewRefund */ createdDate?: Date; } export function ViewRefundFromJSON(json: any): ViewRefund { return ViewRefundFromJSONTyped(json, false); } export function ViewRefundFromJSONTyped(json: any, ignoreDiscriminator: boolean): ViewRefund { if ((json === undefined) || (json === null)) { return json; } return { 'id': !exists(json, 'id') ? undefined : json['id'], 'amount': !exists(json, 'amount') ? undefined : MoneyResponseFromJSON(json['amount']), 'notes': !exists(json, 'notes') ? undefined : json['notes'], 'createdDate': !exists(json, 'created_date') ? undefined : (new Date(json['created_date'])), }; } export function ViewRefundToJSON(value?: ViewRefund | null): any { if (value === undefined) { return undefined; } if (value === null) { return null; } return { 'id': value.id, 'amount': MoneyResponseToJSON(value.amount), 'notes': value.notes, 'created_date': value.createdDate === undefined ? undefined : (value.createdDate.toISOString()), }; } <file_sep>export * from './BookingAssignedAreasResponse'; export * from './BookingLinksResponse'; export * from './BookingListResponse'; export * from './CustomerListResponse'; export * from './CustomerResponse'; export * from './InlineObject'; export * from './InlineObject1'; export * from './InlineObject2'; export * from './InlineResponse401'; export * from './InlineResponse404'; export * from './InlineResponse429'; export * from './MoneyResponse'; export * from './NewCustomerRequest'; export * from './NewCustomerRequestCompanyAddress'; export * from './NotificationResponse'; export * from './NotificationsListResponse'; export * from './PreferenceResponse'; export * from './VenueListResponse'; export * from './VenueResponse'; export * from './ViewAssignedArea'; export * from './ViewBooking'; export * from './ViewBookingAssignedAreas'; export * from './ViewBookingCompanyAddress'; export * from './ViewBookingType'; export * from './ViewCustomer'; export * from './ViewCustomerBookings'; export * from './ViewCustomerCompanyAddress'; export * from './ViewCustomerMarketingPreferences'; export * from './ViewDeposit'; export * from './ViewNotification'; export * from './ViewRefund'; export * from './ViewVenue'; export * from './ViewVenueAddress'; <file_sep>/* tslint:disable */ /* eslint-disable */ /** * Collins API * This site provides details on the various ways that you can integrate with Collins. Not sure you want to be here after all? Check out what’s new on the [London Bar Scene](https://www.designmynight.com/london/new-bar-spy) instead. * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { exists, mapValues } from '../runtime'; /** * * @export * @interface InlineObject1 */ export interface InlineObject1 { /** * Array of bookable area IDs * @type {Array<string>} * @memberof InlineObject1 */ areas?: Array<string>; } export function InlineObject1FromJSON(json: any): InlineObject1 { return InlineObject1FromJSONTyped(json, false); } export function InlineObject1FromJSONTyped(json: any, ignoreDiscriminator: boolean): InlineObject1 { if ((json === undefined) || (json === null)) { return json; } return { 'areas': !exists(json, 'areas') ? undefined : json['areas'], }; } export function InlineObject1ToJSON(value?: InlineObject1 | null): any { if (value === undefined) { return undefined; } if (value === null) { return null; } return { 'areas': value.areas, }; } <file_sep>You must provide your bearer token with every request that you make to the API. To do this, set an HTTP `Authorization` header on your request that consists of the prefix `Bearer` and the token. To obtain a bearer token, please speak to your account manager. ```shell $ curl -H "Authorization: Bearer 1234567890" https://api.collinsbookings.com/api/customers ```<file_sep>/* tslint:disable */ /* eslint-disable */ /** * Collins API * This site provides details on the various ways that you can integrate with Collins. Not sure you want to be here after all? Check out what’s new on the [London Bar Scene](https://www.designmynight.com/london/new-bar-spy) instead. * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { exists, mapValues } from '../runtime'; import { ViewVenue, ViewVenueFromJSON, ViewVenueFromJSONTyped, ViewVenueToJSON, } from './'; /** * * @export * @interface VenueResponse */ export interface VenueResponse { /** * * @type {ViewVenue} * @memberof VenueResponse */ venue?: ViewVenue; } export function VenueResponseFromJSON(json: any): VenueResponse { return VenueResponseFromJSONTyped(json, false); } export function VenueResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): VenueResponse { if ((json === undefined) || (json === null)) { return json; } return { 'venue': !exists(json, 'venue') ? undefined : ViewVenueFromJSON(json['venue']), }; } export function VenueResponseToJSON(value?: VenueResponse | null): any { if (value === undefined) { return undefined; } if (value === null) { return null; } return { 'venue': ViewVenueToJSON(value.venue), }; } <file_sep>Data may be sent to the server either through parameters appended to the URL, or as a JSON object included in the request body. Where JSON is used, you should also include a header specifying the content type as `application/json`. ```shell $ curl -X PUT -H "Content-Type: application/json" -d '{\"first_name\": \"Dan\"}' https://api.collinsbookings.com/api/customers/12345 ```<file_sep>/* tslint:disable */ /* eslint-disable */ /** * Collins API * This site provides details on the various ways that you can integrate with Collins. Not sure you want to be here after all? Check out what’s new on the [London Bar Scene](https://www.designmynight.com/london/new-bar-spy) instead. * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { exists, mapValues } from '../runtime'; import { ViewCustomer, ViewCustomerFromJSON, ViewCustomerFromJSONTyped, ViewCustomerToJSON, } from './'; /** * * @export * @interface CustomerResponse */ export interface CustomerResponse { /** * * @type {ViewCustomer} * @memberof CustomerResponse */ customer?: ViewCustomer; } export function CustomerResponseFromJSON(json: any): CustomerResponse { return CustomerResponseFromJSONTyped(json, false); } export function CustomerResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): CustomerResponse { if ((json === undefined) || (json === null)) { return json; } return { 'customer': !exists(json, 'customer') ? undefined : ViewCustomerFromJSON(json['customer']), }; } export function CustomerResponseToJSON(value?: CustomerResponse | null): any { if (value === undefined) { return undefined; } if (value === null) { return null; } return { 'customer': ViewCustomerToJSON(value.customer), }; } <file_sep>/* tslint:disable */ /* eslint-disable */ /** * Collins API * This site provides details on the various ways that you can integrate with Collins. Not sure you want to be here after all? Check out what’s new on the [London Bar Scene](https://www.designmynight.com/london/new-bar-spy) instead. * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import * as runtime from '../runtime'; import { InlineResponse401, InlineResponse401FromJSON, InlineResponse401ToJSON, InlineResponse404, InlineResponse404FromJSON, InlineResponse404ToJSON, InlineResponse429, InlineResponse429FromJSON, InlineResponse429ToJSON, PreferenceResponse, PreferenceResponseFromJSON, PreferenceResponseToJSON, VenueListResponse, VenueListResponseFromJSON, VenueListResponseToJSON, VenueResponse, VenueResponseFromJSON, VenueResponseToJSON, } from '../models'; export interface GetAllVenuesRequest { status?: GetAllVenuesStatusEnum; title?: string; limit?: number; sort?: Array<string>; page?: string; } export interface GetVenueRequest { venueId: string; } export interface GetVenueMarketingPreferencesRequest { venueId: string; } /** * */ export class VenuesApi extends runtime.BaseAPI { /** * Returns an array of all venues which the authenticated user is authorised to view. The response will be [paginated](/#tag/Pagination). * Get venues */ async getAllVenuesRaw(requestParameters: GetAllVenuesRequest): Promise<runtime.ApiResponse<VenueListResponse>> { const queryParameters: any = {}; if (requestParameters.status !== undefined) { queryParameters['status'] = requestParameters.status; } if (requestParameters.title !== undefined) { queryParameters['title'] = requestParameters.title; } if (requestParameters.limit !== undefined) { queryParameters['limit'] = requestParameters.limit; } if (requestParameters.sort) { queryParameters['sort'] = requestParameters.sort.join(runtime.COLLECTION_FORMATS["csv"]); } if (requestParameters.page !== undefined) { queryParameters['page'] = requestParameters.page; } const headerParameters: runtime.HTTPHeaders = {}; if (this.configuration && this.configuration.accessToken) { const token = this.configuration.accessToken; const tokenString = typeof token === 'function' ? token("BearerAuth", []) : token; if (tokenString) { headerParameters["Authorization"] = `Bearer ${tokenString}`; } } const response = await this.request({ path: `/venues`, method: 'GET', headers: headerParameters, query: queryParameters, }); return new runtime.JSONApiResponse(response, (jsonValue) => VenueListResponseFromJSON(jsonValue)); } /** * Returns an array of all venues which the authenticated user is authorised to view. The response will be [paginated](/#tag/Pagination). * Get venues */ async getAllVenues(requestParameters: GetAllVenuesRequest): Promise<VenueListResponse> { const response = await this.getAllVenuesRaw(requestParameters); return await response.value(); } /** * Returns details about a specific venue * Get a venue */ async getVenueRaw(requestParameters: GetVenueRequest): Promise<runtime.ApiResponse<VenueResponse>> { if (requestParameters.venueId === null || requestParameters.venueId === undefined) { throw new runtime.RequiredError('venueId','Required parameter requestParameters.venueId was null or undefined when calling getVenue.'); } const queryParameters: any = {}; const headerParameters: runtime.HTTPHeaders = {}; if (this.configuration && this.configuration.accessToken) { const token = this.configuration.accessToken; const tokenString = typeof token === 'function' ? token("BearerAuth", []) : token; if (tokenString) { headerParameters["Authorization"] = `Bearer ${tokenString}`; } } const response = await this.request({ path: `/venues/{venueId}`.replace(`{${"venueId"}}`, encodeURIComponent(String(requestParameters.venueId))), method: 'GET', headers: headerParameters, query: queryParameters, }); return new runtime.JSONApiResponse(response, (jsonValue) => VenueResponseFromJSON(jsonValue)); } /** * Returns details about a specific venue * Get a venue */ async getVenue(requestParameters: GetVenueRequest): Promise<VenueResponse> { const response = await this.getVenueRaw(requestParameters); return await response.value(); } /** * Returns an array of active marketing preferences for the given venue. An active marketing preference is one which has been set up on the venue group level and activated on the individual venue. * Get active marketing preferences */ async getVenueMarketingPreferencesRaw(requestParameters: GetVenueMarketingPreferencesRequest): Promise<runtime.ApiResponse<Array<PreferenceResponse>>> { if (requestParameters.venueId === null || requestParameters.venueId === undefined) { throw new runtime.RequiredError('venueId','Required parameter requestParameters.venueId was null or undefined when calling getVenueMarketingPreferences.'); } const queryParameters: any = {}; const headerParameters: runtime.HTTPHeaders = {}; if (this.configuration && this.configuration.accessToken) { const token = this.configuration.accessToken; const tokenString = typeof token === 'function' ? token("BearerAuth", []) : token; if (tokenString) { headerParameters["Authorization"] = `Bearer ${tokenString}`; } } const response = await this.request({ path: `/venues/{venueId}/marketing-preferences`.replace(`{${"venueId"}}`, encodeURIComponent(String(requestParameters.venueId))), method: 'GET', headers: headerParameters, query: queryParameters, }); return new runtime.JSONApiResponse(response, (jsonValue) => jsonValue.map(PreferenceResponseFromJSON)); } /** * Returns an array of active marketing preferences for the given venue. An active marketing preference is one which has been set up on the venue group level and activated on the individual venue. * Get active marketing preferences */ async getVenueMarketingPreferences(requestParameters: GetVenueMarketingPreferencesRequest): Promise<Array<PreferenceResponse>> { const response = await this.getVenueMarketingPreferencesRaw(requestParameters); return await response.value(); } } /** * @export * @enum {string} */ export enum GetAllVenuesStatusEnum { Public = 'public', Private = 'private', Inactive = 'inactive' } <file_sep>/* tslint:disable */ /* eslint-disable */ /** * Collins API * This site provides details on the various ways that you can integrate with Collins. Not sure you want to be here after all? Check out what’s new on the [London Bar Scene](https://www.designmynight.com/london/new-bar-spy) instead. * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { exists, mapValues } from '../runtime'; import { ViewCustomerBookings, ViewCustomerBookingsFromJSON, ViewCustomerBookingsFromJSONTyped, ViewCustomerBookingsToJSON, ViewCustomerCompanyAddress, ViewCustomerCompanyAddressFromJSON, ViewCustomerCompanyAddressFromJSONTyped, ViewCustomerCompanyAddressToJSON, ViewCustomerMarketingPreferences, ViewCustomerMarketingPreferencesFromJSON, ViewCustomerMarketingPreferencesFromJSONTyped, ViewCustomerMarketingPreferencesToJSON, } from './'; /** * * @export * @interface ViewCustomer */ export interface ViewCustomer { /** * The customer's ID * @type {string} * @memberof ViewCustomer */ id?: string; /** * The customer's email address * @type {string} * @memberof ViewCustomer */ email?: string; /** * The customer's first name * @type {string} * @memberof ViewCustomer */ firstName?: string; /** * The customer's last name * @type {string} * @memberof ViewCustomer */ lastName?: string; /** * The customer's phone number * @type {string} * @memberof ViewCustomer */ phone?: string; /** * The name of the customer's company * @type {string} * @memberof ViewCustomer */ company?: string; /** * * @type {ViewCustomerCompanyAddress} * @memberof ViewCustomer */ companyAddress?: ViewCustomerCompanyAddress; /** * The customer's date of birth * @type {string} * @memberof ViewCustomer */ dob?: string; /** * The value given for the custom field * @type {string} * @memberof ViewCustomer */ customFieldValue?: string; /** * An array of associated venue IDs * @type {Array<string>} * @memberof ViewCustomer */ associatedVenues?: Array<string>; /** * An array of marketing preferences this user has given or revoked consent to * @type {Array<ViewCustomerMarketingPreferences>} * @memberof ViewCustomer */ marketingPreferences?: Array<ViewCustomerMarketingPreferences>; /** * An array of bookings this customer has made * @type {Array<ViewCustomerBookings>} * @memberof ViewCustomer */ bookings?: Array<ViewCustomerBookings>; /** * An array of labels that have been applied to the customer * @type {Array<string>} * @memberof ViewCustomer */ labels?: Array<string>; /** * Any notes that have been applied to the customer * @type {string} * @memberof ViewCustomer */ notes?: string; /** * The date and time the customer was created. * * <small>Prior to February 2019, we did not keep * a record of the created date, except for some situations such as data imports. If we don't have * the created date for a customer, `null` will be returned instead.</small> * @type {Date} * @memberof ViewCustomer */ createdDate?: Date | null; /** * The date and time the customer was last updated * @type {Date} * @memberof ViewCustomer */ lastUpdated?: Date; } export function ViewCustomerFromJSON(json: any): ViewCustomer { return ViewCustomerFromJSONTyped(json, false); } export function ViewCustomerFromJSONTyped(json: any, ignoreDiscriminator: boolean): ViewCustomer { if ((json === undefined) || (json === null)) { return json; } return { 'id': !exists(json, 'id') ? undefined : json['id'], 'email': !exists(json, 'email') ? undefined : json['email'], 'firstName': !exists(json, 'first_name') ? undefined : json['first_name'], 'lastName': !exists(json, 'last_name') ? undefined : json['last_name'], 'phone': !exists(json, 'phone') ? undefined : json['phone'], 'company': !exists(json, 'company') ? undefined : json['company'], 'companyAddress': !exists(json, 'company_address') ? undefined : ViewCustomerCompanyAddressFromJSON(json['company_address']), 'dob': !exists(json, 'dob') ? undefined : json['dob'], 'customFieldValue': !exists(json, 'custom_field_value') ? undefined : json['custom_field_value'], 'associatedVenues': !exists(json, 'associated_venues') ? undefined : json['associated_venues'], 'marketingPreferences': !exists(json, 'marketing_preferences') ? undefined : ((json['marketing_preferences'] as Array<any>).map(ViewCustomerMarketingPreferencesFromJSON)), 'bookings': !exists(json, 'bookings') ? undefined : ((json['bookings'] as Array<any>).map(ViewCustomerBookingsFromJSON)), 'labels': !exists(json, 'labels') ? undefined : json['labels'], 'notes': !exists(json, 'notes') ? undefined : json['notes'], 'createdDate': !exists(json, 'created_date') ? undefined : (json['created_date'] === null ? null : new Date(json['created_date'])), 'lastUpdated': !exists(json, 'last_updated') ? undefined : (new Date(json['last_updated'])), }; } export function ViewCustomerToJSON(value?: ViewCustomer | null): any { if (value === undefined) { return undefined; } if (value === null) { return null; } return { 'id': value.id, 'email': value.email, 'first_name': value.firstName, 'last_name': value.lastName, 'phone': value.phone, 'company': value.company, 'company_address': ViewCustomerCompanyAddressToJSON(value.companyAddress), 'dob': value.dob, 'custom_field_value': value.customFieldValue, 'associated_venues': value.associatedVenues, 'marketing_preferences': value.marketingPreferences === undefined ? undefined : ((value.marketingPreferences as Array<any>).map(ViewCustomerMarketingPreferencesToJSON)), 'bookings': value.bookings === undefined ? undefined : ((value.bookings as Array<any>).map(ViewCustomerBookingsToJSON)), 'labels': value.labels, 'notes': value.notes, 'created_date': value.createdDate === undefined ? undefined : (value.createdDate === null ? null : value.createdDate.toISOString()), 'last_updated': value.lastUpdated === undefined ? undefined : (value.lastUpdated.toISOString()), }; } <file_sep>/* tslint:disable */ /* eslint-disable */ /** * Collins API * This site provides details on the various ways that you can integrate with Collins. Not sure you want to be here after all? Check out what’s new on the [London Bar Scene](https://www.designmynight.com/london/new-bar-spy) instead. * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { exists, mapValues } from '../runtime'; import { ViewBookingAssignedAreas, ViewBookingAssignedAreasFromJSON, ViewBookingAssignedAreasFromJSONTyped, ViewBookingAssignedAreasToJSON, ViewBookingCompanyAddress, ViewBookingCompanyAddressFromJSON, ViewBookingCompanyAddressFromJSONTyped, ViewBookingCompanyAddressToJSON, ViewBookingType, ViewBookingTypeFromJSON, ViewBookingTypeFromJSONTyped, ViewBookingTypeToJSON, ViewDeposit, ViewDepositFromJSON, ViewDepositFromJSONTyped, ViewDepositToJSON, ViewRefund, ViewRefundFromJSON, ViewRefundFromJSONTyped, ViewRefundToJSON, } from './'; /** * * @export * @interface ViewBooking */ export interface ViewBooking { /** * The ID of the booking. * @type {string} * @memberof ViewBooking */ id?: string; /** * The user ID which the booking is assigned to. * @type {string} * @memberof ViewBooking */ assignedTo?: string | null; /** * The user ID which the booking was created by. * @type {string} * @memberof ViewBooking */ createdBy?: string | null; /** * The status of the booking * @type {string} * @memberof ViewBooking */ status?: ViewBookingStatusEnum; /** * The date and time the status was last changed. * @type {Date} * @memberof ViewBooking */ statusChangedDate?: Date | null; /** * The date and time the follow up email should be sent. * @type {Date} * @memberof ViewBooking */ followUp?: Date | null; /** * The booking reference ID. * @type {number} * @memberof ViewBooking */ reference?: number | null; /** * The venue ID which the booking is associated with. * @type {string} * @memberof ViewBooking */ venueId?: string | null; /** * The venue group ID which the booking is associated with. * @type {string} * @memberof ViewBooking */ venueGroup?: string; /** * An array of areas the booking is assigned to. * @type {Array<ViewBookingAssignedAreas>} * @memberof ViewBooking */ assignedAreas?: Array<ViewBookingAssignedAreas>; /** * Whether the assigned areas have been locked. * @type {boolean} * @memberof ViewBooking */ assignedAreaLocked?: boolean; /** * The user ID of the user who locked the assigned areas. * @type {string} * @memberof ViewBooking */ assignedAreaLockedBy?: string | null; /** * The number of people the booking is for. * @type {number} * @memberof ViewBooking */ numPeople?: number | null; /** * The date the booking takes place. * @type {Date} * @memberof ViewBooking */ date?: Date | null; /** * The time the booking starts in a 24 hour format. * @type {string} * @memberof ViewBooking */ time?: string | null; /** * The duration of the booking in minutes. * @type {number} * @memberof ViewBooking */ duration?: number | null; /** * * @type {ViewBookingType} * @memberof ViewBooking */ type?: ViewBookingType | null; /** * The total value of this booking. * @type {number} * @memberof ViewBooking */ value?: number | null; /** * The customer ID associated with the booking * @type {string} * @memberof ViewBooking */ customerId?: string | null; /** * The first name for the booking. * @type {string} * @memberof ViewBooking */ firstName?: string | null; /** * The last name for the booking. * @type {string} * @memberof ViewBooking */ lastName?: string | null; /** * The email address for the booking. * @type {string} * @memberof ViewBooking */ email?: string | null; /** * An array of additional email addresses for the booking. * @type {Array<string>} * @memberof ViewBooking */ additionalEmails?: Array<string>; /** * The phone number for the booking. * @type {string} * @memberof ViewBooking */ phone?: string | null; /** * An alternative phone number for the booking. * @type {string} * @memberof ViewBooking */ alternativePhone?: string | null; /** * The name of the company for the booking. * @type {string} * @memberof ViewBooking */ company?: string | null; /** * * @type {ViewBookingCompanyAddress} * @memberof ViewBooking */ companyAddress?: ViewBookingCompanyAddress; /** * An array of any deposits or payments made or requested against this booking. * @type {Array<ViewDeposit>} * @memberof ViewBooking */ deposits?: Array<ViewDeposit>; /** * An array of any refunds made against this booking. * @type {Array<ViewRefund>} * @memberof ViewBooking */ refunds?: Array<ViewRefund>; /** * Whether the booking has been lost * @type {boolean} * @memberof ViewBooking */ lost?: boolean; /** * The number of guests who arrived at the booking. For no-shows, this will be `0`. * @type {number} * @memberof ViewBooking */ actualGuests?: number | null; /** * The current stage of the booking. * @type {string} * @memberof ViewBooking */ currentStage?: string | null; /** * An array of labels attached to the booking. * @type {Array<string>} * @memberof ViewBooking */ labels?: Array<string>; /** * Whether the booking was a walk-in. * @type {boolean} * @memberof ViewBooking */ walkIn?: boolean; /** * Whether the booking was auto-confirmed. * @type {boolean} * @memberof ViewBooking */ autoConfirmed?: boolean; /** * The partner defined source where this booking came from. * @type {string} * @memberof ViewBooking */ partnerSource?: string | null; /** * The date and time the booking was created. * @type {Date} * @memberof ViewBooking */ createdDate?: Date; /** * The date and time the booking was last updated. * @type {Date} * @memberof ViewBooking */ lastUpdated?: Date; } /** * @export * @enum {string} */ export enum ViewBookingStatusEnum { New = 'new', InProgress = 'in_progress', Complete = 'complete', Rejected = 'rejected', Deleted = 'deleted', Lost = 'lost' } export function ViewBookingFromJSON(json: any): ViewBooking { return ViewBookingFromJSONTyped(json, false); } export function ViewBookingFromJSONTyped(json: any, ignoreDiscriminator: boolean): ViewBooking { if ((json === undefined) || (json === null)) { return json; } return { 'id': !exists(json, 'id') ? undefined : json['id'], 'assignedTo': !exists(json, 'assigned_to') ? undefined : json['assigned_to'], 'createdBy': !exists(json, 'created_by') ? undefined : json['created_by'], 'status': !exists(json, 'status') ? undefined : json['status'], 'statusChangedDate': !exists(json, 'status_changed_date') ? undefined : (json['status_changed_date'] === null ? null : new Date(json['status_changed_date'])), 'followUp': !exists(json, 'follow_up') ? undefined : (json['follow_up'] === null ? null : new Date(json['follow_up'])), 'reference': !exists(json, 'reference') ? undefined : json['reference'], 'venueId': !exists(json, 'venue_id') ? undefined : json['venue_id'], 'venueGroup': !exists(json, 'venue_group') ? undefined : json['venue_group'], 'assignedAreas': !exists(json, 'assigned_areas') ? undefined : ((json['assigned_areas'] as Array<any>).map(ViewBookingAssignedAreasFromJSON)), 'assignedAreaLocked': !exists(json, 'assigned_area_locked') ? undefined : json['assigned_area_locked'], 'assignedAreaLockedBy': !exists(json, 'assigned_area_locked_by') ? undefined : json['assigned_area_locked_by'], 'numPeople': !exists(json, 'num_people') ? undefined : json['num_people'], 'date': !exists(json, 'date') ? undefined : (json['date'] === null ? null : new Date(json['date'])), 'time': !exists(json, 'time') ? undefined : json['time'], 'duration': !exists(json, 'duration') ? undefined : json['duration'], 'type': !exists(json, 'type') ? undefined : ViewBookingTypeFromJSON(json['type']), 'value': !exists(json, 'value') ? undefined : json['value'], 'customerId': !exists(json, 'customer_id') ? undefined : json['customer_id'], 'firstName': !exists(json, 'first_name') ? undefined : json['first_name'], 'lastName': !exists(json, 'last_name') ? undefined : json['last_name'], 'email': !exists(json, 'email') ? undefined : json['email'], 'additionalEmails': !exists(json, 'additional_emails') ? undefined : json['additional_emails'], 'phone': !exists(json, 'phone') ? undefined : json['phone'], 'alternativePhone': !exists(json, 'alternative_phone') ? undefined : json['alternative_phone'], 'company': !exists(json, 'company') ? undefined : json['company'], 'companyAddress': !exists(json, 'company_address') ? undefined : ViewBookingCompanyAddressFromJSON(json['company_address']), 'deposits': !exists(json, 'deposits') ? undefined : ((json['deposits'] as Array<any>).map(ViewDepositFromJSON)), 'refunds': !exists(json, 'refunds') ? undefined : ((json['refunds'] as Array<any>).map(ViewRefundFromJSON)), 'lost': !exists(json, 'lost') ? undefined : json['lost'], 'actualGuests': !exists(json, 'actual_guests') ? undefined : json['actual_guests'], 'currentStage': !exists(json, 'current_stage') ? undefined : json['current_stage'], 'labels': !exists(json, 'labels') ? undefined : json['labels'], 'walkIn': !exists(json, 'walk_in') ? undefined : json['walk_in'], 'autoConfirmed': !exists(json, 'auto_confirmed') ? undefined : json['auto_confirmed'], 'partnerSource': !exists(json, 'partner_source') ? undefined : json['partner_source'], 'createdDate': !exists(json, 'created_date') ? undefined : (new Date(json['created_date'])), 'lastUpdated': !exists(json, 'last_updated') ? undefined : (new Date(json['last_updated'])), }; } export function ViewBookingToJSON(value?: ViewBooking | null): any { if (value === undefined) { return undefined; } if (value === null) { return null; } return { 'id': value.id, 'assigned_to': value.assignedTo, 'created_by': value.createdBy, 'status': value.status, 'status_changed_date': value.statusChangedDate === undefined ? undefined : (value.statusChangedDate === null ? null : value.statusChangedDate.toISOString()), 'follow_up': value.followUp === undefined ? undefined : (value.followUp === null ? null : value.followUp.toISOString()), 'reference': value.reference, 'venue_id': value.venueId, 'venue_group': value.venueGroup, 'assigned_areas': value.assignedAreas === undefined ? undefined : ((value.assignedAreas as Array<any>).map(ViewBookingAssignedAreasToJSON)), 'assigned_area_locked': value.assignedAreaLocked, 'assigned_area_locked_by': value.assignedAreaLockedBy, 'num_people': value.numPeople, 'date': value.date === undefined ? undefined : (value.date === null ? null : value.date.toISOString().substr(0,10)), 'time': value.time, 'duration': value.duration, 'type': ViewBookingTypeToJSON(value.type), 'value': value.value, 'customer_id': value.customerId, 'first_name': value.firstName, 'last_name': value.lastName, 'email': value.email, 'additional_emails': value.additionalEmails, 'phone': value.phone, 'alternative_phone': value.alternativePhone, 'company': value.company, 'company_address': ViewBookingCompanyAddressToJSON(value.companyAddress), 'deposits': value.deposits === undefined ? undefined : ((value.deposits as Array<any>).map(ViewDepositToJSON)), 'refunds': value.refunds === undefined ? undefined : ((value.refunds as Array<any>).map(ViewRefundToJSON)), 'lost': value.lost, 'actual_guests': value.actualGuests, 'current_stage': value.currentStage, 'labels': value.labels, 'walk_in': value.walkIn, 'auto_confirmed': value.autoConfirmed, 'partner_source': value.partnerSource, 'created_date': value.createdDate === undefined ? undefined : (value.createdDate.toISOString()), 'last_updated': value.lastUpdated === undefined ? undefined : (value.lastUpdated.toISOString()), }; } <file_sep>All requests to the API are rate limited based on your credentials. You should check the headers for the current status of any rate limits: Header Name | Description --- | --- `X-RateLimit-Limit` | The maximum number of requests that the consumer is permitted to make per hour `X-RateLimit-Remaining` | The number of requests remaining in the current rate limit window `X-RateLimit-Reset` | The time at which the current rate limit window resets, in ISO 8601 format If you go over the rate limit, you will receive an error response with the status code `429`.
6139e4f1bc16c37cb8e09ee197d4c396288fca6a
[ "Markdown", "TypeScript", "Dockerfile" ]
39
Markdown
designmynight/collins-api-docs
e71608fffb2f41ee4d621106c7892982a8d7a2dd
21bf5ac0f6ee783ac7bb63c4c2150dac0115879a
refs/heads/master
<repo_name>tjgykhulj/Compiler-llvm<file_sep>/src/main/java/AST/ASTLogicalOrExpression.java package AST; /* Generated By:JJTree: Do not edit this line. ASTLogicalOrExpression.java Version 4.3 */ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=false,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ public class ASTLogicalOrExpression extends SimpleNode { public String op; public SimpleNode Lexp, Rexp; public ASTLogicalOrExpression(int id) { super(id); } public ASTLogicalOrExpression(MyLang p, int id) { super(p, id); } public ASTContent code_gen(ASTContext context) throws Exception{ // op = jjtGetValue().toString(); Lexp = (SimpleNode)children[0]; Rexp = (SimpleNode)children[1]; ASTContent L = Lexp.code_gen(context).getPValue(); ASTContent R = Rexp.code_gen(context).getPValue(); if(!(L.isBoolean() && R.isBoolean())) throw new Exception("LogicalOr Not boolean."); if(true){ cnt++; return new ASTContent(MyLang.builder.buildOr(L.value, R.value, String.valueOf(cnt)), BOOLEAN_LITERAL); } throw new Exception("LogicalOr unknown error."); } } /* JavaCC - OriginalChecksum=b9a478357c08944077f36c00b6d48663 (do not edit this line) */ <file_sep>/src/main/java/AST/ASTclass_declaration.java package AST; /* Generated By:JJTree: Do not edit this line. ASTclass_declaration.java Version 4.3 */ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=false,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ public class ASTclass_declaration extends SimpleNode { SimpleNode block; public ASTclass_declaration(int id) { super(id); } public ASTclass_declaration(MyLang p, int id) { super(p, id); } public ASTContent code_gen(ASTContext Context) throws Exception{ String className = ((SimpleNode) children[0]).jjtGetValue().toString(); SimpleNode field = this; Context.put(className, field); return null; } } /* JavaCC - OriginalChecksum=fc2e6f67d96484ae1f1440cedb3fc3a0 (do not edit this line) */ <file_sep>/README.md # Compiler-llvm Environment: llvm-3.6\java\ubuntu <file_sep>/src/main/java/AST/ASTFloat.java package AST; import org.llvm.*; /* Generated By:JJTree: Do not edit this line. ASTFloat.java Version 4.3 */ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=false,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ public class ASTFloat extends SimpleNode { public ASTFloat(int id) { super(id); } public ASTFloat(MyLang p, int id) { super(p, id); } public String toString(){ return "Float : "+ Double.valueOf(jjtGetValue().toString()); } public ASTContent code_gen(ASTContext context){ double x = Double.valueOf(jjtGetValue().toString()); return new ASTContent(TypeRef.doubleType().constReal(x), FLOAT_LITERAL); } } /* JavaCC - OriginalChecksum=5cd5d5920ea97ebb407481087b54883d (do not edit this line) */<file_sep>/src/main/java/AST/MyLangTreeConstants.java package AST; /* Generated By:JavaCC: Do not edit this line. MyLangTreeConstants.java Version 5.0 */ public interface MyLangTreeConstants { public int JJTSTART = 0; public int JJTPROGRAM = 1; public int JJTBLOCK = 2; public int JJTVOID = 3; public int JJTIFTHENSTM = 4; public int JJTFOREACHSTM = 5; public int JJTCONTINUESTM = 6; public int JJTBREAKSTM = 7; public int JJTFORSTM = 8; public int JJTWHILESTM = 9; public int JJTRETURNSTM = 10; public int JJTCOMMONSTM = 11; public int JJTCLASS_DECLARATION = 12; public int JJTDECLARATION = 13; public int JJTFUNC_DECLARATION = 14; public int JJTVAR_DECLARATION = 15; public int JJTARRAY = 16; public int JJTTYPE = 17; public int JJTPRIMTYPE = 18; public int JJTARRAYCONSTRUCTOR = 19; public int JJTASSIGNMENT = 20; public int JJTLOGICALOREXPRESSION = 21; public int JJTLOGICALANDEXPRESSION = 22; public int JJTEQUALITYEXPRESSION = 23; public int JJTRELATIONALEXPRESSION = 24; public int JJTSHIFTEXPRESSION = 25; public int JJTOPT = 26; public int JJTCOMMONEXPRESSION = 27; public int JJTUNARYEXPRESSION = 28; public int JJTPRIMARYPREFIXACCESS = 29; public int JJTPRIMARYACCESS = 30; public int JJTIDENTIFIER = 31; public int JJTINTEGER = 32; public int JJTFLOAT = 33; public int JJTCHAR = 34; public int JJTBOOLEAN = 35; public int JJTNULL = 36; public int JJTSTRING = 37; public String[] jjtNodeName = { "start", "program", "block", "void", "ifthenstm", "foreachstm", "continuestm", "breakstm", "forstm", "whilestm", "returnstm", "commonstm", "class_declaration", "declaration", "func_declaration", "var_declaration", "array", "Type", "primtype", "ArrayConstructor", "Assignment", "LogicalOrExpression", "LogicalAndExpression", "EqualityExpression", "RelationalExpression", "ShiftExpression", "Opt", "CommonExpression", "UnaryExpression", "PrimaryPrefixAccess", "PrimaryAccess", "Identifier", "Integer", "Float", "Char", "Boolean", "Null", "String", }; } /* JavaCC - OriginalChecksum=55014d7575d28f253338a75c77124bbf (do not edit this line) */ <file_sep>/src/main/java/AST/MyLangTokenManager.java package AST; /* Generated By:JJTree&JavaCC: Do not edit this line. MyLangTokenManager.java */ /** Token Manager. */ public class MyLangTokenManager implements MyLangConstants { /** Debug output. */ public java.io.PrintStream debugStream = System.out; /** Set debug output. */ public void setDebugStream(java.io.PrintStream ds) { debugStream = ds; } private final int jjStopStringLiteralDfa_0(int pos, long active0, long active1) { switch (pos) { case 0: if ((active0 & 0x44101000000L) != 0L) { jjmatchedKind = 53; return 2; } if ((active0 & 0x20000000040L) != 0L) { jjmatchedKind = 53; return 10; } if ((active0 & 0x39b6ee777f80L) != 0L) { jjmatchedKind = 53; return 34; } if ((active0 & 0x810808000L) != 0L) { jjmatchedKind = 53; return 6; } return -1; case 1: if ((active0 & 0x1020c1202400L) != 0L) return 34; if ((active0 & 0x40L) != 0L) { if (jjmatchedPos != 1) { jjmatchedKind = 53; jjmatchedPos = 1; } return 9; } if ((active0 & 0x2fdf3ed7db80L) != 0L) { if (jjmatchedPos != 1) { jjmatchedKind = 53; jjmatchedPos = 1; } return 34; } return -1; case 2: if ((active0 & 0xa9232c23200L) != 0L) return 34; if ((active0 & 0x254d0c15c980L) != 0L) { if (jjmatchedPos != 2) { jjmatchedKind = 53; jjmatchedPos = 2; } return 34; } if ((active0 & 0x40L) != 0L) { if (jjmatchedPos != 2) { jjmatchedKind = 53; jjmatchedPos = 2; } return 8; } return -1; case 3: if ((active0 & 0x244500014040L) != 0L) return 34; if ((active0 & 0x1081c148980L) != 0L) { jjmatchedKind = 53; jjmatchedPos = 3; return 34; } return -1; case 4: if ((active0 & 0x8108100L) != 0L) return 34; if ((active0 & 0x10814040880L) != 0L) { jjmatchedKind = 53; jjmatchedPos = 4; return 34; } return -1; case 5: if ((active0 & 0x40800L) != 0L) return 34; if ((active0 & 0x10814000080L) != 0L) { jjmatchedKind = 53; jjmatchedPos = 5; return 34; } return -1; case 6: if ((active0 & 0x10010000080L) != 0L) return 34; if ((active0 & 0x804000000L) != 0L) { if (jjmatchedPos != 6) { jjmatchedKind = 53; jjmatchedPos = 6; } return 34; } return -1; case 7: if ((active0 & 0x804000000L) != 0L) return 34; return -1; default : return -1; } } private final int jjStartNfa_0(int pos, long active0, long active1) { return jjMoveNfa_0(jjStopStringLiteralDfa_0(pos, active0, active1), pos + 1); } private int jjStopAtPos(int pos, int kind) { jjmatchedKind = kind; jjmatchedPos = pos; return pos + 1; } private int jjMoveStringLiteralDfa0_0() { switch(curChar) { case 33: return jjMoveStringLiteralDfa1_0(0x8000000000000000L, 0x0L); case 37: return jjStopAtPos(0, 74); case 40: return jjStopAtPos(0, 57); case 41: return jjStopAtPos(0, 59); case 42: return jjStopAtPos(0, 72); case 43: return jjStopAtPos(0, 70); case 44: return jjStopAtPos(0, 58); case 45: return jjStopAtPos(0, 71); case 46: return jjStopAtPos(0, 75); case 47: return jjStopAtPos(0, 73); case 59: return jjStopAtPos(0, 19); case 60: jjmatchedKind = 64; return jjMoveStringLiteralDfa1_0(0x0L, 0x24L); case 61: jjmatchedKind = 46; return jjMoveStringLiteralDfa1_0(0x4000000000000000L, 0x0L); case 62: jjmatchedKind = 65; return jjMoveStringLiteralDfa1_0(0x0L, 0x18L); case 91: return jjStopAtPos(0, 60); case 93: return jjStopAtPos(0, 61); case 97: return jjMoveStringLiteralDfa1_0(0x80000000400L, 0x0L); case 98: return jjMoveStringLiteralDfa1_0(0x8004100L, 0x0L); case 99: return jjMoveStringLiteralDfa1_0(0x4010000L, 0x0L); case 100: return jjMoveStringLiteralDfa1_0(0x200800L, 0x0L); case 101: return jjMoveStringLiteralDfa1_0(0x19622421200L, 0x0L); case 102: return jjMoveStringLiteralDfa1_0(0x810808000L, 0x0L); case 105: return jjMoveStringLiteralDfa1_0(0x20c0002000L, 0x0L); case 110: return jjMoveStringLiteralDfa1_0(0x20000000040L, 0x0L); case 111: return jjMoveStringLiteralDfa1_0(0x100000000000L, 0x0L); case 112: return jjMoveStringLiteralDfa1_0(0x80L, 0x0L); case 114: return jjMoveStringLiteralDfa1_0(0x40000L, 0x0L); case 116: return jjMoveStringLiteralDfa1_0(0x44101000000L, 0x0L); case 118: return jjMoveStringLiteralDfa1_0(0x200000000000L, 0x0L); case 119: return jjMoveStringLiteralDfa1_0(0x100000L, 0x0L); default : return jjMoveNfa_0(3, 0); } } private int jjMoveStringLiteralDfa1_0(long active0, long active1) { try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(0, active0, active1); return 1; } switch(curChar) { case 60: if ((active1 & 0x20L) != 0L) return jjStopAtPos(1, 69); break; case 61: if ((active0 & 0x4000000000000000L) != 0L) return jjStopAtPos(1, 62); else if ((active0 & 0x8000000000000000L) != 0L) return jjStopAtPos(1, 63); else if ((active1 & 0x4L) != 0L) return jjStopAtPos(1, 66); else if ((active1 & 0x8L) != 0L) return jjStopAtPos(1, 67); break; case 62: if ((active1 & 0x10L) != 0L) return jjStopAtPos(1, 68); break; case 101: return jjMoveStringLiteralDfa2_0(active0, 0x40900L, active1, 0L); case 102: if ((active0 & 0x80000000L) != 0L) return jjStartNfaWithStates_0(1, 31, 34); break; case 104: return jjMoveStringLiteralDfa2_0(active0, 0x40100110000L, active1, 0L); case 108: return jjMoveStringLiteralDfa2_0(active0, 0x400008000L, active1, 0L); case 110: if ((active0 & 0x40000000L) != 0L) { jjmatchedKind = 30; jjmatchedPos = 1; } return jjMoveStringLiteralDfa2_0(active0, 0x89222403200L, active1, 0L); case 111: if ((active0 & 0x200000L) != 0L) return jjStartNfaWithStates_0(1, 21, 34); else if ((active0 & 0x1000000L) != 0L) return jjStartNfaWithStates_0(1, 24, 34); return jjMoveStringLiteralDfa2_0(active0, 0x220014804000L, active1, 0L); case 114: if ((active0 & 0x100000000000L) != 0L) return jjStartNfaWithStates_0(1, 44, 34); return jjMoveStringLiteralDfa2_0(active0, 0x8000080L, active1, 0L); case 115: if ((active0 & 0x400L) != 0L) return jjStartNfaWithStates_0(1, 10, 34); else if ((active0 & 0x2000000000L) != 0L) return jjStartNfaWithStates_0(1, 37, 34); break; case 117: return jjMoveStringLiteralDfa2_0(active0, 0x800000040L, active1, 0L); case 120: return jjMoveStringLiteralDfa2_0(active0, 0x10000020000L, active1, 0L); case 121: return jjMoveStringLiteralDfa2_0(active0, 0x4000000000L, active1, 0L); default : break; } return jjStartNfa_0(0, active0, active1); } private int jjMoveStringLiteralDfa2_0(long old0, long active0, long old1, long active1) { if (((active0 &= old0) | (active1 &= old1)) == 0L) return jjStartNfa_0(0, old0, old1); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(1, active0, 0L); return 2; } switch(curChar) { case 97: return jjMoveStringLiteralDfa3_0(active0, 0x10000L); case 100: if ((active0 & 0x200L) != 0L) { jjmatchedKind = 9; jjmatchedPos = 2; } else if ((active0 & 0x80000000000L) != 0L) return jjStartNfaWithStates_0(2, 43, 34); return jjMoveStringLiteralDfa3_0(active0, 0x9222401000L); case 101: return jjMoveStringLiteralDfa3_0(active0, 0x108000000L); case 102: return jjMoveStringLiteralDfa3_0(active0, 0x800L); case 103: return jjMoveStringLiteralDfa3_0(active0, 0x100L); case 105: return jjMoveStringLiteralDfa3_0(active0, 0x240000100000L); case 108: return jjMoveStringLiteralDfa3_0(active0, 0x40L); case 110: return jjMoveStringLiteralDfa3_0(active0, 0x804000000L); case 111: return jjMoveStringLiteralDfa3_0(active0, 0xc080L); case 112: if ((active0 & 0x20000L) != 0L) return jjStartNfaWithStates_0(2, 17, 34); return jjMoveStringLiteralDfa3_0(active0, 0x4000000000L); case 114: if ((active0 & 0x800000L) != 0L) { jjmatchedKind = 23; jjmatchedPos = 2; } return jjMoveStringLiteralDfa3_0(active0, 0x10000000L); case 115: return jjMoveStringLiteralDfa3_0(active0, 0x400000000L); case 116: if ((active0 & 0x2000L) != 0L) return jjStartNfaWithStates_0(2, 13, 34); else if ((active0 & 0x20000000000L) != 0L) return jjStartNfaWithStates_0(2, 41, 34); return jjMoveStringLiteralDfa3_0(active0, 0x10000040000L); default : break; } return jjStartNfa_0(1, active0, 0L); } private int jjMoveStringLiteralDfa3_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(1, old0, 0L); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(2, active0, 0L); return 3; } switch(curChar) { case 32: return jjMoveStringLiteralDfa4_0(active0, 0x9222401000L); case 97: return jjMoveStringLiteralDfa4_0(active0, 0x8008000L); case 99: return jjMoveStringLiteralDfa4_0(active0, 0x800000000L); case 100: if ((active0 & 0x200000000000L) != 0L) return jjStartNfaWithStates_0(3, 45, 34); break; case 101: if ((active0 & 0x400000000L) != 0L) return jjStartNfaWithStates_0(3, 34, 34); else if ((active0 & 0x4000000000L) != 0L) return jjStartNfaWithStates_0(3, 38, 34); return jjMoveStringLiteralDfa4_0(active0, 0x10010000000L); case 103: return jjMoveStringLiteralDfa4_0(active0, 0x80L); case 105: return jjMoveStringLiteralDfa4_0(active0, 0x900L); case 108: if ((active0 & 0x40L) != 0L) return jjStartNfaWithStates_0(3, 6, 34); else if ((active0 & 0x4000L) != 0L) return jjStartNfaWithStates_0(3, 14, 34); return jjMoveStringLiteralDfa4_0(active0, 0x100000L); case 110: if ((active0 & 0x100000000L) != 0L) return jjStartNfaWithStates_0(3, 32, 34); break; case 114: if ((active0 & 0x10000L) != 0L) return jjStartNfaWithStates_0(3, 16, 34); break; case 115: if ((active0 & 0x40000000000L) != 0L) return jjStartNfaWithStates_0(3, 42, 34); break; case 116: return jjMoveStringLiteralDfa4_0(active0, 0x4000000L); case 117: return jjMoveStringLiteralDfa4_0(active0, 0x40000L); default : break; } return jjStartNfa_0(2, active0, 0L); } private int jjMoveStringLiteralDfa4_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(2, old0, 0L); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(3, active0, 0L); return 4; } switch(curChar) { case 97: return jjMoveStringLiteralDfa5_0(active0, 0x10000000L); case 100: return jjMoveStringLiteralDfa5_0(active0, 0x1000L); case 101: if ((active0 & 0x100000L) != 0L) return jjStartNfaWithStates_0(4, 20, 34); break; case 102: return jjMoveStringLiteralDfa5_0(active0, 0x1022000000L); case 105: return jjMoveStringLiteralDfa5_0(active0, 0x204000000L); case 107: if ((active0 & 0x8000000L) != 0L) return jjStartNfaWithStates_0(4, 27, 34); break; case 110: if ((active0 & 0x100L) != 0L) return jjStartNfaWithStates_0(4, 8, 34); return jjMoveStringLiteralDfa5_0(active0, 0x10000000800L); case 114: return jjMoveStringLiteralDfa5_0(active0, 0x40080L); case 116: if ((active0 & 0x8000L) != 0L) return jjStartNfaWithStates_0(4, 15, 34); return jjMoveStringLiteralDfa5_0(active0, 0x8800000000L); case 119: return jjMoveStringLiteralDfa5_0(active0, 0x400000L); default : break; } return jjStartNfa_0(3, active0, 0L); } private int jjMoveStringLiteralDfa5_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(3, old0, 0L); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(4, active0, 0L); return 5; } switch(curChar) { case 97: return jjMoveStringLiteralDfa6_0(active0, 0x80L); case 99: return jjMoveStringLiteralDfa6_0(active0, 0x10000000L); case 100: return jjMoveStringLiteralDfa6_0(active0, 0x10000000000L); case 101: if ((active0 & 0x800L) != 0L) return jjStartNfaWithStates_0(5, 11, 34); return jjMoveStringLiteralDfa6_0(active0, 0x1000L); case 102: if ((active0 & 0x200000000L) != 0L) return jjStopAtPos(5, 33); break; case 104: return jjMoveStringLiteralDfa6_0(active0, 0x400000L); case 105: return jjMoveStringLiteralDfa6_0(active0, 0x800000000L); case 110: if ((active0 & 0x40000L) != 0L) return jjStartNfaWithStates_0(5, 18, 34); return jjMoveStringLiteralDfa6_0(active0, 0x4000000L); case 111: return jjMoveStringLiteralDfa6_0(active0, 0x22000000L); case 117: return jjMoveStringLiteralDfa6_0(active0, 0x1000000000L); case 121: return jjMoveStringLiteralDfa6_0(active0, 0x8000000000L); default : break; } return jjStartNfa_0(4, active0, 0L); } private int jjMoveStringLiteralDfa6_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(4, old0, 0L); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(5, active0, 0L); return 6; } switch(curChar) { case 102: return jjMoveStringLiteralDfa7_0(active0, 0x1000L); case 104: if ((active0 & 0x10000000L) != 0L) return jjStartNfaWithStates_0(6, 28, 34); break; case 105: return jjMoveStringLiteralDfa7_0(active0, 0x400000L); case 109: if ((active0 & 0x80L) != 0L) return jjStartNfaWithStates_0(6, 7, 34); break; case 110: return jjMoveStringLiteralDfa7_0(active0, 0x1000000000L); case 111: return jjMoveStringLiteralDfa7_0(active0, 0x800000000L); case 112: return jjMoveStringLiteralDfa7_0(active0, 0x8000000000L); case 114: if ((active0 & 0x2000000L) != 0L) { jjmatchedKind = 25; jjmatchedPos = 6; } return jjMoveStringLiteralDfa7_0(active0, 0x20000000L); case 115: if ((active0 & 0x10000000000L) != 0L) return jjStartNfaWithStates_0(6, 40, 34); break; case 117: return jjMoveStringLiteralDfa7_0(active0, 0x4000000L); default : break; } return jjStartNfa_0(5, active0, 0L); } private int jjMoveStringLiteralDfa7_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(5, old0, 0L); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(6, active0, 0L); return 7; } switch(curChar) { case 99: return jjMoveStringLiteralDfa8_0(active0, 0x1000000000L); case 101: if ((active0 & 0x4000000L) != 0L) return jjStartNfaWithStates_0(7, 26, 34); else if ((active0 & 0x8000000000L) != 0L) return jjStopAtPos(7, 39); return jjMoveStringLiteralDfa8_0(active0, 0x20000000L); case 105: return jjMoveStringLiteralDfa8_0(active0, 0x1000L); case 108: return jjMoveStringLiteralDfa8_0(active0, 0x400000L); case 110: if ((active0 & 0x800000000L) != 0L) return jjStartNfaWithStates_0(7, 35, 34); break; default : break; } return jjStartNfa_0(6, active0, 0L); } private int jjMoveStringLiteralDfa8_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(6, old0, 0L); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(7, active0, 0L); return 8; } switch(curChar) { case 97: return jjMoveStringLiteralDfa9_0(active0, 0x20000000L); case 101: if ((active0 & 0x400000L) != 0L) return jjStopAtPos(8, 22); break; case 110: return jjMoveStringLiteralDfa9_0(active0, 0x1000L); case 116: return jjMoveStringLiteralDfa9_0(active0, 0x1000000000L); default : break; } return jjStartNfa_0(7, active0, 0L); } private int jjMoveStringLiteralDfa9_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(7, old0, 0L); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(8, active0, 0L); return 9; } switch(curChar) { case 99: return jjMoveStringLiteralDfa10_0(active0, 0x20000000L); case 101: if ((active0 & 0x1000L) != 0L) return jjStopAtPos(9, 12); break; case 105: return jjMoveStringLiteralDfa10_0(active0, 0x1000000000L); default : break; } return jjStartNfa_0(8, active0, 0L); } private int jjMoveStringLiteralDfa10_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(8, old0, 0L); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(9, active0, 0L); return 10; } switch(curChar) { case 104: if ((active0 & 0x20000000L) != 0L) return jjStopAtPos(10, 29); break; case 111: return jjMoveStringLiteralDfa11_0(active0, 0x1000000000L); default : break; } return jjStartNfa_0(9, active0, 0L); } private int jjMoveStringLiteralDfa11_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(9, old0, 0L); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(10, active0, 0L); return 11; } switch(curChar) { case 110: if ((active0 & 0x1000000000L) != 0L) return jjStopAtPos(11, 36); break; default : break; } return jjStartNfa_0(10, active0, 0L); } private int jjStartNfaWithStates_0(int pos, int kind, int state) { jjmatchedKind = kind; jjmatchedPos = pos; try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { return pos + 1; } return jjMoveNfa_0(state, pos + 1); } static final long[] jjbitVec0 = { 0x0L, 0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL }; private int jjMoveNfa_0(int startState, int curPos) { int startsAt = 0; jjnewStateCnt = 35; int i = 1; jjstateSet[0] = startState; int kind = 0x7fffffff; for (;;) { if (++jjround == 0x7fffffff) ReInitRounds(); if (curChar < 64) { long l = 1L << curChar; do { switch(jjstateSet[--i]) { case 9: case 34: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 53) kind = 53; jjCheckNAdd(34); break; case 8: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 53) kind = 53; jjCheckNAdd(34); break; case 6: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 53) kind = 53; jjCheckNAdd(34); break; case 10: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 53) kind = 53; jjCheckNAdd(34); break; case 2: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 53) kind = 53; jjCheckNAdd(34); break; case 3: if ((0x3ff000000000000L & l) != 0L) { if (kind > 47) kind = 47; jjCheckNAddStates(0, 4); } else if (curChar == 34) jjCheckNAddStates(5, 7); else if (curChar == 39) jjAddStates(8, 9); break; case 12: if (curChar == 39) jjAddStates(8, 9); break; case 13: if ((0xffffff7fffffdbffL & l) != 0L) jjCheckNAdd(14); break; case 14: if (curChar == 39 && kind > 51) kind = 51; break; case 16: if ((0x8400000000L & l) != 0L) jjCheckNAdd(14); break; case 17: if (curChar == 34) jjCheckNAddStates(5, 7); break; case 18: if ((0xfffffffbffffdbffL & l) != 0L) jjCheckNAddStates(5, 7); break; case 20: if ((0x8400000000L & l) != 0L) jjCheckNAddStates(5, 7); break; case 21: if (curChar == 34 && kind > 52) kind = 52; break; case 22: if ((0xff000000000000L & l) != 0L) jjCheckNAddStates(10, 13); break; case 23: if ((0xff000000000000L & l) != 0L) jjCheckNAddStates(5, 7); break; case 24: if ((0xf000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 25; break; case 25: if ((0xff000000000000L & l) != 0L) jjCheckNAdd(23); break; case 26: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 47) kind = 47; jjCheckNAddStates(0, 4); break; case 27: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 47) kind = 47; jjCheckNAddTwoStates(27, 28); break; case 29: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(29, 30); break; case 30: if (curChar == 46) jjCheckNAdd(31); break; case 31: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 48) kind = 48; jjCheckNAdd(31); break; case 32: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 54) kind = 54; jjCheckNAdd(32); break; default : break; } } while(i != startsAt); } else if (curChar < 128) { long l = 1L << (curChar & 077); do { switch(jjstateSet[--i]) { case 9: if ((0x7fffffe87fffffeL & l) != 0L) { if (kind > 53) kind = 53; jjCheckNAdd(34); } if (curChar == 108) jjstateSet[jjnewStateCnt++] = 8; break; case 8: if ((0x7fffffe87fffffeL & l) != 0L) { if (kind > 53) kind = 53; jjCheckNAdd(34); } if (curChar == 108) { if (kind > 50) kind = 50; } break; case 6: if ((0x7fffffe87fffffeL & l) != 0L) { if (kind > 53) kind = 53; jjCheckNAdd(34); } if (curChar == 97) jjstateSet[jjnewStateCnt++] = 5; break; case 10: if ((0x7fffffe87fffffeL & l) != 0L) { if (kind > 53) kind = 53; jjCheckNAdd(34); } if (curChar == 117) jjstateSet[jjnewStateCnt++] = 9; break; case 2: if ((0x7fffffe87fffffeL & l) != 0L) { if (kind > 53) kind = 53; jjCheckNAdd(34); } if (curChar == 114) jjstateSet[jjnewStateCnt++] = 1; break; case 3: if ((0x7fffffe87fffffeL & l) != 0L) { if (kind > 53) kind = 53; jjCheckNAdd(34); } if (curChar == 110) jjstateSet[jjnewStateCnt++] = 10; else if (curChar == 102) jjstateSet[jjnewStateCnt++] = 6; else if (curChar == 116) jjstateSet[jjnewStateCnt++] = 2; break; case 0: if (curChar == 101 && kind > 49) kind = 49; break; case 1: if (curChar == 117) jjCheckNAdd(0); break; case 4: if (curChar == 115) jjCheckNAdd(0); break; case 5: if (curChar == 108) jjstateSet[jjnewStateCnt++] = 4; break; case 7: if (curChar == 102) jjstateSet[jjnewStateCnt++] = 6; break; case 11: if (curChar == 110) jjstateSet[jjnewStateCnt++] = 10; break; case 13: if ((0xffffffffefffffffL & l) != 0L) jjCheckNAdd(14); break; case 15: if (curChar == 92) jjstateSet[jjnewStateCnt++] = 16; break; case 16: if ((0x400010000000L & l) != 0L) jjCheckNAdd(14); break; case 18: if ((0xffffffffefffffffL & l) != 0L) jjCheckNAddStates(5, 7); break; case 19: if (curChar == 92) jjAddStates(14, 16); break; case 20: if ((0x14404410000000L & l) != 0L) jjCheckNAddStates(5, 7); break; case 28: if ((0x100000001000L & l) != 0L && kind > 47) kind = 47; break; case 33: if ((0x7fffffe87fffffeL & l) == 0L) break; if (kind > 53) kind = 53; jjCheckNAdd(34); break; case 34: if ((0x7fffffe87fffffeL & l) == 0L) break; if (kind > 53) kind = 53; jjCheckNAdd(34); break; default : break; } } while(i != startsAt); } else { int i2 = (curChar & 0xff) >> 6; long l2 = 1L << (curChar & 077); do { switch(jjstateSet[--i]) { case 13: if ((jjbitVec0[i2] & l2) != 0L) jjstateSet[jjnewStateCnt++] = 14; break; case 18: if ((jjbitVec0[i2] & l2) != 0L) jjAddStates(5, 7); break; default : break; } } while(i != startsAt); } if (kind != 0x7fffffff) { jjmatchedKind = kind; jjmatchedPos = curPos; kind = 0x7fffffff; } ++curPos; if ((i = jjnewStateCnt) == (startsAt = 35 - (jjnewStateCnt = startsAt))) return curPos; try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { return curPos; } } } static final int[] jjnextStates = { 27, 28, 29, 30, 32, 18, 19, 21, 13, 15, 18, 19, 23, 21, 20, 22, 24, }; /** Token literal values. */ public static final String[] jjstrLiteralImages = { "", null, null, null, null, null, "\156\165\154\154", "\160\162\157\147\162\141\155", "\142\145\147\151\156", "\145\156\144", "\141\163", "\144\145\146\151\156\145", "\145\156\144\40\144\145\146\151\156\145", "\151\156\164", "\142\157\157\154", "\146\154\157\141\164", "\143\150\141\162", "\145\170\160", "\162\145\164\165\162\156", "\73", "\167\150\151\154\145", "\144\157", "\145\156\144\40\167\150\151\154\145", "\146\157\162", "\164\157", "\145\156\144\40\146\157\162", "\143\157\156\164\151\156\165\145", "\142\162\145\141\153", "\146\157\162\145\141\143\150", "\145\156\144\40\146\157\162\145\141\143\150", "\151\156", "\151\146", "\164\150\145\156", "\145\156\144\40\151\146", "\145\154\163\145", "\146\165\156\143\164\151\157\156", "\145\156\144\40\146\165\156\143\164\151\157\156", "\151\163", "\164\171\160\145", "\145\156\144\40\164\171\160\145", "\145\170\164\145\156\144\163", "\156\157\164", "\164\150\151\163", "\141\156\144", "\157\162", "\166\157\151\144", "\75", null, null, null, null, null, null, null, null, null, null, "\50", "\54", "\51", "\133", "\135", "\75\75", "\41\75", "\74", "\76", "\74\75", "\76\75", "\76\76", "\74\74", "\53", "\55", "\52", "\57", "\45", "\56", }; /** Lexer state names. */ public static final String[] lexStateNames = { "DEFAULT", }; static final long[] jjtoToken = { 0xffffffffffffffc1L, 0xfffL, }; static final long[] jjtoSkip = { 0x3eL, 0x0L, }; protected SimpleCharStream input_stream; private final int[] jjrounds = new int[35]; private final int[] jjstateSet = new int[70]; protected char curChar; /** Constructor. */ public MyLangTokenManager(SimpleCharStream stream){ if (SimpleCharStream.staticFlag) throw new Error("ERROR: Cannot use a static CharStream class with a non-static lexical analyzer."); input_stream = stream; } /** Constructor. */ public MyLangTokenManager(SimpleCharStream stream, int lexState){ this(stream); SwitchTo(lexState); } /** Reinitialise parser. */ public void ReInit(SimpleCharStream stream) { jjmatchedPos = jjnewStateCnt = 0; curLexState = defaultLexState; input_stream = stream; ReInitRounds(); } private void ReInitRounds() { int i; jjround = 0x80000001; for (i = 35; i-- > 0;) jjrounds[i] = 0x80000000; } /** Reinitialise parser. */ public void ReInit(SimpleCharStream stream, int lexState) { ReInit(stream); SwitchTo(lexState); } /** Switch to specified lex state. */ public void SwitchTo(int lexState) { if (lexState >= 1 || lexState < 0) throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenMgrError.INVALID_LEXICAL_STATE); else curLexState = lexState; } protected Token jjFillToken() { final Token t; final String curTokenImage; final int beginLine; final int endLine; final int beginColumn; final int endColumn; String im = jjstrLiteralImages[jjmatchedKind]; curTokenImage = (im == null) ? input_stream.GetImage() : im; beginLine = input_stream.getBeginLine(); beginColumn = input_stream.getBeginColumn(); endLine = input_stream.getEndLine(); endColumn = input_stream.getEndColumn(); t = Token.newToken(jjmatchedKind, curTokenImage); t.beginLine = beginLine; t.endLine = endLine; t.beginColumn = beginColumn; t.endColumn = endColumn; return t; } int curLexState = 0; int defaultLexState = 0; int jjnewStateCnt; int jjround; int jjmatchedPos; int jjmatchedKind; /** Get the next Token. */ public Token getNextToken() { Token matchedToken; int curPos = 0; EOFLoop : for (;;) { try { curChar = input_stream.BeginToken(); } catch(java.io.IOException e) { jjmatchedKind = 0; matchedToken = jjFillToken(); return matchedToken; } try { input_stream.backup(0); while (curChar <= 32 && (0x100003600L & (1L << curChar)) != 0L) curChar = input_stream.BeginToken(); } catch (java.io.IOException e1) { continue EOFLoop; } jjmatchedKind = 0x7fffffff; jjmatchedPos = 0; curPos = jjMoveStringLiteralDfa0_0(); if (jjmatchedKind != 0x7fffffff) { if (jjmatchedPos + 1 < curPos) input_stream.backup(curPos - jjmatchedPos - 1); if ((jjtoToken[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L) { matchedToken = jjFillToken(); return matchedToken; } else { continue EOFLoop; } } int error_line = input_stream.getEndLine(); int error_column = input_stream.getEndColumn(); String error_after = null; boolean EOFSeen = false; try { input_stream.readChar(); input_stream.backup(1); } catch (java.io.IOException e1) { EOFSeen = true; error_after = curPos <= 1 ? "" : input_stream.GetImage(); if (curChar == '\n' || curChar == '\r') { error_line++; error_column = 0; } else error_column++; } if (!EOFSeen) { input_stream.backup(1); error_after = curPos <= 1 ? "" : input_stream.GetImage(); } throw new TokenMgrError(EOFSeen, curLexState, error_line, error_column, error_after, curChar, TokenMgrError.LEXICAL_ERROR); } } private void jjCheckNAdd(int state) { if (jjrounds[state] != jjround) { jjstateSet[jjnewStateCnt++] = state; jjrounds[state] = jjround; } } private void jjAddStates(int start, int end) { do { jjstateSet[jjnewStateCnt++] = jjnextStates[start]; } while (start++ != end); } private void jjCheckNAddTwoStates(int state1, int state2) { jjCheckNAdd(state1); jjCheckNAdd(state2); } private void jjCheckNAddStates(int start, int end) { do { jjCheckNAdd(jjnextStates[start]); } while (start++ != end); } }<file_sep>/src/main/java/AST/ASTforeachstm.java package AST; import org.llvm.BasicBlock; import org.llvm.TypeRef; import org.llvm.Value; import org.llvm.binding.LLVMLibrary.LLVMIntPredicate; /* Generated By:JJTree: Do not edit this line. ASTforeachstm.java Version 4.3 */ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=false,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ public class ASTforeachstm extends SimpleNode { SimpleNode variable,range,block; public ASTforeachstm(int id) { super(id); } public ASTforeachstm(MyLang p, int id) { super(p, id); } public ASTContent code_gen(ASTContext Context) throws Exception{ variable = (SimpleNode)children[0]; range = (SimpleNode)children[1]; block = (SimpleNode)children[2]; ASTContent cur = new ASTContent( MyLang.builder.buildAlloca(TypeRef.int32Type().type(), "cnt"),IDENTIFIER,47); MyLang.builder.buildStore(ty_int.constInt(0, true), cur.value); ASTContent L = variable.code_gen(Context); ASTContent R = range.code_gen(Context); if(L.type != IDENTIFIER) throw new Exception("Left is not IDENTIFIER!"); Value n1 = ty_int.constInt(0, true); Value n2 = cur.getPValue().value; Value[] values = new Value[2]; values[0] = n1; values[1] = n2; Value ptr = MyLang.builder.buildGEP(((ASTArrayContent)R).value, Value.internalize(values), 2, "a1"); R = new ASTContent(ptr, IDENTIFIER, R.info_type); MyLang.builder.buildStore(R.castTo(L.info_type), L.value); R = range.code_gen(Context); Value limit = ((ASTArrayContent) R).length; ASTContent tot = new ASTContent( MyLang.builder.buildAlloca(TypeRef.int32Type().type(), "cnt"),IDENTIFIER,47); ASTContent limitv = new ASTContent( MyLang.builder.buildLoad(limit, "tmp"),R.info_type); ASTContent limitval = new ASTContent( MyLang.builder.buildStore(limitv.value, tot.value), R.info_type); BasicBlock forheadBB = Context.f_main().appendBasicBlock("forhead"); BasicBlock forbodyBB = Context.f_main().appendBasicBlock("forbody"); BasicBlock forfootBB = Context.f_main().appendBasicBlock("forfoot"); BasicBlock out = Context.f_main().appendBasicBlock("break"); MyLang.builder.buildBr(forheadBB); MyLang.builder.positionBuilderAtEnd(forheadBB); Value cmp = MyLang.builder.buildLoad(cur.value, "cmp"); ASTContent cond = new ASTContent(MyLang.builder.buildICmp(LLVMIntPredicate.LLVMIntSLT, cmp,tot.getPValue().value, String.valueOf(cnt)), BOOLEAN_LITERAL); MyLang.builder.buildCondBr(cond.value , forbodyBB, out); MyLang.builder.positionBuilderAtEnd(forbodyBB); ASTContext bodyContext = new ASTContext(Context, Context.entry, Context.func); bodyContext.breakBB = out; bodyContext.continueBB = forfootBB; block.code_gen(bodyContext); MyLang.builder.buildBr(forfootBB); MyLang.builder.positionBuilderAtEnd(forfootBB); R = range.code_gen(Context); ASTContent curadd = new ASTContent( MyLang.builder.buildAdd(cur.getPValue().value, TypeRef.int32Type().constInt(1, true), String.valueOf(cnt)), INTEGER_LITERAL); MyLang.builder.buildStore(curadd.castTo(cur.info_type), cur.value); n1 = ty_int.constInt(0, true); n2 = cur.getPValue().value; values = new Value[2]; values[0] = n1; values[1] = n2; ptr = MyLang.builder.buildGEP(R.value, Value.internalize(values), 2, "a1"); R = new ASTContent(ptr, IDENTIFIER, R.info_type); MyLang.builder.buildStore(R.castTo(L.info_type), L.value); MyLang.builder.buildBr(forheadBB); BasicBlock end = Context.f_main().appendBasicBlock("endfor"); MyLang.builder.positionBuilderAtEnd(out); MyLang.builder.buildBr(end); MyLang.builder.positionBuilderAtEnd(end); return null; } } /* JavaCC - OriginalChecksum=b1d826f845b298f0d56881aef9b29ec7 (do not edit this line) */ /* JavaCC - OriginalChecksum=b1d826f845b298f0d56881aef9b29ec7 (do not edit this line) */ <file_sep>/src/main/java/AST/ASTUnaryExpression.java package AST; import org.llvm.TypeRef; import org.llvm.Value; /* Generated By:JJTree: Do not edit this line. ASTUnaryExpression.java Version 4.3 */ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=false,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ public class ASTUnaryExpression extends SimpleNode { public String op; public SimpleNode Val; public ASTUnaryExpression(int id) { super(id); } public ASTUnaryExpression(MyLang p, int id) { super(p, id); } public ASTContent code_gen(ASTContext context) throws Exception{ Val = (SimpleNode)children[0]; op = jjtGetValue().toString(); ASTContent val = Val.code_gen(context).getPValue(); if(op.equals("+")){ if(val.isBoolean()) throw new Exception("+Bool is invalid."); if(val.isInteger() || val.isDouble()){ return val; } } else if(op.equals("-")){ if(val.isBoolean()) throw new Exception("+Bool is invalid."); if(val.isInteger()){ cnt++; return new ASTContent(MyLang.builder.buildNeg(val.value, String.valueOf(cnt)), val.type); } if(val.isDouble()){ cnt++; return new ASTContent(MyLang.builder.buildFNeg(val.value, String.valueOf(cnt)), val.type); } } else if(op.equals("not")){ if(val.isBoolean()){ cnt++; return new ASTContent(MyLang.builder.buildNot(val.value, String.valueOf(cnt)), val.type); } throw new Exception("not INT/FLOAT is invalid."); } throw new Exception("Unknown mistake in ASTUnaryExpression."); } } /* JavaCC - OriginalChecksum=edae6ca8ae816fc2e7f47dd87b3ab16d (do not edit this line) */ <file_sep>/src/main/java/AST/ASTContext.java package AST; import java.util.*; import org.llvm.*; public class ASTContext implements MyLangConstants { Map<String, ASTContent> values = new HashMap<String, ASTContent>(); ASTContext father; BasicBlock entry; BasicBlock breakBB; BasicBlock continueBB; ASTContent func; boolean isExtending=false; ASTContext(){} ASTContext(ASTContext father, BasicBlock entry, ASTContent func) { this.father = father; this.func = func; this.entry = entry; if (father!=null){ this.breakBB = father.breakBB; this.continueBB = father.continueBB; } } void put(String name, Value value, int type) throws Exception { if (values.containsKey(name)) throw new Exception("重复的变量名:"+name); if (type == FUNCTION) throw new Exception(name+" is a function but not variable."); values.put(name, new ASTContent(value, type)); } boolean put(String name, Value value, int type, int info_type) throws Exception { if (values.containsKey(name)) throw new Exception("重复的变量名:"+name); values.put(name, new ASTContent(value, type, info_type)); return true; } boolean put(String name, Value value, int type, int info_type, Value length) throws Exception { if (values.containsKey(name)) throw new Exception("重复的变量名:"+name); values.put(name, new ASTArrayContent(value, type, info_type, length)); return true; } boolean put(String name, Value value, int retType, List<Integer> types) throws Exception { if (values.containsKey(name)) if (!isExtending) throw new Exception("重复的函数名:"+name); else return true; values.put(name, new ASTFuncContent(value, retType, types)); return true; } boolean put(String name, SimpleNode sn) throws Exception { if (values.containsKey(name)) throw new Exception("class name duplication: "+name); values.put(name, new ASTClassContent(sn)); return true; } boolean put(String name, ASTContext context) throws Exception { if (values.containsKey(name)) throw new Exception("variable name duplication: "+name); values.put(name, new ASTObjectContent(context)); return true; } ASTContent get(String name) { for ( ASTContext x = this; x != null; x = x.father) if (x.values.containsKey(name)) return x.values.get(name); return null; } Value f_main() { return func.value; } boolean isMain() { if (func==null) return true; return f_main().getValueName().equals("main"); } } <file_sep>/src/main/java/AST/MyLang.java package AST; import java.io.ByteArrayInputStream; import java.util.ArrayList; import java.util.List; import org.llvm.*; /* Generated By:JJTree&JavaCC: Do not edit this line. MyLang.java */ /** An Arithmetic Grammar. */ public class MyLang/* @bgen(jjtree) */ implements MyLangTreeConstants, MyLangConstants {/* @bgen(jjtree) */ protected static JJTMyLangState jjtree = new JJTMyLangState(); /** Main entry point. */ public static Module module = null; public static Builder builder = null; public static void InitialSetting(ASTContext context) throws Exception { TypeRef ty_print = TypeRef.functionType(ty_int, TypeRef.int8Type().pointerType()); Value printf = module.addFunction("printf", ty_print); TypeRef outputType = TypeRef.functionType(ty_int, ty_int); // output int Value outputD = module.addFunction("outputD", outputType); BasicBlock bb = outputD.appendBasicBlock("entry"); List<Integer> argType = new ArrayList<Integer>(); argType.add(INTEGER_LITERAL); context.put("outputD", outputD, INTEGER_LITERAL, argType); builder.positionBuilderAtEnd(bb); Value argC = builder.buildGlobalString("%c", "argD"); Value argD = builder.buildGlobalString("%d", "argD"); Value[] values = { argD, outputD.getFirstParam() }; Value ret = builder.buildCall(printf, "ret", values); builder.buildRet(ret); // output char Value output = module.addFunction("output", outputType); bb = output.appendBasicBlock("entry"); context.put("output", output, INTEGER_LITERAL, argType); builder.positionBuilderAtEnd(bb); Value arg = Value.constIntCast(output.getFirstParam(), TypeRef.int8Type(), false); values[0] = argC; values[1] = arg; builder.buildRet(builder.buildCall(printf, "ret", values)); // output float Value outputF = module.addFunction("outputF", outputType); bb = outputF.appendBasicBlock("entry"); argType = new ArrayList<Integer>(); argType.add(FLOAT_LITERAL); context.put("outputF", outputF, INTEGER_LITERAL, argType); builder.positionBuilderAtEnd(bb); Value argF = builder.buildGlobalString("%f", "argF"); Value[] valueF = { argF, outputF.getFirstParam() }; ret = builder.buildCall(printf, "ret", valueF); builder.buildRet(ret); // output new line Value outputN = module.addFunction("outputN", outputType); bb = outputN.appendBasicBlock("entry"); List<Integer> argTypeN = new ArrayList<Integer>(); argTypeN.add(VOID); context.put("outputN", outputN, INTEGER_LITERAL, argTypeN); builder.positionBuilderAtEnd(bb); values[0] = argC; values[1] = TypeRef.int8Type().constInt('\n', false); builder.buildRet(builder.buildCall(printf, "ret", values)); } public static void main(String[] args) { try { MyLang t = new MyLang(new ByteArrayInputStream(args[0].getBytes())); module = Module.createWithName("test"); builder = Builder.createBuilder(); ASTContext context = new ASTContext(null, null, null); InitialSetting(context); module = Module.createWithNameInContext("module", module.getModuleContext()); TypeRef ty_void = TypeRef.voidType(); TypeRef ty_func = TypeRef.functionType(ty_int, ty_void); Value f_main = module.addFunction("main", ty_func); context.entry = f_main.appendBasicBlock("entry"); builder.positionBuilderAtEnd(context.entry); context.func = new ASTContent(f_main, FLOAT_LITERAL); ASTstart n = t.Start(); //n.dump(""); n.code_gen(context); builder.buildRet(RealZero); module.dumpModule(); // Create an execution engine. ExecutionEngine ee = ExecutionEngine.createForModule(module); // The arguments need to be passed as "GenericValue" objects. boolean isSign = true; // Compile and run! GenericValue retval = ee.runFunction(f_main, GenericValue.createPtr(null)); //System.out.println("ans=" + retval.toFloat(ty_real)); } catch (Exception e) { System.out.println("Oops."); System.out.println(e.getMessage()); e.printStackTrace(); } } /** Main production. */ static final public ASTstart Start() throws ParseException { /*@bgen(jjtree) start */ ASTstart jjtn000 = new ASTstart(JJTSTART); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { procedure(); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; {if (true) return jjtn000;} } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } throw new Error("Missing return statement in function"); } static final public void procedure() throws ParseException { /*@bgen(jjtree) program */ ASTprogram jjtn000 = new ASTprogram(JJTPROGRAM); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { jj_consume_token(PROGRAM); label_1: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case DEFINE: case TYPE: ; break; default: jj_la1[0] = jj_gen; break label_1; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case TYPE: class_declaration(); break; case DEFINE: declaration(); break; default: jj_la1[1] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } jj_consume_token(BEGIN); block(); jj_consume_token(END); jj_consume_token(SEMICOlON); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } } static final public void block() throws ParseException { /*@bgen(jjtree) block */ ASTblock jjtn000 = new ASTblock(JJTBLOCK); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { label_2: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case RETURN: case SEMICOlON: case WHILE: case FOR: case CONTINUE: case BREAK: case FOREACH: case IF: case NOT: case INTEGER_LITERAL: case FLOAT_LITERAL: case BOOLEAN_LITERAL: case NULL_LITERAL: case CHARACTER_LITERAL: case STRING_LITERAL: case IDENTIFIER: case 57: case 60: case 70: case 71: ; break; default: jj_la1[2] = jj_gen; break label_2; } statement(); } } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } } static final public void statement() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case RETURN: return_statement(); break; case SEMICOlON: case NOT: case INTEGER_LITERAL: case FLOAT_LITERAL: case BOOLEAN_LITERAL: case NULL_LITERAL: case CHARACTER_LITERAL: case STRING_LITERAL: case IDENTIFIER: case 57: case 60: case 70: case 71: common_statement(); break; case WHILE: while_statement(); break; case FOR: for_statement(); break; case CONTINUE: continue_statement(); break; case BREAK: break_statement(); break; case FOREACH: foreach_statement(); break; case IF: ifthen_statement(); break; default: jj_la1[3] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } static final public void ifthen_statement() throws ParseException { /*@bgen(jjtree) ifthenstm */ ASTifthenstm jjtn000 = new ASTifthenstm(JJTIFTHENSTM); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { jj_consume_token(IF); expression(); jj_consume_token(THEN); block(); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case ELSE: jj_consume_token(ELSE); block(); break; default: jj_la1[4] = jj_gen; ; } jj_consume_token(ENDIF); jj_consume_token(SEMICOlON); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } } static final public void foreach_statement() throws ParseException { /*@bgen(jjtree) foreachstm */ ASTforeachstm jjtn000 = new ASTforeachstm(JJTFOREACHSTM); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { jj_consume_token(FOREACH); Identifier(); jj_consume_token(IN); expression(); jj_consume_token(DO); block(); jj_consume_token(ENDFORE); jj_consume_token(SEMICOlON); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } } static final public void continue_statement() throws ParseException { /*@bgen(jjtree) continuestm */ ASTcontinuestm jjtn000 = new ASTcontinuestm(JJTCONTINUESTM); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { jj_consume_token(CONTINUE); jj_consume_token(SEMICOlON); } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } } static final public void break_statement() throws ParseException { /*@bgen(jjtree) breakstm */ ASTbreakstm jjtn000 = new ASTbreakstm(JJTBREAKSTM); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { jj_consume_token(BREAK); jj_consume_token(SEMICOlON); } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } } static final public void for_statement() throws ParseException { /*@bgen(jjtree) forstm */ ASTforstm jjtn000 = new ASTforstm(JJTFORSTM); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { jj_consume_token(FOR); Identifier(); jj_consume_token(EQUAL); expression(); jj_consume_token(TO); expression(); jj_consume_token(DO); block(); jj_consume_token(ENDFOR); jj_consume_token(SEMICOlON); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } } static final public void while_statement() throws ParseException { /*@bgen(jjtree) whilestm */ ASTwhilestm jjtn000 = new ASTwhilestm(JJTWHILESTM); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { jj_consume_token(WHILE); expression(); jj_consume_token(DO); block(); jj_consume_token(ENDWHILE); jj_consume_token(SEMICOlON); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } } static final public void return_statement() throws ParseException { /*@bgen(jjtree) returnstm */ ASTreturnstm jjtn000 = new ASTreturnstm(JJTRETURNSTM); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { jj_consume_token(RETURN); expression(); jj_consume_token(SEMICOlON); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } } static final public void common_statement() throws ParseException { /*@bgen(jjtree) commonstm */ ASTcommonstm jjtn000 = new ASTcommonstm(JJTCOMMONSTM); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case NOT: case INTEGER_LITERAL: case FLOAT_LITERAL: case BOOLEAN_LITERAL: case NULL_LITERAL: case CHARACTER_LITERAL: case STRING_LITERAL: case IDENTIFIER: case 57: case 60: case 70: case 71: expression(); break; default: jj_la1[5] = jj_gen; ; } jj_consume_token(SEMICOlON); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } } static final public void class_declaration() throws ParseException { /*@bgen(jjtree) class_declaration */ ASTclass_declaration jjtn000 = new ASTclass_declaration(JJTCLASS_DECLARATION); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { jj_consume_token(TYPE); Identifier(); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case EXTEND: jj_consume_token(EXTEND); Identifier(); break; default: jj_la1[6] = jj_gen; ; } jj_consume_token(IS); label_3: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IDENTIFIER: ; break; default: jj_la1[7] = jj_gen; break label_3; } if (jj_2_1(3)) { function_declaration(); } else { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IDENTIFIER: variable_declaration(); break; default: jj_la1[8] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } } jj_consume_token(ENDTYPE); jj_consume_token(SEMICOlON); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } } static final public void declaration() throws ParseException { /*@bgen(jjtree) declaration */ ASTdeclaration jjtn000 = new ASTdeclaration(JJTDECLARATION); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { jj_consume_token(DEFINE); label_4: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IDENTIFIER: ; break; default: jj_la1[9] = jj_gen; break label_4; } if (jj_2_2(3)) { function_declaration(); } else { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IDENTIFIER: variable_declaration(); break; default: jj_la1[10] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } } jj_consume_token(ENDDEF); jj_consume_token(SEMICOlON); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } } static final public void function_declaration() throws ParseException { /*@bgen(jjtree) func_declaration */ ASTfunc_declaration jjtn000 = new ASTfunc_declaration(JJTFUNC_DECLARATION); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { Identifier(); label_5: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case 57: ; break; default: jj_la1[11] = jj_gen; break label_5; } jj_consume_token(57); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IDENTIFIER: declaration_kind(); label_6: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case 58: ; break; default: jj_la1[12] = jj_gen; break label_6; } jj_consume_token(58); declaration_kind(); } jj_consume_token(AS); Type(); break; default: jj_la1[13] = jj_gen; ; } jj_consume_token(59); } jj_consume_token(AS); jj_consume_token(FUNCTION); jj_consume_token(RETURN); Type(); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IS: jj_consume_token(IS); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case DEFINE: jj_consume_token(DEFINE); label_7: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IDENTIFIER: ; break; default: jj_la1[14] = jj_gen; break label_7; } if (jj_2_3(3)) { variable_declaration(); } else { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IDENTIFIER: function_declaration(); break; default: jj_la1[15] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } } jj_consume_token(ENDDEF); jj_consume_token(SEMICOlON); break; default: jj_la1[16] = jj_gen; ; } block(); jj_consume_token(ENDFUNC); break; default: jj_la1[17] = jj_gen; ; } jj_consume_token(SEMICOlON); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } } static final public void variable_declaration() throws ParseException { /*@bgen(jjtree) var_declaration */ ASTvar_declaration jjtn000 = new ASTvar_declaration(JJTVAR_DECLARATION); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { declaration_kind(); label_8: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case 58: ; break; default: jj_la1[18] = jj_gen; break label_8; } jj_consume_token(58); declaration_kind(); } jj_consume_token(AS); Type(); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IS: jj_consume_token(IS); ExpressionList(); break; default: jj_la1[19] = jj_gen; ; } jj_consume_token(SEMICOlON); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } } static final public void declaration_kind() throws ParseException { if (jj_2_4(3)) { arraydeclaration_num(); } else if (jj_2_5(2)) { arraydeclaration_nonum(); } else { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IDENTIFIER: Identifier(); break; default: jj_la1[20] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } } static final public void arraydeclaration_num() throws ParseException { /*@bgen(jjtree) array */ ASTarray jjtn000 = new ASTarray(JJTARRAY); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { Identifier(); jj_consume_token(60); expression(); jj_consume_token(61); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } } static final public void arraydeclaration_nonum() throws ParseException { /*@bgen(jjtree) array */ ASTarray jjtn000 = new ASTarray(JJTARRAY); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { Identifier(); jj_consume_token(60); jj_consume_token(61); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } } static final public void Type() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case INT: case BOOL: case FLOAT: case CHAR: case VOID: PrimitiveType(); label_9: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case 60: ; break; default: jj_la1[21] = jj_gen; break label_9; } jj_consume_token(60); jj_consume_token(61); } break; case IDENTIFIER: ASTType jjtn001 = new ASTType(JJTTYPE); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { Identifier(); } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, true); } } break; default: jj_la1[22] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } static final public void PrimitiveType() throws ParseException { /*@bgen(jjtree) primtype */ ASTprimtype jjtn000 = new ASTprimtype(JJTPRIMTYPE); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000);Token t; try { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case BOOL: t = jj_consume_token(BOOL); break; case CHAR: t = jj_consume_token(CHAR); break; case INT: t = jj_consume_token(INT); break; case FLOAT: t = jj_consume_token(FLOAT); break; case VOID: t = jj_consume_token(VOID); break; default: jj_la1[23] = jj_gen; jj_consume_token(-1); throw new ParseException(); } jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; jjtn000.jjtSetValue(t.image); } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } } /** An Expression. */ static final public void expression() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case 60: ASTArrayConstructor jjtn001 = new ASTArrayConstructor(JJTARRAYCONSTRUCTOR); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { jj_consume_token(60); ExpressionList(); jj_consume_token(61); } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, true); } } break; case NOT: case INTEGER_LITERAL: case FLOAT_LITERAL: case BOOLEAN_LITERAL: case NULL_LITERAL: case CHARACTER_LITERAL: case STRING_LITERAL: case IDENTIFIER: case 57: case 70: case 71: ASTAssignment jjtn002 = new ASTAssignment(JJTASSIGNMENT); boolean jjtc002 = true; jjtree.openNodeScope(jjtn002); try { LogicalAndExpression(); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case EQUAL: jj_consume_token(EQUAL); expression(); break; default: jj_la1[24] = jj_gen; ; } } catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} } finally { if (jjtc002) { jjtree.closeNodeScope(jjtn002, jjtree.nodeArity() > 1); } } break; default: jj_la1[25] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } static final public void LogicalOrExpression() throws ParseException { ASTLogicalOrExpression jjtn001 = new ASTLogicalOrExpression(JJTLOGICALOREXPRESSION); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { LogicalAndExpression(); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case OR: jj_consume_token(OR); LogicalOrExpression(); break; default: jj_la1[26] = jj_gen; ; } } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, jjtree.nodeArity() > 1); } } } static final public void LogicalAndExpression() throws ParseException { ASTLogicalAndExpression jjtn001 = new ASTLogicalAndExpression(JJTLOGICALANDEXPRESSION); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { EqualityExpression(); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case AND: jj_consume_token(AND); LogicalAndExpression(); break; default: jj_la1[27] = jj_gen; ; } } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, jjtree.nodeArity() > 1); } } } static final public void EqualityExpression() throws ParseException { Token t; ASTEqualityExpression jjtn001 = new ASTEqualityExpression(JJTEQUALITYEXPRESSION); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { RelationalExpression(); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case 62: case 63: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case 62: t = jj_consume_token(62); break; case 63: t = jj_consume_token(63); break; default: jj_la1[28] = jj_gen; jj_consume_token(-1); throw new ParseException(); } jjtn001.jjtSetValue(t.image); EqualityExpression(); break; default: jj_la1[29] = jj_gen; ; } } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, jjtree.nodeArity() > 1); } } } static final public void RelationalExpression() throws ParseException { Token t; ASTRelationalExpression jjtn001 = new ASTRelationalExpression(JJTRELATIONALEXPRESSION); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { ShiftExpression(); if (jj_2_6(2)) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case 64: t = jj_consume_token(64); break; case 65: t = jj_consume_token(65); break; case 66: t = jj_consume_token(66); break; case 67: t = jj_consume_token(67); break; default: jj_la1[30] = jj_gen; jj_consume_token(-1); throw new ParseException(); } jjtn001.jjtSetValue(t.image); ShiftExpression(); } else { ; } } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, jjtree.nodeArity() > 1); } } } static final public void ShiftExpression() throws ParseException { Token t; ASTShiftExpression jjtn001 = new ASTShiftExpression(JJTSHIFTEXPRESSION); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { AdditiveExpression(); if (jj_2_7(2)) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case 68: t = jj_consume_token(68); break; case 69: t = jj_consume_token(69); break; default: jj_la1[31] = jj_gen; jj_consume_token(-1); throw new ParseException(); } jjtn001.jjtSetValue(t.image); AdditiveExpression(); } else { ; } } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, jjtree.nodeArity() > 1); } } } /** An Additive Expression. */ static final public void AdditiveExpression() throws ParseException { Token t; ASTCommonExpression jjtn002 = new ASTCommonExpression(JJTCOMMONEXPRESSION); boolean jjtc002 = true; jjtree.openNodeScope(jjtn002); try { MultiplicativeExpression(); label_10: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case 70: case 71: ; break; default: jj_la1[32] = jj_gen; break label_10; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case 70: t = jj_consume_token(70); break; case 71: t = jj_consume_token(71); break; default: jj_la1[33] = jj_gen; jj_consume_token(-1); throw new ParseException(); } ASTOpt jjtn001 = new ASTOpt(JJTOPT); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { jjtree.closeNodeScope(jjtn001, true); jjtc001 = false; jjtn001.jjtSetValue(t.image); } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, true); } } MultiplicativeExpression(); } } catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} } finally { if (jjtc002) { jjtree.closeNodeScope(jjtn002, jjtree.nodeArity() > 1); } } } /** A Multiplicative Expression. */ static final public void MultiplicativeExpression() throws ParseException { Token t; ASTCommonExpression jjtn002 = new ASTCommonExpression(JJTCOMMONEXPRESSION); boolean jjtc002 = true; jjtree.openNodeScope(jjtn002); try { UnaryExpression(); label_11: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case 72: case 73: case 74: ; break; default: jj_la1[34] = jj_gen; break label_11; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case 72: t = jj_consume_token(72); break; case 73: t = jj_consume_token(73); break; case 74: t = jj_consume_token(74); break; default: jj_la1[35] = jj_gen; jj_consume_token(-1); throw new ParseException(); } ASTOpt jjtn001 = new ASTOpt(JJTOPT); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { jjtree.closeNodeScope(jjtn001, true); jjtc001 = false; jjtn001.jjtSetValue(t.image); } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, true); } } UnaryExpression(); } } catch (Throwable jjte002) { if (jjtc002) { jjtree.clearNodeScope(jjtn002); jjtc002 = false; } else { jjtree.popNode(); } if (jjte002 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte002;} } if (jjte002 instanceof ParseException) { {if (true) throw (ParseException)jjte002;} } {if (true) throw (Error)jjte002;} } finally { if (jjtc002) { jjtree.closeNodeScope(jjtn002, jjtree.nodeArity() > 1); } } } /** A Unary Expression. */ static final public void UnaryExpression() throws ParseException { Token t; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case NOT: case 70: case 71: ASTUnaryExpression jjtn001 = new ASTUnaryExpression(JJTUNARYEXPRESSION); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case 70: t = jj_consume_token(70); break; case 71: t = jj_consume_token(71); break; case NOT: t = jj_consume_token(NOT); break; default: jj_la1[36] = jj_gen; jj_consume_token(-1); throw new ParseException(); } jjtn001.jjtSetValue(t.image); UnaryExpression(); } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, true); } } break; case INTEGER_LITERAL: case FLOAT_LITERAL: case BOOLEAN_LITERAL: case NULL_LITERAL: case CHARACTER_LITERAL: case STRING_LITERAL: case IDENTIFIER: case 57: case 60: Primary(); break; default: jj_la1[37] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } static final public void Primary() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case INTEGER_LITERAL: case FLOAT_LITERAL: case BOOLEAN_LITERAL: case NULL_LITERAL: case CHARACTER_LITERAL: case STRING_LITERAL: Literal(); break; case 57: jj_consume_token(57); expression(); jj_consume_token(59); break; case IDENTIFIER: case 60: ASTPrimaryPrefixAccess jjtn001 = new ASTPrimaryPrefixAccess(JJTPRIMARYPREFIXACCESS); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { PrimaryPrefix(); label_12: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case 57: case 60: case 75: ; break; default: jj_la1[38] = jj_gen; break label_12; } PrimaryAccess(); } } catch (Throwable jjte001) { if (jjtc001) { jjtree.clearNodeScope(jjtn001); jjtc001 = false; } else { jjtree.popNode(); } if (jjte001 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte001;} } if (jjte001 instanceof ParseException) { {if (true) throw (ParseException)jjte001;} } {if (true) throw (Error)jjte001;} } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, jjtree.nodeArity() > 1); } } break; default: jj_la1[39] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } static final public void PrimaryPrefix() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IDENTIFIER: Identifier(); break; case 60: jj_consume_token(60); ExpressionList(); jj_consume_token(61); break; default: jj_la1[40] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } static final public void PrimaryAccess() throws ParseException { Token t; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case 60: t = jj_consume_token(60); ASTPrimaryAccess jjtn001 = new ASTPrimaryAccess(JJTPRIMARYACCESS); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { jjtree.closeNodeScope(jjtn001, true); jjtc001 = false; jjtn001.jjtSetValue(t.image); } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, true); } } expression(); jj_consume_token(61); break; case 75: t = jj_consume_token(75); ASTPrimaryAccess jjtn002 = new ASTPrimaryAccess(JJTPRIMARYACCESS); boolean jjtc002 = true; jjtree.openNodeScope(jjtn002); try { jjtree.closeNodeScope(jjtn002, true); jjtc002 = false; jjtn002.jjtSetValue(t.image); } finally { if (jjtc002) { jjtree.closeNodeScope(jjtn002, true); } } Identifier(); break; case 57: t = jj_consume_token(57); ASTPrimaryAccess jjtn003 = new ASTPrimaryAccess(JJTPRIMARYACCESS); boolean jjtc003 = true; jjtree.openNodeScope(jjtn003); try { jjtree.closeNodeScope(jjtn003, true); jjtc003 = false; jjtn003.jjtSetValue(t.image); } finally { if (jjtc003) { jjtree.closeNodeScope(jjtn003, true); } } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case NOT: case INTEGER_LITERAL: case FLOAT_LITERAL: case BOOLEAN_LITERAL: case NULL_LITERAL: case CHARACTER_LITERAL: case STRING_LITERAL: case IDENTIFIER: case 57: case 60: case 70: case 71: ExpressionList(); break; default: jj_la1[41] = jj_gen; ; } jj_consume_token(59); break; default: jj_la1[42] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } static final public void Name() throws ParseException { Identifier(); label_13: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case 75: ; break; default: jj_la1[43] = jj_gen; break label_13; } jj_consume_token(75); Identifier(); } } static final public void ExpressionList() throws ParseException { expression(); label_14: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case 58: ; break; default: jj_la1[44] = jj_gen; break label_14; } jj_consume_token(58); expression(); } } /**********************************************************Tokens************************************************************************/ /** An Identifier. */ static final public void Identifier() throws ParseException { /*@bgen(jjtree) Identifier */ ASTIdentifier jjtn000 = new ASTIdentifier(JJTIDENTIFIER); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000);Token t; try { t = jj_consume_token(IDENTIFIER); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; jjtn000.jjtSetValue(t.image); } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } } static final public void Literal() throws ParseException { Token t; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case INTEGER_LITERAL: ASTInteger jjtn001 = new ASTInteger(JJTINTEGER); boolean jjtc001 = true; jjtree.openNodeScope(jjtn001); try { t = jj_consume_token(INTEGER_LITERAL); } finally { if (jjtc001) { jjtree.closeNodeScope(jjtn001, true); } } jjtn001.jjtSetValue(t.image); break; case FLOAT_LITERAL: ASTFloat jjtn002 = new ASTFloat(JJTFLOAT); boolean jjtc002 = true; jjtree.openNodeScope(jjtn002); try { t = jj_consume_token(FLOAT_LITERAL); } finally { if (jjtc002) { jjtree.closeNodeScope(jjtn002, true); } } jjtn002.jjtSetValue(t.image); break; case CHARACTER_LITERAL: ASTChar jjtn003 = new ASTChar(JJTCHAR); boolean jjtc003 = true; jjtree.openNodeScope(jjtn003); try { t = jj_consume_token(CHARACTER_LITERAL); } finally { if (jjtc003) { jjtree.closeNodeScope(jjtn003, true); } } jjtn003.jjtSetValue(t.image); break; case BOOLEAN_LITERAL: ASTBoolean jjtn004 = new ASTBoolean(JJTBOOLEAN); boolean jjtc004 = true; jjtree.openNodeScope(jjtn004); try { t = jj_consume_token(BOOLEAN_LITERAL); } finally { if (jjtc004) { jjtree.closeNodeScope(jjtn004, true); } } jjtn004.jjtSetValue(t.image); break; case NULL_LITERAL: ASTNull jjtn005 = new ASTNull(JJTNULL); boolean jjtc005 = true; jjtree.openNodeScope(jjtn005); try { t = jj_consume_token(NULL_LITERAL); } finally { if (jjtc005) { jjtree.closeNodeScope(jjtn005, true); } } jjtn005.jjtSetValue(t.image); break; case STRING_LITERAL: ASTString jjtn006 = new ASTString(JJTSTRING); boolean jjtc006 = true; jjtree.openNodeScope(jjtn006); try { t = jj_consume_token(STRING_LITERAL); } finally { if (jjtc006) { jjtree.closeNodeScope(jjtn006, true); } } jjtn006.jjtSetValue(t.image); break; default: jj_la1[45] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } static private boolean jj_2_1(int xla) { jj_la = xla; jj_lastpos = jj_scanpos = token; try { return !jj_3_1(); } catch(LookaheadSuccess ls) { return true; } finally { jj_save(0, xla); } } static private boolean jj_2_2(int xla) { jj_la = xla; jj_lastpos = jj_scanpos = token; try { return !jj_3_2(); } catch(LookaheadSuccess ls) { return true; } finally { jj_save(1, xla); } } static private boolean jj_2_3(int xla) { jj_la = xla; jj_lastpos = jj_scanpos = token; try { return !jj_3_3(); } catch(LookaheadSuccess ls) { return true; } finally { jj_save(2, xla); } } static private boolean jj_2_4(int xla) { jj_la = xla; jj_lastpos = jj_scanpos = token; try { return !jj_3_4(); } catch(LookaheadSuccess ls) { return true; } finally { jj_save(3, xla); } } static private boolean jj_2_5(int xla) { jj_la = xla; jj_lastpos = jj_scanpos = token; try { return !jj_3_5(); } catch(LookaheadSuccess ls) { return true; } finally { jj_save(4, xla); } } static private boolean jj_2_6(int xla) { jj_la = xla; jj_lastpos = jj_scanpos = token; try { return !jj_3_6(); } catch(LookaheadSuccess ls) { return true; } finally { jj_save(5, xla); } } static private boolean jj_2_7(int xla) { jj_la = xla; jj_lastpos = jj_scanpos = token; try { return !jj_3_7(); } catch(LookaheadSuccess ls) { return true; } finally { jj_save(6, xla); } } static private boolean jj_3R_51() { if (jj_scan_token(NULL_LITERAL)) return true; return false; } static private boolean jj_3R_24() { if (jj_scan_token(58)) return true; if (jj_3R_23()) return true; return false; } static private boolean jj_3R_18() { if (jj_3R_21()) return true; if (jj_scan_token(60)) return true; if (jj_scan_token(61)) return true; return false; } static private boolean jj_3_3() { if (jj_3R_16()) return true; return false; } static private boolean jj_3R_50() { if (jj_scan_token(BOOLEAN_LITERAL)) return true; return false; } static private boolean jj_3R_27() { if (jj_3R_34()) return true; return false; } static private boolean jj_3R_49() { if (jj_scan_token(CHARACTER_LITERAL)) return true; return false; } static private boolean jj_3R_23() { Token xsp; xsp = jj_scanpos; if (jj_3_4()) { jj_scanpos = xsp; if (jj_3_5()) { jj_scanpos = xsp; if (jj_3R_29()) return true; } } return false; } static private boolean jj_3R_17() { if (jj_3R_21()) return true; if (jj_scan_token(60)) return true; if (jj_3R_26()) return true; return false; } static private boolean jj_3_4() { if (jj_3R_17()) return true; return false; } static private boolean jj_3_7() { Token xsp; xsp = jj_scanpos; if (jj_scan_token(68)) { jj_scanpos = xsp; if (jj_scan_token(69)) return true; } if (jj_3R_20()) return true; return false; } static private boolean jj_3R_48() { if (jj_scan_token(FLOAT_LITERAL)) return true; return false; } static private boolean jj_3R_20() { if (jj_3R_27()) return true; return false; } static private boolean jj_3R_47() { if (jj_scan_token(INTEGER_LITERAL)) return true; return false; } static private boolean jj_3R_45() { Token xsp; xsp = jj_scanpos; if (jj_3R_47()) { jj_scanpos = xsp; if (jj_3R_48()) { jj_scanpos = xsp; if (jj_3R_49()) { jj_scanpos = xsp; if (jj_3R_50()) { jj_scanpos = xsp; if (jj_3R_51()) { jj_scanpos = xsp; if (jj_3R_52()) return true; } } } } } return false; } static private boolean jj_3_6() { Token xsp; xsp = jj_scanpos; if (jj_scan_token(64)) { jj_scanpos = xsp; if (jj_scan_token(65)) { jj_scanpos = xsp; if (jj_scan_token(66)) { jj_scanpos = xsp; if (jj_scan_token(67)) return true; } } } if (jj_3R_19()) return true; return false; } static private boolean jj_3R_16() { if (jj_3R_23()) return true; Token xsp; while (true) { xsp = jj_scanpos; if (jj_3R_24()) { jj_scanpos = xsp; break; } } if (jj_scan_token(AS)) return true; if (jj_3R_25()) return true; return false; } static private boolean jj_3R_28() { if (jj_3R_23()) return true; return false; } static private boolean jj_3R_29() { if (jj_3R_21()) return true; return false; } static private boolean jj_3R_22() { if (jj_scan_token(57)) return true; Token xsp; xsp = jj_scanpos; if (jj_3R_28()) jj_scanpos = xsp; if (jj_scan_token(59)) return true; return false; } static private boolean jj_3R_21() { if (jj_scan_token(IDENTIFIER)) return true; return false; } static private boolean jj_3R_15() { if (jj_3R_21()) return true; Token xsp; while (true) { xsp = jj_scanpos; if (jj_3R_22()) { jj_scanpos = xsp; break; } } if (jj_scan_token(AS)) return true; if (jj_scan_token(FUNCTION)) return true; return false; } static private boolean jj_3R_19() { if (jj_3R_20()) return true; return false; } static private boolean jj_3_2() { if (jj_3R_15()) return true; return false; } static private boolean jj_3R_41() { if (jj_3R_19()) return true; return false; } static private boolean jj_3_1() { if (jj_3R_15()) return true; return false; } static private boolean jj_3R_39() { if (jj_3R_41()) return true; return false; } static private boolean jj_3R_36() { if (jj_3R_39()) return true; return false; } static private boolean jj_3_5() { if (jj_3R_18()) return true; return false; } static private boolean jj_3R_33() { if (jj_3R_36()) return true; return false; } static private boolean jj_3R_54() { if (jj_scan_token(60)) return true; return false; } static private boolean jj_3R_26() { Token xsp; xsp = jj_scanpos; if (jj_3R_32()) { jj_scanpos = xsp; if (jj_3R_33()) return true; } return false; } static private boolean jj_3R_32() { if (jj_scan_token(60)) return true; return false; } static private boolean jj_3R_53() { if (jj_3R_21()) return true; return false; } static private boolean jj_3R_46() { Token xsp; xsp = jj_scanpos; if (jj_3R_53()) { jj_scanpos = xsp; if (jj_3R_54()) return true; } return false; } static private boolean jj_3R_44() { if (jj_3R_46()) return true; return false; } static private boolean jj_3R_43() { if (jj_scan_token(57)) return true; return false; } static private boolean jj_3R_38() { if (jj_3R_40()) return true; return false; } static private boolean jj_3R_40() { Token xsp; xsp = jj_scanpos; if (jj_3R_42()) { jj_scanpos = xsp; if (jj_3R_43()) { jj_scanpos = xsp; if (jj_3R_44()) return true; } } return false; } static private boolean jj_3R_42() { if (jj_3R_45()) return true; return false; } static private boolean jj_3R_35() { Token xsp; xsp = jj_scanpos; if (jj_scan_token(14)) { jj_scanpos = xsp; if (jj_scan_token(16)) { jj_scanpos = xsp; if (jj_scan_token(13)) { jj_scanpos = xsp; if (jj_scan_token(15)) { jj_scanpos = xsp; if (jj_scan_token(45)) return true; } } } } return false; } static private boolean jj_3R_34() { Token xsp; xsp = jj_scanpos; if (jj_3R_37()) { jj_scanpos = xsp; if (jj_3R_38()) return true; } return false; } static private boolean jj_3R_37() { Token xsp; xsp = jj_scanpos; if (jj_scan_token(70)) { jj_scanpos = xsp; if (jj_scan_token(71)) { jj_scanpos = xsp; if (jj_scan_token(41)) return true; } } return false; } static private boolean jj_3R_31() { if (jj_3R_21()) return true; return false; } static private boolean jj_3R_52() { if (jj_scan_token(STRING_LITERAL)) return true; return false; } static private boolean jj_3R_25() { Token xsp; xsp = jj_scanpos; if (jj_3R_30()) { jj_scanpos = xsp; if (jj_3R_31()) return true; } return false; } static private boolean jj_3R_30() { if (jj_3R_35()) return true; return false; } static private boolean jj_initialized_once = false; /** Generated Token Manager. */ static public MyLangTokenManager token_source; static SimpleCharStream jj_input_stream; /** Current token. */ static public Token token; /** Next token. */ static public Token jj_nt; static private int jj_ntk; static private Token jj_scanpos, jj_lastpos; static private int jj_la; static private int jj_gen; static final private int[] jj_la1 = new int[46]; static private int[] jj_la1_0; static private int[] jj_la1_1; static private int[] jj_la1_2; static { jj_la1_init_0(); jj_la1_init_1(); jj_la1_init_2(); } private static void jj_la1_init_0() { jj_la1_0 = new int[] {0x800,0x800,0x9c9c0000,0x9c9c0000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x800,0x0,0x0,0x0,0x0,0x0,0x1e000,0x1e000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,}; } private static void jj_la1_init_1() { jj_la1_1 = new int[] {0x40,0x40,0x123f8200,0x123f8200,0x4,0x123f8200,0x100,0x200000,0x200000,0x200000,0x200000,0x2000000,0x4000000,0x200000,0x200000,0x200000,0x0,0x20,0x4000000,0x20,0x200000,0x10000000,0x202000,0x2000,0x4000,0x123f8200,0x1000,0x800,0xc0000000,0xc0000000,0x0,0x0,0x0,0x0,0x0,0x0,0x200,0x123f8200,0x12000000,0x123f8000,0x10200000,0x123f8200,0x12000000,0x0,0x4000000,0x1f8000,}; } private static void jj_la1_init_2() { jj_la1_2 = new int[] {0x0,0x0,0xc0,0xc0,0x0,0xc0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xc0,0x0,0x0,0x0,0x0,0xf,0x30,0xc0,0xc0,0x700,0x700,0xc0,0xc0,0x800,0x0,0x0,0xc0,0x800,0x800,0x0,0x0,}; } static final private JJCalls[] jj_2_rtns = new JJCalls[7]; static private boolean jj_rescan = false; static private int jj_gc = 0; /** Constructor with InputStream. */ public MyLang(java.io.InputStream stream) { this(stream, null); } /** Constructor with InputStream and supplied encoding */ public MyLang(java.io.InputStream stream, String encoding) { if (jj_initialized_once) { System.out.println("ERROR: Second call to constructor of static parser. "); System.out.println(" You must either use ReInit() or set the JavaCC option STATIC to false"); System.out.println(" during parser generation."); throw new Error(); } //jj_initialized_once = true; try { jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); } token_source = new MyLangTokenManager(jj_input_stream); token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 46; i++) jj_la1[i] = -1; for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); } /** Reinitialise. */ static public void ReInit(java.io.InputStream stream) { ReInit(stream, null); } /** Reinitialise. */ static public void ReInit(java.io.InputStream stream, String encoding) { try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); } token_source.ReInit(jj_input_stream); token = new Token(); jj_ntk = -1; jjtree.reset(); jj_gen = 0; for (int i = 0; i < 46; i++) jj_la1[i] = -1; for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); } /** Constructor. */ public MyLang(java.io.Reader stream) { if (jj_initialized_once) { System.out.println("ERROR: Second call to constructor of static parser. "); System.out.println(" You must either use ReInit() or set the JavaCC option STATIC to false"); System.out.println(" during parser generation."); throw new Error(); } jj_initialized_once = true; jj_input_stream = new SimpleCharStream(stream, 1, 1); token_source = new MyLangTokenManager(jj_input_stream); token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 46; i++) jj_la1[i] = -1; for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); } /** Reinitialise. */ static public void ReInit(java.io.Reader stream) { jj_input_stream.ReInit(stream, 1, 1); token_source.ReInit(jj_input_stream); token = new Token(); jj_ntk = -1; jjtree.reset(); jj_gen = 0; for (int i = 0; i < 46; i++) jj_la1[i] = -1; for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); } /** Constructor with generated Token Manager. */ public MyLang(MyLangTokenManager tm) { if (jj_initialized_once) { System.out.println("ERROR: Second call to constructor of static parser. "); System.out.println(" You must either use ReInit() or set the JavaCC option STATIC to false"); System.out.println(" during parser generation."); throw new Error(); } jj_initialized_once = true; token_source = tm; token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 46; i++) jj_la1[i] = -1; for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); } /** Reinitialise. */ public void ReInit(MyLangTokenManager tm) { token_source = tm; token = new Token(); jj_ntk = -1; jjtree.reset(); jj_gen = 0; for (int i = 0; i < 46; i++) jj_la1[i] = -1; for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); } static private Token jj_consume_token(int kind) throws ParseException { Token oldToken; if ((oldToken = token).next != null) token = token.next; else token = token.next = token_source.getNextToken(); jj_ntk = -1; if (token.kind == kind) { jj_gen++; if (++jj_gc > 100) { jj_gc = 0; for (int i = 0; i < jj_2_rtns.length; i++) { JJCalls c = jj_2_rtns[i]; while (c != null) { if (c.gen < jj_gen) c.first = null; c = c.next; } } } return token; } token = oldToken; jj_kind = kind; throw generateParseException(); } static private final class LookaheadSuccess extends java.lang.Error { } static final private LookaheadSuccess jj_ls = new LookaheadSuccess(); static private boolean jj_scan_token(int kind) { if (jj_scanpos == jj_lastpos) { jj_la--; if (jj_scanpos.next == null) { jj_lastpos = jj_scanpos = jj_scanpos.next = token_source.getNextToken(); } else { jj_lastpos = jj_scanpos = jj_scanpos.next; } } else { jj_scanpos = jj_scanpos.next; } if (jj_rescan) { int i = 0; Token tok = token; while (tok != null && tok != jj_scanpos) { i++; tok = tok.next; } if (tok != null) jj_add_error_token(kind, i); } if (jj_scanpos.kind != kind) return true; if (jj_la == 0 && jj_scanpos == jj_lastpos) throw jj_ls; return false; } /** Get the next Token. */ static final public Token getNextToken() { if (token.next != null) token = token.next; else token = token.next = token_source.getNextToken(); jj_ntk = -1; jj_gen++; return token; } /** Get the specific Token. */ static final public Token getToken(int index) { Token t = token; for (int i = 0; i < index; i++) { if (t.next != null) t = t.next; else t = t.next = token_source.getNextToken(); } return t; } static private int jj_ntk() { if ((jj_nt=token.next) == null) return (jj_ntk = (token.next=token_source.getNextToken()).kind); else return (jj_ntk = jj_nt.kind); } static private java.util.List<int[]> jj_expentries = new java.util.ArrayList<int[]>(); static private int[] jj_expentry; static private int jj_kind = -1; static private int[] jj_lasttokens = new int[100]; static private int jj_endpos; static private void jj_add_error_token(int kind, int pos) { if (pos >= 100) return; if (pos == jj_endpos + 1) { jj_lasttokens[jj_endpos++] = kind; } else if (jj_endpos != 0) { jj_expentry = new int[jj_endpos]; for (int i = 0; i < jj_endpos; i++) { jj_expentry[i] = jj_lasttokens[i]; } jj_entries_loop: for (java.util.Iterator<?> it = jj_expentries.iterator(); it.hasNext();) { int[] oldentry = (int[])(it.next()); if (oldentry.length == jj_expentry.length) { for (int i = 0; i < jj_expentry.length; i++) { if (oldentry[i] != jj_expentry[i]) { continue jj_entries_loop; } } jj_expentries.add(jj_expentry); break jj_entries_loop; } } if (pos != 0) jj_lasttokens[(jj_endpos = pos) - 1] = kind; } } /** Generate ParseException. */ static public ParseException generateParseException() { jj_expentries.clear(); boolean[] la1tokens = new boolean[76]; if (jj_kind >= 0) { la1tokens[jj_kind] = true; jj_kind = -1; } for (int i = 0; i < 46; i++) { if (jj_la1[i] == jj_gen) { for (int j = 0; j < 32; j++) { if ((jj_la1_0[i] & (1<<j)) != 0) { la1tokens[j] = true; } if ((jj_la1_1[i] & (1<<j)) != 0) { la1tokens[32+j] = true; } if ((jj_la1_2[i] & (1<<j)) != 0) { la1tokens[64+j] = true; } } } } for (int i = 0; i < 76; i++) { if (la1tokens[i]) { jj_expentry = new int[1]; jj_expentry[0] = i; jj_expentries.add(jj_expentry); } } jj_endpos = 0; jj_rescan_token(); jj_add_error_token(0, 0); int[][] exptokseq = new int[jj_expentries.size()][]; for (int i = 0; i < jj_expentries.size(); i++) { exptokseq[i] = jj_expentries.get(i); } return new ParseException(token, exptokseq, tokenImage); } /** Enable tracing. */ static final public void enable_tracing() { } /** Disable tracing. */ static final public void disable_tracing() { } static private void jj_rescan_token() { jj_rescan = true; for (int i = 0; i < 7; i++) { try { JJCalls p = jj_2_rtns[i]; do { if (p.gen > jj_gen) { jj_la = p.arg; jj_lastpos = jj_scanpos = p.first; switch (i) { case 0: jj_3_1(); break; case 1: jj_3_2(); break; case 2: jj_3_3(); break; case 3: jj_3_4(); break; case 4: jj_3_5(); break; case 5: jj_3_6(); break; case 6: jj_3_7(); break; } } p = p.next; } while (p != null); } catch(LookaheadSuccess ls) { } } jj_rescan = false; } static private void jj_save(int index, int xla) { JJCalls p = jj_2_rtns[index]; while (p.gen > jj_gen) { if (p.next == null) { p = p.next = new JJCalls(); break; } p = p.next; } p.gen = jj_gen + xla - jj_la; p.first = token; p.arg = xla; } static final class JJCalls { int gen; Token first; int arg; JJCalls next; } } <file_sep>/src/main/java/AST/ASTClassContent.java package AST; public class ASTClassContent extends ASTContent { SimpleNode sn; public SimpleNode getNode(){ return sn; } public ASTClassContent(SimpleNode simple){ this.type = TYPE; this.sn = simple; this.info_type = CLASS; } }<file_sep>/src/main/java/AST/ASTIdentifier.java package AST; /* Generated By:JJTree: Do not edit this line. ASTIdentifier.java Version 4.3 */ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=false,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ public class ASTIdentifier extends SimpleNode { public ASTIdentifier(int id) { super(id); } public ASTIdentifier(MyLang p, int id) { super(p, id); } public ASTContent code_gen(ASTContext context) { String name = jjtGetValue().toString(); ASTContent x = context.get(name); return (x != null)? x : new ASTContent(null, IDENTIFIER); } } /* JavaCC - OriginalChecksum=c0c7bd0653bfd8b3776156193ae4bf38 (do not edit this line) */
8d0dbb7843ba09ca9adc930e3c7024bad395f816
[ "Markdown", "Java" ]
12
Java
tjgykhulj/Compiler-llvm
73462f18545b98ef81de221145c98751b35ce4eb
0a869ad5683c039d57740ebe9d1b09f04d7b7c49
refs/heads/main
<repo_name>aghlam/cc-assignment02<file_sep>/ServerlessSetup/handler.ts import { APIGatewayEvent, Callback, Context, Handler } from "aws-lambda"; import { saveItemInDB, getItemFromDB, getCafeNameFromDB } from "./dynamodb-actions"; export const respond = (fulfillmentText: any, statusCode: number): any => { return { statusCode, body: JSON.stringify(fulfillmentText), headers: { "Access-Control-Allow-Credentials": true, "Access-Control-Allow-Origin": "*", "Content-Type": "application/json" } }; }; /** Save an item in cafesList */ export const saveCafe: Handler = async ( event: APIGatewayEvent, context: Context ) => { const incoming: { cafe_id: string, name: string; address: string } = JSON.parse(event.body); const { cafe_id, name, address } = incoming; try { await saveItemInDB(cafe_id, name, address); return respond({ created: incoming }, 201); } catch (err) { return respond(err, 400); } }; /** Get an item from the cafesList */ export const getCafe: Handler = async ( event: APIGatewayEvent, context: Context ) => { const cafe_id: string = event.pathParameters.cafe_id; try { const cafe = await getItemFromDB(cafe_id); return respond(cafe, 200); } catch (err) { return respond(err, 404); } }; /** Get an item from the cafesList */ export const getCafeName: Handler = async ( event: APIGatewayEvent, context: Context ) => { const name: string = event.pathParameters.name; try { const cafe = await getCafeNameFromDB(name); return respond(cafe, 200); } catch (err) { return respond(err, 404); } }; <file_sep>/ServerlessSetup/dynamodb-actions/index.ts import * as AWS from "aws-sdk"; import * as uuid from "uuid/v4"; const dynamoDB = new AWS.DynamoDB.DocumentClient(); /** put a item in the db table */ export function saveItemInDB(cafe_id:string, name: string, address: string) { const params = { TableName: "cafesList", Item: { cafe_id, name, address } }; return dynamoDB .put(params) .promise() .then(res => res) .catch(err => err); } /** get a item from the db table */ export function getItemFromDB(cafe_id: string) { const params = { TableName: "cafesList", Key: { cafe_id } }; return dynamoDB .get(params) .promise() .then(res => res.Item) .catch(err => err); } export function getCafeNameFromDB(name: string) { const params = { TableName: "cafesList", Key: { name } }; return dynamoDB .get(params) .promise() .then(res => res.Item) .catch(err => err); } <file_sep>/reactfrontend/src/components/Login/LoginHooks.js import React from 'react'; import { useGoogleLogin } from 'react-google-login'; // refresh token import { refreshTokenSetup } from './refreshToken'; const clientId = '927460782630-si9oujoue6sd7rhlm546cai5e38g5sct.apps.googleusercontent.com' function LoginHooks() { const onSuccess = (res) => { localStorage.setItem('googleUser', res.profileObj.name) localStorage.setItem('isSignedIn', true) alert( `Logged in successfully welcome ${res.profileObj.name}.` ); refreshTokenSetup(res); window.location.reload(); }; const onFailure = (res) => { console.log('Login failed: res:', res); alert( `Failed to login` ); }; const { signIn } = useGoogleLogin({ onSuccess, onFailure, clientId, isSignedIn: true, accessType: 'offline', }); return ( <button type='button' className="btn btn-outline-light" onClick={signIn} > <img src="https://cc-assignment02-bucket.s3.amazonaws.com/images/google.svg" height='40' width='40' alt="google login" className="icon" /> <span className="buttonText">Sign in with Google</span> </button> ); } export default LoginHooks;<file_sep>/reactfrontend/src/App.js import {BrowserRouter as Router, Switch, Route} from 'react-router-dom' import './App.css'; import 'bootstrap/dist/css/bootstrap.min.css'; import Navigation from './components/Nav/Nav' import Home from './components/Home/Home' import About from './components/About/About' import Cafe from './components/Cafe/Cafe' // import CafePage from './components/Cafe/CafePage' import GMap from './components/GMap/GMap' function App() { return ( <Router> <div className="App"> <Navigation /> <Switch> <Route exact path='/' component={Home} /> <Route path='/about' component={About} /> <Route path='/cafe/:cafe_id' component={Cafe} /> <Route path='/find' component={GMap} /> </Switch> </div> </Router> ); } export default App; <file_sep>/expressbackend/app.js const express = require('express') var request = require('request') const app = express() const port = 5000 app.get('/', (req, res) => { res.send('Hello World!') }) app.get('/getcafebyid/:id', (req, res) => { var cafe_id = req.params.id request('https://xdhg51t95l.execute-api.ap-southeast-2.amazonaws.com/dev/cafe/' + cafe_id, function (error, response, body) { if (!error && response.statusCode == 200) { console.log(body) // Print object res.send(body); } }) }) app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`) })<file_sep>/reactfrontend/src/components/About/About.js import React from 'react' import './About.css' import { Container, Row, Col } from 'react-bootstrap'; function About() { return ( <div> <Container fluid className='about-background'> <Row className='about-row align-items-center'> <Col md={3}/> <Col sm={12} md={6}> <h1 className='display-4 text-light'>Cafe Crusaders is a small time web application created by <NAME> and <NAME> as a university assignment. We aim to assist all coffee lovers on their crusade in finding the best coffee available in their area.</h1> </Col> <Col md={3}/> </Row> </Container> </div> ) } export default About <file_sep>/reactfrontend/src/components/Login/LogoutHooks.js import React from 'react'; import { useGoogleLogout } from 'react-google-login'; const clientId = '927460782630-si9oujoue6sd7rhlm546cai5e38g5sct.apps.googleusercontent.com' const ACCESS_KEY = process.env.REACT_APP_AWS_ACCESS_KEY const SECRET_KEY = process.env.REACT_APP_AWS_SECRET_KEY //Creation of logger for LoginHooks.js const { Logger } = require('aws-cloudwatch-log-browser') const config = { logGroupName: 'cc-a2-logger', logStreamName: 'cc-a2-login-stream', region: 'us-east-1', accessKeyId: ACCESS_KEY, secretAccessKey: SECRET_KEY, uploadFreq: 2000, local: false } const logger = new Logger(config) const LogoutHooks = () => { const onLogoutSuccess = (response) => { alert('Logged out Successfully') localStorage.removeItem('googleUser') localStorage.removeItem('isSignedIn') window.location.reload(); } const onFailure = () => { console.log('Handle failure cases') } const { signOut } = useGoogleLogout({ clientId, onLogoutSuccess, onFailure, }) const logUser = () => { logger.log("User Logged in: " + localStorage.getItem('googleUser')); } return ( <button type='button' className="btn btn-outline-light" onClick={signOut} onLoad={logUser}> <img src="https://cc-assignment02-bucket.s3.amazonaws.com/images/google.svg" height='40' width='40' alt="google login" className="icon"></img> <span className="buttonText">Sign out</span> </button> ) } export default LogoutHooks;
eddd6f73146dc07ad76451154175d5a8f0ad6745
[ "JavaScript", "TypeScript" ]
7
TypeScript
aghlam/cc-assignment02
064ec7bba6a3b92836fc0b32ece1ab0f7a5614a2
d995fd64f33e98aa2b4b9e007715e4103f764c31
refs/heads/dev
<repo_name>CuriouseNick/rain-project-2<file_sep>/README.md # HomeVenience Realtime data app using arduino mimicking IoT devices ![alt text](/public/images/loginpage.png) ![alt text](/public/images/mainapp.png) ## App located in Github [ https://github.com/CuriouseNick/rain-project-2]( https://github.com/CuriouseNick/rain-project-2) ## Getting Started To download the same packages run after forking or cloning the repository. ``` npm install ``` * You must set up your own database configuration with your own environment variables. ### Prerequisites - Visual Studio Code (Or any other editor) - Express.js - Node.js - bodyParser - sequelize - MySQL - Ardunio Hardware (Temp sensor, LED light) - Johnny Five - PubNub - Eon - Firmata Software - Materialize - Passport ## Authors <NAME> <NAME> <NAME> <NAME> ## License This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details ## Acknowledgments Northwestern University Coding Bootcamp All Friends Involved<file_sep>/public/js/graph.js $(document).ready(function(){ // Temperature graph code goes here var pubnub = new PubNub({ publishKey: '<KEY>', subscribeKey: '<KEY>' }); var lightObject; var tempObject; var tempSelection; var fanChoice; var currentSwitch = "off"; $("input[name='group1']").on('change', function() { fanChoice = $("input[name='group1']:checked").val(); console.log(fanChoice); }); $("#tempOptions").on("change", function() { tempSelection = $(tempOptions).val(); console.log(tempSelection); }); $(".switchBtnOn").click(function(){ if (currentSwitch == "on") { console.log("switch is already on"); } else if (currentSwitch == "off") { $(".bulb").toggle(); currentSwitch = $(this).val(); console.log(currentSwitch); } lightObject = { lightStatus: "on" } $.post("/api/dataLight", lightObject, function(data) { console.log(data); }); }); $(".switchBtnOff").click(function(){ if (currentSwitch == "off") { console.log("switch is already off"); } else if (currentSwitch == "on") { $(".bulb").toggle(); currentSwitch = $(this).val(); console.log(currentSwitch); } lightObject = { lightStatus: "off" } $.post("/api/dataLight", lightObject, function(data) { console.log(data); }); }); eon.chart({ channels: ['eon-spline'], history: true, flow: true, pubnub: pubnub, generate: { bindto: '#chart', data: { labels: false } } }); setInterval(function(){ $.get("/api/temp", function(data) { console.log(data); tempObject = data; }); if (tempObject.temperature > tempSelection && fanChoice == "ac") { $("#tempStatus").text("AC is on"); } else if (tempObject.temperature <= tempSelection && tempSelection != undefined && fanChoice == "ac") { $("#tempStatus").text("Temperature set at " + tempSelection + " F"); } else if (tempObject.temperature < tempSelection && fanChoice == "heat") { $("#tempStatus").text("Heat is on"); } else if (tempObject.temperature >= tempSelection && tempSelection != undefined && fanChoice == "heat") { $("#tempStatus").text("Temperature set at " + tempSelection + " F"); } pubnub.publish({ channel: 'eon-spline', message: { eon: { "temperature": tempObject.temperature } } }); }, 2000); // Temperature Gauge code goes here eon.chart({ pubnub: pubnub, channels: ['eon-gauge'], generate: { bindto: '#gauge', data: { type: 'gauge', }, gauge: { label: { format: function(value, ratio){ return value; } }, min: 0, max: 100 }, color: { pattern: ['#FF0000', '#F6C600', '#60B044'], threshold: { values: [30, 60, 90] } } } }); setInterval(function(){ pubnub.publish({ channel: 'eon-gauge', message: { eon: { "temperature": tempObject.temperature } } }) }, 2000); /* --------------------------------------------------------------------- */ }); <file_sep>/server.js var express = require("express"); var bodyParser = require("body-parser"); // ****************************************************************************** var app = express(); var passport = require('passport') var session = require('express-session') var env = require('dotenv').load() var exphbs = require('express-handlebars') var PORT = process.env.PORT || 8080; // Sets up the Express app to handle data parsing // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: true })); // parse application/json app.use(bodyParser.json()); // Static directory app.use(express.static("public")); // For Passport app.use(session({ secret: 'keyboard cat', resave: true, saveUninitialized: true })); // session secret app.use(passport.initialize()); app.use(passport.session()); // persistent login sessions //For Handlebars app.set('views', './auth/views') app.engine('hbs', exphbs({ extname: '.hbs' })); app.set('view engine', '.hbs'); app.get('/', function(req, res) { res.sendFile(path.join(__dirname, "../public/login.html")); }); //Models var models = require("./models"); // Routes // ============================================================= require("./routes/apiRoutes.js")(app); var authRoute = require('./routes/auth.js')(app, passport); // console.log('this is our models!!!!!', models); //load passport strategies require('./config/passport/passport.js')(passport, models.user); //Sync Database models.sequelize.sync().then(function () { console.log('Nice! Database looks fine') }).catch(function (err) { console.log(err, "Something went wrong with the Database Update!") }); require('./app.js')(app); app.listen(8080, function (err) { if (!err) console.log("Site is live"); else console.log(err) }); <file_sep>/config/config.js require('dotenv').config() var config = { "development": { "username": "root", "password": <PASSWORD>, "database": "sequelize_passport", "host": "127.0.0.1", "port": 3306, "dialect": "mysql", pool: { max: 5, min: 0, idle: 20000, acquire: 20000 } }, "test": { "username": "root", "password": <PASSWORD>, "database": "database_test", "host": "127.0.0.1", "port": 3306, "dialect": "mysql" }, "production": { "username": "root", "password": <PASSWORD>, "database": "database_production", "host": "127.0.0.1", "port": 3306, "dialect": "mysql" } } module.exports = config;<file_sep>/models/temperature.js 'use strict' module.exports = function(sequelize, DataTypes) { const temp = sequelize.define("temp", { id: { type: DataTypes.UUID, primaryKey: true, defaultValue: DataTypes.UUIDV4 }, created_at: { type: DataTypes.DATE, allowNull: false }, temperature: { type: DataTypes.STRING, allowNull: false } }); return temp; };
d4b0fb828691d4166f2894bb8a413422e38a0e35
[ "Markdown", "JavaScript" ]
5
Markdown
CuriouseNick/rain-project-2
b838159f6e80974137ca399d84261a38c32c4588
1a0aa3781167186399135afb6950aac6c3f802aa
refs/heads/master
<file_sep>## Usage ```js var deleteEmpty = require('{%= name %}'); ``` ## API Given the following directory structure, the **highlighted directories** would be deleted. ```diff foo/ └─┬ a/ - ├── aa/ ├── bb/ │ └─┬ bbb/ │ ├── one.txt │ └── two.txt - ├── cc/ - ├ b/ - └ c/ ``` **async** ```js deleteEmpty('foo/', function(err, deleted) { console.log(deleted); //=> ['foo/aa/', 'foo/a/cc/', 'foo/b/', 'foo/c/'] }); ``` **sync** ```js deleteEmpty.sync('foo/'); ``` As with the async method, an array of deleted directories is returned, in case you want to log them out or provide some kind of feedback to the user. ```js var deleted = deleteEmpty.sync('foo/'); console.log(deleted); //=> ['foo/aa/', 'foo/a/cc/', 'foo/b/', 'foo/c/'] ``` <file_sep>/*! * delete-empty <https://github.com/jonschlinkert/delete-empty> * * Copyright (c) 2015, 2017, <NAME>. * Released under the MIT License. */ 'use strict'; var fs = require('fs'); var path = require('path'); var relative = require('relative'); var extend = require('extend-shallow'); var series = require('async-each-series'); var rimraf = require('rimraf'); var ok = require('log-ok'); function deleteEmpty(cwd, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } if (typeof callback !== 'function') { throw new TypeError('expected callback to be a function'); } var dirname = path.resolve(cwd); var opts = extend({}, options); var acc = []; function remove(filepath, cb) { var dir = path.resolve(filepath); if (dir.indexOf(dirname) !== 0) { cb(); return; } if (!isDirectory(dir)) { cb(); return; } fs.readdir(dir, function(err, files) { if (err) { cb(err); return; } if (isEmpty(files, opts.filter)) { rimraf(dir, function(err) { if (err) { cb(err); return; } // display relative path for readability var rel = relative(dir); if (opts.verbose !== false) { ok('deleted:', rel); } acc.push(rel); remove(path.dirname(dir), cb); }); } else { series(files, function(file, next) { remove(path.resolve(dir, file), next); }, cb); } }); } remove(dirname, function(err) { callback(err, acc); }); } deleteEmpty.sync = function(cwd, options) { var dirname = path.resolve(cwd); var opts = extend({}, options); var acc = []; function remove(filepath) { var dir = path.resolve(filepath); if (dir.indexOf(dirname) !== 0) { return; } if (isDirectory(dir)) { var files = fs.readdirSync(dir); if (isEmpty(files, opts.filter)) { rimraf.sync(dir); var rel = relative(dir); if (opts.verbose !== false) { ok('deleted:', rel); } acc.push(rel); remove(path.dirname(dir)); } else { for (var i = 0; i < files.length; i++) { remove(path.resolve(dir, files[i])); } } } } remove(dirname); return acc; }; function isDirectory(filepath) { var stat = tryStat(filepath); if (stat) { return stat.isDirectory(); } } function tryStat(filepath) { try { return fs.statSync(filepath); } catch (err) {} } /** * Returns true if the file is a garbage file that can be deleted */ function isGarbageFile(filename) { return /(?:Thumbs\.db|\.DS_Store)$/i.test(filename); } /** * Return true if the given `files` array has zero length or only * includes unwanted files. */ function isEmpty(files, filterFn) { var filter = filterFn || isGarbageFile; for (var i = 0; i < files.length; ++i) { if (!filter(files[i])) { return false; } } return true; } /** * Expose deleteEmpty */ module.exports = deleteEmpty; <file_sep>#!/usr/bin/env node var deleteEmpty = require('..'); var argv = process.argv.slice(2); var cwd = argv[0] || process.cwd(); deleteEmpty(cwd, function(err) { if (err) { console.error(err); process.exit(1); } console.log('done'); process.exit(); }); <file_sep>'use strict'; require('mocha'); var fs = require('fs'); var path = require('path'); var assert = require('assert'); var rimraf = require('rimraf'); var copy = require('./support/copy'); var deleteEmpty = require('..'); var tests = path.join.bind(path, __dirname); var fixtures = path.join.bind(path, tests('fixtures')); describe('deleteEmpty', function() { beforeEach(function(cb) { copy('test/fixtures', 'test/temp', cb); }); afterEach(function(cb) { rimraf('test/temp', cb); }); describe('async', function(cb) { it('should delete the given cwd if empty', function(cb) { deleteEmpty('test/temp/b', function(err, deleted) { if (err) { cb(err); return; } fs.exists('test/temp/b', function(exists) { assert(!exists); cb(); }); }); }); it('should delete nested directories', function(cb) { deleteEmpty('test/temp', function(err, deleted) { if (err) { cb(err); return; } assert(!fs.existsSync('test/temp/a/aa/aaa')); assert(!fs.existsSync('test/temp/b')); assert(!fs.existsSync('test/temp/c')); cb(); }); }); it('should return the array of deleted directories', function(cb) { deleteEmpty('test/temp', function(err, deleted) { if (err) { cb(err); return; } assert.deepEqual(deleted.sort(), [ 'test/temp/a/aa/aaa/aaaa', 'test/temp/a/aa/aaa', 'test/temp/b', 'test/temp/c' ].sort()); cb(); }); }); }); describe('sync', function(cb) { it('should delete the given cwd if empty', function(cb) { deleteEmpty.sync('test/temp/b'); assert(!fs.existsSync('test/temp/b')); cb(); }); it('should delete nested directories', function(cb) { deleteEmpty.sync('test/temp'); assert(!fs.existsSync('test/temp/a/aa/aaa/aaaa')); assert(!fs.existsSync('test/temp/a/aa/aaa')); assert(!fs.existsSync('test/temp/b')); assert(!fs.existsSync('test/temp/c')); cb(); }); it('should return the array of deleted directories', function(cb) { var deleted = deleteEmpty.sync('test/temp'); assert.deepEqual(deleted.sort(), [ 'test/temp/a/aa/aaa/aaaa', 'test/temp/a/aa/aaa', 'test/temp/b', 'test/temp/c' ].sort()); cb(); }); }); }); <file_sep># delete-empty [![NPM version](https://img.shields.io/npm/v/delete-empty.svg?style=flat)](https://www.npmjs.com/package/delete-empty) [![NPM monthly downloads](https://img.shields.io/npm/dm/delete-empty.svg?style=flat)](https://npmjs.org/package/delete-empty) [![NPM total downloads](https://img.shields.io/npm/dt/delete-empty.svg?style=flat)](https://npmjs.org/package/delete-empty) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/delete-empty.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/delete-empty) > Recursively delete all empty folders in a directory and child directories. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save delete-empty ``` ## Usage ```js var deleteEmpty = require('delete-empty'); ``` ## API Given the following directory structure, the **highlighted directories** would be deleted. ```diff foo/ └─┬ a/ - ├── aa/ ├── bb/ │ └─┬ bbb/ │ ├── one.txt │ └── two.txt - ├── cc/ - ├ b/ - └ c/ ``` **async** ```js deleteEmpty('foo/', function(err, deleted) { console.log(deleted); //=> ['foo/aa/', 'foo/a/cc/', 'foo/b/', 'foo/c/'] }); ``` **sync** ```js deleteEmpty.sync('foo/'); ``` As with the async method, an array of deleted directories is returned, in case you want to log them out or provide some kind of feedback to the user. ```js var deleted = deleteEmpty.sync('foo/'); console.log(deleted); //=> ['foo/aa/', 'foo/a/cc/', 'foo/b/', 'foo/c/'] ``` ## About ### Related projects * [copy](https://www.npmjs.com/package/copy): Copy files or directories using globs. | [homepage](https://github.com/jonschlinkert/copy "Copy files or directories using globs.") * [delete](https://www.npmjs.com/package/delete): Delete files and folders and any intermediate directories if they exist (sync and async). | [homepage](https://github.com/jonschlinkert/delete "Delete files and folders and any intermediate directories if they exist (sync and async).") * [fs-utils](https://www.npmjs.com/package/fs-utils): fs extras and utilities to extend the node.js file system module. Used in Assemble and… [more](https://github.com/assemble/fs-utils) | [homepage](https://github.com/assemble/fs-utils "fs extras and utilities to extend the node.js file system module. Used in Assemble and many other projects.") * [matched](https://www.npmjs.com/package/matched): Adds array support to node-glob, sync and async. Also supports tilde expansion (user home) and… [more](https://github.com/jonschlinkert/matched) | [homepage](https://github.com/jonschlinkert/matched "Adds array support to node-glob, sync and async. Also supports tilde expansion (user home) and resolving to global npm modules.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 22 | [jonschlinkert](https://github.com/jonschlinkert) | | 1 | [svenschoenung](https://github.com/svenschoenung) | | 1 | [vpalmisano](https://github.com/vpalmisano) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **<NAME>** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [<NAME>](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.5.0, on April 07, 2017._
b44d5daf35873732d13430caace0a6000fcc1039
[ "Markdown", "JavaScript" ]
5
Markdown
treble-snake/delete-empty
1a563965e6a7be9e29a523bcbcab3f8bec93ed61
7bec5d9c32ffa936be391dfe393c8c274313f90b
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using CorrugatedIron.Config; namespace RiakIronBrowser { public class NodeConfiguration { IRiakNodeConfiguration localNodeConfig = null; public NodeConfiguration(IRiakNodeConfiguration config) { if (config != null) localNodeConfig = config; else localNodeConfig = new RiakNodeConfiguration(); } public IRiakNodeConfiguration Node { get { return localNodeConfig; } set { localNodeConfig = value; } } public override string ToString() { StringBuilder builder = new StringBuilder(); builder.Append(localNodeConfig.Name); builder.Append(" - "); builder.Append(localNodeConfig.HostAddress); builder.Append(":"); builder.Append(localNodeConfig.PbcPort); //builder.Append(" "); //builder.Append(localNodeConfig.RestScheme); //builder.Append(":"); //builder.Append(localNodeConfig.RestPort); return builder.ToString(); } } } <file_sep>using CorrugatedIron; using CorrugatedIron.Config; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace RiakIronBrowser { /// <summary> /// Interaction logic for SettingsWindow.xaml /// </summary> public partial class SettingsWindow : Window { Configuration exeConfiguration = null; IRiakClusterConfiguration config = null; public SettingsWindow() { InitializeComponent(); exeConfiguration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); config = (IRiakClusterConfiguration)exeConfiguration.GetSection("riakConfig"); LoadFromConfig(); } private void LoadFromConfig() { NodePoolTimeTextBox.Text = config.NodePollTime.ToString(); RetryCountTextBox.Text = config.DefaultRetryCount.ToString(); RetryWaitTimeTextBox.Text = config.DefaultRetryWaitTime.ToString(); foreach (IRiakNodeConfiguration node in config.RiakNodes) NodeListBox.Items.Add(new NodeConfiguration(node)); } private void SaveButton_Click(object sender, RoutedEventArgs e) { exeConfiguration.Save(); Close(); } private void AddNodeButton_Click(object sender, RoutedEventArgs e) { NodeWindow window = new NodeWindow(null); window.ShowDialog(); if (window.Node != null) NodeListBox.Items.Add(window.Node); } private void RemoveNodeButton_Click(object sender, RoutedEventArgs e) { NodeListBox.Items.Remove(NodeListBox.SelectedItem); } private void EditNodeButton_Click(object sender, RoutedEventArgs e) { NodeWindow window = new NodeWindow((NodeConfiguration)NodeListBox.SelectedItem); window.ShowDialog(); if (window.Node != null) NodeListBox.SelectedItem = window.Node; NodeListBox.Items.Refresh(); } private void NodeListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (NodeListBox.SelectedIndex >= 0) { RemoveNodeButton.IsEnabled = true; EditNodeButton.IsEnabled = true; } else { RemoveNodeButton.IsEnabled = false; EditNodeButton.IsEnabled = false; } } } } <file_sep>using CorrugatedIron; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RiakIronBrowser { public class RiakBase { IRiakClient client = null; public RiakBase() { var cluster = RiakCluster.FromConfig("riakConfig"); client = cluster.CreateClient(); } public IList<string> GetAllBuckets() { var result = client.ListBuckets(); return result.Value.ToList(); } public IList<string> GetAllKeys(string bucket) { var result = client.ListKeys(bucket); return result.Value.ToList(); } /// <summary> /// Deletes a complete bucket. Actually deletes all the keys in the bucket effectively deleting said bucket. /// </summary> /// <param name="bucket">Name of bucket to delete.</param> /// <returns>Errors returned</returns> public IList<string> DeleteBucket(string bucket) { var results = client.DeleteBucket(bucket); IList<string> errorList = new List<string>(); foreach (var result in results) if (!result.IsSuccess) errorList.Add(result.ErrorMessage); return errorList; } public void DeleteKey(string bucket, string key) { var result = client.Delete(bucket, key); if (!result.IsSuccess) throw new Exception(result.ErrorMessage); } } } <file_sep>RiakIronBrowser =============== Simple Browser for Riak written in C# utilizing CorrugatedIron. <file_sep>using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; namespace RiakIronBrowser { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { RiakBase riak = null; public MainWindow() { InitializeComponent(); riak = new RiakBase(); LoadBucketList(); } private void BucketLoad_Click(object sender, RoutedEventArgs e) { if (BucketListBox.SelectedIndex >= 0) { LoadKeyList(); } } private void DeleteBucketButton_Click(object sender, RoutedEventArgs e) { if (BucketListBox.SelectedIndex >= 0) { IList<string> errors = riak.DeleteBucket(GetBucket()); StringBuilder builder = new StringBuilder("Following errors occured:"); foreach (string error in errors) builder.AppendLine(error); MessageBox.Show(builder.ToString()); LoadBucketList(); } } private void LoadBucketList() { IList<string> list = riak.GetAllBuckets(); BucketListBox.Items.Clear(); foreach (string bucket in list) BucketListBox.Items.Add(bucket); } private void LoadKeyList() { IList<string> keyList = riak.GetAllKeys(GetBucket()); CountLabel.Content = "Count: " + keyList.Count(); KeyListBox.Items.Clear(); foreach (string key in keyList) KeyListBox.Items.Add(key); } private string GetBucket() { return (string)BucketListBox.SelectedValue; } private string GetKey() { return (string)KeyListBox.SelectedValue; } private void DeleteKeyButton_Click(object sender, RoutedEventArgs e) { if ((KeyListBox.SelectedIndex >= 0) && (BucketListBox.SelectedIndex >= 0)) { riak.DeleteKey(GetBucket(), GetKey()); LoadKeyList(); } } private void SettingsButton_Click(object sender, RoutedEventArgs e) { SettingsWindow window = new SettingsWindow(); window.ShowDialog(); } } } <file_sep>using CorrugatedIron.Config; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace RiakIronBrowser { /// <summary> /// Interaction logic for NodeWindow.xaml /// </summary> public partial class NodeWindow : Window { NodeConfiguration localNode = null; bool isValid = false; public NodeWindow(NodeConfiguration node) { InitializeComponent(); if (node != null) localNode = node; else localNode = new NodeConfiguration(null); PopulateFields(); } private void PopulateFields() { NameTextBox.Text = localNode.Node.Name; AddressTextBox.Text = localNode.Node.HostAddress; PbcPortTextBox.Text = localNode.Node.PbcPort.ToString(); RestSchemeTextBox.Text = localNode.Node.RestScheme; RestPortTextBox.Text = localNode.Node.RestPort.ToString(); PoolSizeTextBox.Text = localNode.Node.PoolSize.ToString(); } private void SaveFields() { RiakNodeConfiguration newNode = new RiakNodeConfiguration(); newNode.Name = NameTextBox.Text; newNode.HostAddress = AddressTextBox.Text; newNode.PbcPort = int.Parse(PbcPortTextBox.Text); newNode.RestScheme = RestSchemeTextBox.Text; newNode.RestPort = int.Parse(RestPortTextBox.Text); newNode.PoolSize = int.Parse(PoolSizeTextBox.Text); localNode.Node = newNode; } public NodeConfiguration Node { get { return localNode; } } private void DoneButton_Click(object sender, RoutedEventArgs e) { try { SaveFields(); isValid = true; } catch (Exception) { } Close(); } private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { if(!isValid) localNode = null; } } }
8f06c1410b47edcd628e056b2576aacf0960656d
[ "Markdown", "C#" ]
6
C#
AlphaCluster/RiakIronBrowser
3a616a74d2ecc86ff9125bb56480627b1e96f5c4
b6d198feac502ac49b88e88fc826106a014d928e
refs/heads/master
<file_sep>############################################################################### # BSD 3-Clause License # # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Author & Contact: <NAME> (<EMAIL>) ############################################################################### import torch import torch.nn as nn import torch.nn.functional as F class PartialConv2d(nn.Conv2d): r""" Args: multi_channel (bool, optional): Mask each channel. Default: ``False`` return_mask (bool, optional): Return mask tensor. Default: ``False`` """ def __init__(self, *args, multi_channel=False, return_mask=False, **kwargs): super().__init__(*args, **kwargs) # whether the mask is multi-channel or not self.multi_channel = multi_channel self.return_mask = return_mask if self.multi_channel: mask_weight = torch.ones_like(self.weight) else: mask_weight = torch.ones(1, 1, *self.weight.shape[2:]) self.register_buffer('mask_weight', mask_weight) self.slide_winsize = torch.prod(torch.tensor(self.mask_weight.shape[1:])).item() self.last_size = None self.mask_output = None self.mask_ratio = None def forward(self, input, mask=None): input_size = input.shape[2:] if mask is not None or self.last_size != input_size: self.last_size = input_size with torch.no_grad(): if mask is None: # if mask is not provided, create a mask if self.multi_channel: mask = torch.ones_like(input) else: mask = torch.ones(1, 1, *input_size).to(input) mask_count = F.conv2d(mask, self.mask_weight, bias=None, stride=self.stride, padding=self.padding, dilation=self.dilation, groups=1) self.mask_output = torch.gt(mask_count, 0).to(mask_count) self.mask_ratio = torch.mul(self.slide_winsize / mask_count.add(1e-8), self.mask_output) if self.mask_output.type() != input.type() or self.mask_ratio.type() != input.type(): self.mask_output = self.mask_output.to(input) self.mask_ratio = self.mask_ratio.to(input) output = F.conv2d(torch.mul(input, mask) if mask is not None else input, self.weight, bias=None, stride=self.stride, padding=self.padding, dilation=self.dilation, groups=self.groups) output = torch.mul(output, self.mask_ratio) if self.bias is not None: output = output + self.bias.view(1, self.out_channels, *(1,)*len(input_size)) output = torch.mul(output, self.mask_output) if self.return_mask: return output, self.mask_output else: return output
b188a8a62bbfd472c082ba1733b78e7a7adb68c2
[ "Python" ]
1
Python
ttivy/partialconv
64caeb0b04caa9b1b7e4bedacdb7967a6294a256
89412a10327caeeeaad77b7dab2a6e9bb9ebedc6
refs/heads/master
<repo_name>BasavarajBalte/Java8<file_sep>/src/com/java8/Learn.java package com.java8; import java.awt.List; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.OptionalInt; import java.util.Spliterator; import java.util.function.IntPredicate; import java.util.function.IntToDoubleFunction; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import java.util.stream.StreamSupport; public class Learn { public static void main(String[] args) { /* * int[] number = { 1, 2, 3, 4, 5, 6, 7 }; int min = * IntStream.of(number).distinct().sorted().limit(3).sum(); * System.out.println(min); IntStream.range(1, * 100).forEach(System.out::println); IntStream.range(50, * 100).boxed().collect(Collectors.toList()); * * * Predicate<Integer> predicate = new Predicate<Integer>() { * * @Override public boolean test(Integer t) { * * return t > 4; } }; * * * IntPredicate predicate = new IntPredicate() { * * @Override public boolean test(int value) { * * return value > 4; } }; * * // IntToDoubleFunction * IntStream.of(number).filter(predicate).forEach(System.out::println); * * java.util.List<Person> person = new ArrayList<Person>(); person.add(new * Person(1, "rbc")); person.add(new Person(3, "abc")); person.add(new Person(2, * "xc")); person.forEach(e -> { System.out.println(e.getName()); }); * System.out.println("0-----------------------"); * person.sort(Comparator.comparing(Person::getName).thenComparing(Person::getId * )); person.forEach(e -> { System.out.println(e.getName()); }); */ Path file = Paths.get("pepole.txt"); try (Stream<String> lines = Files.lines(file)) { Spliterator<String> lineSpliterator = lines.spliterator(); Spliterator<Person> pepolesp = new PersonSpliterator(lineSpliterator); Stream<Person> pepole = StreamSupport.stream(pepolesp, false); pepole.forEach(System.out::println); } catch (Exception e2) { // TODO: handle exception } } }
c81cffe1a059dfd933705d69d466a35d7defd355
[ "Java" ]
1
Java
BasavarajBalte/Java8
6396a9fa5e3215c8fe8acfa453af09462d0824d1
094978e3f0d5680f6ed43dc0ba7c795a2465090e
refs/heads/master
<file_sep><!DOCTYPE html> <html id='en' lang='en'> <head> <title>xxx nude madhori,katrina,karishma pics fock photos</title> <link href="ssoistoineypoagh.css" media="screen" rel="stylesheet" type="text/css"/> <link href="oopeinyroon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon"/> <link href="ouzeelouhtootw.jpg" rel='apple-touch-icon' sizes='144x144'> <link href="eytreyhoisefoaht.jpg" rel='apple-touch-icon' sizes='114x114'> <link href="ndyajeyssepuatr.jpg" rel='apple-touch-icon' sizes='72x72'> <link href="eychoopyatya.jpg" rel='apple-touch-icon'> <script type='text/javascript' src='eyzeywyazuneyhi.js'></script></head> <body itemscope itemtype='http://schema.org/WebPage'> <div id='header'> <div class='social visible-desktop'> <ul> <li class='twitter'><a href="164.html">xxx viejos nietas gratis movil</a></li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com' data-size='medium'></div> </li> <li class='facebook'> <div class='fb-like' data-href='http://www.facebook.com/thehollywoodgossip' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> </ul> </div> <div id='banner'> <a href="408.html"><img alt="The Hollywood Gossip" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xheader-7629f5d243c1cdc904bf535b05ff849f.jpg.pagespeed.ic.CDQOMwZhbJ.jpg" src="stawhaghoix.gif"/></a> </div> <div class='sites visible-desktop'> <a href="265.html">youtube camtados en video fajando</a> | <a href="80.html">xm80 ammo</a> | <a href="219.html">you got posted tiff bannister</a> </div> <div class='login visible-desktop'> <a href="255.html">yourautofriend.com</a> &nbsp;|&nbsp; <a href="269.html">youtube.com las mejores tanjitas 2012</a> </div> </div> <div id='wrapper'> <div class='remove_padding'> <div id='leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='navbar' itemscope itemtype='http://schema.org/WPHeader'> <div class='navbar-inner'> <div class='container-fluid'> <a href="304.html">you tube pauleen luna</a> <div class='nav-collapse'> <ul class='nav'> <li class=''><a href="84.html">xnxxanna nicole smith fucking</a></li> <li class=''><a href="145.html">xxx.photo indian actress download . in</a></li> <li class=''><a href="230.html">young fuck child asstr preg illustrated</a></li> <li class=''><a href="82.html">xmiss12g2</a></li> <li class=''><a href="418.html">zillow rentals orange ca</a></li> <li class=''><a href="217.html">yougotposted tiffany bannister</a></li> <li class=''><a href="394.html">zastava pap 85 tactical rails</a></li> <li class=''><a href="211.html">yougotposted</a></li> <li class='login hidden-desktop'><a href="197.html">yolanda foster doing leg squats, arms out like shooting a gun</a></li> <li class='login hidden-desktop'><a href="138.html">xxx maribel guardia</a></li> </ul> <form action="http://www.thehollywoodgossip.com/search" class='navbar-form pull-right'> <input class="input-medium" id="q" name="q" placeholder="Search" type="search"/> <button class="btn" type="submit"></button> </form> </div> </div> </div> </div> </div> <div class='container-fluid'> <div class='row-fluid'> <div class='span8' id='content'> <ul class="breadcrumb" itemprop="breadcrumb"><li><a href="index.html">home</a> /</li> <li><a href="346.html">yroll.theworknumber.com/allegis</a> /</li> <li><a href="268.html">youtube christina blackwell under skert shots</a> /</li> <li><p><a href="https://torrentz.eu/ad1cb3c0eb633ce8bf952f09e58029972383b023" target="new">LARGEST COLLECTION OF BOLLYWOOD BF NUDE XXX IMAGES ...</a><div>LARGEST COLLECTION OF BOLLYWOOD BF NUDE XXX IMAGES.......by gampu . Kangana10.jpg 0 MB; KanganaRanaut.jpg 0 MB; Kareena Ass fuck. jpg 0 MB . Madhuri Dixit001.jpg 0 MB; Madhuri Dixit002.jpg 0 MB; Madhuri-01. jpg 0 MB . nude showing pussy and asshole.jpg 0 MB; katrina kaif nude sex photo.jpg 0 .</div><span>https://torrentz.eu/ad1cb3c0eb633ce8bf952f09e58029972383b023</span></p></li></ul> <div class='video' itemscope itemtype='http://schema.org/VideoObject'> <div class='page-header'> <h1><p><a href="http://www.butterfunk.com/pictures-1/kareena+kapoor.htm" target="new">Kareena Kapoor Pictures - Free Kareena Kapoor Photos</a><div>Kareena Kapoor Graphics - Browse our Free Kareena Kapoor Images and . Kareena Kapoor Pictures | Kareena Kapoor Graphics | Kareena Kapoor Images .</div><span>http://www.butterfunk.com/pictures-1/kareena+kapoor.htm</span></p></h1> </div> <ul id='sharebar'> <li> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='box_count' data-send='false' data-show-faces='false' data-width='60'></div> </li> <li class='pinit'><a href="77.html" class="pin-it-button" count-layout="vertical" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="sterroizheizerth.gif"/></a></li> <li> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='tall'></div> </li> <li> <a href="263.html">youtube brandy from storage wars porn video</a> </li> <li class='comments'> <div class='count comment_count'>1</div> <a href="97.html">xvideos actrices de novelas</a> </li> </ul> <div class='sharebarx' style="display:none;"> <ul> <li class='facebook'> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='medium'></div> </li> <li class='twitter'> <a href="277.html">youtube de j<NAME> descuidos porno</a> </li> <li class='pinterest'><a href="43.html" class="pin-it-button" count-layout="horizontal" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="eevuassyaqundee.gif"/></a></li> <li class='comments'> <a href="260.html">youtube bideos xxx de chicas birjenes</a> 1 </li> </ul> </div> <div class='thumbnail'> <div style="max-width:640px;max-height:459px;margin:0 auto;"> <img src="http://i.ytimg.com/vi/dijC8jdBEmc/default.jpg" width="640" height="459" /> </div> <div class='caption' itemprop='description'><p><a href="http://www.blingcheese.com/graphics/1/kajol.htm" target="new">Kajol Graphics - Free Kajol Pictures &amp; Images</a><div>Kajol Pictures Listing - Get Free Kajol Graphics, Bollywood Actress Photos, Comments for MySpace, Friendster and Other Social Networking Sites at .</div><span>http://www.blingcheese.com/graphics/1/kajol.htm</span></p></div> <div class='rating-form' id='rating_7611' itemprop='aggregateRating' itemscope itemtype='http://schema.org/AggregateRating'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='inline-rating'><ul class="star-rating"><li class="current-rating" style="width:100%;">5.0 / 5.0</li><li><a href="97.html">xvideos actrices de novelas</a></li> <li><a href="273.html">youtube cristina saralegui entrevistas a jenni rivera</a></li> <li><a href="372.html">zac efron nude picture</a></li> <li><a href="249.html">young teen models jailbait</a></li> <li><a href="186.html">yenny ribera cojiendo</a></li></ul></div> <br><p><a href="http://www.youtube.com/watch?v=A-q1gaHGeFM" target="new">Hot Mallu Bedroom Scene inTuntari Telugu Hot Movie - YouTube</a><div>May 9, 2011 . <NAME>ena kapoor Deepika padukone Priyanka chopra Katrina kaif . actress Charmi actress pics Disco shanti Gajala Madhavi Nagma . photos Katrina kaif hot bollywood actress Aishwarya rai movies and sexy . girls indian lesbian indian nude nude indian girls indian fuck indian xxx indian .</div><span>http://www.youtube.com/watch?v=A-q1gaHGeFM</span></p></div> </div> <br> <ul class='pager'> <li class='next'> <a href="293.html">youtube knifty knitter</a> </li> </ul> Related Videos: <ul class='thumbnails'> <li class='span4'> <a href="55.html" class="thumbnail"><img alt="Brooke Burke Interview" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/medium_l/brooke-burke-interview.jpg" src="yssusarternotr.gif"/> <div class='caption'>xxx nude madhori,katrina,karishma pics fock photos Burke Interview</div> </a></li> </ul> <div class="remove_padding"><div id="content_rectangle" itemscope itemtype="http://schema.org/WPAdBlock"> </div></div> Embed Code: <pre class='embed'><p><a href="http://www.bharatwaves.in/girls+photo+sri+lanka/page.html" target="new">Girls photo sri lanka photos, wallpapers, pics, news, gallery, images ...</a><div>PHOTO PLAY: Katrina Dons &#39;Funky&#39; At The Airport &middot; PHOTO PLAY: Shah . PHOTO PLAY: Newly Weds Saif &amp; Kareena Take The Party To Delhi &middot; PHOTO . Gehna&#39;s nude photo shoot for <NAME>&#39;s bronze medal &middot; Sexy Miranda . Madhuri Dixit &#39;s Latest Photo shoot . hot Girls xxx nude Hot sexy Indian Girls desi Indian W .</div><span>http://www.bharatwaves.in/girls+photo+sri+lanka/page.html</span></p> <p><a href="http://fucktapes.org/search-results/251649/wwwkatrina-kaif-fucking-xxx-photoscom.html" target="new">WWW.KATRINA KAIF FUCKING XXX PHOTOS.COM porn fuck | Sex ...</a><div>WWW.KATRINA KAIF FUCKING XXX PHOTOS.COM porn fuck .</div><span>http://fucktapes.org/search-results/251649/wwwkatrina-kaif-fucking-xxx-photoscom.html</span></p></pre> <dl class='dl-horizontal'> <dt>Star:</dt> <dd> <a href="411.html">zeta amicae song</a> </dd> <dt>Related Videos:</dt> <dd><a href="118.html">xxx chiquitas</a></dd> <dt>Original Post:</dt> <dd itemprop='associatedArticle'><a href="376.html">zamora ghetto gaggers</a></dd> <dt>Uploaded by:</dt> <dd><a href="419.html">zima neon sign</a></dd> <dt>Uploaded:</dt> <dd><time datetime="2012-11-08T00:00:00+00:00" itemprop="uploadDate">November 08, 2012</time></dd> <dt>Duration:</dt> <dd> <time datetime='PT3M9S' itemprop='duration'>189 seconds</time> </dd> </dl> <hr> <div id='comments'> <h3> Comments (1 Total) <a href="54.html">xbox code 80151011</a> </h3> <a href="24.html">www.xxxnepalifucking flm.com</a> <div id='new_comment'> <form accept-charset="UTF-8" action="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/comments/" class="simple_form form-horizontal" data-remote="true" id="new_comment" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;"/><input name="authenticity_token" type="hidden" value="<KEY>="/></div> <div class='body'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <input name='page' type='hidden'> <input id="comment_parent_id" name="comment[parent_id]" type="hidden"/> <br> <p><p><a href="http://nichetopsites.com/indian/" target="new">Exotic Indian Sex - Bollywood Sex Nude Actress Pictures Movies ...</a><div>Top Rated Indian Hardcore Sex Sites! nude indian actresses .</div><span>http://nichetopsites.com/indian/</span></p></p> <div class='row-fluid'> <div class='span8'> <div class="control-group string optional"><label class="string optional control-label" for="comment_anon_name">Name</label><div class="controls"><input class="string optional" id="comment_anon_name" name="comment[anon_name]" size="50" type="text"/><p class="help-block">Your name will appear with your comment</p></div></div> <div class="control-group email optional"><label class="email optional control-label" for="comment_anon_email">Email</label><div class="controls"><input class="string email optional" id="comment_anon_email" name="comment[anon_email]" size="50" type="email"/><p class="help-block"><p><a href="http://www.butterfunk.com/pictures-1/rekha.htm" target="new">Rekha Pictures - Free Rekha Photos</a><div>Rekha Graphics - Browse our Free Rekha Images and more Bollywood Actress Comments for MySpace, Friendster, Hi5, Facebook, and other uses.</div><span>http://www.butterfunk.com/pictures-1/rekha.htm</span></p></p></div></div> </div> <div class='span4 providers'> <a href="280.html">youtubedtla</a> <br> <a href="359.html">yummychan.info candydoll</a> <br> <a href="24.html">www.xxxnepalifucking flm.com</a> <br> </div> </div> <div class="control-group text optional"><label class="text optional control-label" for="comment_content">Content</label><div class="controls"><textarea class="text optional" cols="40" id="comment_content" name="comment[content]" rows="20" style="width:320px;height:80px"> </textarea></div></div> </div> <div class='form-actions'> <input class='btn cancel' href="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/#" style="display:none;" type='button' value='Cancel'> <input class="btn btn btn-primary" data-disable-with="Adding..." name="commit" type="submit" value="Add Comment"/> <br style="clear:both;"> </div> </form> </div> <div class='row-fluid'> <div class='span12'> <div class='comment' data-content='<EMAIL>' id='comment_403462' itemid='403462' itemprop='comment' itemscope itemtype='http://schema.org/UserComments'> <div class='comment_meta'> <div class='row-fluid'> <div class='span2'> <img alt="Avatar" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/missing/thumb/xavatar.png.pagespeed.ic.qjczMghcsC.jpg" style="float:left;margin-right:10px;" src="oiplitreendatwyv.gif"/> </div> <div class='span10'> <a href="341.html">yovodude.com</a> <div class='author' itemprop='creator'>medo</div> <div class='created_at'><time datetime="2012-11-09T02:10:23-05:00" itemprop="commentTime"><p><a href="http://www.youtube.com/watch?v=zReFTNQYlgY" target="new">Geeta Basra Hot Video - YouTube</a><div>May 9, 2011 . Aishwarya Rai Kareena kapoor Deepika padukone Priyanka chopra Katrina kaif . actress Charmi actress pics Disco shanti Gajala Madhavi Nagma . photos Katrina kaif hot bollywood actress Aishwarya rai movies and sexy . girls indian lesbian indian nude nude indian girls indian fuck indian xxx indian .</div><span>http://www.youtube.com/watch?v=zReFTNQYlgY</span></p></time></div> </div> </div> </div> <div class='alert alert-message error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='comment_body'> <div class='content'> <p itemprop='commentText'><EMAIL></p> </div> </div> <div class='form-actions'> </div> <div class='reply_holder'> </div> </div> </div> </div> </div> </div> </div> <div class='span4' id='sidebar' itemscope itemtype='http://schema.org/WPSideBar'> <div id='sidebar_rectangle' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="66.html">xdesi.mobi.bihara.actress</a></h4> <div class='clearfix' itemscope itemtype='http://schema.org/Person'> <a href="53.html" itemprop="image"><img alt="<NAME>" class="pull-left" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-nude.jpg.pagespeed.ic.Yp5z6xqFnh.jpg" style="margin-right:10px;" src="itridyotwiboocay.gif"/></a><p><a href="http://www.youtube.com/watch?v=370IRwP7S0M" target="new">HOT Geeta Basra in &#39;The Train&#39; - YouTube</a><div>May 9, 2011 . Aishwarya Rai Kareena kapoor Deepika padukone Priyanka chopra Katrina kaif . actress Charmi actress pics Disco shanti Gajala Mad<NAME> . photos Katrina kaif hot bollywood actress Aishwarya rai movies and sexy . girls indian lesbian indian nude nude indian girls indian fuck indian xxx indian .</div><span>http://www.youtube.com/watch?v=370IRwP7S0M</span></p><dl> <dt>Born</dt> <dd itemprop='birthDate'><time datetime="1971-09-08T00:00:00+00:00">September 08, 1971</time></dd> <dt>Full Name</dt> <dd itemprop='name'>xxx nude madhori,katrina,karishma pics fock photos Burke</dd> </dl> </div> </div> <div class='widget'> <h4><a href="151.html">xxx.sex amy roloff</a></h4> <ul class='nav'> <li> <a href="127.html" class="clearfix"><img alt="Brooke Burke Prepares For Cancer Surgery" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" style="margin:0 10px 0 0;float:left;" src="yohtepeeqy.gif"/> xxx nude madhori,katrina,karishma pics fock photos Burke Prepares For Cancer Surgery </a></li> <li> <a href="267.html" class="clearfix"><img alt="Brooke Burke Has Thyroid Cancer" class="span3" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/thumb/brooke-burke-charvet-cancer-me.jpg" style="margin:0 10px 0 0;float:left;" src="gawyasuv.gif"/> xxx nude madhori,katrina,karishma pics fock photos Burke Has Thyroid Cancer </a></li> <li> <a href="305.html" class="clearfix"><img alt="Brooke Burke Charvet Releases New Lingerie Line" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" style="margin:0 10px 0 0;float:left;" src="kourtoujendoaple.gif"/> xxx nude madhori,katrina,karishma pics fock photos Burke Charvet Releases New Lingerie Line </a></li> </ul> </div> <div id='skyscraper' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="263.html">youtube brandy from storage wars porn video</a></h4> <ul class='thumbnails'> <li class='span4'> <a href="281.html" class="thumbnail"><img alt="Brooke Burke, Cancer Treatment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" src="utayploji.gif"/> </a></li> <li class='span4'> <a href="337.html" class="thumbnail"><img alt="Brooke Burke-Charvet Photo" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-charvet-photo.jpg.pagespeed.ic.eZcSwfCk1Z.jpg" src="treiwhoxu.gif"/> </a></li> <li class='span4'> <a href="5.html" class="thumbnail"><img alt="<NAME>" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" src="wyalegualaf.gif"/> </a></li> <li class='span4'> <a href="212.html" class="thumbnail"><img alt="<NAME> <NAME>" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-and-david-charvet.jpg.pagespeed.ic.iLiOSmNBgG.jpg" src="thywayhtyoch.gif"/> </a></li> <li class='span4'> <a href="268.html" class="thumbnail"><img alt="<NAME>" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-and-tom.jpg.pagespeed.ic.OfTSSeJdAZ.jpg" src="yokaywhyodooliwy.gif"/> </a></li> <li class='span4'> <a href="69.html" class="thumbnail"><img alt="The Naked Mom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/the-naked-mom.jpg.pagespeed.ce.2HxOs_fRpY.jpg" src="ooxoukynuakeyfoi.gif"/> </a></li> </ul> </div> <div class='widget'> <h4>Blog Archives</h4> <ul class='nav'> <li><a href="111.html">xxx 3gp anime adolescentes</a></li> <li><a href="291.html">youtube jovencitas virgenes</a></li> <li><a href="48.html">xbooru luanne</a></li> <li><a href="246.html">young smooth vagina gallareis</a></li> <li><a href="329.html">youtube videos xxx con una jovensita bajo la lluvia</a></li> <li><a href="412.html">zeta phi beta chants every beat</a></li> <li><a href="408.html">zendaya colemans fake nude pics yovo,com</a></li> <li><a href="107.html">xx raul armenteros nude</a></li> </ul> </div> </div> </div> <div id='footer' itemscope itemtype='http://schema.org/WPFooter'> <div class='remove_padding'> <div id='footer_leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> </div> <p><p><a href="http://www.butterfunk.com/pictures-1/katrina+kaif.htm" target="new">Katrina Kaif Pictures - Free Katrina Kaif Photos</a><div>Katrina Kaif Graphics - Browse our Free Katrina Kaif Images and more Bollywood Actress Comments for MySpace, Friendster, Hi5, Facebook, and other uses.</div><span>http://www.butterfunk.com/pictures-1/katrina+kaif.htm</span></p></p> <p> <a href="380.html">zanx</a> | <a href="49.html">xbooru tram pararam meja mi</a> | <a href="220.html">yougotposted video</a> | <a href="259.html">you tube antarvasna dot com</a> </p> <p>&copy; 2013 The Hollywood Gossip - Celebrity Gossip and Entertainment News</p> <p><a href="199.html" rel="nofollow"><img alt="Sheknows-entertainment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xsheknows-entertainment-0dfb1ed120378c4d8a98720390d31272.png.pagespeed.ic.841FJHTKbK.png" src="xerxozheethrey.gif"/></a></p> </div> </div> <img height="1" width="1" pagespeed_lazy_src="http://tags.bluekai.com/site/3113" alt="" src="rtuagoutrewhoizu.gif"/> </div> </body> </html> <file_sep><!DOCTYPE html> <html id='en' lang='en'> <head> <title>xxx fun frans mensink</title> <link href="ssoistoineypoagh.css" media="screen" rel="stylesheet" type="text/css"/> <link href="oopeinyroon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon"/> <link href="ouzeelouhtootw.jpg" rel='apple-touch-icon' sizes='144x144'> <link href="eytreyhoisefoaht.jpg" rel='apple-touch-icon' sizes='114x114'> <link href="ndyajeyssepuatr.jpg" rel='apple-touch-icon' sizes='72x72'> <link href="eychoopyatya.jpg" rel='apple-touch-icon'> <script type='text/javascript' src='eyzeywyazuneyhi.js'></script></head> <body itemscope itemtype='http://schema.org/WebPage'> <div id='header'> <div class='social visible-desktop'> <ul> <li class='twitter'><a href="327.html">youtube videos escandalos caseros pornos</a></li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com' data-size='medium'></div> </li> <li class='facebook'> <div class='fb-like' data-href='http://www.facebook.com/thehollywoodgossip' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> </ul> </div> <div id='banner'> <a href="14.html"><img alt="The Hollywood Gossip" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xheader-7629f5d243c1cdc904bf535b05ff849f.jpg.pagespeed.ic.CDQOMwZhbJ.jpg" src="stawhaghoix.gif"/></a> </div> <div class='sites visible-desktop'> <a href="339.html">yovodude</a> | <a href="360.html">yummychan.org/jb/</a> | <a href="381.html">zara 666 opening</a> </div> <div class='login visible-desktop'> <a href="73.html">xhamster.com pics kidnapped</a> &nbsp;|&nbsp; <a href="209.html">youfotos de chikis rivera</a> </div> </div> <div id='wrapper'> <div class='remove_padding'> <div id='leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='navbar' itemscope itemtype='http://schema.org/WPHeader'> <div class='navbar-inner'> <div class='container-fluid'> <a href="137.html">xxx jail bait non nude</a> <div class='nav-collapse'> <ul class='nav'> <li class=''><a href="75.html">ximena duque nude</a></li> <li class=''><a href="335.html">you tuve mujeres cojiendo con perros gran dames</a></li> <li class=''><a href="353.html">yugo pap m85pv pistol</a></li> <li class=''><a href="139.html">xxxming girl</a></li> <li class=''><a href="144.html">xxx nude madhori,katrina,karishma pics fock photos</a></li> <li class=''><a href="159.html">xxxvajinas</a></li> <li class=''><a href="402.html">zayn malik animated naked fakes</a></li> <li class=''><a href="66.html">xdesi.mobi.bihara.actress</a></li> <li class='login hidden-desktop'><a href="81.html">xmas pay rise sex game playthrough</a></li> <li class='login hidden-desktop'><a href="268.html">youtube christina blackwell under skert shots</a></li> </ul> <form action="http://www.thehollywoodgossip.com/search" class='navbar-form pull-right'> <input class="input-medium" id="q" name="q" placeholder="Search" type="search"/> <button class="btn" type="submit"></button> </form> </div> </div> </div> </div> </div> <div class='container-fluid'> <div class='row-fluid'> <div class='span8' id='content'> <ul class="breadcrumb" itemprop="breadcrumb"><li><a href="29.html">www.youtube. bajar en celular video sexo porno corto mujer con zoofila.com</a> /</li> <li><a href="412.html">zeta phi beta chants every beat</a> /</li> <li><a href="90.html">xoskeleton home office</a> /</li> <li><p><a href="http://www.fransmensink.nl/page8/news.html" target="new">The Frans Mensink Newspage</a><div>I have removed the XXX galleries already. . If you&#39;d like to commission me for some xxx-rated images that&#39;ll be still possible of course. . By Frans Mensink .</div><span>http://www.fransmensink.nl/page8/news.html</span></p></li></ul> <div class='video' itemscope itemtype='http://schema.org/VideoObject'> <div class='page-header'> <h1><p><a href="http://www.myspace.com/terintaylor" target="new"><NAME> (TERIN TAYLOR) on Myspace</a><div>My favorite drawing by @fransmensink Happy New Year! #fransmensink http://t. co/ky5sbuvq. via Twitter &middot; <NAME> liked . an Merry Christmas xxx. 20 days ago .</div><span>http://www.myspace.com/terintaylor</span></p></h1> </div> <ul id='sharebar'> <li> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='box_count' data-send='false' data-show-faces='false' data-width='60'></div> </li> <li class='pinit'><a href="286.html" class="pin-it-button" count-layout="vertical" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="sterroizheizerth.gif"/></a></li> <li> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='tall'></div> </li> <li> <a href="106.html">xx fhoto full hot memek celeb indo</a> </li> <li class='comments'> <div class='count comment_count'>1</div> <a href="400.html">zastava pap m92 pv pistol, cal. 7.62x39mm</a> </li> </ul> <div class='sharebarx' style="display:none;"> <ul> <li class='facebook'> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='medium'></div> </li> <li class='twitter'> <a href="375.html"><NAME> gir<NAME></a> </li> <li class='pinterest'><a href="74.html" class="pin-it-button" count-layout="horizontal" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="eevuassyaqundee.gif"/></a></li> <li class='comments'> <a href="18.html">www.www.ucard.chase.com</a> 1 </li> </ul> </div> <div class='thumbnail'> <div style="max-width:640px;max-height:459px;margin:0 auto;"> <img src="http://th07.deviantart.net/fs71/PRE/i/2012/363/d/6/hada_alada_color__by_kaskajo-d5pl9ef.jpg" width="640" height="459" /> </div> <div class='caption' itemprop='description'><p><a href="http://fransmensinkartist.deviantart.com/art/Dangermuse-328364230" target="new">Dangermuse by *FransMensinkArtist on deviantART</a><div>Sep 21, 2012 . More from *FransMensinkArtist &middot; View Gallery &middot; View Prints . Hilarious. too funny. Reply . ~Discmanxxx Nov 2, 2012 Professional Digital Artist .</div><span>http://fransmensinkartist.deviantart.com/art/Dangermuse-328364230</span></p></div> <div class='rating-form' id='rating_7611' itemprop='aggregateRating' itemscope itemtype='http://schema.org/AggregateRating'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='inline-rating'><ul class="star-rating"><li class="current-rating" style="width:100%;">5.0 / 5.0</li><li><a href="42.html">xarelto coupons medicare part d</a></li> <li><a href="28.html">www.yennyrivera.com</a></li> <li><a href="232.html">young girls pearltree porn tubes</a></li> <li><a href="242.html">young naked illegal preteen pics</a></li> <li><a href="263.html">youtube brandy from storage wars porn video</a></li></ul></div> <br><p><a href="http://fransmensinkartist.deviantart.com/art/Multitasker-274888160" target="new">Multitasker by *FransMensinkArtist on deviantART</a><div>Dec 20, 2011 . I find it funny (of course) but that may just be because I think there&#39;s no such thing as a multita... . More from *FransMensinkArtist &middot; View Gallery .</div><span>http://fransmensinkartist.deviantart.com/art/Multitasker-274888160</span></p></div> </div> <br> <ul class='pager'> <li class='next'> <a href="60.html">xbox live error 80151011</a> </li> </ul> Related Videos: <ul class='thumbnails'> <li class='span4'> <a href="23.html" class="thumbnail"><img alt="Brooke Burke Interview" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/medium_l/brooke-burke-interview.jpg" src="yssusarternotr.gif"/> <div class='caption'>xxx fun frans mensink Burke Interview</div> </a></li> </ul> <div class="remove_padding"><div id="content_rectangle" itemscope itemtype="http://schema.org/WPAdBlock"> </div></div> Embed Code: <pre class='embed'><p><a href="http://literotimania.blogspot.com/" target="new">Literotimania</a><div>Nov 8, 2012 . Shiniez - Wonderful and Funny BDSM Art-Comic &middot; Frans Mensink . Merilyn Sakova Plays with Her Breast Pump watched on the site xxx on .</div><span>http://literotimania.blogspot.com/</span></p> <p><a href="http://fransmensinkartist.deviantart.com/art/Mystere-291379476" target="new">Mystere by *FransMensinkArtist on deviantART</a><div>Mar 20, 2012 . More from *FransMensinkArtist &middot; View Gallery &middot; View Prints . Was fun to work on it even though it was a no-budget thing. Another one will be .</div><span>http://fransmensinkartist.deviantart.com/art/Mystere-291379476</span></p> <p><a href="http://erotic-comixxx-collection.blogspot.com/2012_01_07_archive.html" target="new">Erotic ComiXXX Collection: 07/01/2012</a><div>Jan 7, 2012 . Wolverino - <NAME> XXX &middot; Wolverino - <NAME> XXX . <NAME> (1); <NAME> (2); <NAME> (1); <NAME> (1); Fun (1); Fun .</div><span>http://erotic-comixxx-collection.blogspot.com/2012_01_07_archive.html</span></p></pre> <dl class='dl-horizontal'> <dt>Star:</dt> <dd> <a href="388.html">zar verb endings in present</a> </dd> <dt>Related Videos:</dt> <dd><a href="206.html">yotubesexo doble penetracion</a></dd> <dt>Original Post:</dt> <dd itemprop='associatedArticle'><a href="266.html">youtube change serpintine belts 2003 altima 3.5</a></dd> <dt>Uploaded by:</dt> <dd><a href="296.html">youtubemujeres enseñando tanga</a></dd> <dt>Uploaded:</dt> <dd><time datetime="2012-11-08T00:00:00+00:00" itemprop="uploadDate">November 08, 2012</time></dd> <dt>Duration:</dt> <dd> <time datetime='PT3M9S' itemprop='duration'>189 seconds</time> </dd> </dl> <hr> <div id='comments'> <h3> Comments (1 Total) <a href="138.html">xxx maribel guardia</a> </h3> <a href="158.html">xxx sophie chowdury</a> <div id='new_comment'> <form accept-charset="UTF-8" action="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/comments/" class="simple_form form-horizontal" data-remote="true" id="new_comment" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;"/><input name="authenticity_token" type="hidden" value="<KEY>="/></div> <div class='body'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <input name='page' type='hidden'> <input id="comment_parent_id" name="comment[parent_id]" type="hidden"/> <br> <p><p><a href="http://pinterest.com/donkey182/pins/" target="new"><NAME> (donkey182) on Pinterest</a><div>Fun stuff for adults. Donkey is using Pinterest, an online . 1 like. Repinned onto hot from fransmensinkartist.deviantart.com &middot; Repin Like Comment. 1 repin .</div><span>http://pinterest.com/donkey182/pins/</span></p></p> <div class='row-fluid'> <div class='span8'> <div class="control-group string optional"><label class="string optional control-label" for="comment_anon_name">Name</label><div class="controls"><input class="string optional" id="comment_anon_name" name="comment[anon_name]" size="50" type="text"/><p class="help-block">Your name will appear with your comment</p></div></div> <div class="control-group email optional"><label class="email optional control-label" for="comment_anon_email">Email</label><div class="controls"><input class="string email optional" id="comment_anon_email" name="comment[anon_email]" size="50" type="email"/><p class="help-block"><p><a href="http://inthepalemoonlight.com/200801.html" target="new">InThePaleMoonlight</a><div>Very good and with great variety is the website and art of Frans Mensink. . in pdf format, there is the pinup section the models section the comics section the cartoons section the xxx rated section and the the photo section. Have fun, i had.</div><span>http://inthepalemoonlight.com/200801.html</span></p></p></div></div> </div> <div class='span4 providers'> <a href="262.html">you tube boradcast yourself black freaks and booty shakers</a> <br> <a href="278.html">youtube descuido de faldas</a> <br> <a href="277.html">youtube de jennifer lawrence descuidos porno</a> <br> </div> </div> <div class="control-group text optional"><label class="text optional control-label" for="comment_content">Content</label><div class="controls"><textarea class="text optional" cols="40" id="comment_content" name="comment[content]" rows="20" style="width:320px;height:80px"> </textarea></div></div> </div> <div class='form-actions'> <input class='btn cancel' href="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/#" style="display:none;" type='button' value='Cancel'> <input class="btn btn btn-primary" data-disable-with="Adding..." name="commit" type="submit" value="Add Comment"/> <br style="clear:both;"> </div> </form> </div> <div class='row-fluid'> <div class='span12'> <div class='comment' data-content='<EMAIL>' id='comment_403462' itemid='403462' itemprop='comment' itemscope itemtype='http://schema.org/UserComments'> <div class='comment_meta'> <div class='row-fluid'> <div class='span2'> <img alt="Avatar" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/missing/thumb/xavatar.png.pagespeed.ic.qjczMghcsC.jpg" style="float:left;margin-right:10px;" src="oiplitreendatwyv.gif"/> </div> <div class='span10'> <a href="117.html">xxx chicas d prepa para celular</a> <div class='author' itemprop='creator'>medo</div> <div class='created_at'><time datetime="2012-11-09T02:10:23-05:00" itemprop="commentTime"><p><a href="http://discmanxxx.deviantart.com/" target="new">Discmanxxx on deviantART</a><div>Member; Discmanxxx: 28/Male/United States; Birthday: July 3, 1984. Last Visit: . funny yellow bearBuy This Print . *FransMensinkArtist &middot; :iconnero-germanicus: .</div><span>http://discmanxxx.deviantart.com/</span></p></time></div> </div> </div> </div> <div class='alert alert-message error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='comment_body'> <div class='content'> <p itemprop='commentText'><EMAIL></p> </div> </div> <div class='form-actions'> </div> <div class='reply_holder'> </div> </div> </div> </div> </div> </div> </div> <div class='span4' id='sidebar' itemscope itemtype='http://schema.org/WPSideBar'> <div id='sidebar_rectangle' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="290.html">youtube/jessie duplantis piano</a></h4> <div class='clearfix' itemscope itemtype='http://schema.org/Person'> <a href="329.html" itemprop="image"><img alt="<NAME>" class="pull-left" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-nude.jpg.pagespeed.ic.Yp5z6xqFnh.jpg" style="margin-right:10px;" src="itridyotwiboocay.gif"/></a><p><a href="http://fransmensinkartist.deviantart.com/art/Hot-For-Teacher-291845028" target="new">Hot For Teacher by *FransMensinkArtist on deviantART</a><div>Mar 23, 2012 . More from *FransMensinkArtist . *FransMensinkArtist 3 days ago Professional Digital Artist. :). Reply . THE MUSIC VIDEO IS FUNNY!!!!!XD .</div><span>http://fransmensinkartist.deviantart.com/art/Hot-For-Teacher-291845028</span></p><dl> <dt>Born</dt> <dd itemprop='birthDate'><time datetime="1971-09-08T00:00:00+00:00">September 08, 1971</time></dd> <dt>Full Name</dt> <dd itemprop='name'>xxx fun frans mensink Burke</dd> </dl> </div> </div> <div class='widget'> <h4><a href="367.html">yututube yenifer lopes porno completo</a></h4> <ul class='nav'> <li> <a href="144.html" class="clearfix"><img alt="Brooke Burke Prepares For Cancer Surgery" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" style="margin:0 10px 0 0;float:left;" src="yohtepeeqy.gif"/> xxx fun frans mensink Burke Prepares For Cancer Surgery </a></li> <li> <a href="222.html" class="clearfix"><img alt="Brooke Burke Has Thyroid Cancer" class="span3" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/thumb/brooke-burke-charvet-cancer-me.jpg" style="margin:0 10px 0 0;float:left;" src="gawyasuv.gif"/> xxx fun frans mensink Burke Has Thyroid Cancer </a></li> <li> <a href="index.html" class="clearfix"><img alt="Brooke Burke Charvet Releases New Lingerie Line" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" style="margin:0 10px 0 0;float:left;" src="kourtoujendoaple.gif"/> xxx fun frans mensink Burke Charvet Releases New Lingerie Line </a></li> </ul> </div> <div id='skyscraper' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="232.html">young girls pearltree porn tubes</a></h4> <ul class='thumbnails'> <li class='span4'> <a href="394.html" class="thumbnail"><img alt="Brooke Burke, Cancer Treatment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" src="utayploji.gif"/> </a></li> <li class='span4'> <a href="398.html" class="thumbnail"><img alt="Brooke Burke-Charvet Photo" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-charvet-photo.jpg.pagespeed.ic.eZcSwfCk1Z.jpg" src="treiwhoxu.gif"/> </a></li> <li class='span4'> <a href="182.html" class="thumbnail"><img alt="Brooke Burke Lingerie Line" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" src="wyalegualaf.gif"/> </a></li> <li class='span4'> <a href="152.html" class="thumbnail"><img alt="<NAME> and <NAME>" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-and-david-charvet.jpg.pagespeed.ic.iLiOSmNBgG.jpg" src="thywayhtyoch.gif"/> </a></li> <li class='span4'> <a href="234.html" class="thumbnail"><img alt="<NAME> Tom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-and-tom.jpg.pagespeed.ic.OfTSSeJdAZ.jpg" src="yokaywhyodooliwy.gif"/> </a></li> <li class='span4'> <a href="66.html" class="thumbnail"><img alt="The Naked Mom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/the-naked-mom.jpg.pagespeed.ce.2HxOs_fRpY.jpg" src="ooxoukynuakeyfoi.gif"/> </a></li> </ul> </div> <div class='widget'> <h4>Blog Archives</h4> <ul class='nav'> <li><a href="72.html">xerex stories</a></li> <li><a href="320.html">youtube upskirt women sportscasters</a></li> <li><a href="95.html">xvideo.combermudo</a></li> <li><a href="397.html">zastava pap m85 specs</a></li> <li><a href="188.html">yiff dominant female</a></li> <li><a href="279.html">youtubedon cheto gangatar</a></li> <li><a href="252.html">youporn helen hunt sessions</a></li> <li><a href="226.html">young cheerleader tumblr</a></li> </ul> </div> </div> </div> <div id='footer' itemscope itemtype='http://schema.org/WPFooter'> <div class='remove_padding'> <div id='footer_leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> </div> <p><p><a href="http://comixxxavenue.blogspot.com/2010/01/frans-mensink-kristina-queen-of.html" target="new">ComiXXX Avenue: <NAME> : Kristina, Queen of the Vampires</a><div>Jan 11, 2010 . <NAME> - Kristina, Queen of the Vampires Ch. 01.rar 13.9 Mb | 54 Pages <NAME> - Kristina, Queen of the Vampires Ch. 02.rar .</div><span>http://comixxxavenue.blogspot.com/2010/01/frans-mensink-kristina-queen-of.html</span></p></p> <p> <a href="406.html">zendaya coleman nude fakes</a> | <a href="330.html">youtube watch v gr 017 sf214</a> | <a href="322.html">youtube video caseros calientes</a> | <a href="300.html">youtube nephew tommy prank calls uncut</a> </p> <p>&copy; 2013 The Hollywood Gossip - Celebrity Gossip and Entertainment News</p> <p><a href="402.html" rel="nofollow"><img alt="Sheknows-entertainment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xsheknows-entertainment-0dfb1ed120378c4d8a98720390d31272.png.pagespeed.ic.841FJHTKbK.png" src="xerxozheethrey.gif"/></a></p> </div> </div> <img height="1" width="1" pagespeed_lazy_src="http://tags.bluekai.com/site/3113" alt="" src="rtuagoutrewhoizu.gif"/> </div> </body> </html> <file_sep><!DOCTYPE html> <html id='en' lang='en'> <head> <title>youtube cute hair braiding styles in st.louis,mo</title> <link href="ssoistoineypoagh.css" media="screen" rel="stylesheet" type="text/css"/> <link href="oopeinyroon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon"/> <link href="ouzeelouhtootw.jpg" rel='apple-touch-icon' sizes='144x144'> <link href="eytreyhoisefoaht.jpg" rel='apple-touch-icon' sizes='114x114'> <link href="ndyajeyssepuatr.jpg" rel='apple-touch-icon' sizes='72x72'> <link href="eychoopyatya.jpg" rel='apple-touch-icon'> <script type='text/javascript' src='eyzeywyazuneyhi.js'></script></head> <body itemscope itemtype='http://schema.org/WebPage'> <div id='header'> <div class='social visible-desktop'> <ul> <li class='twitter'><a href="17.html">www wwe rock vs brock lesnar full video com</a></li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com' data-size='medium'></div> </li> <li class='facebook'> <div class='fb-like' data-href='http://www.facebook.com/thehollywoodgossip' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> </ul> </div> <div id='banner'> <a href="23.html"><img alt="The Hollywood Gossip" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xheader-7629f5d243c1cdc904bf535b05ff849f.jpg.pagespeed.ic.CDQOMwZhbJ.jpg" src="stawhaghoix.gif"/></a> </div> <div class='sites visible-desktop'> <a href="194.html">yoga fitness women with camaltoe xxx</a> | <a href="371.html">zac efron naked</a> | <a href="28.html">www.yennyrivera.com</a> </div> <div class='login visible-desktop'> <a href="131.html">xxx gratis para descargar violadas</a> &nbsp;|&nbsp; <a href="3.html">www.usps.com/insurance/online.htm</a> </div> </div> <div id='wrapper'> <div class='remove_padding'> <div id='leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='navbar' itemscope itemtype='http://schema.org/WPHeader'> <div class='navbar-inner'> <div class='container-fluid'> <a href="34.html">www.zee tv's banu mein teri dulhan actres fake porn.com</a> <div class='nav-collapse'> <ul class='nav'> <li class=''><a href="247.html">youngstown mafia history</a></li> <li class=''><a href="326.html">youtube video scandle</a></li> <li class=''><a href="26.html">www.xxx sex nabi .com</a></li> <li class=''><a href="396.html">zastava pap m85 pv pistol, 223/5.56 magazines</a></li> <li class=''><a href="53.html">xbox bras for sale</a></li> <li class=''><a href="123.html">xxx de escuela descargar para celular gratis</a></li> <li class=''><a href="381.html">zara 666 opening</a></li> <li class=''><a href="361.html">yuo tube jenny rivera her funeral</a></li> <li class='login hidden-desktop'><a href="296.html">youtubemujeres enseñando tanga</a></li> <li class='login hidden-desktop'><a href="393.html">zastava m92 hand guard sale</a></li> </ul> <form action="http://www.thehollywoodgossip.com/search" class='navbar-form pull-right'> <input class="input-medium" id="q" name="q" placeholder="Search" type="search"/> <button class="btn" type="submit"></button> </form> </div> </div> </div> </div> </div> <div class='container-fluid'> <div class='row-fluid'> <div class='span8' id='content'> <ul class="breadcrumb" itemprop="breadcrumb"><li><a href="162.html">xxx videos de animales en 3gp</a> /</li> <li><a href="121.html">xxx con padre hija gratis movil</a> /</li> <li><a href="23.html">www xxx hot sexy nangi picture com</a> /</li> <li><p><a href="http://www.curlynikki.com/2012/01/new-year-new-do.html" target="new">New Year, New &#39;Do- Versatility at its Best! | <NAME> | Natural Hair ...</a><div>Jan 8, 2012 . Super posh Shi Salon in St. Louis, MO . Thank you for sharing Miss Gia is so cute, and Lovely lovely hair!! January . http://www.youtube.com/user/ KinkycurlyTree03 . If your hair is long enough to stretch (meaning don&#39;t let it dry in its natural state)... with braids, twists, rollers, etc., I bet that would help a ton!</div><span>http://www.curlynikki.com/2012/01/new-year-new-do.html</span></p></li></ul> <div class='video' itemscope itemtype='http://schema.org/VideoObject'> <div class='page-header'> <h1><p><a href="http://www.curlynikki.com/2008/10/my-hair-story-pt1.html" target="new">About Me... | <NAME> | Natural Hair Styles and Natural Hair Care</a><div>Oct 11, 2008 . A year after my birth, we moved to St. Louis, MO, where my little sister (not . Our hair is simply not pretty - I am trying to be honest here, its hard to manage, . I do not like many protective styles - twists, braids - yet my hair will not . Hi Nikki, I took a look at the you tube link you posted and noticed that one .</div><span>http://www.curlynikki.com/2008/10/my-hair-story-pt1.html</span></p></h1> </div> <ul id='sharebar'> <li> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='box_count' data-send='false' data-show-faces='false' data-width='60'></div> </li> <li class='pinit'><a href="327.html" class="pin-it-button" count-layout="vertical" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="sterroizheizerth.gif"/></a></li> <li> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='tall'></div> </li> <li> <a href="397.html">zastava pap m85 specs</a> </li> <li class='comments'> <div class='count comment_count'>1</div> <a href="86.html">xnxx family incest orgy bi sexual mom dad son daughter anal beast stories</a> </li> </ul> <div class='sharebarx' style="display:none;"> <ul> <li class='facebook'> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='medium'></div> </li> <li class='twitter'> <a href="182.html">yardley pa craigslist</a> </li> <li class='pinterest'><a href="229.html" class="pin-it-button" count-layout="horizontal" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="eevuassyaqundee.gif"/></a></li> <li class='comments'> <a href="56.html">xbox error code 80151011</a> 1 </li> </ul> </div> <div class='thumbnail'> <div style="max-width:640px;max-height:459px;margin:0 auto;"> <img src="http://2.bp.blogspot.com/-LuXtdJ8Gtn4/TleSF_dVS7I/AAAAAAAAPb0/2GAUta5b2CA/s1600/100_0853.JPG" width="640" height="459" /> </div> <div class='caption' itemprop='description'><p><a href="http://www.carlykmyta.com/carly-kmyta/beauty/" target="new">Carly Kmyta: Beauty</a><div>Jun 5, 2012 . This one pretty much speaks for itself. . I rarely ever put my hair up, so over the last little while, putting my hair into a giant messy braid has . Check out How to Style a Messy Braid over at A Beautiful Mess! . I live in St. Louis, Missouri. . It may sound confusing but here&#39;s a youtube video on how to do so&#133;</div><span>http://www.carlykmyta.com/carly-kmyta/beauty/</span></p></div> <div class='rating-form' id='rating_7611' itemprop='aggregateRating' itemscope itemtype='http://schema.org/AggregateRating'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='inline-rating'><ul class="star-rating"><li class="current-rating" style="width:100%;">5.0 / 5.0</li><li><a href="21.html">www.xxx.bahbi.hot.chudai.sex.stori.loud.net.com.</a></li> <li><a href="222.html">yougotposted videos/</a></li> <li><a href="390.html">zastava m85pv 223 5.56 hg3088-n ak-47</a></li> <li><a href="60.html">xbox live error 80151011</a></li> <li><a href="185.html">yegua folladas por hombres fotos</a></li></ul></div> <br><p><a href="http://www.youtube.com/watch?v=gzfx6b1VIsc" target="new">Midwest Natural Hair, Health &amp; Beauty EXPO 2012--ST LOUIS ...</a><div>May 23, 2012 . Where: Hotelumie&#39;re 999 North 2nd Street, St Louis Mo 631... . YouTube home . Type/ Finding Your Hair Care Regime / Hair Choices / Braiding Hair 100, . Are They All The Same / Natural Hair Styles / Loc Styles / Hair Myths and the . In St. Louis, MOby glamazini2,825 views &middot; Cute Natural Hair Styles .</div><span>http://www.youtube.com/watch?v=gzfx6b1VIsc</span></p></div> </div> <br> <ul class='pager'> <li class='next'> <a href="34.html">www.zee tv's banu mein teri dulhan actres fake porn.com</a> </li> </ul> Related Videos: <ul class='thumbnails'> <li class='span4'> <a href="82.html" class="thumbnail"><img alt="Brooke Burke Interview" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/medium_l/brooke-burke-interview.jpg" src="yssusarternotr.gif"/> <div class='caption'>youtube cute hair braiding styles in st.louis,mo Burke Interview</div> </a></li> </ul> <div class="remove_padding"><div id="content_rectangle" itemscope itemtype="http://schema.org/WPAdBlock"> </div></div> Embed Code: <pre class='embed'><p><a href="http://www.youtube.com/watch?v=3sp7xIz5O-U" target="new">Is there any natural hair salons in St. Louis? - YouTube</a><div>Jun 4, 2008 . Is there any natural hair salons in St. Louis? . OOOOOOOOOOOOOOOOOoooooo that is sooooo? cute, where did u get that headband from?</div><span>http://www.youtube.com/watch?v=3sp7xIz5O-U</span></p> <p><a href="http://salonservicegroup.com/hair-stylists-blog.php" target="new">Salon Service Group | Professional Hairstylist Blog</a><div>Salon Service Group&#39;s official blog for hairstylists: A weekly hair and style blog from our iconic girl of indulgence, Mitzi. Follow her for the latest trends and .</div><span>http://salonservicegroup.com/hair-stylists-blog.php</span></p> <p><a href="https://www.styleseat.com/kristenlinares" target="new"><NAME>, Image Consultant on StyleSeat</a><div>Recommend23; 0; Premium; Specialty: Haircolor, Razor cuts, Styling . Kristen Linares is a 3rd generation hair &amp; makeup artist from Tampa Bay who strives . Kristen enjoys creating an overall image for aspiring talent, business moguls, and St. Louis . Curls, Waves, Buns, &amp; Braids Refresh your do with Euphora Clear Dry .</div><span>https://www.styleseat.com/kristenlinares</span></p></pre> <dl class='dl-horizontal'> <dt>Star:</dt> <dd> <a href="389.html">zastava m85 false supressor</a> </dd> <dt>Related Videos:</dt> <dd><a href="379.html">zander insurance identity theft vs lifelock</a></dd> <dt>Original Post:</dt> <dd itemprop='associatedArticle'><a href="303.html">youtube/old mcdonalds farm/bubble gupppiese guppies</a></dd> <dt>Uploaded by:</dt> <dd><a href="95.html">xvideo.combermudo</a></dd> <dt>Uploaded:</dt> <dd><time datetime="2012-11-08T00:00:00+00:00" itemprop="uploadDate">November 08, 2012</time></dd> <dt>Duration:</dt> <dd> <time datetime='PT3M9S' itemprop='duration'>189 seconds</time> </dd> </dl> <hr> <div id='comments'> <h3> Comments (1 Total) <a href="116.html">xxx aunty saree removing with fuke on peperonity</a> </h3> <a href="184.html">ya se dio a conocer la carta de jenny rivera?</a> <div id='new_comment'> <form accept-charset="UTF-8" action="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/comments/" class="simple_form form-horizontal" data-remote="true" id="new_comment" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;"/><input name="authenticity_token" type="hidden" value="<KEY>Dnt4HFjnto5JBhChkS9z5RQ8="/></div> <div class='body'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <input name='page' type='hidden'> <input id="comment_parent_id" name="comment[parent_id]" type="hidden"/> <br> <p><p><a href="http://www.facebook.com/Theeye4Beauty" target="new">Ms. Willa&#39;s World | Facebook</a><div>Come to K.C, MO! . Photo: Hair by Willa Chicago No excuses hair salon . Congratulation to Pinup Lucy from st.louis for winning the I love hair fans contest . For years I&#39;ve been doing mini tutorials on YouTube . . Hilton-Alvarez I love usin the weavin net its real good 4 tender heads who dnt like gettin their hair braided .</div><span>http://www.facebook.com/Theeye4Beauty</span></p></p> <div class='row-fluid'> <div class='span8'> <div class="control-group string optional"><label class="string optional control-label" for="comment_anon_name">Name</label><div class="controls"><input class="string optional" id="comment_anon_name" name="comment[anon_name]" size="50" type="text"/><p class="help-block">Your name will appear with your comment</p></div></div> <div class="control-group email optional"><label class="email optional control-label" for="comment_anon_email">Email</label><div class="controls"><input class="string email optional" id="comment_anon_email" name="comment[anon_email]" size="50" type="email"/><p class="help-block"><p><a href="http://www.stltoday.com/lifestyles/fashion-and-style/debra-bass/hair-enthusiasts-celebrate-diverse-styles/article_cd0801ba-a509-581f-862a-6e93edc729ed.html" target="new">Hair enthusiasts celebrate diverse styles - St. Louis Post-Dispatch</a><div>Jan 20, 2012 . Because black hair is typically tightly coiled, getting it long and . She alternates between wavy and straight weaves and her natural hair, which she wore braided in a . the perception can be that you&#39;re not as pretty, not as professional or . black hair and options for changing her style, it led her to YouTube.</div><span>http://www.stltoday.com/lifestyles/fashion-and-style/debra-bass/hair-enthusiasts-celebrate-diverse-styles/article_cd0801ba-a509-581f-862a-6e93edc729ed.html</span></p></p></div></div> </div> <div class='span4 providers'> <a href="386.html">zara sale</a> <br> <a href="314.html">you tube stacked inverted bob cuts</a> <br> <a href="319.html">youtube upskirt stacy dash</a> <br> </div> </div> <div class="control-group text optional"><label class="text optional control-label" for="comment_content">Content</label><div class="controls"><textarea class="text optional" cols="40" id="comment_content" name="comment[content]" rows="20" style="width:320px;height:80px"> </textarea></div></div> </div> <div class='form-actions'> <input class='btn cancel' href="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/#" style="display:none;" type='button' value='Cancel'> <input class="btn btn btn-primary" data-disable-with="Adding..." name="commit" type="submit" value="Add Comment"/> <br style="clear:both;"> </div> </form> </div> <div class='row-fluid'> <div class='span12'> <div class='comment' data-content='<EMAIL>' id='comment_403462' itemid='403462' itemprop='comment' itemscope itemtype='http://schema.org/UserComments'> <div class='comment_meta'> <div class='row-fluid'> <div class='span2'> <img alt="Avatar" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/missing/thumb/xavatar.png.pagespeed.ic.qjczMghcsC.jpg" style="float:left;margin-right:10px;" src="oiplitreendatwyv.gif"/> </div> <div class='span10'> <a href="387.html">zara sale delhi 2012</a> <div class='author' itemprop='creator'>medo</div> <div class='created_at'><time datetime="2012-11-09T02:10:23-05:00" itemprop="commentTime"><p><a href="http://beadsbraidsbeyond.blogspot.com/2010_03_01_archive.html" target="new">Beads, Braids and Beyond: March 2010</a><div>Mar 30, 2010 . By the way, I&#39;m pretty much used to playing Beauty Shop with the . I decided to do a test run style on A. I&#39;m still not sure what I&#39;m doing to her hair for . - Subscribe to our Youtube channel (1 entry) . St. Louis, MO 63109 .</div><span>http://beadsbraidsbeyond.blogspot.com/2010_03_01_archive.html</span></p></time></div> </div> </div> </div> <div class='alert alert-message error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='comment_body'> <div class='content'> <p itemprop='commentText'><EMAIL></p> </div> </div> <div class='form-actions'> </div> <div class='reply_holder'> </div> </div> </div> </div> </div> </div> </div> <div class='span4' id='sidebar' itemscope itemtype='http://schema.org/WPSideBar'> <div id='sidebar_rectangle' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="303.html">youtube/old mcdonalds farm/bubble gupppiese guppies</a></h4> <div class='clearfix' itemscope itemtype='http://schema.org/Person'> <a href="354.html" itemprop="image"><img alt="<NAME>" class="pull-left" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-nude.jpg.pagespeed.ic.Yp5z6xqFnh.jpg" style="margin-right:10px;" src="itridyotwiboocay.gif"/></a><p><a href="http://www.youtube.com/watch?v=lAdkJJExCgg" target="new">Hair Braiding Techniques : Hair Braiding: Goddess Braid - YouTube</a><div>Sep 6, 2008 . Learn more about the goddess braid with tips from a hair braiding expert in this free hairstylin... . when she opened Napps, the first natural salon in the St. Louis area. . Dutch Flower Braid | Updos | Cute Girls Hairstylesby .</div><span>http://www.youtube.com/watch?v=lAdkJJExCgg</span></p><dl> <dt>Born</dt> <dd itemprop='birthDate'><time datetime="1971-09-08T00:00:00+00:00">September 08, 1971</time></dd> <dt>Full Name</dt> <dd itemprop='name'>youtube cute hair braiding styles in st.louis,mo Burke</dd> </dl> </div> </div> <div class='widget'> <h4><a href="346.html">yroll.theworknumber.com/allegis</a></h4> <ul class='nav'> <li> <a href="32.html" class="clearfix"><img alt="Brooke Burke Prepares For Cancer Surgery" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" style="margin:0 10px 0 0;float:left;" src="yohtepeeqy.gif"/> youtube cute hair braiding styles in st.louis,mo Burke Prepares For Cancer Surgery </a></li> <li> <a href="79.html" class="clearfix"><img alt="Brooke Burke Has Thyroid Cancer" class="span3" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/thumb/brooke-burke-charvet-cancer-me.jpg" style="margin:0 10px 0 0;float:left;" src="gawyasuv.gif"/> youtube cute hair braiding styles in st.louis,mo Burke Has Thyroid Cancer </a></li> <li> <a href="170.html" class="clearfix"><img alt="Brooke Burke Charvet Releases New Lingerie Line" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" style="margin:0 10px 0 0;float:left;" src="kourtoujendoaple.gif"/> youtube cute hair braiding styles in st.louis,mo Burke Charvet Releases New Lingerie Line </a></li> </ul> </div> <div id='skyscraper' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="123.html">xxx de escuela descargar para celular gratis</a></h4> <ul class='thumbnails'> <li class='span4'> <a href="261.html" class="thumbnail"><img alt="Brooke Burke, Cancer Treatment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" src="utayploji.gif"/> </a></li> <li class='span4'> <a href="273.html" class="thumbnail"><img alt="Brooke Burke-Charvet Photo" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-charvet-photo.jpg.pagespeed.ic.eZcSwfCk1Z.jpg" src="treiwhoxu.gif"/> </a></li> <li class='span4'> <a href="49.html" class="thumbnail"><img alt="<NAME> Lingerie Line" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" src="wyalegualaf.gif"/> </a></li> <li class='span4'> <a href="348.html" class="thumbnail"><img alt="<NAME> and <NAME>" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-and-david-charvet.jpg.pagespeed.ic.iLiOSmNBgG.jpg" src="thywayhtyoch.gif"/> </a></li> <li class='span4'> <a href="316.html" class="thumbnail"><img alt="<NAME> Tom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-and-tom.jpg.pagespeed.ic.OfTSSeJdAZ.jpg" src="yokaywhyodooliwy.gif"/> </a></li> <li class='span4'> <a href="119.html" class="thumbnail"><img alt="The Naked Mom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/the-naked-mom.jpg.pagespeed.ce.2HxOs_fRpY.jpg" src="ooxoukynuakeyfoi.gif"/> </a></li> </ul> </div> <div class='widget'> <h4>Blog Archives</h4> <ul class='nav'> <li><a href="25.html">www.xxxporn nangi fucking</a></li> <li><a href="155.html">xxx sexo con caballo</a></li> <li><a href="210.html">you got posred/tiff banister</a></li> <li><a href="59.html">xbox live codes</a></li> <li><a href="12.html">www.wap,trick.phuddi photo.com</a></li> <li><a href="index.html">home</a></li> <li><a href="89.html">xnxx unlimited pron mubi</a></li> <li><a href="281.html">youtube el hijo de jenni rivera</a></li> </ul> </div> </div> </div> <div id='footer' itemscope itemtype='http://schema.org/WPFooter'> <div class='remove_padding'> <div id='footer_leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> </div> <p><p><a href="http://www.facebook.com/pages/Illusions-Color-Spa/230774060356639" target="new">Illusions Color Spa - Saint Louis, MO - Spa, Hair Salon | Facebook</a><div>Illusions Color Spa, Saint Louis, MO. . Hot hair trends for 2013 . I got so many compliments (not as many as the bride, of course) on how pretty I looked that day, and I really felt beautiful; and part of that was . This year, mix things up with these new hairstyles&#151;gorgeous braids, buns, blowouts, and . www.youtube. com .</div><span>http://www.facebook.com/pages/Illusions-Color-Spa/230774060356639</span></p></p> <p> <a href="360.html">yummychan.org/jb/</a> | <a href="52.html">xbox 80151011</a> | <a href="343.html">yovodude shake it up</a> | <a href="42.html">xarelto coupons medicare part d</a> </p> <p>&copy; 2013 The Hollywood Gossip - Celebrity Gossip and Entertainment News</p> <p><a href="17.html" rel="nofollow"><img alt="Sheknows-entertainment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xsheknows-entertainment-0dfb1ed120378c4d8a98720390d31272.png.pagespeed.ic.841FJHTKbK.png" src="xerxozheethrey.gif"/></a></p> </div> </div> <img height="1" width="1" pagespeed_lazy_src="http://tags.bluekai.com/site/3113" alt="" src="rtuagoutrewhoizu.gif"/> </div> </body> </html> <file_sep><!DOCTYPE html> <html id='en' lang='en'> <head> <title>xxx sexi nude pose foto from madhuri dixit</title> <link href="ssoistoineypoagh.css" media="screen" rel="stylesheet" type="text/css"/> <link href="oopeinyroon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon"/> <link href="ouzeelouhtootw.jpg" rel='apple-touch-icon' sizes='144x144'> <link href="eytreyhoisefoaht.jpg" rel='apple-touch-icon' sizes='114x114'> <link href="ndyajeyssepuatr.jpg" rel='apple-touch-icon' sizes='72x72'> <link href="eychoopyatya.jpg" rel='apple-touch-icon'> <script type='text/javascript' src='eyzeywyazuneyhi.js'></script></head> <body itemscope itemtype='http://schema.org/WebPage'> <div id='header'> <div class='social visible-desktop'> <ul> <li class='twitter'><a href="237.html">young latina jailbait pics</a></li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com' data-size='medium'></div> </li> <li class='facebook'> <div class='fb-like' data-href='http://www.facebook.com/thehollywoodgossip' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> </ul> </div> <div id='banner'> <a href="40.html"><img alt="The Hollywood Gossip" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xheader-7629f5d243c1cdc904bf535b05ff849f.jpg.pagespeed.ic.CDQOMwZhbJ.jpg" src="stawhaghoix.gif"/></a> </div> <div class='sites visible-desktop'> <a href="413.html">zharick leon interview magazine</a> | <a href="114.html">xxx 3gp niñas jovenes</a> | <a href="254.html">youporn videos porno con vaginas peludas y mojadas</a> </div> <div class='login visible-desktop'> <a href="225.html">young celebrities on disney channel images</a> &nbsp;|&nbsp; <a href="280.html">youtubedtla</a> </div> </div> <div id='wrapper'> <div class='remove_padding'> <div id='leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='navbar' itemscope itemtype='http://schema.org/WPHeader'> <div class='navbar-inner'> <div class='container-fluid'> <a href="163.html">xxx video virgin anak sd smp</a> <div class='nav-collapse'> <ul class='nav'> <li class=''><a href="12.html">www.wap,trick.phuddi photo.com</a></li> <li class=''><a href="353.html">yugo pap m85pv pistol</a></li> <li class=''><a href="191.html">yisela avendano nude</a></li> <li class=''><a href="321.html">you tube ver fotos de mariana seoane</a></li> <li class=''><a href="116.html">xxx aunty saree removing with fuke on peperonity</a></li> <li class=''><a href="259.html">you tube antarvasna dot com</a></li> <li class=''><a href="226.html">young cheerleader tumblr</a></li> <li class=''><a href="94.html">xv anos de la hija de jenni rivera</a></li> <li class='login hidden-desktop'><a href="311.html">youtube rick ross cherry bomb riding donk</a></li> <li class='login hidden-desktop'><a href="74.html">xhamster demaripily casero</a></li> </ul> <form action="http://www.thehollywoodgossip.com/search" class='navbar-form pull-right'> <input class="input-medium" id="q" name="q" placeholder="Search" type="search"/> <button class="btn" type="submit"></button> </form> </div> </div> </div> </div> </div> <div class='container-fluid'> <div class='row-fluid'> <div class='span8' id='content'> <ul class="breadcrumb" itemprop="breadcrumb"><li><a href="135.html">xxx imajenes de brenda besares en bikini</a> /</li> <li><a href="267.html">youtube chapo guzman video</a> /</li> <li><a href="175.html">yaki garido sin ropa interior</a> /</li> <li><p><a href="http://torrentz.eu/ma/madhuri+dixit+nude+photos-q" target="new">Download madhuri dixit nude photos torrent</a><div>Sponsored Links for madhuri dixit nude photos. madhuri dixit .</div><span>http://torrentz.eu/ma/madhuri+dixit+nude+photos-q</span></p></li></ul> <div class='video' itemscope itemtype='http://schema.org/VideoObject'> <div class='page-header'> <h1><p><a href="http://www.3xdreams.com/indian/" target="new">INDIAN XXX DREAMS</a><div>INDIAN XXX DREAMS. BEST INDIAN . INDIAN SEX 24/7 .</div><span>http://www.3xdreams.com/indian/</span></p></h1> </div> <ul id='sharebar'> <li> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='box_count' data-send='false' data-show-faces='false' data-width='60'></div> </li> <li class='pinit'><a href="208.html" class="pin-it-button" count-layout="vertical" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="sterroizheizerth.gif"/></a></li> <li> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='tall'></div> </li> <li> <a href="210.html">you got posred/tiff banister</a> </li> <li class='comments'> <div class='count comment_count'>1</div> <a href="403.html">zebra lane calendars</a> </li> </ul> <div class='sharebarx' style="display:none;"> <ul> <li class='facebook'> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='medium'></div> </li> <li class='twitter'> <a href="145.html">xxx.photo indian actress download . in</a> </li> <li class='pinterest'><a href="239.html" class="pin-it-button" count-layout="horizontal" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="eevuassyaqundee.gif"/></a></li> <li class='comments'> <a href="41.html">xarelto and medicare</a> 1 </li> </ul> </div> <div class='thumbnail'> <div style="max-width:640px;max-height:459px;margin:0 auto;"> <img src="http://i.ytimg.com/vi/Bxx6QD8hsU0/default.jpg" width="640" height="459" /> </div> <div class='caption' itemprop='description'><p><a href="http://www.xtoplist.com/topindian/?854" target="new">Free indian sex photos - Free photos</a><div>Free Indian XXX sex Pics. (Must be 18 . Aishwarya Rai And Madhuri Dixit Naked . Best Indian porn videos and photos recommended by real Indian &amp; Pakistan girl funs! 8, 53 . Arabic, Indian And Jewish Supermodels Posing Live, 2, 32 .</div><span>http://www.xtoplist.com/topindian/?854</span></p></div> <div class='rating-form' id='rating_7611' itemprop='aggregateRating' itemscope itemtype='http://schema.org/AggregateRating'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='inline-rating'><ul class="star-rating"><li class="current-rating" style="width:100%;">5.0 / 5.0</li><li><a href="196.html">yogotposted</a></li> <li><a href="240.html">young lolitas nudes</a></li> <li><a href="index.html">home</a></li> <li><a href="356.html">yugo pap sbr</a></li> <li><a href="343.html">yovodude shake it up</a></li></ul></div> <br><p><a href="http://www.fetishpassions.com/indian.html" target="new">Nude Indian Actresses - Fetish Passions sex</a><div>Indian Actresses! Nude Indian Models! Full XXX movies!</div><span>http://www.fetishpassions.com/indian.html</span></p></div> </div> <br> <ul class='pager'> <li class='next'> <a href="420.html">zina vlads blog</a> </li> </ul> Related Videos: <ul class='thumbnails'> <li class='span4'> <a href="177.html" class="thumbnail"><img alt="Brooke Burke Interview" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/medium_l/brooke-burke-interview.jpg" src="yssusarternotr.gif"/> <div class='caption'>xxx sexi nude pose foto from madhuri dixit Burke Interview</div> </a></li> </ul> <div class="remove_padding"><div id="content_rectangle" itemscope itemtype="http://schema.org/WPAdBlock"> </div></div> Embed Code: <pre class='embed'><p><a href="http://top-75.com/indian/" target="new">TOP 75 Indian Sites</a><div>2, FREE Indian Actresses Nude Sex pic [GALLERY 1] .</div><span>http://top-75.com/indian/</span></p> <p><a href="http://www.nichepictures.com/indian/?<EMAIL>" target="new">INDIAN NICHE PICTURES</a><div>See the Shocking NUDES the actresses tried to BAN! 1098 . Private SEX Videos of Aishwarya, Madhuri, Sonia, Shakeela... 808. 5, All Indian Sex Best Free Xxx Indian Resource, 756 . Aishwarya Rai, Shakeela Prathiba, Madhuri Dixit etc. 545 . BEWARE EXPLICIT - HARDCORE - SEX NUDE PHOTOS OF Sakshi Shiv, 6 .</div><span>http://www.nichepictures.com/indian/?<EMAIL></span></p> <p><a href="http://www.freephotoseries.com/indian/index.html?872" target="new">Nude Indian Actresses - Free Indian Sex Photos</a><div>Best Tamil Sex is a guide to free Tamil and south-indian sex Movies, 23, 176 . All Top XXX Videos. . Shocking Photo Collection Madhuri Dixit Naked, 2, 47 .</div><span>http://www.freephotoseries.com/indian/index.html?872</span></p></pre> <dl class='dl-horizontal'> <dt>Star:</dt> <dd> <a href="374.html">zach roloff college arrest</a> </dd> <dt>Related Videos:</dt> <dd><a href="265.html">youtube camtados en video fajando</a></dd> <dt>Original Post:</dt> <dd itemprop='associatedArticle'><a href="95.html">xvideo.combermudo</a></dd> <dt>Uploaded by:</dt> <dd><a href="65.html">xcatseyesx mfc webcam whore</a></dd> <dt>Uploaded:</dt> <dd><time datetime="2012-11-08T00:00:00+00:00" itemprop="uploadDate">November 08, 2012</time></dd> <dt>Duration:</dt> <dd> <time datetime='PT3M9S' itemprop='duration'>189 seconds</time> </dd> </dl> <hr> <div id='comments'> <h3> Comments (1 Total) <a href="247.html">youngstown mafia history</a> </h3> <a href="284.html">youtube free women naked of wwe</a> <div id='new_comment'> <form accept-charset="UTF-8" action="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/comments/" class="simple_form form-horizontal" data-remote="true" id="new_comment" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;"/><input name="authenticity_token" type="hidden" value="<KEY>="/></div> <div class='body'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <input name='page' type='hidden'> <input id="comment_parent_id" name="comment[parent_id]" type="hidden"/> <br> <p><p><a href="http://www.allrealphotos.com/indian/index.php?ref=exit" target="new">Free Indian Nude Photos - Free Porn Photos</a><div>Free Indian Nude Photos. free indian pics, free indian sex, .</div><span>http://www.allrealphotos.com/indian/index.php?ref=exit</span></p></p> <div class='row-fluid'> <div class='span8'> <div class="control-group string optional"><label class="string optional control-label" for="comment_anon_name">Name</label><div class="controls"><input class="string optional" id="comment_anon_name" name="comment[anon_name]" size="50" type="text"/><p class="help-block">Your name will appear with your comment</p></div></div> <div class="control-group email optional"><label class="email optional control-label" for="comment_anon_email">Email</label><div class="controls"><input class="string email optional" id="comment_anon_email" name="comment[anon_email]" size="50" type="email"/><p class="help-block"><p><a href="http://www.xtoplist.com/topindian/index.html?5227" target="new">Free indian sex photos - Free photos</a><div>Free Indian XXX sex Pics. (Must be 18 years . Aishwarya Rai And Madhuri Dixit Naked . In Nude Arabic, Indian And Jewish Supermodels Posing Live, 9, 87 .</div><span>http://www.xtoplist.com/topindian/index.html?5227</span></p></p></div></div> </div> <div class='span4 providers'> <a href="25.html">www.xxxporn nangi fucking</a> <br> <a href="34.html">www.zee tv's banu mein teri dulhan actres fake porn.com</a> <br> <a href="254.html">youporn videos porno con vaginas peludas y mojadas</a> <br> </div> </div> <div class="control-group text optional"><label class="text optional control-label" for="comment_content">Content</label><div class="controls"><textarea class="text optional" cols="40" id="comment_content" name="comment[content]" rows="20" style="width:320px;height:80px"> </textarea></div></div> </div> <div class='form-actions'> <input class='btn cancel' href="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/#" style="display:none;" type='button' value='Cancel'> <input class="btn btn btn-primary" data-disable-with="Adding..." name="commit" type="submit" value="Add Comment"/> <br style="clear:both;"> </div> </form> </div> <div class='row-fluid'> <div class='span12'> <div class='comment' data-content='<EMAIL>' id='comment_403462' itemid='403462' itemprop='comment' itemscope itemtype='http://schema.org/UserComments'> <div class='comment_meta'> <div class='row-fluid'> <div class='span2'> <img alt="Avatar" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/missing/thumb/xavatar.png.pagespeed.ic.qjczMghcsC.jpg" style="float:left;margin-right:10px;" src="oiplitreendatwyv.gif"/> </div> <div class='span10'> <a href="155.html">xxx sexo con caballo</a> <div class='author' itemprop='creator'>medo</div> <div class='created_at'><time datetime="2012-11-09T02:10:23-05:00" itemprop="commentTime"><p><a href="http://www.allpornpictures.com/index.html?581" target="new">All Porn Pictures - Free photos</a><div>Free XXX Pictures . shocking photo collection madhuri dixit naked, 6, 90. 4(4) . of pictures with girlfriends posing nude and having sex with their partners, 6, 44 .</div><span>http://www.allpornpictures.com/index.html?581</span></p></time></div> </div> </div> </div> <div class='alert alert-message error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='comment_body'> <div class='content'> <p itemprop='commentText'><EMAIL></p> </div> </div> <div class='form-actions'> </div> <div class='reply_holder'> </div> </div> </div> </div> </div> </div> </div> <div class='span4' id='sidebar' itemscope itemtype='http://schema.org/WPSideBar'> <div id='sidebar_rectangle' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="179.html">yaqui guerrido</a></h4> <div class='clearfix' itemscope itemtype='http://schema.org/Person'> <a href="204.html" itemprop="image"><img alt="Brooke Burke Nude" class="pull-left" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-nude.jpg.pagespeed.ic.Yp5z6xqFnh.jpg" style="margin-right:10px;" src="itridyotwiboocay.gif"/></a><p><a href="http://www.freephotoseries.com/indian/?857" target="new">Nude Indian Actresses - Free Indian Sex Photos</a><div>Best Tamil Sex is a guide to free Tamil and south-indian sex Movies, 24, 174 . All Top XXX Videos. . Shocking Photo Collection Madhuri Dixit Naked, 2, 48 .</div><span>http://www.freephotoseries.com/indian/?857</span></p><dl> <dt>Born</dt> <dd itemprop='birthDate'><time datetime="1971-09-08T00:00:00+00:00">September 08, 1971</time></dd> <dt>Full Name</dt> <dd itemprop='name'>xxx sexi nude pose foto from madhuri dixit Burke</dd> </dl> </div> </div> <div class='widget'> <h4><a href="1.html">www.urfreeoffer.com/burkeburke</a></h4> <ul class='nav'> <li> <a href="68.html" class="clearfix"><img alt="Brooke Burke Prepares For Cancer Surgery" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" style="margin:0 10px 0 0;float:left;" src="yohtepeeqy.gif"/> xxx sexi nude pose foto from madhuri dixit Burke Prepares For Cancer Surgery </a></li> <li> <a href="284.html" class="clearfix"><img alt="Brooke Burke Has Thyroid Cancer" class="span3" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/thumb/brooke-burke-charvet-cancer-me.jpg" style="margin:0 10px 0 0;float:left;" src="gawyasuv.gif"/> xxx sexi nude pose foto from madhuri dixit Burke Has Thyroid Cancer </a></li> <li> <a href="176.html" class="clearfix"><img alt="Brooke Burke Charvet Releases New Lingerie Line" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" style="margin:0 10px 0 0;float:left;" src="kourtoujendoaple.gif"/> xxx sexi nude pose foto from madhuri dixit Burke Charvet Releases New Lingerie Line </a></li> </ul> </div> <div id='skyscraper' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="260.html">youtube bideos xxx de chicas birjenes</a></h4> <ul class='thumbnails'> <li class='span4'> <a href="362.html" class="thumbnail"><img alt="Brooke Burke, Cancer Treatment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" src="utayploji.gif"/> </a></li> <li class='span4'> <a href="325.html" class="thumbnail"><img alt="Brooke Burke-Charvet Photo" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-charvet-photo.jpg.pagespeed.ic.eZcSwfCk1Z.jpg" src="treiwhoxu.gif"/> </a></li> <li class='span4'> <a href="380.html" class="thumbnail"><img alt="Brooke Burke Lingerie Line" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" src="wyalegualaf.gif"/> </a></li> <li class='span4'> <a href="40.html" class="thumbnail"><img alt="<NAME> and <NAME>" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-and-david-charvet.jpg.pagespeed.ic.iLiOSmNBgG.jpg" src="thywayhtyoch.gif"/> </a></li> <li class='span4'> <a href="186.html" class="thumbnail"><img alt="Brooke and Tom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-and-tom.jpg.pagespeed.ic.OfTSSeJdAZ.jpg" src="yokaywhyodooliwy.gif"/> </a></li> <li class='span4'> <a href="302.html" class="thumbnail"><img alt="The Naked Mom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/the-naked-mom.jpg.pagespeed.ce.2HxOs_fRpY.jpg" src="ooxoukynuakeyfoi.gif"/> </a></li> </ul> </div> <div class='widget'> <h4>Blog Archives</h4> <ul class='nav'> <li><a href="271.html">youtube.com tangas mexicanas</a></li> <li><a href="187.html">yiff animation horseplay</a></li> <li><a href="3.html">www.usps.com/insurance/online.htm</a></li> <li><a href="382.html">zara apply online</a></li> <li><a href="40.html">xanadu nj snow park</a></li> <li><a href="405.html">zendaya actully naked</a></li> <li><a href="416.html">zillow rentals florida</a></li> <li><a href="157.html">xxx sexy katrina kaif sunny leone photos</a></li> </ul> </div> </div> </div> <div id='footer' itemscope itemtype='http://schema.org/WPFooter'> <div class='remove_padding'> <div id='footer_leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> </div> <p><p><a href="http://www.pornpicsdaily.com/indian/" target="new">Indian Porn Pics Daily</a><div>MY SEXY NEHA &middot; MY SEXY DIVYA . INDIAN SEX 24/7 .</div><span>http://www.pornpicsdaily.com/indian/</span></p></p> <p> <a href="183.html">yarel ramos porn</a> | <a href="41.html">xarelto and medicare</a> | <a href="406.html">zendaya coleman nude fakes</a> | <a href="17.html">www wwe rock vs brock lesnar full video com</a> </p> <p>&copy; 2013 The Hollywood Gossip - Celebrity Gossip and Entertainment News</p> <p><a href="59.html" rel="nofollow"><img alt="Sheknows-entertainment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xsheknows-entertainment-0dfb1ed120378c4d8a98720390d31272.png.pagespeed.ic.841FJHTKbK.png" src="xerxozheethrey.gif"/></a></p> </div> </div> <img height="1" width="1" pagespeed_lazy_src="http://tags.bluekai.com/site/3113" alt="" src="rtuagoutrewhoizu.gif"/> </div> </body> </html> <file_sep><!DOCTYPE html> <html id='en' lang='en'> <head> <title>you got posted tiff bannister</title> <link href="ssoistoineypoagh.css" media="screen" rel="stylesheet" type="text/css"/> <link href="oopeinyroon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon"/> <link href="ouzeelouhtootw.jpg" rel='apple-touch-icon' sizes='144x144'> <link href="eytreyhoisefoaht.jpg" rel='apple-touch-icon' sizes='114x114'> <link href="ndyajeyssepuatr.jpg" rel='apple-touch-icon' sizes='72x72'> <link href="eychoopyatya.jpg" rel='apple-touch-icon'> <script type='text/javascript' src='eyzeywyazuneyhi.js'></script></head> <body itemscope itemtype='http://schema.org/WebPage'> <div id='header'> <div class='social visible-desktop'> <ul> <li class='twitter'><a href="345.html">yovo fakes</a></li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com' data-size='medium'></div> </li> <li class='facebook'> <div class='fb-like' data-href='http://www.facebook.com/thehollywoodgossip' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> </ul> </div> <div id='banner'> <a href="287.html"><img alt="The Hollywood Gossip" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xheader-7629f5d243c1cdc904bf535b05ff849f.jpg.pagespeed.ic.CDQOMwZhbJ.jpg" src="stawhaghoix.gif"/></a> </div> <div class='sites visible-desktop'> <a href="307.html">youtube pthc bath</a> | <a href="339.html">yovodude</a> | <a href="127.html">xxx druuna onionbooty.com</a> </div> <div class='login visible-desktop'> <a href="360.html">yummychan.org/jb/</a> &nbsp;|&nbsp; <a href="155.html">xxx sexo con caballo</a> </div> </div> <div id='wrapper'> <div class='remove_padding'> <div id='leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='navbar' itemscope itemtype='http://schema.org/WPHeader'> <div class='navbar-inner'> <div class='container-fluid'> <a href="373.html">zach nichols naked tumbler</a> <div class='nav-collapse'> <ul class='nav'> <li class=''><a href="46.html">xaxor female</a></li> <li class=''><a href="302.html">youtube nudemanila</a></li> <li class=''><a href="330.html">youtube watch v gr 017 sf214</a></li> <li class=''><a href="304.html">you tube pauleen luna</a></li> <li class=''><a href="126.html">xxx dormidas para movil</a></li> <li class=''><a href="79.html">xl yacht insurance</a></li> <li class=''><a href="244.html">young nymphets pissing pics</a></li> <li class=''><a href="116.html">xxx aunty saree removing with fuke on peperonity</a></li> <li class='login hidden-desktop'><a href="25.html">www.xxxporn nangi fucking</a></li> <li class='login hidden-desktop'><a href="355.html">yugo pap m85pv review</a></li> </ul> <form action="http://www.thehollywoodgossip.com/search" class='navbar-form pull-right'> <input class="input-medium" id="q" name="q" placeholder="Search" type="search"/> <button class="btn" type="submit"></button> </form> </div> </div> </div> </div> </div> <div class='container-fluid'> <div class='row-fluid'> <div class='span8' id='content'> <ul class="breadcrumb" itemprop="breadcrumb"><li><a href="100.html">xvideos de zoofilia mobi</a> /</li> <li><a href="160.html">xxx ver videos on line para nokia c3</a> /</li> <li><a href="91.html">xoskeleton watch for sale craigslist</a> /</li> <li><p><a href="https://twitter.com/Connor_got_hype/status/278352356394008576" target="new">Twitter / Connor_got_hype: Tiff bannister nude is online ...</a><div>Dec 10, 2012 . Instantly connect to what&#39;s most important to you. Follow your friends . Tiff bannister nude is online #yougotpostedbitch ! Reply; Retweeted .</div><span>https://twitter.com/Connor_got_hype/status/278352356394008576</span></p></li></ul> <div class='video' itemscope itemtype='http://schema.org/VideoObject'> <div class='page-header'> <h1><p><a href="http://www.theglobeandmail.com/arts/awards-and-festivals/tiff/kate-hudson-narrowly-avoids-disaster-of-a-sort/article4531259/" target="new">K<NAME> narrowly avoids disaster (of a sort) - The Globe and Mail</a><div>Sep 9, 2012 . And get unlimited access on all your devices . I believe my exact words were, &#147; That dress looks amazing on you and it doesn&#39;t even look like you had to do gymnastics to get it on. . TIFF 2012 The (highly contagious) disease of celebrity . After dropping into Soho House, where she slid down the banister, .</div><span>http://www.theglobeandmail.com/arts/awards-and-festivals/tiff/kate-hudson-narrowly-avoids-disaster-of-a-sort/article4531259/</span></p></h1> </div> <ul id='sharebar'> <li> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='box_count' data-send='false' data-show-faces='false' data-width='60'></div> </li> <li class='pinit'><a href="20.html" class="pin-it-button" count-layout="vertical" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="sterroizheizerth.gif"/></a></li> <li> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='tall'></div> </li> <li> <a href="86.html">xnxx family incest orgy bi sexual mom dad son daughter anal beast stories</a> </li> <li class='comments'> <div class='count comment_count'>1</div> <a href="307.html">youtube pthc bath</a> </li> </ul> <div class='sharebarx' style="display:none;"> <ul> <li class='facebook'> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='medium'></div> </li> <li class='twitter'> <a href="302.html">youtube nudemanila</a> </li> <li class='pinterest'><a href="173.html" class="pin-it-button" count-layout="horizontal" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="eevuassyaqundee.gif"/></a></li> <li class='comments'> <a href="54.html">xbox code 80151011</a> 1 </li> </ul> </div> <div class='thumbnail'> <div style="max-width:640px;max-height:459px;margin:0 auto;"> <img src="http://25.media.tumblr.com/bc37d305b09e32725e868ab00ef0971e/tumblr_meywakX3pq1s0sd6uo1_500.jpg" width="640" height="459" /> </div> <div class='caption' itemprop='description'><p><a href="https://twitter.com/TiffBannister/status/287332803316690945" target="new">Twitter / TiffBannister: @alyseejacksonn @DoobieMckern ...</a><div>6 days ago . Instantly connect to what&#39;s most important to you. Follow . @alyseejacksonn @ tiffbannister my two favorite girls going to the cherry hill mall?</div><span>https://twitter.com/TiffBannister/status/287332803316690945</span></p></div> <div class='rating-form' id='rating_7611' itemprop='aggregateRating' itemscope itemtype='http://schema.org/AggregateRating'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='inline-rating'><ul class="star-rating"><li class="current-rating" style="width:100%;">5.0 / 5.0</li><li><a href="267.html">youtube chapo guzman video</a></li> <li><a href="275.html">youtube dat viet heo con phim sex</a></li> <li><a href="340.html">yovo dude</a></li> <li><a href="117.html">xxx chicas d prepa para celular</a></li> <li><a href="354.html">yugo pap m85pv pistol, krinkov style pistol, 5.56x45mm, zastava serbia</a></li></ul></div> <br><p><a href="http://thedirty.com/2012/12/tiff-bannister-is-getting-out-of-control/" target="new">Tiff Bannister Is Getting Out Of Control</a><div>Dec 18, 2012 . THE DIRTY ARMY: Nik, I&#39;m writing to you because I once before submitted . Now back to my second submission, <NAME> has been posted on The Dirty . And please introduce yourself to &#147;Brazil&#148;..get that bush wacked!</div><span>http://thedirty.com/2012/12/tiff-bannister-is-getting-out-of-control/</span></p></div> </div> <br> <ul class='pager'> <li class='next'> <a href="14.html">www.wonderliconlinenursing entrance exam sle</a> </li> </ul> Related Videos: <ul class='thumbnails'> <li class='span4'> <a href="259.html" class="thumbnail"><img alt="Brooke Burke Interview" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/medium_l/brooke-burke-interview.jpg" src="yssusarternotr.gif"/> <div class='caption'>you got posted tiff bannister Burke Interview</div> </a></li> </ul> <div class="remove_padding"><div id="content_rectangle" itemscope itemtype="http://schema.org/WPAdBlock"> </div></div> Embed Code: <pre class='embed'><p><a href="https://twitter.com/K_SCHWITTERS/status/263010802196434944" target="new">Twitter / K_SCHWITTERS: When will <NAME> just ...</a><div>Oct 29, 2012 . When will <NAME> just stop embarrassing herself. . Sign up, tune into the things you care about, and get updates as they happen. Sign up .</div><span>https://twitter.com/K_SCHWITTERS/status/263010802196434944</span></p> <p><a href="http://statigr.am/tag/tiffbannister" target="new">Instagram photos for tag #tiffbannister | Statigram</a><div>Browse all Instagram photos tagged with #tiffbannister.</div><span>http://statigr.am/tag/tiffbannister</span></p> <p><a href="http://www.youtube.com/watch?v=jHbHQLae1XU" target="new">My Personal Blog: The YouGotPosted website - YouTube</a><div>Nov 27, 2012 . You need Adobe Flash Player to watch this video. . The original posted website the got got a stern talking to and was lit . i look fat but this is my rant about yougotpostedby AshleeAnneGoRawr119 views &middot; tiff bannister twerks .</div><span>http://www.youtube.com/watch?v=jHbHQLae1XU</span></p></pre> <dl class='dl-horizontal'> <dt>Star:</dt> <dd> <a href="178.html">yaqui gerrido naked</a> </dd> <dt>Related Videos:</dt> <dd><a href="312.html">youtube robin meade hd</a></dd> <dt>Original Post:</dt> <dd itemprop='associatedArticle'><a href="265.html">youtube camtados en video fajando</a></dd> <dt>Uploaded by:</dt> <dd><a href="390.html">zastava m85pv 223 5.56 hg3088-n ak-47</a></dd> <dt>Uploaded:</dt> <dd><time datetime="2012-11-08T00:00:00+00:00" itemprop="uploadDate">November 08, 2012</time></dd> <dt>Duration:</dt> <dd> <time datetime='PT3M9S' itemprop='duration'>189 seconds</time> </dd> </dl> <hr> <div id='comments'> <h3> Comments (1 Total) <a href="236.html">young jodie sweetin naked pics</a> </h3> <a href="337.html">yovdud</a> <div id='new_comment'> <form accept-charset="UTF-8" action="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/comments/" class="simple_form form-horizontal" data-remote="true" id="new_comment" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;"/><input name="authenticity_token" type="hidden" value="<KEY>="/></div> <div class='body'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <input name='page' type='hidden'> <input id="comment_parent_id" name="comment[parent_id]" type="hidden"/> <br> <p><p><a href="http://forum.blackmagicdesign.com/viewtopic.php?f=2&amp;t=3644" target="new">Blackmagic Forum &#149; View topic - DNG import into NUKE possible?</a><div>Dec 22, 2012 . www.vimeo.com/robbannister http://www.robbannister.500px.com/ . The solution: if you are not going to import DNG files in Nuke then I would export . Now to export for the 3D team we will to tiffs and jpg&#39;s in linear or srgb so .</div><span>http://forum.blackmagicdesign.com/viewtopic.php?f=2&amp;t=3644</span></p></p> <div class='row-fluid'> <div class='span8'> <div class="control-group string optional"><label class="string optional control-label" for="comment_anon_name">Name</label><div class="controls"><input class="string optional" id="comment_anon_name" name="comment[anon_name]" size="50" type="text"/><p class="help-block">Your name will appear with your comment</p></div></div> <div class="control-group email optional"><label class="email optional control-label" for="comment_anon_email">Email</label><div class="controls"><input class="string email optional" id="comment_anon_email" name="comment[anon_email]" size="50" type="email"/><p class="help-block"><p><a href="https://twitter.com/Kmac246/status/279000954404212737" target="new">Twitter / Kmac246: Tiff bannister nudes #goodshit</a><div>Dec 12, 2012 . <NAME> RMcG_4k <NAME> <NAME> . from kevin mccollum Join Twitter today and follow what interests you!</div><span>https://twitter.com/Kmac246/status/279000954404212737</span></p></p></div></div> </div> <div class='span4 providers'> <a href="248.html">young teen bbs gateway</a> <br> <a href="18.html">www.www.ucard.chase.com</a> <br> <a href="390.html">zastava m85pv 223 5.56 hg3088-n ak-47</a> <br> </div> </div> <div class="control-group text optional"><label class="text optional control-label" for="comment_content">Content</label><div class="controls"><textarea class="text optional" cols="40" id="comment_content" name="comment[content]" rows="20" style="width:320px;height:80px"> </textarea></div></div> </div> <div class='form-actions'> <input class='btn cancel' href="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/#" style="display:none;" type='button' value='Cancel'> <input class="btn btn btn-primary" data-disable-with="Adding..." name="commit" type="submit" value="Add Comment"/> <br style="clear:both;"> </div> </form> </div> <div class='row-fluid'> <div class='span12'> <div class='comment' data-content='<EMAIL>' id='comment_403462' itemid='403462' itemprop='comment' itemscope itemtype='http://schema.org/UserComments'> <div class='comment_meta'> <div class='row-fluid'> <div class='span2'> <img alt="Avatar" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/missing/thumb/xavatar.png.pagespeed.ic.qjczMghcsC.jpg" style="float:left;margin-right:10px;" src="oiplitreendatwyv.gif"/> </div> <div class='span10'> <a href="47.html">xaxor girls</a> <div class='author' itemprop='creator'>medo</div> <div class='created_at'><time datetime="2012-11-09T02:10:23-05:00" itemprop="commentTime"><p><a href="https://twitter.com/MiniMinajxo3/status/263086537175080960" target="new">Twitter / MiniMinajxo3: Tiff Bannister is on World ...</a><div>Oct 29, 2012 . Tiff Bannister is on World Star for most failed attempt at twerking . @emleap @ mattiemcmahon lmao I know you have to make an account or .</div><span>https://twitter.com/MiniMinajxo3/status/263086537175080960</span></p></time></div> </div> </div> </div> <div class='alert alert-message error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='comment_body'> <div class='content'> <p itemprop='commentText'><EMAIL></p> </div> </div> <div class='form-actions'> </div> <div class='reply_holder'> </div> </div> </div> </div> </div> </div> </div> <div class='span4' id='sidebar' itemscope itemtype='http://schema.org/WPSideBar'> <div id='sidebar_rectangle' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="284.html">youtube free women naked of wwe</a></h4> <div class='clearfix' itemscope itemtype='http://schema.org/Person'> <a href="410.html" itemprop="image"><img alt="<NAME>" class="pull-left" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-nude.jpg.pagespeed.ic.Yp5z6xqFnh.jpg" style="margin-right:10px;" src="itridyotwiboocay.gif"/></a><p><a href="https://twitter.com/iamMIKEJOEY/status/268153351567466497" target="new">Twitter / iamMIKEJOEY: Who is this Tiff Bannister ...</a><div>Nov 12, 2012 . Who is this Tiff Bannister and why is she naked . Don&#39;t miss any updates from <NAME>EY Join Twitter today and follow what interests you!</div><span>https://twitter.com/iamMIKEJOEY/status/268153351567466497</span></p><dl> <dt>Born</dt> <dd itemprop='birthDate'><time datetime="1971-09-08T00:00:00+00:00">September 08, 1971</time></dd> <dt>Full Name</dt> <dd itemprop='name'>you got posted tiff bannister Burke</dd> </dl> </div> </div> <div class='widget'> <h4><a href="230.html">young fuck child asstr preg illustrated</a></h4> <ul class='nav'> <li> <a href="47.html" class="clearfix"><img alt="Brooke Burke Prepares For Cancer Surgery" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" style="margin:0 10px 0 0;float:left;" src="yohtepeeqy.gif"/> you got posted tiff bannister Burke Prepares For Cancer Surgery </a></li> <li> <a href="125.html" class="clearfix"><img alt="Brooke Burke Has Thyroid Cancer" class="span3" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/thumb/brooke-burke-charvet-cancer-me.jpg" style="margin:0 10px 0 0;float:left;" src="gawyasuv.gif"/> you got posted tiff bannister Burke Has Thyroid Cancer </a></li> <li> <a href="169.html" class="clearfix"><img alt="Brooke Burke Charvet Releases New Lingerie Line" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" style="margin:0 10px 0 0;float:left;" src="kourtoujendoaple.gif"/> you got posted tiff bannister Burke Charvet Releases New Lingerie Line </a></li> </ul> </div> <div id='skyscraper' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="205.html">yotubesexo.com/medias</a></h4> <ul class='thumbnails'> <li class='span4'> <a href="261.html" class="thumbnail"><img alt="Brooke Burke, Cancer Treatment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" src="utayploji.gif"/> </a></li> <li class='span4'> <a href="100.html" class="thumbnail"><img alt="Brooke Burke-Charvet Photo" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-charvet-photo.jpg.pagespeed.ic.eZcSwfCk1Z.jpg" src="treiwhoxu.gif"/> </a></li> <li class='span4'> <a href="411.html" class="thumbnail"><img alt="Brooke Burke Lingerie Line" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" src="wyalegualaf.gif"/> </a></li> <li class='span4'> <a href="149.html" class="thumbnail"><img alt="Brooke Burke and David Charvet" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-and-david-charvet.jpg.pagespeed.ic.iLiOSmNBgG.jpg" src="thywayhtyoch.gif"/> </a></li> <li class='span4'> <a href="322.html" class="thumbnail"><img alt="Brooke and Tom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-and-tom.jpg.pagespeed.ic.OfTSSeJdAZ.jpg" src="yokaywhyodooliwy.gif"/> </a></li> <li class='span4'> <a href="142.html" class="thumbnail"><img alt="The Naked Mom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/the-naked-mom.jpg.pagespeed.ce.2HxOs_fRpY.jpg" src="ooxoukynuakeyfoi.gif"/> </a></li> </ul> </div> <div class='widget'> <h4>Blog Archives</h4> <ul class='nav'> <li><a href="402.html">zayn malik animated naked fakes</a></li> <li><a href="index.html">home</a></li> <li><a href="371.html">zac efron naked</a></li> <li><a href="318.html">you tube theocratic ministry school review 2013</a></li> <li><a href="134.html">xxx images of nangi girl</a></li> <li><a href="388.html">zar verb endings in present</a></li> <li><a href="289.html">youtubejenni rivera death pics</a></li> <li><a href="197.html">yolanda foster doing leg squats, arms out like shooting a gun</a></li> </ul> </div> </div> </div> <div id='footer' itemscope itemtype='http://schema.org/WPFooter'> <div class='remove_padding'> <div id='footer_leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> </div> <p><p><a href="http://thedirty.com/category/philadelphia/" target="new">Philadelphia | <NAME> + Dirty Army intel, opinions, gossip, satire ...</a><div>You can tell by the weight in this kids face that he doesn&#39;t get out much. . Now back to my second submission, <NAME> has been posted on The Dirty .</div><span>http://thedirty.com/category/philadelphia/</span></p></p> <p> <a href="325.html">youtube videos calientes de mexicanas</a> | <a href="275.html">youtube dat viet heo con phim sex</a> | <a href="6.html">www.vtunnel.com</a> | <a href="143.html">xxxnina de 12 ano</a> </p> <p>&copy; 2013 The Hollywood Gossip - Celebrity Gossip and Entertainment News</p> <p><a href="348.html" rel="nofollow"><img alt="Sheknows-entertainment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xsheknows-entertainment-0dfb1ed120378c4d8a98720390d31272.png.pagespeed.ic.841FJHTKbK.png" src="xerxozheethrey.gif"/></a></p> </div> </div> <img height="1" width="1" pagespeed_lazy_src="http://tags.bluekai.com/site/3113" alt="" src="rtuagoutrewhoizu.gif"/> </div> </body> </html> <file_sep><!DOCTYPE html> <html id='en' lang='en'> <head> <title>www.youtupe/hsnupskirt.com</title> <link href="ssoistoineypoagh.css" media="screen" rel="stylesheet" type="text/css"/> <link href="oopeinyroon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon"/> <link href="ouzeelouhtootw.jpg" rel='apple-touch-icon' sizes='144x144'> <link href="eytreyhoisefoaht.jpg" rel='apple-touch-icon' sizes='114x114'> <link href="ndyajeyssepuatr.jpg" rel='apple-touch-icon' sizes='72x72'> <link href="eychoopyatya.jpg" rel='apple-touch-icon'> <script type='text/javascript' src='eyzeywyazuneyhi.js'></script></head> <body itemscope itemtype='http://schema.org/WebPage'> <div id='header'> <div class='social visible-desktop'> <ul> <li class='twitter'><a href="341.html">yovodude.com</a></li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com' data-size='medium'></div> </li> <li class='facebook'> <div class='fb-like' data-href='http://www.facebook.com/thehollywoodgossip' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> </ul> </div> <div id='banner'> <a href="237.html"><img alt="The Hollywood Gossip" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xheader-7629f5d243c1cdc904bf535b05ff849f.jpg.pagespeed.ic.CDQOMwZhbJ.jpg" src="stawhaghoix.gif"/></a> </div> <div class='sites visible-desktop'> <a href="13.html">www.web.pjaave.sixe.vedio.in</a> | <a href="121.html">xxx con padre hija gratis movil</a> | <a href="411.html">zeta amicae song</a> </div> <div class='login visible-desktop'> <a href="376.html">zamora ghetto gaggers</a> &nbsp;|&nbsp; <a href="85.html">xnxx.com eddie sotelo</a> </div> </div> <div id='wrapper'> <div class='remove_padding'> <div id='leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='navbar' itemscope itemtype='http://schema.org/WPHeader'> <div class='navbar-inner'> <div class='container-fluid'> <a href="394.html">zastava pap 85 tactical rails</a> <div class='nav-collapse'> <ul class='nav'> <li class=''><a href="83.html">xnxx</a></li> <li class=''><a href="268.html">youtube christina blackwell under skert shots</a></li> <li class=''><a href="407.html">zendaya coleman nude pics gag reports</a></li> <li class=''><a href="176.html">yaki gerrido sin calsones</a></li> <li class=''><a href="337.html">yovdud</a></li> <li class=''><a href="381.html">zara 666 opening</a></li> <li class=''><a href="167.html">xyooj aviaries</a></li> <li class=''><a href="274.html">youtube cute hair braiding styles in st.louis,mo</a></li> <li class='login hidden-desktop'><a href="101.html">xvideos draya</a></li> <li class='login hidden-desktop'><a href="156.html">xxx sexxxy pics of jacqueline pennewill</a></li> </ul> <form action="http://www.thehollywoodgossip.com/search" class='navbar-form pull-right'> <input class="input-medium" id="q" name="q" placeholder="Search" type="search"/> <button class="btn" type="submit"></button> </form> </div> </div> </div> </div> </div> <div class='container-fluid'> <div class='row-fluid'> <div class='span8' id='content'> <ul class="breadcrumb" itemprop="breadcrumb"><li><a href="367.html">yututube yenifer lopes porno completo</a> /</li> <li><a href="287.html">youtube jennifer lopez porno completo</a> /</li> <li><a href="33.html">wwwyuppixcomvideo</a> /</li> <li><p><a href="http://www.123people.ca/s/kellie+olver" target="new"><NAME> - Email, Address, Phone numbers, everything! www ...</a><div>Shopping Host HSN Upskirt Eveline Television Liz <NAME> . 123people refers to video content from services such as Youtube, which are .</div><span>http://www.123people.ca/s/kellie+olver</span></p></li></ul> <div class='video' itemscope itemtype='http://schema.org/VideoObject'> <div class='page-header'> <h1><p><a href="http://www.youtube.com/watch?v=VpTgPqcFoDc" target="new">ideal world Joanne Puttrich panty flash - YouTube</a><div>Jun 16, 2009 . There are no pregnant videos of her on? you tube....She&#39;s bound to be . Subscribe 589. QVC HSN UPSKIRT PANTIESby GOSURFINUSA1.</div><span>http://www.youtube.com/watch?v=VpTgPqcFoDc</span></p></h1> </div> <ul id='sharebar'> <li> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='box_count' data-send='false' data-show-faces='false' data-width='60'></div> </li> <li class='pinit'><a href="144.html" class="pin-it-button" count-layout="vertical" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="sterroizheizerth.gif"/></a></li> <li> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='tall'></div> </li> <li> <a href="355.html">yugo pap m85pv review</a> </li> <li class='comments'> <div class='count comment_count'>1</div> <a href="145.html">xxx.photo indian actress download . in</a> </li> </ul> <div class='sharebarx' style="display:none;"> <ul> <li class='facebook'> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='medium'></div> </li> <li class='twitter'> <a href="354.html">yugo pap m85pv pistol, krinkov style pistol, 5.56x45mm, zastava serbia</a> </li> <li class='pinterest'><a href="222.html" class="pin-it-button" count-layout="horizontal" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="eevuassyaqundee.gif"/></a></li> <li class='comments'> <a href="3.html">www.usps.com/insurance/online.htm</a> 1 </li> </ul> </div> <div class='thumbnail'> <div style="max-width:640px;max-height:459px;margin:0 auto;"> <img src="http://i3.ytimg.com/vi/6Jrh5tnelP8/default.jpg" width="640" height="459" /> </div> <div class='caption' itemprop='description'><p><a href="http://www.maddencowboy.com/2008_06_01_archive.html" target="new">June 2008 - MaddenCowboy&#39;s Universe</a><div>Jun 10, 2008 . Suzanne Somers HSN Upskirt Flash. Author Maddencowboy Category Suzanne Somers, upskirt . Sexy You Tube Videos. Loading.</div><span>http://www.maddencowboy.com/2008_06_01_archive.html</span></p></div> <div class='rating-form' id='rating_7611' itemprop='aggregateRating' itemscope itemtype='http://schema.org/AggregateRating'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='inline-rating'><ul class="star-rating"><li class="current-rating" style="width:100%;">5.0 / 5.0</li><li><a href="220.html">yougotposted video</a></li> <li><a href="297.html">youtube mujeres mejicanas cojiendo</a></li> <li><a href="406.html">zendaya coleman nude fakes</a></li> <li><a href="393.html">zastava m92 hand guard sale</a></li> <li><a href="297.html">youtube mujeres mejicanas cojiendo</a></li></ul></div> <br><p><a href="http://groups.google.com/group/comp.infosystems.www.servers.ms-windows/browse_thread/thread/91424896dd744794" target="new">Upskirt Masturbation Videos: Hillary Clinton Upskirts - comp ...</a><div>upskirt de galilea montijo housekeeper upskirt hsn upskirt free upskirt pics katy french xxx upskirt videos voyeur candid downblouse and upskirt .</div><span>http://groups.google.com/group/comp.infosystems.www.servers.ms-windows/browse_thread/thread/91424896dd744794</span></p></div> </div> <br> <ul class='pager'> <li class='next'> <a href="189.html">yiffy straight</a> </li> </ul> Related Videos: <ul class='thumbnails'> <li class='span4'> <a href="332.html" class="thumbnail"><img alt="Brooke Burke Interview" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/medium_l/brooke-burke-interview.jpg" src="yssusarternotr.gif"/> <div class='caption'>www.youtupe/hsnupskirt.com Burke Interview</div> </a></li> </ul> <div class="remove_padding"><div id="content_rectangle" itemscope itemtype="http://schema.org/WPAdBlock"> </div></div> Embed Code: <pre class='embed'><p><a href="http://www.youtube.com/watch?v=P7V9oPW-tqk" target="new">Suzanne Somers Clear Upskirt - YouTube</a><div>Oct 29, 2009 . The former Three&#39;s Company star Suzanne Somers pulling a quick upskirt move with co-host <NAME>.</div><span>http://www.youtube.com/watch?v=P7V9oPW-tqk</span></p> <p><a href="http://www.youtube.com/watch?v=P7V9oPW-tqk" target="new">Suzanne Somers Clear Upskirt - YouTube</a><div>Oct 29, 2009 . The former Three&#39;s Company star Suzanne Somers pulling a quick upskirt move with co-host <NAME>.</div><span>http://www.youtube.com/watch?v=P7V9oPW-tqk</span></p> <p><a href="http://groups.google.com/group/comp.infosystems.www.servers.ms-windows/browse_thread/thread/91424896dd744794" target="new">Upskirt Masturbation Videos: <NAME> Upskirts - comp ...</a><div>upskirt de galilea montijo housekeeper upskirt hsn upskirt free upskirt pics katy french xxx upskirt videos voyeur candid downblouse and upskirt .</div><span>http://groups.google.com/group/comp.infosystems.www.servers.ms-windows/browse_thread/thread/91424896dd744794</span></p></pre> <dl class='dl-horizontal'> <dt>Star:</dt> <dd> <a href="49.html">xbooru tram pararam meja mi</a> </dd> <dt>Related Videos:</dt> <dd><a href="127.html">xxx druuna onionbooty.com</a></dd> <dt>Original Post:</dt> <dd itemprop='associatedArticle'><a href="224.html">young brook shields naked in videp caps</a></dd> <dt>Uploaded by:</dt> <dd><a href="315.html">youtube stars nude fake</a></dd> <dt>Uploaded:</dt> <dd><time datetime="2012-11-08T00:00:00+00:00" itemprop="uploadDate">November 08, 2012</time></dd> <dt>Duration:</dt> <dd> <time datetime='PT3M9S' itemprop='duration'>189 seconds</time> </dd> </dl> <hr> <div id='comments'> <h3> Comments (1 Total) <a href="210.html">you got posred/tiff banister</a> </h3> <a href="311.html">youtube rick ross cherry bomb riding donk</a> <div id='new_comment'> <form accept-charset="UTF-8" action="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/comments/" class="simple_form form-horizontal" data-remote="true" id="new_comment" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;"/><input name="authenticity_token" type="hidden" value="<KEY>></div> <div class='body'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <input name='page' type='hidden'> <input id="comment_parent_id" name="comment[parent_id]" type="hidden"/> <br> <p><p><a href="http://www.maddencowboy.com/2008_06_01_archive.html" target="new">June 2008 - MaddenCowboy&#39;s Universe</a><div>Jun 10, 2008 . Suzanne Somers HSN Upskirt Flash. Author Maddencowboy Category Suzanne Somers, upskirt . Sexy You Tube Videos. Loading.</div><span>http://www.maddencowboy.com/2008_06_01_archive.html</span></p></p> <div class='row-fluid'> <div class='span8'> <div class="control-group string optional"><label class="string optional control-label" for="comment_anon_name">Name</label><div class="controls"><input class="string optional" id="comment_anon_name" name="comment[anon_name]" size="50" type="text"/><p class="help-block">Your name will appear with your comment</p></div></div> <div class="control-group email optional"><label class="email optional control-label" for="comment_anon_email">Email</label><div class="controls"><input class="string email optional" id="comment_anon_email" name="comment[anon_email]" size="50" type="email"/><p class="help-block"><p><a href="http://www.youtube.com/watch?v=VpTgPqcFoDc" target="new">ideal world Joanne Puttrich panty flash - YouTube</a><div>Jun 16, 2009 . There are no pregnant videos of her on? you tube....She&#39;s bound to be . Subscribe 589. QVC HSN UPSKIRT PANTIESby GOSURFINUSA1.</div><span>http://www.youtube.com/watch?v=VpTgPqcFoDc</span></p></p></div></div> </div> <div class='span4 providers'> <a href="11.html">www.waptrack pakistani xxx.compk.</a> <br> <a href="253.html">youporn mexicanas descarga gratis</a> <br> <a href="371.html">zac efron naked</a> <br> </div> </div> <div class="control-group text optional"><label class="text optional control-label" for="comment_content">Content</label><div class="controls"><textarea class="text optional" cols="40" id="comment_content" name="comment[content]" rows="20" style="width:320px;height:80px"> </textarea></div></div> </div> <div class='form-actions'> <input class='btn cancel' href="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/#" style="display:none;" type='button' value='Cancel'> <input class="btn btn btn-primary" data-disable-with="Adding..." name="commit" type="submit" value="Add Comment"/> <br style="clear:both;"> </div> </form> </div> <div class='row-fluid'> <div class='span12'> <div class='comment' data-content='<EMAIL>' id='comment_403462' itemid='403462' itemprop='comment' itemscope itemtype='http://schema.org/UserComments'> <div class='comment_meta'> <div class='row-fluid'> <div class='span2'> <img alt="Avatar" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/missing/thumb/xavatar.png.pagespeed.ic.qjczMghcsC.jpg" style="float:left;margin-right:10px;" src="oiplitreendatwyv.gif"/> </div> <div class='span10'> <a href="243.html">young nude jail bait girls models</a> <div class='author' itemprop='creator'>medo</div> <div class='created_at'><time datetime="2012-11-09T02:10:23-05:00" itemprop="commentTime"><p><a href="http://www.123people.ca/s/kellie+olver" target="new"><NAME> - Email, Address, Phone numbers, everything! www ...</a><div>Shopping Host HSN Upskirt Eveline Television Liz <NAME> . 123people refers to video content from services such as Youtube, which are .</div><span>http://www.123people.ca/s/kellie+olver</span></p></time></div> </div> </div> </div> <div class='alert alert-message error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='comment_body'> <div class='content'> <p itemprop='commentText'><EMAIL></p> </div> </div> <div class='form-actions'> </div> <div class='reply_holder'> </div> </div> </div> </div> </div> </div> </div> <div class='span4' id='sidebar' itemscope itemtype='http://schema.org/WPSideBar'> <div id='sidebar_rectangle' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="98.html">xvideos.com para movil descarga 100% gratis nokia asha 303</a></h4> <div class='clearfix' itemscope itemtype='http://schema.org/Person'> <a href="304.html" itemprop="image"><img alt="<NAME>" class="pull-left" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-nude.jpg.pagespeed.ic.Yp5z6xqFnh.jpg" style="margin-right:10px;" src="itridyotwiboocay.gif"/></a><p><a href="http://groups.google.com/group/comp.infosystems.www.servers.ms-windows/browse_thread/thread/91424896dd744794" target="new">Upskirt Masturbation Videos: Hillary Clinton Upskirts - comp ...</a><div>upskirt de galilea montijo housekeeper upskirt hsn upskirt free upskirt pics katy french xxx upskirt videos voyeur candid downblouse and upskirt .</div><span>http://groups.google.com/group/comp.infosystems.www.servers.ms-windows/browse_thread/thread/91424896dd744794</span></p><dl> <dt>Born</dt> <dd itemprop='birthDate'><time datetime="1971-09-08T00:00:00+00:00">September 08, 1971</time></dd> <dt>Full Name</dt> <dd itemprop='name'>www.youtupe/hsnupskirt.com Burke</dd> </dl> </div> </div> <div class='widget'> <h4><a href="137.html">xxx jail bait non nude</a></h4> <ul class='nav'> <li> <a href="390.html" class="clearfix"><img alt="Brooke Burke Prepares For Cancer Surgery" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" style="margin:0 10px 0 0;float:left;" src="yohtepeeqy.gif"/> www.youtupe/hsnupskirt.com Burke Prepares For Cancer Surgery </a></li> <li> <a href="419.html" class="clearfix"><img alt="Brooke Burke Has Thyroid Cancer" class="span3" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/thumb/brooke-burke-charvet-cancer-me.jpg" style="margin:0 10px 0 0;float:left;" src="gawyasuv.gif"/> www.youtupe/hsnupskirt.com Burke Has Thyroid Cancer </a></li> <li> <a href="index.html" class="clearfix"><img alt="Brooke Burke Charvet Releases New Lingerie Line" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" style="margin:0 10px 0 0;float:left;" src="kourtoujendoaple.gif"/> www.youtupe/hsnupskirt.com Burke Charvet Releases New Lingerie Line </a></li> </ul> </div> <div id='skyscraper' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="44.html">+xavier made in assembled in malaysia swiss watches black man an woman</a></h4> <ul class='thumbnails'> <li class='span4'> <a href="62.html" class="thumbnail"><img alt="Brooke Burke, Cancer Treatment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" src="utayploji.gif"/> </a></li> <li class='span4'> <a href="359.html" class="thumbnail"><img alt="Brooke Burke-Charvet Photo" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-charvet-photo.jpg.pagespeed.ic.eZcSwfCk1Z.jpg" src="treiwhoxu.gif"/> </a></li> <li class='span4'> <a href="94.html" class="thumbnail"><img alt="Brooke Burke Lingerie Line" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" src="wyalegualaf.gif"/> </a></li> <li class='span4'> <a href="35.html" class="thumbnail"><img alt="<NAME> and <NAME>" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-and-david-charvet.jpg.pagespeed.ic.iLiOSmNBgG.jpg" src="thywayhtyoch.gif"/> </a></li> <li class='span4'> <a href="38.html" class="thumbnail"><img alt="<NAME> Tom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-and-tom.jpg.pagespeed.ic.OfTSSeJdAZ.jpg" src="yokaywhyodooliwy.gif"/> </a></li> <li class='span4'> <a href="14.html" class="thumbnail"><img alt="The Naked Mom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/the-naked-mom.jpg.pagespeed.ce.2HxOs_fRpY.jpg" src="ooxoukynuakeyfoi.gif"/> </a></li> </ul> </div> <div class='widget'> <h4>Blog Archives</h4> <ul class='nav'> <li><a href="38.html">x3love.com</a></li> <li><a href="222.html">yougotposted videos/</a></li> <li><a href="233.html">young gymnastics slips accidental nudity tumblr</a></li> <li><a href="265.html">youtube camtados en video fajando</a></li> <li><a href="373.html">zach nichols naked tumbler</a></li> <li><a href="119.html">xxx comic rich bitch #2: public toy</a></li> <li><a href="295.html">youtube minas en colales</a></li> <li><a href="398.html">zastava pap m92</a></li> </ul> </div> </div> </div> <div id='footer' itemscope itemtype='http://schema.org/WPFooter'> <div class='remove_padding'> <div id='footer_leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> </div> <p><p><a href="http://www.youtube.com/watch?v=P7V9oPW-tqk" target="new">Suzanne Somers Clear Upskirt - YouTube</a><div>Oct 29, 2009 . The former Three&#39;s Company star Suzanne Somers pulling a quick upskirt move with co-host <NAME>.</div><span>http://www.youtube.com/watch?v=P7V9oPW-tqk</span></p></p> <p> <a href="294.html">youtubelabigorra</a> | <a href="268.html">youtube christina blackwell under skert shots</a> | <a href="257.html">youth extra large ayton fleece hooded jacket coat yxl hoody reviews</a> | <a href="186.html"><NAME>jiendo</a> </p> <p>&copy; 2013 The Hollywood Gossip - Celebrity Gossip and Entertainment News</p> <p><a href="184.html" rel="nofollow"><img alt="Sheknows-entertainment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xsheknows-entertainment-0dfb1ed120378c4d8a98720390d31272.png.pagespeed.ic.841FJHTKbK.png" src="xerxozheethrey.gif"/></a></p> </div> </div> <img height="1" width="1" pagespeed_lazy_src="http://tags.bluekai.com/site/3113" alt="" src="rtuagoutrewhoizu.gif"/> </div> </body> </html> <file_sep><!DOCTYPE html> <html id='en' lang='en'> <head> <title>zillow rentals orange ca</title> <link href="ssoistoineypoagh.css" media="screen" rel="stylesheet" type="text/css"/> <link href="oopeinyroon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon"/> <link href="ouzeelouhtootw.jpg" rel='apple-touch-icon' sizes='144x144'> <link href="eytreyhoisefoaht.jpg" rel='apple-touch-icon' sizes='114x114'> <link href="ndyajeyssepuatr.jpg" rel='apple-touch-icon' sizes='72x72'> <link href="eychoopyatya.jpg" rel='apple-touch-icon'> <script type='text/javascript' src='eyzeywyazuneyhi.js'></script></head> <body itemscope itemtype='http://schema.org/WebPage'> <div id='header'> <div class='social visible-desktop'> <ul> <li class='twitter'><a href="256.html">your dog been neutered by rickey smiley</a></li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com' data-size='medium'></div> </li> <li class='facebook'> <div class='fb-like' data-href='http://www.facebook.com/thehollywoodgossip' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> </ul> </div> <div id='banner'> <a href="2.html"><img alt="The Hollywood Gossip" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xheader-7629f5d243c1cdc904bf535b05ff849f.jpg.pagespeed.ic.CDQOMwZhbJ.jpg" src="stawhaghoix.gif"/></a> </div> <div class='sites visible-desktop'> <a href="394.html">zastava pap 85 tactical rails</a> | <a href="399.html">zastava pap m92 pv pistol, 7.62x39mm, 30 rnd mag</a> | <a href="256.html">your dog been neutered by rickey smiley</a> </div> <div class='login visible-desktop'> <a href="88.html">xnxx penelope menchaca desnuda</a> &nbsp;|&nbsp; <a href="123.html">xxx de escuela descargar para celular gratis</a> </div> </div> <div id='wrapper'> <div class='remove_padding'> <div id='leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='navbar' itemscope itemtype='http://schema.org/WPHeader'> <div class='navbar-inner'> <div class='container-fluid'> <a href="415.html">zig zag cornrows</a> <div class='nav-collapse'> <ul class='nav'> <li class=''><a href="360.html">yummychan.org/jb/</a></li> <li class=''><a href="4.html">www.usps.com/insurance/postoffice.htm</a></li> <li class=''><a href="72.html">xerex stories</a></li> <li class=''><a href="390.html">zastava m85pv 223 5.56 hg3088-n ak-47</a></li> <li class=''><a href="399.html">zastava pap m92 pv pistol, 7.62x39mm, 30 rnd mag</a></li> <li class=''><a href="31.html">www.youtupe/hsnupskirt.com</a></li> <li class=''><a href="346.html">yroll.theworknumber.com/allegis</a></li> <li class=''><a href="378.html">zander id theft compaints</a></li> <li class='login hidden-desktop'><a href="392.html">zastava m92 folding stock</a></li> <li class='login hidden-desktop'><a href="44.html">+xavier made in assembled in malaysia swiss watches black man an woman</a></li> </ul> <form action="http://www.thehollywoodgossip.com/search" class='navbar-form pull-right'> <input class="input-medium" id="q" name="q" placeholder="Search" type="search"/> <button class="btn" type="submit"></button> </form> </div> </div> </div> </div> </div> <div class='container-fluid'> <div class='row-fluid'> <div class='span8' id='content'> <ul class="breadcrumb" itemprop="breadcrumb"><li><a href="67.html">xdesi.mobi/x2/download/desi panjab fat</a> /</li> <li><a href="259.html">you tube antarvasna dot com</a> /</li> <li><a href="141.html">xxx nangi video film</a> /</li> <li><p><a href="http://www.zillow.com/orange-ca-92867/" target="new">92867 Real Estate &amp; 92867 Homes for Sale - Zillow</a><div>. homes for sale and check out 92867, CA market info on Zillow.</div><span>http://www.zillow.com/orange-ca-92867/</span></p></li></ul> <div class='video' itemscope itemtype='http://schema.org/VideoObject'> <div class='page-header'> <h1><p><a href="http://www.zillow.com/orange-ca/rent-houses/" target="new">Houses for Rent in Orange and Single Family Homes for Rent - Zillow</a><div>Search homes for rent in Orange. Find single family houses, townhouses, townhomes and more on Zillow.</div><span>http://www.zillow.com/orange-ca/rent-houses/</span></p></h1> </div> <ul id='sharebar'> <li> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='box_count' data-send='false' data-show-faces='false' data-width='60'></div> </li> <li class='pinit'><a href="381.html" class="pin-it-button" count-layout="vertical" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="sterroizheizerth.gif"/></a></li> <li> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='tall'></div> </li> <li> <a href="134.html">xxx images of nangi girl</a> </li> <li class='comments'> <div class='count comment_count'>1</div> <a href="111.html">xxx 3gp anime adolescentes</a> </li> </ul> <div class='sharebarx' style="display:none;"> <ul> <li class='facebook'> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='medium'></div> </li> <li class='twitter'> <a href="333.html">youtubewirewrapping</a> </li> <li class='pinterest'><a href="415.html" class="pin-it-button" count-layout="horizontal" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="eevuassyaqundee.gif"/></a></li> <li class='comments'> <a href="65.html">xcatseyesx mfc webcam whore</a> 1 </li> </ul> </div> <div class='thumbnail'> <div style="max-width:640px;max-height:459px;margin:0 auto;"> <img src="http://photos1.zillow.com/p_c/ISi8spd5vqv8gz.jpg" width="640" height="459" /> </div> <div class='caption' itemprop='description'><p><a href="http://www.zillow.com/orange-ca/rent/apartment_condo_type/" target="new">Orange CA Apartments For Rent &amp; Orange Rentals - Zillow</a><div>Find an apartment or condo in Orange CA. Get free Orange rental listings &amp; market information on Zillow. - Page 1.</div><span>http://www.zillow.com/orange-ca/rent/apartment_condo_type/</span></p></div> <div class='rating-form' id='rating_7611' itemprop='aggregateRating' itemscope itemtype='http://schema.org/AggregateRating'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='inline-rating'><ul class="star-rating"><li class="current-rating" style="width:100%;">5.0 / 5.0</li><li><a href="224.html">young brook shields naked in videp caps</a></li> <li><a href="398.html">zastava pap m92</a></li> <li><a href="114.html">xxx 3gp niñas jovenes</a></li> <li><a href="308.html">youtube rapid city sd mariahs drunk</a></li> <li><a href="412.html">zeta phi beta chants every beat</a></li></ul></div> <br><p><a href="http://www.zillow.com/orange-county-ca/rent/apartment_condo_type/" target="new">Orange County CA Apartments For Rent &amp; Orange County ... - Zillow</a><div>Find an apartment or condo in Orange County CA. Get free Orange County rental listings &amp; market information on Zillow. - Page 1.</div><span>http://www.zillow.com/orange-county-ca/rent/apartment_condo_type/</span></p></div> </div> <br> <ul class='pager'> <li class='next'> <a href="223.html">youjiiz para telefonos nokia 201</a> </li> </ul> Related Videos: <ul class='thumbnails'> <li class='span4'> <a href="369.html" class="thumbnail"><img alt="Brooke Burke Interview" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/medium_l/brooke-burke-interview.jpg" src="yssusarternotr.gif"/> <div class='caption'>zillow rentals orange ca Burke Interview</div> </a></li> </ul> <div class="remove_padding"><div id="content_rectangle" itemscope itemtype="http://schema.org/WPAdBlock"> </div></div> Embed Code: <pre class='embed'><p><a href="http://www.zillow.com/orange-ca/duplex/" target="new">Orange Duplex &amp; Triplex Homes for Sale - Zillow</a><div>Search duplex and triplex homes for sale in Orange. Find multi-family housing and more on Zillow. . Loading results... 18825 E Pearl Ave APT A, Orange, CA .</div><span>http://www.zillow.com/orange-ca/duplex/</span></p> <p><a href="http://www.zillow.com/orange-county-ca/rent/" target="new">Orange County Apartments for Rent and Orange County CA ... - Zillow</a><div>Search Orange County apartments for rent as well as lofts, houses, condos, and more.</div><span>http://www.zillow.com/orange-county-ca/rent/</span></p> <p><a href="http://www.zillow.com/orange-county-ca/rent-houses/" target="new">Houses for Rent in Orange County and Single Family ... - Zillow</a><div>Search homes for rent in Orange County. Find single family .</div><span>http://www.zillow.com/orange-county-ca/rent-houses/</span></p></pre> <dl class='dl-horizontal'> <dt>Star:</dt> <dd> <a href="321.html">you tube ver fotos de mariana seoane</a> </dd> <dt>Related Videos:</dt> <dd><a href="325.html">youtube videos calientes de mexicanas</a></dd> <dt>Original Post:</dt> <dd itemprop='associatedArticle'><a href="80.html">xm80 ammo</a></dd> <dt>Uploaded by:</dt> <dd><a href="101.html">xvideos draya</a></dd> <dt>Uploaded:</dt> <dd><time datetime="2012-11-08T00:00:00+00:00" itemprop="uploadDate">November 08, 2012</time></dd> <dt>Duration:</dt> <dd> <time datetime='PT3M9S' itemprop='duration'>189 seconds</time> </dd> </dl> <hr> <div id='comments'> <h3> Comments (1 Total) <a href="126.html">xxx dormidas para movil</a> </h3> <a href="219.html">you got posted tiff bannister</a> <div id='new_comment'> <form accept-charset="UTF-8" action="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/comments/" class="simple_form form-horizontal" data-remote="true" id="new_comment" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;"/><input name="authenticity_token" type="hidden" value="<KEY>="/></div> <div class='body'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <input name='page' type='hidden'> <input id="comment_parent_id" name="comment[parent_id]" type="hidden"/> <br> <p><p><a href="http://www.zillow.com/homedetails/(undisclosed-Address)-Orange-CA-92867/2115492596_zpid/" target="new">View photos. For rent: $2,650.... Orange, CA 92867 - Zillow</a><div>View photos. For rent: $2650. 4 bed, 2.0 bath, 1543 sqft home at (undisclosed Address). Lovely four bedroom single story home in the popular Presidential tract .</div><span>http://www.zillow.com/homedetails/(undisclosed-Address)-Orange-CA-92867/2115492596_zpid/</span></p></p> <div class='row-fluid'> <div class='span8'> <div class="control-group string optional"><label class="string optional control-label" for="comment_anon_name">Name</label><div class="controls"><input class="string optional" id="comment_anon_name" name="comment[anon_name]" size="50" type="text"/><p class="help-block">Your name will appear with your comment</p></div></div> <div class="control-group email optional"><label class="email optional control-label" for="comment_anon_email">Email</label><div class="controls"><input class="string email optional" id="comment_anon_email" name="comment[anon_email]" size="50" type="email"/><p class="help-block"><p><a href="http://www.zillow.com/orange-county-ca/" target="new">Orange County Real Estate &amp; Orange County CA Homes for ... - Zillow</a><div>Search Orange County real estate listings for homes for sale .</div><span>http://www.zillow.com/orange-county-ca/</span></p></p></div></div> </div> <div class='span4 providers'> <a href="251.html">youporn.com/nn preteen models</a> <br> <a href="173.html">yahoo server unavalible iphone 5</a> <br> <a href="286.html">you tube imagenes de she mails follando</a> <br> </div> </div> <div class="control-group text optional"><label class="text optional control-label" for="comment_content">Content</label><div class="controls"><textarea class="text optional" cols="40" id="comment_content" name="comment[content]" rows="20" style="width:320px;height:80px"> </textarea></div></div> </div> <div class='form-actions'> <input class='btn cancel' href="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/#" style="display:none;" type='button' value='Cancel'> <input class="btn btn btn-primary" data-disable-with="Adding..." name="commit" type="submit" value="Add Comment"/> <br style="clear:both;"> </div> </form> </div> <div class='row-fluid'> <div class='span12'> <div class='comment' data-content='<EMAIL>' id='comment_403462' itemid='403462' itemprop='comment' itemscope itemtype='http://schema.org/UserComments'> <div class='comment_meta'> <div class='row-fluid'> <div class='span2'> <img alt="Avatar" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/missing/thumb/xavatar.png.pagespeed.ic.qjczMghcsC.jpg" style="float:left;margin-right:10px;" src="oiplitreendatwyv.gif"/> </div> <div class='span10'> <a href="343.html">yovodude shake it up</a> <div class='author' itemprop='creator'>medo</div> <div class='created_at'><time datetime="2012-11-09T02:10:23-05:00" itemprop="commentTime"><p><a href="http://www.zillow.com/local-info/CA-Orange-home-value/r_33252/" target="new">Orange Home Prices and Home Values in CA - Zillow Local Info</a><div>Compare Orange home prices, home values, median listing prices, price cuts, sold . Rent list price ($) . 417 N Wheatgrass Dr, Orange, CA Home For Sale .</div><span>http://www.zillow.com/local-info/CA-Orange-home-value/r_33252/</span></p></time></div> </div> </div> </div> <div class='alert alert-message error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='comment_body'> <div class='content'> <p itemprop='commentText'><EMAIL></p> </div> </div> <div class='form-actions'> </div> <div class='reply_holder'> </div> </div> </div> </div> </div> </div> </div> <div class='span4' id='sidebar' itemscope itemtype='http://schema.org/WPSideBar'> <div id='sidebar_rectangle' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="263.html">youtube brandy from storage wars porn video</a></h4> <div class='clearfix' itemscope itemtype='http://schema.org/Person'> <a href="315.html" itemprop="image"><img alt="<NAME>" class="pull-left" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-nude.jpg.pagespeed.ic.Yp5z6xqFnh.jpg" style="margin-right:10px;" src="itridyotwiboocay.gif"/></a><p><a href="http://www.zillow.com/orange-ca-92869/" target="new">92869 Real Estate &amp; 92869 Homes for Sale - Zillow</a><div>. homes for sale and check out 92869, CA market info on Zillow.</div><span>http://www.zillow.com/orange-ca-92869/</span></p><dl> <dt>Born</dt> <dd itemprop='birthDate'><time datetime="1971-09-08T00:00:00+00:00">September 08, 1971</time></dd> <dt>Full Name</dt> <dd itemprop='name'>zillow rentals orange ca Burke</dd> </dl> </div> </div> <div class='widget'> <h4><a href="323.html">you tube video jenni rivera and chiquis boyfriend</a></h4> <ul class='nav'> <li> <a href="12.html" class="clearfix"><img alt="Brooke Burke Prepares For Cancer Surgery" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" style="margin:0 10px 0 0;float:left;" src="yohtepeeqy.gif"/> zillow rentals orange ca Burke Prepares For Cancer Surgery </a></li> <li> <a href="301.html" class="clearfix"><img alt="Brooke Burke Has Thyroid Cancer" class="span3" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/thumb/brooke-burke-charvet-cancer-me.jpg" style="margin:0 10px 0 0;float:left;" src="gawyasuv.gif"/> zillow rentals orange ca Burke Has Thyroid Cancer </a></li> <li> <a href="136.html" class="clearfix"><img alt="Brooke Burke Charvet Releases New Lingerie Line" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" style="margin:0 10px 0 0;float:left;" src="kourtoujendoaple.gif"/> zillow rentals orange ca Burke Charvet Releases New Lingerie Line </a></li> </ul> </div> <div id='skyscraper' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="281.html">youtube el hijo de jenni rivera</a></h4> <ul class='thumbnails'> <li class='span4'> <a href="index.html" class="thumbnail"><img alt="Brooke Burke, Cancer Treatment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" src="utayploji.gif"/> </a></li> <li class='span4'> <a href="236.html" class="thumbnail"><img alt="Brooke Burke-Charvet Photo" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-charvet-photo.jpg.pagespeed.ic.eZcSwfCk1Z.jpg" src="treiwhoxu.gif"/> </a></li> <li class='span4'> <a href="229.html" class="thumbnail"><img alt="Brooke Burke Lingerie Line" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" src="wyalegualaf.gif"/> </a></li> <li class='span4'> <a href="418.html" class="thumbnail"><img alt="Brooke Burke and David Charvet" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-and-david-charvet.jpg.pagespeed.ic.iLiOSmNBgG.jpg" src="thywayhtyoch.gif"/> </a></li> <li class='span4'> <a href="154.html" class="thumbnail"><img alt="<NAME>" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-and-tom.jpg.pagespeed.ic.OfTSSeJdAZ.jpg" src="yokaywhyodooliwy.gif"/> </a></li> <li class='span4'> <a href="52.html" class="thumbnail"><img alt="The Naked Mom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/the-naked-mom.jpg.pagespeed.ce.2HxOs_fRpY.jpg" src="ooxoukynuakeyfoi.gif"/> </a></li> </ul> </div> <div class='widget'> <h4>Blog Archives</h4> <ul class='nav'> <li><a href="147.html">xxx pickers danielle tattoos</a></li> <li><a href="128.html">xxxfotos porno d chicas peludas</a></li> <li><a href="108.html">xxsmodels bianka</a></li> <li><a href="84.html">xnxxanna nicole smith fucking</a></li> <li><a href="319.html">youtube upskirt stacy dash</a></li> <li><a href="211.html">yougotposted</a></li> <li><a href="255.html">yourautofriend.com</a></li> <li><a href="88.html">xnxx penelope menchaca desnuda</a></li> </ul> </div> </div> </div> <div id='footer' itemscope itemtype='http://schema.org/WPFooter'> <div class='remove_padding'> <div id='footer_leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> </div> <p><p><a href="http://www.zillow.com/orange-ca/rent/" target="new">Orange Apartments for rent &amp; Orange CA Apartment Rentals - Zillow</a><div>Search Orange apartments for rent as well as lofts, houses, .</div><span>http://www.zillow.com/orange-ca/rent/</span></p></p> <p> <a href="376.html">zamora ghetto gaggers</a> | <a href="292.html">youtube jp sauer and sohn suhl</a> | <a href="282.html">youtube fake nudes lee newton</a> | <a href="60.html">xbox live error 80151011</a> </p> <p>&copy; 2013 The Hollywood Gossip - Celebrity Gossip and Entertainment News</p> <p><a href="350.html" rel="nofollow"><img alt="Sheknows-entertainment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xsheknows-entertainment-0dfb1ed120378c4d8a98720390d31272.png.pagespeed.ic.841FJHTKbK.png" src="xerxozheethrey.gif"/></a></p> </div> </div> <img height="1" width="1" pagespeed_lazy_src="http://tags.bluekai.com/site/3113" alt="" src="rtuagoutrewhoizu.gif"/> </div> </body> </html> <file_sep>Links * http://dahufileguco.github.com/1.html * http://dahufileguco.github.com/2.html * http://dahufileguco.github.com/3.html * http://dahufileguco.github.com/4.html * http://dahufileguco.github.com/5.html * http://dahufileguco.github.com/6.html * http://dahufileguco.github.com/7.html * http://dahufileguco.github.com/8.html * http://dahufileguco.github.com/10.html * http://dahufileguco.github.com/11.html<file_sep><!DOCTYPE html> <html id='en' lang='en'> <head> <title>you tube strugis booty 2012</title> <link href="ssoistoineypoagh.css" media="screen" rel="stylesheet" type="text/css"/> <link href="oopeinyroon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon"/> <link href="ouzeelouhtootw.jpg" rel='apple-touch-icon' sizes='144x144'> <link href="eytreyhoisefoaht.jpg" rel='apple-touch-icon' sizes='114x114'> <link href="ndyajeyssepuatr.jpg" rel='apple-touch-icon' sizes='72x72'> <link href="eychoopyatya.jpg" rel='apple-touch-icon'> <script type='text/javascript' src='eyzeywyazuneyhi.js'></script></head> <body itemscope itemtype='http://schema.org/WebPage'> <div id='header'> <div class='social visible-desktop'> <ul> <li class='twitter'><a href="408.html">zendaya colemans fake nude pics yovo,com</a></li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com' data-size='medium'></div> </li> <li class='facebook'> <div class='fb-like' data-href='http://www.facebook.com/thehollywoodgossip' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> </ul> </div> <div id='banner'> <a href="360.html"><img alt="The Hollywood Gossip" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xheader-7629f5d243c1cdc904bf535b05ff849f.jpg.pagespeed.ic.CDQOMwZhbJ.jpg" src="stawhaghoix.gif"/></a> </div> <div class='sites visible-desktop'> <a href="176.html">yaki gerrido sin calsones</a> | <a href="406.html">zendaya coleman nude fakes</a> | <a href="112.html">xxx 3 gp de aguelas con sus ñetos</a> </div> <div class='login visible-desktop'> <a href="214.html">yougotposted instagram</a> &nbsp;|&nbsp; <a href="213.html">yougotposted.com</a> </div> </div> <div id='wrapper'> <div class='remove_padding'> <div id='leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='navbar' itemscope itemtype='http://schema.org/WPHeader'> <div class='navbar-inner'> <div class='container-fluid'> <a href="330.html">youtube watch v gr 017 sf214</a> <div class='nav-collapse'> <ul class='nav'> <li class=''><a href="37.html">www.zurichna.com/nydbl to:</a></li> <li class=''><a href="403.html">zebra lane calendars</a></li> <li class=''><a href="289.html">youtubejenni rivera death pics</a></li> <li class=''><a href="198.html">yolanda foster malibu home, working out, photos</a></li> <li class=''><a href="211.html">yougotposted</a></li> <li class=''><a href="90.html">xoskeleton home office</a></li> <li class=''><a href="197.html">yolanda foster doing leg squats, arms out like shooting a gun</a></li> <li class=''><a href="148.html">xxx pictures emily vancamp</a></li> <li class='login hidden-desktop'><a href="8.html">www.walmart mybenefits</a></li> <li class='login hidden-desktop'><a href="294.html">youtubelabigorra</a></li> </ul> <form action="http://www.thehollywoodgossip.com/search" class='navbar-form pull-right'> <input class="input-medium" id="q" name="q" placeholder="Search" type="search"/> <button class="btn" type="submit"></button> </form> </div> </div> </div> </div> </div> <div class='container-fluid'> <div class='row-fluid'> <div class='span8' id='content'> <ul class="breadcrumb" itemprop="breadcrumb"><li><a href="58.html">xbox live 80151011</a> /</li> <li><a href="24.html">www.xxxnepalifucking flm.com</a> /</li> <li><a href="77.html">xlola vika forum</a> /</li> <li><p><a href="http://www.youtube.com/watch?v=9LP2AgTtbG4" target="new">Biker Babes at Hulett, WY during the Sturgis Rally - YouTube</a><div>Aug 10, 2012 . Got it! Alert icon. You need Adobe Flash Player to watch this video. . Watch Later STURGIS BOOTY 2012by long13hair5,337 views; Thumbnail .</div><span>http://www.youtube.com/watch?v=9LP2AgTtbG4</span></p></li></ul> <div class='video' itemscope itemtype='http://schema.org/VideoObject'> <div class='page-header'> <h1><p><a href="http://www.youtube.com/watch?v=6QzTx0qesjg" target="new">Booty Bouncin @ One Eyed Jacks - Sturgis - YouTube</a><div>Mar 31, 2009 . Booty Bouncin @ One Eyed Jacks - Sturgis. thefablifeofcourtney&middot;113 . Sturgis 2009by <NAME>ade363,468 views; Sturgis Main Street 2012 11:09 .</div><span>http://www.youtube.com/watch?v=6QzTx0qesjg</span></p></h1> </div> <ul id='sharebar'> <li> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='box_count' data-send='false' data-show-faces='false' data-width='60'></div> </li> <li class='pinit'><a href="151.html" class="pin-it-button" count-layout="vertical" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="sterroizheizerth.gif"/></a></li> <li> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='tall'></div> </li> <li> <a href="26.html">www.xxx sex nabi .com</a> </li> <li class='comments'> <div class='count comment_count'>1</div> <a href="187.html">yiff animation horseplay</a> </li> </ul> <div class='sharebarx' style="display:none;"> <ul> <li class='facebook'> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='medium'></div> </li> <li class='twitter'> <a href="327.html">youtube videos escandalos caseros pornos</a> </li> <li class='pinterest'><a href="252.html" class="pin-it-button" count-layout="horizontal" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="eevuassyaqundee.gif"/></a></li> <li class='comments'> <a href="359.html">yummychan.info candydoll</a> 1 </li> </ul> </div> <div class='thumbnail'> <div style="max-width:640px;max-height:459px;margin:0 auto;"> <img src="http://i.ytimg.com/vi/af0q4klR-is/0.jpg" width="640" height="459" /> </div> <div class='caption' itemprop='description'><p><a href="http://www.youtube.com/watch?v=Pmms6G1T1m4" target="new">Harvard Baseball Parody- Sturgis Baseball &quot;What Makes ... - YouTube</a><div>May 18, 2012 . Harvard Baseball Parody- Sturgis Baseball &quot;What Makes You Beautiful&quot; . Published on May 18, 2012 . Buy &quot;What Makes You Beautiful&quot; on . Shawty its ur Bootyby dahirkanehl295,266 views &middot; BASEBALL EDITION | Dude .</div><span>http://www.youtube.com/watch?v=Pmms6G1T1m4</span></p></div> <div class='rating-form' id='rating_7611' itemprop='aggregateRating' itemscope itemtype='http://schema.org/AggregateRating'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='inline-rating'><ul class="star-rating"><li class="current-rating" style="width:100%;">5.0 / 5.0</li><li><a href="115.html">xxxanimalesconmujeres</a></li> <li><a href="391.html">zastava m85 pv 5.56 .223 pistol ak-47 in 223</a></li> <li><a href="39.html">xacyfex.github.com las-mujeres-mas-peludas-de-la-panocha.html</a></li> <li><a href="62.html">xbox live gold membership codes</a></li> <li><a href="371.html">zac efron naked</a></li></ul></div> <br><p><a href="http://www.youtube.com/watch?v=GbbqLF4AZjY" target="new">titties at sturgis - YouTube</a><div>Dec 3, 2011 . Alert icon. You need Adobe Flash Player to watch this video. . STURGIS BOOTY 2012by long13hair5,337 views; TRYING NOT TO LOVE YOU .</div><span>http://www.youtube.com/watch?v=GbbqLF4AZjY</span></p></div> </div> <br> <ul class='pager'> <li class='next'> <a href="355.html">yugo pap m85pv review</a> </li> </ul> Related Videos: <ul class='thumbnails'> <li class='span4'> <a href="175.html" class="thumbnail"><img alt="Brooke Burke Interview" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/medium_l/brooke-burke-interview.jpg" src="yssusarternotr.gif"/> <div class='caption'>you tube strugis booty 2012 Burke Interview</div> </a></li> </ul> <div class="remove_padding"><div id="content_rectangle" itemscope itemtype="http://schema.org/WPAdBlock"> </div></div> Embed Code: <pre class='embed'><p><a href="http://www.youtube.com/watch?v=VWg62ERNUIE" target="new">Breann and I- Booty Wurk dance ;) - YouTube</a><div>Aug 4, 2012 . Sign in to YouTube. Sign in with your YouTube Account (YouTube, Google+, Gmail, Orkut, Picasa, or Chrome) to like <NAME>&#39;s video.</div><span>http://www.youtube.com/watch?v=VWg62ERNUIE</span></p> <p><a href="http://www.youtube.com/watch?v=RZTBMAtNc1I" target="new">Booty: 2012 Best Booty - YouTube</a><div>Aug 2, 2012 . http://www.youtube-grab.net To Download This Booty 2012 Best Booty . Photos Sex Tapeby EastfistFeatured26,470 &middot; STURGIS BOOTY 2012 .</div><span>http://www.youtube.com/watch?v=RZTBMAtNc1I</span></p> <p><a href="http://www.youtube.com/watch?v=PWaRdljzwws" target="new">Hottest Girls of Sturgis 2012! - YouTube</a><div>Oct 8, 2012 . Got it! Alert icon. You need Adobe Flash Player to watch this video. . Lagos Girls. by yorubamagic121,587 views &middot; STURGIS BOOTY 2012 2:43 .</div><span>http://www.youtube.com/watch?v=PWaRdljzwws</span></p></pre> <dl class='dl-horizontal'> <dt>Star:</dt> <dd> <a href="420.html">zina vlads blog</a> </dd> <dt>Related Videos:</dt> <dd><a href="351.html">yugo car company</a></dd> <dt>Original Post:</dt> <dd itemprop='associatedArticle'><a href="125.html">xxx descargar videos desvirgadas 3gmp movil</a></dd> <dt>Uploaded by:</dt> <dd><a href="314.html">you tube stacked inverted bob cuts</a></dd> <dt>Uploaded:</dt> <dd><time datetime="2012-11-08T00:00:00+00:00" itemprop="uploadDate">November 08, 2012</time></dd> <dt>Duration:</dt> <dd> <time datetime='PT3M9S' itemprop='duration'>189 seconds</time> </dd> </dl> <hr> <div id='comments'> <h3> Comments (1 Total) <a href="350.html">yugo car</a> </h3> <a href="390.html">zastava m85pv 223 5.56 hg3088-n ak-47</a> <div id='new_comment'> <form accept-charset="UTF-8" action="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/comments/" class="simple_form form-horizontal" data-remote="true" id="new_comment" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;"/><input name="authenticity_token" type="hidden" value="<KEY>="/></div> <div class='body'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <input name='page' type='hidden'> <input id="comment_parent_id" name="comment[parent_id]" type="hidden"/> <br> <p><p><a href="http://www.youtube.com/watch?v=AHOhQBflCP8" target="new">Booty wurk DANCE:) - YouTube</a><div>Sep 1, 2012 . Statistics Report. Published on Sep 1, 2012 . Breann and I- Booty Wurk dance ;) by Mariah Sturgis488 views &middot; One Direction | Booty Wurk 3:19 .</div><span>http://www.youtube.com/watch?v=AHOhQBflCP8</span></p></p> <div class='row-fluid'> <div class='span8'> <div class="control-group string optional"><label class="string optional control-label" for="comment_anon_name">Name</label><div class="controls"><input class="string optional" id="comment_anon_name" name="comment[anon_name]" size="50" type="text"/><p class="help-block">Your name will appear with your comment</p></div></div> <div class="control-group email optional"><label class="email optional control-label" for="comment_anon_email">Email</label><div class="controls"><input class="string email optional" id="comment_anon_email" name="comment[anon_email]" size="50" type="email"/><p class="help-block"><p><a href="http://www.youtube.com/watch?v=iTb2fPeewO4" target="new">STURGIS BOOTY 2012 - YouTube</a><div>Sep 27, 2012 . Long13Hair, WOW! Thank you sir for the pics. Would that happen to be Sturgis Michigan? If so I would love to be there next time. I&#39;m not too far.</div><span>http://www.youtube.com/watch?v=iTb2fPeewO4</span></p></p></div></div> </div> <div class='span4 providers'> <a href="208.html">you can see at http://weirdnews.about.com/od/lovesexandmarriage/a/john-falcon-biggest-penis.htm</a> <br> <a href="116.html">xxx aunty saree removing with fuke on peperonity</a> <br> <a href="49.html">xbooru tram pararam meja mi</a> <br> </div> </div> <div class="control-group text optional"><label class="text optional control-label" for="comment_content">Content</label><div class="controls"><textarea class="text optional" cols="40" id="comment_content" name="comment[content]" rows="20" style="width:320px;height:80px"> </textarea></div></div> </div> <div class='form-actions'> <input class='btn cancel' href="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/#" style="display:none;" type='button' value='Cancel'> <input class="btn btn btn-primary" data-disable-with="Adding..." name="commit" type="submit" value="Add Comment"/> <br style="clear:both;"> </div> </form> </div> <div class='row-fluid'> <div class='span12'> <div class='comment' data-content='<EMAIL>' id='comment_403462' itemid='403462' itemprop='comment' itemscope itemtype='http://schema.org/UserComments'> <div class='comment_meta'> <div class='row-fluid'> <div class='span2'> <img alt="Avatar" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/missing/thumb/xavatar.png.pagespeed.ic.qjczMghcsC.jpg" style="float:left;margin-right:10px;" src="oiplitreendatwyv.gif"/> </div> <div class='span10'> <a href="266.html">youtube change serpintine belts 2003 altima 3.5</a> <div class='author' itemprop='creator'>medo</div> <div class='created_at'><time datetime="2012-11-09T02:10:23-05:00" itemprop="commentTime"><p><a href="http://www.youtube.com/watch?v=yxSBmcI81t0" target="new">BLACK BOOTY BIKE WEEK - YouTube</a><div>Dec 3, 2012 . Sexy Black Booty Shakeby Bratt Art50,212 views &middot; Daytona 2012 Bike . perfectMILFby SoFlyBooty023,165 views &middot; Sturgis Bike Rally 2010 .</div><span>http://www.youtube.com/watch?v=yxSBmcI81t0</span></p></time></div> </div> </div> </div> <div class='alert alert-message error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='comment_body'> <div class='content'> <p itemprop='commentText'><EMAIL></p> </div> </div> <div class='form-actions'> </div> <div class='reply_holder'> </div> </div> </div> </div> </div> </div> </div> <div class='span4' id='sidebar' itemscope itemtype='http://schema.org/WPSideBar'> <div id='sidebar_rectangle' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="224.html">young brook shields naked in videp caps</a></h4> <div class='clearfix' itemscope itemtype='http://schema.org/Person'> <a href="54.html" itemprop="image"><img alt="<NAME>" class="pull-left" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-nude.jpg.pagespeed.ic.Yp5z6xqFnh.jpg" style="margin-right:10px;" src="itridyotwiboocay.gif"/></a><p><a href="http://www.youtube.com/watch?v=juz49p9d2kQ" target="new">Hot girl in black bikini - YouTube</a><div>Oct 8, 2012 . You need Adobe Flash Player to watch this video. . STURGIS BOOTY 2012by long13hair3,360 views &middot; Sturgis 2012 Lazelle St 2012 08 10 .</div><span>http://www.youtube.com/watch?v=juz49p9d2kQ</span></p><dl> <dt>Born</dt> <dd itemprop='birthDate'><time datetime="1971-09-08T00:00:00+00:00">September 08, 1971</time></dd> <dt>Full Name</dt> <dd itemprop='name'>you tube strugis booty 2012 Burke</dd> </dl> </div> </div> <div class='widget'> <h4><a href="102.html">xvideos jovencitas 18 años para movil descarga gratis</a></h4> <ul class='nav'> <li> <a href="31.html" class="clearfix"><img alt="Brooke Burke Prepares For Cancer Surgery" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" style="margin:0 10px 0 0;float:left;" src="yohtepeeqy.gif"/> you tube strugis booty 2012 Burke Prepares For Cancer Surgery </a></li> <li> <a href="102.html" class="clearfix"><img alt="Brooke Burke Has Thyroid Cancer" class="span3" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/thumb/brooke-burke-charvet-cancer-me.jpg" style="margin:0 10px 0 0;float:left;" src="gawyasuv.gif"/> you tube strugis booty 2012 Burke Has Thyroid Cancer </a></li> <li> <a href="201.html" class="clearfix"><img alt="Brooke Burke Charvet Releases New Lingerie Line" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" style="margin:0 10px 0 0;float:left;" src="kourtoujendoaple.gif"/> you tube strugis booty 2012 Burke Charvet Releases New Lingerie Line </a></li> </ul> </div> <div id='skyscraper' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="271.html">youtube.com tangas mexicanas</a></h4> <ul class='thumbnails'> <li class='span4'> <a href="index.html" class="thumbnail"><img alt="Brooke Burke, Cancer Treatment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" src="utayploji.gif"/> </a></li> <li class='span4'> <a href="1.html" class="thumbnail"><img alt="Brooke Burke-Charvet Photo" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-charvet-photo.jpg.pagespeed.ic.eZcSwfCk1Z.jpg" src="treiwhoxu.gif"/> </a></li> <li class='span4'> <a href="4.html" class="thumbnail"><img alt="<NAME> Lingerie Line" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" src="wyalegualaf.gif"/> </a></li> <li class='span4'> <a href="332.html" class="thumbnail"><img alt="<NAME> and <NAME>" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-and-david-charvet.jpg.pagespeed.ic.iLiOSmNBgG.jpg" src="thywayhtyoch.gif"/> </a></li> <li class='span4'> <a href="4.html" class="thumbnail"><img alt="<NAME>" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-and-tom.jpg.pagespeed.ic.OfTSSeJdAZ.jpg" src="yokaywhyodooliwy.gif"/> </a></li> <li class='span4'> <a href="168.html" class="thumbnail"><img alt="The Naked Mom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/the-naked-mom.jpg.pagespeed.ce.2HxOs_fRpY.jpg" src="ooxoukynuakeyfoi.gif"/> </a></li> </ul> </div> <div class='widget'> <h4>Blog Archives</h4> <ul class='nav'> <li><a href="13.html">www.web.pjaave.sixe.vedio.in</a></li> <li><a href="278.html">youtube descuido de faldas</a></li> <li><a href="116.html">xxx aunty saree removing with fuke on peperonity</a></li> <li><a href="291.html">youtube jovencitas virgenes</a></li> <li><a href="30.html">www.youtube.com/heatherchilders</a></li> <li><a href="258.html">youtube alicia machado porno completo</a></li> <li><a href="156.html">xxx sexxxy pics of jacqueline pennewill</a></li> <li><a href="111.html">xxx 3gp anime adolescentes</a></li> </ul> </div> </div> </div> <div id='footer' itemscope itemtype='http://schema.org/WPFooter'> <div class='remove_padding'> <div id='footer_leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> </div> <p><p><a href="http://www.youtube.com/watch?v=8Nxw--yOFII" target="new">Sturgis 2012 Sundance Burnout Wednesday... - YouTube</a><div>Aug 13, 2012 . You need Adobe Flash Player to watch this video. . STURGIS BOOTY 2012by long13hair5,337 views; sturgis 2012-17Craziest Things From .</div><span>http://www.youtube.com/watch?v=8Nxw--yOFII</span></p></p> <p> <a href="270.html">youtube.com/martha mccallum</a> | <a href="65.html">xcatseyesx mfc webcam whore</a> | <a href="152.html">xxx.sex girl amy roloff</a> | <a href="25.html">www.xxxporn nangi fucking</a> </p> <p>&copy; 2013 The Hollywood Gossip - Celebrity Gossip and Entertainment News</p> <p><a href="357.html" rel="nofollow"><img alt="Sheknows-entertainment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xsheknows-entertainment-0dfb1ed120378c4d8a98720390d31272.png.pagespeed.ic.841FJHTKbK.png" src="xerxozheethrey.gif"/></a></p> </div> </div> <img height="1" width="1" pagespeed_lazy_src="http://tags.bluekai.com/site/3113" alt="" src="rtuagoutrewhoizu.gif"/> </div> </body> </html> <file_sep><!DOCTYPE html> <html id='en' lang='en'> <head> <title>yugo zastava factory m92 parts kit</title> <link href="ssoistoineypoagh.css" media="screen" rel="stylesheet" type="text/css"/> <link href="oopeinyroon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon"/> <link href="ouzeelouhtootw.jpg" rel='apple-touch-icon' sizes='144x144'> <link href="eytreyhoisefoaht.jpg" rel='apple-touch-icon' sizes='114x114'> <link href="ndyajeyssepuatr.jpg" rel='apple-touch-icon' sizes='72x72'> <link href="eychoopyatya.jpg" rel='apple-touch-icon'> <script type='text/javascript' src='eyzeywyazuneyhi.js'></script></head> <body itemscope itemtype='http://schema.org/WebPage'> <div id='header'> <div class='social visible-desktop'> <ul> <li class='twitter'><a href="110.html">xxx 2012 con animales</a></li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com' data-size='medium'></div> </li> <li class='facebook'> <div class='fb-like' data-href='http://www.facebook.com/thehollywoodgossip' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> </ul> </div> <div id='banner'> <a href="210.html"><img alt="The Hollywood Gossip" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xheader-7629f5d243c1cdc904bf535b05ff849f.jpg.pagespeed.ic.CDQOMwZhbJ.jpg" src="stawhaghoix.gif"/></a> </div> <div class='sites visible-desktop'> <a href="374.html">zach roloff college arrest</a> | <a href="116.html">xxx aunty saree removing with fuke on peperonity</a> | <a href="260.html">youtube bideos xxx de chicas birjenes</a> </div> <div class='login visible-desktop'> <a href="365.html">yutu mujeres cojiendo</a> &nbsp;|&nbsp; <a href="133.html">xxximagenes de panochas abirtas</a> </div> </div> <div id='wrapper'> <div class='remove_padding'> <div id='leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='navbar' itemscope itemtype='http://schema.org/WPHeader'> <div class='navbar-inner'> <div class='container-fluid'> <a href="324.html">youtube videos bailando y ensenando</a> <div class='nav-collapse'> <ul class='nav'> <li class=''><a href="17.html">www wwe rock vs brock lesnar full video com</a></li> <li class=''><a href="382.html">zara apply online</a></li> <li class=''><a href="15.html">www.worldstaruncut.com</a></li> <li class=''><a href="291.html">youtube jovencitas virgenes</a></li> <li class=''><a href="45.html">xavier quartz gold watch</a></li> <li class=''><a href="213.html">yougotposted.com</a></li> <li class=''><a href="140.html">xxx nakked animals fukking bollywood babes</a></li> <li class=''><a href="179.html">yaqui guerrido</a></li> <li class='login hidden-desktop'><a href="105.html">xvideos tahiry from love and hip hop</a></li> <li class='login hidden-desktop'><a href="341.html">yovodude.com</a></li> </ul> <form action="http://www.thehollywoodgossip.com/search" class='navbar-form pull-right'> <input class="input-medium" id="q" name="q" placeholder="Search" type="search"/> <button class="btn" type="submit"></button> </form> </div> </div> </div> </div> </div> <div class='container-fluid'> <div class='row-fluid'> <div class='span8' id='content'> <ul class="breadcrumb" itemprop="breadcrumb"><li><a href="320.html">youtube upskirt women sportscasters</a> /</li> <li><a href="338.html">yoville vip</a> /</li> <li><a href="376.html">zamora ghetto gaggers</a> /</li> <li><p><a href="http://armsofamerica.com/partskits-2.aspx" target="new">Arms Of America - Parts Kits</a><div>Results 1 - 12 of 12 . Yugoslavian factory new, Zastava Arsenal M85 parts kit .223 semi auto . . IGF Yugo M92 Krinkov Fake Suppressor Threaded 26 x 1.5 LH .</div><span>http://armsofamerica.com/partskits-2.aspx</span></p></li></ul> <div class='video' itemscope itemtype='http://schema.org/VideoObject'> <div class='page-header'> <h1><p><a href="http://www.cheaperthandirt.com/product/7-GHG3089N" target="new">Century Zastava PAP M92 Semi Auto Handgun 7.62x39 10&quot; Barrel ...</a><div>Straight from the Zastava factory, these are untouched and high quality PAP pistols . Century Zastava PAP M92 Semi Auto Handgun 7.62x39 10 Barrel 30 .</div><span>http://www.cheaperthandirt.com/product/7-GHG3089N</span></p></h1> </div> <ul id='sharebar'> <li> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='box_count' data-send='false' data-show-faces='false' data-width='60'></div> </li> <li class='pinit'><a href="65.html" class="pin-it-button" count-layout="vertical" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="sterroizheizerth.gif"/></a></li> <li> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='tall'></div> </li> <li> <a href="124.html">xxx de perros 3g</a> </li> <li class='comments'> <div class='count comment_count'>1</div> <a href="65.html">xcatseyesx mfc webcam whore</a> </li> </ul> <div class='sharebarx' style="display:none;"> <ul> <li class='facebook'> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='medium'></div> </li> <li class='twitter'> <a href="131.html">xxx gratis para descargar violadas</a> </li> <li class='pinterest'><a href="250.html" class="pin-it-button" count-layout="horizontal" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="eevuassyaqundee.gif"/></a></li> <li class='comments'> <a href="195.html">yoga sales</a> 1 </li> </ul> </div> <div class='thumbnail'> <div style="max-width:640px;max-height:459px;margin:0 auto;"> <img src="http://i666.photobucket.com/albums/vv30/woodey123/pix925027346.jpg" width="640" height="459" /> </div> <div class='caption' itemprop='description'><p><a href="http://www.ak-47.us/" target="new">AK-47 information, bayonets, ammo and magazines</a><div>We compared their parts side by side Zastava made M92 AK47 Krink Pistol PAP 7.62&times;39 mm compared with the Yugo Krink AK47 M92 Parts Kit .</div><span>http://www.ak-47.us/</span></p></div> <div class='rating-form' id='rating_7611' itemprop='aggregateRating' itemscope itemtype='http://schema.org/AggregateRating'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='inline-rating'><ul class="star-rating"><li class="current-rating" style="width:100%;">5.0 / 5.0</li><li><a href="261.html">you tube bondage</a></li> <li><a href="215.html">yougotposted making flames</a></li> <li><a href="247.html">youngstown mafia history</a></li> <li><a href="136.html">xxx jaguar artwork</a></li> <li><a href="23.html">www xxx hot sexy nangi picture com</a></li></ul></div> <br><p><a href="http://armsofamerica.com/yugom92krinkovpartskitwbarrelaccessoriesnomagazine.aspx" target="new">Yugo M92 Krinkov Parts kit w/ barrel + accessories (No magazine)</a><div>Sep 2, 2012 . brand new Yugoslavian M92 Krinkov Parts kit comes complete with . The Zastava M92 SMG chambers and fires the 7.62x39mm round.</div><span>http://armsofamerica.com/yugom92krinkovpartskitwbarrelaccessoriesnomagazine.aspx</span></p></div> </div> <br> <ul class='pager'> <li class='next'> <a href="145.html">xxx.photo indian actress download . in</a> </li> </ul> Related Videos: <ul class='thumbnails'> <li class='span4'> <a href="292.html" class="thumbnail"><img alt="Brooke Burke Interview" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/medium_l/brooke-burke-interview.jpg" src="yssusarternotr.gif"/> <div class='caption'>yugo zastava factory m92 parts kit Burke Interview</div> </a></li> </ul> <div class="remove_padding"><div id="content_rectangle" itemscope itemtype="http://schema.org/WPAdBlock"> </div></div> Embed Code: <pre class='embed'><p><a href="http://www.youtube.com/watch?v=IMXDRix2KKM" target="new">AKS-74U vs.Yugo M92 - Block Penetration - YouTube</a><div>Aug 2, 2010 . Yugo M92 krinkov or zastava M92 or automat M92 is made in &quot;Zastava arms&quot; in . is the m92 a factory milled receiver type? if so could you tell me what year it . Yugo M92 Krinkov Virgin Parts Kit Unboxing (AK47, 7.62x39)by .</div><span>http://www.youtube.com/watch?v=IMXDRix2KKM</span></p> <p><a href="http://en.wikipedia.org/wiki/Zastava_Arms" target="new">Zastava Arms - Wikipedia, the free encyclopedia</a><div>Zastava Arms is a Serbian manufacturer of firearms and artillery. . eventually allowing the plant to produce weapons with full parts interchangeability. . PAP M59/66 (Yugo SKS) with a rifle grenade launcher and folding bayonet. . the development and testing and started batch production of 7.62 mm submachine gun M92, .</div><span>http://en.wikipedia.org/wiki/Zastava_Arms</span></p></pre> <dl class='dl-horizontal'> <dt>Star:</dt> <dd> <a href="61.html">xbox live error code 80151011</a> </dd> <dt>Related Videos:</dt> <dd><a href="235.html">young jailbait non nude</a></dd> <dt>Original Post:</dt> <dd itemprop='associatedArticle'><a href="322.html">youtube video caseros calientes</a></dd> <dt>Uploaded by:</dt> <dd><a href="285.html">youtube gory death pictures</a></dd> <dt>Uploaded:</dt> <dd><time datetime="2012-11-08T00:00:00+00:00" itemprop="uploadDate">November 08, 2012</time></dd> <dt>Duration:</dt> <dd> <time datetime='PT3M9S' itemprop='duration'>189 seconds</time> </dd> </dl> <hr> <div id='comments'> <h3> Comments (1 Total) <a href="323.html">you tube video jenni rivera and chiquis boyfriend</a> </h3> <a href="143.html">xxxnina de 12 ano</a> <div id='new_comment'> <form accept-charset="UTF-8" action="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/comments/" class="simple_form form-horizontal" data-remote="true" id="new_comment" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;"/><input name="authenticity_token" type="hidden" value="dnWqi+nJgFJVOg7dUXsDnt4HFjnto5JBhChkS9z5RQ8="/></div> <div class='body'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <input name='page' type='hidden'> <input id="comment_parent_id" name="comment[parent_id]" type="hidden"/> <br> <p><p><a href="http://www.ar15.com/forums/t_4_98/125758_.html" target="new">AK Pistol Specs - (Draco, Yugo M92/M85, Bulgarian SLR, Hellpup ...</a><div>AK Pistol Specs - (Draco, Yugo M92/M85, Bulgarian SLR, Hellpup, Centurion 39 Sporter) - AR15.COM. . Manufacturer: Zastava Serbia Importer: . Made in USA AK47 pistol w/ factory lifetime warranty. Features . It means it was based off of Surplus Romanian parts kits to complete the pistol. User Info .</div><span>http://www.ar15.com/forums/t_4_98/125758_.html</span></p></p> <div class='row-fluid'> <div class='span8'> <div class="control-group string optional"><label class="string optional control-label" for="comment_anon_name">Name</label><div class="controls"><input class="string optional" id="comment_anon_name" name="comment[anon_name]" size="50" type="text"/><p class="help-block">Your name will appear with your comment</p></div></div> <div class="control-group email optional"><label class="email optional control-label" for="comment_anon_email">Email</label><div class="controls"><input class="string email optional" id="comment_anon_email" name="comment[anon_email]" size="50" type="email"/><p class="help-block"><p><a href="http://www.youtube.com/watch?v=a78rZUi-Hhw" target="new">PAP AK47 Pistol vs. Yugo Krink M92 - YouTube</a><div>Oct 9, 2012 . We compared their parts side by side Zastava made M92 AK47 Krink Pistol . Zastava made M92 AK47 Krink Pistol PAP 7.62x39 mm compared with the Yugo Krink AK47 M92 Parts Kit . same shit made in the same factory? .</div><span>http://www.youtube.com/watch?v=a78rZUi-Hhw</span></p></p></div></div> </div> <div class='span4 providers'> <a href="396.html">zastava pap m85 pv pistol, 223/5.56 magazines</a> <br> <a href="385.html">zara girls</a> <br> <a href="330.html">youtube watch v gr 017 sf214</a> <br> </div> </div> <div class="control-group text optional"><label class="text optional control-label" for="comment_content">Content</label><div class="controls"><textarea class="text optional" cols="40" id="comment_content" name="comment[content]" rows="20" style="width:320px;height:80px"> </textarea></div></div> </div> <div class='form-actions'> <input class='btn cancel' href="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/#" style="display:none;" type='button' value='Cancel'> <input class="btn btn btn-primary" data-disable-with="Adding..." name="commit" type="submit" value="Add Comment"/> <br style="clear:both;"> </div> </form> </div> <div class='row-fluid'> <div class='span12'> <div class='comment' data-content='<EMAIL>' id='comment_403462' itemid='403462' itemprop='comment' itemscope itemtype='http://schema.org/UserComments'> <div class='comment_meta'> <div class='row-fluid'> <div class='span2'> <img alt="Avatar" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/missing/thumb/xavatar.png.pagespeed.ic.qjczMghcsC.jpg" style="float:left;margin-right:10px;" src="oiplitreendatwyv.gif"/> </div> <div class='span10'> <a href="296.html">youtubemujeres enseñando tanga</a> <div class='author' itemprop='creator'>medo</div> <div class='created_at'><time datetime="2012-11-09T02:10:23-05:00" itemprop="commentTime"><p><a href="http://www.impactguns.com/pap-m92-pv-pistol-762x39mm-30-rnd-mag-hg3089-n-787450220720.aspx" target="new">Zastava PAP M92 PV Pistol, 7.62x39mm, 30 Rnd Mag - Impact Guns</a><div>Zastava Firearms-Zastava PAP M92 PV Pistol, 7.62x39mm, 30 Rnd . This AK style pistol is a brand new firearm made by the famous Zastava factory in Serbia!</div><span>http://www.impactguns.com/pap-m92-pv-pistol-762x39mm-30-rnd-mag-hg3089-n-787450220720.aspx</span></p></time></div> </div> </div> </div> <div class='alert alert-message error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='comment_body'> <div class='content'> <p itemprop='commentText'><EMAIL></p> </div> </div> <div class='form-actions'> </div> <div class='reply_holder'> </div> </div> </div> </div> </div> </div> </div> <div class='span4' id='sidebar' itemscope itemtype='http://schema.org/WPSideBar'> <div id='sidebar_rectangle' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="404.html">zen bracelets for luck money</a></h4> <div class='clearfix' itemscope itemtype='http://schema.org/Person'> <a href="164.html" itemprop="image"><img alt="<NAME>" class="pull-left" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-nude.jpg.pagespeed.ic.Yp5z6xqFnh.jpg" style="margin-right:10px;" src="itridyotwiboocay.gif"/></a><p><a href="http://www.riflegear.com/p-1740-century-arms-pap-m92-pv-762x39-pistol.aspx" target="new">Century Arms PAP M92 PV 7.62x39 Pistol</a><div>Century Arms PAP M92 PV 7.62x39 Pistol. . Lower Receivers and Parts . AK style pistol is a brand new firearm made by the famous Zastava factory in Serbia.</div><span>http://www.riflegear.com/p-1740-century-arms-pap-m92-pv-762x39-pistol.aspx</span></p><dl> <dt>Born</dt> <dd itemprop='birthDate'><time datetime="1971-09-08T00:00:00+00:00">September 08, 1971</time></dd> <dt>Full Name</dt> <dd itemprop='name'>yugo zastava factory m92 parts kit Burke</dd> </dl> </div> </div> <div class='widget'> <h4><a href="71.html">xerex sagad tukso</a></h4> <ul class='nav'> <li> <a href="385.html" class="clearfix"><img alt="Brooke Burke Prepares For Cancer Surgery" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" style="margin:0 10px 0 0;float:left;" src="yohtepeeqy.gif"/> yugo zastava factory m92 parts kit Burke Prepares For Cancer Surgery </a></li> <li> <a href="138.html" class="clearfix"><img alt="Brooke Burke Has Thyroid Cancer" class="span3" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/thumb/brooke-burke-charvet-cancer-me.jpg" style="margin:0 10px 0 0;float:left;" src="gawyasuv.gif"/> yugo zastava factory m92 parts kit Burke Has Thyroid Cancer </a></li> <li> <a href="234.html" class="clearfix"><img alt="Brooke Burke Charvet Releases New Lingerie Line" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" style="margin:0 10px 0 0;float:left;" src="kourtoujendoaple.gif"/> yugo zastava factory m92 parts kit Burke Charvet Releases New Lingerie Line </a></li> </ul> </div> <div id='skyscraper' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="189.html">yiffy straight</a></h4> <ul class='thumbnails'> <li class='span4'> <a href="369.html" class="thumbnail"><img alt="Brooke Burke, Cancer Treatment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" src="utayploji.gif"/> </a></li> <li class='span4'> <a href="215.html" class="thumbnail"><img alt="Brooke Burke-Charvet Photo" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-charvet-photo.jpg.pagespeed.ic.eZcSwfCk1Z.jpg" src="treiwhoxu.gif"/> </a></li> <li class='span4'> <a href="101.html" class="thumbnail"><img alt="<NAME>" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" src="wyalegualaf.gif"/> </a></li> <li class='span4'> <a href="315.html" class="thumbnail"><img alt="<NAME> <NAME>" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-and-david-charvet.jpg.pagespeed.ic.iLiOSmNBgG.jpg" src="thywayhtyoch.gif"/> </a></li> <li class='span4'> <a href="115.html" class="thumbnail"><img alt="<NAME>" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-and-tom.jpg.pagespeed.ic.OfTSSeJdAZ.jpg" src="yokaywhyodooliwy.gif"/> </a></li> <li class='span4'> <a href="200.html" class="thumbnail"><img alt="The Naked Mom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/the-naked-mom.jpg.pagespeed.ce.2HxOs_fRpY.jpg" src="ooxoukynuakeyfoi.gif"/> </a></li> </ul> </div> <div class='widget'> <h4>Blog Archives</h4> <ul class='nav'> <li><a href="299.html">youtube nephew tommy left my medicine</a></li> <li><a href="199.html">yolanda on ghetto gaggers full video</a></li> <li><a href="335.html">you tuve mujeres cojiendo con perros gran dames</a></li> <li><a href="175.html">yaki garido sin ropa interior</a></li> <li><a href="342.html">yovodudefakes.com</a></li> <li><a href="index.html">home</a></li> <li><a href="267.html">youtube chapo guzman video</a></li> <li><a href="131.html">xxx gratis para descargar violadas</a></li> </ul> </div> </div> </div> <div id='footer' itemscope itemtype='http://schema.org/WPFooter'> <div class='remove_padding'> <div id='footer_leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> </div> <p><p><a href="http://www.atlanticfirearms.com/ak-47-74-rifles.html" target="new">AK 47 / 74 Rifles - Atlantic Firearms | AR15 &amp; AK47 Rifles | Mags ...</a><div>Zastava AK-47 M70 PAP 7.62x39 Rifle, Imported AK Rifles with a nice line up . This AK style pistol is a brand new firearm made by the famous Zastava factory in Serbia . Krinkov M92 AK47 7.62x39 Rifle, Semi Auto rifle and a great platform for . Premium AK 74 rifles built using Bulgarian parts kits and required US parts.</div><span>http://www.atlanticfirearms.com/ak-47-74-rifles.html</span></p></p> <p> <a href="272.html">youtube connie stevens topless</a> | <a href="94.html">xv anos de la hija de jenni rivera</a> | <a href="313.html">youtube selena gomez funeral</a> | <a href="83.html">xnxx</a> </p> <p>&copy; 2013 The Hollywood Gossip - Celebrity Gossip and Entertainment News</p> <p><a href="161.html" rel="nofollow"><img alt="Sheknows-entertainment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xsheknows-entertainment-0dfb1ed120378c4d8a98720390d31272.png.pagespeed.ic.841FJHTKbK.png" src="xerxozheethrey.gif"/></a></p> </div> </div> <img height="1" width="1" pagespeed_lazy_src="http://tags.bluekai.com/site/3113" alt="" src="rtuagoutrewhoizu.gif"/> </div> </body> </html> <file_sep><!DOCTYPE html> <html id='en' lang='en'> <head> <title>xerex sagad tukso</title> <link href="ssoistoineypoagh.css" media="screen" rel="stylesheet" type="text/css"/> <link href="oopeinyroon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon"/> <link href="ouzeelouhtootw.jpg" rel='apple-touch-icon' sizes='144x144'> <link href="eytreyhoisefoaht.jpg" rel='apple-touch-icon' sizes='114x114'> <link href="ndyajeyssepuatr.jpg" rel='apple-touch-icon' sizes='72x72'> <link href="eychoopyatya.jpg" rel='apple-touch-icon'> <script type='text/javascript' src='eyzeywyazuneyhi.js'></script></head> <body itemscope itemtype='http://schema.org/WebPage'> <div id='header'> <div class='social visible-desktop'> <ul> <li class='twitter'><a href="270.html">youtube.com/martha mccallum</a></li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com' data-size='medium'></div> </li> <li class='facebook'> <div class='fb-like' data-href='http://www.facebook.com/thehollywoodgossip' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> </ul> </div> <div id='banner'> <a href="273.html"><img alt="The Hollywood Gossip" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xheader-7629f5d243c1cdc904bf535b05ff849f.jpg.pagespeed.ic.CDQOMwZhbJ.jpg" src="stawhaghoix.gif"/></a> </div> <div class='sites visible-desktop'> <a href="106.html">xx fhoto full hot memek celeb indo</a> | <a href="289.html">youtubejenni rivera death pics</a> | <a href="116.html">xxx aunty saree removing with fuke on peperonity</a> </div> <div class='login visible-desktop'> <a href="34.html">www.zee tv's banu mein teri dulhan actres fake porn.com</a> &nbsp;|&nbsp; <a href="36.html">www.zoofilia video porno mujere con perro</a> </div> </div> <div id='wrapper'> <div class='remove_padding'> <div id='leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='navbar' itemscope itemtype='http://schema.org/WPHeader'> <div class='navbar-inner'> <div class='container-fluid'> <a href="164.html">xxx viejos nietas gratis movil</a> <div class='nav-collapse'> <ul class='nav'> <li class=''><a href="127.html">xxx druuna onionbooty.com</a></li> <li class=''><a href="419.html">zima neon sign</a></li> <li class=''><a href="40.html">xanadu nj snow park</a></li> <li class=''><a href="138.html">xxx maribel guardia</a></li> <li class=''><a href="214.html">yougotposted instagram</a></li> <li class=''><a href="242.html">young naked illegal preteen pics</a></li> <li class=''><a href="176.html">yaki gerrido sin calsones</a></li> <li class=''><a href="353.html">yugo pap m85pv pistol</a></li> <li class='login hidden-desktop'><a href="313.html">youtube selena gomez funeral</a></li> <li class='login hidden-desktop'><a href="243.html">young nude jail bait girls models</a></li> </ul> <form action="http://www.thehollywoodgossip.com/search" class='navbar-form pull-right'> <input class="input-medium" id="q" name="q" placeholder="Search" type="search"/> <button class="btn" type="submit"></button> </form> </div> </div> </div> </div> </div> <div class='container-fluid'> <div class='row-fluid'> <div class='span8' id='content'> <ul class="breadcrumb" itemprop="breadcrumb"><li><a href="17.html">www wwe rock vs brock lesnar full video com</a> /</li> <li><a href="248.html">young teen bbs gateway</a> /</li> <li><a href="399.html">zastava pap m92 pv pistol, 7.62x39mm, 30 rnd mag</a> /</li> <li><p><a href="http://www.facebook.com/racquel.magturo" target="new"><NAME> | Facebook</a><div>&quot;si Xerex&quot;- And- &quot;the Tigang Sa Bahay &quot;groups&quot; . Society Group, ALam mo yung mahaL kita? yun ung gusto kong sabihin pero hindi ko kaya, LAPTRiP SAGAD!</div><span>http://www.facebook.com/racquel.magturo</span></p></li></ul> <div class='video' itemscope itemtype='http://schema.org/VideoObject'> <div class='page-header'> <h1><p><a href="http://www.btscene.org/verified-search/torrent/pinoy+wingtip/pageno/5/" target="new">Download pinoy wingtip torrent - BTScene Torrents</a><div>Dec 29, 2012 . TUKSO (2005) [PINOY] DVDRiP DivX NoSubs [Tagalog] WingTip TUKSO . SAGAD SA INIT (1998) [PINOY] DivX NoSubs [Tagalog] WingTip . PANTASYA ( 2007) + XeReX Series I [PINOY] DivX NoSubs [Tagalog] WingTip .</div><span>http://www.btscene.org/verified-search/torrent/pinoy+wingtip/pageno/5/</span></p></h1> </div> <ul id='sharebar'> <li> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='box_count' data-send='false' data-show-faces='false' data-width='60'></div> </li> <li class='pinit'><a href="358.html" class="pin-it-button" count-layout="vertical" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="sterroizheizerth.gif"/></a></li> <li> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='tall'></div> </li> <li> <a href="47.html">xaxor girls</a> </li> <li class='comments'> <div class='count comment_count'>1</div> <a href="60.html">xbox live error 80151011</a> </li> </ul> <div class='sharebarx' style="display:none;"> <ul> <li class='facebook'> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='medium'></div> </li> <li class='twitter'> <a href="index.html">home</a> </li> <li class='pinterest'><a href="159.html" class="pin-it-button" count-layout="horizontal" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="eevuassyaqundee.gif"/></a></li> <li class='comments'> <a href="166.html">xxx wwe aj sex movie.nat</a> 1 </li> </ul> </div> <div class='thumbnail'> <div style="max-width:640px;max-height:459px;margin:0 auto;"> <img src="http://www.pinoyexchange.com/forums/image.php?u=474184&dateline=1340780931" width="640" height="459" /> </div> <div class='caption' itemprop='description'><p><a href="http://www.facebook.com/jay.david.9828" target="new"><NAME> | Facebook</a><div>Like &middot; Virgin pa kase ako kuya. Like &middot; Gandang lahi. Like &middot; &quot;si Xerex&quot;- And- &quot;the Tigang Sa Bahay &quot;groups&quot; &middot; Like &middot; Pinoy_Hot_Line (Rated PG) - Creator Twit&#39;z .</div><span>http://www.facebook.com/jay.david.9828</span></p></div> <div class='rating-form' id='rating_7611' itemprop='aggregateRating' itemscope itemtype='http://schema.org/AggregateRating'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='inline-rating'><ul class="star-rating"><li class="current-rating" style="width:100%;">5.0 / 5.0</li><li><a href="42.html">xarelto coupons medicare part d</a></li> <li><a href="262.html">you tube boradcast yourself black freaks and booty shakers</a></li> <li><a href="122.html">xxx cum gaggers</a></li> <li><a href="225.html">young celebrities on disney channel images</a></li> <li><a href="146.html">xxx photos of sonakshi sinha</a></li></ul></div> <br><p><a href="http://ejaybasaliso.blogspot.com/" target="new">Ang mga walang ka-kwenta-kwentang aritikulo !</a><div>15 Mar 2012. para maging kakaiba ang pangalan ng kanilang anak nariyan ang sagad . ginagamit na rin ang mga X halimbawa Xierra Xavier, Xerex, Xylk. . nag- imbento ng salitang &#147;Mama&#39;s Boy&#148; na karaniwang tukso sa mga lalake.</div><span>http://ejaybasaliso.blogspot.com/</span></p></div> </div> <br> <ul class='pager'> <li class='next'> <a href="100.html">xvideos de zoofilia mobi</a> </li> </ul> Related Videos: <ul class='thumbnails'> <li class='span4'> <a href="47.html" class="thumbnail"><img alt="Brooke Burke Interview" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/medium_l/brooke-burke-interview.jpg" src="yssusarternotr.gif"/> <div class='caption'>xerex sagad tukso Burke Interview</div> </a></li> </ul> <div class="remove_padding"><div id="content_rectangle" itemscope itemtype="http://schema.org/WPAdBlock"> </div></div> Embed Code: <pre class='embed'><p><a href="http://www.facebook.com/brain.cacho" target="new"><NAME> | Facebook</a><div>HIPON PALA!!, I love listening to lies when i know the truth, Tukso Layuan mo aq! . tapos wala kang mahanap., AT ISASAGAD KO PA!, I LOVE YOU SAGAD ! :), Xerex Xaviera University of Dummy Account, PALAG PALAG SIR!, Cristine .</div><span>http://www.facebook.com/brain.cacho</span></p> <p><a href="http://boyshiatsu.blogspot.com/" target="new">Boy Shiatsu</a><div>2 mga araw na nakalipas. tsupaan tayo, yung sagad sa lalamunan! putangina! ang sarap nun! . ng dyaryong Remate araw-araw para magbasa ng Xerex Xaviera ang .</div><span>http://boyshiatsu.blogspot.com/</span></p> <p><a href="http://bebsisms.wordpress.com/2007/03/" target="new">March | 2007 | tale of the boy who refused to grow up</a><div>28 Mar 2007 . Sagad (2002) 391. Sagad sa init (1998) . Tukso layuan mo ako 2 (1997) 473. Tukso ng . Xerex the Series First Edition (2004) (V). Posted in .</div><span>http://bebsisms.wordpress.com/2007/03/</span></p></pre> <dl class='dl-horizontal'> <dt>Star:</dt> <dd> <a href="315.html">youtube stars nude fake</a> </dd> <dt>Related Videos:</dt> <dd><a href="397.html">zastava pap m85 specs</a></dd> <dt>Original Post:</dt> <dd itemprop='associatedArticle'><a href="42.html">xarelto coupons medicare part d</a></dd> <dt>Uploaded by:</dt> <dd><a href="358.html">yugo zastava m92pv krink ak pistol 7.62x39</a></dd> <dt>Uploaded:</dt> <dd><time datetime="2012-11-08T00:00:00+00:00" itemprop="uploadDate">November 08, 2012</time></dd> <dt>Duration:</dt> <dd> <time datetime='PT3M9S' itemprop='duration'>189 seconds</time> </dd> </dl> <hr> <div id='comments'> <h3> Comments (1 Total) <a href="248.html">young teen bbs gateway</a> </h3> <a href="38.html">x3love.com</a> <div id='new_comment'> <form accept-charset="UTF-8" action="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/comments/" class="simple_form form-horizontal" data-remote="true" id="new_comment" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;"/><input name="authenticity_token" type="hidden" value="<KEY>="/></div> <div class='body'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <input name='page' type='hidden'> <input id="comment_parent_id" name="comment[parent_id]" type="hidden"/> <br> <p><p><a href="http://definitelyfilipino.com/blog/author/ejaebasaliso/" target="new">ejaybasaliso &#150; The Blog for Online Filipinos</a><div>Nariyan ang sagad sa dami ng H sa pangalan gaya ng <NAME>. Yung iba naman ginagamit na rin ang mga X halimbawa Xierra Xavier, Xerex, Xylk. . Tanungin mo sa nag-imbento ng salitang &#147;Mama&#39;s Boy&#148; na karaniwang tukso sa .</div><span>http://definitelyfilipino.com/blog/author/ejaebasaliso/</span></p></p> <div class='row-fluid'> <div class='span8'> <div class="control-group string optional"><label class="string optional control-label" for="comment_anon_name">Name</label><div class="controls"><input class="string optional" id="comment_anon_name" name="comment[anon_name]" size="50" type="text"/><p class="help-block">Your name will appear with your comment</p></div></div> <div class="control-group email optional"><label class="email optional control-label" for="comment_anon_email">Email</label><div class="controls"><input class="string email optional" id="comment_anon_email" name="comment[anon_email]" size="50" type="email"/><p class="help-block"><p><a href="http://pornicore.blogspot.com/2011_12_01_archive.html" target="new">Porn XXX: December 2011</a><div>Dec 31, 2011 . Pinoy Kabarkads. TV ng Pinoy &middot; Pinoy Sagad sa Pagchupa . to Facebook. Labels: aubrey miles, pinoy movie, Xerex Movie (Pinoy Movie) .</div><span>http://pornicore.blogspot.com/2011_12_01_archive.html</span></p></p></div></div> </div> <div class='span4 providers'> <a href="87.html">xnxxgooglesex</a> <br> <a href="291.html">youtube jovencitas virgenes</a> <br> <a href="49.html">xbooru tram pararam meja mi</a> <br> </div> </div> <div class="control-group text optional"><label class="text optional control-label" for="comment_content">Content</label><div class="controls"><textarea class="text optional" cols="40" id="comment_content" name="comment[content]" rows="20" style="width:320px;height:80px"> </textarea></div></div> </div> <div class='form-actions'> <input class='btn cancel' href="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/#" style="display:none;" type='button' value='Cancel'> <input class="btn btn btn-primary" data-disable-with="Adding..." name="commit" type="submit" value="Add Comment"/> <br style="clear:both;"> </div> </form> </div> <div class='row-fluid'> <div class='span12'> <div class='comment' data-content='<EMAIL>' id='comment_403462' itemid='403462' itemprop='comment' itemscope itemtype='http://schema.org/UserComments'> <div class='comment_meta'> <div class='row-fluid'> <div class='span2'> <img alt="Avatar" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/missing/thumb/xavatar.png.pagespeed.ic.qjczMghcsC.jpg" style="float:left;margin-right:10px;" src="oiplitreendatwyv.gif"/> </div> <div class='span10'> <a href="102.html">xvideos jovencitas 18 años para movil descarga gratis</a> <div class='author' itemprop='creator'>medo</div> <div class='created_at'><time datetime="2012-11-09T02:10:23-05:00" itemprop="commentTime"><p><a href="http://www.facebook.com/maurene.andres" target="new"><NAME> | Facebook</a><div>&quot;si Xerex&quot;- And- &quot;the Tigang Sa Bahay &quot;groups&quot; &middot; Like . MALALABANAN MO BA ANG TUKSO??, Kapag ang tanga natuto, humanda ka! . Kung Ayaw Mong Masaktan Ng Sagad, Kaming mga tapat magmahal, ROBIN PADILLAand 171 more .</div><span>http://www.facebook.com/maurene.andres</span></p></time></div> </div> </div> </div> <div class='alert alert-message error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='comment_body'> <div class='content'> <p itemprop='commentText'><EMAIL></p> </div> </div> <div class='form-actions'> </div> <div class='reply_holder'> </div> </div> </div> </div> </div> </div> </div> <div class='span4' id='sidebar' itemscope itemtype='http://schema.org/WPSideBar'> <div id='sidebar_rectangle' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="32.html">www youtuve hiroin anuska shrma nangi phto</a></h4> <div class='clearfix' itemscope itemtype='http://schema.org/Person'> <a href="252.html" itemprop="image"><img alt="<NAME>" class="pull-left" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-nude.jpg.pagespeed.ic.Yp5z6xqFnh.jpg" style="margin-right:10px;" src="itridyotwiboocay.gif"/></a><p><a href="http://homepage2.nifty.com/asipara/movie_top.htm" target="new">?????????</a><div>?????? ?? ????? &middot; ?????? ???????? ????????? ??????????? . ????? &middot; ????? ?? ???? &middot; ????? ???? &middot; ????? ?? ??? ????? ?? .</div><span>http://homepage2.nifty.com/asipara/movie_top.htm</span></p><dl> <dt>Born</dt> <dd itemprop='birthDate'><time datetime="1971-09-08T00:00:00+00:00">September 08, 1971</time></dd> <dt>Full Name</dt> <dd itemprop='name'><NAME></dd> </dl> </div> </div> <div class='widget'> <h4><a href="266.html">youtube change serpintine belts 2003 altima 3.5</a></h4> <ul class='nav'> <li> <a href="126.html" class="clearfix"><img alt="Brooke Burke Prepares For Cancer Surgery" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" style="margin:0 10px 0 0;float:left;" src="yohtepeeqy.gif"/> xerex sagad tukso Burke Prepares For Cancer Surgery </a></li> <li> <a href="45.html" class="clearfix"><img alt="Brooke Burke Has Thyroid Cancer" class="span3" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/thumb/brooke-burke-charvet-cancer-me.jpg" style="margin:0 10px 0 0;float:left;" src="gawyasuv.gif"/> xerex sagad tukso Burke Has Thyroid Cancer </a></li> <li> <a href="74.html" class="clearfix"><img alt="Brooke Burke Charvet Releases New Lingerie Line" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" style="margin:0 10px 0 0;float:left;" src="kourtoujendoaple.gif"/> xerex sagad tukso Burke Charvet Releases New Lingerie Line </a></li> </ul> </div> <div id='skyscraper' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="305.html">youtube pleyboy <NAME></a></h4> <ul class='thumbnails'> <li class='span4'> <a href="321.html" class="thumbnail"><img alt="Brooke Burke, Cancer Treatment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" src="utayploji.gif"/> </a></li> <li class='span4'> <a href="111.html" class="thumbnail"><img alt="Brooke Burke-Charvet Photo" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-charvet-photo.jpg.pagespeed.ic.eZcSwfCk1Z.jpg" src="treiwhoxu.gif"/> </a></li> <li class='span4'> <a href="247.html" class="thumbnail"><img alt="<NAME> Lingerie Line" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" src="wyalegualaf.gif"/> </a></li> <li class='span4'> <a href="123.html" class="thumbnail"><img alt="<NAME> and David Charvet" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-and-david-charvet.jpg.pagespeed.ic.iLiOSmNBgG.jpg" src="thywayhtyoch.gif"/> </a></li> <li class='span4'> <a href="233.html" class="thumbnail"><img alt="<NAME> Tom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-and-tom.jpg.pagespeed.ic.OfTSSeJdAZ.jpg" src="yokaywhyodooliwy.gif"/> </a></li> <li class='span4'> <a href="188.html" class="thumbnail"><img alt="The Naked Mom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/the-naked-mom.jpg.pagespeed.ce.2HxOs_fRpY.jpg" src="ooxoukynuakeyfoi.gif"/> </a></li> </ul> </div> <div class='widget'> <h4>Blog Archives</h4> <ul class='nav'> <li><a href="183.html">yarel ramos porn</a></li> <li><a href="359.html">yummychan.info candydoll</a></li> <li><a href="75.html">ximena duque nude</a></li> <li><a href="315.html">youtube stars nude fake</a></li> <li><a href="132.html">xxx icet's wife coco best nude naked sex pics</a></li> <li><a href="250.html">younv jailbait nonude model</a></li> <li><a href="209.html">youfotos de chikis rivera</a></li> <li><a href="237.html">young latina jailbait pics</a></li> </ul> </div> </div> </div> <div id='footer' itemscope itemtype='http://schema.org/WPFooter'> <div class='remove_padding'> <div id='footer_leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> </div> <p><p><a href="http://www.facebook.com/Penekula" target="new">Pelikula Update | Facebook</a><div><NAME> - <NAME> &amp; <NAME>. Tukso layuan . Requested Movie: Sagad sa Init - Sharmaine Arnaiz &amp; Ara Mina. SAGAD SA .</div><span>http://www.facebook.com/Penekula</span></p></p> <p> <a href="325.html">youtube videos calientes de mexicanas</a> | <a href="222.html">yougotposted videos/</a> | <a href="87.html">xnxxgooglesex</a> | <a href="269.html">youtube.com las mejores tanjitas 2012</a> </p> <p>&copy; 2013 The Hollywood Gossip - Celebrity Gossip and Entertainment News</p> <p><a href="90.html" rel="nofollow"><img alt="Sheknows-entertainment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xsheknows-entertainment-0dfb1ed120378c4d8a98720390d31272.png.pagespeed.ic.841FJHTKbK.png" src="xerxozheethrey.gif"/></a></p> </div> </div> <img height="1" width="1" pagespeed_lazy_src="http://tags.bluekai.com/site/3113" alt="" src="rtuagoutrewhoizu.gif"/> </div> </body> </html> <file_sep><!DOCTYPE html> <html id='en' lang='en'> <head> <title>www.zurichna.com/nydbl to:</title> <link href="ssoistoineypoagh.css" media="screen" rel="stylesheet" type="text/css"/> <link href="oopeinyroon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon"/> <link href="ouzeelouhtootw.jpg" rel='apple-touch-icon' sizes='144x144'> <link href="eytreyhoisefoaht.jpg" rel='apple-touch-icon' sizes='114x114'> <link href="ndyajeyssepuatr.jpg" rel='apple-touch-icon' sizes='72x72'> <link href="eychoopyatya.jpg" rel='apple-touch-icon'> <script type='text/javascript' src='eyzeywyazuneyhi.js'></script></head> <body itemscope itemtype='http://schema.org/WebPage'> <div id='header'> <div class='social visible-desktop'> <ul> <li class='twitter'><a href="106.html">xx fhoto full hot memek celeb indo</a></li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com' data-size='medium'></div> </li> <li class='facebook'> <div class='fb-like' data-href='http://www.facebook.com/thehollywoodgossip' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> </ul> </div> <div id='banner'> <a href="304.html"><img alt="The Hollywood Gossip" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xheader-7629f5d243c1cdc904bf535b05ff849f.jpg.pagespeed.ic.CDQOMwZhbJ.jpg" src="stawhaghoix.gif"/></a> </div> <div class='sites visible-desktop'> <a href="33.html">wwwyuppixcomvideo</a> | <a href="231.html">young girl imgchili</a> | <a href="202.html">yoshi shiraki mens haircuts</a> </div> <div class='login visible-desktop'> <a href="412.html">zeta phi beta chants every beat</a> &nbsp;|&nbsp; <a href="117.html">xxx chicas d prepa para celular</a> </div> </div> <div id='wrapper'> <div class='remove_padding'> <div id='leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='navbar' itemscope itemtype='http://schema.org/WPHeader'> <div class='navbar-inner'> <div class='container-fluid'> <a href="381.html">zara 666 opening</a> <div class='nav-collapse'> <ul class='nav'> <li class=''><a href="97.html">xvideos actrices de novelas</a></li> <li class=''><a href="351.html">yugo car company</a></li> <li class=''><a href="122.html">xxx cum gaggers</a></li> <li class=''><a href="268.html">youtube christina blackwell under skert shots</a></li> <li class=''><a href="319.html">youtube upskirt stacy dash</a></li> <li class=''><a href="75.html">ximena duque nude</a></li> <li class=''><a href="393.html">zastava m92 hand guard sale</a></li> <li class=''><a href="148.html">xxx pictures emily vancamp</a></li> <li class='login hidden-desktop'><a href="106.html">xx fhoto full hot memek celeb indo</a></li> <li class='login hidden-desktop'><a href="276.html">youtube dee<NAME></a></li> </ul> <form action="http://www.thehollywoodgossip.com/search" class='navbar-form pull-right'> <input class="input-medium" id="q" name="q" placeholder="Search" type="search"/> <button class="btn" type="submit"></button> </form> </div> </div> </div> </div> </div> <div class='container-fluid'> <div class='row-fluid'> <div class='span8' id='content'> <ul class="breadcrumb" itemprop="breadcrumb"><li><a href="172.html">yahoo server unavailable on iphone 5</a> /</li> <li><a href="236.html">young jodie sweetin naked pics</a> /</li> <li><a href="134.html">xxx images of nangi girl</a> /</li> <li><p><a href="https://secure.zurichna.com/specialties/nydbl/nydbl.nsf/pages/3a6b0ef8ba91db7085256a6b00580d36" target="new">NYDBL Claim Forms/Reporting - Zurich North America</a><div>NYDBL Claim Forms/Reporting. Early notification for New York State disability claims&#133;. &#133;made easy. Simply fill out all of the information on the following form .</div><span>https://secure.zurichna.com/specialties/nydbl/nydbl.nsf/pages/3a6b0ef8ba91db7085256a6b00580d36</span></p></li></ul> <div class='video' itemscope itemtype='http://schema.org/VideoObject'> <div class='page-header'> <h1><p><a href="https://uszicc.zurichna.com/nydbl/dblecenroll/DBLEcEnroll_login.asp" target="new">Online Bill Payment-Login - Zurich North America</a><div>This is a secure section of Zurich North America which requires your User Id. Your User Id is either your Tax Identification Number or your Unemployment .</div><span>https://uszicc.zurichna.com/nydbl/dblecenroll/DBLEcEnroll_login.asp</span></p></h1> </div> <ul id='sharebar'> <li> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='box_count' data-send='false' data-show-faces='false' data-width='60'></div> </li> <li class='pinit'><a href="314.html" class="pin-it-button" count-layout="vertical" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="sterroizheizerth.gif"/></a></li> <li> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='tall'></div> </li> <li> <a href="405.html">zendaya actully naked</a> </li> <li class='comments'> <div class='count comment_count'>1</div> <a href="249.html">young teen models jailbait</a> </li> </ul> <div class='sharebarx' style="display:none;"> <ul> <li class='facebook'> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='medium'></div> </li> <li class='twitter'> <a href="294.html">youtubelabigorra</a> </li> <li class='pinterest'><a href="340.html" class="pin-it-button" count-layout="horizontal" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="eevuassyaqundee.gif"/></a></li> <li class='comments'> <a href="410.html">zerobio mono drag</a> 1 </li> </ul> </div> <div class='thumbnail'> <div style="max-width:640px;max-height:459px;margin:0 auto;"> <img src="http://www.pa.ethz.ch/anstellung-arbeit/lohnsystem/Salary_overview.gif?hires" width="640" height="459" /> </div> <div class='caption' itemprop='description'><p><a href="https://secure.zurichna.com/specialties/nydbl/nydbl.nsf/pages/30DCF4C6B73A17838625786B0033F3D0" target="new">Notice of Compliance Poster - Zurich North America</a><div>Use this page to request a Notice of Compliance Poster under the New York State Disability Benefits Law. Please complete all fields below for the in force .</div><span>https://secure.zurichna.com/specialties/nydbl/nydbl.nsf/pages/30DCF4C6B73A17838625786B0033F3D0</span></p></div> <div class='rating-form' id='rating_7611' itemprop='aggregateRating' itemscope itemtype='http://schema.org/AggregateRating'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='inline-rating'><ul class="star-rating"><li class="current-rating" style="width:100%;">5.0 / 5.0</li><li><a href="156.html">xxx sexxxy pics of jacqueline pennewill</a></li> <li><a href="262.html">you tube boradcast yourself black freaks and booty shakers</a></li> <li><a href="252.html">youporn helen hunt sessions</a></li> <li><a href="408.html">zendaya colemans fake nude pics yovo,com</a></li> <li><a href="51.html">xbox 360 voice changer headset</a></li></ul></div> <br><p><a href="http://www.zurichna.com/zna/accidentandhealth/disability/njtdb.htm" target="new">New Jersey Disability coverage-Zurich NA</a><div>Zurich will no longer be providing Statutory Disability coverage in New Jersey. Zurich will no longer be providing Statutory Disability coverage in New Jersey.</div><span>http://www.zurichna.com/zna/accidentandhealth/disability/njtdb.htm</span></p></div> </div> <br> <ul class='pager'> <li class='next'> <a href="84.html">xnxxanna nicole smith fucking</a> </li> </ul> Related Videos: <ul class='thumbnails'> <li class='span4'> <a href="4.html" class="thumbnail"><img alt="Brooke Burke Interview" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/medium_l/brooke-burke-interview.jpg" src="yssusarternotr.gif"/> <div class='caption'>www.zurichna.com/nydbl to: Burke Interview</div> </a></li> </ul> <div class="remove_padding"><div id="content_rectangle" itemscope itemtype="http://schema.org/WPAdBlock"> </div></div> Embed Code: <pre class='embed'><p><a href="https://secure.zurichna.com/specialties/nydbl/nydbl.nsf/0/a7cb990af011cb3385256afc0063fce0/$FILE/Printable%20Audit%20Form.pdf" target="new">In order to process your annual audit - Zurich North America</a><div>Zurich North America. 58 South Service Road, Melville, NY 11747-2342. DBL Mailing Address: P.O. Box 9102, Plainview, NY 11803-9002. Telephone: (631) .</div><span>https://secure.zurichna.com/specialties/nydbl/nydbl.nsf/0/a7cb990af011cb3385256afc0063fce0/$FILE/Printable%20Audit%20Form.pdf</span></p> <p><a href="https://secure.zurichna.com/specialties/nydbl/nydbl.nsf/pages/C10C92198A27648E85256C4C0056369C" target="new">Contacts - Zurich North America</a><div>Contacts. Premium Accounting and Policy Administration: Zurich 58 South Service Road, Suite 300. Melville, New York 11747 -or- Zurich P.O. Box 9102 .</div><span>https://secure.zurichna.com/specialties/nydbl/nydbl.nsf/pages/C10C92198A27648E85256C4C0056369C</span></p></pre> <dl class='dl-horizontal'> <dt>Star:</dt> <dd> <a href="400.html">zastava pap m92 pv pistol, cal. 7.62x39mm</a> </dd> <dt>Related Videos:</dt> <dd><a href="53.html">xbox bras for sale</a></dd> <dt>Original Post:</dt> <dd itemprop='associatedArticle'><a href="28.html">www.yennyrivera.com</a></dd> <dt>Uploaded by:</dt> <dd><a href="380.html">zanx</a></dd> <dt>Uploaded:</dt> <dd><time datetime="2012-11-08T00:00:00+00:00" itemprop="uploadDate">November 08, 2012</time></dd> <dt>Duration:</dt> <dd> <time datetime='PT3M9S' itemprop='duration'>189 seconds</time> </dd> </dl> <hr> <div id='comments'> <h3> Comments (1 Total) <a href="310.html">youtube rick ross cherry bomb donk riding</a> </h3> <a href="43.html">xarelto coupons with insurance coverage</a> <div id='new_comment'> <form accept-charset="UTF-8" action="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/comments/" class="simple_form form-horizontal" data-remote="true" id="new_comment" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;"/><input name="authenticity_token" type="hidden" value="<KEY>></div> <div class='body'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <input name='page' type='hidden'> <input id="comment_parent_id" name="comment[parent_id]" type="hidden"/> <br> <p><p><a href="http://www.zurichna.com/zna/accidentandhealth/disability/Disabdisability.htm" target="new">Disability- Zurich in North America</a><div>Zurich insurance professionals are here to assess your risk &amp; provide accident . For information regarding the reporting of claims in NY, please go to NYDBL .</div><span>http://www.zurichna.com/zna/accidentandhealth/disability/Disabdisability.htm</span></p></p> <div class='row-fluid'> <div class='span8'> <div class="control-group string optional"><label class="string optional control-label" for="comment_anon_name">Name</label><div class="controls"><input class="string optional" id="comment_anon_name" name="comment[anon_name]" size="50" type="text"/><p class="help-block">Your name will appear with your comment</p></div></div> <div class="control-group email optional"><label class="email optional control-label" for="comment_anon_email">Email</label><div class="controls"><input class="string email optional" id="comment_anon_email" name="comment[anon_email]" size="50" type="email"/><p class="help-block"><p><a href="http://www.zurichna.com/internet/zna/SiteCollectionDocuments/en/Products/accidentandhealth/StatutorydisabilityNYandNJ.pdf" target="new">Statutory disability -NY and NJ - Zurich</a><div>Zurich&#39;s dedicated Web site for NYDBL. (www.zurichna.com/nydbl). &#150; Online quotes and applications for groups of one to 49 lives. &#150; Online premium payments .</div><span>http://www.zurichna.com/internet/zna/SiteCollectionDocuments/en/Products/accidentandhealth/StatutorydisabilityNYandNJ.pdf</span></p></p></div></div> </div> <div class='span4 providers'> <a href="342.html">yovodudefakes.com</a> <br> <a href="69.html">xerex kwentong kalibugan</a> <br> <a href="index.html">home</a> <br> </div> </div> <div class="control-group text optional"><label class="text optional control-label" for="comment_content">Content</label><div class="controls"><textarea class="text optional" cols="40" id="comment_content" name="comment[content]" rows="20" style="width:320px;height:80px"> </textarea></div></div> </div> <div class='form-actions'> <input class='btn cancel' href="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/#" style="display:none;" type='button' value='Cancel'> <input class="btn btn btn-primary" data-disable-with="Adding..." name="commit" type="submit" value="Add Comment"/> <br style="clear:both;"> </div> </form> </div> <div class='row-fluid'> <div class='span12'> <div class='comment' data-content='<EMAIL>' id='comment_403462' itemid='403462' itemprop='comment' itemscope itemtype='http://schema.org/UserComments'> <div class='comment_meta'> <div class='row-fluid'> <div class='span2'> <img alt="Avatar" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/missing/thumb/xavatar.png.pagespeed.ic.qjczMghcsC.jpg" style="float:left;margin-right:10px;" src="oiplitreendatwyv.gif"/> </div> <div class='span10'> <a href="121.html">xxx con padre hija gratis movil</a> <div class='author' itemprop='creator'>medo</div> <div class='created_at'><time datetime="2012-11-09T02:10:23-05:00" itemprop="commentTime"><p><a href="https://uszicc.zurichna.com/nydbl/dblcoi/" target="new">DBLCertificateOfLogin - Zurich North America</a><div>Use this page to request and generate a DB120.1 Form, Certificate of Insurance Coverage under the New York State Disability Benefits Law. Please complete .</div><span>https://uszicc.zurichna.com/nydbl/dblcoi/</span></p></time></div> </div> </div> </div> <div class='alert alert-message error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='comment_body'> <div class='content'> <p itemprop='commentText'><EMAIL></p> </div> </div> <div class='form-actions'> </div> <div class='reply_holder'> </div> </div> </div> </div> </div> </div> </div> <div class='span4' id='sidebar' itemscope itemtype='http://schema.org/WPSideBar'> <div id='sidebar_rectangle' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="134.html">xxx images of nangi girl</a></h4> <div class='clearfix' itemscope itemtype='http://schema.org/Person'> <a href="307.html" itemprop="image"><img alt="<NAME>" class="pull-left" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-nude.jpg.pagespeed.ic.Yp5z6xqFnh.jpg" style="margin-right:10px;" src="itridyotwiboocay.gif"/></a><p><a href="http://secure.zurichna.com/zus/zurichus.nsf/pages/My+Zurich?OpenDocument&amp;login" target="new">MyZurich login - Zurich North America</a><div>Zurich Small Business agents - starting on Jan. 7, 2013, you will need to access the quote engine through a new portal. An e-mail was sent to you on December .</div><span>http://secure.zurichna.com/zus/zurichus.nsf/pages/My+Zurich?OpenDocument&amp;login</span></p><dl> <dt>Born</dt> <dd itemprop='birthDate'><time datetime="1971-09-08T00:00:00+00:00">September 08, 1971</time></dd> <dt>Full Name</dt> <dd itemprop='name'>www.zurichna.com/nydbl to: Burke</dd> </dl> </div> </div> <div class='widget'> <h4><a href="171.html">yahoo server unavailable iphone 5</a></h4> <ul class='nav'> <li> <a href="364.html" class="clearfix"><img alt="Brooke Burke Prepares For Cancer Surgery" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" style="margin:0 10px 0 0;float:left;" src="yohtepeeqy.gif"/> www.zurichna.com/nydbl to: Burke Prepares For Cancer Surgery </a></li> <li> <a href="148.html" class="clearfix"><img alt="Brooke Burke Has Thyroid Cancer" class="span3" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/thumb/brooke-burke-charvet-cancer-me.jpg" style="margin:0 10px 0 0;float:left;" src="gawyasuv.gif"/> www.zurichna.com/nydbl to: Burke Has Thyroid Cancer </a></li> <li> <a href="43.html" class="clearfix"><img alt="Brooke Burke Charvet Releases New Lingerie Line" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" style="margin:0 10px 0 0;float:left;" src="kourtoujendoaple.gif"/> www.zurichna.com/nydbl to: Burke Charvet Releases New Lingerie Line </a></li> </ul> </div> <div id='skyscraper' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="42.html">xarelto coupons medicare part d</a></h4> <ul class='thumbnails'> <li class='span4'> <a href="327.html" class="thumbnail"><img alt="Brooke Burke, Cancer Treatment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" src="utayploji.gif"/> </a></li> <li class='span4'> <a href="390.html" class="thumbnail"><img alt="Brooke Burke-Charvet Photo" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-charvet-photo.jpg.pagespeed.ic.eZcSwfCk1Z.jpg" src="treiwhoxu.gif"/> </a></li> <li class='span4'> <a href="339.html" class="thumbnail"><img alt="Brooke Burke Lingerie Line" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" src="wyalegualaf.gif"/> </a></li> <li class='span4'> <a href="253.html" class="thumbnail"><img alt="<NAME> and <NAME>" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-and-david-charvet.jpg.pagespeed.ic.iLiOSmNBgG.jpg" src="thywayhtyoch.gif"/> </a></li> <li class='span4'> <a href="152.html" class="thumbnail"><img alt="<NAME> Tom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-and-tom.jpg.pagespeed.ic.OfTSSeJdAZ.jpg" src="yokaywhyodooliwy.gif"/> </a></li> <li class='span4'> <a href="67.html" class="thumbnail"><img alt="The Naked Mom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/the-naked-mom.jpg.pagespeed.ce.2HxOs_fRpY.jpg" src="ooxoukynuakeyfoi.gif"/> </a></li> </ul> </div> <div class='widget'> <h4>Blog Archives</h4> <ul class='nav'> <li><a href="235.html">young jailbait non nude</a></li> <li><a href="136.html">xxx jaguar artwork</a></li> <li><a href="368.html">yvette vickers body</a></li> <li><a href="253.html">youporn mexicanas descarga gratis</a></li> <li><a href="112.html">xxx 3 gp de aguelas con sus ñetos</a></li> <li><a href="371.html">zac efron naked</a></li> <li><a href="9.html">www wapdam big porn picthers bravoteens com</a></li> <li><a href="308.html">youtube rapid city sd mariahs drunk</a></li> </ul> </div> </div> </div> <div id='footer' itemscope itemtype='http://schema.org/WPFooter'> <div class='remove_padding'> <div id='footer_leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> </div> <p><p><a href="https://secure.zurichna.com/specialties/nydbl/nydbl.nsf/pages/home?OpenDocument" target="new">NY DBL Home - Zurich North America</a><div>Zurich will no longer be providing Statutory Disability coverage in New York. Zurich will no longer be providing Statutory Disability coverage in New York.</div><span>https://secure.zurichna.com/specialties/nydbl/nydbl.nsf/pages/home?OpenDocument</span></p></p> <p> <a href="195.html">yoga sales</a> | <a href="251.html">youporn.com/nn preteen models</a> | <a href="205.html">yotubesexo.com/medias</a> | <a href="321.html">you tube ver fotos de mariana seoane</a> </p> <p>&copy; 2013 The Hollywood Gossip - Celebrity Gossip and Entertainment News</p> <p><a href="198.html" rel="nofollow"><img alt="Sheknows-entertainment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xsheknows-entertainment-0dfb1ed120378c4d8a98720390d31272.png.pagespeed.ic.841FJHTKbK.png" src="xerxozheethrey.gif"/></a></p> </div> </div> <img height="1" width="1" pagespeed_lazy_src="http://tags.bluekai.com/site/3113" alt="" src="rtuagoutrewhoizu.gif"/> </div> </body> </html> <file_sep><!DOCTYPE html> <html id='en' lang='en'> <head> <title>xxxvajinas</title> <link href="ssoistoineypoagh.css" media="screen" rel="stylesheet" type="text/css"/> <link href="oopeinyroon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon"/> <link href="ouzeelouhtootw.jpg" rel='apple-touch-icon' sizes='144x144'> <link href="eytreyhoisefoaht.jpg" rel='apple-touch-icon' sizes='114x114'> <link href="ndyajeyssepuatr.jpg" rel='apple-touch-icon' sizes='72x72'> <link href="eychoopyatya.jpg" rel='apple-touch-icon'> <script type='text/javascript' src='eyzeywyazuneyhi.js'></script></head> <body itemscope itemtype='http://schema.org/WebPage'> <div id='header'> <div class='social visible-desktop'> <ul> <li class='twitter'><a href="120.html">xxx con flacas gratis 3gp</a></li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com' data-size='medium'></div> </li> <li class='facebook'> <div class='fb-like' data-href='http://www.facebook.com/thehollywoodgossip' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> </ul> </div> <div id='banner'> <a href="383.html"><img alt="The Hollywood Gossip" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xheader-7629f5d243c1cdc904bf535b05ff849f.jpg.pagespeed.ic.CDQOMwZhbJ.jpg" src="stawhaghoix.gif"/></a> </div> <div class='sites visible-desktop'> <a href="386.html">zara sale</a> | <a href="264.html">youtube brooke burke playboy</a> | <a href="104.html">xvideos mujeres follando con perros</a> </div> <div class='login visible-desktop'> <a href="117.html">xxx chicas d prepa para celular</a> &nbsp;|&nbsp; <a href="91.html">xoskeleton watch for sale craigslist</a> </div> </div> <div id='wrapper'> <div class='remove_padding'> <div id='leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='navbar' itemscope itemtype='http://schema.org/WPHeader'> <div class='navbar-inner'> <div class='container-fluid'> <a href="49.html">xbooru tram pararam meja mi</a> <div class='nav-collapse'> <ul class='nav'> <li class=''><a href="160.html">xxx ver videos on line para nokia c3</a></li> <li class=''><a href="23.html">www xxx hot sexy nangi picture com</a></li> <li class=''><a href="285.html">youtube gory death pictures</a></li> <li class=''><a href="index.html">home</a></li> <li class=''><a href="169.html">yaguelin bracamonte en el porno</a></li> <li class=''><a href="181.html">yaqui guerrido en tangas</a></li> <li class=''><a href="91.html">xoskeleton watch for sale craigslist</a></li> <li class=''><a href="377.html">zander identify theft vs. lifelock</a></li> <li class='login hidden-desktop'><a href="361.html">yuo tube jenny rivera her funeral</a></li> <li class='login hidden-desktop'><a href="41.html">xarelto and medicare</a></li> </ul> <form action="http://www.thehollywoodgossip.com/search" class='navbar-form pull-right'> <input class="input-medium" id="q" name="q" placeholder="Search" type="search"/> <button class="btn" type="submit"></button> </form> </div> </div> </div> </div> </div> <div class='container-fluid'> <div class='row-fluid'> <div class='span8' id='content'> <ul class="breadcrumb" itemprop="breadcrumb"><li><a href="167.html">xyooj aviaries</a> /</li> <li><a href="135.html">xxx imajenes de brenda besares en bikini</a> /</li> <li><a href="392.html">zastava m92 folding stock</a> /</li> <li><p><a href="http://www.memecik.com/freexxx/xxxvaginas" target="new">Free xxxvaginas XXX Videos | Porn Movies | Memecik.com</a><div>100% free xxxvaginas sex videos. xxxvaginas xxx porn movies.</div><span>http://www.memecik.com/freexxx/xxxvaginas</span></p></li></ul> <div class='video' itemscope itemtype='http://schema.org/VideoObject'> <div class='page-header'> <h1><p><a href="http://www.nuvideos.info/hot-girls-fucking-one-lucky-guy.html" target="new">Hot girls fucking one lucky guy</a><div>Dec 27, 2012 . Tags: dad camara oculta, videos xxx vajinas peludas, xnxx porno rellenitas, mexicanas bbw voys xxx, colegialas venezolanasxxx, xxxafricanas .</div><span>http://www.nuvideos.info/hot-girls-fucking-one-lucky-guy.html</span></p></h1> </div> <ul id='sharebar'> <li> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='box_count' data-send='false' data-show-faces='false' data-width='60'></div> </li> <li class='pinit'><a href="57.html" class="pin-it-button" count-layout="vertical" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="sterroizheizerth.gif"/></a></li> <li> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='tall'></div> </li> <li> <a href="43.html">xarelto coupons with insurance coverage</a> </li> <li class='comments'> <div class='count comment_count'>1</div> <a href="382.html">zara apply online</a> </li> </ul> <div class='sharebarx' style="display:none;"> <ul> <li class='facebook'> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='medium'></div> </li> <li class='twitter'> <a href="247.html">youngstown mafia history</a> </li> <li class='pinterest'><a href="331.html" class="pin-it-button" count-layout="horizontal" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="eevuassyaqundee.gif"/></a></li> <li class='comments'> <a href="137.html">xxx jail bait non nude</a> 1 </li> </ul> </div> <div class='thumbnail'> <div style="max-width:640px;max-height:459px;margin:0 auto;"> <img src="http://thumbnails.domaintools.com/domaintools/2012-12-13T20:39:24.000Z/HkYRyiBf7tyyGdET048l4wOI7Ck=/xxxvoce.net/thumbnail/current/xxxvoce.jpg" width="640" height="459" /> </div> <div class='caption' itemprop='description'><p><a href="http://www.xvideoswet.com/vajinas-grande-xxx.html" target="new">vajinas grande xxx - vajinas grande xxx porn tube - vajinas grande ...</a><div>Dec 22, 2012 . Related Videos. xxxindianxxx. 100% Like 305 views 2012-10-28 03:57:20. xxxxxindian. 100% Like 289 views 2012-10-28 03:57:22. xxxmovias .</div><span>http://www.xvideoswet.com/vajinas-grande-xxx.html</span></p></div> <div class='rating-form' id='rating_7611' itemprop='aggregateRating' itemscope itemtype='http://schema.org/AggregateRating'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='inline-rating'><ul class="star-rating"><li class="current-rating" style="width:100%;">5.0 / 5.0</li><li><a href="275.html">youtube dat viet heo con phim sex</a></li> <li><a href="148.html">xxx pictures emily vancamp</a></li> <li><a href="418.html">zillow rentals orange ca</a></li> <li><a href="204.html">yotube bideos gringas mamando berga sexso porno</a></li> <li><a href="34.html">www.zee tv's banu mein teri dulhan actres fake porn.com</a></li></ul></div> <br><p><a href="http://www.memecik.com/freexxx/xxxvaginas" target="new">Free xxxvaginas XXX Videos | Porn Movies | Memecik.com</a><div>100% free xxxvaginas sex videos. xxxvaginas xxx porn movies.</div><span>http://www.memecik.com/freexxx/xxxvaginas</span></p></div> </div> <br> <ul class='pager'> <li class='next'> <a href="145.html">xxx.photo indian actress download . in</a> </li> </ul> Related Videos: <ul class='thumbnails'> <li class='span4'> <a href="131.html" class="thumbnail"><img alt="Brooke Burke Interview" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/medium_l/brooke-burke-interview.jpg" src="yssusarternotr.gif"/> <div class='caption'>xxxvajinas Burke Interview</div> </a></li> </ul> <div class="remove_padding"><div id="content_rectangle" itemscope itemtype="http://schema.org/WPAdBlock"> </div></div> Embed Code: <pre class='embed'><p><a href="http://www.nuvideos.info/hot-girls-fucking-one-lucky-guy.html" target="new">Hot girls fucking one lucky guy</a><div>Dec 27, 2012 . Tags: dad camara oculta, videos xxx vajinas peludas, xnxx porno rellenitas, mexicanas bbw voys xxx, colegialas venezolanasxxx, xxxafricanas .</div><span>http://www.nuvideos.info/hot-girls-fucking-one-lucky-guy.html</span></p> <p><a href="http://www.xvideoswet.com/vajinas-grande-xxx.html" target="new">vajinas grande xxx - vajinas grande xxx porn tube - vajinas grande ...</a><div>Dec 22, 2012 . Related Videos. xxxindianxxx. 100% Like 305 views 2012-10-28 03:57:20. xxxxxindian. 100% Like 289 views 2012-10-28 03:57:22. xxxmovias .</div><span>http://www.xvideoswet.com/vajinas-grande-xxx.html</span></p> <p><a href="http://www.nuvideos.info/hot-girls-fucking-one-lucky-guy.html" target="new">Hot girls fucking one lucky guy</a><div>Dec 27, 2012 . Tags: dad camara oculta, videos xxx vajinas peludas, xnxx porno rellenitas, mexicanas bbw voys xxx, colegialas venezolanasxxx, xxxafricanas .</div><span>http://www.nuvideos.info/hot-girls-fucking-one-lucky-guy.html</span></p></pre> <dl class='dl-horizontal'> <dt>Star:</dt> <dd> <a href="71.html">xerex sagad tukso</a> </dd> <dt>Related Videos:</dt> <dd><a href="29.html">www.youtube. bajar en celular video sexo porno corto mujer con zoofila.com</a></dd> <dt>Original Post:</dt> <dd itemprop='associatedArticle'><a href="309.html">you tuberestos de janny rivera</a></dd> <dt>Uploaded by:</dt> <dd><a href="356.html">yugo pap sbr</a></dd> <dt>Uploaded:</dt> <dd><time datetime="2012-11-08T00:00:00+00:00" itemprop="uploadDate">November 08, 2012</time></dd> <dt>Duration:</dt> <dd> <time datetime='PT3M9S' itemprop='duration'>189 seconds</time> </dd> </dl> <hr> <div id='comments'> <h3> Comments (1 Total) <a href="259.html">you tube antarvasna dot com</a> </h3> <a href="341.html">yovodude.com</a> <div id='new_comment'> <form accept-charset="UTF-8" action="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/comments/" class="simple_form form-horizontal" data-remote="true" id="new_comment" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;"/><input name="authenticity_token" type="hidden" value="<KEY>="/></div> <div class='body'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <input name='page' type='hidden'> <input id="comment_parent_id" name="comment[parent_id]" type="hidden"/> <br> <p><p><a href="http://www.xvideoswet.com/vajinas-grande-xxx.html" target="new">vajinas grande xxx - vajinas grande xxx porn tube - vajinas grande ...</a><div>Dec 22, 2012 . Related Videos. xxxindianxxx. 100% Like 305 views 2012-10-28 03:57:20. xxxxxindian. 100% Like 289 views 2012-10-28 03:57:22. xxxmovias .</div><span>http://www.xvideoswet.com/vajinas-grande-xxx.html</span></p></p> <div class='row-fluid'> <div class='span8'> <div class="control-group string optional"><label class="string optional control-label" for="comment_anon_name">Name</label><div class="controls"><input class="string optional" id="comment_anon_name" name="comment[anon_name]" size="50" type="text"/><p class="help-block">Your name will appear with your comment</p></div></div> <div class="control-group email optional"><label class="email optional control-label" for="comment_anon_email">Email</label><div class="controls"><input class="string email optional" id="comment_anon_email" name="comment[anon_email]" size="50" type="email"/><p class="help-block"><p><a href="http://www.sexdude.info/germans-have-sex-in-the-bathtub.html" target="new">Germans have Sex in the Bathtub</a><div>Dec 18, 2012. de brazile&Atilde;&plusmn;as, &Acirc;&iquest;colegialas hondure&Atilde;&plusmn;as?, slepin desvianas, mexicanas panochitas peludas xxx, vajinas raras, videos de secretriasxxx .</div><span>http://www.sexdude.info/germans-have-sex-in-the-bathtub.html</span></p></p></div></div> </div> <div class='span4 providers'> <a href="314.html">you tube stacked inverted bob cuts</a> <br> <a href="209.html">youfotos de chikis rivera</a> <br> <a href="90.html">xoskeleton home office</a> <br> </div> </div> <div class="control-group text optional"><label class="text optional control-label" for="comment_content">Content</label><div class="controls"><textarea class="text optional" cols="40" id="comment_content" name="comment[content]" rows="20" style="width:320px;height:80px"> </textarea></div></div> </div> <div class='form-actions'> <input class='btn cancel' href="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/#" style="display:none;" type='button' value='Cancel'> <input class="btn btn btn-primary" data-disable-with="Adding..." name="commit" type="submit" value="Add Comment"/> <br style="clear:both;"> </div> </form> </div> <div class='row-fluid'> <div class='span12'> <div class='comment' data-content='<EMAIL>' id='comment_403462' itemid='403462' itemprop='comment' itemscope itemtype='http://schema.org/UserComments'> <div class='comment_meta'> <div class='row-fluid'> <div class='span2'> <img alt="Avatar" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/missing/thumb/xavatar.png.pagespeed.ic.qjczMghcsC.jpg" style="float:left;margin-right:10px;" src="oiplitreendatwyv.gif"/> </div> <div class='span10'> <a href="2.html">www.usbankingonline</a> <div class='author' itemprop='creator'>medo</div> <div class='created_at'><time datetime="2012-11-09T02:10:23-05:00" itemprop="commentTime"><p><a href="http://www.memecik.com/freexxx/xxxvaginas" target="new">Free xxxvaginas XXX Videos | Porn Movies | Memecik.com</a><div>100% free xxxvaginas sex videos. xxxvaginas xxx porn movies.</div><span>http://www.memecik.com/freexxx/xxxvaginas</span></p></time></div> </div> </div> </div> <div class='alert alert-message error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='comment_body'> <div class='content'> <p itemprop='commentText'><EMAIL></p> </div> </div> <div class='form-actions'> </div> <div class='reply_holder'> </div> </div> </div> </div> </div> </div> </div> <div class='span4' id='sidebar' itemscope itemtype='http://schema.org/WPSideBar'> <div id='sidebar_rectangle' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="149.html">xxx poringa</a></h4> <div class='clearfix' itemscope itemtype='http://schema.org/Person'> <a href="14.html" itemprop="image"><img alt="<NAME>" class="pull-left" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-nude.jpg.pagespeed.ic.Yp5z6xqFnh.jpg" style="margin-right:10px;" src="itridyotwiboocay.gif"/></a><p><a href="http://www.xxxporns.net/tags/index33.html" target="new">33 - Xxxporns.net</a><div>. movie 3d rapidshare watch extreme rape movies xxxvajinas.com Kasmiri porn movies japaneze forced porno lady boobs itali mature xxx johanna maldonado .</div><span>http://www.xxxporns.net/tags/index33.html</span></p><dl> <dt>Born</dt> <dd itemprop='birthDate'><time datetime="1971-09-08T00:00:00+00:00">September 08, 1971</time></dd> <dt>Full Name</dt> <dd itemprop='name'><NAME></dd> </dl> </div> </div> <div class='widget'> <h4><a href="268.html">youtube christina blackwell under skert shots</a></h4> <ul class='nav'> <li> <a href="348.html" class="clearfix"><img alt="Brooke Burke Prepares For Cancer Surgery" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" style="margin:0 10px 0 0;float:left;" src="yohtepeeqy.gif"/> xxxvajinas Burke Prepares For Cancer Surgery </a></li> <li> <a href="156.html" class="clearfix"><img alt="Brooke Burke Has Thyroid Cancer" class="span3" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/thumb/brooke-burke-charvet-cancer-me.jpg" style="margin:0 10px 0 0;float:left;" src="gawyasuv.gif"/> xxxvajinas Burke Has Thyroid Cancer </a></li> <li> <a href="106.html" class="clearfix"><img alt="Brooke Burke Charvet Releases New Lingerie Line" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" style="margin:0 10px 0 0;float:left;" src="kourtoujendoaple.gif"/> xxxvajinas Burke Charvet Releases New Lingerie Line </a></li> </ul> </div> <div id='skyscraper' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="82.html">xmiss12g2</a></h4> <ul class='thumbnails'> <li class='span4'> <a href="97.html" class="thumbnail"><img alt="Brooke Burke, Cancer Treatment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" src="utayploji.gif"/> </a></li> <li class='span4'> <a href="297.html" class="thumbnail"><img alt="Brooke Burke-Charvet Photo" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-charvet-photo.jpg.pagespeed.ic.eZcSwfCk1Z.jpg" src="treiwhoxu.gif"/> </a></li> <li class='span4'> <a href="141.html" class="thumbnail"><img alt="Brooke Burke Lingerie Line" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" src="wyalegualaf.gif"/> </a></li> <li class='span4'> <a href="166.html" class="thumbnail"><img alt="<NAME> and <NAME>" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-and-david-charvet.jpg.pagespeed.ic.iLiOSmNBgG.jpg" src="thywayhtyoch.gif"/> </a></li> <li class='span4'> <a href="371.html" class="thumbnail"><img alt="<NAME> Tom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-and-tom.jpg.pagespeed.ic.OfTSSeJdAZ.jpg" src="yokaywhyodooliwy.gif"/> </a></li> <li class='span4'> <a href="217.html" class="thumbnail"><img alt="The Naked Mom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/the-naked-mom.jpg.pagespeed.ce.2HxOs_fRpY.jpg" src="ooxoukynuakeyfoi.gif"/> </a></li> </ul> </div> <div class='widget'> <h4>Blog Archives</h4> <ul class='nav'> <li><a href="141.html">xxx nangi video film</a></li> <li><a href="108.html">xxsmodels bianka</a></li> <li><a href="322.html">youtube video caseros calientes</a></li> <li><a href="1.html">www.urfreeoffer.com/burkeburke</a></li> <li><a href="360.html">yummychan.org/jb/</a></li> <li><a href="73.html">xhamster.com pics kidnapped</a></li> <li><a href="10.html">www.wapdesi .com</a></li> <li><a href="328.html">youtube. videos mujeres con animales gratis</a></li> </ul> </div> </div> </div> <div id='footer' itemscope itemtype='http://schema.org/WPFooter'> <div class='remove_padding'> <div id='footer_leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> </div> <p><p><a href="http://www.xnxxtr.info/sikisler/xxxvajina-pormo.html" target="new">xxxvajina pormo sex pornolar?, xxxvajina pormo porno videolar? ...</a><div>xxxvajina pormo canl? erotik pornolar, xxxvajina pormo t&uuml;rk siki? porno, xxxvajina pormo sex siki? videosu, xxxvajina pormo anal pornolar.</div><span>http://www.xnxxtr.info/sikisler/xxxvajina-pormo.html</span></p></p> <p> <a href="94.html">xv anos de la hija de jenni rivera</a> | <a href="170.html">yahoo mail server unavailable iphone 5</a> | <a href="292.html">youtube jp sauer and sohn suhl</a> | <a href="67.html">xdesi.mobi/x2/download/desi panjab fat</a> </p> <p>&copy; 2013 The Hollywood Gossip - Celebrity Gossip and Entertainment News</p> <p><a href="125.html" rel="nofollow"><img alt="Sheknows-entertainment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xsheknows-entertainment-0dfb1ed120378c4d8a98720390d31272.png.pagespeed.ic.841FJHTKbK.png" src="xerxozheethrey.gif"/></a></p> </div> </div> <img height="1" width="1" pagespeed_lazy_src="http://tags.bluekai.com/site/3113" alt="" src="rtuagoutrewhoizu.gif"/> </div> </body> </html> <file_sep><!DOCTYPE html> <html id='en' lang='en'> <head> <title>xoxo watch instructions</title> <link href="ssoistoineypoagh.css" media="screen" rel="stylesheet" type="text/css"/> <link href="oopeinyroon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon"/> <link href="ouzeelouhtootw.jpg" rel='apple-touch-icon' sizes='144x144'> <link href="eytreyhoisefoaht.jpg" rel='apple-touch-icon' sizes='114x114'> <link href="ndyajeyssepuatr.jpg" rel='apple-touch-icon' sizes='72x72'> <link href="eychoopyatya.jpg" rel='apple-touch-icon'> <script type='text/javascript' src='eyzeywyazuneyhi.js'></script></head> <body itemscope itemtype='http://schema.org/WebPage'> <div id='header'> <div class='social visible-desktop'> <ul> <li class='twitter'><a href="180.html">yaqui guerrido descuido</a></li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com' data-size='medium'></div> </li> <li class='facebook'> <div class='fb-like' data-href='http://www.facebook.com/thehollywoodgossip' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> </ul> </div> <div id='banner'> <a href="412.html"><img alt="The Hollywood Gossip" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xheader-7629f5d243c1cdc904bf535b05ff849f.jpg.pagespeed.ic.CDQOMwZhbJ.jpg" src="stawhaghoix.gif"/></a> </div> <div class='sites visible-desktop'> <a href="191.html">yisela avendano nude</a> | <a href="315.html">youtube stars nude fake</a> | <a href="1.html">www.urfreeoffer.com/burkeburke</a> </div> <div class='login visible-desktop'> <a href="213.html">yougotposted.com</a> &nbsp;|&nbsp; <a href="402.html">zayn malik animated naked fakes</a> </div> </div> <div id='wrapper'> <div class='remove_padding'> <div id='leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='navbar' itemscope itemtype='http://schema.org/WPHeader'> <div class='navbar-inner'> <div class='container-fluid'> <a href="388.html">zar verb endings in present</a> <div class='nav-collapse'> <ul class='nav'> <li class=''><a href="350.html">yugo car</a></li> <li class=''><a href="113.html">xxx 3gp de maestros/as</a></li> <li class=''><a href="199.html">yolanda on ghetto gaggers full video</a></li> <li class=''><a href="388.html">zar verb endings in present</a></li> <li class=''><a href="5.html">www. vajinas mojadas.com famosas.com</a></li> <li class=''><a href="101.html">xvideos draya</a></li> <li class=''><a href="141.html">xxx nangi video film</a></li> <li class=''><a href="283.html">youtube fat lady singing</a></li> <li class='login hidden-desktop'><a href="210.html">you got posred/tiff banister</a></li> <li class='login hidden-desktop'><a href="281.html">youtube el hijo de jenni rivera</a></li> </ul> <form action="http://www.thehollywoodgossip.com/search" class='navbar-form pull-right'> <input class="input-medium" id="q" name="q" placeholder="Search" type="search"/> <button class="btn" type="submit"></button> </form> </div> </div> </div> </div> </div> <div class='container-fluid'> <div class='row-fluid'> <div class='span8' id='content'> <ul class="breadcrumb" itemprop="breadcrumb"><li><a href="318.html">you tube theocratic ministry school review 2013</a> /</li> <li><a href="79.html">xl yacht insurance</a> /</li> <li><a href="416.html">zillow rentals florida</a> /</li> <li><p><a href="http://www.youtube.com/watch?v=8xQoy-tNggM" target="new">XOXO Women&#39;s XO5302A Rhinestone Accent Gold-Tone ... - YouTube</a><div>Jul 13, 2011 . You need Adobe Flash Player to watch this video. Download it from Adobe. XOXO Women&#39;s XO5302A Rhinestone Accent Gold-Tone Bracelet .</div><span>http://www.youtube.com/watch?v=8xQoy-tNggM</span></p></li></ul> <div class='video' itemscope itemtype='http://schema.org/VideoObject'> <div class='page-header'> <h1><p><a href="http://www.sulit.com.ph/index.php/view+classifieds/id/7524263/XOXO+Women&#39;s+XO8038+Silver+White+Bumpy+Silicon+Strap+Watch" target="new">XOXO Women&#39;s XO8038 Silver White Bumpy Silicon Strap Watch ...</a><div>3 days ago . Dial color Silver Bezel material Metal Bezel function Stationary Movement Analog quartz. Comes in Original XOXO Box with watch manual and .</div><span>http://www.sulit.com.ph/index.php/view+classifieds/id/7524263/XOXO+Women&#39;s+XO8038+Silver+White+Bumpy+Silicon+Strap+Watch</span></p></h1> </div> <ul id='sharebar'> <li> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='box_count' data-send='false' data-show-faces='false' data-width='60'></div> </li> <li class='pinit'><a href="408.html" class="pin-it-button" count-layout="vertical" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="sterroizheizerth.gif"/></a></li> <li> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='tall'></div> </li> <li> <a href="134.html">xxx images of nangi girl</a> </li> <li class='comments'> <div class='count comment_count'>1</div> <a href="91.html">xoskeleton watch for sale craigslist</a> </li> </ul> <div class='sharebarx' style="display:none;"> <ul> <li class='facebook'> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='medium'></div> </li> <li class='twitter'> <a href="369.html">yvm torrent</a> </li> <li class='pinterest'><a href="327.html" class="pin-it-button" count-layout="horizontal" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="eevuassyaqundee.gif"/></a></li> <li class='comments'> <a href="391.html">zastava m85 pv 5.56 .223 pistol ak-47 in 223</a> 1 </li> </ul> </div> <div class='thumbnail'> <div style="max-width:640px;max-height:459px;margin:0 auto;"> <img src="http://i.ebayimg.com/00/s/MTAyNFgxMDI0/$(KGrHqEOKkME6QdcBfl-BOwLey(uTg~~60_35.JPG" width="640" height="459" /> </div> <div class='caption' itemprop='description'><p><a href="http://www.amazon.com/XOXO-Womens-XO114-Rhinestone-Bracelet/dp/B003DIPA9C" target="new">XOXO Women&#39;s XO114 Rhinestone Accent White Enamel Bracelet ...</a><div>XOXO Women&#39;s XO114 Rhinestone Accent White Enamel Bracelet Watch: Watches: . You may find many from bracelet watch women shopping guide.</div><span>http://www.amazon.com/XOXO-Womens-XO114-Rhinestone-Bracelet/dp/B003DIPA9C</span></p></div> <div class='rating-form' id='rating_7611' itemprop='aggregateRating' itemscope itemtype='http://schema.org/AggregateRating'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='inline-rating'><ul class="star-rating"><li class="current-rating" style="width:100%;">5.0 / 5.0</li><li><a href="229.html">young flexible tumblr</a></li> <li><a href="203.html">yotube bervideos colejialss de guatemala sexso porno</a></li> <li><a href="365.html">yutu mujeres cojiendo</a></li> <li><a href="206.html">yotubesexo doble penetracion</a></li> <li><a href="271.html">youtube.com tangas mexicanas</a></li></ul></div> <br><p><a href="http://www.ayosdito.ph/XOXO+Womens+Rhinestone+Accent+GoldTone+Watch-4412998.htm" target="new">XOXO Womens Rhinestone Accent GoldTone Watch | Clothing ...</a><div>XOXO Womens Rhinestone Accent GoldTone Watch Price: PHP1 995 Condition: 2. :628383934. . 100% AUTHENTIC w/ ORIGINAL BOX &amp; WATCH MANUAL .</div><span>http://www.ayosdito.ph/XOXO+Womens+Rhinestone+Accent+GoldTone+Watch-4412998.htm</span></p></div> </div> <br> <ul class='pager'> <li class='next'> <a href="286.html">you tube imagenes de she mails follando</a> </li> </ul> Related Videos: <ul class='thumbnails'> <li class='span4'> <a href="236.html" class="thumbnail"><img alt="Brooke Burke Interview" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/medium_l/brooke-burke-interview.jpg" src="yssusarternotr.gif"/> <div class='caption'>xoxo watch instructions Burke Interview</div> </a></li> </ul> <div class="remove_padding"><div id="content_rectangle" itemscope itemtype="http://schema.org/WPAdBlock"> </div></div> Embed Code: <pre class='embed'><p><a href="http://www.kohls.com/catalog/jewelry-and-watches-necklaces-fashion-xoxo.jsp?CN=3000001634+4294872445" target="new">Jewelry &amp; Watches Necklaces Fashion: XOXO | Kohl&#39;s</a><div>Shop the Kohl&#39;s Jewelry &amp; Watches XOXO Fashion collection today! Expect great things when you save at Kohls.com.</div><span>http://www.kohls.com/catalog/jewelry-and-watches-necklaces-fashion-xoxo.jsp?CN=3000001634+4294872445</span></p> <p><a href="http://www.ebay.ph/itm/Xoxo-Watch-Womens-Square-Case-Silver-Dial-Pink-Charm-Bracelet-SALE-BNEW-/330781993367" target="new">Xoxo Watch Women&#39;s Square Case Silver Dial Pink Charm Bracelet ...</a><div>Xoxo Watch Women&#39;s Square Case Silver Dial Pink Charm Bracelet SALE . Express , Other - See seller&#39;s payment instructions | See payment information .</div><span>http://www.ebay.ph/itm/Xoxo-Watch-Womens-Square-Case-Silver-Dial-Pink-Charm-Bracelet-SALE-BNEW-/330781993367</span></p></pre> <dl class='dl-horizontal'> <dt>Star:</dt> <dd> <a href="79.html">xl yacht insurance</a> </dd> <dt>Related Videos:</dt> <dd><a href="388.html">zar verb endings in present</a></dd> <dt>Original Post:</dt> <dd itemprop='associatedArticle'><a href="353.html">yugo pap m85pv pistol</a></dd> <dt>Uploaded by:</dt> <dd><a href="74.html">xhamster de<NAME>ero</a></dd> <dt>Uploaded:</dt> <dd><time datetime="2012-11-08T00:00:00+00:00" itemprop="uploadDate">November 08, 2012</time></dd> <dt>Duration:</dt> <dd> <time datetime='PT3M9S' itemprop='duration'>189 seconds</time> </dd> </dl> <hr> <div id='comments'> <h3> Comments (1 Total) <a href="103.html">x videos mexicanas gratis para celular</a> </h3> <a href="380.html">zanx</a> <div id='new_comment'> <form accept-charset="UTF-8" action="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/comments/" class="simple_form form-horizontal" data-remote="true" id="new_comment" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;"/><input name="authenticity_token" type="hidden" value="<KEY>="/></div> <div class='body'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <input name='page' type='hidden'> <input id="comment_parent_id" name="comment[parent_id]" type="hidden"/> <br> <p><p><a href="http://www.mickeyshoppe.com/" target="new">Xoxo Watches, Nine West Wallets and Bags, &amp; more! | Mickey Shoppe</a><div>1 fashion store for all xoxo watches, Handbags, nine west wallets, Dresses, Watches and more! . There were no instructions with it. The time was not set for the .</div><span>http://www.mickeyshoppe.com/</span></p></p> <div class='row-fluid'> <div class='span8'> <div class="control-group string optional"><label class="string optional control-label" for="comment_anon_name">Name</label><div class="controls"><input class="string optional" id="comment_anon_name" name="comment[anon_name]" size="50" type="text"/><p class="help-block">Your name will appear with your comment</p></div></div> <div class="control-group email optional"><label class="email optional control-label" for="comment_anon_email">Email</label><div class="controls"><input class="string email optional" id="comment_anon_email" name="comment[anon_email]" size="50" type="email"/><p class="help-block"><p><a href="http://www.amazon.com/XOXO-Womens-XO3042-Black-Leather/dp/B002PY7NS6" target="new">XOXO Women&#39;s XO3042 Black Leather Strap Watch: Watches ...</a><div>Warranty Offer: All XOXO watches purchased direct from Amazon.com are . date and AM/PM) There were no instructions, and I have had similar watches in the .</div><span>http://www.amazon.com/XOXO-Womens-XO3042-Black-Leather/dp/B002PY7NS6</span></p></p></div></div> </div> <div class='span4 providers'> <a href="308.html">youtube rapid city sd mariahs drunk</a> <br> <a href="328.html">youtube. videos mujeres con animales gratis</a> <br> <a href="407.html">zendaya coleman nude pics gag reports</a> <br> </div> </div> <div class="control-group text optional"><label class="text optional control-label" for="comment_content">Content</label><div class="controls"><textarea class="text optional" cols="40" id="comment_content" name="comment[content]" rows="20" style="width:320px;height:80px"> </textarea></div></div> </div> <div class='form-actions'> <input class='btn cancel' href="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/#" style="display:none;" type='button' value='Cancel'> <input class="btn btn btn-primary" data-disable-with="Adding..." name="commit" type="submit" value="Add Comment"/> <br style="clear:both;"> </div> </form> </div> <div class='row-fluid'> <div class='span12'> <div class='comment' data-content='<EMAIL>' id='comment_403462' itemid='403462' itemprop='comment' itemscope itemtype='http://schema.org/UserComments'> <div class='comment_meta'> <div class='row-fluid'> <div class='span2'> <img alt="Avatar" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/missing/thumb/xavatar.png.pagespeed.ic.qjczMghcsC.jpg" style="float:left;margin-right:10px;" src="oiplitreendatwyv.gif"/> </div> <div class='span10'> <a href="265.html">youtube camtados en video fajando</a> <div class='author' itemprop='creator'>medo</div> <div class='created_at'><time datetime="2012-11-09T02:10:23-05:00" itemprop="commentTime"><p><a href="http://www.globalphotos.org/calgary-tower.htm" target="new">Buy Xoxo Watches, Bremont Watches Price &amp; Watches At ...</a><div>From prescribing under costume his african feet tea a Buy Xoxo Watches great . instructions he using felt tadalafill the direct ground shipped become actors soft .</div><span>http://www.globalphotos.org/calgary-tower.htm</span></p></time></div> </div> </div> </div> <div class='alert alert-message error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='comment_body'> <div class='content'> <p itemprop='commentText'><EMAIL></p> </div> </div> <div class='form-actions'> </div> <div class='reply_holder'> </div> </div> </div> </div> </div> </div> </div> <div class='span4' id='sidebar' itemscope itemtype='http://schema.org/WPSideBar'> <div id='sidebar_rectangle' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="191.html">yisela avendano nude</a></h4> <div class='clearfix' itemscope itemtype='http://schema.org/Person'> <a href="30.html" itemprop="image"><img alt="<NAME>" class="pull-left" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-nude.jpg.pagespeed.ic.Yp5z6xqFnh.jpg" style="margin-right:10px;" src="itridyotwiboocay.gif"/></a><p><a href="http://kathrynvercillo.hubpages.com/hub/Guide-to-Buying-a-Rose-Gold-Watch" target="new">Watches: Guide to Buying a Rose Gold Watch</a><div>Oct 30, 2012 . Bling Jewelry Geneva Rose Gold Plated Classic Round CZ Ladies Watch. Amazon Price: $10.45. List Price: $64.99. XOXO Women&#39;s XO5386 .</div><span>http://kathrynvercillo.hubpages.com/hub/Guide-to-Buying-a-Rose-Gold-Watch</span></p><dl> <dt>Born</dt> <dd itemprop='birthDate'><time datetime="1971-09-08T00:00:00+00:00">September 08, 1971</time></dd> <dt>Full Name</dt> <dd itemprop='name'>xoxo watch instructions Burke</dd> </dl> </div> </div> <div class='widget'> <h4><a href="5.html">www. vajinas mojadas.com famosas.com</a></h4> <ul class='nav'> <li> <a href="300.html" class="clearfix"><img alt="Brooke Burke Prepares For Cancer Surgery" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" style="margin:0 10px 0 0;float:left;" src="yohtepeeqy.gif"/> xoxo watch instructions Burke Prepares For Cancer Surgery </a></li> <li> <a href="87.html" class="clearfix"><img alt="Brooke Burke Has Thyroid Cancer" class="span3" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/thumb/brooke-burke-charvet-cancer-me.jpg" style="margin:0 10px 0 0;float:left;" src="gawyasuv.gif"/> xoxo watch instructions Burke Has Thyroid Cancer </a></li> <li> <a href="85.html" class="clearfix"><img alt="Brooke Burke Charvet Releases New Lingerie Line" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" style="margin:0 10px 0 0;float:left;" src="kourtoujendoaple.gif"/> xoxo watch instructions Burke Charvet Releases New Lingerie Line </a></li> </ul> </div> <div id='skyscraper' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="289.html">youtubejenni rivera death pics</a></h4> <ul class='thumbnails'> <li class='span4'> <a href="78.html" class="thumbnail"><img alt="Brooke Burke, Cancer Treatment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" src="utayploji.gif"/> </a></li> <li class='span4'> <a href="94.html" class="thumbnail"><img alt="Brooke Burke-Charvet Photo" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-charvet-photo.jpg.pagespeed.ic.eZcSwfCk1Z.jpg" src="treiwhoxu.gif"/> </a></li> <li class='span4'> <a href="357.html" class="thumbnail"><img alt="Brooke Burke Lingerie Line" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" src="wyalegualaf.gif"/> </a></li> <li class='span4'> <a href="335.html" class="thumbnail"><img alt="<NAME> and David Charvet" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-and-david-charvet.jpg.pagespeed.ic.iLiOSmNBgG.jpg" src="thywayhtyoch.gif"/> </a></li> <li class='span4'> <a href="362.html" class="thumbnail"><img alt="Brooke and Tom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-and-tom.jpg.pagespeed.ic.OfTSSeJdAZ.jpg" src="yokaywhyodooliwy.gif"/> </a></li> <li class='span4'> <a href="404.html" class="thumbnail"><img alt="The Naked Mom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/the-naked-mom.jpg.pagespeed.ce.2HxOs_fRpY.jpg" src="ooxoukynuakeyfoi.gif"/> </a></li> </ul> </div> <div class='widget'> <h4>Blog Archives</h4> <ul class='nav'> <li><a href="54.html">xbox code 80151011</a></li> <li><a href="67.html">xdesi.mobi/x2/download/desi panjab fat</a></li> <li><a href="167.html">xyooj aviaries</a></li> <li><a href="171.html">yahoo server unavailable iphone 5</a></li> <li><a href="79.html">xl yacht insurance</a></li> <li><a href="223.html">youjiiz para telefonos nokia 201</a></li> <li><a href="350.html">yugo car</a></li> <li><a href="193.html">ynuproon hub</a></li> </ul> </div> </div> </div> <div id='footer' itemscope itemtype='http://schema.org/WPFooter'> <div class='remove_padding'> <div id='footer_leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> </div> <p><p><a href="http://www.amazon.com/XOXO-XO5301A-Rhinestone-Silver-Tone-Bracelet/dp/B004P0UUBK" target="new">XOXO Women&#39;s XO5301A Rhinestone Accent Silver-Tone Bracelet ...</a><div>XOXO Women&#39;s XO5301A Rhinestone Accent Silver-Tone Bracelet Watch: Watches: . You may find many from bracelet watch women shopping guide.</div><span>http://www.amazon.com/XOXO-XO5301A-Rhinestone-Silver-Tone-Bracelet/dp/B004P0UUBK</span></p></p> <p> <a href="46.html">xaxor female</a> | <a href="332.html">youtube wire valentine day charm</a> | <a href="249.html">young teen models jailbait</a> | <a href="383.html">zara basic sandal black orange nude</a> </p> <p>&copy; 2013 The Hollywood Gossip - Celebrity Gossip and Entertainment News</p> <p><a href="346.html" rel="nofollow"><img alt="Sheknows-entertainment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xsheknows-entertainment-0dfb1ed120378c4d8a98720390d31272.png.pagespeed.ic.841FJHTKbK.png" src="xerxozheethrey.gif"/></a></p> </div> </div> <img height="1" width="1" pagespeed_lazy_src="http://tags.bluekai.com/site/3113" alt="" src="rtuagoutrewhoizu.gif"/> </div> </body> </html> <file_sep><!DOCTYPE html> <html id='en' lang='en'> <head> <title>yahoo server unavailable on iphone 5</title> <link href="ssoistoineypoagh.css" media="screen" rel="stylesheet" type="text/css"/> <link href="oopeinyroon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon"/> <link href="ouzeelouhtootw.jpg" rel='apple-touch-icon' sizes='144x144'> <link href="eytreyhoisefoaht.jpg" rel='apple-touch-icon' sizes='114x114'> <link href="ndyajeyssepuatr.jpg" rel='apple-touch-icon' sizes='72x72'> <link href="eychoopyatya.jpg" rel='apple-touch-icon'> <script type='text/javascript' src='eyzeywyazuneyhi.js'></script></head> <body itemscope itemtype='http://schema.org/WebPage'> <div id='header'> <div class='social visible-desktop'> <ul> <li class='twitter'><a href="65.html">xcatseyesx mfc webcam whore</a></li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com' data-size='medium'></div> </li> <li class='facebook'> <div class='fb-like' data-href='http://www.facebook.com/thehollywoodgossip' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> </ul> </div> <div id='banner'> <a href="169.html"><img alt="The Hollywood Gossip" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xheader-7629f5d243c1cdc904bf535b05ff849f.jpg.pagespeed.ic.CDQOMwZhbJ.jpg" src="stawhaghoix.gif"/></a> </div> <div class='sites visible-desktop'> <a href="196.html">yogotposted</a> | <a href="269.html">youtube.com las mejores tanjitas 2012</a> | <a href="355.html">yugo pap m85pv review</a> </div> <div class='login visible-desktop'> <a href="370.html">zabrdasti choda</a> &nbsp;|&nbsp; <a href="7.html">www.walmartbenefits.com/mybenefits</a> </div> </div> <div id='wrapper'> <div class='remove_padding'> <div id='leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='navbar' itemscope itemtype='http://schema.org/WPHeader'> <div class='navbar-inner'> <div class='container-fluid'> <a href="271.html">youtube.com tangas mexicanas</a> <div class='nav-collapse'> <ul class='nav'> <li class=''><a href="283.html">youtube fat lady singing</a></li> <li class=''><a href="120.html">xxx con flacas gratis 3gp</a></li> <li class=''><a href="325.html">youtube videos calientes de mexicanas</a></li> <li class=''><a href="24.html">www.xxxnepalifucking flm.com</a></li> <li class=''><a href="237.html">young latina jailbait pics</a></li> <li class=''><a href="112.html">xxx 3 gp de aguelas con sus ñetos</a></li> <li class=''><a href="215.html">yougotposted making flames</a></li> <li class=''><a href="357.html">yugo zastava factory m92 parts kit</a></li> <li class='login hidden-desktop'><a href="181.html">yaqui guerrido en tangas</a></li> <li class='login hidden-desktop'><a href="282.html">youtube fake nudes lee newton</a></li> </ul> <form action="http://www.thehollywoodgossip.com/search" class='navbar-form pull-right'> <input class="input-medium" id="q" name="q" placeholder="Search" type="search"/> <button class="btn" type="submit"></button> </form> </div> </div> </div> </div> </div> <div class='container-fluid'> <div class='row-fluid'> <div class='span8' id='content'> <ul class="breadcrumb" itemprop="breadcrumb"><li><a href="41.html">xarelto and medicare</a> /</li> <li><a href="12.html">www.wap,trick.phuddi photo.com</a> /</li> <li><a href="336.html">youvebeenposted naked pictures annonymous</a> /</li> <li><p><a href="http://www.justanswer.com/computer/78e5w-yahoosmtp-server-iphone-down.html" target="new">my yahoosmtp server from my iphone 5 has been down for the ...</a><div>Oct 13, 2012 . Question - my yahoosmtp server from my iphone 5 has been down for the. Find the answer . it says yahoo server is unavailable. Nalosin : ok.</div><span>http://www.justanswer.com/computer/78e5w-yahoosmtp-server-iphone-down.html</span></p></li></ul> <div class='video' itemscope itemtype='http://schema.org/VideoObject'> <div class='page-header'> <h1><p><a href="http://www.isitdownrightnow.com/mail.yahoo.com.html" target="new">Mail.yahoo.com - Is Yahoo Mail Down Right Now?</a><div>We have tried pinging Yahoo Mail website using our server and the website returned . <NAME> &middot; 1 day 22 hours 5 mins ago . I am trying to add my yahoo account on my iphone and ipad but it keeps saying yahoo server unavailable!</div><span>http://www.isitdownrightnow.com/mail.yahoo.com.html</span></p></h1> </div> <ul id='sharebar'> <li> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='box_count' data-send='false' data-show-faces='false' data-width='60'></div> </li> <li class='pinit'><a href="141.html" class="pin-it-button" count-layout="vertical" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="sterroizheizerth.gif"/></a></li> <li> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='tall'></div> </li> <li> <a href="243.html">young nude jail bait girls models</a> </li> <li class='comments'> <div class='count comment_count'>1</div> <a href="41.html">xarelto and medicare</a> </li> </ul> <div class='sharebarx' style="display:none;"> <ul> <li class='facebook'> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='medium'></div> </li> <li class='twitter'> <a href="100.html">xvideos de zoofilia mobi</a> </li> <li class='pinterest'><a href="24.html" class="pin-it-button" count-layout="horizontal" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="eevuassyaqundee.gif"/></a></li> <li class='comments'> <a href="18.html">www.www.ucard.chase.com</a> 1 </li> </ul> </div> <div class='thumbnail'> <div style="max-width:640px;max-height:459px;margin:0 auto;"> <img src="http://i2.ytimg.com/vi/yWVWEwm5wTc/1.jpg" width="640" height="459" /> </div> <div class='caption' itemprop='description'><p><a href="http://forums.macrumors.com/showthread.php?t=1450622" target="new">Yahoo mail will not verify on iPhone 5 help - MacRumors Forums</a><div>Hi all did a restore from my old iPhone 4S iOS 5 device and I can not get the . just says yahoo server unavailable try again later. but on my old .</div><span>http://forums.macrumors.com/showthread.php?t=1450622</span></p></div> <div class='rating-form' id='rating_7611' itemprop='aggregateRating' itemscope itemtype='http://schema.org/AggregateRating'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='inline-rating'><ul class="star-rating"><li class="current-rating" style="width:100%;">5.0 / 5.0</li><li><a href="index.html">home</a></li> <li><a href="53.html">xbox bras for sale</a></li> <li><a href="122.html">xxx cum gaggers</a></li> <li><a href="21.html">www.xxx.bahbi.hot.chudai.sex.stori.loud.net.com.</a></li> <li><a href="101.html">xvideos draya</a></li></ul></div> <br><p><a href="http://www.opsactive.com/apple-activation-server-unavailable-in-ios/" target="new">Apple Activation Server unavailable in IOS 6 | Optimum Performance ...</a><div>Sep 19, 2012 . Your iPhone could not be activated because the activation server is . 5 Responses to &#147;Apple Activation Server unavailable in IOS 6&#148;. Milot on .</div><span>http://www.opsactive.com/apple-activation-server-unavailable-in-ios/</span></p></div> </div> <br> <ul class='pager'> <li class='next'> <a href="403.html">zebra lane calendars</a> </li> </ul> Related Videos: <ul class='thumbnails'> <li class='span4'> <a href="99.html" class="thumbnail"><img alt="Brooke Burke Interview" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/medium_l/brooke-burke-interview.jpg" src="yssusarternotr.gif"/> <div class='caption'>yahoo server unavailable on iphone 5 Burke Interview</div> </a></li> </ul> <div class="remove_padding"><div id="content_rectangle" itemscope itemtype="http://schema.org/WPAdBlock"> </div></div> Embed Code: <pre class='embed'><p><a href="http://www.iphonefaq.org/archives/97645" target="new">Can I sync my Yahoo calendar with my iPhone? | The iPhone FAQ</a><div>Dec 29, 2012 . Into the &quot;Server&quot; field type &quot;yahoo&quot; (caldav.calendar.yahoo.com will . 5. Touch &quot; Next&quot; and the iPhone will verify your username and password .</div><span>http://www.iphonefaq.org/archives/97645</span></p> <p><a href="http://www.brothersoft.com/downloads/iphone-4s-yahoo-email-server-unavailable.html" target="new">Iphone 4s yahoo email server unavailable Free Download</a><div>Iphone 4s yahoo email server unavailable Free Download .</div><span>http://www.brothersoft.com/downloads/iphone-4s-yahoo-email-server-unavailable.html</span></p> <p><a href="https://discussions.apple.com/thread/4351965?start=0&amp;tstart=0" target="new">HT4810 Yahoo! server unavailable error: Apple Support Communities</a><div>Sep 25, 2012 . Just got a new Iphone5 in UK but when setting up email account for Yahoo Mail, I got this Yahoo Server unavailable error. Anyone has any idea .</div><span>https://discussions.apple.com/thread/4351965?start=0&amp;tstart=0</span></p></pre> <dl class='dl-horizontal'> <dt>Star:</dt> <dd> <a href="335.html">you tuve mujeres cojiendo con perros gran dames</a> </dd> <dt>Related Videos:</dt> <dd><a href="247.html">youngstown mafia history</a></dd> <dt>Original Post:</dt> <dd itemprop='associatedArticle'><a href="8.html">www.walmart mybenefits</a></dd> <dt>Uploaded by:</dt> <dd><a href="412.html">zeta phi beta chants every beat</a></dd> <dt>Uploaded:</dt> <dd><time datetime="2012-11-08T00:00:00+00:00" itemprop="uploadDate">November 08, 2012</time></dd> <dt>Duration:</dt> <dd> <time datetime='PT3M9S' itemprop='duration'>189 seconds</time> </dd> </dl> <hr> <div id='comments'> <h3> Comments (1 Total) <a href="61.html">xbox live error code 80151011</a> </h3> <a href="316.html">you tube strugis booty 2012</a> <div id='new_comment'> <form accept-charset="UTF-8" action="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/comments/" class="simple_form form-horizontal" data-remote="true" id="new_comment" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;"/><input name="authenticity_token" type="hidden" value="dnWqi+nJgFJVOg7dUXsDnt4HFjnto5JBhChkS9z5RQ8="/></div> <div class='body'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <input name='page' type='hidden'> <input id="comment_parent_id" name="comment[parent_id]" type="hidden"/> <br> <p><p><a href="http://forums.imore.com/iphone-5/242731-outgoing-e-mail-issues-w-iphone-5-a.html" target="new">Outgoing e-mail issues w/iphone 5 - iPhone, iPad, iPod Forums at ...</a><div>Oct 18, 2012 . When I try to reply to or forward an e-mail in my iphone&#39;s e-mail app, I get the . it might be something on the yahoo server that isn&#39;t connecting.</div><span>http://forums.imore.com/iphone-5/242731-outgoing-e-mail-issues-w-iphone-5-a.html</span></p></p> <div class='row-fluid'> <div class='span8'> <div class="control-group string optional"><label class="string optional control-label" for="comment_anon_name">Name</label><div class="controls"><input class="string optional" id="comment_anon_name" name="comment[anon_name]" size="50" type="text"/><p class="help-block">Your name will appear with your comment</p></div></div> <div class="control-group email optional"><label class="email optional control-label" for="comment_anon_email">Email</label><div class="controls"><input class="string email optional" id="comment_anon_email" name="comment[anon_email]" size="50" type="email"/><p class="help-block"><p><a href="http://www.youtube.com/watch?v=yWVWEwm5wTc" target="new">iPhone 5: Yahoo Mail Fix for server problems - YouTube</a><div>Sep 22, 2012 . iPhone 5: Yahoo Mail Fix for server problems . User name: (what comes BEFORE &#39;@yahoo.com&#39;) . This feature is not available right now.</div><span>http://www.youtube.com/watch?v=yWVWEwm5wTc</span></p></p></div></div> </div> <div class='span4 providers'> <a href="409.html">zendaya follando xxx</a> <br> <a href="390.html">zastava m85pv 223 5.56 hg3088-n ak-47</a> <br> <a href="59.html">xbox live codes</a> <br> </div> </div> <div class="control-group text optional"><label class="text optional control-label" for="comment_content">Content</label><div class="controls"><textarea class="text optional" cols="40" id="comment_content" name="comment[content]" rows="20" style="width:320px;height:80px"> </textarea></div></div> </div> <div class='form-actions'> <input class='btn cancel' href="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/#" style="display:none;" type='button' value='Cancel'> <input class="btn btn btn-primary" data-disable-with="Adding..." name="commit" type="submit" value="Add Comment"/> <br style="clear:both;"> </div> </form> </div> <div class='row-fluid'> <div class='span12'> <div class='comment' data-content='<EMAIL>' id='comment_403462' itemid='403462' itemprop='comment' itemscope itemtype='http://schema.org/UserComments'> <div class='comment_meta'> <div class='row-fluid'> <div class='span2'> <img alt="Avatar" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/missing/thumb/xavatar.png.pagespeed.ic.qjczMghcsC.jpg" style="float:left;margin-right:10px;" src="oiplitreendatwyv.gif"/> </div> <div class='span10'> <a href="150.html">xxx pussy dilatadas</a> <div class='author' itemprop='creator'>medo</div> <div class='created_at'><time datetime="2012-11-09T02:10:23-05:00" itemprop="commentTime"><p><a href="http://help.yahoo.com/kb/index?page=content&amp;id=SLN8834&amp;locale=en_US&amp;y=PROD_MAIL_MOBILE" target="new">Error: &quot;Server Unavailable&quot; - Help - Yahoo!</a><div>Dec 13, 2012 . Error: &quot;Server Unavailable&quot; when accessing Yahoo! on iPhone, iPad, iPod Touch. ID: SLN8834. Refers to: Mobile Mail. Cause. Recent updates .</div><span>http://help.yahoo.com/kb/index?page=content&amp;id=SLN8834&amp;locale=en_US&amp;y=PROD_MAIL_MOBILE</span></p></time></div> </div> </div> </div> <div class='alert alert-message error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='comment_body'> <div class='content'> <p itemprop='commentText'><EMAIL></p> </div> </div> <div class='form-actions'> </div> <div class='reply_holder'> </div> </div> </div> </div> </div> </div> </div> <div class='span4' id='sidebar' itemscope itemtype='http://schema.org/WPSideBar'> <div id='sidebar_rectangle' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="69.html">xerex kwentong kalibugan</a></h4> <div class='clearfix' itemscope itemtype='http://schema.org/Person'> <a href="370.html" itemprop="image"><img alt="<NAME>" class="pull-left" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-nude.jpg.pagespeed.ic.Yp5z6xqFnh.jpg" style="margin-right:10px;" src="itridyotwiboocay.gif"/></a><p><a href="http://www.helpowl.com/q/Yahoo/Technical-Support/keeps-saying-server-unavailable-try-yahoo-mail-iphone/37937" target="new">Keeps Saying Server Unavailable When I Try To Get My Yahoo Mail ...</a><div>Yahoo Support Question - Keeps Saying Server Unavailable When I Try To Get My Yahoo . Question posted by kendraslack on January 21st, 2011 5:52 AM. Keeps Saying Server Unavailable When I Try To Get My Yahoo Mail On My Iphone .</div><span>http://www.helpowl.com/q/Yahoo/Technical-Support/keeps-saying-server-unavailable-try-yahoo-mail-iphone/37937</span></p><dl> <dt>Born</dt> <dd itemprop='birthDate'><time datetime="1971-09-08T00:00:00+00:00">September 08, 1971</time></dd> <dt>Full Name</dt> <dd itemprop='name'>yahoo server unavailable on iphone 5 Burke</dd> </dl> </div> </div> <div class='widget'> <h4><a href="129.html">xxx fun frans mensink</a></h4> <ul class='nav'> <li> <a href="182.html" class="clearfix"><img alt="Brooke Burke Prepares For Cancer Surgery" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" style="margin:0 10px 0 0;float:left;" src="yohtepeeqy.gif"/> yahoo server unavailable on iphone 5 Burke Prepares For Cancer Surgery </a></li> <li> <a href="336.html" class="clearfix"><img alt="Brooke Burke Has Thyroid Cancer" class="span3" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/thumb/brooke-burke-charvet-cancer-me.jpg" style="margin:0 10px 0 0;float:left;" src="gawyasuv.gif"/> yahoo server unavailable on iphone 5 Burke Has Thyroid Cancer </a></li> <li> <a href="59.html" class="clearfix"><img alt="Brooke Burke Charvet Releases New Lingerie Line" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" style="margin:0 10px 0 0;float:left;" src="kourtoujendoaple.gif"/> yahoo server unavailable on iphone 5 Burke Charvet Releases New Lingerie Line </a></li> </ul> </div> <div id='skyscraper' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="359.html">yummychan.info candydoll</a></h4> <ul class='thumbnails'> <li class='span4'> <a href="16.html" class="thumbnail"><img alt="Brooke Burke, Cancer Treatment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" src="utayploji.gif"/> </a></li> <li class='span4'> <a href="417.html" class="thumbnail"><img alt="Brooke Burke-Charvet Photo" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-charvet-photo.jpg.pagespeed.ic.eZcSwfCk1Z.jpg" src="treiwhoxu.gif"/> </a></li> <li class='span4'> <a href="417.html" class="thumbnail"><img alt="Brooke Burke Lingerie Line" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" src="wyalegualaf.gif"/> </a></li> <li class='span4'> <a href="130.html" class="thumbnail"><img alt="<NAME> and <NAME>" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-and-david-charvet.jpg.pagespeed.ic.iLiOSmNBgG.jpg" src="thywayhtyoch.gif"/> </a></li> <li class='span4'> <a href="271.html" class="thumbnail"><img alt="<NAME> Tom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-and-tom.jpg.pagespeed.ic.OfTSSeJdAZ.jpg" src="yokaywhyodooliwy.gif"/> </a></li> <li class='span4'> <a href="319.html" class="thumbnail"><img alt="The Naked Mom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/the-naked-mom.jpg.pagespeed.ce.2HxOs_fRpY.jpg" src="ooxoukynuakeyfoi.gif"/> </a></li> </ul> </div> <div class='widget'> <h4>Blog Archives</h4> <ul class='nav'> <li><a href="304.html">you tube pauleen luna</a></li> <li><a href="91.html">xoskeleton watch for sale craigslist</a></li> <li><a href="178.html">yaqui gerrido naked</a></li> <li><a href="353.html">yugo pap m85pv pistol</a></li> <li><a href="19.html">www. x hindi antarvasna kahani video</a></li> <li><a href="63.html">xbox redeem a code glitch</a></li> <li><a href="112.html">xxx 3 gp de aguelas con sus ñetos</a></li> <li><a href="348.html">yugioh gx jaden and jesse sex</a></li> </ul> </div> </div> </div> <div id='footer' itemscope itemtype='http://schema.org/WPFooter'> <div class='remove_padding'> <div id='footer_leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> </div> <p><p><a href="http://www.everythingicafe.com/forum/threads/no-email-on-iphone-5.99464/" target="new">No email on iPhone 5 | iPhone and iPad Forums at everythingiCafe</a><div>So got my new iPhone the girl at the Apple store that helped me said I . The error message i get says Yahoo server unavailable (which i have .</div><span>http://www.everythingicafe.com/forum/threads/no-email-on-iphone-5.99464/</span></p></p> <p> <a href="256.html">your dog been neutered by rickey smiley</a> | <a href="91.html">xoskeleton watch for sale craigslist</a> | <a href="417.html">zillow rentals in tampa</a> | <a href="20.html">www. x hindi ant<NAME></a> </p> <p>&copy; 2013 The Hollywood Gossip - Celebrity Gossip and Entertainment News</p> <p><a href="248.html" rel="nofollow"><img alt="Sheknows-entertainment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xsheknows-entertainment-0dfb1ed120378c4d8a98720390d31272.png.pagespeed.ic.841FJHTKbK.png" src="xerxozheethrey.gif"/></a></p> </div> </div> <img height="1" width="1" pagespeed_lazy_src="http://tags.bluekai.com/site/3113" alt="" src="rtuagoutrewhoizu.gif"/> </div> </body> </html> <file_sep><!DOCTYPE html> <html id='en' lang='en'> <head> <title>xxx images of nangi girl</title> <link href="ssoistoineypoagh.css" media="screen" rel="stylesheet" type="text/css"/> <link href="oopeinyroon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon"/> <link href="ouzeelouhtootw.jpg" rel='apple-touch-icon' sizes='144x144'> <link href="eytreyhoisefoaht.jpg" rel='apple-touch-icon' sizes='114x114'> <link href="ndyajeyssepuatr.jpg" rel='apple-touch-icon' sizes='72x72'> <link href="eychoopyatya.jpg" rel='apple-touch-icon'> <script type='text/javascript' src='eyzeywyazuneyhi.js'></script></head> <body itemscope itemtype='http://schema.org/WebPage'> <div id='header'> <div class='social visible-desktop'> <ul> <li class='twitter'><a href="66.html">xdesi.mobi.bihara.actress</a></li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com' data-size='medium'></div> </li> <li class='facebook'> <div class='fb-like' data-href='http://www.facebook.com/thehollywoodgossip' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> </ul> </div> <div id='banner'> <a href="348.html"><img alt="The Hollywood Gossip" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xheader-7629f5d243c1cdc904bf535b05ff849f.jpg.pagespeed.ic.CDQOMwZhbJ.jpg" src="stawhaghoix.gif"/></a> </div> <div class='sites visible-desktop'> <a href="259.html">you tube antarvasna dot com</a> | <a href="102.html">xvideos jovencitas 18 años para movil descarga gratis</a> | <a href="77.html">xlola vika forum</a> </div> <div class='login visible-desktop'> <a href="403.html">zebra lane calendars</a> &nbsp;|&nbsp; <a href="251.html">youporn.com/nn preteen models</a> </div> </div> <div id='wrapper'> <div class='remove_padding'> <div id='leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='navbar' itemscope itemtype='http://schema.org/WPHeader'> <div class='navbar-inner'> <div class='container-fluid'> <a href="176.html">yaki gerrido sin calsones</a> <div class='nav-collapse'> <ul class='nav'> <li class=''><a href="index.html">home</a></li> <li class=''><a href="140.html">xxx nakked animals fukking bollywood babes</a></li> <li class=''><a href="269.html">youtube.com las mejores tanjitas 2012</a></li> <li class=''><a href="229.html">young flexible tumblr</a></li> <li class=''><a href="210.html">you got posred/tiff banister</a></li> <li class=''><a href="285.html">youtube gory death pictures</a></li> <li class=''><a href="228.html">young flat chested models</a></li> <li class=''><a href="45.html">xavier quartz gold watch</a></li> <li class='login hidden-desktop'><a href="217.html">yougotposted tiffany bannister</a></li> <li class='login hidden-desktop'><a href="180.html">yaqui guerrido descuido</a></li> </ul> <form action="http://www.thehollywoodgossip.com/search" class='navbar-form pull-right'> <input class="input-medium" id="q" name="q" placeholder="Search" type="search"/> <button class="btn" type="submit"></button> </form> </div> </div> </div> </div> </div> <div class='container-fluid'> <div class='row-fluid'> <div class='span8' id='content'> <ul class="breadcrumb" itemprop="breadcrumb"><li><a href="170.html">yahoo mail server unavailable iphone 5</a> /</li> <li><a href="170.html">yahoo mail server unavailable iphone 5</a> /</li> <li><a href="207.html">you can print this blank stat sheet by doing an image google search on</a> /</li> <li><p><a href="http://fucktapes.org/search-results/299984/katrina-kaif-full-nangi-image.html" target="new">katrina kaif full nangi image porn fuck | Sex Tube</a><div>katrina kaif full nangi image porn fuck . This site has adult .</div><span>http://fucktapes.org/search-results/299984/katrina-kaif-full-nangi-image.html</span></p></li></ul> <div class='video' itemscope itemtype='http://schema.org/VideoObject'> <div class='page-header'> <h1><p><a href="http://www.oocities.org/indianspice4u/" target="new">bollywood,hot,sexy,erotic,xxx,indian,models,nangi,busty ... - OoCities</a><div>Bollywood sexy models and actress in picture gallery with bikini and saree full with nude scenes from movies beautiful nangi and full bust open in hot mood.</div><span>http://www.oocities.org/indianspice4u/</span></p></h1> </div> <ul id='sharebar'> <li> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='box_count' data-send='false' data-show-faces='false' data-width='60'></div> </li> <li class='pinit'><a href="352.html" class="pin-it-button" count-layout="vertical" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="sterroizheizerth.gif"/></a></li> <li> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='tall'></div> </li> <li> <a href="194.html">yoga fitness women with camaltoe xxx</a> </li> <li class='comments'> <div class='count comment_count'>1</div> <a href="212.html">yougotposted asian</a> </li> </ul> <div class='sharebarx' style="display:none;"> <ul> <li class='facebook'> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='medium'></div> </li> <li class='twitter'> <a href="56.html">xbox error code 80151011</a> </li> <li class='pinterest'><a href="66.html" class="pin-it-button" count-layout="horizontal" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="eevuassyaqundee.gif"/></a></li> <li class='comments'> <a href="236.html">young jodie sweetin naked pics</a> 1 </li> </ul> </div> <div class='thumbnail'> <div style="max-width:640px;max-height:459px;margin:0 auto;"> <img src="http://1.bp.blogspot.com/-1Fg8C-rjqsE/T3trJQn6wQI/AAAAAAAAD2w/GjkOvY31HBs/s45/k013.jpg" width="640" height="459" /> </div> <div class='caption' itemprop='description'><p><a href="http://photos56789.blogspot.com/2012/05/indian-girl-in-saree-showing-her-boobs.html" target="new">XXX Pics Nude Sex: Indian Girl in Saree showing her boobs and ...</a><div>XXX Fucking Images Of Girls: X rated: UPDATED DAILY. . Aunty nangi on beach . The best collection of hot and nude indian aunties images @ Nude Indian .</div><span>http://photos56789.blogspot.com/2012/05/indian-girl-in-saree-showing-her-boobs.html</span></p></div> <div class='rating-form' id='rating_7611' itemprop='aggregateRating' itemscope itemtype='http://schema.org/AggregateRating'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='inline-rating'><ul class="star-rating"><li class="current-rating" style="width:100%;">5.0 / 5.0</li><li><a href="84.html">xnxxanna nicole smith fucking</a></li> <li><a href="80.html">xm80 ammo</a></li> <li><a href="260.html">youtube bideos xxx de chicas birjenes</a></li> <li><a href="132.html">xxx icet's wife coco best nude naked sex pics</a></li> <li><a href="29.html">www.youtube. bajar en celular video sexo porno corto mujer con zoofila.com</a></li></ul></div> <br><p><a href="http://torrentz.eu/en/english+girl+ki+nangi+pics-q" target="new">Download english girl ki nangi pics torrent</a><div>Sponsored Links for english girl ki nangi pics. english girl ki .</div><span>http://torrentz.eu/en/english+girl+ki+nangi+pics-q</span></p></div> </div> <br> <ul class='pager'> <li class='next'> <a href="279.html">youtubedon cheto gangatar</a> </li> </ul> Related Videos: <ul class='thumbnails'> <li class='span4'> <a href="246.html" class="thumbnail"><img alt="Brooke Burke Interview" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/medium_l/brooke-burke-interview.jpg" src="yssusarternotr.gif"/> <div class='caption'>xxx images of nangi girl Burke Interview</div> </a></li> </ul> <div class="remove_padding"><div id="content_rectangle" itemscope itemtype="http://schema.org/WPAdBlock"> </div></div> Embed Code: <pre class='embed'><p><a href="http://yuppix.com/video/sexi-full-nangi-big-boobs-girls" target="new">Sexi full nangi big boobs girls</a><div>Related: sexy full nangi bigs boobs vidoes american sexy giirl nangi big boobs images xxx sexy pic of big boob girls latest sexy adlt nuds big boobs girls photos .</div><span>http://yuppix.com/video/sexi-full-nangi-big-boobs-girls</span></p> <p><a href="http://torrentz.eu/ka/katrina+kaif+ki+nangi+photo-q" target="new">Download katrina kaif ki nangi photo torrent</a><div>Sponsored Links for katrina kaif ki nangi photo. katrina kaif ki .</div><span>http://torrentz.eu/ka/katrina+kaif+ki+nangi+photo-q</span></p> <p><a href="http://torrentz.eu/de/desi+girl+bathing+nangi+photo-q" target="new">Download desi girl bathing nangi photo torrent</a><div>Sponsored Links for desi girl bathing nangi photo. desi girl .</div><span>http://torrentz.eu/de/desi+girl+bathing+nangi+photo-q</span></p></pre> <dl class='dl-horizontal'> <dt>Star:</dt> <dd> <a href="90.html">xoskeleton home office</a> </dd> <dt>Related Videos:</dt> <dd><a href="143.html">xxxnina de 12 ano</a></dd> <dt>Original Post:</dt> <dd itemprop='associatedArticle'><a href="80.html">xm80 ammo</a></dd> <dt>Uploaded by:</dt> <dd><a href="358.html">yugo zastava m92pv krink ak pistol 7.62x39</a></dd> <dt>Uploaded:</dt> <dd><time datetime="2012-11-08T00:00:00+00:00" itemprop="uploadDate">November 08, 2012</time></dd> <dt>Duration:</dt> <dd> <time datetime='PT3M9S' itemprop='duration'>189 seconds</time> </dd> </dl> <hr> <div id='comments'> <h3> Comments (1 Total) <a href="265.html">youtube camtados en video fajando</a> </h3> <a href="184.html">ya se dio a conocer la carta de jenny rivera?</a> <div id='new_comment'> <form accept-charset="UTF-8" action="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/comments/" class="simple_form form-horizontal" data-remote="true" id="new_comment" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;"/><input name="authenticity_token" type="hidden" value="dnWqi+nJgFJVOg7dUXsDnt4HFjnto5JBhChkS9z5RQ8="/></div> <div class='body'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <input name='page' type='hidden'> <input id="comment_parent_id" name="comment[parent_id]" type="hidden"/> <br> <p><p><a href="http://torrentz.eu/se/sexy+antay+ki+nangi+photo-q" target="new">Download sexy antay ki nangi photo torrent</a><div>Victorias Secret Sexy Girl Marloes Horst HQ Photo Shoot &raquo; images: 2 years7 MB 20. Playboys Sexy Wife Rachel Nicole 2011 HQ Photo Shoot &raquo; images xxx: 1 .</div><span>http://torrentz.eu/se/sexy+antay+ki+nangi+photo-q</span></p></p> <div class='row-fluid'> <div class='span8'> <div class="control-group string optional"><label class="string optional control-label" for="comment_anon_name">Name</label><div class="controls"><input class="string optional" id="comment_anon_name" name="comment[anon_name]" size="50" type="text"/><p class="help-block">Your name will appear with your comment</p></div></div> <div class="control-group email optional"><label class="email optional control-label" for="comment_anon_email">Email</label><div class="controls"><input class="string email optional" id="comment_anon_email" name="comment[anon_email]" size="50" type="email"/><p class="help-block"><p><a href="http://photos56789.blogspot.com/2012/05/mallu-aunty-boobs.html" target="new">XXX Pics Nude Sex: Mallu Aunty Boobs</a><div>XXX Fucking Images Of Girls: X rated: UPDATED DAILY......... VISIT . Indian Girl in Saree showing her boobs and nipples &middot; School girl . Aunty nangi on beach .</div><span>http://photos56789.blogspot.com/2012/05/mallu-aunty-boobs.html</span></p></p></div></div> </div> <div class='span4 providers'> <a href="308.html">youtube rapid city sd mariahs drunk</a> <br> <a href="278.html">youtube descuido de faldas</a> <br> <a href="307.html">youtube pthc bath</a> <br> </div> </div> <div class="control-group text optional"><label class="text optional control-label" for="comment_content">Content</label><div class="controls"><textarea class="text optional" cols="40" id="comment_content" name="comment[content]" rows="20" style="width:320px;height:80px"> </textarea></div></div> </div> <div class='form-actions'> <input class='btn cancel' href="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/#" style="display:none;" type='button' value='Cancel'> <input class="btn btn btn-primary" data-disable-with="Adding..." name="commit" type="submit" value="Add Comment"/> <br style="clear:both;"> </div> </form> </div> <div class='row-fluid'> <div class='span12'> <div class='comment' data-content='<EMAIL>' id='comment_403462' itemid='403462' itemprop='comment' itemscope itemtype='http://schema.org/UserComments'> <div class='comment_meta'> <div class='row-fluid'> <div class='span2'> <img alt="Avatar" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/missing/thumb/xavatar.png.pagespeed.ic.qjczMghcsC.jpg" style="float:left;margin-right:10px;" src="oiplitreendatwyv.gif"/> </div> <div class='span10'> <a href="179.html">yaqui guerrido</a> <div class='author' itemprop='creator'>medo</div> <div class='created_at'><time datetime="2012-11-09T02:10:23-05:00" itemprop="commentTime"><p><a href="http://photos56789.blogspot.com/2012/07/aunty-nangi-on-beach.html" target="new">XXX Pics Nude Sex: Aunty nangi on beach</a><div>XXX Fucking Images Of Girls: X rated: UPDATED DAILY......... VISIT . desi aunty woman lady married boobs white bra seen transparent xxx randi pics sexy chut .</div><span>http://photos56789.blogspot.com/2012/07/aunty-nangi-on-beach.html</span></p></time></div> </div> </div> </div> <div class='alert alert-message error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='comment_body'> <div class='content'> <p itemprop='commentText'><EMAIL></p> </div> </div> <div class='form-actions'> </div> <div class='reply_holder'> </div> </div> </div> </div> </div> </div> </div> <div class='span4' id='sidebar' itemscope itemtype='http://schema.org/WPSideBar'> <div id='sidebar_rectangle' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="215.html">yougotposted making flames</a></h4> <div class='clearfix' itemscope itemtype='http://schema.org/Person'> <a href="177.html" itemprop="image"><img alt="Brooke Burke Nude" class="pull-left" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-nude.jpg.pagespeed.ic.Yp5z6xqFnh.jpg" style="margin-right:10px;" src="itridyotwiboocay.gif"/></a><p><a href="http://torrentz.eu/na/nangi+american+girl+Photo-q" target="new">Download nangi american girl Photo torrent</a><div>nangi american girl Photo Full Download: 1538 downloads at 2998 kb/s . Penny Pax All American Girl Loves Anal 2012 &raquo; xxx: 9 months689 MB 22. Tom Petty .</div><span>http://torrentz.eu/na/nangi+american+girl+Photo-q</span></p><dl> <dt>Born</dt> <dd itemprop='birthDate'><time datetime="1971-09-08T00:00:00+00:00">September 08, 1971</time></dd> <dt>Full Name</dt> <dd itemprop='name'>xxx images of nangi girl Burke</dd> </dl> </div> </div> <div class='widget'> <h4><a href="241.html">young manufacturing bull pup stock marlin 795 photo</a></h4> <ul class='nav'> <li> <a href="216.html" class="clearfix"><img alt="Brooke Burke Prepares For Cancer Surgery" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" style="margin:0 10px 0 0;float:left;" src="yohtepeeqy.gif"/> xxx images of nangi girl Burke Prepares For Cancer Surgery </a></li> <li> <a href="225.html" class="clearfix"><img alt="Brooke Burke Has Thyroid Cancer" class="span3" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/thumb/brooke-burke-charvet-cancer-me.jpg" style="margin:0 10px 0 0;float:left;" src="gawyasuv.gif"/> xxx images of nangi girl Burke Has Thyroid Cancer </a></li> <li> <a href="312.html" class="clearfix"><img alt="Brooke Burke Charvet Releases New Lingerie Line" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" style="margin:0 10px 0 0;float:left;" src="kourtoujendoaple.gif"/> xxx images of nangi girl Burke Charvet Releases New Lingerie Line </a></li> </ul> </div> <div id='skyscraper' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="285.html">youtube gory death pictures</a></h4> <ul class='thumbnails'> <li class='span4'> <a href="114.html" class="thumbnail"><img alt="Brooke Burke, Cancer Treatment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" src="utayploji.gif"/> </a></li> <li class='span4'> <a href="217.html" class="thumbnail"><img alt="Brooke Burke-Charvet Photo" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-charvet-photo.jpg.pagespeed.ic.eZcSwfCk1Z.jpg" src="treiwhoxu.gif"/> </a></li> <li class='span4'> <a href="227.html" class="thumbnail"><img alt="Brooke Burke Lingerie Line" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" src="wyalegualaf.gif"/> </a></li> <li class='span4'> <a href="109.html" class="thumbnail"><img alt="<NAME> and <NAME>" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-and-david-charvet.jpg.pagespeed.ic.iLiOSmNBgG.jpg" src="thywayhtyoch.gif"/> </a></li> <li class='span4'> <a href="171.html" class="thumbnail"><img alt="<NAME> Tom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-and-tom.jpg.pagespeed.ic.OfTSSeJdAZ.jpg" src="yokaywhyodooliwy.gif"/> </a></li> <li class='span4'> <a href="345.html" class="thumbnail"><img alt="The Naked Mom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/the-naked-mom.jpg.pagespeed.ce.2HxOs_fRpY.jpg" src="ooxoukynuakeyfoi.gif"/> </a></li> </ul> </div> <div class='widget'> <h4>Blog Archives</h4> <ul class='nav'> <li><a href="328.html">youtube. videos mujeres con animales gratis</a></li> <li><a href="99.html">xvideos . com videos porno de niñas de 12 años de españa</a></li> <li><a href="4.html">www.usps.com/insurance/postoffice.htm</a></li> <li><a href="242.html">young naked illegal preteen pics</a></li> <li><a href="256.html">your dog been neutered by rickey smiley</a></li> <li><a href="199.html">yolanda on ghetto gaggers full video</a></li> <li><a href="396.html">zastava pap m85 pv pistol, 223/5.56 magazines</a></li> <li><a href="274.html">youtube cute hair braiding styles in st.louis,mo</a></li> </ul> </div> </div> </div> <div id='footer' itemscope itemtype='http://schema.org/WPFooter'> <div class='remove_padding'> <div id='footer_leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> </div> <p><p><a href="http://torrentz.eu/bh/bhartiy+nangi+ladki+hot+photos-q" target="new">Download bhartiy nangi ladki hot photos torrent</a><div>Sponsored Links for bhartiy nangi ladki hot photos .</div><span>http://torrentz.eu/bh/bhartiy+nangi+ladki+hot+photos-q</span></p></p> <p> <a href="155.html">xxx sexo con caballo</a> | <a href="166.html">xxx wwe aj sex movie.nat</a> | <a href="87.html">xnxxgooglesex</a> | <a href="36.html">www.zoofilia video porno mujere con perro</a> </p> <p>&copy; 2013 The Hollywood Gossip - Celebrity Gossip and Entertainment News</p> <p><a href="300.html" rel="nofollow"><img alt="Sheknows-entertainment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xsheknows-entertainment-0dfb1ed120378c4d8a98720390d31272.png.pagespeed.ic.841FJHTKbK.png" src="xerxozheethrey.gif"/></a></p> </div> </div> <img height="1" width="1" pagespeed_lazy_src="http://tags.bluekai.com/site/3113" alt="" src="rtuagoutrewhoizu.gif"/> </div> </body> </html> <file_sep><!DOCTYPE html> <html id='en' lang='en'> <head> <title>yugo pap m85pv pistol</title> <link href="ssoistoineypoagh.css" media="screen" rel="stylesheet" type="text/css"/> <link href="oopeinyroon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon"/> <link href="ouzeelouhtootw.jpg" rel='apple-touch-icon' sizes='144x144'> <link href="eytreyhoisefoaht.jpg" rel='apple-touch-icon' sizes='114x114'> <link href="ndyajeyssepuatr.jpg" rel='apple-touch-icon' sizes='72x72'> <link href="eychoopyatya.jpg" rel='apple-touch-icon'> <script type='text/javascript' src='eyzeywyazuneyhi.js'></script></head> <body itemscope itemtype='http://schema.org/WebPage'> <div id='header'> <div class='social visible-desktop'> <ul> <li class='twitter'><a href="278.html">youtube descuido de faldas</a></li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com' data-size='medium'></div> </li> <li class='facebook'> <div class='fb-like' data-href='http://www.facebook.com/thehollywoodgossip' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> </ul> </div> <div id='banner'> <a href="312.html"><img alt="The Hollywood Gossip" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xheader-7629f5d243c1cdc904bf535b05ff849f.jpg.pagespeed.ic.CDQOMwZhbJ.jpg" src="stawhaghoix.gif"/></a> </div> <div class='sites visible-desktop'> <a href="index.html">home</a> | <a href="300.html">youtube nephew tommy prank calls uncut</a> | <a href="44.html">+xavier made in assembled in malaysia swiss watches black man an woman</a> </div> <div class='login visible-desktop'> <a href="404.html">zen bracelets for luck money</a> &nbsp;|&nbsp; <a href="74.html">xhamster demaripily casero</a> </div> </div> <div id='wrapper'> <div class='remove_padding'> <div id='leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='navbar' itemscope itemtype='http://schema.org/WPHeader'> <div class='navbar-inner'> <div class='container-fluid'> <a href="273.html">youtube cristina saralegui entrevistas a jenni rivera</a> <div class='nav-collapse'> <ul class='nav'> <li class=''><a href="19.html">www. x hindi antarvasna kahani video</a></li> <li class=''><a href="110.html">xxx 2012 con animales</a></li> <li class=''><a href="115.html">xxxanimalesconmujeres</a></li> <li class=''><a href="18.html">www.www.ucard.chase.com</a></li> <li class=''><a href="412.html">zeta phi beta chants every beat</a></li> <li class=''><a href="65.html">xcatseyesx mfc webcam whore</a></li> <li class=''><a href="214.html">yougotposted instagram</a></li> <li class=''><a href="212.html">yougotposted asian</a></li> <li class='login hidden-desktop'><a href="239.html">young lolita nudes</a></li> <li class='login hidden-desktop'><a href="233.html">young gymnastics slips accidental nudity tumblr</a></li> </ul> <form action="http://www.thehollywoodgossip.com/search" class='navbar-form pull-right'> <input class="input-medium" id="q" name="q" placeholder="Search" type="search"/> <button class="btn" type="submit"></button> </form> </div> </div> </div> </div> </div> <div class='container-fluid'> <div class='row-fluid'> <div class='span8' id='content'> <ul class="breadcrumb" itemprop="breadcrumb"><li><a href="49.html">xbooru tram pararam meja mi</a> /</li> <li><a href="150.html">xxx pussy dilatadas</a> /</li> <li><a href="311.html">youtube rick ross cherry bomb riding donk</a> /</li> <li><p><a href="http://www.gunsamerica.com/967809544/YUGO_ZASTAVA_PAP_M92_PV_7_62X39.htm" target="new">YUGO ZASTAVA PAP M92 PV 7.62X39 for - Guns for Sale ...</a><div>YUGO ZASTAVA PAP M92 PV 7.62X39 for sale in category Century International Arms . AK47 Zastava M85PV pistol . CAI/Zastava PAP M85PV AK-47 pistol .</div><span>http://www.gunsamerica.com/967809544/YUGO_ZASTAVA_PAP_M92_PV_7_62X39.htm</span></p></li></ul> <div class='video' itemscope itemtype='http://schema.org/VideoObject'> <div class='page-header'> <h1><p><a href="http://www.northeastshooters.com/vbulletin/archive/index.php/f-206-p-3.html" target="new">slickguns.com [Archive] - Page 3 - Northeastshooters.com</a><div>CIA Zastava PAP M92 PV AK47 Krinkov Style Pistol 7.62X39 30RD . Century HG-3088-N YUGO PAP-M85PV AK Style Pistol 5.56x45mm - $576 + $6 S/H .</div><span>http://www.northeastshooters.com/vbulletin/archive/index.php/f-206-p-3.html</span></p></h1> </div> <ul id='sharebar'> <li> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='box_count' data-send='false' data-show-faces='false' data-width='60'></div> </li> <li class='pinit'><a href="242.html" class="pin-it-button" count-layout="vertical" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="sterroizheizerth.gif"/></a></li> <li> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='tall'></div> </li> <li> <a href="335.html">you tuve mujeres cojiendo con perros gran dames</a> </li> <li class='comments'> <div class='count comment_count'>1</div> <a href="293.html">youtube knifty knitter</a> </li> </ul> <div class='sharebarx' style="display:none;"> <ul> <li class='facebook'> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='medium'></div> </li> <li class='twitter'> <a href="395.html">zastava pap 92 to buy</a> </li> <li class='pinterest'><a href="74.html" class="pin-it-button" count-layout="horizontal" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="eevuassyaqundee.gif"/></a></li> <li class='comments'> <a href="189.html">yiffy straight</a> 1 </li> </ul> </div> <div class='thumbnail'> <div style="max-width:640px;max-height:459px;margin:0 auto;"> <img src="http://sphotos-b.xx.fbcdn.net/hphotos-ash3/544850_325086450931584_1005704732_n.jpg" width="640" height="459" /> </div> <div class='caption' itemprop='description'><p><a href="http://www.slickguns.com/product/century-hg-3088-n-pap-m85pv-pistol-582-free-shipping" target="new">Century HG-3088-N YUGO PAP-M85PV AK Style Pistol 5.56x45mm ...</a><div>Sep 27, 2012 . Century Arms M85 PAP Semi-automatic 556NATO 10&quot; Steel Black Black 30Rd 1 Mag Hinged Top Cover Adjustable Sights HG3088-N .</div><span>http://www.slickguns.com/product/century-hg-3088-n-pap-m85pv-pistol-582-free-shipping</span></p></div> <div class='rating-form' id='rating_7611' itemprop='aggregateRating' itemscope itemtype='http://schema.org/AggregateRating'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='inline-rating'><ul class="star-rating"><li class="current-rating" style="width:100%;">5.0 / 5.0</li><li><a href="114.html">xxx 3gp niñas jovenes</a></li> <li><a href="155.html">xxx sexo con caballo</a></li> <li><a href="341.html">yovodude.com</a></li> <li><a href="260.html">youtube bideos xxx de chicas birjenes</a></li> <li><a href="107.html">xx raul armenteros nude</a></li></ul></div> <br><p><a href="http://www.jgsales.com/yugo-pap-m85pv-pistol,-krinkov-style-pistol,-5.56x45mm,-zastava-serbia-mfg.-new.-p-58080.html" target="new">Yugo PAP M85PV Pistol, Krinkov style pistol, 5.56x45mm, Zastava ...</a><div>Nov 14, 2012 . This is the Yugo M85PV AK PAP Pattern Pistol, Krinkov style, chambered for 5.56 x45. Has a 10.25 inch barrel and 20.25 inch overall length.</div><span>http://www.jgsales.com/yugo-pap-m85pv-pistol,-krinkov-style-pistol,-5.56x45mm,-zastava-serbia-mfg.-new.-p-58080.html</span></p></div> </div> <br> <ul class='pager'> <li class='next'> <a href="337.html">yovdud</a> </li> </ul> Related Videos: <ul class='thumbnails'> <li class='span4'> <a href="214.html" class="thumbnail"><img alt="Brooke Burke Interview" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/medium_l/brooke-burke-interview.jpg" src="yssusarternotr.gif"/> <div class='caption'>yugo pap m85pv pistol Burke Interview</div> </a></li> </ul> <div class="remove_padding"><div id="content_rectangle" itemscope itemtype="http://schema.org/WPAdBlock"> </div></div> Embed Code: <pre class='embed'><p><a href="http://www.youtube.com/watch?v=nUidnh9-GtY" target="new">M85PV Pistol &amp; M95A Rifle - YouTube</a><div>Nov 5, 2012 . Me plinking with the new M85PV pistol and my M95A rifle. . Yugo Krink M92by GunWebsites8,022 views &middot; M92 PAP (Zastava) AK47 Pistol HD .</div><span>http://www.youtube.com/watch?v=nUidnh9-GtY</span></p> <p><a href="http://www.gunsamerica.com/Search.aspx?T=zastava%20pap" target="new">Zastava PAP M70 - Guns for Sale GunsAmerica</a><div>9 Listings . AK-47 Pistol in .223(5.56 NATO) by Zastava PAP M85PV New in Box . $2,499.00, Yugo AK Zastava PAP M92 PV 7.62x39mm XYX Misc Pistols .</div><span>http://www.gunsamerica.com/Search.aspx?T=zastava%20pap</span></p> <p><a href="http://www.gunsamerica.com/Search/Category/178/2/Guns/Pistols/Century-Arms-International.htm" target="new">Century International Arms - Pistols For Sale Gun Auctions Gun ...</a><div>42 Listings . Zastava, Serbia The NEW Yugo Zastava M92PV AK pistol features a 10 1/4&#148; barrel, . This new CAI/Zastava PAP M85PV pistol fires the .223 round.</div><span>http://www.gunsamerica.com/Search/Category/178/2/Guns/Pistols/Century-Arms-International.htm</span></p></pre> <dl class='dl-horizontal'> <dt>Star:</dt> <dd> <a href="244.html">young nymphets pissing pics</a> </dd> <dt>Related Videos:</dt> <dd><a href="131.html">xxx gratis para descargar violadas</a></dd> <dt>Original Post:</dt> <dd itemprop='associatedArticle'><a href="324.html">youtube videos bailando y ensenando</a></dd> <dt>Uploaded by:</dt> <dd><a href="358.html">yugo zastava m92pv krink ak pistol 7.62x39</a></dd> <dt>Uploaded:</dt> <dd><time datetime="2012-11-08T00:00:00+00:00" itemprop="uploadDate">November 08, 2012</time></dd> <dt>Duration:</dt> <dd> <time datetime='PT3M9S' itemprop='duration'>189 seconds</time> </dd> </dl> <hr> <div id='comments'> <h3> Comments (1 Total) <a href="185.html">yegua folladas por hombres fotos</a> </h3> <a href="96.html">xvideo mayrin villanueva</a> <div id='new_comment'> <form accept-charset="UTF-8" action="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/comments/" class="simple_form form-horizontal" data-remote="true" id="new_comment" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;"/><input name="authenticity_token" type="hidden" value="dnWqi+nJgFJVOg7dUXsDnt4HFjnto5JBhChkS9z5RQ8="/></div> <div class='body'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <input name='page' type='hidden'> <input id="comment_parent_id" name="comment[parent_id]" type="hidden"/> <br> <p><p><a href="http://www.gunsamerica.com/Search/Category/181/Guns/Pistols/Century-Arms-International/Pistols.htm" target="new">Century International Arms - Guns for Sale GunsAmerica</a><div>43 Listings . Cetury arms AK 47 Pistol Zastavia PAP 5.56X45 10.25&quot;barrel HG3088N . Zastava M85PV AK Pistol 5.56X45 NEW Yugo Zastava M85PV AK pistol .</div><span>http://www.gunsamerica.com/Search/Category/181/Guns/Pistols/Century-Arms-International/Pistols.htm</span></p></p> <div class='row-fluid'> <div class='span8'> <div class="control-group string optional"><label class="string optional control-label" for="comment_anon_name">Name</label><div class="controls"><input class="string optional" id="comment_anon_name" name="comment[anon_name]" size="50" type="text"/><p class="help-block">Your name will appear with your comment</p></div></div> <div class="control-group email optional"><label class="email optional control-label" for="comment_anon_email">Email</label><div class="controls"><input class="string email optional" id="comment_anon_email" name="comment[anon_email]" size="50" type="email"/><p class="help-block"><p><a href="http://www.armslist.com/classifieds/lima-ohio" target="new">ARMSLIST - Lima Gun Classifieds</a><div>Dec 17, 2012 . FS: NIB Yugo M85PV PAP AK Pistol UNFIRED in box 5.56mm/223 Krinkov. $775. Brandy new in box...trigger tag still attached. T... Lima .</div><span>http://www.armslist.com/classifieds/lima-ohio</span></p></p></div></div> </div> <div class='span4 providers'> <a href="321.html">you tube ver fotos de mariana seoane</a> <br> <a href="239.html">young lolita nudes</a> <br> <a href="37.html">www.zurichna.com/nydbl to:</a> <br> </div> </div> <div class="control-group text optional"><label class="text optional control-label" for="comment_content">Content</label><div class="controls"><textarea class="text optional" cols="40" id="comment_content" name="comment[content]" rows="20" style="width:320px;height:80px"> </textarea></div></div> </div> <div class='form-actions'> <input class='btn cancel' href="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/#" style="display:none;" type='button' value='Cancel'> <input class="btn btn btn-primary" data-disable-with="Adding..." name="commit" type="submit" value="Add Comment"/> <br style="clear:both;"> </div> </form> </div> <div class='row-fluid'> <div class='span12'> <div class='comment' data-content='<EMAIL>' id='comment_403462' itemid='403462' itemprop='comment' itemscope itemtype='http://schema.org/UserComments'> <div class='comment_meta'> <div class='row-fluid'> <div class='span2'> <img alt="Avatar" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/missing/thumb/xavatar.png.pagespeed.ic.qjczMghcsC.jpg" style="float:left;margin-right:10px;" src="oiplitreendatwyv.gif"/> </div> <div class='span10'> <a href="245.html">young picture of alpo drug dealer</a> <div class='author' itemprop='creator'>medo</div> <div class='created_at'><time datetime="2012-11-09T02:10:23-05:00" itemprop="commentTime"><p><a href="http://www.gunsnet.net/showthread.php?19965-Yugo-PAP-M85PV-Pistol-5-56-Model" target="new">Yugo PAP M85PV Pistol 5.56 Model</a><div>I do like their design, they seem to have thought of everything in how to maintain it. You notice how much more quiet the M16 was with it vs. the .</div><span>http://www.gunsnet.net/showthread.php?19965-Yugo-PAP-M85PV-Pistol-5-56-Model</span></p></time></div> </div> </div> </div> <div class='alert alert-message error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='comment_body'> <div class='content'> <p itemprop='commentText'><EMAIL></p> </div> </div> <div class='form-actions'> </div> <div class='reply_holder'> </div> </div> </div> </div> </div> </div> </div> <div class='span4' id='sidebar' itemscope itemtype='http://schema.org/WPSideBar'> <div id='sidebar_rectangle' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="171.html">yahoo server unavailable iphone 5</a></h4> <div class='clearfix' itemscope itemtype='http://schema.org/Person'> <a href="317.html" itemprop="image"><img alt="<NAME>" class="pull-left" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-nude.jpg.pagespeed.ic.Yp5z6xqFnh.jpg" style="margin-right:10px;" src="itridyotwiboocay.gif"/></a><p><a href="http://www.gunsamerica.com/Search/Category/181/2/Guns/Pistols/Century-Arms-International/Pistols.htm" target="new">Century International Arms - Guns for Sale GunsAmerica</a><div>42 Listings . Zastava, Serbia The NEW Yugo Zastava M92PV AK pistol features a 10 1/4&#148; barrel, . This new CAI/Zastava PAP M85PV pistol fires the .223 round.</div><span>http://www.gunsamerica.com/Search/Category/181/2/Guns/Pistols/Century-Arms-International/Pistols.htm</span></p><dl> <dt>Born</dt> <dd itemprop='birthDate'><time datetime="1971-09-08T00:00:00+00:00">September 08, 1971</time></dd> <dt>Full Name</dt> <dd itemprop='name'>yugo pap m85pv pistol Burke</dd> </dl> </div> </div> <div class='widget'> <h4><a href="287.html">youtube jennifer lopez porno completo</a></h4> <ul class='nav'> <li> <a href="149.html" class="clearfix"><img alt="Brooke Burke Prepares For Cancer Surgery" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" style="margin:0 10px 0 0;float:left;" src="yohtepeeqy.gif"/> yugo pap m85pv pistol Burke Prepares For Cancer Surgery </a></li> <li> <a href="77.html" class="clearfix"><img alt="Brooke Burke Has Thyroid Cancer" class="span3" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/thumb/brooke-burke-charvet-cancer-me.jpg" style="margin:0 10px 0 0;float:left;" src="gawyasuv.gif"/> yugo pap m85pv pistol Burke Has Thyroid Cancer </a></li> <li> <a href="293.html" class="clearfix"><img alt="Brooke Burke Charvet Releases New Lingerie Line" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" style="margin:0 10px 0 0;float:left;" src="kourtoujendoaple.gif"/> yugo pap m85pv pistol Burke Charvet Releases New Lingerie Line </a></li> </ul> </div> <div id='skyscraper' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="12.html">www.wap,trick.phuddi photo.com</a></h4> <ul class='thumbnails'> <li class='span4'> <a href="240.html" class="thumbnail"><img alt="Brooke Burke, Cancer Treatment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" src="utayploji.gif"/> </a></li> <li class='span4'> <a href="245.html" class="thumbnail"><img alt="Brooke Burke-Charvet Photo" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-charvet-photo.jpg.pagespeed.ic.eZcSwfCk1Z.jpg" src="treiwhoxu.gif"/> </a></li> <li class='span4'> <a href="174.html" class="thumbnail"><img alt="Brooke Burke Lingerie Line" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" src="wyalegualaf.gif"/> </a></li> <li class='span4'> <a href="292.html" class="thumbnail"><img alt="<NAME> and <NAME>" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-and-david-charvet.jpg.pagespeed.ic.iLiOSmNBgG.jpg" src="thywayhtyoch.gif"/> </a></li> <li class='span4'> <a href="223.html" class="thumbnail"><img alt="<NAME> Tom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-and-tom.jpg.pagespeed.ic.OfTSSeJdAZ.jpg" src="yokaywhyodooliwy.gif"/> </a></li> <li class='span4'> <a href="385.html" class="thumbnail"><img alt="The Naked Mom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/the-naked-mom.jpg.pagespeed.ce.2HxOs_fRpY.jpg" src="ooxoukynuakeyfoi.gif"/> </a></li> </ul> </div> <div class='widget'> <h4>Blog Archives</h4> <ul class='nav'> <li><a href="93.html">xtube.com pinoy gwapo</a></li> <li><a href="249.html">young teen models jailbait</a></li> <li><a href="192.html">yisela avendano sexo</a></li> <li><a href="207.html">you can print this blank stat sheet by doing an image google search on</a></li> <li><a href="342.html">yovodudefakes.com</a></li> <li><a href="382.html">zara apply online</a></li> <li><a href="261.html">you tube bondage</a></li> <li><a href="79.html">xl yacht insurance</a></li> </ul> </div> </div> </div> <div id='footer' itemscope itemtype='http://schema.org/WPFooter'> <div class='remove_padding'> <div id='footer_leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> </div> <p><p><a href="http://www.ar15.com/forums/t_4_98/145696_Yugo_PAP_M85PV_Pistol_In_5_45_.html" target="new">Yugo PAP M85PV Pistol In 5.45? - AR15.COM</a><div>Yugo PAP M85PV Pistol In 5.45? . I&#39;m afraid there&#39;s no Yugo in 5.45x39 . Also, 5.45 mag is straighter than 7.62x39- which is on the PAP in .</div><span>http://www.ar15.com/forums/t_4_98/145696_Yugo_PAP_M85PV_Pistol_In_5_45_.html</span></p></p> <p> <a href="363.html">yurts canada</a> | <a href="66.html">xdesi.mobi.bihara.actress</a> | <a href="315.html">youtube stars nude fake</a> | <a href="253.html">youporn mexicanas descarga gratis</a> </p> <p>&copy; 2013 The Hollywood Gossip - Celebrity Gossip and Entertainment News</p> <p><a href="420.html" rel="nofollow"><img alt="Sheknows-entertainment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xsheknows-entertainment-0dfb1ed120378c4d8a98720390d31272.png.pagespeed.ic.841FJHTKbK.png" src="xerxozheethrey.gif"/></a></p> </div> </div> <img height="1" width="1" pagespeed_lazy_src="http://tags.bluekai.com/site/3113" alt="" src="rtuagoutrewhoizu.gif"/> </div> </body> </html> <file_sep><!DOCTYPE html> <html id='en' lang='en'> <head> <title>yovo dude</title> <link href="ssoistoineypoagh.css" media="screen" rel="stylesheet" type="text/css"/> <link href="oopeinyroon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon"/> <link href="ouzeelouhtootw.jpg" rel='apple-touch-icon' sizes='144x144'> <link href="eytreyhoisefoaht.jpg" rel='apple-touch-icon' sizes='114x114'> <link href="ndyajeyssepuatr.jpg" rel='apple-touch-icon' sizes='72x72'> <link href="eychoopyatya.jpg" rel='apple-touch-icon'> <script type='text/javascript' src='eyzeywyazuneyhi.js'></script></head> <body itemscope itemtype='http://schema.org/WebPage'> <div id='header'> <div class='social visible-desktop'> <ul> <li class='twitter'><a href="15.html">www.worldstaruncut.com</a></li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com' data-size='medium'></div> </li> <li class='facebook'> <div class='fb-like' data-href='http://www.facebook.com/thehollywoodgossip' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> </ul> </div> <div id='banner'> <a href="235.html"><img alt="The Hollywood Gossip" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xheader-7629f5d243c1cdc904bf535b05ff849f.jpg.pagespeed.ic.CDQOMwZhbJ.jpg" src="stawhaghoix.gif"/></a> </div> <div class='sites visible-desktop'> <a href="104.html">xvideos mujeres follando con perros</a> | <a href="383.html">zara basic sandal black orange nude</a> | <a href="245.html">young picture of alpo drug dealer</a> </div> <div class='login visible-desktop'> <a href="176.html">yaki gerrido sin calsones</a> &nbsp;|&nbsp; <a href="42.html">xarelto coupons medicare part d</a> </div> </div> <div id='wrapper'> <div class='remove_padding'> <div id='leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='navbar' itemscope itemtype='http://schema.org/WPHeader'> <div class='navbar-inner'> <div class='container-fluid'> <a href="index.html">home</a> <div class='nav-collapse'> <ul class='nav'> <li class=''><a href="326.html">youtube video scandle</a></li> <li class=''><a href="77.html">xlola vika forum</a></li> <li class=''><a href="5.html">www. vajinas mojadas.com famosas.com</a></li> <li class=''><a href="201.html">yorki hair cut picture en yutube</a></li> <li class=''><a href="44.html">+xavier made in assembled in malaysia swiss watches black man an woman</a></li> <li class=''><a href="176.html">yaki gerrido sin calsones</a></li> <li class=''><a href="205.html">yotubesexo.com/medias</a></li> <li class=''><a href="268.html">youtube christina blackwell under skert shots</a></li> <li class='login hidden-desktop'><a href="204.html">yotube bideos gringas mamando berga sexso porno</a></li> <li class='login hidden-desktop'><a href="280.html">youtubedtla</a></li> </ul> <form action="http://www.thehollywoodgossip.com/search" class='navbar-form pull-right'> <input class="input-medium" id="q" name="q" placeholder="Search" type="search"/> <button class="btn" type="submit"></button> </form> </div> </div> </div> </div> </div> <div class='container-fluid'> <div class='row-fluid'> <div class='span8' id='content'> <ul class="breadcrumb" itemprop="breadcrumb"><li><a href="292.html">youtube jp sauer and sohn suhl</a> /</li> <li><a href="279.html">youtubedon cheto gangatar</a> /</li> <li><a href="330.html">youtube watch v gr 017 sf214</a> /</li> <li><p><a href="http://www.happyfame.com/2011/01/justin-bieber-kissing-selena-gomez-was-not-real-aka-fake/" target="new"><NAME> was Not REAL aka FAKE ...</a><div>Jan 1, 2011 . selena gomez fakes justin bieber fake naked yovodude com fakes de selena gomez Justin bieber pics clear YOVODUDE COM SELENA .</div><span>http://www.happyfame.com/2011/01/justin-bieber-kissing-selena-gomez-was-not-real-aka-fake/</span></p></li></ul> <div class='video' itemscope itemtype='http://schema.org/VideoObject'> <div class='page-header'> <h1><p><a href="http://website.informer.com/terms/Miley_Cyrus_Yovodude_Fakes" target="new">Miley Cyrus Yovodude Fakes at Website Informer</a><div>Miley Cyrus Yovodude Fakes was used to find: ? &#149; Sevelina Girls Games &#149; ? | fashion dress up and makeover games Exclusive collection of Fashion ? dress .</div><span>http://website.informer.com/terms/Miley_Cyrus_Yovodude_Fakes</span></p></h1> </div> <ul id='sharebar'> <li> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='box_count' data-send='false' data-show-faces='false' data-width='60'></div> </li> <li class='pinit'><a href="279.html" class="pin-it-button" count-layout="vertical" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="sterroizheizerth.gif"/></a></li> <li> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='tall'></div> </li> <li> <a href="44.html">+xavier made in assembled in malaysia swiss watches black man an woman</a> </li> <li class='comments'> <div class='count comment_count'>1</div> <a href="343.html">yovodude shake it up</a> </li> </ul> <div class='sharebarx' style="display:none;"> <ul> <li class='facebook'> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='medium'></div> </li> <li class='twitter'> <a href="246.html">young smooth vagina gallareis</a> </li> <li class='pinterest'><a href="174.html" class="pin-it-button" count-layout="horizontal" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="eevuassyaqundee.gif"/></a></li> <li class='comments'> <a href="381.html">zara 666 opening</a> 1 </li> </ul> </div> <div class='thumbnail'> <div style="max-width:640px;max-height:459px;margin:0 auto;"> <img src="http://grapher.compete.com/yovodude.com_uv_460.png" width="640" height="459" /> </div> <div class='caption' itemprop='description'><p><a href="http://www.webutation.net/go/review/yovodude.com" target="new">Yovodude.com Review</a><div>Is Yovodude.com safe and reliable? Read current user-experience and reviews of yovodude.com ... The Webutation Security Check of Yovodude.com is .</div><span>http://www.webutation.net/go/review/yovodude.com</span></p></div> <div class='rating-form' id='rating_7611' itemprop='aggregateRating' itemscope itemtype='http://schema.org/AggregateRating'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='inline-rating'><ul class="star-rating"><li class="current-rating" style="width:100%;">5.0 / 5.0</li><li><a href="16.html">www. wwe divas porn nude and naked pictures.</a></li> <li><a href="169.html">yaguelin bracamonte en el porno</a></li> <li><a href="218.html">you got posted/tiff banister</a></li> <li><a href="3.html">www.usps.com/insurance/online.htm</a></li> <li><a href="91.html">xoskeleton watch for sale craigslist</a></li></ul></div> <br><p><a href="http://www.sitetrail.com/yovodude.com" target="new">yovodude.com - SiteTrail</a><div>Yovodude.com analysis, stats and news. Teen age celebrities fake nude! Selena Gomez, <NAME>, <NAME>, <NAME> &amp; many more Disney .</div><span>http://www.sitetrail.com/yovodude.com</span></p></div> </div> <br> <ul class='pager'> <li class='next'> <a href="284.html">youtube free women naked of wwe</a> </li> </ul> Related Videos: <ul class='thumbnails'> <li class='span4'> <a href="150.html" class="thumbnail"><img alt="Brooke Burke Interview" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/medium_l/brooke-burke-interview.jpg" src="yssusarternotr.gif"/> <div class='caption'>yovo dude Burke Interview</div> </a></li> </ul> <div class="remove_padding"><div id="content_rectangle" itemscope itemtype="http://schema.org/WPAdBlock"> </div></div> Embed Code: <pre class='embed'><p><a href="http://www.yovofakesblog.com/" target="new">Yovo Fakes - Nude Celebrity Fakes</a><div>Jan 2, 2013 . Yovo Fakes presents the best celebrity fakes. . The Dude well and truly gets his pole smoked by the gorgeous girl they got to play Bunny.</div><span>http://www.yovofakesblog.com/</span></p> <p><a href="http://lo8s.com/yovodude.com/" target="new">Yovodude.com Yovodude Full Analysis</a><div>Domain Name, yovodude.com [ Page Rank: 1 ]. IP address .</div><span>http://lo8s.com/yovodude.com/</span></p> <p><a href="http://website.informer.com/terms/Bella_Thorne_Yovodude_Fakes_Pics" target="new">Bella Thorne Yovodude Fakes Pics at Website Informer</a><div>Bella Thorne Yovodude Fakes Pics was used to find: yovodude.com &raquo; best of teen age celebrities fake nude best of teen age celebrities fake nude. 411 534 .</div><span>http://website.informer.com/terms/Bella_Thorne_Yovodude_Fakes_Pics</span></p></pre> <dl class='dl-horizontal'> <dt>Star:</dt> <dd> <a href="14.html">www.wonderliconlinenursing entrance exam sle</a> </dd> <dt>Related Videos:</dt> <dd><a href="214.html">yougotposted instagram</a></dd> <dt>Original Post:</dt> <dd itemprop='associatedArticle'><a href="90.html">xoskeleton home office</a></dd> <dt>Uploaded by:</dt> <dd><a href="97.html">xvideos actrices de novelas</a></dd> <dt>Uploaded:</dt> <dd><time datetime="2012-11-08T00:00:00+00:00" itemprop="uploadDate">November 08, 2012</time></dd> <dt>Duration:</dt> <dd> <time datetime='PT3M9S' itemprop='duration'>189 seconds</time> </dd> </dl> <hr> <div id='comments'> <h3> Comments (1 Total) <a href="297.html">youtube mujeres mejicanas cojiendo</a> </h3> <a href="254.html">youporn videos porno con vaginas peludas y mojadas</a> <div id='new_comment'> <form accept-charset="UTF-8" action="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/comments/" class="simple_form form-horizontal" data-remote="true" id="new_comment" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;"/><input name="authenticity_token" type="hidden" value="dnWqi+nJgFJVOg7dUXsDnt4HFjnto5JBhChkS9z5RQ8="/></div> <div class='body'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <input name='page' type='hidden'> <input id="comment_parent_id" name="comment[parent_id]" type="hidden"/> <br> <p><p><a href="http://gd-analytics.com/www.yovodude.com" target="new">www.yovodude.com</a><div>Site analysis for www.yovodude.com. . yovodude.com ?? best of teen age celebrities fake nude. Description: best of teen age celebrities fake nude. Keywords: .</div><span>http://gd-analytics.com/www.yovodude.com</span></p></p> <div class='row-fluid'> <div class='span8'> <div class="control-group string optional"><label class="string optional control-label" for="comment_anon_name">Name</label><div class="controls"><input class="string optional" id="comment_anon_name" name="comment[anon_name]" size="50" type="text"/><p class="help-block">Your name will appear with your comment</p></div></div> <div class="control-group email optional"><label class="email optional control-label" for="comment_anon_email">Email</label><div class="controls"><input class="string email optional" id="comment_anon_email" name="comment[anon_email]" size="50" type="email"/><p class="help-block"><p><a href="http://website.informer.com/terms/Jennette_Mccurdy_Yovodude" target="new">Jennette Mccurdy Yovodude at Website Informer</a><div>yovodude.com &raquo; best of teen age celebrities fake nude best of teen age celebrities fake nude . Additional websites, related to Jennette Mccurdy Yovodude: .</div><span>http://website.informer.com/terms/Jennette_Mccurdy_Yovodude</span></p></p></div></div> </div> <div class='span4 providers'> <a href="103.html">x videos mexicanas gratis para celular</a> <br> <a href="403.html">zebra lane calendars</a> <br> <a href="188.html">yiff dominant female</a> <br> </div> </div> <div class="control-group text optional"><label class="text optional control-label" for="comment_content">Content</label><div class="controls"><textarea class="text optional" cols="40" id="comment_content" name="comment[content]" rows="20" style="width:320px;height:80px"> </textarea></div></div> </div> <div class='form-actions'> <input class='btn cancel' href="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/#" style="display:none;" type='button' value='Cancel'> <input class="btn btn btn-primary" data-disable-with="Adding..." name="commit" type="submit" value="Add Comment"/> <br style="clear:both;"> </div> </form> </div> <div class='row-fluid'> <div class='span12'> <div class='comment' data-content='<EMAIL>' id='comment_403462' itemid='403462' itemprop='comment' itemscope itemtype='http://schema.org/UserComments'> <div class='comment_meta'> <div class='row-fluid'> <div class='span2'> <img alt="Avatar" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/missing/thumb/xavatar.png.pagespeed.ic.qjczMghcsC.jpg" style="float:left;margin-right:10px;" src="oiplitreendatwyv.gif"/> </div> <div class='span10'> <a href="60.html">xbox live error 80151011</a> <div class='author' itemprop='creator'>medo</div> <div class='created_at'><time datetime="2012-11-09T02:10:23-05:00" itemprop="commentTime"><p><a href="http://wiki.answers.com/Q/Does_kelsey_chow_have_fake_porn_except_yovodude" target="new">Does kelsey chow have fake porn except yovodude</a><div>Does kelsey chow have fake porn except yovodude? In: Uncategorized [Edit categories]. Answer: Yes. Improve answer. First answer by Contributor . Last edit by .</div><span>http://wiki.answers.com/Q/Does_kelsey_chow_have_fake_porn_except_yovodude</span></p></time></div> </div> </div> </div> <div class='alert alert-message error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='comment_body'> <div class='content'> <p itemprop='commentText'><EMAIL></p> </div> </div> <div class='form-actions'> </div> <div class='reply_holder'> </div> </div> </div> </div> </div> </div> </div> <div class='span4' id='sidebar' itemscope itemtype='http://schema.org/WPSideBar'> <div id='sidebar_rectangle' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="114.html">xxx 3gp niñas jovenes</a></h4> <div class='clearfix' itemscope itemtype='http://schema.org/Person'> <a href="197.html" itemprop="image"><img alt="<NAME>" class="pull-left" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-nude.jpg.pagespeed.ic.Yp5z6xqFnh.jpg" style="margin-right:10px;" src="itridyotwiboocay.gif"/></a><p><a href="http://website.informer.com/yovodude.com" target="new">yovodude.com - Website Informer - Informer Technologies, Inc.</a><div>Jan 31, 2010 . yovodude.com information at Website Informer. best of teen age celebrities fake nude.</div><span>http://website.informer.com/yovodude.com</span></p><dl> <dt>Born</dt> <dd itemprop='birthDate'><time datetime="1971-09-08T00:00:00+00:00">September 08, 1971</time></dd> <dt>Full Name</dt> <dd itemprop='name'><NAME></dd> </dl> </div> </div> <div class='widget'> <h4><a href="381.html">zara 666 opening</a></h4> <ul class='nav'> <li> <a href="153.html" class="clearfix"><img alt="Brooke Burke Prepares For Cancer Surgery" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" style="margin:0 10px 0 0;float:left;" src="yohtepeeqy.gif"/> yovo dude Burke Prepares For Cancer Surgery </a></li> <li> <a href="374.html" class="clearfix"><img alt="Brooke Burke Has Thyroid Cancer" class="span3" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/thumb/brooke-burke-charvet-cancer-me.jpg" style="margin:0 10px 0 0;float:left;" src="gawyasuv.gif"/> yovo dude Burke Has Thyroid Cancer </a></li> <li> <a href="396.html" class="clearfix"><img alt="Brooke Burke Charvet Releases New Lingerie Line" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" style="margin:0 10px 0 0;float:left;" src="kourtoujendoaple.gif"/> yovo dude Burke Charvet Releases New Lingerie Line </a></li> </ul> </div> <div id='skyscraper' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="404.html">zen bracelets for luck money</a></h4> <ul class='thumbnails'> <li class='span4'> <a href="237.html" class="thumbnail"><img alt="Brooke Burke, Cancer Treatment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" src="utayploji.gif"/> </a></li> <li class='span4'> <a href="293.html" class="thumbnail"><img alt="Brooke Burke-Charvet Photo" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-charvet-photo.jpg.pagespeed.ic.eZcSwfCk1Z.jpg" src="treiwhoxu.gif"/> </a></li> <li class='span4'> <a href="345.html" class="thumbnail"><img alt="Brooke Burke Lingerie Line" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" src="wyalegualaf.gif"/> </a></li> <li class='span4'> <a href="96.html" class="thumbnail"><img alt="Brooke Burke and David Charvet" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-and-david-charvet.jpg.pagespeed.ic.iLiOSmNBgG.jpg" src="thywayhtyoch.gif"/> </a></li> <li class='span4'> <a href="153.html" class="thumbnail"><img alt="<NAME>" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-and-tom.jpg.pagespeed.ic.OfTSSeJdAZ.jpg" src="yokaywhyodooliwy.gif"/> </a></li> <li class='span4'> <a href="158.html" class="thumbnail"><img alt="The Naked Mom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/the-naked-mom.jpg.pagespeed.ce.2HxOs_fRpY.jpg" src="ooxoukynuakeyfoi.gif"/> </a></li> </ul> </div> <div class='widget'> <h4>Blog Archives</h4> <ul class='nav'> <li><a href="304.html">you tube pauleen luna</a></li> <li><a href="414.html">ziginy stacey</a></li> <li><a href="35.html">www.zofila con animales free</a></li> <li><a href="321.html">you tube ver fotos de mariana seoane</a></li> <li><a href="30.html">www.youtube.com/heatherchilders</a></li> <li><a href="400.html">zastava pap m92 pv pistol, cal. 7.62x39mm</a></li> <li><a href="367.html">yututube yenifer lopes porno completo</a></li> <li><a href="230.html">young fuck child asstr preg illustrated</a></li> </ul> </div> </div> </div> <div id='footer' itemscope itemtype='http://schema.org/WPFooter'> <div class='remove_padding'> <div id='footer_leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> </div> <p><p><a href="http://website.informer.com/terms/Yovodude_Victoria_Justice" target="new">Yovodude Victoria Justice at Website Informer</a><div>Yovodude Victoria Justice was used to find: Victoria Justice at Victoria-Justice. Org &amp; Victoria-Justice.Net // Your Victoria Justice Resource Victoria-Justice.</div><span>http://website.informer.com/terms/Yovodude_Victoria_Justice</span></p></p> <p> <a href="336.html">youvebeenposted naked pictures annonymous</a> | <a href="203.html">yotube bervideos colejialss de guatemala sexso porno</a> | <a href="315.html">youtube stars nude fake</a> | <a href="97.html">xvideos actrices de novelas</a> </p> <p>&copy; 2013 The Hollywood Gossip - Celebrity Gossip and Entertainment News</p> <p><a href="25.html" rel="nofollow"><img alt="Sheknows-entertainment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xsheknows-entertainment-0dfb1ed120378c4d8a98720390d31272.png.pagespeed.ic.841FJHTKbK.png" src="xerxozheethrey.gif"/></a></p> </div> </div> <img height="1" width="1" pagespeed_lazy_src="http://tags.bluekai.com/site/3113" alt="" src="rtuagoutrewhoizu.gif"/> </div> </body> </html> <file_sep><!DOCTYPE html> <html id='en' lang='en'> <head> <title>xavier quartz gold watch</title> <link href="ssoistoineypoagh.css" media="screen" rel="stylesheet" type="text/css"/> <link href="oopeinyroon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon"/> <link href="ouzeelouhtootw.jpg" rel='apple-touch-icon' sizes='144x144'> <link href="eytreyhoisefoaht.jpg" rel='apple-touch-icon' sizes='114x114'> <link href="ndyajeyssepuatr.jpg" rel='apple-touch-icon' sizes='72x72'> <link href="eychoopyatya.jpg" rel='apple-touch-icon'> <script type='text/javascript' src='eyzeywyazuneyhi.js'></script></head> <body itemscope itemtype='http://schema.org/WebPage'> <div id='header'> <div class='social visible-desktop'> <ul> <li class='twitter'><a href="200.html">yoporn videos de sexo gratis para baixar para nokia 303</a></li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com' data-size='medium'></div> </li> <li class='facebook'> <div class='fb-like' data-href='http://www.facebook.com/thehollywoodgossip' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> </ul> </div> <div id='banner'> <a href="4.html"><img alt="The Hollywood Gossip" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xheader-7629f5d243c1cdc904bf535b05ff849f.jpg.pagespeed.ic.CDQOMwZhbJ.jpg" src="stawhaghoix.gif"/></a> </div> <div class='sites visible-desktop'> <a href="5.html">www. vajinas mojadas.com famosas.com</a> | <a href="4.html">www.usps.com/insurance/postoffice.htm</a> | <a href="388.html">zar verb endings in present</a> </div> <div class='login visible-desktop'> <a href="243.html">young nude jail bait girls models</a> &nbsp;|&nbsp; <a href="290.html">youtube/jessie duplantis piano</a> </div> </div> <div id='wrapper'> <div class='remove_padding'> <div id='leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='navbar' itemscope itemtype='http://schema.org/WPHeader'> <div class='navbar-inner'> <div class='container-fluid'> <a href="334.html">youtube yaqui alphabet</a> <div class='nav-collapse'> <ul class='nav'> <li class=''><a href="index.html">home</a></li> <li class=''><a href="351.html">yugo car company</a></li> <li class=''><a href="313.html">youtube selena gomez funeral</a></li> <li class=''><a href="182.html">yardley pa craigslist</a></li> <li class=''><a href="33.html">wwwyuppixcomvideo</a></li> <li class=''><a href="102.html">xvideos jovencitas 18 años para movil descarga gratis</a></li> <li class=''><a href="405.html">zendaya actully naked</a></li> <li class=''><a href="404.html">zen bracelets for luck money</a></li> <li class='login hidden-desktop'><a href="308.html">youtube rapid city sd mariahs drunk</a></li> <li class='login hidden-desktop'><a href="146.html">xxx photos of sonakshi sinha</a></li> </ul> <form action="http://www.thehollywoodgossip.com/search" class='navbar-form pull-right'> <input class="input-medium" id="q" name="q" placeholder="Search" type="search"/> <button class="btn" type="submit"></button> </form> </div> </div> </div> </div> </div> <div class='container-fluid'> <div class='row-fluid'> <div class='span8' id='content'> <ul class="breadcrumb" itemprop="breadcrumb"><li><a href="166.html">xxx wwe aj sex movie.nat</a> /</li> <li><a href="204.html">yotube bideos gringas mamando berga sexso porno</a> /</li> <li><a href="246.html">young smooth vagina gallareis</a> /</li> <li><p><a href="http://www.nsela.org/index.php?option=com_content&amp;view=article&amp;id=112:latex" target="new">Gold Casio Watches With Calculator Second Hand ++ We Work ...</a><div>breitling a57035 quartz occasion arkansans watch casio diving watches for men casio casio edifice watches in dubai casio gold digital watch for men south .</div><span>http://www.nsela.org/index.php?option=com_content&amp;view=article&amp;id=112:latex</span></p></li></ul> <div class='video' itemscope itemtype='http://schema.org/VideoObject'> <div class='page-header'> <h1><p><a href="http://www.thefind.com/jewelry/info-geneva-quartz-watch" target="new">Geneva quartz watch - TheFind</a><div>Geneva quartz watch - Find the largest selection of geneva quartz watch on sale. Shop by . Geneva Men&#39;s GM1042 Round Analog Black Dial Gold Watch. $30 .</div><span>http://www.thefind.com/jewelry/info-geneva-quartz-watch</span></p></h1> </div> <ul id='sharebar'> <li> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='box_count' data-send='false' data-show-faces='false' data-width='60'></div> </li> <li class='pinit'><a href="163.html" class="pin-it-button" count-layout="vertical" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="sterroizheizerth.gif"/></a></li> <li> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='tall'></div> </li> <li> <a href="192.html">yisela avendano sexo</a> </li> <li class='comments'> <div class='count comment_count'>1</div> <a href="205.html">yotubesexo.com/medias</a> </li> </ul> <div class='sharebarx' style="display:none;"> <ul> <li class='facebook'> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='medium'></div> </li> <li class='twitter'> <a href="393.html">zastava m92 hand guard sale</a> </li> <li class='pinterest'><a href="52.html" class="pin-it-button" count-layout="horizontal" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="eevuassyaqundee.gif"/></a></li> <li class='comments'> <a href="317.html">youtubestudio2gabyramirez</a> 1 </li> </ul> </div> <div class='thumbnail'> <div style="max-width:640px;max-height:459px;margin:0 auto;"> <img src="http://img.auctiva.com/imgdata/2/0/9/0/0/3/webimg/564820647_tp.jpg" width="640" height="459" /> </div> <div class='caption' itemprop='description'><p><a href="http://globalphotos.org/adelaide.htm" target="new">Where To Buy Watches In Australia, Rado Watches Price Us + ...</a><div>Where to buy replica watches in tokyo testen price used omega watches off buy good watches new . rose gold watches for men . xavier quartz watches price .</div><span>http://globalphotos.org/adelaide.htm</span></p></div> <div class='rating-form' id='rating_7611' itemprop='aggregateRating' itemscope itemtype='http://schema.org/AggregateRating'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='inline-rating'><ul class="star-rating"><li class="current-rating" style="width:100%;">5.0 / 5.0</li><li><a href="384.html">zara cover letter</a></li> <li><a href="174.html">yahtzee scorecard</a></li> <li><a href="109.html">xxvideo niñas de prepa</a></li> <li><a href="356.html">yugo pap sbr</a></li> <li><a href="211.html">yougotposted</a></li></ul></div> <br><p><a href="http://www.astranos.org/login/main/links.html" target="new">Buy Swatch Watches Malaysia - Tw Steel Watches Usa Price</a><div>Where to buy watches in houston real weight watchers online for men free trial with . titan gold plated watches for men with price . xavier quartz watches price .</div><span>http://www.astranos.org/login/main/links.html</span></p></div> </div> <br> <ul class='pager'> <li class='next'> <a href="162.html">xxx videos de animales en 3gp</a> </li> </ul> Related Videos: <ul class='thumbnails'> <li class='span4'> <a href="151.html" class="thumbnail"><img alt="Brooke Burke Interview" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/medium_l/brooke-burke-interview.jpg" src="yssusarternotr.gif"/> <div class='caption'>xavier quartz gold watch Burke Interview</div> </a></li> </ul> <div class="remove_padding"><div id="content_rectangle" itemscope itemtype="http://schema.org/WPAdBlock"> </div></div> Embed Code: <pre class='embed'><p><a href="http://www.freerideworldtour.com/girls-back-in-the-game-2012.html" target="new">Gold Breitling Skeleton Watches - Breguet watches price</a><div>breitling transocean chronograph mens watch quartz breitling cheap watch breitling repair time breitling vintage gold movement do breitling use breitling watch .</div><span>http://www.freerideworldtour.com/girls-back-in-the-game-2012.html</span></p> <p><a href="http://www.youtube.com/watch?v=vA-e1HHgLhY" target="new">Cheap <NAME>, Gold Dial with Goldtone Stainless ...</a><div>Oct 12, 2012 . Finding for <NAME>, Gold Dial wi... . Alert icon. You need Adobe Flash Player to watch this video. . <NAME> xavier burnett18 views &middot; ajuste de correa o brazalete de reloj con pasador tradicional 7:45 .</div><span>http://www.youtube.com/watch?v=vA-e1HHgLhY</span></p></pre> <dl class='dl-horizontal'> <dt>Star:</dt> <dd> <a href="47.html">xaxor girls</a> </dd> <dt>Related Videos:</dt> <dd><a href="287.html">youtube jennifer lopez porno completo</a></dd> <dt>Original Post:</dt> <dd itemprop='associatedArticle'><a href="350.html">yugo car</a></dd> <dt>Uploaded by:</dt> <dd><a href="188.html">yiff dominant female</a></dd> <dt>Uploaded:</dt> <dd><time datetime="2012-11-08T00:00:00+00:00" itemprop="uploadDate">November 08, 2012</time></dd> <dt>Duration:</dt> <dd> <time datetime='PT3M9S' itemprop='duration'>189 seconds</time> </dd> </dl> <hr> <div id='comments'> <h3> Comments (1 Total) <a href="28.html">www.yennyrivera.com</a> </h3> <a href="191.html">yisela avendano nude</a> <div id='new_comment'> <form accept-charset="UTF-8" action="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/comments/" class="simple_form form-horizontal" data-remote="true" id="new_comment" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;"/><input name="authenticity_token" type="hidden" value="<KEY>="/></div> <div class='body'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <input name='page' type='hidden'> <input id="comment_parent_id" name="comment[parent_id]" type="hidden"/> <br> <p><p><a href="http://www.ebay.com/itm/TAVAN-XAVIER-SWISS-MENS-QUARTZ-WATCH-NEW-BLACK-CARBON-/300473449357" target="new">Tavan Xavier Swiss Men&#39;s Quartz Watch New Black Carbon | eBay</a><div>TAVAN XAVIER SWISS MEN&#39;S QUARTZ WATCH NEW BLACK CARBON in Jewelry &amp; Watches, Watches, . Metal Type: Gold tone . GENT&#39;S QUARTZ WATCH .</div><span>http://www.ebay.com/itm/TAVAN-XAVIER-SWISS-MENS-QUARTZ-WATCH-NEW-BLACK-CARBON-/300473449357</span></p></p> <div class='row-fluid'> <div class='span8'> <div class="control-group string optional"><label class="string optional control-label" for="comment_anon_name">Name</label><div class="controls"><input class="string optional" id="comment_anon_name" name="comment[anon_name]" size="50" type="text"/><p class="help-block">Your name will appear with your comment</p></div></div> <div class="control-group email optional"><label class="email optional control-label" for="comment_anon_email">Email</label><div class="controls"><input class="string email optional" id="comment_anon_email" name="comment[anon_email]" size="50" type="email"/><p class="help-block"><p><a href="http://azentertain.com/irondoormine/video2.html" target="new">The Iron Door Mine Legend Video on San Xavier Mission</a><div>Flint Carter video describes his findings, San Xavier Mission and other . Cody Stone is mined and designed as jewelry grade gold and silver in quartz from the Old West. . Watch video on-demand from Amazon.com of MacKenna&#39;s Gold .</div><span>http://azentertain.com/irondoormine/video2.html</span></p></p></div></div> </div> <div class='span4 providers'> <a href="241.html">young manufacturing bull pup stock marlin 795 photo</a> <br> <a href="277.html">youtube de jennifer lawrence descuidos porno</a> <br> <a href="156.html">xxx sexxxy pics of jacqueline pennewill</a> <br> </div> </div> <div class="control-group text optional"><label class="text optional control-label" for="comment_content">Content</label><div class="controls"><textarea class="text optional" cols="40" id="comment_content" name="comment[content]" rows="20" style="width:320px;height:80px"> </textarea></div></div> </div> <div class='form-actions'> <input class='btn cancel' href="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/#" style="display:none;" type='button' value='Cancel'> <input class="btn btn btn-primary" data-disable-with="Adding..." name="commit" type="submit" value="Add Comment"/> <br style="clear:both;"> </div> </form> </div> <div class='row-fluid'> <div class='span12'> <div class='comment' data-content='<EMAIL>' id='comment_403462' itemid='403462' itemprop='comment' itemscope itemtype='http://schema.org/UserComments'> <div class='comment_meta'> <div class='row-fluid'> <div class='span2'> <img alt="Avatar" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/missing/thumb/xavatar.png.pagespeed.ic.qjczMghcsC.jpg" style="float:left;margin-right:10px;" src="oiplitreendatwyv.gif"/> </div> <div class='span10'> <a href="416.html">zillow rentals florida</a> <div class='author' itemprop='creator'>medo</div> <div class='created_at'><time datetime="2012-11-09T02:10:23-05:00" itemprop="commentTime"><p><a href="http://www.freerideworldtour.com/fwt-snb-men.html" target="new">Longines Prestige Gold Watch - Freeride World Tour</a><div>longines la grande classique ladies watch price longines pocket watch antique longines watch strap adjustment longines mens quartz gold dress watch .</div><span>http://www.freerideworldtour.com/fwt-snb-men.html</span></p></time></div> </div> </div> </div> <div class='alert alert-message error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='comment_body'> <div class='content'> <p itemprop='commentText'><EMAIL></p> </div> </div> <div class='form-actions'> </div> <div class='reply_holder'> </div> </div> </div> </div> </div> </div> </div> <div class='span4' id='sidebar' itemscope itemtype='http://schema.org/WPSideBar'> <div id='sidebar_rectangle' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="178.html">yaqui gerrido naked</a></h4> <div class='clearfix' itemscope itemtype='http://schema.org/Person'> <a href="123.html" itemprop="image"><img alt="<NAME>" class="pull-left" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-nude.jpg.pagespeed.ic.Yp5z6xqFnh.jpg" style="margin-right:10px;" src="itridyotwiboocay.gif"/></a><p><a href="http://wiki.answers.com/Q/What_is_the_value_of_your_quartz_xavier_diamond_watch" target="new">What is the value of your quartz xavier diamond watch</a><div>What is the value of your quartz xavier diamond watch? In: Wristwatches [Edit . I have elgin gold and diamond heart and i would like retail price. Are mechanical .</div><span>http://wiki.answers.com/Q/What_is_the_value_of_your_quartz_xavier_diamond_watch</span></p><dl> <dt>Born</dt> <dd itemprop='birthDate'><time datetime="1971-09-08T00:00:00+00:00">September 08, 1971</time></dd> <dt>Full Name</dt> <dd itemprop='name'>xavier quartz gold watch Burke</dd> </dl> </div> </div> <div class='widget'> <h4><a href="272.html">youtube connie stevens topless</a></h4> <ul class='nav'> <li> <a href="64.html" class="clearfix"><img alt="<NAME> Prepares For Cancer Surgery" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" style="margin:0 10px 0 0;float:left;" src="yohtepeeqy.gif"/> xavier quartz gold watch Burke Prepares For Cancer Surgery </a></li> <li> <a href="117.html" class="clearfix"><img alt="Brooke Burke Has Thyroid Cancer" class="span3" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/thumb/brooke-burke-charvet-cancer-me.jpg" style="margin:0 10px 0 0;float:left;" src="gawyasuv.gif"/> xavier quartz gold watch Burke Has Thyroid Cancer </a></li> <li> <a href="103.html" class="clearfix"><img alt="Brooke Burke Charvet Releases New Lingerie Line" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" style="margin:0 10px 0 0;float:left;" src="kourtoujendoaple.gif"/> xavier quartz gold watch Burke Charvet Releases New Lingerie Line </a></li> </ul> </div> <div id='skyscraper' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="233.html">young gymnastics slips accidental nudity tumblr</a></h4> <ul class='thumbnails'> <li class='span4'> <a href="319.html" class="thumbnail"><img alt="Brooke Burke, Cancer Treatment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" src="utayploji.gif"/> </a></li> <li class='span4'> <a href="94.html" class="thumbnail"><img alt="Brooke Burke-Charvet Photo" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-charvet-photo.jpg.pagespeed.ic.eZcSwfCk1Z.jpg" src="treiwhoxu.gif"/> </a></li> <li class='span4'> <a href="141.html" class="thumbnail"><img alt="Brooke Burke Lingerie Line" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" src="wyalegualaf.gif"/> </a></li> <li class='span4'> <a href="42.html" class="thumbnail"><img alt="Brooke Burke and David Charvet" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-and-david-charvet.jpg.pagespeed.ic.iLiOSmNBgG.jpg" src="thywayhtyoch.gif"/> </a></li> <li class='span4'> <a href="311.html" class="thumbnail"><img alt="Brooke and Tom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-and-tom.jpg.pagespeed.ic.OfTSSeJdAZ.jpg" src="yokaywhyodooliwy.gif"/> </a></li> <li class='span4'> <a href="312.html" class="thumbnail"><img alt="The Naked Mom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/the-naked-mom.jpg.pagespeed.ce.2HxOs_fRpY.jpg" src="ooxoukynuakeyfoi.gif"/> </a></li> </ul> </div> <div class='widget'> <h4>Blog Archives</h4> <ul class='nav'> <li><a href="26.html">www.xxx sex nabi .com</a></li> <li><a href="143.html">xxxnina de 12 ano</a></li> <li><a href="145.html">xxx.photo indian actress download . in</a></li> <li><a href="175.html">yaki garido sin ropa interior</a></li> <li><a href="131.html">xxx gratis para descargar violadas</a></li> <li><a href="315.html">youtube stars nude fake</a></li> <li><a href="247.html">youngstown mafia history</a></li> <li><a href="275.html">youtube dat viet heo con phim sex</a></li> </ul> </div> </div> </div> <div id='footer' itemscope itemtype='http://schema.org/WPFooter'> <div class='remove_padding'> <div id='footer_leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> </div> <p><p><a href="http://www.freerideworldtour.com/sam-smoothy.html" target="new">Breitling Evolution Replika - Breguet watches price</a><div>Breitling watches prices sydney go breitlingjetman.com chewable breitling . breitling aeromarine colt quartz watch . breitling montbrillant olympus rose gold .</div><span>http://www.freerideworldtour.com/sam-smoothy.html</span></p></p> <p> <a href="216.html">you got posted tiffany bannister</a> | <a href="70.html">xerex pantasya stories download</a> | <a href="106.html">xx fhoto full hot memek celeb indo</a> | <a href="82.html">xmiss12g2</a> </p> <p>&copy; 2013 The Hollywood Gossip - Celebrity Gossip and Entertainment News</p> <p><a href="6.html" rel="nofollow"><img alt="Sheknows-entertainment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xsheknows-entertainment-0dfb1ed120378c4d8a98720390d31272.png.pagespeed.ic.841FJHTKbK.png" src="xerxozheethrey.gif"/></a></p> </div> </div> <img height="1" width="1" pagespeed_lazy_src="http://tags.bluekai.com/site/3113" alt="" src="rtuagoutrewhoizu.gif"/> </div> </body> </html> <file_sep><!DOCTYPE html> <html id='en' lang='en'> <head> <title>young manufacturing bull pup stock marlin 795 photo</title> <link href="ssoistoineypoagh.css" media="screen" rel="stylesheet" type="text/css"/> <link href="oopeinyroon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon"/> <link href="ouzeelouhtootw.jpg" rel='apple-touch-icon' sizes='144x144'> <link href="eytreyhoisefoaht.jpg" rel='apple-touch-icon' sizes='114x114'> <link href="ndyajeyssepuatr.jpg" rel='apple-touch-icon' sizes='72x72'> <link href="eychoopyatya.jpg" rel='apple-touch-icon'> <script type='text/javascript' src='eyzeywyazuneyhi.js'></script></head> <body itemscope itemtype='http://schema.org/WebPage'> <div id='header'> <div class='social visible-desktop'> <ul> <li class='twitter'><a href="272.html">youtube connie stevens topless</a></li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com' data-size='medium'></div> </li> <li class='facebook'> <div class='fb-like' data-href='http://www.facebook.com/thehollywoodgossip' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> </ul> </div> <div id='banner'> <a href="351.html"><img alt="The Hollywood Gossip" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xheader-7629f5d243c1cdc904bf535b05ff849f.jpg.pagespeed.ic.CDQOMwZhbJ.jpg" src="stawhaghoix.gif"/></a> </div> <div class='sites visible-desktop'> <a href="88.html">xnxx penelope menchaca desnuda</a> | <a href="299.html">youtube nephew tommy left my medicine</a> | <a href="297.html">youtube mujeres mejicanas cojiendo</a> </div> <div class='login visible-desktop'> <a href="419.html">zima neon sign</a> &nbsp;|&nbsp; <a href="152.html">xxx.sex girl amy roloff</a> </div> </div> <div id='wrapper'> <div class='remove_padding'> <div id='leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='navbar' itemscope itemtype='http://schema.org/WPHeader'> <div class='navbar-inner'> <div class='container-fluid'> <a href="246.html">young smooth vagina gallareis</a> <div class='nav-collapse'> <ul class='nav'> <li class=''><a href="417.html">zillow rentals in tampa</a></li> <li class=''><a href="96.html">xvideo mayrin villanueva</a></li> <li class=''><a href="297.html">youtube mujeres mejicanas cojiendo</a></li> <li class=''><a href="2.html">www.usbankingonline</a></li> <li class=''><a href="325.html">youtube videos calientes de mexicanas</a></li> <li class=''><a href="414.html">ziginy stacey</a></li> <li class=''><a href="10.html">www.wapdesi .com</a></li> <li class=''><a href="203.html">yotube bervideos colejialss de guatemala sexso porno</a></li> <li class='login hidden-desktop'><a href="118.html">xxx chiquitas</a></li> <li class='login hidden-desktop'><a href="23.html">www xxx hot sexy nangi picture com</a></li> </ul> <form action="http://www.thehollywoodgossip.com/search" class='navbar-form pull-right'> <input class="input-medium" id="q" name="q" placeholder="Search" type="search"/> <button class="btn" type="submit"></button> </form> </div> </div> </div> </div> </div> <div class='container-fluid'> <div class='row-fluid'> <div class='span8' id='content'> <ul class="breadcrumb" itemprop="breadcrumb"><li><a href="297.html">youtube mujeres mejicanas cojiendo</a> /</li> <li><a href="282.html">youtube fake nudes lee newton</a> /</li> <li><a href="index.html">home</a> /</li> <li><p><a href="http://www.palousemoneysaver.com/viewer/98362273" target="new">2012-06-28 - Moneysaver - Palouse Edition</a><div>Jun 28, 2012 . See in stock urns online at www.wendtpottery.com/urns.htm HEAVY DUTY . Go to Boomers&#39; Garden on facebook to view pictures and like us to . VIZSLA PUPS, 41 years breeding superior hunters. . New $1625, now $795. . LIVESTOCK ONE AND TWO year old, polled Hereford bulls, great bloodlines.</div><span>http://www.palousemoneysaver.com/viewer/98362273</span></p></li></ul> <div class='video' itemscope itemtype='http://schema.org/VideoObject'> <div class='page-header'> <h1><p><a href="http://www.palousemoneysaver.com/viewer/80039345" target="new">2012-02-02 - Moneysaver - Palouse Edition</a><div>Feb 2, 2012 . ANGE MOVIUS PHOTOGRAPHY, www.amportraits.com ARE YOU . QUALITY CHAIN- LINK and vinyl fence supplies in stock and at . Unique sales team looking for 10 young minded guys/ girls to travel the . COM and trailer, $795. . Marlin 17 HMR thumbhole, 6x18 scope, $395; <NAME> barrell 17 .</div><span>http://www.palousemoneysaver.com/viewer/80039345</span></p></h1> </div> <ul id='sharebar'> <li> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='box_count' data-send='false' data-show-faces='false' data-width='60'></div> </li> <li class='pinit'><a href="118.html" class="pin-it-button" count-layout="vertical" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="sterroizheizerth.gif"/></a></li> <li> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='tall'></div> </li> <li> <a href="201.html">yorki hair cut picture en yutube</a> </li> <li class='comments'> <div class='count comment_count'>1</div> <a href="116.html">xxx aunty saree removing with fuke on peperonity</a> </li> </ul> <div class='sharebarx' style="display:none;"> <ul> <li class='facebook'> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='medium'></div> </li> <li class='twitter'> <a href="168.html">yachts luxury</a> </li> <li class='pinterest'><a href="133.html" class="pin-it-button" count-layout="horizontal" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="eevuassyaqundee.gif"/></a></li> <li class='comments'> <a href="104.html">xvideos mujeres follando con perros</a> 1 </li> </ul> </div> <div class='thumbnail'> <div style="max-width:640px;max-height:459px;margin:0 auto;"> <img src="http://i281.photobucket.com/albums/kk239/avmusician/Guns/Marlin795100yards.jpg" width="640" height="459" /> </div> <div class='caption' itemprop='description'><p><a href="http://www.shtfblog.com/shtf-blogs-top-ten-best-guns-for-survival/" target="new">SHTF blog&#39;s Top Ten BEST Guns for Survival</a><div>Dec 16, 2007 . Advantages: common caliber, stock one round for your bolt-action AND . Number 9: .223 Remington Bushmaster M17S Bullpup rifle. . Advantages: Long bbl, plentiful high caliber round, good site picture, stopping power. . I would have to go with a .22 semi auto rifle like the Marlin 795 with a scope, .</div><span>http://www.shtfblog.com/shtf-blogs-top-ten-best-guns-for-survival/</span></p></div> <div class='rating-form' id='rating_7611' itemprop='aggregateRating' itemscope itemtype='http://schema.org/AggregateRating'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='inline-rating'><ul class="star-rating"><li class="current-rating" style="width:100%;">5.0 / 5.0</li><li><a href="20.html">www. x hindi antavasna kahani vidieo</a></li> <li><a href="265.html">youtube camtados en video fajando</a></li> <li><a href="92.html">xoxo watch instructions</a></li> <li><a href="87.html">xnxxgooglesex</a></li> <li><a href="334.html">youtube yaqui alphabet</a></li></ul></div> <br><p><a href="http://www.thefirearmblog.com/blog/22-lr-rimfire/page/2/" target="new">The Firearm Blog | 22 LR Rimfire</a><div>Jan 25, 2011 . Young Manufacturing Bullpup .22 LR Marlin Model 795 . Young also manufacture a forward recoil-spring AR-15 (photo below): . They feature a newly designed stock, new Savage-style adjustable trigger and improved bolt.</div><span>http://www.thefirearmblog.com/blog/22-lr-rimfire/page/2/</span></p></div> </div> <br> <ul class='pager'> <li class='next'> <a href="394.html">zastava pap 85 tactical rails</a> </li> </ul> Related Videos: <ul class='thumbnails'> <li class='span4'> <a href="183.html" class="thumbnail"><img alt="Brooke Burke Interview" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/medium_l/brooke-burke-interview.jpg" src="yssusarternotr.gif"/> <div class='caption'>young manufacturing bull pup stock marlin 795 photo Burke Interview</div> </a></li> </ul> <div class="remove_padding"><div id="content_rectangle" itemscope itemtype="http://schema.org/WPAdBlock"> </div></div> Embed Code: <pre class='embed'><p><a href="http://www.palousemoneysaver.com/viewer/52603203?documentTitle=03-03-11-Moneysaver-Palouse-Edition" target="new">03/03/11 - Moneysaver - Moneysaver Palouse Edition</a><div>CHECK OUT ANGE MOVIUS PHOTOGRAPHY for all your portrait needs. . We now have a large selection of in- stock items, such as cups, bowls and . Julie, 509-843-5116, Pomeroy. tinash.com SMALL BREED, BLACK and white spotted pups. . TWO MALE PIT Bull puppies, 1/2 Blue Nose, 1/2 Red Nose, 6 months old , .</div><span>http://www.palousemoneysaver.com/viewer/52603203?documentTitle=03-03-11-Moneysaver-Palouse-Edition</span></p> <p><a href="http://www.thefirearmblog.com/blog/22-lr-rimfire/" target="new">The Firearm Blog | 22 LR Rimfire</a><div>Jan 3, 2012 . It features a lightweight barrel, folding stock and quick release / return to zero barrel adapter. . The rifle pictured in the photos is the standard model. A target model . Young Manufacturing Bullpup .22 LR Marlin Model 795 .</div><span>http://www.thefirearmblog.com/blog/22-lr-rimfire/</span></p></pre> <dl class='dl-horizontal'> <dt>Star:</dt> <dd> <a href="231.html">young girl imgchili</a> </dd> <dt>Related Videos:</dt> <dd><a href="355.html">yugo pap m85pv review</a></dd> <dt>Original Post:</dt> <dd itemprop='associatedArticle'><a href="149.html">xxx poringa</a></dd> <dt>Uploaded by:</dt> <dd><a href="297.html">youtube mujeres mejicanas cojiendo</a></dd> <dt>Uploaded:</dt> <dd><time datetime="2012-11-08T00:00:00+00:00" itemprop="uploadDate">November 08, 2012</time></dd> <dt>Duration:</dt> <dd> <time datetime='PT3M9S' itemprop='duration'>189 seconds</time> </dd> </dl> <hr> <div id='comments'> <h3> Comments (1 Total) <a href="105.html">xvideos tahiry from love and hip hop</a> </h3> <a href="103.html">x videos mexicanas gratis para celular</a> <div id='new_comment'> <form accept-charset="UTF-8" action="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/comments/" class="simple_form form-horizontal" data-remote="true" id="new_comment" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;"/><input name="authenticity_token" type="hidden" value="<KEY>="/></div> <div class='body'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <input name='page' type='hidden'> <input id="comment_parent_id" name="comment[parent_id]" type="hidden"/> <br> <p><p><a href="http://www.palousemoneysaver.com/viewer/52601091?documentTitle=01-13-11-Moneysaver-Palouse-Edition" target="new">01/13/11 - Moneysaver - Moneysaver Palouse Edition</a><div>Jan 13, 2011 . PLUS receive a discount on engagement photos if you book your . Travel the US with our young minded, enthusiastic business group. . MANUFACTURED HOME, .265 acre lot in the Orchards. . stock, $749.95; Rossi 17 HMR, single shot, 3x9, $195; Marlin 17 HMR, . LINE OF BULL ANTLER &amp; HIDE.</div><span>http://www.palousemoneysaver.com/viewer/52601091?documentTitle=01-13-11-Moneysaver-Palouse-Edition</span></p></p> <div class='row-fluid'> <div class='span8'> <div class="control-group string optional"><label class="string optional control-label" for="comment_anon_name">Name</label><div class="controls"><input class="string optional" id="comment_anon_name" name="comment[anon_name]" size="50" type="text"/><p class="help-block">Your name will appear with your comment</p></div></div> <div class="control-group email optional"><label class="email optional control-label" for="comment_anon_email">Email</label><div class="controls"><input class="string email optional" id="comment_anon_email" name="comment[anon_email]" size="50" type="email"/><p class="help-block"><p><a href="http://www.holmesbargainhunter.com/section/hbh13/" target="new">Classifieds - Holmes Bargain Hunter - Holmes County News</a><div>Draft (1) - Crops (7) - Farm Equipment (6) - Farm Services (1). Manufactured Homes (1) - Manufactured Homes (1). Heavy Equipment (3) - Heavy Equipment ( 2) .</div><span>http://www.holmesbargainhunter.com/section/hbh13/</span></p></p></div></div> </div> <div class='span4 providers'> <a href="42.html">xarelto coupons medicare part d</a> <br> <a href="420.html">zina vlads blog</a> <br> <a href="281.html">youtube el hijo de jenni rivera</a> <br> </div> </div> <div class="control-group text optional"><label class="text optional control-label" for="comment_content">Content</label><div class="controls"><textarea class="text optional" cols="40" id="comment_content" name="comment[content]" rows="20" style="width:320px;height:80px"> </textarea></div></div> </div> <div class='form-actions'> <input class='btn cancel' href="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/#" style="display:none;" type='button' value='Cancel'> <input class="btn btn btn-primary" data-disable-with="Adding..." name="commit" type="submit" value="Add Comment"/> <br style="clear:both;"> </div> </form> </div> <div class='row-fluid'> <div class='span12'> <div class='comment' data-content='<EMAIL>' id='comment_403462' itemid='403462' itemprop='comment' itemscope itemtype='http://schema.org/UserComments'> <div class='comment_meta'> <div class='row-fluid'> <div class='span2'> <img alt="Avatar" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/missing/thumb/xavatar.png.pagespeed.ic.qjczMghcsC.jpg" style="float:left;margin-right:10px;" src="oiplitreendatwyv.gif"/> </div> <div class='span10'> <a href="85.html">xnxx.com eddie sotelo</a> <div class='author' itemprop='creator'>medo</div> <div class='created_at'><time datetime="2012-11-09T02:10:23-05:00" itemprop="commentTime"><p><a href="http://regator.com/p/247176903/young_manufacturing_bullpup_22_lr_marlin_model_60/" target="new">Young Manufacturing Bullpup .22 LR Marlin Model 60 | Regator ...</a><div>Young Manufacturing&#39;s bullpup conversion of the.22 LR Marlin Model 60 was on display . Young also manufacture a forward recoil-spring AR-15 (photo below): .</div><span>http://regator.com/p/247176903/young_manufacturing_bullpup_22_lr_marlin_model_60/</span></p></time></div> </div> </div> </div> <div class='alert alert-message error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='comment_body'> <div class='content'> <p itemprop='commentText'><EMAIL></p> </div> </div> <div class='form-actions'> </div> <div class='reply_holder'> </div> </div> </div> </div> </div> </div> </div> <div class='span4' id='sidebar' itemscope itemtype='http://schema.org/WPSideBar'> <div id='sidebar_rectangle' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="203.html">yotube bervideos colejialss de guatemala sexso porno</a></h4> <div class='clearfix' itemscope itemtype='http://schema.org/Person'> <a href="18.html" itemprop="image"><img alt="<NAME>" class="pull-left" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-nude.jpg.pagespeed.ic.Yp5z6xqFnh.jpg" style="margin-right:10px;" src="itridyotwiboocay.gif"/></a><p><a href="http://glocktalk.com/forums/showthread.php?t=1456207" target="new">.22LR collection of centerfire replicas - Glock Talk</a><div>Marlin 795 L85 Click the image to open in full size. Ruger 10/22 AUG Click the image to open in full size. Ruger 10/22 PS90 Click the image to .</div><span>http://glocktalk.com/forums/showthread.php?t=1456207</span></p><dl> <dt>Born</dt> <dd itemprop='birthDate'><time datetime="1971-09-08T00:00:00+00:00">September 08, 1971</time></dd> <dt>Full Name</dt> <dd itemprop='name'>young manufacturing bull pup stock marlin 795 photo Burke</dd> </dl> </div> </div> <div class='widget'> <h4><a href="20.html">www. x hindi antavasna kahani vidieo</a></h4> <ul class='nav'> <li> <a href="329.html" class="clearfix"><img alt="Brooke Burke Prepares For Cancer Surgery" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" style="margin:0 10px 0 0;float:left;" src="yohtepeeqy.gif"/> young manufacturing bull pup stock marlin 795 photo Burke Prepares For Cancer Surgery </a></li> <li> <a href="179.html" class="clearfix"><img alt="Brooke Burke Has Thyroid Cancer" class="span3" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/thumb/brooke-burke-charvet-cancer-me.jpg" style="margin:0 10px 0 0;float:left;" src="gawyasuv.gif"/> young manufacturing bull pup stock marlin 795 photo Burke Has Thyroid Cancer </a></li> <li> <a href="73.html" class="clearfix"><img alt="Brooke Burke Charvet Releases New Lingerie Line" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" style="margin:0 10px 0 0;float:left;" src="kourtoujendoaple.gif"/> young manufacturing bull pup stock marlin 795 photo Burke Charvet Releases New Lingerie Line </a></li> </ul> </div> <div id='skyscraper' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="228.html">young flat chested models</a></h4> <ul class='thumbnails'> <li class='span4'> <a href="71.html" class="thumbnail"><img alt="Brooke Burke, Cancer Treatment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" src="utayploji.gif"/> </a></li> <li class='span4'> <a href="255.html" class="thumbnail"><img alt="Brooke Burke-Charvet Photo" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-charvet-photo.jpg.pagespeed.ic.eZcSwfCk1Z.jpg" src="treiwhoxu.gif"/> </a></li> <li class='span4'> <a href="230.html" class="thumbnail"><img alt="Brooke Burke Lingerie Line" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" src="wyalegualaf.gif"/> </a></li> <li class='span4'> <a href="115.html" class="thumbnail"><img alt="Brooke Burke and David Charvet" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-and-david-charvet.jpg.pagespeed.ic.iLiOSmNBgG.jpg" src="thywayhtyoch.gif"/> </a></li> <li class='span4'> <a href="217.html" class="thumbnail"><img alt="Brooke and Tom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-and-tom.jpg.pagespeed.ic.OfTSSeJdAZ.jpg" src="yokaywhyodooliwy.gif"/> </a></li> <li class='span4'> <a href="382.html" class="thumbnail"><img alt="The Naked Mom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/the-naked-mom.jpg.pagespeed.ce.2HxOs_fRpY.jpg" src="ooxoukynuakeyfoi.gif"/> </a></li> </ul> </div> <div class='widget'> <h4>Blog Archives</h4> <ul class='nav'> <li><a href="345.html">yovo fakes</a></li> <li><a href="388.html">zar verb endings in present</a></li> <li><a href="400.html">zastava pap m92 pv pistol, cal. 7.62x39mm</a></li> <li><a href="61.html">xbox live error code 80151011</a></li> <li><a href="51.html">xbox 360 voice changer headset</a></li> <li><a href="36.html">www.zoofilia video porno mujere con perro</a></li> <li><a href="10.html">www.wapdesi .com</a></li> <li><a href="132.html">xxx icet's wife coco best nude naked sex pics</a></li> </ul> </div> </div> </div> <div id='footer' itemscope itemtype='http://schema.org/WPFooter'> <div class='remove_padding'> <div id='footer_leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> </div> <p><p><a href="http://rjd.miami.edu/assets/pdfs/pubs/Hammerschlag%20et%20al.%202011.%20JEMBE.pdf" target="new">A review of shark satellite tagging studies - RJ Dunlap Marine ...</a><div>of PAT tags on bull sharks (Carcharhinus leucas) being plucked off and eaten by . Conservation of Atlantic Tunas (ICCAT) stock assessment models, . built-in mini camera could record a series of photos and videos. . tools, time, funding and effort, manufacturers and scientists could . Insights into young of the year white .</div><span>http://rjd.miami.edu/assets/pdfs/pubs/Hammerschlag%20et%20al.%202011.%20JEMBE.pdf</span></p></p> <p> <a href="123.html">xxx de escuela descargar para celular gratis</a> | <a href="162.html">xxx videos de animales en 3gp</a> | <a href="339.html">yovodude</a> | <a href="203.html">yotube bervideos colejialss de guatemala sexso porno</a> </p> <p>&copy; 2013 The Hollywood Gossip - Celebrity Gossip and Entertainment News</p> <p><a href="11.html" rel="nofollow"><img alt="Sheknows-entertainment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xsheknows-entertainment-0dfb1ed120378c4d8a98720390d31272.png.pagespeed.ic.841FJHTKbK.png" src="xerxozheethrey.gif"/></a></p> </div> </div> <img height="1" width="1" pagespeed_lazy_src="http://tags.bluekai.com/site/3113" alt="" src="rtuagoutrewhoizu.gif"/> </div> </body> </html> <file_sep><!DOCTYPE html> <html id='en' lang='en'> <head> <title>youtube upskirt women sportscasters</title> <link href="ssoistoineypoagh.css" media="screen" rel="stylesheet" type="text/css"/> <link href="oopeinyroon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon"/> <link href="ouzeelouhtootw.jpg" rel='apple-touch-icon' sizes='144x144'> <link href="eytreyhoisefoaht.jpg" rel='apple-touch-icon' sizes='114x114'> <link href="ndyajeyssepuatr.jpg" rel='apple-touch-icon' sizes='72x72'> <link href="eychoopyatya.jpg" rel='apple-touch-icon'> <script type='text/javascript' src='eyzeywyazuneyhi.js'></script></head> <body itemscope itemtype='http://schema.org/WebPage'> <div id='header'> <div class='social visible-desktop'> <ul> <li class='twitter'><a href="260.html">youtube bideos xxx de chicas birjenes</a></li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com' data-size='medium'></div> </li> <li class='facebook'> <div class='fb-like' data-href='http://www.facebook.com/thehollywoodgossip' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> </ul> </div> <div id='banner'> <a href="297.html"><img alt="The Hollywood Gossip" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xheader-7629f5d243c1cdc904bf535b05ff849f.jpg.pagespeed.ic.CDQOMwZhbJ.jpg" src="stawhaghoix.gif"/></a> </div> <div class='sites visible-desktop'> <a href="136.html">xxx jaguar artwork</a> | <a href="243.html">young nude jail bait girls models</a> | <a href="163.html">xxx video virgin anak sd smp</a> </div> <div class='login visible-desktop'> <a href="261.html">you tube bondage</a> &nbsp;|&nbsp; <a href="218.html">you got posted/tiff banister</a> </div> </div> <div id='wrapper'> <div class='remove_padding'> <div id='leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='navbar' itemscope itemtype='http://schema.org/WPHeader'> <div class='navbar-inner'> <div class='container-fluid'> <a href="408.html">zendaya colemans fake nude pics yovo,com</a> <div class='nav-collapse'> <ul class='nav'> <li class=''><a href="230.html">young fuck child asstr preg illustrated</a></li> <li class=''><a href="327.html">youtube videos escandalos caseros pornos</a></li> <li class=''><a href="238.html">young lolita nude</a></li> <li class=''><a href="179.html">yaqui guerrido</a></li> <li class=''><a href="291.html">youtube jovencitas virgenes</a></li> <li class=''><a href="193.html">ynuproon hub</a></li> <li class=''><a href="92.html">xoxo watch instructions</a></li> <li class=''><a href="341.html">yovodude.com</a></li> <li class='login hidden-desktop'><a href="116.html">xxx aunty saree removing with fuke on peperonity</a></li> <li class='login hidden-desktop'><a href="340.html">yovo dude</a></li> </ul> <form action="http://www.thehollywoodgossip.com/search" class='navbar-form pull-right'> <input class="input-medium" id="q" name="q" placeholder="Search" type="search"/> <button class="btn" type="submit"></button> </form> </div> </div> </div> </div> </div> <div class='container-fluid'> <div class='row-fluid'> <div class='span8' id='content'> <ul class="breadcrumb" itemprop="breadcrumb"><li><a href="60.html">xbox live error 80151011</a> /</li> <li><a href="40.html">xanadu nj snow park</a> /</li> <li><a href="107.html">xx raul armenteros nude</a> /</li> <li><p><a href="http://www.slate.com/articles/technology/the_browser/2007/01/the_camera_phone.html" target="new">When camera phones attack. - Slate Magazine</a><div>Jan 17, 2007 . One representative example: Sportscaster Sean Salisbury was . a touch of media hysteria, you can certainly find disturbing videos on YouTube. . Peeping Toms quickly realized the potential for upskirt pics and shower-room souvenirs. . In Saudi Arabia, women have been taking pictures of other women .</div><span>http://www.slate.com/articles/technology/the_browser/2007/01/the_camera_phone.html</span></p></li></ul> <div class='video' itemscope itemtype='http://schema.org/VideoObject'> <div class='page-header'> <h1><p><a href="http://article.wn.com/view/2012/09/27/Alleged_Peeping_Tom_Arrested_in_Fontana/" target="new">Alleged &quot;Peeping Tom&quot; Arrested in Fontana - Worldnews.com</a><div>Sep 27, 2012 . Playlist for Jane Eyre by <NAME>&euml;: www.youtube.com <NAME> free audiobook . Upskirt Police officer arrested for using cell phone in Macy&#39;s . BodyGal.com ===== Lawyers for sportscaster <NAME> have vowed to find . Doctor dresses up in drag, plants pinhole camera in women&#39;s restroom .</div><span>http://article.wn.com/view/2012/09/27/Alleged_Peeping_Tom_Arrested_in_Fontana/</span></p></h1> </div> <ul id='sharebar'> <li> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='box_count' data-send='false' data-show-faces='false' data-width='60'></div> </li> <li class='pinit'><a href="62.html" class="pin-it-button" count-layout="vertical" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="sterroizheizerth.gif"/></a></li> <li> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='tall'></div> </li> <li> <a href="index.html">home</a> </li> <li class='comments'> <div class='count comment_count'>1</div> <a href="248.html">young teen bbs gateway</a> </li> </ul> <div class='sharebarx' style="display:none;"> <ul> <li class='facebook'> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='medium'></div> </li> <li class='twitter'> <a href="1.html">www.urfreeoffer.com/burkeburke</a> </li> <li class='pinterest'><a href="344.html" class="pin-it-button" count-layout="horizontal" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="eevuassyaqundee.gif"/></a></li> <li class='comments'> <a href="408.html">zendaya colemans fake nude pics yovo,com</a> 1 </li> </ul> </div> <div class='thumbnail'> <div style="max-width:640px;max-height:459px;margin:0 auto;"> <img src="http://i.ytimg.com/vi/PVsAv5I9OCA/0.jpg" width="640" height="459" /> </div> <div class='caption' itemprop='description'><p><a href="http://www.dailymail.co.uk/news/article-2016557/Shoe-cam-suspect-William-Wright-pleads-guilty-filming-upskirt-videos.html" target="new">&#39;Shoe cam&#39; suspect William Wright pleads guilty to filming upskirt ...</a><div>Jul 19, 2011 . A Tennessee man who filmed thousands of women with a camera hidden . Cult YouTube gun channel boss found shot dead on rural. . All apologies: ESPN has said sorry to Miss Alabama 2012 after two of its sportscasters .</div><span>http://www.dailymail.co.uk/news/article-2016557/Shoe-cam-suspect-William-Wright-pleads-guilty-filming-upskirt-videos.html</span></p></div> <div class='rating-form' id='rating_7611' itemprop='aggregateRating' itemscope itemtype='http://schema.org/AggregateRating'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='inline-rating'><ul class="star-rating"><li class="current-rating" style="width:100%;">5.0 / 5.0</li><li><a href="42.html">xarelto coupons medicare part d</a></li> <li><a href="334.html">youtube yaqui alphabet</a></li> <li><a href="309.html">you tuberestos de janny rivera</a></li> <li><a href="233.html">young gymnastics slips accidental nudity tumblr</a></li> <li><a href="350.html">yugo car</a></li></ul></div> <br><p><a href="http://www.imdb.com/name/nm0124930/filmokey" target="new"><NAME> - Keywords</a><div>3, told-in-flashback. 3, topless-female-nudity . 2, female-archaeologist. 2, fire- breathing . 1, reference-to-youtube. 1, refugee . 1, sportscaster. 1, sprite . 1, upskirt. 1, vacation. 1, valet. 1, vampire-slayer. 1, van. 1, variety-show. 1, vault .</div><span>http://www.imdb.com/name/nm0124930/filmokey</span></p></div> </div> <br> <ul class='pager'> <li class='next'> <a href="328.html">youtube. videos mujeres con animales gratis</a> </li> </ul> Related Videos: <ul class='thumbnails'> <li class='span4'> <a href="142.html" class="thumbnail"><img alt="Brooke Burke Interview" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/medium_l/brooke-burke-interview.jpg" src="yssusarternotr.gif"/> <div class='caption'>youtube upskirt women sportscasters Burke Interview</div> </a></li> </ul> <div class="remove_padding"><div id="content_rectangle" itemscope itemtype="http://schema.org/WPAdBlock"> </div></div> Embed Code: <pre class='embed'><p><a href="http://www.youtube.com/watch?v=0H_FN0loW8I" target="new">athletic women in spanky shorts and sports bras - YouTube</a><div>May 13, 2009 . Female Sportscasters: Challenging a Male-Dominated Industryby . Ballet Dancer Upskirt - Funnyby hotladies2010359,532 views &middot; Sexy girl .</div><span>http://www.youtube.com/watch?v=0H_FN0loW8I</span></p> <p><a href="http://www.youtube.com/watch?v=NE6FXyMXE0k" target="new">voyeur of summer - YouTube</a><div>Jul 31, 2009. the summer of voyeurism, so look elsewhere for a sportscasting babe. there is much to . No panties in train Japan 2 upskirt voyeur Video Dailymotionby . Ultimate Beach Voyeur - Mature Women At Topless Beach Teaseby .</div><span>http://www.youtube.com/watch?v=NE6FXyMXE0k</span></p> <p><a href="http://www.youtube.com/watch?v=g_AmPqyYb0Q" target="new">VERY SEXY WOMEN!!!! (MUST SEE!!!) - YouTube</a><div>Apr 5, 2012 . Hidden camera cute girl voyeur upskirt sexy assby Howedes Hicks9,650 . Erin Andrews America&#39;s Sexiest Sportscaster in HDby Zaanannim327,996 views . Hot hidden cam nice upskirt women on street with sexy butts nice .</div><span>http://www.youtube.com/watch?v=g_AmPqyYb0Q</span></p></pre> <dl class='dl-horizontal'> <dt>Star:</dt> <dd> <a href="315.html">youtube stars nude fake</a> </dd> <dt>Related Videos:</dt> <dd><a href="314.html">you tube stacked inverted bob cuts</a></dd> <dt>Original Post:</dt> <dd itemprop='associatedArticle'><a href="150.html">xxx pussy dilatadas</a></dd> <dt>Uploaded by:</dt> <dd><a href="374.html"><NAME> college arrest</a></dd> <dt>Uploaded:</dt> <dd><time datetime="2012-11-08T00:00:00+00:00" itemprop="uploadDate">November 08, 2012</time></dd> <dt>Duration:</dt> <dd> <time datetime='PT3M9S' itemprop='duration'>189 seconds</time> </dd> </dl> <hr> <div id='comments'> <h3> Comments (1 Total) <a href="229.html">young flexible tumblr</a> </h3> <a href="299.html">youtube nephew tommy left my medicine</a> <div id='new_comment'> <form accept-charset="UTF-8" action="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/comments/" class="simple_form form-horizontal" data-remote="true" id="new_comment" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;"/><input name="authenticity_token" type="hidden" value="<KEY>="/></div> <div class='body'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <input name='page' type='hidden'> <input id="comment_parent_id" name="comment[parent_id]" type="hidden"/> <br> <p><p><a href="http://www.youtube.com/watch?v=AJW-uf2GFso" target="new">Upskirt on TV show - YouTube</a><div>Jul 9, 2006 . Guest star falling and giving us a great upskirt shot.</div><span>http://www.youtube.com/watch?v=AJW-uf2GFso</span></p></p> <div class='row-fluid'> <div class='span8'> <div class="control-group string optional"><label class="string optional control-label" for="comment_anon_name">Name</label><div class="controls"><input class="string optional" id="comment_anon_name" name="comment[anon_name]" size="50" type="text"/><p class="help-block">Your name will appear with your comment</p></div></div> <div class="control-group email optional"><label class="email optional control-label" for="comment_anon_email">Email</label><div class="controls"><input class="string email optional" id="comment_anon_email" name="comment[anon_email]" size="50" type="email"/><p class="help-block"><p><a href="http://www.top100lists.ca/funnyvideos.html" target="new">TOP 100 FUNNY VIDEOS of all-time - TOP 100 LISTS</a><div>UPSKIRTS/NIP SLIPS . TOP 99 ASKMENs MOST DESIRABLE WOMEN of 2011 . at Edmond&#39;s Sixth Grade Festival, Chance posted this video on YouTube and it . the true story of a truly old-school sportscaster who was well before his time.</div><span>http://www.top100lists.ca/funnyvideos.html</span></p></p></div></div> </div> <div class='span4 providers'> <a href="339.html">yovodude</a> <br> <a href="43.html">xarelto coupons with insurance coverage</a> <br> <a href="165.html">xxx with sunakshi</a> <br> </div> </div> <div class="control-group text optional"><label class="text optional control-label" for="comment_content">Content</label><div class="controls"><textarea class="text optional" cols="40" id="comment_content" name="comment[content]" rows="20" style="width:320px;height:80px"> </textarea></div></div> </div> <div class='form-actions'> <input class='btn cancel' href="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/#" style="display:none;" type='button' value='Cancel'> <input class="btn btn btn-primary" data-disable-with="Adding..." name="commit" type="submit" value="Add Comment"/> <br style="clear:both;"> </div> </form> </div> <div class='row-fluid'> <div class='span12'> <div class='comment' data-content='<EMAIL>' id='comment_403462' itemid='403462' itemprop='comment' itemscope itemtype='http://schema.org/UserComments'> <div class='comment_meta'> <div class='row-fluid'> <div class='span2'> <img alt="Avatar" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/missing/thumb/xavatar.png.pagespeed.ic.qjczMghcsC.jpg" style="float:left;margin-right:10px;" src="oiplitreendatwyv.gif"/> </div> <div class='span10'> <a href="236.html">young jodie sweetin naked pics</a> <div class='author' itemprop='creator'>medo</div> <div class='created_at'><time datetime="2012-11-09T02:10:23-05:00" itemprop="commentTime"><p><a href="http://article.wn.com/view/2012/09/17/Kathie_Lee_Gifford_Tears_Up_Over_Today_Hosts_Support_For_Her/" target="new"><NAME> Tears Up Over &#39;Today&#39; Hosts&#39; Support For Her ...</a><div>Sep 17, 2012 . SUBSCRIBE NOW: www.youtube.com . <NAME> - Upskirt . of life at home with her sportscaster husband and their two children: <NAME> . women journalists Category:Christian religion-related songwriters .</div><span>http://article.wn.com/view/2012/09/17/Kathie_Lee_Gifford_Tears_Up_Over_Today_Hosts_Support_For_Her/</span></p></time></div> </div> </div> </div> <div class='alert alert-message error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='comment_body'> <div class='content'> <p itemprop='commentText'><EMAIL></p> </div> </div> <div class='form-actions'> </div> <div class='reply_holder'> </div> </div> </div> </div> </div> </div> </div> <div class='span4' id='sidebar' itemscope itemtype='http://schema.org/WPSideBar'> <div id='sidebar_rectangle' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="257.html">youth extra large ayton fleece hooded jacket coat yxl hoody reviews</a></h4> <div class='clearfix' itemscope itemtype='http://schema.org/Person'> <a href="202.html" itemprop="image"><img alt="<NAME>" class="pull-left" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-nude.jpg.pagespeed.ic.Yp5z6xqFnh.jpg" style="margin-right:10px;" src="itridyotwiboocay.gif"/></a><p><a href="http://www.dailymail.co.uk/sciencetech/article-2207552/Reddit-message-board-r-creepshots-posts-photos-normal-women-taken-unawares.html" target="new">Reddit message board r/ creepshots posts photos of normal women ...</a><div>Sep 23, 2012 . Most focus on the buttocks or breasts of non-consenting women going about their daily . who has posted a variety of &#39;upskirt&#39; images, says he is a teacher . Cult YouTube gun channel boss found shot dead on rural. . All apologies: ESPN has said sorry to Miss Alabama 2012 after two of its sportscasters .</div><span>http://www.dailymail.co.uk/sciencetech/article-2207552/Reddit-message-board-r-creepshots-posts-photos-normal-women-taken-unawares.html</span></p><dl> <dt>Born</dt> <dd itemprop='birthDate'><time datetime="1971-09-08T00:00:00+00:00">September 08, 1971</time></dd> <dt>Full Name</dt> <dd itemprop='name'>youtube upskirt women sportscasters Burke</dd> </dl> </div> </div> <div class='widget'> <h4><a href="81.html">xmas pay rise sex game playthrough</a></h4> <ul class='nav'> <li> <a href="24.html" class="clearfix"><img alt="Brooke Burke Prepares For Cancer Surgery" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" style="margin:0 10px 0 0;float:left;" src="yohtepeeqy.gif"/> youtube upskirt women sportscasters Burke Prepares For Cancer Surgery </a></li> <li> <a href="357.html" class="clearfix"><img alt="Brooke Burke Has Thyroid Cancer" class="span3" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/thumb/brooke-burke-charvet-cancer-me.jpg" style="margin:0 10px 0 0;float:left;" src="gawyasuv.gif"/> youtube upskirt women sportscasters Burke Has Thyroid Cancer </a></li> <li> <a href="320.html" class="clearfix"><img alt="Brooke Burke Charvet Releases New Lingerie Line" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" style="margin:0 10px 0 0;float:left;" src="kourtoujendoaple.gif"/> youtube upskirt women sportscasters Burke Charvet Releases New Lingerie Line </a></li> </ul> </div> <div id='skyscraper' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="152.html">xxx.sex girl amy roloff</a></h4> <ul class='thumbnails'> <li class='span4'> <a href="319.html" class="thumbnail"><img alt="Brooke Burke, Cancer Treatment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" src="utayploji.gif"/> </a></li> <li class='span4'> <a href="95.html" class="thumbnail"><img alt="Brooke Burke-Charvet Photo" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-charvet-photo.jpg.pagespeed.ic.eZcSwfCk1Z.jpg" src="treiwhoxu.gif"/> </a></li> <li class='span4'> <a href="264.html" class="thumbnail"><img alt="Brooke Burke Lingerie Line" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" src="wyalegualaf.gif"/> </a></li> <li class='span4'> <a href="358.html" class="thumbnail"><img alt="<NAME> and <NAME>" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-and-david-charvet.jpg.pagespeed.ic.iLiOSmNBgG.jpg" src="thywayhtyoch.gif"/> </a></li> <li class='span4'> <a href="372.html" class="thumbnail"><img alt="Brooke and Tom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-and-tom.jpg.pagespeed.ic.OfTSSeJdAZ.jpg" src="yokaywhyodooliwy.gif"/> </a></li> <li class='span4'> <a href="237.html" class="thumbnail"><img alt="The Naked Mom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/the-naked-mom.jpg.pagespeed.ce.2HxOs_fRpY.jpg" src="ooxoukynuakeyfoi.gif"/> </a></li> </ul> </div> <div class='widget'> <h4>Blog Archives</h4> <ul class='nav'> <li><a href="224.html">young brook shields naked in videp caps</a></li> <li><a href="250.html">younv jailbait nonude model</a></li> <li><a href="347.html">y su novia fakes</a></li> <li><a href="391.html">zastava m85 pv 5.56 .223 pistol ak-47 in 223</a></li> <li><a href="91.html">xoskeleton watch for sale craigslist</a></li> <li><a href="43.html">xarelto coupons with insurance coverage</a></li> <li><a href="377.html">zander identify theft vs. lifelock</a></li> <li><a href="320.html">youtube upskirt women sportscasters</a></li> </ul> </div> </div> </div> <div id='footer' itemscope itemtype='http://schema.org/WPFooter'> <div class='remove_padding'> <div id='footer_leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> </div> <p><p><a href="http://www.dailymail.co.uk/news/article-2239989/Perverted-engineer-filmed-skirts-1-000-women-supermarkets-train-stations-banned-owning-camera.html" target="new">Perverted engineer &#39;who filmed up the skirts of 1,000 women in ...</a><div>Nov 28, 2012 . Police believe the upskirt video clips found on several cameras and . Cult YouTube gun channel boss found shot dead on rural. . All apologies: ESPN has said sorry to Miss Alabama 2012 after two of its sportscasters .</div><span>http://www.dailymail.co.uk/news/article-2239989/Perverted-engineer-filmed-skirts-1-000-women-supermarkets-train-stations-banned-owning-camera.html</span></p></p> <p> <a href="335.html">you tuve mujeres cojiendo con perros gran dames</a> | <a href="156.html">xxx sexxxy pics of jacqueline pennewill</a> | <a href="144.html">xxx nude madhori,katrina,karishma pics fock photos</a> | <a href="365.html">yutu mujeres cojiendo</a> </p> <p>&copy; 2013 The Hollywood Gossip - Celebrity Gossip and Entertainment News</p> <p><a href="61.html" rel="nofollow"><img alt="Sheknows-entertainment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xsheknows-entertainment-0dfb1ed120378c4d8a98720390d31272.png.pagespeed.ic.841FJHTKbK.png" src="xerxozheethrey.gif"/></a></p> </div> </div> <img height="1" width="1" pagespeed_lazy_src="http://tags.bluekai.com/site/3113" alt="" src="rtuagoutrewhoizu.gif"/> </div> </body> </html> <file_sep>/* Links * http://dahufileguco.github.com/1.html * http://dahufileguco.github.com/2.html * http://dahufileguco.github.com/3.html * http://dahufileguco.github.com/4.html * http://dahufileguco.github.com/5.html * http://dahufileguco.github.com/6.html * http://dahufileguco.github.com/7.html * http://dahufileguco.github.com/8.html * http://dahufileguco.github.com/10.html * http://dahufileguco.github.com/11.html */ package abc <file_sep><!DOCTYPE html> <html id='en' lang='en'> <head> <title>xxx photos of sonakshi sinha</title> <link href="ssoistoineypoagh.css" media="screen" rel="stylesheet" type="text/css"/> <link href="oopeinyroon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon"/> <link href="ouzeelouhtootw.jpg" rel='apple-touch-icon' sizes='144x144'> <link href="eytreyhoisefoaht.jpg" rel='apple-touch-icon' sizes='114x114'> <link href="ndyajeyssepuatr.jpg" rel='apple-touch-icon' sizes='72x72'> <link href="eychoopyatya.jpg" rel='apple-touch-icon'> <script type='text/javascript' src='eyzeywyazuneyhi.js'></script></head> <body itemscope itemtype='http://schema.org/WebPage'> <div id='header'> <div class='social visible-desktop'> <ul> <li class='twitter'><a href="221.html">yougotposted videos</a></li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com' data-size='medium'></div> </li> <li class='facebook'> <div class='fb-like' data-href='http://www.facebook.com/thehollywoodgossip' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> </ul> </div> <div id='banner'> <a href="414.html"><img alt="The Hollywood Gossip" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xheader-7629f5d243c1cdc904bf535b05ff849f.jpg.pagespeed.ic.CDQOMwZhbJ.jpg" src="stawhaghoix.gif"/></a> </div> <div class='sites visible-desktop'> <a href="281.html">youtube el hijo de jenni rivera</a> | <a href="327.html">youtube videos escandalos caseros pornos</a> | <a href="407.html">zendaya coleman nude pics gag reports</a> </div> <div class='login visible-desktop'> <a href="220.html">yougotposted video</a> &nbsp;|&nbsp; <a href="373.html">zach nichols naked tumbler</a> </div> </div> <div id='wrapper'> <div class='remove_padding'> <div id='leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='navbar' itemscope itemtype='http://schema.org/WPHeader'> <div class='navbar-inner'> <div class='container-fluid'> <a href="385.html">zara girls</a> <div class='nav-collapse'> <ul class='nav'> <li class=''><a href="84.html">xnxxanna nicole smith fucking</a></li> <li class=''><a href="156.html">xxx sexxxy pics of jacqueline pennewill</a></li> <li class=''><a href="171.html">yahoo server unavailable iphone 5</a></li> <li class=''><a href="166.html">xxx wwe aj sex movie.nat</a></li> <li class=''><a href="391.html">zastava m85 pv 5.56 .223 pistol ak-47 in 223</a></li> <li class=''><a href="39.html">xacyfex.github.com las-mujeres-mas-peludas-de-la-panocha.html</a></li> <li class=''><a href="212.html">yougotposted asian</a></li> <li class=''><a href="157.html">xxx sexy katrina kaif sunny leone photos</a></li> <li class='login hidden-desktop'><a href="144.html">xxx nude madhori,katrina,karishma pics fock photos</a></li> <li class='login hidden-desktop'><a href="400.html">zastava pap m92 pv pistol, cal. 7.62x39mm</a></li> </ul> <form action="http://www.thehollywoodgossip.com/search" class='navbar-form pull-right'> <input class="input-medium" id="q" name="q" placeholder="Search" type="search"/> <button class="btn" type="submit"></button> </form> </div> </div> </div> </div> </div> <div class='container-fluid'> <div class='row-fluid'> <div class='span8' id='content'> <ul class="breadcrumb" itemprop="breadcrumb"><li><a href="393.html">zastava m92 hand guard sale</a> /</li> <li><a href="316.html">you tube strugis booty 2012</a> /</li> <li><a href="419.html">zima neon sign</a> /</li> <li><p><a href="http://torrentz.eu/so/sonakshi+sinha+boobs+photos-q" target="new">Download sonakshi sinha boobs photos torrent</a><div>Sponsored Links for sonakshi sinha boobs photos. sonakshi .</div><span>http://torrentz.eu/so/sonakshi+sinha+boobs+photos-q</span></p></li></ul> <div class='video' itemscope itemtype='http://schema.org/VideoObject'> <div class='page-header'> <h1><p><a href="http://torrentz.eu/so/sonakshi+sinha+photos+sex-q" target="new">Download sonakshi sinha photos sex torrent</a><div>Sponsored Links for sonakshi sinha photos sex. sonakshi sinha .</div><span>http://torrentz.eu/so/sonakshi+sinha+photos+sex-q</span></p></h1> </div> <ul id='sharebar'> <li> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='box_count' data-send='false' data-show-faces='false' data-width='60'></div> </li> <li class='pinit'><a href="23.html" class="pin-it-button" count-layout="vertical" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="sterroizheizerth.gif"/></a></li> <li> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='tall'></div> </li> <li> <a href="355.html">yugo pap m85pv review</a> </li> <li class='comments'> <div class='count comment_count'>1</div> <a href="3.html">www.usps.com/insurance/online.htm</a> </li> </ul> <div class='sharebarx' style="display:none;"> <ul> <li class='facebook'> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='medium'></div> </li> <li class='twitter'> <a href="292.html">youtube jp sauer and sohn suhl</a> </li> <li class='pinterest'><a href="178.html" class="pin-it-button" count-layout="horizontal" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="eevuassyaqundee.gif"/></a></li> <li class='comments'> <a href="256.html">your dog been neutered by r<NAME>iley</a> 1 </li> </ul> </div> <div class='thumbnail'> <div style="max-width:640px;max-height:459px;margin:0 auto;"> <img src="http://www.shotpix.com/images/36549324057371847157.png" width="640" height="459" /> </div> <div class='caption' itemprop='description'><p><a href="http://torrentz.eu/so/sonakshi+sinha++xxx-q" target="new">Download sonakshi sinha xxx torrent</a><div>Sponsored Links for sonakshi sinha xxx. sonakshi sinha xxx .</div><span>http://torrentz.eu/so/sonakshi+sinha++xxx-q</span></p></div> <div class='rating-form' id='rating_7611' itemprop='aggregateRating' itemscope itemtype='http://schema.org/AggregateRating'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='inline-rating'><ul class="star-rating"><li class="current-rating" style="width:100%;">5.0 / 5.0</li><li><a href="index.html">home</a></li> <li><a href="102.html">xvideos jovencitas 18 años para movil descarga gratis</a></li> <li><a href="274.html">youtube cute hair braiding styles in st.louis,mo</a></li> <li><a href="217.html">yougotposted tiffany bannister</a></li> <li><a href="2.html">www.usbankingonline</a></li></ul></div> <br><p><a href="http://torrentz.eu/so/sonakshi+sinha+nude+fakes+pics++-q" target="new">Download sonakshi sinha nude fakes pics torrent</a><div>Sponsored Links for sonakshi sinha nude fakes pics. sonakshi .</div><span>http://torrentz.eu/so/sonakshi+sinha+nude+fakes+pics++-q</span></p></div> </div> <br> <ul class='pager'> <li class='next'> <a href="183.html">yarel ramos porn</a> </li> </ul> Related Videos: <ul class='thumbnails'> <li class='span4'> <a href="126.html" class="thumbnail"><img alt="Brooke Burke Interview" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/medium_l/brooke-burke-interview.jpg" src="yssusarternotr.gif"/> <div class='caption'>xxx photos of sonakshi sinha Burke Interview</div> </a></li> </ul> <div class="remove_padding"><div id="content_rectangle" itemscope itemtype="http://schema.org/WPAdBlock"> </div></div> Embed Code: <pre class='embed'><p><a href="http://www.egydown.com/gx/sonakshi+sinha+sex+xxx+video+3gp+free+download.html" target="new">sonakshi sinha sex xxx video 3gp free download Megaupload ...</a><div>Results 1 - 20 . We recommend you to download sonakshi sinha sex xxx video 3gp free download from the . http://www.free-media-converter.com/images/ .</div><span>http://www.egydown.com/gx/sonakshi+sinha+sex+xxx+video+3gp+free+download.html</span></p> <p><a href="http://torrentz.cd/9de9c48dd2cb5532a801653c7b8e065377da53e6/Indian-Beautiful-Actress-Sonakshi-Sinha-Pictures-Pack-1-.torrent" target="new">Indian Beautiful Actress Sonakshi Sinha Pictures [Pack 1 - Torrent</a><div>Related. sonakshi sinha pics bit, sonakshi sinha, indian bollywood girl sonakshi sinha xxx picher, bollywood.sonaksi.sina.xxx, www.xxxpicher bolybood.com, .</div><span>http://torrentz.cd/9de9c48dd2cb5532a801653c7b8e065377da53e6/Indian-Beautiful-Actress-Sonakshi-Sinha-Pictures-Pack-1-.torrent</span></p></pre> <dl class='dl-horizontal'> <dt>Star:</dt> <dd> <a href="197.html">yolanda foster doing leg squats, arms out like shooting a gun</a> </dd> <dt>Related Videos:</dt> <dd><a href="19.html">www. x hindi antarvasna kahani video</a></dd> <dt>Original Post:</dt> <dd itemprop='associatedArticle'><a href="206.html">yotubesexo doble penetracion</a></dd> <dt>Uploaded by:</dt> <dd><a href="210.html">you got posred/tiff banister</a></dd> <dt>Uploaded:</dt> <dd><time datetime="2012-11-08T00:00:00+00:00" itemprop="uploadDate">November 08, 2012</time></dd> <dt>Duration:</dt> <dd> <time datetime='PT3M9S' itemprop='duration'>189 seconds</time> </dd> </dl> <hr> <div id='comments'> <h3> Comments (1 Total) <a href="161.html">xxx videos 3gp menores streaming gratis</a> </h3> <a href="167.html">xyooj aviaries</a> <div id='new_comment'> <form accept-charset="UTF-8" action="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/comments/" class="simple_form form-horizontal" data-remote="true" id="new_comment" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;"/><input name="authenticity_token" type="hidden" value="<KEY>="/></div> <div class='body'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <input name='page' type='hidden'> <input id="comment_parent_id" name="comment[parent_id]" type="hidden"/> <br> <p><p><a href="http://torrentz.eu/so/sonakshi+sinha+nude+images-q" target="new">Download sonakshi sinha nude images torrent</a><div>Sponsored Links for sonakshi sinha nude images. sonakshi .</div><span>http://torrentz.eu/so/sonakshi+sinha+nude+images-q</span></p></p> <div class='row-fluid'> <div class='span8'> <div class="control-group string optional"><label class="string optional control-label" for="comment_anon_name">Name</label><div class="controls"><input class="string optional" id="comment_anon_name" name="comment[anon_name]" size="50" type="text"/><p class="help-block">Your name will appear with your comment</p></div></div> <div class="control-group email optional"><label class="email optional control-label" for="comment_anon_email">Email</label><div class="controls"><input class="string email optional" id="comment_anon_email" name="comment[anon_email]" size="50" type="email"/><p class="help-block"><p><a href="http://torrentz.cd/31719993770057bada52cddecd4076d748e0ec99/Indian-Beautiful-Actress-Sonakshi-Sinha-Pictures-Pack-2-.torrent" target="new">Indian Beautiful Actress Sonakshi Sinha Pictures [Pack 2 - Torrent</a><div>sonakshi sehna pussy picture download, sonikshi sinha open actor xxx photos, Indian Beautiful actress pussy, sonakshi indian actres xxx pics, sonakshi pussy .</div><span>http://torrentz.cd/31719993770057bada52cddecd4076d748e0ec99/Indian-Beautiful-Actress-Sonakshi-Sinha-Pictures-Pack-2-.torrent</span></p></p></div></div> </div> <div class='span4 providers'> <a href="145.html">xxx.photo indian actress download . in</a> <br> <a href="118.html">xxx chiquitas</a> <br> <a href="270.html">youtube.com/martha mccallum</a> <br> </div> </div> <div class="control-group text optional"><label class="text optional control-label" for="comment_content">Content</label><div class="controls"><textarea class="text optional" cols="40" id="comment_content" name="comment[content]" rows="20" style="width:320px;height:80px"> </textarea></div></div> </div> <div class='form-actions'> <input class='btn cancel' href="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/#" style="display:none;" type='button' value='Cancel'> <input class="btn btn btn-primary" data-disable-with="Adding..." name="commit" type="submit" value="Add Comment"/> <br style="clear:both;"> </div> </form> </div> <div class='row-fluid'> <div class='span12'> <div class='comment' data-content='<EMAIL>' id='comment_403462' itemid='403462' itemprop='comment' itemscope itemtype='http://schema.org/UserComments'> <div class='comment_meta'> <div class='row-fluid'> <div class='span2'> <img alt="Avatar" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/missing/thumb/xavatar.png.pagespeed.ic.qjczMghcsC.jpg" style="float:left;margin-right:10px;" src="oiplitreendatwyv.gif"/> </div> <div class='span10'> <a href="151.html">xxx.sex amy roloff</a> <div class='author' itemprop='creator'>medo</div> <div class='created_at'><time datetime="2012-11-09T02:10:23-05:00" itemprop="commentTime"><p><a href="http://torrentz.eu/so/sonakshi+sinha+nude+photo+-q" target="new">Download sonakshi sinha nude photo torrent</a><div>Sponsored Links for sonakshi sinha nude photo. sonakshi .</div><span>http://torrentz.eu/so/sonakshi+sinha+nude+photo+-q</span></p></time></div> </div> </div> </div> <div class='alert alert-message error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='comment_body'> <div class='content'> <p itemprop='commentText'><EMAIL></p> </div> </div> <div class='form-actions'> </div> <div class='reply_holder'> </div> </div> </div> </div> </div> </div> </div> <div class='span4' id='sidebar' itemscope itemtype='http://schema.org/WPSideBar'> <div id='sidebar_rectangle' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="281.html">youtube el hijo de jenni rivera</a></h4> <div class='clearfix' itemscope itemtype='http://schema.org/Person'> <a href="283.html" itemprop="image"><img alt="<NAME>" class="pull-left" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-nude.jpg.pagespeed.ic.Yp5z6xqFnh.jpg" style="margin-right:10px;" src="itridyotwiboocay.gif"/></a><p><a href="http://torrentz.eu/nu/nude+bollywood+actress+photo+sonakshi+sinha-q" target="new">Download nude bollywood actress photo sonakshi sinha torrent</a><div>Indian Beautiful Actress Sonakshi Sinha Pictures Pack 2 &raquo; images: 4?4 . Bollywood Actress Sherlyn Chopra Playboy November 2012 Sneak P &raquo; xxx: 4?4 .</div><span>http://torrentz.eu/nu/nude+bollywood+actress+photo+sonakshi+sinha-q</span></p><dl> <dt>Born</dt> <dd itemprop='birthDate'><time datetime="1971-09-08T00:00:00+00:00">September 08, 1971</time></dd> <dt>Full Name</dt> <dd itemprop='name'>xxx photos of sonakshi sinha Burke</dd> </dl> </div> </div> <div class='widget'> <h4><a href="32.html">www youtuve hiroin anuska shrma nangi phto</a></h4> <ul class='nav'> <li> <a href="104.html" class="clearfix"><img alt="Brooke Burke Prepares For Cancer Surgery" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" style="margin:0 10px 0 0;float:left;" src="yohtepeeqy.gif"/> xxx photos of sonakshi sinha Burke Prepares For Cancer Surgery </a></li> <li> <a href="107.html" class="clearfix"><img alt="Brooke Burke Has Thyroid Cancer" class="span3" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/thumb/brooke-burke-charvet-cancer-me.jpg" style="margin:0 10px 0 0;float:left;" src="gawyasuv.gif"/> xxx photos of sonakshi sinha Burke Has Thyroid Cancer </a></li> <li> <a href="136.html" class="clearfix"><img alt="Brooke Burke Charvet Releases New Lingerie Line" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" style="margin:0 10px 0 0;float:left;" src="kourtoujendoaple.gif"/> xxx photos of sonakshi sinha Burke Charvet Releases New Lingerie Line </a></li> </ul> </div> <div id='skyscraper' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="92.html">xoxo watch instructions</a></h4> <ul class='thumbnails'> <li class='span4'> <a href="173.html" class="thumbnail"><img alt="Brooke Burke, Cancer Treatment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" src="utayploji.gif"/> </a></li> <li class='span4'> <a href="353.html" class="thumbnail"><img alt="Brooke Burke-Charvet Photo" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-charvet-photo.jpg.pagespeed.ic.eZcSwfCk1Z.jpg" src="treiwhoxu.gif"/> </a></li> <li class='span4'> <a href="298.html" class="thumbnail"><img alt="Brooke Burke Lingerie Line" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" src="wyalegualaf.gif"/> </a></li> <li class='span4'> <a href="248.html" class="thumbnail"><img alt="Brooke Burke and David Charvet" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-and-david-charvet.jpg.pagespeed.ic.iLiOSmNBgG.jpg" src="thywayhtyoch.gif"/> </a></li> <li class='span4'> <a href="179.html" class="thumbnail"><img alt="Brooke and Tom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-and-tom.jpg.pagespeed.ic.OfTSSeJdAZ.jpg" src="yokaywhyodooliwy.gif"/> </a></li> <li class='span4'> <a href="297.html" class="thumbnail"><img alt="The Naked Mom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/the-naked-mom.jpg.pagespeed.ce.2HxOs_fRpY.jpg" src="ooxoukynuakeyfoi.gif"/> </a></li> </ul> </div> <div class='widget'> <h4>Blog Archives</h4> <ul class='nav'> <li><a href="320.html">youtube upskirt women sportscasters</a></li> <li><a href="23.html">www xxx hot sexy nangi picture com</a></li> <li><a href="259.html">you tube antarvasna dot com</a></li> <li><a href="130.html">xxxfunny.mobi</a></li> <li><a href="59.html">xbox live codes</a></li> <li><a href="237.html">young latina jailbait pics</a></li> <li><a href="89.html">xnxx unlimited pron mubi</a></li> <li><a href="377.html">zander identify theft vs. lifelock</a></li> </ul> </div> </div> </div> <div id='footer' itemscope itemtype='http://schema.org/WPFooter'> <div class='remove_padding'> <div id='footer_leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> </div> <p><p><a href="http://torrentz.eu/so/sonakshi+sinha+blue+film-q" target="new">Download sonakshi sinha blue film torrent</a><div>Sponsored Links for sonakshi sinha blue film. sonakshi sinha .</div><span>http://torrentz.eu/so/sonakshi+sinha+blue+film-q</span></p></p> <p> <a href="13.html">www.web.pjaave.sixe.vedio.in</a> | <a href="181.html">yaqui guerrido en tangas</a> | <a href="131.html">xxx gratis para descargar violadas</a> | <a href="181.html">yaqui guerrido en tangas</a> </p> <p>&copy; 2013 The Hollywood Gossip - Celebrity Gossip and Entertainment News</p> <p><a href="18.html" rel="nofollow"><img alt="Sheknows-entertainment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xsheknows-entertainment-0dfb1ed120378c4d8a98720390d31272.png.pagespeed.ic.841FJHTKbK.png" src="xerxozheethrey.gif"/></a></p> </div> </div> <img height="1" width="1" pagespeed_lazy_src="http://tags.bluekai.com/site/3113" alt="" src="rtuagoutrewhoizu.gif"/> </div> </body> </html> <file_sep><!DOCTYPE html> <html id='en' lang='en'> <head> <title>yolanda foster doing leg squats, arms out like shooting a gun</title> <link href="ssoistoineypoagh.css" media="screen" rel="stylesheet" type="text/css"/> <link href="oopeinyroon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon"/> <link href="ouzeelouhtootw.jpg" rel='apple-touch-icon' sizes='144x144'> <link href="eytreyhoisefoaht.jpg" rel='apple-touch-icon' sizes='114x114'> <link href="ndyajeyssepuatr.jpg" rel='apple-touch-icon' sizes='72x72'> <link href="eychoopyatya.jpg" rel='apple-touch-icon'> <script type='text/javascript' src='eyzeywyazuneyhi.js'></script></head> <body itemscope itemtype='http://schema.org/WebPage'> <div id='header'> <div class='social visible-desktop'> <ul> <li class='twitter'><a href="193.html">ynuproon hub</a></li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com' data-size='medium'></div> </li> <li class='facebook'> <div class='fb-like' data-href='http://www.facebook.com/thehollywoodgossip' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> </ul> </div> <div id='banner'> <a href="333.html"><img alt="The Hollywood Gossip" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xheader-7629f5d243c1cdc904bf535b05ff849f.jpg.pagespeed.ic.CDQOMwZhbJ.jpg" src="stawhaghoix.gif"/></a> </div> <div class='sites visible-desktop'> <a href="354.html">yugo pap m85pv pistol, krinkov style pistol, 5.56x45mm, zastava serbia</a> | <a href="79.html">xl yacht insurance</a> | <a href="210.html">you got posred/tiff banister</a> </div> <div class='login visible-desktop'> <a href="390.html">zastava m85pv 223 5.56 hg3088-n ak-47</a> &nbsp;|&nbsp; <a href="207.html">you can print this blank stat sheet by doing an image google search on</a> </div> </div> <div id='wrapper'> <div class='remove_padding'> <div id='leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='navbar' itemscope itemtype='http://schema.org/WPHeader'> <div class='navbar-inner'> <div class='container-fluid'> <a href="356.html">yugo pap sbr</a> <div class='nav-collapse'> <ul class='nav'> <li class=''><a href="102.html">xvideos jovencitas 18 años para movil descarga gratis</a></li> <li class=''><a href="349.html">yugo</a></li> <li class=''><a href="119.html">xxx comic rich bitch #2: public toy</a></li> <li class=''><a href="395.html">zastava pap 92 to buy</a></li> <li class=''><a href="52.html">xbox 80151011</a></li> <li class=''><a href="352.html">yugo m92/m85 26mm flash hider</a></li> <li class=''><a href="418.html">zillow rentals orange ca</a></li> <li class=''><a href="105.html">xvideos tahiry from love and hip hop</a></li> <li class='login hidden-desktop'><a href="259.html">you tube antarvasna dot com</a></li> <li class='login hidden-desktop'><a href="417.html">zillow rentals in tampa</a></li> </ul> <form action="http://www.thehollywoodgossip.com/search" class='navbar-form pull-right'> <input class="input-medium" id="q" name="q" placeholder="Search" type="search"/> <button class="btn" type="submit"></button> </form> </div> </div> </div> </div> </div> <div class='container-fluid'> <div class='row-fluid'> <div class='span8' id='content'> <ul class="breadcrumb" itemprop="breadcrumb"><li><a href="260.html">youtube bideos xxx de chicas birjenes</a> /</li> <li><a href="381.html">zara 666 opening</a> /</li> <li><a href="51.html">xbox 360 voice changer headset</a> /</li> <li><p><a href="http://article.wn.com/view/2011/08/22/Bruker_Launches_D8_QUEST_and_D8_VENTURE_Crystallography_Syst_u/" target="new">Bruker Launches D8 QUEST and D8 VENTURE Crystallography ...</a><div>Aug 22, 2011 . Check out the photos from this shoot at: . to his arms in one workout <NAME>va built arms bigger than his head and legs bigger than his . times Find out what High Intensity Training can do for you Announcing the release . Boyer Coe @ Nautilus headquarters on the Duo-Squat. . photo: WN / Yolanda .</div><span>http://article.wn.com/view/2011/08/22/Bruker_Launches_D8_QUEST_and_D8_VENTURE_Crystallography_Syst_u/</span></p></li></ul> <div class='video' itemscope itemtype='http://schema.org/VideoObject'> <div class='page-header'> <h1><p><a href="http://article.wn.com/view/2012/06/04/Bodybuilding_The_benefits_of_taking_a_break_from_training_pa_f/" target="new">Bodybuilding: The benefits of taking a break from training - part 2 ...</a><div>Jun 4, 2012 . for more on this topic www.2buildmusclefast.com www.2buildmusclefast.com BE SURE TO CHECK OUT ALL OUR VIDEOS IM SURE THE .</div><span>http://article.wn.com/view/2012/06/04/Bodybuilding_The_benefits_of_taking_a_break_from_training_pa_f/</span></p></h1> </div> <ul id='sharebar'> <li> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='box_count' data-send='false' data-show-faces='false' data-width='60'></div> </li> <li class='pinit'><a href="62.html" class="pin-it-button" count-layout="vertical" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="sterroizheizerth.gif"/></a></li> <li> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='tall'></div> </li> <li> <a href="134.html">xxx images of nangi girl</a> </li> <li class='comments'> <div class='count comment_count'>1</div> <a href="362.html">yurt rentals in hawai</a> </li> </ul> <div class='sharebarx' style="display:none;"> <ul> <li class='facebook'> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='medium'></div> </li> <li class='twitter'> <a href="238.html">young lolita nude</a> </li> <li class='pinterest'><a href="240.html" class="pin-it-button" count-layout="horizontal" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="eevuassyaqundee.gif"/></a></li> <li class='comments'> <a href="219.html">you got posted tiff bannister</a> 1 </li> </ul> </div> <div class='thumbnail'> <div style="max-width:640px;max-height:459px;margin:0 auto;"> <img src="http://i.ytimg.com/vi/lzSJOUkirzM/0.jpg" width="640" height="459" /> </div> <div class='caption' itemprop='description'><p><a href="http://article.wn.com/view/2012/07/20/London_2012_Team_GB_suffer_warmup_loss_to_Brazil/" target="new">London 2012: Team GB suffer warm-up loss to Brazil - Worldnews.com</a><div>Jul 20, 2012 . Sandro&#39;s early goal out Brazil in control, before <NAME> fouled Hulk to allow Naymar to double his team&#39;s advantage from the spot....</div><span>http://article.wn.com/view/2012/07/20/London_2012_Team_GB_suffer_warmup_loss_to_Brazil/</span></p></div> <div class='rating-form' id='rating_7611' itemprop='aggregateRating' itemscope itemtype='http://schema.org/AggregateRating'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='inline-rating'><ul class="star-rating"><li class="current-rating" style="width:100%;">5.0 / 5.0</li><li><a href="17.html">www wwe rock vs brock lesnar full video com</a></li> <li><a href="234.html">young jailbait models</a></li> <li><a href="116.html">xxx aunty saree removing with fuke on peperonity</a></li> <li><a href="140.html">xxx nakked animals fukking bollywood babes</a></li> <li><a href="154.html">xxx sexi nude pose foto from sonaxi shinha.</a></li></ul></div> <br><p><a href="http://www.insidebayarea.com/breaking-news" target="new">Breaking News - Inside Bay Area</a><div>Two shot, one in critical condition after East Oakland shooting . never know it from the Razzie nominations singling out Hollywood&#39;s worst of the year. . particularly plans to do pile driving for new overpasses at Davis Street and Marina . through their days, their lithe bodies sliding like liquid through the unlikeliest of places.</div><span>http://www.insidebayarea.com/breaking-news</span></p></div> </div> <br> <ul class='pager'> <li class='next'> <a href="75.html">ximena duque nude</a> </li> </ul> Related Videos: <ul class='thumbnails'> <li class='span4'> <a href="287.html" class="thumbnail"><img alt="Brooke Burke Interview" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/medium_l/brooke-burke-interview.jpg" src="yssusarternotr.gif"/> <div class='caption'>yolanda foster doing leg squats, arms out like shooting a gun Burke Interview</div> </a></li> </ul> <div class="remove_padding"><div id="content_rectangle" itemscope itemtype="http://schema.org/WPAdBlock"> </div></div> Embed Code: <pre class='embed'><p><a href="http://www.huffingtonpost.com/rebecca-shapiro/real-housewives-beverly-hills-war-rages_b_2317456.html" target="new"><NAME>: &#39;Real Housewives Of Beverly Hills&#39; Recap: The ...</a><div>Dec 18, 2012 . Spoiler alert: Do not read on if you haven&#39;t seen Season 3, Episode 7 of . that is Yolanda sprinting up her palatial staircase like a madwoman, doing better . strange pulsating squat-type-things with her arms stretched out in front of her. . her model daughter walk the runway and her butt and legs were &quot;so .</div><span>http://www.huffingtonpost.com/rebecca-shapiro/real-housewives-beverly-hills-war-rages_b_2317456.html</span></p> <p><a href="http://www.triangletribune.com/clientuploads/TTPDFs/tt090212B.pdf" target="new">Section B - The Triangle Tribune</a><div>Sep 9, 2012 . that&#39;s one of the things that attracted me here - open arms, . &#147;Teams like Wingate are play- . fensive back <NAME> rounded out the scoring with a 70-yard . Persons who speak Spanish and do not speak English, or have a . to shoot. Football Classic&#39;s 41st year; last season,. Morgan State took on .</div><span>http://www.triangletribune.com/clientuploads/TTPDFs/tt090212B.pdf</span></p></pre> <dl class='dl-horizontal'> <dt>Star:</dt> <dd> <a href="300.html">youtube nephew tommy prank calls uncut</a> </dd> <dt>Related Videos:</dt> <dd><a href="38.html">x3love.com</a></dd> <dt>Original Post:</dt> <dd itemprop='associatedArticle'><a href="251.html">youporn.com/nn preteen models</a></dd> <dt>Uploaded by:</dt> <dd><a href="306.html">youtube porn hud caliente</a></dd> <dt>Uploaded:</dt> <dd><time datetime="2012-11-08T00:00:00+00:00" itemprop="uploadDate">November 08, 2012</time></dd> <dt>Duration:</dt> <dd> <time datetime='PT3M9S' itemprop='duration'>189 seconds</time> </dd> </dl> <hr> <div id='comments'> <h3> Comments (1 Total) <a href="185.html">yegua folladas por hombres fotos</a> </h3> <a href="409.html">zendaya follando xxx</a> <div id='new_comment'> <form accept-charset="UTF-8" action="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/comments/" class="simple_form form-horizontal" data-remote="true" id="new_comment" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;"/><input name="authenticity_token" type="hidden" value="<KEY>="/></div> <div class='body'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <input name='page' type='hidden'> <input id="comment_parent_id" name="comment[parent_id]" type="hidden"/> <br> <p><p><a href="http://www.last.fm/music/Andy+Gibb/+journal" target="new"><NAME> Journals &#150; Last.fm</a><div>He overdosed himself too much of the nearly 100%-pure heroin to shoot up the third . Together with <NAME> and The Big Bopper, he flew out of the Mason City . After she told <NAME>&iacute;var that she could not be trusted anymore with . but after the last band played, he was feeling faint and couldn&#39;t feel his legs.</div><span>http://www.last.fm/music/Andy+Gibb/+journal</span></p></p> <div class='row-fluid'> <div class='span8'> <div class="control-group string optional"><label class="string optional control-label" for="comment_anon_name">Name</label><div class="controls"><input class="string optional" id="comment_anon_name" name="comment[anon_name]" size="50" type="text"/><p class="help-block">Your name will appear with your comment</p></div></div> <div class="control-group email optional"><label class="email optional control-label" for="comment_anon_email">Email</label><div class="controls"><input class="string email optional" id="comment_anon_email" name="comment[anon_email]" size="50" type="email"/><p class="help-block"><p><a href="http://www.island-life.net/back_issues/ISLANDLIFE2007b.htm" target="new">ISLAND LIFE: 2007B</a><div>But to carry out our duties, lets bolster Time&#39;s Deathwatch with our own. . His best-known books, like The Best and the Brightest (about the Vietnam War . Over at the Shoreline Squat, Marlene and Andre are gearing up for the New Years, . This nonsense has nothing to do with Measure A and everything to do with old .</div><span>http://www.island-life.net/back_issues/ISLANDLIFE2007b.htm</span></p></p></div></div> </div> <div class='span4 providers'> <a href="261.html">you tube bondage</a> <br> <a href="162.html">xxx videos de animales en 3gp</a> <br> <a href="16.html">www. wwe divas porn nude and naked pictures.</a> <br> </div> </div> <div class="control-group text optional"><label class="text optional control-label" for="comment_content">Content</label><div class="controls"><textarea class="text optional" cols="40" id="comment_content" name="comment[content]" rows="20" style="width:320px;height:80px"> </textarea></div></div> </div> <div class='form-actions'> <input class='btn cancel' href="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/#" style="display:none;" type='button' value='Cancel'> <input class="btn btn btn-primary" data-disable-with="Adding..." name="commit" type="submit" value="Add Comment"/> <br style="clear:both;"> </div> </form> </div> <div class='row-fluid'> <div class='span12'> <div class='comment' data-content='<EMAIL>' id='comment_403462' itemid='403462' itemprop='comment' itemscope itemtype='http://schema.org/UserComments'> <div class='comment_meta'> <div class='row-fluid'> <div class='span2'> <img alt="Avatar" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/missing/thumb/xavatar.png.pagespeed.ic.qjczMghcsC.jpg" style="float:left;margin-right:10px;" src="oiplitreendatwyv.gif"/> </div> <div class='span10'> <a href="205.html">yotubesexo.com/medias</a> <div class='author' itemprop='creator'>medo</div> <div class='created_at'><time datetime="2012-11-09T02:10:23-05:00" itemprop="commentTime"><p><a href="http://article.wn.com/view/2012/06/02/chris_hemsworth_diet_workout/" target="new">chris hemsworth diet workout - Worldnews.com</a><div>Jun 2, 2012 . <NAME> workout is mostly bodyweight exercises like push-ups, pull-ups, sit- ups, deadlifts, bench press and body squats done .</div><span>http://article.wn.com/view/2012/06/02/chris_hemsworth_diet_workout/</span></p></time></div> </div> </div> </div> <div class='alert alert-message error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='comment_body'> <div class='content'> <p itemprop='commentText'><EMAIL></p> </div> </div> <div class='form-actions'> </div> <div class='reply_holder'> </div> </div> </div> </div> </div> </div> </div> <div class='span4' id='sidebar' itemscope itemtype='http://schema.org/WPSideBar'> <div id='sidebar_rectangle' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="99.html">xvideos . com videos porno de niñas de 12 años de españa</a></h4> <div class='clearfix' itemscope itemtype='http://schema.org/Person'> <a href="index.html" itemprop="image"><img alt="<NAME>" class="pull-left" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-nude.jpg.pagespeed.ic.Yp5z6xqFnh.jpg" style="margin-right:10px;" src="itridyotwiboocay.gif"/></a><p><a href="http://members.tripod.com/fbb_fan/reviews.html" target="new">Fbb_fan&#39;s Female Bodybuilding Page</a><div>Jan 29, 1999 . If you would like to contribute a review, send me a message. . 306 - Yolanda Hughes / <NAME> . Her arms and legs both look incredible in the dress; the bikini . and there&#39;s another where they shot her doing her hair in a mirror. . I&#39; ll say one thing, though - she really filled out those fishnet tights .</div><span>http://members.tripod.com/fbb_fan/reviews.html</span></p><dl> <dt>Born</dt> <dd itemprop='birthDate'><time datetime="1971-09-08T00:00:00+00:00">September 08, 1971</time></dd> <dt>Full Name</dt> <dd itemprop='name'><NAME> doing leg squats, arms out like shooting a gun Burke</dd> </dl> </div> </div> <div class='widget'> <h4><a href="110.html">xxx 2012 con animales</a></h4> <ul class='nav'> <li> <a href="232.html" class="clearfix"><img alt="Brooke Burke Prepares For Cancer Surgery" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" style="margin:0 10px 0 0;float:left;" src="yohtepeeqy.gif"/> yolanda foster doing leg squats, arms out like shooting a gun Burke Prepares For Cancer Surgery </a></li> <li> <a href="78.html" class="clearfix"><img alt="Brooke Burke Has Thyroid Cancer" class="span3" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/thumb/brooke-burke-charvet-cancer-me.jpg" style="margin:0 10px 0 0;float:left;" src="gawyasuv.gif"/> yolanda foster doing leg squats, arms out like shooting a gun Burke Has Thyroid Cancer </a></li> <li> <a href="122.html" class="clearfix"><img alt="Brooke Burke Charvet Releases New Lingerie Line" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" style="margin:0 10px 0 0;float:left;" src="kourtoujendoaple.gif"/> yolanda foster doing leg squats, arms out like shooting a gun Burke Charvet Releases New Lingerie Line </a></li> </ul> </div> <div id='skyscraper' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="397.html">zastava pap m85 specs</a></h4> <ul class='thumbnails'> <li class='span4'> <a href="401.html" class="thumbnail"><img alt="Brooke Burke, Cancer Treatment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" src="utayploji.gif"/> </a></li> <li class='span4'> <a href="415.html" class="thumbnail"><img alt="Brooke Burke-Charvet Photo" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-charvet-photo.jpg.pagespeed.ic.eZcSwfCk1Z.jpg" src="treiwhoxu.gif"/> </a></li> <li class='span4'> <a href="148.html" class="thumbnail"><img alt="Brooke Burke Lingerie Line" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" src="wyalegualaf.gif"/> </a></li> <li class='span4'> <a href="188.html" class="thumbnail"><img alt="Broo<NAME> and <NAME>" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-and-david-charvet.jpg.pagespeed.ic.iLiOSmNBgG.jpg" src="thywayhtyoch.gif"/> </a></li> <li class='span4'> <a href="28.html" class="thumbnail"><img alt="<NAME>" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-and-tom.jpg.pagespeed.ic.OfTSSeJdAZ.jpg" src="yokaywhyodooliwy.gif"/> </a></li> <li class='span4'> <a href="392.html" class="thumbnail"><img alt="The Naked Mom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/the-naked-mom.jpg.pagespeed.ce.2HxOs_fRpY.jpg" src="ooxoukynuakeyfoi.gif"/> </a></li> </ul> </div> <div class='widget'> <h4>Blog Archives</h4> <ul class='nav'> <li><a href="141.html">xxx nangi video film</a></li> <li><a href="27.html">www.ybr.com/jnjbsc</a></li> <li><a href="110.html">xxx 2012 con animales</a></li> <li><a href="290.html">youtube/jessie duplantis piano</a></li> <li><a href="70.html">xerex pantasya stories download</a></li> <li><a href="251.html">youporn.com/nn preteen models</a></li> <li><a href="150.html">xxx pussy dilatadas</a></li> <li><a href="239.html">young lolita nudes</a></li> </ul> </div> </div> </div> <div id='footer' itemscope itemtype='http://schema.org/WPFooter'> <div class='remove_padding'> <div id='footer_leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> </div> <p><p><a href="http://article.wn.com/view/2012/08/03/Is_Boris_Johnson_serious_When_it_comes_to_No_10_the_answer_i/" target="new">Is <NAME> serious? When it comes to No 10, the answer is ...</a><div>Aug 3, 2012 . Like us on Facebook at www.facebook.com and follow us on Twitter at . Find out what Boris&#39; arch nemesis Ken Livingstone has to say about it . Report by <NAME>. . guards around the chain to prevent pants&#39; legs getting entangled. . we&#39; re with the Oxford Gun Company showing how shooting can .</div><span>http://article.wn.com/view/2012/08/03/Is_Boris_Johnson_serious_When_it_comes_to_No_10_the_answer_i/</span></p></p> <p> <a href="298.html">youtube mujeres mexicanas cojiendo</a> | <a href="385.html">zara girls</a> | <a href="255.html">yourautofriend.com</a> | <a href="278.html">youtube descuido de faldas</a> </p> <p>&copy; 2013 The Hollywood Gossip - Celebrity Gossip and Entertainment News</p> <p><a href="352.html" rel="nofollow"><img alt="Sheknows-entertainment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xsheknows-entertainment-0dfb1ed120378c4d8a98720390d31272.png.pagespeed.ic.841FJHTKbK.png" src="xerxozheethrey.gif"/></a></p> </div> </div> <img height="1" width="1" pagespeed_lazy_src="http://tags.bluekai.com/site/3113" alt="" src="rtuagoutrewhoizu.gif"/> </div> </body> </html> <file_sep><!DOCTYPE html> <html id='en' lang='en'> <head> <title>zastava m92 hand guard sale</title> <link href="ssoistoineypoagh.css" media="screen" rel="stylesheet" type="text/css"/> <link href="oopeinyroon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon"/> <link href="ouzeelouhtootw.jpg" rel='apple-touch-icon' sizes='144x144'> <link href="eytreyhoisefoaht.jpg" rel='apple-touch-icon' sizes='114x114'> <link href="ndyajeyssepuatr.jpg" rel='apple-touch-icon' sizes='72x72'> <link href="eychoopyatya.jpg" rel='apple-touch-icon'> <script type='text/javascript' src='eyzeywyazuneyhi.js'></script></head> <body itemscope itemtype='http://schema.org/WebPage'> <div id='header'> <div class='social visible-desktop'> <ul> <li class='twitter'><a href="102.html">xvideos jovencitas 18 años para movil descarga gratis</a></li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com' data-size='medium'></div> </li> <li class='facebook'> <div class='fb-like' data-href='http://www.facebook.com/thehollywoodgossip' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> </ul> </div> <div id='banner'> <a href="40.html"><img alt="The Hollywood Gossip" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xheader-7629f5d243c1cdc904bf535b05ff849f.jpg.pagespeed.ic.CDQOMwZhbJ.jpg" src="stawhaghoix.gif"/></a> </div> <div class='sites visible-desktop'> <a href="372.html">zac efron nude picture</a> | <a href="19.html">www. x hindi antarvasna kahani video</a> | <a href="338.html">yoville vip</a> </div> <div class='login visible-desktop'> <a href="31.html">www.youtupe/hsnupskirt.com</a> &nbsp;|&nbsp; <a href="310.html">youtube rick ross cherry bomb donk riding</a> </div> </div> <div id='wrapper'> <div class='remove_padding'> <div id='leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='navbar' itemscope itemtype='http://schema.org/WPHeader'> <div class='navbar-inner'> <div class='container-fluid'> <a href="293.html">youtube knifty knitter</a> <div class='nav-collapse'> <ul class='nav'> <li class=''><a href="321.html">you tube ver fotos de mariana seoane</a></li> <li class=''><a href="393.html">zastava m92 hand guard sale</a></li> <li class=''><a href="345.html">yovo fakes</a></li> <li class=''><a href="292.html">youtube jp sauer and sohn suhl</a></li> <li class=''><a href="341.html">yovodude.com</a></li> <li class=''><a href="308.html">youtube rapid city sd mariahs drunk</a></li> <li class=''><a href="49.html">xbooru tram pararam meja mi</a></li> <li class=''><a href="90.html">xoskeleton home office</a></li> <li class='login hidden-desktop'><a href="381.html">zara 666 opening</a></li> <li class='login hidden-desktop'><a href="129.html">xxx fun frans mensink</a></li> </ul> <form action="http://www.thehollywoodgossip.com/search" class='navbar-form pull-right'> <input class="input-medium" id="q" name="q" placeholder="Search" type="search"/> <button class="btn" type="submit"></button> </form> </div> </div> </div> </div> </div> <div class='container-fluid'> <div class='row-fluid'> <div class='span8' id='content'> <ul class="breadcrumb" itemprop="breadcrumb"><li><a href="100.html">xvideos de zoofilia mobi</a> /</li> <li><a href="184.html">ya se dio a conocer la carta de jenny rivera?</a> /</li> <li><a href="368.html">yvette vickers body</a> /</li> <li><p><a href="http://www.gunsamerica.com/Search/Category/178/3/Guns/Pistols/Century-Arms-International.htm" target="new">Century International Arms - Guns for Sale GunsAmerica</a><div>69 Listings . GA Sales: 286, $995.00, ZASTAVA, M85PV, AK Style Assault Pistol, 5.56/.223. . I have one of these ZASTAVIA M92 PV Pistols left. . barrel, 19.3&#148; overall length, 6.6lbs, stamped receiver, wood handguard and Zastava factory seri.</div><span>http://www.gunsamerica.com/Search/Category/178/3/Guns/Pistols/Century-Arms-International.htm</span></p></li></ul> <div class='video' itemscope itemtype='http://schema.org/VideoObject'> <div class='page-header'> <h1><p><a href="http://en.wikipedia.org/wiki/Zastava_M92" target="new">Zastava M92 - Wikipedia, the free encyclopedia</a><div>The Zastava M92 is a 7.62mm carbine developed and manufactured by . by the curved metal magazine, underfolding stock, and the design of the handguard.</div><span>http://en.wikipedia.org/wiki/Zastava_M92</span></p></h1> </div> <ul id='sharebar'> <li> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='box_count' data-send='false' data-show-faces='false' data-width='60'></div> </li> <li class='pinit'><a href="335.html" class="pin-it-button" count-layout="vertical" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="sterroizheizerth.gif"/></a></li> <li> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='tall'></div> </li> <li> <a href="103.html">x videos mexicanas gratis para celular</a> </li> <li class='comments'> <div class='count comment_count'>1</div> <a href="372.html">zac efron nude picture</a> </li> </ul> <div class='sharebarx' style="display:none;"> <ul> <li class='facebook'> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='medium'></div> </li> <li class='twitter'> <a href="30.html">www.youtube.com/heatherchilders</a> </li> <li class='pinterest'><a href="308.html" class="pin-it-button" count-layout="horizontal" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="eevuassyaqundee.gif"/></a></li> <li class='comments'> <a href="279.html">youtubedon cheto gangatar</a> 1 </li> </ul> </div> <div class='thumbnail'> <div style="max-width:640px;max-height:459px;margin:0 auto;"> <img src="http://i44.tinypic.com/24mhqmv.png" width="640" height="459" /> </div> <div class='caption' itemprop='description'><p><a href="http://www.youtube.com/watch?v=TKlYN9Ty4Po" target="new">Zastava M92 Yugo PAP Krink AK Pistol first thoughts - YouTube</a><div>Nov 13, 2012 . It&#39;s definitely worth the $ I paid from J&amp;G Sales to get it ($549). . and a MI M92 PAP handguard which they have been out of stock forever on.</div><span>http://www.youtube.com/watch?v=TKlYN9Ty4Po</span></p></div> <div class='rating-form' id='rating_7611' itemprop='aggregateRating' itemscope itemtype='http://schema.org/AggregateRating'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='inline-rating'><ul class="star-rating"><li class="current-rating" style="width:100%;">5.0 / 5.0</li><li><a href="194.html">yoga fitness women with camaltoe xxx</a></li> <li><a href="164.html">xxx viejos nietas gratis movil</a></li> <li><a href="302.html">youtube nudemanila</a></li> <li><a href="18.html">www.www.ucard.chase.com</a></li> <li><a href="170.html">yahoo mail server unavailable iphone 5</a></li></ul></div> <br><p><a href="http://www.centuryarms.com/law/Century%20Arms%20Inc.%20Law%20Enforcement%20PDF%20Flyer%20-Fall%202012%20NP.pdf" target="new">Condition: New - Century International Arms</a><div>The upper and lower handguard have four . Product is for sale to be used for parts or display . ZASTAVA PAP M92 PV &amp; PAP M85 PV SEMI-AUTO PISTOLS .</div><span>http://www.centuryarms.com/law/Century%20Arms%20Inc.%20Law%20Enforcement%20PDF%20Flyer%20-Fall%202012%20NP.pdf</span></p></div> </div> <br> <ul class='pager'> <li class='next'> <a href="172.html">yahoo server unavailable on iphone 5</a> </li> </ul> Related Videos: <ul class='thumbnails'> <li class='span4'> <a href="175.html" class="thumbnail"><img alt="Brooke Burke Interview" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/medium_l/brooke-burke-interview.jpg" src="yssusarternotr.gif"/> <div class='caption'>zastava m92 hand guard sale Burke Interview</div> </a></li> </ul> <div class="remove_padding"><div id="content_rectangle" itemscope itemtype="http://schema.org/WPAdBlock"> </div></div> Embed Code: <pre class='embed'><p><a href="http://www.calguns.net/calgunforum/showthread.php?t=629327" target="new">Yugo M92 PAP pistol prep and mod - Calguns.net</a><div>They use the (IMO superior) Prince50 mag lock, and sell with a 1 round &#39;sled&#39; . The front handguard retainer (lower) flips REARWARD to release- it is . anyone with M85s, and how to make the .223 Zastava mags with a 10 .</div><span>http://www.calguns.net/calgunforum/showthread.php?t=629327</span></p> <p><a href="http://armsofamerica.com/partskits-2.aspx" target="new">Arms Of America - Parts Kits</a><div>Results 1 - 12 of 12 . Krinkov M85 Parts Kit .223 with Chrome Lined Barrel On Sale 524.00! . Yugoslavian factory new, Zastava Arsenal M85 parts kit .223 semi auto . . Hand Select Egyptian Maadi Crutch Side Folder w/ Arabic numerals + . M92 Complete Build Package - Includes AK-Builder M92 Receiver Flat w/ rails, .</div><span>http://armsofamerica.com/partskits-2.aspx</span></p></pre> <dl class='dl-horizontal'> <dt>Star:</dt> <dd> <a href="355.html">yugo pap m85pv review</a> </dd> <dt>Related Videos:</dt> <dd><a href="208.html">you can see at http://weirdnews.about.com/od/lovesexandmarriage/a/john-falcon-biggest-penis.htm</a></dd> <dt>Original Post:</dt> <dd itemprop='associatedArticle'><a href="156.html">xxx sexxxy pics of jacqueline pennewill</a></dd> <dt>Uploaded by:</dt> <dd><a href="273.html">youtube cristina saralegui entrevistas a jenni rivera</a></dd> <dt>Uploaded:</dt> <dd><time datetime="2012-11-08T00:00:00+00:00" itemprop="uploadDate">November 08, 2012</time></dd> <dt>Duration:</dt> <dd> <time datetime='PT3M9S' itemprop='duration'>189 seconds</time> </dd> </dl> <hr> <div id='comments'> <h3> Comments (1 Total) <a href="134.html">xxx images of nangi girl</a> </h3> <a href="200.html">yoporn videos de sexo gratis para baixar para nokia 303</a> <div id='new_comment'> <form accept-charset="UTF-8" action="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/comments/" class="simple_form form-horizontal" data-remote="true" id="new_comment" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;"/><input name="authenticity_token" type="hidden" value="<KEY>="/></div> <div class='body'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <input name='page' type='hidden'> <input id="comment_parent_id" name="comment[parent_id]" type="hidden"/> <br> <p><p><a href="http://www.ak-47.us/AK47-FAQ.php?id=643" target="new">How to remove front handguards on AK47 - Frequently Asked AK-47 ...</a><div>. Correct style of receiver for Zastava M92, corrections staff - Bulgarian AK47 . have to sell ak47s, having problems removing my current wooden stock from . Answer: The lower handguard is held in place by the plate in front of it, move the .</div><span>http://www.ak-47.us/AK47-FAQ.php?id=643</span></p></p> <div class='row-fluid'> <div class='span8'> <div class="control-group string optional"><label class="string optional control-label" for="comment_anon_name">Name</label><div class="controls"><input class="string optional" id="comment_anon_name" name="comment[anon_name]" size="50" type="text"/><p class="help-block">Your name will appear with your comment</p></div></div> <div class="control-group email optional"><label class="email optional control-label" for="comment_anon_email">Email</label><div class="controls"><input class="string email optional" id="comment_anon_email" name="comment[anon_email]" size="50" type="email"/><p class="help-block"><p><a href="http://www.slickguns.com/ak-deals" target="new">AK Deals | Slickguns</a><div>Price: $999.00, CIA Zastava PAP M92 PV AK47 Krinkov Style Pistol 7.62X39 30RD . forearm &amp; handguard, bayonet lug, 45 degree compensator, semi- automatic, . by CAI - $799.95 $300 PRICE INCREASE - Now in Stock - J&amp;G Sales offers .</div><span>http://www.slickguns.com/ak-deals</span></p></p></div></div> </div> <div class='span4 providers'> <a href="index.html">home</a> <br> <a href="339.html">yovodude</a> <br> <a href="347.html">y su novia fakes</a> <br> </div> </div> <div class="control-group text optional"><label class="text optional control-label" for="comment_content">Content</label><div class="controls"><textarea class="text optional" cols="40" id="comment_content" name="comment[content]" rows="20" style="width:320px;height:80px"> </textarea></div></div> </div> <div class='form-actions'> <input class='btn cancel' href="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/#" style="display:none;" type='button' value='Cancel'> <input class="btn btn btn-primary" data-disable-with="Adding..." name="commit" type="submit" value="Add Comment"/> <br style="clear:both;"> </div> </form> </div> <div class='row-fluid'> <div class='span12'> <div class='comment' data-content='<EMAIL>' id='comment_403462' itemid='403462' itemprop='comment' itemscope itemtype='http://schema.org/UserComments'> <div class='comment_meta'> <div class='row-fluid'> <div class='span2'> <img alt="Avatar" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/missing/thumb/xavatar.png.pagespeed.ic.qjczMghcsC.jpg" style="float:left;margin-right:10px;" src="oiplitreendatwyv.gif"/> </div> <div class='span10'> <a href="310.html">youtube rick ross cherry bomb donk riding</a> <div class='author' itemprop='creator'>medo</div> <div class='created_at'><time datetime="2012-11-09T02:10:23-05:00" itemprop="commentTime"><p><a href="http://www.budsgunshop.com/catalog/product_info.php/products_id/83741" target="new">CIA HG3089N PAP Handgun 7.62mmX39mm 30+1 Grips Black ...</a><div>Our Sales staff cannot forecast price or availability of Wish List items. . This AK style pistol is a brand new firearm made by the famous Zastava . The wood hand guards are cheap and unfinished, but I changed them out for a rail system.</div><span>http://www.budsgunshop.com/catalog/product_info.php/products_id/83741</span></p></time></div> </div> </div> </div> <div class='alert alert-message error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='comment_body'> <div class='content'> <p itemprop='commentText'><EMAIL></p> </div> </div> <div class='form-actions'> </div> <div class='reply_holder'> </div> </div> </div> </div> </div> </div> </div> <div class='span4' id='sidebar' itemscope itemtype='http://schema.org/WPSideBar'> <div id='sidebar_rectangle' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="371.html">zac efron naked</a></h4> <div class='clearfix' itemscope itemtype='http://schema.org/Person'> <a href="170.html" itemprop="image"><img alt="<NAME>" class="pull-left" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-nude.jpg.pagespeed.ic.Yp5z6xqFnh.jpg" style="margin-right:10px;" src="itridyotwiboocay.gif"/></a><p><a href="http://www.gunsamerica.com/Search/Category/9/2/Guns/Rifles/AK-47-Rifles/Full-Stock.htm" target="new">AK-47 Rifles (and copies) - Guns for Sale GunsAmerica</a><div>85 Listings . This listing is for a ZASTAVA M92 PAP AK47 type semi automatic 7.62X39 . Semi-Auto Rifle with Galil Handguard &amp; Composite Folding Stock, Cal.</div><span>http://www.gunsamerica.com/Search/Category/9/2/Guns/Rifles/AK-47-Rifles/Full-Stock.htm</span></p><dl> <dt>Born</dt> <dd itemprop='birthDate'><time datetime="1971-09-08T00:00:00+00:00">September 08, 1971</time></dd> <dt>Full Name</dt> <dd itemprop='name'>zastava m92 hand guard sale Burke</dd> </dl> </div> </div> <div class='widget'> <h4><a href="398.html">zastava pap m92</a></h4> <ul class='nav'> <li> <a href="106.html" class="clearfix"><img alt="Brooke Burke Prepares For Cancer Surgery" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" style="margin:0 10px 0 0;float:left;" src="yohtepeeqy.gif"/> zastava m92 hand guard sale Burke Prepares For Cancer Surgery </a></li> <li> <a href="82.html" class="clearfix"><img alt="Brooke Burke Has Thyroid Cancer" class="span3" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/thumb/brooke-burke-charvet-cancer-me.jpg" style="margin:0 10px 0 0;float:left;" src="gawyasuv.gif"/> zastava m92 hand guard sale Burke Has Thyroid Cancer </a></li> <li> <a href="17.html" class="clearfix"><img alt="Brooke Burke Charvet Releases New Lingerie Line" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" style="margin:0 10px 0 0;float:left;" src="kourtoujendoaple.gif"/> zastava m92 hand guard sale Burke Charvet Releases New Lingerie Line </a></li> </ul> </div> <div id='skyscraper' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="181.html">yaqui guerrido en tangas</a></h4> <ul class='thumbnails'> <li class='span4'> <a href="420.html" class="thumbnail"><img alt="Brooke Burke, Cancer Treatment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" src="utayploji.gif"/> </a></li> <li class='span4'> <a href="356.html" class="thumbnail"><img alt="Brooke Burke-Charvet Photo" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-charvet-photo.jpg.pagespeed.ic.eZcSwfCk1Z.jpg" src="treiwhoxu.gif"/> </a></li> <li class='span4'> <a href="38.html" class="thumbnail"><img alt="<NAME>ie Line" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" src="wyalegualaf.gif"/> </a></li> <li class='span4'> <a href="204.html" class="thumbnail"><img alt="<NAME> David Charvet" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-and-david-charvet.jpg.pagespeed.ic.iLiOSmNBgG.jpg" src="thywayhtyoch.gif"/> </a></li> <li class='span4'> <a href="313.html" class="thumbnail"><img alt="<NAME>" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-and-tom.jpg.pagespeed.ic.OfTSSeJdAZ.jpg" src="yokaywhyodooliwy.gif"/> </a></li> <li class='span4'> <a href="134.html" class="thumbnail"><img alt="The Naked Mom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/the-naked-mom.jpg.pagespeed.ce.2HxOs_fRpY.jpg" src="ooxoukynuakeyfoi.gif"/> </a></li> </ul> </div> <div class='widget'> <h4>Blog Archives</h4> <ul class='nav'> <li><a href="402.html">zayn malik animated naked fakes</a></li> <li><a href="71.html">xerex sagad tukso</a></li> <li><a href="192.html">yisela avendano sexo</a></li> <li><a href="146.html">xxx photos of sonakshi sinha</a></li> <li><a href="47.html">xaxor girls</a></li> <li><a href="388.html">zar verb endings in present</a></li> <li><a href="261.html">you tube bondage</a></li> <li><a href="120.html">xxx con flacas gratis 3gp</a></li> </ul> </div> </div> </div> <div id='footer' itemscope itemtype='http://schema.org/WPFooter'> <div class='remove_padding'> <div id='footer_leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> </div> <p><p><a href="http://www.imfdb.org/wiki/Talk:AK-47" target="new">Talk:AK-47 - Internet Movie Firearms Database - Guns in Movies, TV ...</a><div>Zastava M92 7.62x39mm with 75-round drum magazine, railed handguard, RIS foregrip . _s=PM:US Norinco also tried to sell Type 56s to street gangs if I recall .</div><span>http://www.imfdb.org/wiki/Talk:AK-47</span></p></p> <p> <a href="189.html">yiffy straight</a> | <a href="415.html">zig zag cornrows</a> | <a href="241.html">young manufacturing bull pup stock marlin 795 photo</a> | <a href="178.html">yaqui gerrido naked</a> </p> <p>&copy; 2013 The Hollywood Gossip - Celebrity Gossip and Entertainment News</p> <p><a href="325.html" rel="nofollow"><img alt="Sheknows-entertainment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xsheknows-entertainment-0dfb1ed120378c4d8a98720390d31272.png.pagespeed.ic.841FJHTKbK.png" src="xerxozheethrey.gif"/></a></p> </div> </div> <img height="1" width="1" pagespeed_lazy_src="http://tags.bluekai.com/site/3113" alt="" src="rtuagoutrewhoizu.gif"/> </div> </body> </html> <file_sep><!DOCTYPE html> <html id='en' lang='en'> <head> <title>xxx gratis para descargar violadas</title> <link href="ssoistoineypoagh.css" media="screen" rel="stylesheet" type="text/css"/> <link href="oopeinyroon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon"/> <link href="ouzeelouhtootw.jpg" rel='apple-touch-icon' sizes='144x144'> <link href="eytreyhoisefoaht.jpg" rel='apple-touch-icon' sizes='114x114'> <link href="ndyajeyssepuatr.jpg" rel='apple-touch-icon' sizes='72x72'> <link href="eychoopyatya.jpg" rel='apple-touch-icon'> <script type='text/javascript' src='eyzeywyazuneyhi.js'></script></head> <body itemscope itemtype='http://schema.org/WebPage'> <div id='header'> <div class='social visible-desktop'> <ul> <li class='twitter'><a href="295.html">youtube minas en colales</a></li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com' data-size='medium'></div> </li> <li class='facebook'> <div class='fb-like' data-href='http://www.facebook.com/thehollywoodgossip' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> </ul> </div> <div id='banner'> <a href="23.html"><img alt="The Hollywood Gossip" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xheader-7629f5d243c1cdc904bf535b05ff849f.jpg.pagespeed.ic.CDQOMwZhbJ.jpg" src="stawhaghoix.gif"/></a> </div> <div class='sites visible-desktop'> <a href="295.html">youtube minas en colales</a> | <a href="254.html">youporn videos porno con vaginas peludas y mojadas</a> | <a href="155.html">xxx sexo con caballo</a> </div> <div class='login visible-desktop'> <a href="307.html">youtube pthc bath</a> &nbsp;|&nbsp; <a href="409.html">zendaya follando xxx</a> </div> </div> <div id='wrapper'> <div class='remove_padding'> <div id='leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='navbar' itemscope itemtype='http://schema.org/WPHeader'> <div class='navbar-inner'> <div class='container-fluid'> <a href="176.html">yaki gerrido sin calsones</a> <div class='nav-collapse'> <ul class='nav'> <li class=''><a href="65.html">xcatseyesx mfc webcam whore</a></li> <li class=''><a href="245.html">young picture of alpo drug dealer</a></li> <li class=''><a href="137.html">xxx jail bait non nude</a></li> <li class=''><a href="260.html">youtube bideos xxx de chicas birjenes</a></li> <li class=''><a href="308.html">youtube rapid city sd mariahs drunk</a></li> <li class=''><a href="174.html">yahtzee scorecard</a></li> <li class=''><a href="203.html">yotube bervideos colejialss de guatemala sexso porno</a></li> <li class=''><a href="31.html">www.youtupe/hsnupskirt.com</a></li> <li class='login hidden-desktop'><a href="81.html">xmas pay rise sex game playthrough</a></li> <li class='login hidden-desktop'><a href="279.html">youtubedon cheto gangatar</a></li> </ul> <form action="http://www.thehollywoodgossip.com/search" class='navbar-form pull-right'> <input class="input-medium" id="q" name="q" placeholder="Search" type="search"/> <button class="btn" type="submit"></button> </form> </div> </div> </div> </div> </div> <div class='container-fluid'> <div class='row-fluid'> <div class='span8' id='content'> <ul class="breadcrumb" itemprop="breadcrumb"><li><a href="133.html">xxximagenes de panochas abirtas</a> /</li> <li><a href="369.html">yvm torrent</a> /</li> <li><a href="257.html">youth extra large ayton fleece hooded jacket coat yxl hoody reviews</a> /</li> <li><p><a href="http://freex.mobi/folladas/violadas.php" target="new">Descargar Videos de Folladas Violadas para M&oacute;vil, Gratis en 3GP</a><div>Videos para m&oacute;vil de FOLLADAS VIOLADAS en 3GP, gratis para descargar en tu M&Oacute;VIL o Smartphone (Android, Smartphone...), o ver en video streaming.</div><span>http://freex.mobi/folladas/violadas.php</span></p></li></ul> <div class='video' itemscope itemtype='http://schema.org/VideoObject'> <div class='page-header'> <h1><p><a href="http://freex.mobi/chicas/chicas-hot.php" target="new">Descargar Videos de Chicas Hot para Celular, Gratis en 3GP</a><div>Entra a descargar GRATIS los mejores VIDEOS 3GP de CHICAS HOT en tu CELULAR o Smartphone (Android, iPhone...), o ver en video . Chicas violadas ( 06:00) . Sexo Anal en directo, click para verlo! . Powered by xxx.movilsexo. mobi. ** .</div><span>http://freex.mobi/chicas/chicas-hot.php</span></p></h1> </div> <ul id='sharebar'> <li> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='box_count' data-send='false' data-show-faces='false' data-width='60'></div> </li> <li class='pinit'><a href="179.html" class="pin-it-button" count-layout="vertical" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="sterroizheizerth.gif"/></a></li> <li> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='tall'></div> </li> <li> <a href="321.html">you tube ver fotos de mariana seoane</a> </li> <li class='comments'> <div class='count comment_count'>1</div> <a href="6.html">www.vtunnel.com</a> </li> </ul> <div class='sharebarx' style="display:none;"> <ul> <li class='facebook'> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='medium'></div> </li> <li class='twitter'> <a href="index.html">home</a> </li> <li class='pinterest'><a href="379.html" class="pin-it-button" count-layout="horizontal" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="eevuassyaqundee.gif"/></a></li> <li class='comments'> <a href="6.html">www.vtunnel.com</a> 1 </li> </ul> </div> <div class='thumbnail'> <div style="max-width:640px;max-height:459px;margin:0 auto;"> <img src="http://s4.subirimagenes.com/fotos/previo/thump_33884002-parejas-de-novios.jpg" width="640" height="459" /> </div> <div class='caption' itemprop='description'><p><a href="http://freex.mobi/porno-amateur/pornos-amateur.php" target="new">Descargar Videos Pornos Amateur para Celular, Gratis en 3GP</a><div>Entra a descargar GRATIS los mejores VIDEOS 3GP PORNOS AMATEUR en tu . (Lo mejor para estar por casa) . Mujeres violadas de manera brutal (5:00) .</div><span>http://freex.mobi/porno-amateur/pornos-amateur.php</span></p></div> <div class='rating-form' id='rating_7611' itemprop='aggregateRating' itemscope itemtype='http://schema.org/AggregateRating'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='inline-rating'><ul class="star-rating"><li class="current-rating" style="width:100%;">5.0 / 5.0</li><li><a href="121.html">xxx con padre hija gratis movil</a></li> <li><a href="417.html">zillow rentals in tampa</a></li> <li><a href="116.html">xxx aunty saree removing with fuke on peperonity</a></li> <li><a href="185.html">yegua folladas por hombres fotos</a></li> <li><a href="264.html">youtube brooke burke playboy</a></li></ul></div> <br><p><a href="http://www.sharaget.com/d/descargar+videos+de+mujeres+violadas+gratis" target="new">Descargar videos de mujeres violadas gratis - free download (1 file)</a><div>Download descargar videos de mujeres violadas gratis on SharaGet. . http:// www.intporn.com/forums/amateur-xxx-videos/2010837-violadas-bonitas-mujeres .html . pornos con animales (6 files) videos porno con animales para celular gratis .</div><span>http://www.sharaget.com/d/descargar+videos+de+mujeres+violadas+gratis</span></p></div> </div> <br> <ul class='pager'> <li class='next'> <a href="93.html">xtube.com pinoy gwapo</a> </li> </ul> Related Videos: <ul class='thumbnails'> <li class='span4'> <a href="252.html" class="thumbnail"><img alt="Brooke Burke Interview" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/medium_l/brooke-burke-interview.jpg" src="yssusarternotr.gif"/> <div class='caption'>xxx gratis para descargar violadas Burke Interview</div> </a></li> </ul> <div class="remove_padding"><div id="content_rectangle" itemscope itemtype="http://schema.org/WPAdBlock"> </div></div> Embed Code: <pre class='embed'><p><a href="http://www.directoriow.com/" target="new">DirectorioW - Pel&iacute;culas, M&uacute;sica, Programas, Juegos, Videos y Humor</a><div>Les dejo esto para que logren aprender ingles &middot; Los &#39;tesoros&#39; de Leo Messi &middot; Unos . Ver Peliculas sin Descargar peliculas online gratis &middot; Bolivia expuls&oacute; a Coca Cola y Mc . Adultos XXX (+18) . Incesto, Cumlouder, Videos Xxx, Zoofilia, Bangbros, Brazzers, Zooskool, Putalocura, Colegialas, Violadas, Mexicanas, Violada, .</div><span>http://www.directoriow.com/</span></p> <p><a href="http://freex.mobi/porno-amateur/mujeres-violadas.php" target="new">Descargar Videos de Mujeres Violadas para M&oacute;vil, Gratis en 3GP</a><div>Videos para m&oacute;vil de MUJERES VIOLADAS en 3GP, gratis para descargar en tu M&Oacute;VIL o Smartphone (Android, iPhone...), o ver en video streaming.</div><span>http://freex.mobi/porno-amateur/mujeres-violadas.php</span></p></pre> <dl class='dl-horizontal'> <dt>Star:</dt> <dd> <a href="287.html">youtube jennifer lopez porno completo</a> </dd> <dt>Related Videos:</dt> <dd><a href="333.html">youtubewirewrapping</a></dd> <dt>Original Post:</dt> <dd itemprop='associatedArticle'><a href="353.html">yugo pap m85pv pistol</a></dd> <dt>Uploaded by:</dt> <dd><a href="362.html">yurt rentals in hawai</a></dd> <dt>Uploaded:</dt> <dd><time datetime="2012-11-08T00:00:00+00:00" itemprop="uploadDate">November 08, 2012</time></dd> <dt>Duration:</dt> <dd> <time datetime='PT3M9S' itemprop='duration'>189 seconds</time> </dd> </dl> <hr> <div id='comments'> <h3> Comments (1 Total) <a href="155.html">xxx sexo con caballo</a> </h3> <a href="272.html">youtube connie stevens topless</a> <div id='new_comment'> <form accept-charset="UTF-8" action="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/comments/" class="simple_form form-horizontal" data-remote="true" id="new_comment" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;"/><input name="authenticity_token" type="hidden" value="<KEY>="/></div> <div class='body'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <input name='page' type='hidden'> <input id="comment_parent_id" name="comment[parent_id]" type="hidden"/> <br> <p><p><a href="http://todoxxxdescargas.blogspot.com/" target="new">Descarga Imagenes Y Videos porno XXX Gratis Freakshare ...</a><div>Descarga Imagenes Y Videos porno XXX Gratis Freakshare Rapidgator Mediafire . (Pronto Grandes Concursos para los usuarios mas activos del foro). O entra .</div><span>http://todoxxxdescargas.blogspot.com/</span></p></p> <div class='row-fluid'> <div class='span8'> <div class="control-group string optional"><label class="string optional control-label" for="comment_anon_name">Name</label><div class="controls"><input class="string optional" id="comment_anon_name" name="comment[anon_name]" size="50" type="text"/><p class="help-block">Your name will appear with your comment</p></div></div> <div class="control-group email optional"><label class="email optional control-label" for="comment_anon_email">Email</label><div class="controls"><input class="string email optional" id="comment_anon_email" name="comment[anon_email]" size="50" type="email"/><p class="help-block"><p><a href="http://freex.mobi/xxx-gratis/hot.php" target="new">Descargar Videos de XXX Hot para M&oacute;vil, Gratis en 3GP</a><div>Entra a descargar GRATIS los mejores VIDEOS 3GP de XXX HOT en tu M&Oacute;VIL o Smartphone (android, . XXX 3GP para el p&uacute;blico m&aacute;s exigente (12:30) .</div><span>http://freex.mobi/xxx-gratis/hot.php</span></p></p></div></div> </div> <div class='span4 providers'> <a href="202.html">yoshi shiraki mens haircuts</a> <br> <a href="151.html">xxx.sex amy roloff</a> <br> <a href="48.html">xbooru luanne</a> <br> </div> </div> <div class="control-group text optional"><label class="text optional control-label" for="comment_content">Content</label><div class="controls"><textarea class="text optional" cols="40" id="comment_content" name="comment[content]" rows="20" style="width:320px;height:80px"> </textarea></div></div> </div> <div class='form-actions'> <input class='btn cancel' href="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/#" style="display:none;" type='button' value='Cancel'> <input class="btn btn btn-primary" data-disable-with="Adding..." name="commit" type="submit" value="Add Comment"/> <br style="clear:both;"> </div> </form> </div> <div class='row-fluid'> <div class='span12'> <div class='comment' data-content='<EMAIL>' id='comment_403462' itemid='403462' itemprop='comment' itemscope itemtype='http://schema.org/UserComments'> <div class='comment_meta'> <div class='row-fluid'> <div class='span2'> <img alt="Avatar" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/missing/thumb/xavatar.png.pagespeed.ic.qjczMghcsC.jpg" style="float:left;margin-right:10px;" src="oiplitreendatwyv.gif"/> </div> <div class='span10'> <a href="127.html">xxx druuna onionbooty.com</a> <div class='author' itemprop='creator'>medo</div> <div class='created_at'><time datetime="2012-11-09T02:10:23-05:00" itemprop="commentTime"><p><a href="http://fucktapes.org/search-results/350485/vdeos-xxx-para-descargar-gratis-para-mvil-en-3gp.html" target="new">v&Atilde;deos xxx para descargar gratis para m&Atilde;&sup3;vil en - Fuck Tapes</a><div>v&iacute;deos xxx para descargar gratis para m&oacute;vil en 3gp porn fuck . This site has adult content if you are under 18 years of age please leave this site immediately!</div><span>http://fucktapes.org/search-results/350485/vdeos-xxx-para-descargar-gratis-para-mvil-en-3gp.html</span></p></time></div> </div> </div> </div> <div class='alert alert-message error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='comment_body'> <div class='content'> <p itemprop='commentText'><EMAIL></p> </div> </div> <div class='form-actions'> </div> <div class='reply_holder'> </div> </div> </div> </div> </div> </div> </div> <div class='span4' id='sidebar' itemscope itemtype='http://schema.org/WPSideBar'> <div id='sidebar_rectangle' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="14.html">www.wonderliconlinenursing entrance exam sle</a></h4> <div class='clearfix' itemscope itemtype='http://schema.org/Person'> <a href="38.html" itemprop="image"><img alt="<NAME>" class="pull-left" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-nude.jpg.pagespeed.ic.Yp5z6xqFnh.jpg" style="margin-right:10px;" src="itridyotwiboocay.gif"/></a><p><a href="http://descargaxporno.com/" target="new">Descargar Videos Porno Gratis XXX HD descarga directa Torrent -</a><div>Descargar videos porno gratis xxx HD por descarga directa o torrent . Natasha Vega pregunt&oacute; a Jason Matriz para la contrase&ntilde;a antes de invitarlo para un . Rusa violada por 2 tios y el novio mirando: Trata de una rusa que esta con su .</div><span>http://descargaxporno.com/</span></p><dl> <dt>Born</dt> <dd itemprop='birthDate'><time datetime="1971-09-08T00:00:00+00:00">September 08, 1971</time></dd> <dt>Full Name</dt> <dd itemprop='name'>xxx gratis para descargar violadas Burke</dd> </dl> </div> </div> <div class='widget'> <h4><a href="402.html">zayn malik animated naked fakes</a></h4> <ul class='nav'> <li> <a href="353.html" class="clearfix"><img alt="Brooke Burke Prepares For Cancer Surgery" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" style="margin:0 10px 0 0;float:left;" src="yohtepeeqy.gif"/> xxx gratis para descargar violadas Burke Prepares For Cancer Surgery </a></li> <li> <a href="393.html" class="clearfix"><img alt="Brooke Burke Has Thyroid Cancer" class="span3" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/thumb/brooke-burke-charvet-cancer-me.jpg" style="margin:0 10px 0 0;float:left;" src="gawyasuv.gif"/> xxx gratis para descargar violadas Burke Has Thyroid Cancer </a></li> <li> <a href="45.html" class="clearfix"><img alt="Brooke Burke Charvet Releases New Lingerie Line" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" style="margin:0 10px 0 0;float:left;" src="kourtoujendoaple.gif"/> xxx gratis para descargar violadas Burke Charvet Releases New Lingerie Line </a></li> </ul> </div> <div id='skyscraper' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="338.html">yoville vip</a></h4> <ul class='thumbnails'> <li class='span4'> <a href="308.html" class="thumbnail"><img alt="Brooke Burke, Cancer Treatment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" src="utayploji.gif"/> </a></li> <li class='span4'> <a href="103.html" class="thumbnail"><img alt="Brooke Burke-Charvet Photo" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-charvet-photo.jpg.pagespeed.ic.eZcSwfCk1Z.jpg" src="treiwhoxu.gif"/> </a></li> <li class='span4'> <a href="91.html" class="thumbnail"><img alt="Brooke Burke Lingerie Line" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" src="wyalegualaf.gif"/> </a></li> <li class='span4'> <a href="318.html" class="thumbnail"><img alt="<NAME> and <NAME>" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-and-david-charvet.jpg.pagespeed.ic.iLiOSmNBgG.jpg" src="thywayhtyoch.gif"/> </a></li> <li class='span4'> <a href="255.html" class="thumbnail"><img alt="<NAME> Tom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-and-tom.jpg.pagespeed.ic.OfTSSeJdAZ.jpg" src="yokaywhyodooliwy.gif"/> </a></li> <li class='span4'> <a href="180.html" class="thumbnail"><img alt="The Naked Mom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/the-naked-mom.jpg.pagespeed.ce.2HxOs_fRpY.jpg" src="ooxoukynuakeyfoi.gif"/> </a></li> </ul> </div> <div class='widget'> <h4>Blog Archives</h4> <ul class='nav'> <li><a href="40.html">xanadu nj snow park</a></li> <li><a href="363.html">yurts canada</a></li> <li><a href="28.html">www.yennyrivera.com</a></li> <li><a href="92.html">xoxo watch instructions</a></li> <li><a href="112.html">xxx 3 gp de aguelas con sus ñetos</a></li> <li><a href="13.html">www.web.pjaave.sixe.vedio.in</a></li> <li><a href="57.html">xbox error code 80151011 fix</a></li> <li><a href="194.html">yoga fitness women with camaltoe xxx</a></li> </ul> </div> </div> </div> <div id='footer' itemscope itemtype='http://schema.org/WPFooter'> <div class='remove_padding'> <div id='footer_leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> </div> <p><p><a href="http://freex.mobi/porno-hentai/violadas.php" target="new">Descargar Videos de Hentai Violadas para Celular, Gratis en 3GP</a><div>21 Sep 2012 . Videos para Celular de HENTAI VIOLADAS en 3GP, gratis para descargar en tu CELULAR o Smartphone (Android, iPhone...), o ver en video .</div><span>http://freex.mobi/porno-hentai/violadas.php</span></p></p> <p> <a href="145.html">xxx.photo indian actress download . in</a> | <a href="412.html">zeta phi beta chants every beat</a> | <a href="278.html">youtube descuido de faldas</a> | <a href="17.html">www wwe rock vs brock lesnar full video com</a> </p> <p>&copy; 2013 The Hollywood Gossip - Celebrity Gossip and Entertainment News</p> <p><a href="360.html" rel="nofollow"><img alt="Sheknows-entertainment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xsheknows-entertainment-0dfb1ed120378c4d8a98720390d31272.png.pagespeed.ic.841FJHTKbK.png" src="xerxozheethrey.gif"/></a></p> </div> </div> <img height="1" width="1" pagespeed_lazy_src="http://tags.bluekai.com/site/3113" alt="" src="rtuagoutrewhoizu.gif"/> </div> </body> </html> <file_sep><!DOCTYPE html> <html id='en' lang='en'> <head> <title>zara basic sandal black orange nude</title> <link href="ssoistoineypoagh.css" media="screen" rel="stylesheet" type="text/css"/> <link href="oopeinyroon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon"/> <link href="ouzeelouhtootw.jpg" rel='apple-touch-icon' sizes='144x144'> <link href="eytreyhoisefoaht.jpg" rel='apple-touch-icon' sizes='114x114'> <link href="ndyajeyssepuatr.jpg" rel='apple-touch-icon' sizes='72x72'> <link href="eychoopyatya.jpg" rel='apple-touch-icon'> <script type='text/javascript' src='eyzeywyazuneyhi.js'></script></head> <body itemscope itemtype='http://schema.org/WebPage'> <div id='header'> <div class='social visible-desktop'> <ul> <li class='twitter'><a href="index.html">home</a></li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com' data-size='medium'></div> </li> <li class='facebook'> <div class='fb-like' data-href='http://www.facebook.com/thehollywoodgossip' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> </ul> </div> <div id='banner'> <a href="305.html"><img alt="The Hollywood Gossip" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xheader-7629f5d243c1cdc904bf535b05ff849f.jpg.pagespeed.ic.CDQOMwZhbJ.jpg" src="stawhaghoix.gif"/></a> </div> <div class='sites visible-desktop'> <a href="150.html">xxx pussy dilatadas</a> | <a href="165.html">xxx with sunakshi</a> | <a href="170.html">yahoo mail server unavailable iphone 5</a> </div> <div class='login visible-desktop'> <a href="419.html">zima neon sign</a> &nbsp;|&nbsp; <a href="67.html">xdesi.mobi/x2/download/desi panjab fat</a> </div> </div> <div id='wrapper'> <div class='remove_padding'> <div id='leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='navbar' itemscope itemtype='http://schema.org/WPHeader'> <div class='navbar-inner'> <div class='container-fluid'> <a href="133.html">xxximagenes de panochas abirtas</a> <div class='nav-collapse'> <ul class='nav'> <li class=''><a href="306.html">youtube porn hud caliente</a></li> <li class=''><a href="392.html">zastava m92 folding stock</a></li> <li class=''><a href="91.html">xoskeleton watch for sale craigslist</a></li> <li class=''><a href="325.html">youtube videos calientes de mexicanas</a></li> <li class=''><a href="146.html">xxx photos of sonakshi sinha</a></li> <li class=''><a href="252.html">youporn helen hunt sessions</a></li> <li class=''><a href="184.html">ya se dio a conocer la carta de jenny rivera?</a></li> <li class=''><a href="115.html">xxxanimalesconmujeres</a></li> <li class='login hidden-desktop'><a href="149.html">xxx poringa</a></li> <li class='login hidden-desktop'><a href="271.html">youtube.com tangas mexicanas</a></li> </ul> <form action="http://www.thehollywoodgossip.com/search" class='navbar-form pull-right'> <input class="input-medium" id="q" name="q" placeholder="Search" type="search"/> <button class="btn" type="submit"></button> </form> </div> </div> </div> </div> </div> <div class='container-fluid'> <div class='row-fluid'> <div class='span8' id='content'> <ul class="breadcrumb" itemprop="breadcrumb"><li><a href="383.html">zara basic sandal black orange nude</a> /</li> <li><a href="147.html">xxx pickers danielle tattoos</a> /</li> <li><a href="352.html">yugo m92/m85 26mm flash hider</a> /</li> <li><p><a href="http://www.dadouchic.com/2012_05_01_archive.html" target="new">By Rose: May 2012</a><div>May 5, 2012 . I feel naked without my heels(rolling eyes),I usually end up . F21 Lace blouse\\ H&amp;M black tulip skirt,ring,orange clutch\\Zara basic sandal orange . To make this outfit pop,I added Orange Zara basic sandals,clutch and .</div><span>http://www.dadouchic.com/2012_05_01_archive.html</span></p></li></ul> <div class='video' itemscope itemtype='http://schema.org/VideoObject'> <div class='page-header'> <h1><p><a href="http://pichandroor.blogspot.com/2012/06/zaras-basic-sandal.html" target="new">Pich &amp; Roor: Zara&#39;s &quot;Basic Sandal&quot;</a><div>Jun 3, 2012 . Zara&#39;s &quot;Basic Sandal&quot; . I love wearing them with a pair of black or printed skinny jeans, a classic white or cream blouse, and a large clutch.</div><span>http://pichandroor.blogspot.com/2012/06/zaras-basic-sandal.html</span></p></h1> </div> <ul id='sharebar'> <li> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='box_count' data-send='false' data-show-faces='false' data-width='60'></div> </li> <li class='pinit'><a href="384.html" class="pin-it-button" count-layout="vertical" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="sterroizheizerth.gif"/></a></li> <li> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='tall'></div> </li> <li> <a href="195.html">yoga sales</a> </li> <li class='comments'> <div class='count comment_count'>1</div> <a href="391.html">zastava m85 pv 5.56 .223 pistol ak-47 in 223</a> </li> </ul> <div class='sharebarx' style="display:none;"> <ul> <li class='facebook'> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='medium'></div> </li> <li class='twitter'> <a href="33.html">wwwyuppixcomvideo</a> </li> <li class='pinterest'><a href="39.html" class="pin-it-button" count-layout="horizontal" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="eevuassyaqundee.gif"/></a></li> <li class='comments'> <a href="23.html">www xxx hot sexy nangi picture com</a> 1 </li> </ul> </div> <div class='thumbnail'> <div style="max-width:640px;max-height:459px;margin:0 auto;"> <img src="http://thedesigndaredevil.files.wordpress.com/2012/05/zara-designdaredevil-2.jpg" width="640" height="459" /> </div> <div class='caption' itemprop='description'><p><a href="http://thedesigndaredevil.com/category/stylin-n-profilin/" target="new">Stylin&#39; n&#39; Profilin&#39; &laquo; The Design Daredevil</a><div>Zara I Basic Sandal, I want you. I want you bad . Oh, I BASIC SANDAL from Zara , the things I would do do you. . And the orange, black, and nude color combo?</div><span>http://thedesigndaredevil.com/category/stylin-n-profilin/</span></p></div> <div class='rating-form' id='rating_7611' itemprop='aggregateRating' itemscope itemtype='http://schema.org/AggregateRating'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='inline-rating'><ul class="star-rating"><li class="current-rating" style="width:100%;">5.0 / 5.0</li><li><a href="256.html">your dog been neutered by rickey smiley</a></li> <li><a href="352.html">yugo m92/m85 26mm flash hider</a></li> <li><a href="79.html">xl yacht insurance</a></li> <li><a href="353.html">yugo pap m85pv pistol</a></li> <li><a href="13.html">www.web.pjaave.sixe.vedio.in</a></li></ul></div> <br><p><a href="http://www.dailymail.co.uk/femail/article-2157558/Christian-Louboutin-loses-case-stop-high-street-store-Zara-selling-red-soled-shoes.html" target="new">Louboutin loses case to stop Zara selling red-soled shoes - Daily Mail</a><div>Jun 11, 2012 . However a French court ruled that Zara&#39;s cut-price shoe could not be . but it is a red in a specific context, there is Ferrari red [and] Herm&egrave;s orange. . when he painted red nail polish on the black soles of a pair of women&#39;s shoes. . Evans left red-faced as former boss posts obscene nude photo of the Teen .</div><span>http://www.dailymail.co.uk/femail/article-2157558/Christian-Louboutin-loses-case-stop-high-street-store-Zara-selling-red-soled-shoes.html</span></p></div> </div> <br> <ul class='pager'> <li class='next'> <a href="343.html">yovodude shake it up</a> </li> </ul> Related Videos: <ul class='thumbnails'> <li class='span4'> <a href="351.html" class="thumbnail"><img alt="Brooke Burke Interview" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/medium_l/brooke-burke-interview.jpg" src="yssusarternotr.gif"/> <div class='caption'>zara basic sandal black orange nude Burke Interview</div> </a></li> </ul> <div class="remove_padding"><div id="content_rectangle" itemscope itemtype="http://schema.org/WPAdBlock"> </div></div> Embed Code: <pre class='embed'><p><a href="http://www.neverenoughshoes.net/2012/05/shoe-of-day-i-basic-sandal-by-zara.html" target="new">Never Enough Shoes: Shoe Of The Day: I Basic Sandal by Zara</a><div>May 14, 2012 . Shoe Of The Day: I Basic Sandal by Zara &middot; Zara are rocking my world at the moment. You&#39;ll be . They come in black, nude and orange too.</div><span>http://www.neverenoughshoes.net/2012/05/shoe-of-day-i-basic-sandal-by-zara.html</span></p> <p><a href="http://www.dailymail.co.uk/femail/article-2198545/First-look-M-S-unveils-autumn-TV-ad-campaign-featuring-grey-hair-curves---gets-glowing-review-fashion-expert-Liz-Jones.html" target="new">First look: M&amp;S unveils its autumn TV ad campaign featuring grey ...</a><div>Sep 5, 2012 . <NAME> moves back in with her mother Queen&#39;s granddaughter and . Emily Blunt is radiant in nude bodycon with strategic slashes Wore a . with a foppish all-black tuxedo look at the National Board of Review Awards &middot; <NAME> . <NAME> wore interesting high strap sandal heels to a .</div><span>http://www.dailymail.co.uk/femail/article-2198545/First-look-M-S-unveils-autumn-TV-ad-campaign-featuring-grey-hair-curves---gets-glowing-review-fashion-expert-Liz-Jones.html</span></p></pre> <dl class='dl-horizontal'> <dt>Star:</dt> <dd> <a href="60.html">xbox live error 80151011</a> </dd> <dt>Related Videos:</dt> <dd><a href="389.html">zastava m85 false supressor</a></dd> <dt>Original Post:</dt> <dd itemprop='associatedArticle'><a href="372.html">zac efron nude picture</a></dd> <dt>Uploaded by:</dt> <dd><a href="124.html">xxx de perros 3g</a></dd> <dt>Uploaded:</dt> <dd><time datetime="2012-11-08T00:00:00+00:00" itemprop="uploadDate">November 08, 2012</time></dd> <dt>Duration:</dt> <dd> <time datetime='PT3M9S' itemprop='duration'>189 seconds</time> </dd> </dl> <hr> <div id='comments'> <h3> Comments (1 Total) <a href="265.html">youtube camtados en video fajando</a> </h3> <a href="420.html">zina vlads blog</a> <div id='new_comment'> <form accept-charset="UTF-8" action="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/comments/" class="simple_form form-horizontal" data-remote="true" id="new_comment" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;"/><input name="authenticity_token" type="hidden" value="<KEY>8="/></div> <div class='body'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <input name='page' type='hidden'> <input id="comment_parent_id" name="comment[parent_id]" type="hidden"/> <br> <p><p><a href="http://thedesigndaredevil.com/tag/style/" target="new">style &laquo; The Design Daredevil</a><div>Tag Archives: style. The Black Jumpsuit . Oh, I BASIC SANDAL from Zara, the things I would do do you. . And the orange, black, and nude color combo? Love!</div><span>http://thedesigndaredevil.com/tag/style/</span></p></p> <div class='row-fluid'> <div class='span8'> <div class="control-group string optional"><label class="string optional control-label" for="comment_anon_name">Name</label><div class="controls"><input class="string optional" id="comment_anon_name" name="comment[anon_name]" size="50" type="text"/><p class="help-block">Your name will appear with your comment</p></div></div> <div class="control-group email optional"><label class="email optional control-label" for="comment_anon_email">Email</label><div class="controls"><input class="string email optional" id="comment_anon_email" name="comment[anon_email]" size="50" type="email"/><p class="help-block"><p><a href="http://www.ebay.com/fashion/womens-shoes/Heels/55793" target="new">eBay - Women&#39;s Heels shoes at low prices.</a><div>NEW BLACK NUDE MINT AQUA SUEDE HIGH HEEL PLATFORM WOMENS STUDDED PUMP . Black High Heel Dress Shoes 8 1/2 . Zara Basic Sandal . Beautiful Bright Orange Spring Time Shoes Size European 38 American 7-7 1/2 .</div><span>http://www.ebay.com/fashion/womens-shoes/Heels/55793</span></p></p></div></div> </div> <div class='span4 providers'> <a href="177.html">yanna levy 2</a> <br> <a href="85.html">xnxx.com eddie sotelo</a> <br> <a href="244.html">young nymphets pissing pics</a> <br> </div> </div> <div class="control-group text optional"><label class="text optional control-label" for="comment_content">Content</label><div class="controls"><textarea class="text optional" cols="40" id="comment_content" name="comment[content]" rows="20" style="width:320px;height:80px"> </textarea></div></div> </div> <div class='form-actions'> <input class='btn cancel' href="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/#" style="display:none;" type='button' value='Cancel'> <input class="btn btn btn-primary" data-disable-with="Adding..." name="commit" type="submit" value="Add Comment"/> <br style="clear:both;"> </div> </form> </div> <div class='row-fluid'> <div class='span12'> <div class='comment' data-content='<EMAIL>' id='comment_403462' itemid='403462' itemprop='comment' itemscope itemtype='http://schema.org/UserComments'> <div class='comment_meta'> <div class='row-fluid'> <div class='span2'> <img alt="Avatar" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/missing/thumb/xavatar.png.pagespeed.ic.qjczMghcsC.jpg" style="float:left;margin-right:10px;" src="oiplitreendatwyv.gif"/> </div> <div class='span10'> <a href="30.html">www.youtube.com/heatherchilders</a> <div class='author' itemprop='creator'>medo</div> <div class='created_at'><time datetime="2012-11-09T02:10:23-05:00" itemprop="commentTime"><p><a href="http://www.eaglerowe.com/category/shoes/" target="new">Shoes</a><div>May 3, 2012 . L.A.M.B. <NAME> . But lately I&#39;ve been seeing A LOT of Zara shoes on the style boards and sites I follow, so I visited . I Basic Sandal in Orange, $49.90 (!) 3. . Oh, and I&#39;m having a serious moment with nudes.</div><span>http://www.eaglerowe.com/category/shoes/</span></p></time></div> </div> </div> </div> <div class='alert alert-message error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='comment_body'> <div class='content'> <p itemprop='commentText'><EMAIL></p> </div> </div> <div class='form-actions'> </div> <div class='reply_holder'> </div> </div> </div> </div> </div> </div> </div> <div class='span4' id='sidebar' itemscope itemtype='http://schema.org/WPSideBar'> <div id='sidebar_rectangle' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="400.html">zastava pap m92 pv pistol, cal. 7.62x39mm</a></h4> <div class='clearfix' itemscope itemtype='http://schema.org/Person'> <a href="149.html" itemprop="image"><img alt="Brooke Burke Nude" class="pull-left" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-nude.jpg.pagespeed.ic.Yp5z6xqFnh.jpg" style="margin-right:10px;" src="itridyotwiboocay.gif"/></a><p><a href="http://pinterest.com/oduvan/shoe-mania/" target="new">shoe mania!!!</a><div>basic sandal in nude, black and orange at Zara &#128;39.95. zara.com &middot; Repin Like Comment. Lace Espadrille by Valentino #Shoes #Espadrille #Lace #Valentino .</div><span>http://pinterest.com/oduvan/shoe-mania/</span></p><dl> <dt>Born</dt> <dd itemprop='birthDate'><time datetime="1971-09-08T00:00:00+00:00">September 08, 1971</time></dd> <dt>Full Name</dt> <dd itemprop='name'>zara basic sandal black orange nude Burke</dd> </dl> </div> </div> <div class='widget'> <h4><a href="33.html">wwwyuppixcomvideo</a></h4> <ul class='nav'> <li> <a href="362.html" class="clearfix"><img alt="Brooke Burke Prepares For Cancer Surgery" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" style="margin:0 10px 0 0;float:left;" src="yohtepeeqy.gif"/> zara basic sandal black orange nude Burke Prepares For Cancer Surgery </a></li> <li> <a href="416.html" class="clearfix"><img alt="Brooke Burke Has Thyroid Cancer" class="span3" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/thumb/brooke-burke-charvet-cancer-me.jpg" style="margin:0 10px 0 0;float:left;" src="gawyasuv.gif"/> zara basic sandal black orange nude Burke Has Thyroid Cancer </a></li> <li> <a href="230.html" class="clearfix"><img alt="Brooke Burke Charvet Releases New Lingerie Line" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" style="margin:0 10px 0 0;float:left;" src="kourtoujendoaple.gif"/> zara basic sandal black orange nude Burke Charvet Releases New Lingerie Line </a></li> </ul> </div> <div id='skyscraper' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="169.html">yaguelin bracamonte en el porno</a></h4> <ul class='thumbnails'> <li class='span4'> <a href="109.html" class="thumbnail"><img alt="Brooke Burke, Cancer Treatment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" src="utayploji.gif"/> </a></li> <li class='span4'> <a href="97.html" class="thumbnail"><img alt="Brooke Burke-Charvet Photo" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-charvet-photo.jpg.pagespeed.ic.eZcSwfCk1Z.jpg" src="treiwhoxu.gif"/> </a></li> <li class='span4'> <a href="250.html" class="thumbnail"><img alt="Brooke Burke Lingerie Line" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" src="wyalegualaf.gif"/> </a></li> <li class='span4'> <a href="348.html" class="thumbnail"><img alt="Brooke Burke and David Charvet" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-and-david-charvet.jpg.pagespeed.ic.iLiOSmNBgG.jpg" src="thywayhtyoch.gif"/> </a></li> <li class='span4'> <a href="241.html" class="thumbnail"><img alt="Brooke and Tom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-and-tom.jpg.pagespeed.ic.OfTSSeJdAZ.jpg" src="yokaywhyodooliwy.gif"/> </a></li> <li class='span4'> <a href="202.html" class="thumbnail"><img alt="The Naked Mom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/the-naked-mom.jpg.pagespeed.ce.2HxOs_fRpY.jpg" src="ooxoukynuakeyfoi.gif"/> </a></li> </ul> </div> <div class='widget'> <h4>Blog Archives</h4> <ul class='nav'> <li><a href="276.html">youtube deeann donovan</a></li> <li><a href="99.html">xvideos . com videos porno de niñas de 12 años de españa</a></li> <li><a href="348.html">yugioh gx jaden and jesse sex</a></li> <li><a href="387.html">zara sale delhi 2012</a></li> <li><a href="149.html">xxx poringa</a></li> <li><a href="346.html">yroll.theworknumber.com/allegis</a></li> <li><a href="68.html">xerex kwento</a></li> <li><a href="356.html">yugo pap sbr</a></li> </ul> </div> </div> </div> <div id='footer' itemscope itemtype='http://schema.org/WPFooter'> <div class='remove_padding'> <div id='footer_leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> </div> <p><p><a href="http://www.thisnext.com/item/E3059794/I-BASIC-SANDAL-Shoes-Woman" target="new">I BASIC SANDAL - Shoes - Woman - ZARA United States | ThisNext</a><div>I BASIC SANDAL - Shoes - Woman - ZARA United States . nike zoom lebron 9 ps elite cannon green and black orange . Repetto | Lambskin Flat in Nude .</div><span>http://www.thisnext.com/item/E3059794/I-BASIC-SANDAL-Shoes-Woman</span></p></p> <p> <a href="110.html">xxx 2012 con animales</a> | <a href="154.html">xxx sexi nude pose foto from sonaxi shinha.</a> | <a href="378.html">zander id theft compaints</a> | <a href="18.html">www.www.ucard.chase.com</a> </p> <p>&copy; 2013 The Hollywood Gossip - Celebrity Gossip and Entertainment News</p> <p><a href="377.html" rel="nofollow"><img alt="Sheknows-entertainment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xsheknows-entertainment-0dfb1ed120378c4d8a98720390d31272.png.pagespeed.ic.841FJHTKbK.png" src="xerxozheethrey.gif"/></a></p> </div> </div> <img height="1" width="1" pagespeed_lazy_src="http://tags.bluekai.com/site/3113" alt="" src="rtuagoutrewhoizu.gif"/> </div> </body> </html> <file_sep><!DOCTYPE html> <html id='en' lang='en'> <head> <title>yourautofriend.com</title> <link href="ssoistoineypoagh.css" media="screen" rel="stylesheet" type="text/css"/> <link href="oopeinyroon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon"/> <link href="ouzeelouhtootw.jpg" rel='apple-touch-icon' sizes='144x144'> <link href="eytreyhoisefoaht.jpg" rel='apple-touch-icon' sizes='114x114'> <link href="ndyajeyssepuatr.jpg" rel='apple-touch-icon' sizes='72x72'> <link href="eychoopyatya.jpg" rel='apple-touch-icon'> <script type='text/javascript' src='eyzeywyazuneyhi.js'></script></head> <body itemscope itemtype='http://schema.org/WebPage'> <div id='header'> <div class='social visible-desktop'> <ul> <li class='twitter'><a href="301.html">youtubenephew tommy prank call to financial secretary</a></li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com' data-size='medium'></div> </li> <li class='facebook'> <div class='fb-like' data-href='http://www.facebook.com/thehollywoodgossip' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> </ul> </div> <div id='banner'> <a href="140.html"><img alt="The Hollywood Gossip" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xheader-7629f5d243c1cdc904bf535b05ff849f.jpg.pagespeed.ic.CDQOMwZhbJ.jpg" src="stawhaghoix.gif"/></a> </div> <div class='sites visible-desktop'> <a href="76.html">ximsl.com wap.ua</a> | <a href="293.html">youtube knifty knitter</a> | <a href="70.html">xerex pantasya stories download</a> </div> <div class='login visible-desktop'> <a href="293.html">youtube knifty knitter</a> &nbsp;|&nbsp; <a href="290.html">youtube/jessie duplantis piano</a> </div> </div> <div id='wrapper'> <div class='remove_padding'> <div id='leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='navbar' itemscope itemtype='http://schema.org/WPHeader'> <div class='navbar-inner'> <div class='container-fluid'> <a href="208.html">you can see at http://weirdnews.about.com/od/lovesexandmarriage/a/john-falcon-biggest-penis.htm</a> <div class='nav-collapse'> <ul class='nav'> <li class=''><a href="148.html">xxx pictures emily vancamp</a></li> <li class=''><a href="367.html">yututube yenifer lopes porno completo</a></li> <li class=''><a href="238.html">young lolita nude</a></li> <li class=''><a href="57.html">xbox error code 80151011 fix</a></li> <li class=''><a href="410.html">zerobio mono drag</a></li> <li class=''><a href="341.html">yovodude.com</a></li> <li class=''><a href="282.html">youtube fake nudes lee newton</a></li> <li class=''><a href="45.html">xavier quartz gold watch</a></li> <li class='login hidden-desktop'><a href="159.html">xxxvajinas</a></li> <li class='login hidden-desktop'><a href="89.html">xnxx unlimited pron mubi</a></li> </ul> <form action="http://www.thehollywoodgossip.com/search" class='navbar-form pull-right'> <input class="input-medium" id="q" name="q" placeholder="Search" type="search"/> <button class="btn" type="submit"></button> </form> </div> </div> </div> </div> </div> <div class='container-fluid'> <div class='row-fluid'> <div class='span8' id='content'> <ul class="breadcrumb" itemprop="breadcrumb"><li><a href="135.html">xxx imajenes de brenda besares en bikini</a> /</li> <li><a href="275.html">youtube dat viet heo con phim sex</a> /</li> <li><a href="194.html">yoga fitness women with camaltoe xxx</a> /</li> <li><p><a href="http://www.yourautofriend.com/searchresults/results/7/ATVs/Michigan" target="new">ATVs - For Sale in Michigan - YourAutoFriend.com</a><div>Title: 2007 Honda Rincon for $2000 - 11/22/2012. Private Seller 2007 - Honda - Rincon Price: $ 2,000. Mileage: 100. Location of listing: Benton Harbor, .</div><span>http://www.yourautofriend.com/searchresults/results/7/ATVs/Michigan</span></p></li></ul> <div class='video' itemscope itemtype='http://schema.org/VideoObject'> <div class='page-header'> <h1><p><a href="http://www.yourautofriend.com/" target="new">YourAutoFriend.com</a><div>Buy and sell a used or new atv, car or motorcycle in our free photo classifieds. Search our automotive database of used atvs, cars and motorcycles for sale.</div><span>http://www.yourautofriend.com/</span></p></h1> </div> <ul id='sharebar'> <li> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='box_count' data-send='false' data-show-faces='false' data-width='60'></div> </li> <li class='pinit'><a href="283.html" class="pin-it-button" count-layout="vertical" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="sterroizheizerth.gif"/></a></li> <li> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='tall'></div> </li> <li> <a href="145.html">xxx.photo indian actress download . in</a> </li> <li class='comments'> <div class='count comment_count'>1</div> <a href="392.html">zastava m92 folding stock</a> </li> </ul> <div class='sharebarx' style="display:none;"> <ul> <li class='facebook'> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='medium'></div> </li> <li class='twitter'> <a href="index.html">home</a> </li> <li class='pinterest'><a href="146.html" class="pin-it-button" count-layout="horizontal" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="eevuassyaqundee.gif"/></a></li> <li class='comments'> <a href="312.html">youtube robin meade hd</a> 1 </li> </ul> </div> <div class='thumbnail'> <div style="max-width:640px;max-height:459px;margin:0 auto;"> <img src="http://thedomainfo.com/thumbs/yourautofriend.com_medium.jpg" width="640" height="459" /> </div> <div class='caption' itemprop='description'><p><a href="http://www.yourautofriend.com/atvs/" target="new">Sell My ATV - YourAutoFriend.com</a><div>Sell your used or new ATV for free. Post your ATV for sale in our free photo classifieds.</div><span>http://www.yourautofriend.com/atvs/</span></p></div> <div class='rating-form' id='rating_7611' itemprop='aggregateRating' itemscope itemtype='http://schema.org/AggregateRating'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='inline-rating'><ul class="star-rating"><li class="current-rating" style="width:100%;">5.0 / 5.0</li><li><a href="187.html">yiff animation horseplay</a></li> <li><a href="400.html">zastava pap m92 pv pistol, cal. 7.62x39mm</a></li> <li><a href="327.html">youtube videos escandalos caseros pornos</a></li> <li><a href="262.html">you tube boradcast yourself black freaks and booty shakers</a></li> <li><a href="215.html">yougotposted making flames</a></li></ul></div> <br><p><a href="http://www.yourautofriend.com/searchresults/results.asp?catid=7&amp;subcatid=" target="new">ATVs - For Sale in All Locations - YourAutoFriend.com</a><div>Already a member? Sign In | Signup &middot; New Cars &middot; Auto Loan .</div><span>http://www.yourautofriend.com/searchresults/results.asp?catid=7&amp;subcatid=</span></p></div> </div> <br> <ul class='pager'> <li class='next'> <a href="162.html">xxx videos de animales en 3gp</a> </li> </ul> Related Videos: <ul class='thumbnails'> <li class='span4'> <a href="143.html" class="thumbnail"><img alt="Brooke Burke Interview" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/medium_l/brooke-burke-interview.jpg" src="yssusarternotr.gif"/> <div class='caption'>yourautofriend.com Burke Interview</div> </a></li> </ul> <div class="remove_padding"><div id="content_rectangle" itemscope itemtype="http://schema.org/WPAdBlock"> </div></div> Embed Code: <pre class='embed'><p><a href="http://www.yourautofriend.com/searchresults/results/7/ATVs/Wisconsin" target="new">ATVs - For Sale in Wisconsin - YourAutoFriend.com</a><div>Title: 2007 Polaris Ranger XP 700 EFI at $2900 - 11/28/2012. Private Seller 2007 - Polaris - Ranger XP 700 EFI Price: $ 2,900. Mileage: 1,215. Location of .</div><span>http://www.yourautofriend.com/searchresults/results/7/ATVs/Wisconsin</span></p> <p><a href="http://www.yourautofriend.com/searchresults/results.asp?catid=7&amp;subcatid=731" target="new">ATVs - Other For Sale in All Locations - YourAutoFriend.com</a><div>Already a member? Sign In | Signup &middot; New Cars &middot; Auto Loan .</div><span>http://www.yourautofriend.com/searchresults/results.asp?catid=7&amp;subcatid=731</span></p> <p><a href="http://www.yourautofriend.com/newcars/" target="new">New Cars - YourAutoFriend.com</a><div>Looking to buy a new car? With a few easy steps, choose the new car you want and get a free quote from your local dealer.</div><span>http://www.yourautofriend.com/newcars/</span></p></pre> <dl class='dl-horizontal'> <dt>Star:</dt> <dd> <a href="212.html">yougotposted asian</a> </dd> <dt>Related Videos:</dt> <dd><a href="262.html">you tube boradcast yourself black freaks and booty shakers</a></dd> <dt>Original Post:</dt> <dd itemprop='associatedArticle'><a href="77.html">xlola vika forum</a></dd> <dt>Uploaded by:</dt> <dd><a href="213.html">yougotposted.com</a></dd> <dt>Uploaded:</dt> <dd><time datetime="2012-11-08T00:00:00+00:00" itemprop="uploadDate">November 08, 2012</time></dd> <dt>Duration:</dt> <dd> <time datetime='PT3M9S' itemprop='duration'>189 seconds</time> </dd> </dl> <hr> <div id='comments'> <h3> Comments (1 Total) <a href="147.html">xxx pickers danielle tattoos</a> </h3> <a href="138.html">xxx maribel guardia</a> <div id='new_comment'> <form accept-charset="UTF-8" action="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/comments/" class="simple_form form-horizontal" data-remote="true" id="new_comment" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;"/><input name="authenticity_token" type="hidden" value="<KEY>="/></div> <div class='body'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <input name='page' type='hidden'> <input id="comment_parent_id" name="comment[parent_id]" type="hidden"/> <br> <p><p><a href="http://www.yourautofriend.com/advanced_search.asp" target="new">Search - YourAutoFriend.com</a><div>Used &amp; New Automotive Classifieds. Search Atvs, Cars and Motorcycles for Sale by Owner. Buy Used Atvs, Cars and Motorcycles.</div><span>http://www.yourautofriend.com/advanced_search.asp</span></p></p> <div class='row-fluid'> <div class='span8'> <div class="control-group string optional"><label class="string optional control-label" for="comment_anon_name">Name</label><div class="controls"><input class="string optional" id="comment_anon_name" name="comment[anon_name]" size="50" type="text"/><p class="help-block">Your name will appear with your comment</p></div></div> <div class="control-group email optional"><label class="email optional control-label" for="comment_anon_email">Email</label><div class="controls"><input class="string email optional" id="comment_anon_email" name="comment[anon_email]" size="50" type="email"/><p class="help-block"><p><a href="http://www.yourautofriend.com/searchresults/results.asp?catid=7&amp;subcatid=689" target="new">ATVs - Kawasaki For Sale in All Locations - YourAutoFriend.com</a><div>Title: 2005 Kawasaki Brute Force 750i at $1800 - 11/13/2012. Private Seller 2005 - Kawasaki - KVF750A1 Price: $ 1,800. Mileage: 888. Location of listing: .</div><span>http://www.yourautofriend.com/searchresults/results.asp?catid=7&amp;subcatid=689</span></p></p></div></div> </div> <div class='span4 providers'> <a href="224.html">young brook shields naked in videp caps</a> <br> <a href="189.html">yiffy straight</a> <br> <a href="95.html">xvideo.combermudo</a> <br> </div> </div> <div class="control-group text optional"><label class="text optional control-label" for="comment_content">Content</label><div class="controls"><textarea class="text optional" cols="40" id="comment_content" name="comment[content]" rows="20" style="width:320px;height:80px"> </textarea></div></div> </div> <div class='form-actions'> <input class='btn cancel' href="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/#" style="display:none;" type='button' value='Cancel'> <input class="btn btn btn-primary" data-disable-with="Adding..." name="commit" type="submit" value="Add Comment"/> <br style="clear:both;"> </div> </form> </div> <div class='row-fluid'> <div class='span12'> <div class='comment' data-content='<EMAIL>' id='comment_403462' itemid='403462' itemprop='comment' itemscope itemtype='http://schema.org/UserComments'> <div class='comment_meta'> <div class='row-fluid'> <div class='span2'> <img alt="Avatar" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/missing/thumb/xavatar.png.pagespeed.ic.qjczMghcsC.jpg" style="float:left;margin-right:10px;" src="oiplitreendatwyv.gif"/> </div> <div class='span10'> <a href="273.html">youtube cristina saralegui entrevistas a jenni rivera</a> <div class='author' itemprop='creator'>medo</div> <div class='created_at'><time datetime="2012-11-09T02:10:23-05:00" itemprop="commentTime"><p><a href="http://www.yourautofriend.com/placead.asp" target="new">sell my car atv or motorcycle - YourAutoFriend.com</a><div>Sell your used or new car, atv or motorcycle for free. Post your vehicle for sale in our free photo classifieds.</div><span>http://www.yourautofriend.com/placead.asp</span></p></time></div> </div> </div> </div> <div class='alert alert-message error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='comment_body'> <div class='content'> <p itemprop='commentText'><EMAIL></p> </div> </div> <div class='form-actions'> </div> <div class='reply_holder'> </div> </div> </div> </div> </div> </div> </div> <div class='span4' id='sidebar' itemscope itemtype='http://schema.org/WPSideBar'> <div id='sidebar_rectangle' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="121.html">xxx con padre hija gratis movil</a></h4> <div class='clearfix' itemscope itemtype='http://schema.org/Person'> <a href="261.html" itemprop="image"><img alt="<NAME>" class="pull-left" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-nude.jpg.pagespeed.ic.Yp5z6xqFnh.jpg" style="margin-right:10px;" src="itridyotwiboocay.gif"/></a><p><a href="http://www.yourautofriend.com/searchresults/results/7/ATVs/Tennessee" target="new">ATVs - For Sale in Tennessee - YourAutoFriend.com</a><div>Title: 2005 YAMAHA GRIZZLY 4x4 for $1850 - 11/7/2012. Private Seller 2005 - Yamaha - Grizzly Price: $ 1,850. Mileage: 862. Location of listing: Memphis, .</div><span>http://www.yourautofriend.com/searchresults/results/7/ATVs/Tennessee</span></p><dl> <dt>Born</dt> <dd itemprop='birthDate'><time datetime="1971-09-08T00:00:00+00:00">September 08, 1971</time></dd> <dt>Full Name</dt> <dd itemprop='name'>yourautofriend.com Burke</dd> </dl> </div> </div> <div class='widget'> <h4><a href="297.html">youtube mujeres mejicanas cojiendo</a></h4> <ul class='nav'> <li> <a href="294.html" class="clearfix"><img alt="Brooke Burke Prepares For Cancer Surgery" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" style="margin:0 10px 0 0;float:left;" src="yohtepeeqy.gif"/> yourautofriend.com Burke Prepares For Cancer Surgery </a></li> <li> <a href="53.html" class="clearfix"><img alt="Brooke Burke Has Thyroid Cancer" class="span3" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/thumb/brooke-burke-charvet-cancer-me.jpg" style="margin:0 10px 0 0;float:left;" src="gawyasuv.gif"/> yourautofriend.com Burke Has Thyroid Cancer </a></li> <li> <a href="177.html" class="clearfix"><img alt="Brooke Burke Charvet Releases New Lingerie Line" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" style="margin:0 10px 0 0;float:left;" src="kourtoujendoaple.gif"/> yourautofriend.com Burke Charvet Releases New Lingerie Line </a></li> </ul> </div> <div id='skyscraper' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="400.html">zastava pap m92 pv pistol, cal. 7.62x39mm</a></h4> <ul class='thumbnails'> <li class='span4'> <a href="420.html" class="thumbnail"><img alt="Brooke Burke, Cancer Treatment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" src="utayploji.gif"/> </a></li> <li class='span4'> <a href="331.html" class="thumbnail"><img alt="Brooke Burke-Charvet Photo" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-charvet-photo.jpg.pagespeed.ic.eZcSwfCk1Z.jpg" src="treiwhoxu.gif"/> </a></li> <li class='span4'> <a href="289.html" class="thumbnail"><img alt="Brooke Burke Lingerie Line" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" src="wyalegualaf.gif"/> </a></li> <li class='span4'> <a href="331.html" class="thumbnail"><img alt="Brooke Burke and David Charvet" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-and-david-charvet.jpg.pagespeed.ic.iLiOSmNBgG.jpg" src="thywayhtyoch.gif"/> </a></li> <li class='span4'> <a href="287.html" class="thumbnail"><img alt="<NAME> Tom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-and-tom.jpg.pagespeed.ic.OfTSSeJdAZ.jpg" src="yokaywhyodooliwy.gif"/> </a></li> <li class='span4'> <a href="28.html" class="thumbnail"><img alt="The Naked Mom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/the-naked-mom.jpg.pagespeed.ce.2HxOs_fRpY.jpg" src="ooxoukynuakeyfoi.gif"/> </a></li> </ul> </div> <div class='widget'> <h4>Blog Archives</h4> <ul class='nav'> <li><a href="275.html">youtube dat viet heo con phim sex</a></li> <li><a href="317.html">youtubestudio2gabyramirez</a></li> <li><a href="122.html">xxx cum gaggers</a></li> <li><a href="360.html">yummychan.org/jb/</a></li> <li><a href="105.html">xvideos tahiry from love and hip hop</a></li> <li><a href="215.html">yougotposted making flames</a></li> <li><a href="262.html">you tube boradcast yourself black freaks and booty shakers</a></li> <li><a href="222.html">yougotposted videos/</a></li> </ul> </div> </div> </div> <div id='footer' itemscope itemtype='http://schema.org/WPFooter'> <div class='remove_padding'> <div id='footer_leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> </div> <p><p><a href="http://www.worthofweb.com/website-value/yourautofriend.com" target="new">yourautofriend.com is worth $ 1,641 - Worth Of Web</a><div>Evaluate website value of yourautofriend.com and other websites at Worth Of Web. Find data about visits, pageviews, earnings, ad revenue and net worth.</div><span>http://www.worthofweb.com/website-value/yourautofriend.com</span></p></p> <p> <a href="150.html">xxx pussy dilatadas</a> | <a href="16.html">www. wwe divas porn nude and naked pictures.</a> | <a href="156.html">xxx sexxxy pics of jacqueline pennewill</a> | <a href="414.html">ziginy stacey</a> </p> <p>&copy; 2013 The Hollywood Gossip - Celebrity Gossip and Entertainment News</p> <p><a href="276.html" rel="nofollow"><img alt="Sheknows-entertainment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xsheknows-entertainment-0dfb1ed120378c4d8a98720390d31272.png.pagespeed.ic.841FJHTKbK.png" src="xerxozheethrey.gif"/></a></p> </div> </div> <img height="1" width="1" pagespeed_lazy_src="http://tags.bluekai.com/site/3113" alt="" src="rtuagoutrewhoizu.gif"/> </div> </body> </html> <file_sep><!DOCTYPE html> <html id='en' lang='en'> <head> <title>youporn videos porno con vaginas peludas y mojadas</title> <link href="ssoistoineypoagh.css" media="screen" rel="stylesheet" type="text/css"/> <link href="oopeinyroon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon"/> <link href="ouzeelouhtootw.jpg" rel='apple-touch-icon' sizes='144x144'> <link href="eytreyhoisefoaht.jpg" rel='apple-touch-icon' sizes='114x114'> <link href="ndyajeyssepuatr.jpg" rel='apple-touch-icon' sizes='72x72'> <link href="eychoopyatya.jpg" rel='apple-touch-icon'> <script type='text/javascript' src='eyzeywyazuneyhi.js'></script></head> <body itemscope itemtype='http://schema.org/WebPage'> <div id='header'> <div class='social visible-desktop'> <ul> <li class='twitter'><a href="346.html">yroll.theworknumber.com/allegis</a></li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com' data-size='medium'></div> </li> <li class='facebook'> <div class='fb-like' data-href='http://www.facebook.com/thehollywoodgossip' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> </ul> </div> <div id='banner'> <a href="62.html"><img alt="The Hollywood Gossip" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xheader-7629f5d243c1cdc904bf535b05ff849f.jpg.pagespeed.ic.CDQOMwZhbJ.jpg" src="stawhaghoix.gif"/></a> </div> <div class='sites visible-desktop'> <a href="393.html">zastava m92 hand guard sale</a> | <a href="200.html">yoporn videos de sexo gratis para baixar para nokia 303</a> | <a href="75.html">ximena duque nude</a> </div> <div class='login visible-desktop'> <a href="269.html">youtube.com las mejores tanjitas 2012</a> &nbsp;|&nbsp; <a href="93.html">xtube.com pinoy gwapo</a> </div> </div> <div id='wrapper'> <div class='remove_padding'> <div id='leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='navbar' itemscope itemtype='http://schema.org/WPHeader'> <div class='navbar-inner'> <div class='container-fluid'> <a href="390.html">zastava m85pv 223 5.56 hg3088-n ak-47</a> <div class='nav-collapse'> <ul class='nav'> <li class=''><a href="167.html">xyooj aviaries</a></li> <li class=''><a href="131.html">xxx gratis para descargar violadas</a></li> <li class=''><a href="231.html">young girl imgchili</a></li> <li class=''><a href="24.html">www.xxxnepalifucking flm.com</a></li> <li class=''><a href="263.html">youtube brandy from storage wars porn video</a></li> <li class=''><a href="176.html">yaki gerrido sin calsones</a></li> <li class=''><a href="357.html">yugo zastava factory m92 parts kit</a></li> <li class=''><a href="211.html">yougotposted</a></li> <li class='login hidden-desktop'><a href="262.html">you tube boradcast yourself black freaks and booty shakers</a></li> <li class='login hidden-desktop'><a href="347.html">y su novia fakes</a></li> </ul> <form action="http://www.thehollywoodgossip.com/search" class='navbar-form pull-right'> <input class="input-medium" id="q" name="q" placeholder="Search" type="search"/> <button class="btn" type="submit"></button> </form> </div> </div> </div> </div> </div> <div class='container-fluid'> <div class='row-fluid'> <div class='span8' id='content'> <ul class="breadcrumb" itemprop="breadcrumb"><li><a href="141.html">xxx nangi video film</a> /</li> <li><a href="325.html">youtube videos calientes de mexicanas</a> /</li> <li><a href="261.html">you tube bondage</a> /</li> <li><p><a href="http://www.aztecaporno.ws/search/?q=%22Camiseta+Mojada%22&amp;kwid=1006950&amp;c=1" target="new">Camiseta Mojada - Porno</a><div>Camiseta Mojada Porno. . Long Close Up Pussy Movies At Great VideosZ Collection 9:00hace 1 . 7:56hace 1 a&ntilde;oYouPorn report . Peluda/Peludo ( 112376) .</div><span>http://www.aztecaporno.ws/search/?q=%22Camiseta+Mojada%22&amp;kwid=1006950&amp;c=1</span></p></li></ul> <div class='video' itemscope itemtype='http://schema.org/VideoObject'> <div class='page-header'> <h1><p><a href="http://www.cerdas.org/" target="new">Videos Porno y Sexo GRATIS en tu web de Cerdas</a><div>Solo los mejores videos porno y el mejor sexo gratis en espa&ntilde;ol e internacional lo encontrar&aacute;s cada d&iacute;a en tu web adulta y espa&ntilde;ola con incre&iacute;bles Cerdas.</div><span>http://www.cerdas.org/</span></p></h1> </div> <ul id='sharebar'> <li> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='box_count' data-send='false' data-show-faces='false' data-width='60'></div> </li> <li class='pinit'><a href="312.html" class="pin-it-button" count-layout="vertical" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="sterroizheizerth.gif"/></a></li> <li> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='tall'></div> </li> <li> <a href="232.html">young girls pearltree porn tubes</a> </li> <li class='comments'> <div class='count comment_count'>1</div> <a href="398.html">zastava pap m92</a> </li> </ul> <div class='sharebarx' style="display:none;"> <ul> <li class='facebook'> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='medium'></div> </li> <li class='twitter'> <a href="407.html">zendaya coleman nude pics gag reports</a> </li> <li class='pinterest'><a href="277.html" class="pin-it-button" count-layout="horizontal" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="eevuassyaqundee.gif"/></a></li> <li class='comments'> <a href="28.html">www.yennyrivera.com</a> 1 </li> </ul> </div> <div class='thumbnail'> <div style="max-width:640px;max-height:459px;margin:0 auto;"> <img src="http://liferoom.net/images/subject/icon1.gif" width="640" height="459" /> </div> <div class='caption' itemprop='description'><p><a href="http://www.aztecaporno.ws/search/?q=%22Labios+Vaginales%22&amp;kwid=1013950&amp;c=1" target="new">Labios Vaginales - Porno</a><div>Labios Vaginales Porno. . 4:00hace 1 a&ntilde;oYouPorn report &middot; Long Pussy Lips 0: 59hace 1 a&ntilde;oYouPorn . Slut With Huge Pussy Lips Gets Enormous Part6 - Fetish Sex Video 6:07hace 7 . Camiseta Mojada (251) . Peluda/Peludo ( 112376) .</div><span>http://www.aztecaporno.ws/search/?q=%22Labios+Vaginales%22&amp;kwid=1013950&amp;c=1</span></p></div> <div class='rating-form' id='rating_7611' itemprop='aggregateRating' itemscope itemtype='http://schema.org/AggregateRating'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='inline-rating'><ul class="star-rating"><li class="current-rating" style="width:100%;">5.0 / 5.0</li><li><a href="27.html">www.ybr.com/jnjbsc</a></li> <li><a href="30.html">www.youtube.com/heatherchilders</a></li> <li><a href="300.html">youtube nephew tommy prank calls uncut</a></li> <li><a href="364.html">yu tube videos cachondos de jenni rivera</a></li> <li><a href="142.html">xxx negro teen anal sex with girls</a></li></ul></div> <br><p><a href="http://www.parejasfollando.es/tag/guarras/" target="new">Guarras, Guarras con Parejas Follando</a><div>guarras, aut&eacute;nticas parejas follando con guarras, disfruta de los mejores videos porno de parejas follando con guarras y gtr&aacute;tis.</div><span>http://www.parejasfollando.es/tag/guarras/</span></p></div> </div> <br> <ul class='pager'> <li class='next'> <a href="224.html">young brook shields naked in videp caps</a> </li> </ul> Related Videos: <ul class='thumbnails'> <li class='span4'> <a href="403.html" class="thumbnail"><img alt="Brooke Burke Interview" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/medium_l/brooke-burke-interview.jpg" src="yssusarternotr.gif"/> <div class='caption'>youporn videos porno con vaginas peludas y mojadas Burke Interview</div> </a></li> </ul> <div class="remove_padding"><div id="content_rectangle" itemscope itemtype="http://schema.org/WPAdBlock"> </div></div> Embed Code: <pre class='embed'><p><a href="http://goods.marketgid.com/goods/3606752/" target="new">MB ECS 945P-A v3.0(Conroe)</a><div>video porno xxx de la modelo telcel brazillianbuttlift by beachbody donk thatbooty 44 . flamer112 gmail com bump on vagina wall protruding wireing diagram sears . fotos de panochas bien peludas carrie mythbusters nude amniotic fluid odor . elder berman com www youporn 18 com bobby kent crime scene albertsons .</div><span>http://goods.marketgid.com/goods/3606752/</span></p> <p><a href="http://www.pornochilango.com/2012_09_01_archive.html" target="new">PORNO CHILANGO: septiembre 2012</a><div>3 Sep 2012 . Los mejores videos porno gratis en la red con jovencitas mexicanas adictas . mas tener una verga adentro de su humeda panocha peluda, que poner . las tetas y la pone a gatas para metersela en la mojada panocha. . para que le metan la verga en el culo o la vagina para los que esten interesados .</div><span>http://www.pornochilango.com/2012_09_01_archive.html</span></p></pre> <dl class='dl-horizontal'> <dt>Star:</dt> <dd> <a href="356.html">yugo pap sbr</a> </dd> <dt>Related Videos:</dt> <dd><a href="118.html">xxx chiquitas</a></dd> <dt>Original Post:</dt> <dd itemprop='associatedArticle'><a href="125.html">xxx descargar videos desvirgadas 3gmp movil</a></dd> <dt>Uploaded by:</dt> <dd><a href="371.html">zac efron naked</a></dd> <dt>Uploaded:</dt> <dd><time datetime="2012-11-08T00:00:00+00:00" itemprop="uploadDate">November 08, 2012</time></dd> <dt>Duration:</dt> <dd> <time datetime='PT3M9S' itemprop='duration'>189 seconds</time> </dd> </dl> <hr> <div id='comments'> <h3> Comments (1 Total) <a href="222.html">yougotposted videos/</a> </h3> <a href="101.html">xvideos draya</a> <div id='new_comment'> <form accept-charset="UTF-8" action="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/comments/" class="simple_form form-horizontal" data-remote="true" id="new_comment" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;"/><input name="authenticity_token" type="hidden" value="<KEY>></div> <div class='body'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <input name='page' type='hidden'> <input id="comment_parent_id" name="comment[parent_id]" type="hidden"/> <br> <p><p><a href="http://www.youporn.com/watch/152856/hey-there-vagina/" target="new">Hey There Vagina - Free Porn Videos - YouPorn</a><div>Watch Hey There Vagina at Youporn.com - Youporn is the biggest free porn tube site on the net!</div><span>http://www.youporn.com/watch/152856/hey-there-vagina/</span></p></p> <div class='row-fluid'> <div class='span8'> <div class="control-group string optional"><label class="string optional control-label" for="comment_anon_name">Name</label><div class="controls"><input class="string optional" id="comment_anon_name" name="comment[anon_name]" size="50" type="text"/><p class="help-block">Your name will appear with your comment</p></div></div> <div class="control-group email optional"><label class="email optional control-label" for="comment_anon_email">Email</label><div class="controls"><input class="string email optional" id="comment_anon_email" name="comment[anon_email]" size="50" type="email"/><p class="help-block"><p><a href="http://www.parejasfollando.es/tag/webcam/" target="new">Webcam, Webcam con Parejas Follando</a><div>webcam, aut&eacute;nticas parejas follando con webcam, disfruta de los mejores videos porno de parejas follando con webcam y gtr&aacute;tis.</div><span>http://www.parejasfollando.es/tag/webcam/</span></p></p></div></div> </div> <div class='span4 providers'> <a href="124.html">xxx de perros 3g</a> <br> <a href="345.html">yovo fakes</a> <br> <a href="57.html">xbox error code 80151011 fix</a> <br> </div> </div> <div class="control-group text optional"><label class="text optional control-label" for="comment_content">Content</label><div class="controls"><textarea class="text optional" cols="40" id="comment_content" name="comment[content]" rows="20" style="width:320px;height:80px"> </textarea></div></div> </div> <div class='form-actions'> <input class='btn cancel' href="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/#" style="display:none;" type='button' value='Cancel'> <input class="btn btn btn-primary" data-disable-with="Adding..." name="commit" type="submit" value="Add Comment"/> <br style="clear:both;"> </div> </form> </div> <div class='row-fluid'> <div class='span12'> <div class='comment' data-content='<EMAIL>' id='comment_403462' itemid='403462' itemprop='comment' itemscope itemtype='http://schema.org/UserComments'> <div class='comment_meta'> <div class='row-fluid'> <div class='span2'> <img alt="Avatar" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/missing/thumb/xavatar.png.pagespeed.ic.qjczMghcsC.jpg" style="float:left;margin-right:10px;" src="oiplitreendatwyv.gif"/> </div> <div class='span10'> <a href="408.html">zendaya colemans fake nude pics yovo,com</a> <div class='author' itemprop='creator'>medo</div> <div class='created_at'><time datetime="2012-11-09T02:10:23-05:00" itemprop="commentTime"><p><a href="http://www.xnxx-free.com/" target="new">XNXX Free Videos Porno 100% Gratis</a><div>Porno xnxx gratis, videos tube, peliculas porno &#150; xnxx-free.com. Porno porno y m&aacute;s porno en XNXX-FREE Todos los dias actualizamos videos porno en .</div><span>http://www.xnxx-free.com/</span></p></time></div> </div> </div> </div> <div class='alert alert-message error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='comment_body'> <div class='content'> <p itemprop='commentText'><EMAIL></p> </div> </div> <div class='form-actions'> </div> <div class='reply_holder'> </div> </div> </div> </div> </div> </div> </div> <div class='span4' id='sidebar' itemscope itemtype='http://schema.org/WPSideBar'> <div id='sidebar_rectangle' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="21.html">www.xxx.bahbi.hot.chudai.sex.stori.loud.net.com.</a></h4> <div class='clearfix' itemscope itemtype='http://schema.org/Person'> <a href="184.html" itemprop="image"><img alt="<NAME>" class="pull-left" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-nude.jpg.pagespeed.ic.Yp5z6xqFnh.jpg" style="margin-right:10px;" src="itridyotwiboocay.gif"/></a><p><a href="http://www.youporn.com/watch/152856/hey-there-vagina/" target="new">Hey There Vagina - Free Porn Videos - YouPorn</a><div>Watch Hey There Vagina at Youporn.com - Youporn is the biggest free porn tube site on the net!</div><span>http://www.youporn.com/watch/152856/hey-there-vagina/</span></p><dl> <dt>Born</dt> <dd itemprop='birthDate'><time datetime="1971-09-08T00:00:00+00:00">September 08, 1971</time></dd> <dt>Full Name</dt> <dd itemprop='name'>youporn videos porno con vaginas peludas y mojadas Burke</dd> </dl> </div> </div> <div class='widget'> <h4><a href="32.html">www youtuve hiroin anuska shrma nangi phto</a></h4> <ul class='nav'> <li> <a href="351.html" class="clearfix"><img alt="Brooke Burke Prepares For Cancer Surgery" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" style="margin:0 10px 0 0;float:left;" src="yohtepeeqy.gif"/> youporn videos porno con vaginas peludas y mojadas Burke Prepares For Cancer Surgery </a></li> <li> <a href="244.html" class="clearfix"><img alt="Brooke Burke Has Thyroid Cancer" class="span3" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/thumb/brooke-burke-charvet-cancer-me.jpg" style="margin:0 10px 0 0;float:left;" src="gawyasuv.gif"/> youporn videos porno con vaginas peludas y mojadas Burke Has Thyroid Cancer </a></li> <li> <a href="index.html" class="clearfix"><img alt="Brooke Burke Charvet Releases New Lingerie Line" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" style="margin:0 10px 0 0;float:left;" src="kourtoujendoaple.gif"/> youporn videos porno con vaginas peludas y mojadas Burke Charvet Releases New Lingerie Line </a></li> </ul> </div> <div id='skyscraper' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="62.html">xbox live gold membership codes</a></h4> <ul class='thumbnails'> <li class='span4'> <a href="331.html" class="thumbnail"><img alt="Brooke Burke, Cancer Treatment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" src="utayploji.gif"/> </a></li> <li class='span4'> <a href="247.html" class="thumbnail"><img alt="Brooke Burke-Charvet Photo" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-charvet-photo.jpg.pagespeed.ic.eZcSwfCk1Z.jpg" src="treiwhoxu.gif"/> </a></li> <li class='span4'> <a href="157.html" class="thumbnail"><img alt="Brooke Burke Lingerie Line" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" src="wyalegualaf.gif"/> </a></li> <li class='span4'> <a href="122.html" class="thumbnail"><img alt="<NAME> and <NAME>" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-and-david-charvet.jpg.pagespeed.ic.iLiOSmNBgG.jpg" src="thywayhtyoch.gif"/> </a></li> <li class='span4'> <a href="90.html" class="thumbnail"><img alt="<NAME> Tom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-and-tom.jpg.pagespeed.ic.OfTSSeJdAZ.jpg" src="yokaywhyodooliwy.gif"/> </a></li> <li class='span4'> <a href="373.html" class="thumbnail"><img alt="The Naked Mom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/the-naked-mom.jpg.pagespeed.ce.2HxOs_fRpY.jpg" src="ooxoukynuakeyfoi.gif"/> </a></li> </ul> </div> <div class='widget'> <h4>Blog Archives</h4> <ul class='nav'> <li><a href="162.html">xxx videos de animales en 3gp</a></li> <li><a href="147.html">xxx pickers danielle tattoos</a></li> <li><a href="254.html">youporn videos porno con vaginas peludas y mojadas</a></li> <li><a href="112.html">xxx 3 gp de aguelas con sus ñetos</a></li> <li><a href="213.html">yougotposted.com</a></li> <li><a href="175.html">yaki garido sin ropa interior</a></li> <li><a href="300.html">youtube nephew tommy prank calls uncut</a></li> <li><a href="360.html">yummychan.org/jb/</a></li> </ul> </div> </div> </div> <div id='footer' itemscope itemtype='http://schema.org/WPFooter'> <div class='remove_padding'> <div id='footer_leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> </div> <p><p><a href="http://www.xnxx-free.com/" target="new">XNXX Free Videos Porno 100% Gratis</a><div>Porno xnxx gratis, videos tube, peliculas porno &#150; xnxx-free.com. Porno porno y m&aacute;s porno en XNXX-FREE Todos los dias actualizamos videos porno en .</div><span>http://www.xnxx-free.com/</span></p></p> <p> <a href="350.html">yugo car</a> | <a href="60.html">xbox live error 80151011</a> | <a href="172.html">yahoo server unavailable on iphone 5</a> | <a href="115.html">xxxanimalesconmujeres</a> </p> <p>&copy; 2013 The Hollywood Gossip - Celebrity Gossip and Entertainment News</p> <p><a href="81.html" rel="nofollow"><img alt="Sheknows-entertainment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xsheknows-entertainment-0dfb1ed120378c4d8a98720390d31272.png.pagespeed.ic.841FJHTKbK.png" src="xerxozheethrey.gif"/></a></p> </div> </div> <img height="1" width="1" pagespeed_lazy_src="http://tags.bluekai.com/site/3113" alt="" src="rtuagoutrewhoizu.gif"/> </div> </body> </html> <file_sep><!DOCTYPE html> <html id='en' lang='en'> <head> <title>youtubemujeres enseñando tanga</title> <link href="ssoistoineypoagh.css" media="screen" rel="stylesheet" type="text/css"/> <link href="oopeinyroon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon"/> <link href="ouzeelouhtootw.jpg" rel='apple-touch-icon' sizes='144x144'> <link href="eytreyhoisefoaht.jpg" rel='apple-touch-icon' sizes='114x114'> <link href="ndyajeyssepuatr.jpg" rel='apple-touch-icon' sizes='72x72'> <link href="eychoopyatya.jpg" rel='apple-touch-icon'> <script type='text/javascript' src='eyzeywyazuneyhi.js'></script></head> <body itemscope itemtype='http://schema.org/WebPage'> <div id='header'> <div class='social visible-desktop'> <ul> <li class='twitter'><a href="118.html">xxx chiquitas</a></li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com' data-size='medium'></div> </li> <li class='facebook'> <div class='fb-like' data-href='http://www.facebook.com/thehollywoodgossip' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> </ul> </div> <div id='banner'> <a href="123.html"><img alt="The Hollywood Gossip" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xheader-7629f5d243c1cdc904bf535b05ff849f.jpg.pagespeed.ic.CDQOMwZhbJ.jpg" src="stawhaghoix.gif"/></a> </div> <div class='sites visible-desktop'> <a href="192.html">yisela avendano sexo</a> | <a href="152.html">xxx.sex girl amy roloff</a> | <a href="112.html">xxx 3 gp de aguelas con sus ñetos</a> </div> <div class='login visible-desktop'> <a href="134.html">xxx images of nangi girl</a> &nbsp;|&nbsp; <a href="381.html">zara 666 opening</a> </div> </div> <div id='wrapper'> <div class='remove_padding'> <div id='leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='navbar' itemscope itemtype='http://schema.org/WPHeader'> <div class='navbar-inner'> <div class='container-fluid'> <a href="255.html">yourautofriend.com</a> <div class='nav-collapse'> <ul class='nav'> <li class=''><a href="133.html">xxximagenes de panochas abirtas</a></li> <li class=''><a href="396.html">zastava pap m85 pv pistol, 223/5.56 magazines</a></li> <li class=''><a href="36.html">www.zoofilia video porno mujere con perro</a></li> <li class=''><a href="207.html">you can print this blank stat sheet by doing an image google search on</a></li> <li class=''><a href="282.html">youtube fake nudes lee newton</a></li> <li class=''><a href="322.html">youtube video caseros calientes</a></li> <li class=''><a href="330.html">youtube watch v gr 017 sf214</a></li> <li class=''><a href="229.html">young flexible tumblr</a></li> <li class='login hidden-desktop'><a href="232.html">young girls pearltree porn tubes</a></li> <li class='login hidden-desktop'><a href="59.html">xbox live codes</a></li> </ul> <form action="http://www.thehollywoodgossip.com/search" class='navbar-form pull-right'> <input class="input-medium" id="q" name="q" placeholder="Search" type="search"/> <button class="btn" type="submit"></button> </form> </div> </div> </div> </div> </div> <div class='container-fluid'> <div class='row-fluid'> <div class='span8' id='content'> <ul class="breadcrumb" itemprop="breadcrumb"><li><a href="149.html">xxx poringa</a> /</li> <li><a href="111.html">xxx 3gp anime adolescentes</a> /</li> <li><a href="172.html">yahoo server unavailable on iphone 5</a> /</li> <li><p><a href="http://www.youtube.com/watch?v=9jN-KrTgdS0" target="new">TANGAS EN LA CALLE - YouTube</a><div>Feb 7, 2012 . RICAS TANGAS. . Descuido en el camion tanga blancaby RisasINCFeatured 157,006; LENCERIA CON TANGAS DE HILO DENTAL (7) 10:09 .</div><span>http://www.youtube.com/watch?v=9jN-KrTgdS0</span></p></li></ul> <div class='video' itemscope itemtype='http://schema.org/VideoObject'> <div class='page-header'> <h1><p><a href="http://www.abc.es/blogs/nieves/public/post/primeras-imagenes-de-la-materia-oscura-3545.asp" target="new">Primeras im&aacute;genes de la materia oscura - ABC.es</a><div>Apr 27, 2010 . mujeres ense&Atilde;&plusmn;ando calsones . ninnel conde y maribel guardia sin tangas . youtube chicas mostrando las tangas en guadalajara jasmine .</div><span>http://www.abc.es/blogs/nieves/public/post/primeras-imagenes-de-la-materia-oscura-3545.asp</span></p></h1> </div> <ul id='sharebar'> <li> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='box_count' data-send='false' data-show-faces='false' data-width='60'></div> </li> <li class='pinit'><a href="236.html" class="pin-it-button" count-layout="vertical" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="sterroizheizerth.gif"/></a></li> <li> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='tall'></div> </li> <li> <a href="398.html">zastava pap m92</a> </li> <li class='comments'> <div class='count comment_count'>1</div> <a href="175.html">yaki garido sin ropa interior</a> </li> </ul> <div class='sharebarx' style="display:none;"> <ul> <li class='facebook'> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='medium'></div> </li> <li class='twitter'> <a href="346.html">yroll.theworknumber.com/allegis</a> </li> <li class='pinterest'><a href="171.html" class="pin-it-button" count-layout="horizontal" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="eevuassyaqundee.gif"/></a></li> <li class='comments'> <a href="128.html">xxxfotos porno d chicas peludas</a> 1 </li> </ul> </div> <div class='thumbnail'> <div style="max-width:640px;max-height:459px;margin:0 auto;"> <img src="http://i2.ytimg.com/i/qqk_hOU5q9aZcysD_n9V2w/1.jpg?v=bc008c" width="640" height="459" /> </div> <div class='caption' itemprop='description'><p><a href="http://www.youtube.com/watch?v=3uzpg_vWKh8" target="new">Inspector de Tangas - YouTube</a><div>21 Abr 2012 . el puto de flavio mendoza mostrando las tangas de estas minitas. . Maritere Alessandri ense&ntilde;a tangaby intermedio19143,356 views &middot; model . chicas ense&Ntilde; ando sus Tangas by MANUEL16bf260,503 views &middot; Morra,loka .</div><span>http://www.youtube.com/watch?v=3uzpg_vWKh8</span></p></div> <div class='rating-form' id='rating_7611' itemprop='aggregateRating' itemscope itemtype='http://schema.org/AggregateRating'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='inline-rating'><ul class="star-rating"><li class="current-rating" style="width:100%;">5.0 / 5.0</li><li><a href="27.html">www.ybr.com/jnjbsc</a></li> <li><a href="384.html">zara cover letter</a></li> <li><a href="29.html">www.youtube. bajar en celular video sexo porno corto mujer con zoofila.com</a></li> <li><a href="414.html">ziginy stacey</a></li> <li><a href="81.html">xmas pay rise sex game playthrough</a></li></ul></div> <br><p><a href="http://www.youtube.com/watch?v=9jN-KrTgdS0" target="new">TANGAS EN LA CALLE - YouTube</a><div>Feb 7, 2012 . RICAS TANGAS. . Descuido en el camion tanga blancaby RisasINCFeatured 157,006; LENCERIA CON TANGAS DE HILO DENTAL (7) 10:09 .</div><span>http://www.youtube.com/watch?v=9jN-KrTgdS0</span></p></div> </div> <br> <ul class='pager'> <li class='next'> <a href="45.html">xavier quartz gold watch</a> </li> </ul> Related Videos: <ul class='thumbnails'> <li class='span4'> <a href="368.html" class="thumbnail"><img alt="Brooke Burke Interview" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/medium_l/brooke-burke-interview.jpg" src="yssusarternotr.gif"/> <div class='caption'>youtubemujeres enseñando tanga Burke Interview</div> </a></li> </ul> <div class="remove_padding"><div id="content_rectangle" itemscope itemtype="http://schema.org/WPAdBlock"> </div></div> Embed Code: <pre class='embed'><p><a href="http://www.abc.es/blogs/nieves/public/post/primeras-imagenes-de-la-materia-oscura-3545.asp" target="new">Primeras im&aacute;genes de la materia oscura - ABC.es</a><div>Apr 27, 2010 . mujeres ense&Atilde;&plusmn;ando calsones . ninnel conde y maribel guardia sin tangas . youtube chicas mostrando las tangas en guadalajara jasmine .</div><span>http://www.abc.es/blogs/nieves/public/post/primeras-imagenes-de-la-materia-oscura-3545.asp</span></p> <p><a href="http://www.youtube.com/watch?v=3uzpg_vWKh8" target="new">Inspector de Tangas - YouTube</a><div>21 Abr 2012 . el puto de flavio mendoza mostrando las tangas de estas minitas. . Maritere Alessandri ense&ntilde;a tangaby intermedio19143,356 views &middot; model . chicas ense&Ntilde; ando sus Tangas by MANUEL16bf260,503 views &middot; Morra,loka .</div><span>http://www.youtube.com/watch?v=3uzpg_vWKh8</span></p></pre> <dl class='dl-horizontal'> <dt>Star:</dt> <dd> <a href="75.html">ximena duque nude</a> </dd> <dt>Related Videos:</dt> <dd><a href="68.html">xerex kwento</a></dd> <dt>Original Post:</dt> <dd itemprop='associatedArticle'><a href="380.html">zanx</a></dd> <dt>Uploaded by:</dt> <dd><a href="255.html">yourautofriend.com</a></dd> <dt>Uploaded:</dt> <dd><time datetime="2012-11-08T00:00:00+00:00" itemprop="uploadDate">November 08, 2012</time></dd> <dt>Duration:</dt> <dd> <time datetime='PT3M9S' itemprop='duration'>189 seconds</time> </dd> </dl> <hr> <div id='comments'> <h3> Comments (1 Total) <a href="276.html">youtube deeann donovan</a> </h3> <a href="112.html">xxx 3 gp de aguelas con sus ñetos</a> <div id='new_comment'> <form accept-charset="UTF-8" action="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/comments/" class="simple_form form-horizontal" data-remote="true" id="new_comment" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;"/><input name="authenticity_token" type="hidden" value="<KEY>></div> <div class='body'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <input name='page' type='hidden'> <input id="comment_parent_id" name="comment[parent_id]" type="hidden"/> <br> <p><p><a href="http://www.php-calendar.com/php-calendar/index.php?action=display_day&amp;year=2011&amp;month=1&amp;day=28" target="new">January 28 - PHP-Calendar</a><div>28 Ene 2011. <NAME>, 503988, rjxrw.wo.tc/56446 Fotos de tangas en la . ando todo, 97907, idhbsfh.wo.tc/0801zf Gallos de pelea en houston, . Youtube mujeres gravadas orinando, %]]], kvdbg.wo.tc/rj5 Videos de abemtura, 081601, . quotes, 00238, 12157.xeviu.nl-web.net/ Chicas ensena ndo, 37297, .</div><span>http://www.php-calendar.com/php-calendar/index.php?action=display_day&amp;year=2011&amp;month=1&amp;day=28</span></p></p> <div class='row-fluid'> <div class='span8'> <div class="control-group string optional"><label class="string optional control-label" for="comment_anon_name">Name</label><div class="controls"><input class="string optional" id="comment_anon_name" name="comment[anon_name]" size="50" type="text"/><p class="help-block">Your name will appear with your comment</p></div></div> <div class="control-group email optional"><label class="email optional control-label" for="comment_anon_email">Email</label><div class="controls"><input class="string email optional" id="comment_anon_email" name="comment[anon_email]" size="50" type="email"/><p class="help-block"><p><a href="http://www.abc.es/blogs/nieves/public/post/primeras-imagenes-de-la-materia-oscura-3545.asp" target="new">Primeras im&aacute;genes de la materia oscura - ABC.es</a><div>Apr 27, 2010 . mujeres ense&Atilde;&plusmn;ando calsones . ninnel conde y maribel guardia sin tangas . youtube chicas mostrando las tangas en guadalajara jasmine .</div><span>http://www.abc.es/blogs/nieves/public/post/primeras-imagenes-de-la-materia-oscura-3545.asp</span></p></p></div></div> </div> <div class='span4 providers'> <a href="165.html">xxx with sunakshi</a> <br> <a href="176.html">yaki gerrido sin calsones</a> <br> <a href="174.html">yahtzee scorecard</a> <br> </div> </div> <div class="control-group text optional"><label class="text optional control-label" for="comment_content">Content</label><div class="controls"><textarea class="text optional" cols="40" id="comment_content" name="comment[content]" rows="20" style="width:320px;height:80px"> </textarea></div></div> </div> <div class='form-actions'> <input class='btn cancel' href="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/#" style="display:none;" type='button' value='Cancel'> <input class="btn btn btn-primary" data-disable-with="Adding..." name="commit" type="submit" value="Add Comment"/> <br style="clear:both;"> </div> </form> </div> <div class='row-fluid'> <div class='span12'> <div class='comment' data-content='<EMAIL>' id='comment_403462' itemid='403462' itemprop='comment' itemscope itemtype='http://schema.org/UserComments'> <div class='comment_meta'> <div class='row-fluid'> <div class='span2'> <img alt="Avatar" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/missing/thumb/xavatar.png.pagespeed.ic.qjczMghcsC.jpg" style="float:left;margin-right:10px;" src="oiplitreendatwyv.gif"/> </div> <div class='span10'> <a href="39.html">xacyfex.github.com las-mujeres-mas-peludas-de-la-panocha.html</a> <div class='author' itemprop='creator'>medo</div> <div class='created_at'><time datetime="2012-11-09T02:10:23-05:00" itemprop="commentTime"><p><a href="http://www.youtube.com/watch?v=9jN-KrTgdS0" target="new">TANGAS EN LA CALLE - YouTube</a><div>Feb 7, 2012 . RICAS TANGAS. . Descuido en el camion tanga blancaby RisasINCFeatured 157,006; LENCERIA CON TANGAS DE HILO DENTAL (7) 10:09 .</div><span>http://www.youtube.com/watch?v=9jN-KrTgdS0</span></p></time></div> </div> </div> </div> <div class='alert alert-message error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='comment_body'> <div class='content'> <p itemprop='commentText'><EMAIL></p> </div> </div> <div class='form-actions'> </div> <div class='reply_holder'> </div> </div> </div> </div> </div> </div> </div> <div class='span4' id='sidebar' itemscope itemtype='http://schema.org/WPSideBar'> <div id='sidebar_rectangle' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="374.html">zach roloff college arrest</a></h4> <div class='clearfix' itemscope itemtype='http://schema.org/Person'> <a href="367.html" itemprop="image"><img alt="<NAME>" class="pull-left" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-nude.jpg.pagespeed.ic.Yp5z6xqFnh.jpg" style="margin-right:10px;" src="itridyotwiboocay.gif"/></a><p><a href="http://www.youtube.com/watch?v=3uzpg_vWKh8" target="new">Inspector de Tangas - YouTube</a><div>21 Abr 2012 . el puto de flavio mendoza mostrando las tangas de estas minitas. . Maritere Alessandri ense&ntilde;a tangaby intermedio19143,356 views &middot; model . chicas ense&Ntilde; ando sus Tangas by MANUEL16bf260,503 views &middot; Morra,loka .</div><span>http://www.youtube.com/watch?v=3uzpg_vWKh8</span></p><dl> <dt>Born</dt> <dd itemprop='birthDate'><time datetime="1971-09-08T00:00:00+00:00">September 08, 1971</time></dd> <dt>Full Name</dt> <dd itemprop='name'><NAME></dd> </dl> </div> </div> <div class='widget'> <h4><a href="413.html">zharick leon interview magazine</a></h4> <ul class='nav'> <li> <a href="36.html" class="clearfix"><img alt="Brooke Burke Prepares For Cancer Surgery" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" style="margin:0 10px 0 0;float:left;" src="yohtepeeqy.gif"/> youtubemujeres enseñando tanga Burke Prepares For Cancer Surgery </a></li> <li> <a href="344.html" class="clearfix"><img alt="Brooke Burke Has Thyroid Cancer" class="span3" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/thumb/brooke-burke-charvet-cancer-me.jpg" style="margin:0 10px 0 0;float:left;" src="gawyasuv.gif"/> youtubemujeres enseñando tanga Burke Has Thyroid Cancer </a></li> <li> <a href="311.html" class="clearfix"><img alt="Brooke Burke Charvet Releases New Lingerie Line" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" style="margin:0 10px 0 0;float:left;" src="kourtoujendoaple.gif"/> youtubemujeres enseñando tanga Burke Charvet Releases New Lingerie Line </a></li> </ul> </div> <div id='skyscraper' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="207.html">you can print this blank stat sheet by doing an image google search on</a></h4> <ul class='thumbnails'> <li class='span4'> <a href="191.html" class="thumbnail"><img alt="Brooke Burke, Cancer Treatment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" src="utayploji.gif"/> </a></li> <li class='span4'> <a href="180.html" class="thumbnail"><img alt="Brooke Burke-Charvet Photo" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-charvet-photo.jpg.pagespeed.ic.eZcSwfCk1Z.jpg" src="treiwhoxu.gif"/> </a></li> <li class='span4'> <a href="181.html" class="thumbnail"><img alt="Brooke Burke Lingerie Line" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" src="wyalegualaf.gif"/> </a></li> <li class='span4'> <a href="137.html" class="thumbnail"><img alt="Brooke Burke and David Charvet" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-and-david-charvet.jpg.pagespeed.ic.iLiOSmNBgG.jpg" src="thywayhtyoch.gif"/> </a></li> <li class='span4'> <a href="329.html" class="thumbnail"><img alt="Brooke and Tom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-and-tom.jpg.pagespeed.ic.OfTSSeJdAZ.jpg" src="yokaywhyodooliwy.gif"/> </a></li> <li class='span4'> <a href="284.html" class="thumbnail"><img alt="The Naked Mom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/the-naked-mom.jpg.pagespeed.ce.2HxOs_fRpY.jpg" src="ooxoukynuakeyfoi.gif"/> </a></li> </ul> </div> <div class='widget'> <h4>Blog Archives</h4> <ul class='nav'> <li><a href="139.html">xxxming girl</a></li> <li><a href="50.html">xbox 360 controller motherboard replacement</a></li> <li><a href="137.html">xxx jail bait non nude</a></li> <li><a href="index.html">home</a></li> <li><a href="110.html">xxx 2012 con animales</a></li> <li><a href="371.html">zac efron naked</a></li> <li><a href="44.html">+xavier made in assembled in malaysia swiss watches black man an woman</a></li> <li><a href="134.html">xxx images of nangi girl</a></li> </ul> </div> </div> </div> <div id='footer' itemscope itemtype='http://schema.org/WPFooter'> <div class='remove_padding'> <div id='footer_leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> </div> <p><p><a href="http://www.abc.es/blogs/nieves/public/post/primeras-imagenes-de-la-materia-oscura-3545.asp" target="new">Primeras im&aacute;genes de la materia oscura - ABC.es</a><div>Apr 27, 2010 . mujeres ense&Atilde;&plusmn;ando calsones . ninnel conde y maribel guardia sin tangas . youtube chicas mostrando las tangas en guadalajara jasmine .</div><span>http://www.abc.es/blogs/nieves/public/post/primeras-imagenes-de-la-materia-oscura-3545.asp</span></p></p> <p> <a href="39.html">xacyfex.github.com las-mujeres-mas-peludas-de-la-panocha.html</a> | <a href="112.html">xxx 3 gp de aguelas con sus ñetos</a> | <a href="163.html">xxx video virgin anak sd smp</a> | <a href="347.html">y su novia fakes</a> </p> <p>&copy; 2013 The Hollywood Gossip - Celebrity Gossip and Entertainment News</p> <p><a href="243.html" rel="nofollow"><img alt="Sheknows-entertainment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xsheknows-entertainment-0dfb1ed120378c4d8a98720390d31272.png.pagespeed.ic.841FJHTKbK.png" src="xerxozheethrey.gif"/></a></p> </div> </div> <img height="1" width="1" pagespeed_lazy_src="http://tags.bluekai.com/site/3113" alt="" src="rtuagoutrewhoizu.gif"/> </div> </body> </html> <file_sep><!DOCTYPE html> <html id='en' lang='en'> <head> <title>yougotposted tiffany bannister</title> <link href="ssoistoineypoagh.css" media="screen" rel="stylesheet" type="text/css"/> <link href="oopeinyroon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon"/> <link href="ouzeelouhtootw.jpg" rel='apple-touch-icon' sizes='144x144'> <link href="eytreyhoisefoaht.jpg" rel='apple-touch-icon' sizes='114x114'> <link href="ndyajeyssepuatr.jpg" rel='apple-touch-icon' sizes='72x72'> <link href="eychoopyatya.jpg" rel='apple-touch-icon'> <script type='text/javascript' src='eyzeywyazuneyhi.js'></script></head> <body itemscope itemtype='http://schema.org/WebPage'> <div id='header'> <div class='social visible-desktop'> <ul> <li class='twitter'><a href="184.html">ya se dio a conocer la carta de jenny rivera?</a></li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com' data-size='medium'></div> </li> <li class='facebook'> <div class='fb-like' data-href='http://www.facebook.com/thehollywoodgossip' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> </ul> </div> <div id='banner'> <a href="385.html"><img alt="The Hollywood Gossip" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xheader-7629f5d243c1cdc904bf535b05ff849f.jpg.pagespeed.ic.CDQOMwZhbJ.jpg" src="stawhaghoix.gif"/></a> </div> <div class='sites visible-desktop'> <a href="406.html">zendaya coleman nude fakes</a> | <a href="183.html">yarel ramos porn</a> | <a href="200.html">yoporn videos de sexo gratis para baixar para nokia 303</a> </div> <div class='login visible-desktop'> <a href="95.html">xvideo.combermudo</a> &nbsp;|&nbsp; <a href="index.html">home</a> </div> </div> <div id='wrapper'> <div class='remove_padding'> <div id='leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='navbar' itemscope itemtype='http://schema.org/WPHeader'> <div class='navbar-inner'> <div class='container-fluid'> <a href="328.html">youtube. videos mujeres con animales gratis</a> <div class='nav-collapse'> <ul class='nav'> <li class=''><a href="307.html">youtube pthc bath</a></li> <li class=''><a href="18.html">www.www.ucard.chase.com</a></li> <li class=''><a href="410.html">zerobio mono drag</a></li> <li class=''><a href="144.html">xxx nude madhori,katrina,karishma pics fock photos</a></li> <li class=''><a href="144.html">xxx nude madhori,katrina,karishma pics fock photos</a></li> <li class=''><a href="183.html">yarel ramos porn</a></li> <li class=''><a href="263.html">youtube brandy from storage wars porn video</a></li> <li class=''><a href="22.html">wwwxxx com bulu sexy video sex archive</a></li> <li class='login hidden-desktop'><a href="23.html">www xxx hot sexy nangi picture com</a></li> <li class='login hidden-desktop'><a href="181.html">yaqui guerrido en tangas</a></li> </ul> <form action="http://www.thehollywoodgossip.com/search" class='navbar-form pull-right'> <input class="input-medium" id="q" name="q" placeholder="Search" type="search"/> <button class="btn" type="submit"></button> </form> </div> </div> </div> </div> </div> <div class='container-fluid'> <div class='row-fluid'> <div class='span8' id='content'> <ul class="breadcrumb" itemprop="breadcrumb"><li><a href="130.html">xxxfunny.mobi</a> /</li> <li><a href="141.html">xxx nangi video film</a> /</li> <li><a href="391.html">zastava m85 pv 5.56 .223 pistol ak-47 in 223</a> /</li> <li><p><a href="http://www.youtube.com/watch?v=K9aSkQ_Kmj8" target="new">P64 x Davie Don&#39;t Exist - Get Nasty Girl [Tiff Bannister Song] - YouTube</a><div>Dec 19, 2012 . Remove; Report profile image; Flag for spam; Block User; Unblock User. meganmeg1 2 weeks ago. Tiffany bannister ,? does not look like a bag .</div><span>http://www.youtube.com/watch?v=K9aSkQ_Kmj8</span></p></li></ul> <div class='video' itemscope itemtype='http://schema.org/VideoObject'> <div class='page-header'> <h1><p><a href="http://www.facebook.com/shamus.mcclernand" target="new"><NAME> | Facebook</a><div>. Not A Cop, R.I.P Sandy Hook Elementary School Children, YouGotPosted, . Niggas be like, <NAME>, Nestle Toll House, &#39;<NAME>, Ariana Grande., Team . Dwayne The Rock Johnson, ?The Crush with Lee &amp; Tiffany, Dennis Prager, .</div><span>http://www.facebook.com/shamus.mcclernand</span></p></h1> </div> <ul id='sharebar'> <li> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='box_count' data-send='false' data-show-faces='false' data-width='60'></div> </li> <li class='pinit'><a href="322.html" class="pin-it-button" count-layout="vertical" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="sterroizheizerth.gif"/></a></li> <li> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='tall'></div> </li> <li> <a href="293.html">youtube knifty knitter</a> </li> <li class='comments'> <div class='count comment_count'>1</div> <a href="109.html">xxvideo niñas de prepa</a> </li> </ul> <div class='sharebarx' style="display:none;"> <ul> <li class='facebook'> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='medium'></div> </li> <li class='twitter'> <a href="305.html">youtube pleyboy <NAME></a> </li> <li class='pinterest'><a href="173.html" class="pin-it-button" count-layout="horizontal" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="eevuassyaqundee.gif"/></a></li> <li class='comments'> <a href="356.html">yugo pap sbr</a> 1 </li> </ul> </div> <div class='thumbnail'> <div style="max-width:640px;max-height:459px;margin:0 auto;"> <img src="http://profile.ak.fbcdn.net/hprofile-ak-ash4/370639_1543203303_893746712_q.jpg" width="640" height="459" /> </div> <div class='caption' itemprop='description'><p><a href="http://www.youtube.com/user/ohlookshawnkhan" target="new"><NAME> - YouTube</a><div><NAME> commented 2 weeks ago. yougotposted c0m / tiffany-bannister-from -marlton-nj. You&#39;re welcome. 2:32. Watch Later .</div><span>http://www.youtube.com/user/ohlookshawnkhan</span></p></div> <div class='rating-form' id='rating_7611' itemprop='aggregateRating' itemscope itemtype='http://schema.org/AggregateRating'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='inline-rating'><ul class="star-rating"><li class="current-rating" style="width:100%;">5.0 / 5.0</li><li><a href="66.html">xdesi.mobi.bihara.actress</a></li> <li><a href="267.html">youtube chapo guzman video</a></li> <li><a href="241.html">young manufacturing bull pup stock marlin 795 photo</a></li> <li><a href="37.html">www.zurichna.com/nydbl to:</a></li> <li><a href="216.html">you got posted tiffany bannister</a></li></ul></div> <br><p><a href="http://yougotposted.com/category/girls/page/2/" target="new">Girls | You Got Posted - Part 2</a><div>7 hours ago . You Got Posted&#153; is for ADULTS ONLY. If you are under 18 years old, exit. You must agree to our terms before accessing this site.</div><span>http://yougotposted.com/category/girls/page/2/</span></p></div> </div> <br> <ul class='pager'> <li class='next'> <a href="148.html">xxx pictures emily vancamp</a> </li> </ul> Related Videos: <ul class='thumbnails'> <li class='span4'> <a href="5.html" class="thumbnail"><img alt="Brooke Burke Interview" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/medium_l/brooke-burke-interview.jpg" src="yssusarternotr.gif"/> <div class='caption'>yougotposted tiffany bannister Burke Interview</div> </a></li> </ul> <div class="remove_padding"><div id="content_rectangle" itemscope itemtype="http://schema.org/WPAdBlock"> </div></div> Embed Code: <pre class='embed'><p><a href="http://www.facebook.com/tyler.bloss.1" target="new"><NAME> | Facebook</a><div>. YouGotPosted, The Baddest Females, The Craziest Fights, Candy Mountain . BlocktoberFest, <NAME>, <NAME> is for guys who have pornhub .</div><span>http://www.facebook.com/tyler.bloss.1</span></p> <p><a href="http://www.youtube.com/all_comments?v=rrPcE2MMRq8" target="new">Page 1 of comments on tiff dancin/twerk - YouTube</a><div>Remove; Report profile image; Flag for spam; Block User; Unblock User. byKlepto 2 weeks ago. yougotposted(DOT)com(/)tiffany-bannister-from-marlton- nj(/) .</div><span>http://www.youtube.com/all_comments?v=rrPcE2MMRq8</span></p> <p><a href="http://www.youtube.com/watch?v=jHbHQLae1XU" target="new">My Personal Blog: The YouGotPosted website - YouTube</a><div>Nov 27, 2012 . you got posted up by an old dudeby datboyrob89 views &middot; <NAME> 3D 1: 36. Watch Later <NAME>annister 3Dby dakthunder4447,805 .</div><span>http://www.youtube.com/watch?v=jHbHQLae1XU</span></p></pre> <dl class='dl-horizontal'> <dt>Star:</dt> <dd> <a href="113.html">xxx 3gp de maestros/as</a> </dd> <dt>Related Videos:</dt> <dd><a href="62.html">xbox live gold membership codes</a></dd> <dt>Original Post:</dt> <dd itemprop='associatedArticle'><a href="176.html">yaki gerrido sin calsones</a></dd> <dt>Uploaded by:</dt> <dd><a href="217.html">yougotposted <NAME></a></dd> <dt>Uploaded:</dt> <dd><time datetime="2012-11-08T00:00:00+00:00" itemprop="uploadDate">November 08, 2012</time></dd> <dt>Duration:</dt> <dd> <time datetime='PT3M9S' itemprop='duration'>189 seconds</time> </dd> </dl> <hr> <div id='comments'> <h3> Comments (1 Total) <a href="200.html">yoporn videos de sexo gratis para baixar para nokia 303</a> </h3> <a href="350.html">yugo car</a> <div id='new_comment'> <form accept-charset="UTF-8" action="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/comments/" class="simple_form form-horizontal" data-remote="true" id="new_comment" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;"/><input name="authenticity_token" type="hidden" value="<KEY>="/></div> <div class='body'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <input name='page' type='hidden'> <input id="comment_parent_id" name="comment[parent_id]" type="hidden"/> <br> <p><p><a href="http://yougotposted.com/category/new-jersey/" target="new">New Jersey | You Got Posted</a><div>54 minutes ago . You Got Posted&#153; is for ADULTS ONLY. If you are under 18 years old, exit. You must agree to our terms before accessing this site.</div><span>http://yougotposted.com/category/new-jersey/</span></p></p> <div class='row-fluid'> <div class='span8'> <div class="control-group string optional"><label class="string optional control-label" for="comment_anon_name">Name</label><div class="controls"><input class="string optional" id="comment_anon_name" name="comment[anon_name]" size="50" type="text"/><p class="help-block">Your name will appear with your comment</p></div></div> <div class="control-group email optional"><label class="email optional control-label" for="comment_anon_email">Email</label><div class="controls"><input class="string email optional" id="comment_anon_email" name="comment[anon_email]" size="50" type="email"/><p class="help-block"><p><a href="http://www.facebook.com/shamus.mcclernand" target="new"><NAME> | Facebook</a><div>. Not A Cop, R.I.P Sandy Hook Elementary School Children, YouGotPosted, . Niggas be like, <NAME>, Nestle Toll House, &#39;<NAME>, <NAME>., Team . Dwayne The R<NAME>, ?The Crush with Lee &amp; Tiffany, Dennis Prager, .</div><span>http://www.facebook.com/shamus.mcclernand</span></p></p></div></div> </div> <div class='span4 providers'> <a href="190.html">yisela avendano free sex videos</a> <br> <a href="146.html">xxx photos of sonakshi sinha</a> <br> <a href="118.html">xxx chiquitas</a> <br> </div> </div> <div class="control-group text optional"><label class="text optional control-label" for="comment_content">Content</label><div class="controls"><textarea class="text optional" cols="40" id="comment_content" name="comment[content]" rows="20" style="width:320px;height:80px"> </textarea></div></div> </div> <div class='form-actions'> <input class='btn cancel' href="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/#" style="display:none;" type='button' value='Cancel'> <input class="btn btn btn-primary" data-disable-with="Adding..." name="commit" type="submit" value="Add Comment"/> <br style="clear:both;"> </div> </form> </div> <div class='row-fluid'> <div class='span12'> <div class='comment' data-content='<EMAIL>' id='comment_403462' itemid='403462' itemprop='comment' itemscope itemtype='http://schema.org/UserComments'> <div class='comment_meta'> <div class='row-fluid'> <div class='span2'> <img alt="Avatar" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/missing/thumb/xavatar.png.pagespeed.ic.qjczMghcsC.jpg" style="float:left;margin-right:10px;" src="oiplitreendatwyv.gif"/> </div> <div class='span10'> <a href="361.html">yuo tube jenny rivera her funeral</a> <div class='author' itemprop='creator'>medo</div> <div class='created_at'><time datetime="2012-11-09T02:10:23-05:00" itemprop="commentTime"><p><a href="http://www.youtube.com/all_comments?v=rrPcE2MMRq8" target="new">Page 1 of comments on tiff dancin/twerk - YouTube</a><div>Remove; Report profile image; Flag for spam; Block User; Unblock User. byKlepto 2 weeks ago. yougotposted(DOT)com(/)tiffany-bannister-from-marlton- nj(/) .</div><span>http://www.youtube.com/all_comments?v=rrPcE2MMRq8</span></p></time></div> </div> </div> </div> <div class='alert alert-message error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='comment_body'> <div class='content'> <p itemprop='commentText'><EMAIL></p> </div> </div> <div class='form-actions'> </div> <div class='reply_holder'> </div> </div> </div> </div> </div> </div> </div> <div class='span4' id='sidebar' itemscope itemtype='http://schema.org/WPSideBar'> <div id='sidebar_rectangle' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="251.html">youporn.com/nn preteen models</a></h4> <div class='clearfix' itemscope itemtype='http://schema.org/Person'> <a href="394.html" itemprop="image"><img alt="Brooke Burke Nude" class="pull-left" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-nude.jpg.pagespeed.ic.Yp5z6xqFnh.jpg" style="margin-right:10px;" src="itridyotwiboocay.gif"/></a><p><a href="http://www.youtube.com/watch?v=K9aSkQ_Kmj8" target="new">P64 x Davie Don&#39;t Exist - Get Nasty Girl [Tiff Bannister Song] - YouTube</a><div>Dec 19, 2012 . Remove; Report profile image; Flag for spam; Block User; Unblock User. meganmeg1 2 weeks ago. Tiffany bannister ,? does not look like a bag .</div><span>http://www.youtube.com/watch?v=K9aSkQ_Kmj8</span></p><dl> <dt>Born</dt> <dd itemprop='birthDate'><time datetime="1971-09-08T00:00:00+00:00">September 08, 1971</time></dd> <dt>Full Name</dt> <dd itemprop='name'>yougotposted tiffany bannister Burke</dd> </dl> </div> </div> <div class='widget'> <h4><a href="223.html">youjiiz para telefonos nokia 201</a></h4> <ul class='nav'> <li> <a href="341.html" class="clearfix"><img alt="Brooke Burke Prepares For Cancer Surgery" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" style="margin:0 10px 0 0;float:left;" src="yohtepeeqy.gif"/> yougotposted tiffany bannister Burke Prepares For Cancer Surgery </a></li> <li> <a href="159.html" class="clearfix"><img alt="Brooke Burke Has Thyroid Cancer" class="span3" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/thumb/brooke-burke-charvet-cancer-me.jpg" style="margin:0 10px 0 0;float:left;" src="gawyasuv.gif"/> yougotposted tiffany bannister Burke Has Thyroid Cancer </a></li> <li> <a href="146.html" class="clearfix"><img alt="Brooke Burke Charvet Releases New Lingerie Line" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" style="margin:0 10px 0 0;float:left;" src="kourtoujendoaple.gif"/> yougotposted tiffany bannister Burke Charvet Releases New Lingerie Line </a></li> </ul> </div> <div id='skyscraper' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="51.html">xbox 360 voice changer headset</a></h4> <ul class='thumbnails'> <li class='span4'> <a href="101.html" class="thumbnail"><img alt="Brooke Burke, Cancer Treatment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" src="utayploji.gif"/> </a></li> <li class='span4'> <a href="319.html" class="thumbnail"><img alt="Brooke Burke-Charvet Photo" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-charvet-photo.jpg.pagespeed.ic.eZcSwfCk1Z.jpg" src="treiwhoxu.gif"/> </a></li> <li class='span4'> <a href="195.html" class="thumbnail"><img alt="Brooke Burke Lingerie Line" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" src="wyalegualaf.gif"/> </a></li> <li class='span4'> <a href="333.html" class="thumbnail"><img alt="<NAME> and <NAME>" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-and-david-charvet.jpg.pagespeed.ic.iLiOSmNBgG.jpg" src="thywayhtyoch.gif"/> </a></li> <li class='span4'> <a href="417.html" class="thumbnail"><img alt="<NAME> Tom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-and-tom.jpg.pagespeed.ic.OfTSSeJdAZ.jpg" src="yokaywhyodooliwy.gif"/> </a></li> <li class='span4'> <a href="20.html" class="thumbnail"><img alt="The Naked Mom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/the-naked-mom.jpg.pagespeed.ce.2HxOs_fRpY.jpg" src="ooxoukynuakeyfoi.gif"/> </a></li> </ul> </div> <div class='widget'> <h4>Blog Archives</h4> <ul class='nav'> <li><a href="15.html">www.worldstaruncut.com</a></li> <li><a href="27.html">www.ybr.com/jnjbsc</a></li> <li><a href="208.html">you can see at http://weirdnews.about.com/od/lovesexandmarriage/a/john-falcon-biggest-penis.htm</a></li> <li><a href="51.html">xbox 360 voice changer headset</a></li> <li><a href="60.html">xbox live error 80151011</a></li> <li><a href="43.html">xarelto coupons with insurance coverage</a></li> <li><a href="386.html">zara sale</a></li> <li><a href="77.html">xlola vika forum</a></li> </ul> </div> </div> </div> <div id='footer' itemscope itemtype='http://schema.org/WPFooter'> <div class='remove_padding'> <div id='footer_leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> </div> <p><p><a href="http://www.youtube.com/user/ohlookshawnkhan" target="new"><NAME> - YouTube</a><div><NAME> commented 2 weeks ago. yougotposted c0m / tiffany-bannister-from -marlton-nj. You&#39;re welcome. 2:32. Watch Later .</div><span>http://www.youtube.com/user/ohlookshawnkhan</span></p></p> <p> <a href="401.html">zastava pap m92 pv pistol muzzle brake</a> | <a href="351.html">yugo car company</a> | <a href="93.html">xtube.com pinoy gwapo</a> | <a href="337.html">yovdud</a> </p> <p>&copy; 2013 The Hollywood Gossip - Celebrity Gossip and Entertainment News</p> <p><a href="316.html" rel="nofollow"><img alt="Sheknows-entertainment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xsheknows-entertainment-0dfb1ed120378c4d8a98720390d31272.png.pagespeed.ic.841FJHTKbK.png" src="xerxozheethrey.gif"/></a></p> </div> </div> <img height="1" width="1" pagespeed_lazy_src="http://tags.bluekai.com/site/3113" alt="" src="rtuagoutrewhoizu.gif"/> </div> </body> </html> <file_sep><!DOCTYPE html> <html id='en' lang='en'> <head> <title>zara sale delhi 2012</title> <link href="ssoistoineypoagh.css" media="screen" rel="stylesheet" type="text/css"/> <link href="oopeinyroon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon"/> <link href="ouzeelouhtootw.jpg" rel='apple-touch-icon' sizes='144x144'> <link href="eytreyhoisefoaht.jpg" rel='apple-touch-icon' sizes='114x114'> <link href="ndyajeyssepuatr.jpg" rel='apple-touch-icon' sizes='72x72'> <link href="eychoopyatya.jpg" rel='apple-touch-icon'> <script type='text/javascript' src='eyzeywyazuneyhi.js'></script></head> <body itemscope itemtype='http://schema.org/WebPage'> <div id='header'> <div class='social visible-desktop'> <ul> <li class='twitter'><a href="119.html">xxx comic rich bitch #2: public toy</a></li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com' data-size='medium'></div> </li> <li class='facebook'> <div class='fb-like' data-href='http://www.facebook.com/thehollywoodgossip' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> </ul> </div> <div id='banner'> <a href="399.html"><img alt="The Hollywood Gossip" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xheader-7629f5d243c1cdc904bf535b05ff849f.jpg.pagespeed.ic.CDQOMwZhbJ.jpg" src="stawhaghoix.gif"/></a> </div> <div class='sites visible-desktop'> <a href="345.html">yovo fakes</a> | <a href="31.html">www.youtupe/hsnupskirt.com</a> | <a href="164.html">xxx viejos nietas gratis movil</a> </div> <div class='login visible-desktop'> <a href="367.html">yututube yenifer lopes porno completo</a> &nbsp;|&nbsp; <a href="343.html">yovodude shake it up</a> </div> </div> <div id='wrapper'> <div class='remove_padding'> <div id='leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='navbar' itemscope itemtype='http://schema.org/WPHeader'> <div class='navbar-inner'> <div class='container-fluid'> <a href="122.html">xxx cum gaggers</a> <div class='nav-collapse'> <ul class='nav'> <li class=''><a href="163.html">xxx video virgin anak sd smp</a></li> <li class=''><a href="141.html">xxx nangi video film</a></li> <li class=''><a href="318.html">you tube theocratic ministry school review 2013</a></li> <li class=''><a href="335.html">you tuve mujeres cojiendo con perros gran dames</a></li> <li class=''><a href="287.html">youtube jennifer lopez porno completo</a></li> <li class=''><a href="225.html">young celebrities on disney channel images</a></li> <li class=''><a href="6.html">www.vtunnel.com</a></li> <li class=''><a href="323.html">you tube video jenni rivera and chiquis boyfriend</a></li> <li class='login hidden-desktop'><a href="386.html">zara sale</a></li> <li class='login hidden-desktop'><a href="137.html">xxx jail bait non nude</a></li> </ul> <form action="http://www.thehollywoodgossip.com/search" class='navbar-form pull-right'> <input class="input-medium" id="q" name="q" placeholder="Search" type="search"/> <button class="btn" type="submit"></button> </form> </div> </div> </div> </div> </div> <div class='container-fluid'> <div class='row-fluid'> <div class='span8' id='content'> <ul class="breadcrumb" itemprop="breadcrumb"><li><a href="50.html">xbox 360 controller motherboard replacement</a> /</li> <li><a href="111.html">xxx 3gp anime adolescentes</a> /</li> <li><a href="393.html">zastava m92 hand guard sale</a> /</li> <li><p><a href="http://www.timeoutdelhi.net/shopping/features/restraining-order" target="new">Shopping | Fashion | Accessories | Zara | Time Out Delhi</a><div>Features &middot; Sales &amp; exhibitions &middot; Music . Sign up now for our free newsletter of what&#39;s on in Delhi &#150; from the Time Out team. Email * . Zara, R2,390 3. Zara, R 1,590 4. Blur, R . By <NAME> on November 23 2012 7.56am. Tags: Shopping .</div><span>http://www.timeoutdelhi.net/shopping/features/restraining-order</span></p></li></ul> <div class='video' itemscope itemtype='http://schema.org/VideoObject'> <div class='page-header'> <h1><p><a href="http://delhi.burrp.com/listing/zara_saket_new-delhi_womens-clothing-stores/1765397633" target="new">Zara, Saket, New Delhi, Women&#39;s Clothing Stores - burrp.com</a><div>Zara, Select Citywalk Mall Saket, New Delhi on burrp.com. . which includes design, production, distribution and sales through our extensive retail network.</div><span>http://delhi.burrp.com/listing/zara_saket_new-delhi_womens-clothing-stores/1765397633</span></p></h1> </div> <ul id='sharebar'> <li> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='box_count' data-send='false' data-show-faces='false' data-width='60'></div> </li> <li class='pinit'><a href="338.html" class="pin-it-button" count-layout="vertical" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="sterroizheizerth.gif"/></a></li> <li> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='tall'></div> </li> <li> <a href="166.html">xxx wwe aj sex movie.nat</a> </li> <li class='comments'> <div class='count comment_count'>1</div> <a href="121.html">xxx con padre hija gratis movil</a> </li> </ul> <div class='sharebarx' style="display:none;"> <ul> <li class='facebook'> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='medium'></div> </li> <li class='twitter'> <a href="36.html">www.zoofilia video porno mujere con perro</a> </li> <li class='pinterest'><a href="361.html" class="pin-it-button" count-layout="horizontal" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="eevuassyaqundee.gif"/></a></li> <li class='comments'> <a href="186.html">yenny ribera cojiendo</a> 1 </li> </ul> </div> <div class='thumbnail'> <div style="max-width:640px;max-height:459px;margin:0 auto;"> <img src="http://i.ytimg.com/vi/-OV3n1ibG3g/0.jpg" width="640" height="459" /> </div> <div class='caption' itemprop='description'><p><a href="http://newdelhi.olx.in/zara-long-wallets-iid-458275262" target="new">Zara Long Wallets - Delhi - Clothing</a><div>ZARA Long Wallet Unisex MRP: 2390 Shipment Packed Showroom Article Quantity: 150 pieces Contact me 9999014922 This Product is 100% Original - Clothing - Delhi. . OLX Mobile &middot; Facebook &middot; Twitter. Delhi Free classifieds - Copyright &copy; 2006-2012 OLX, Inc. Back to Results &gt; Home &gt; For Sale &gt; Clothing.</div><span>http://newdelhi.olx.in/zara-long-wallets-iid-458275262</span></p></div> <div class='rating-form' id='rating_7611' itemprop='aggregateRating' itemscope itemtype='http://schema.org/AggregateRating'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='inline-rating'><ul class="star-rating"><li class="current-rating" style="width:100%;">5.0 / 5.0</li><li><a href="380.html">zanx</a></li> <li><a href="45.html">xavier quartz gold watch</a></li> <li><a href="44.html">+xavier made in assembled in malaysia swiss watches black man an woman</a></li> <li><a href="110.html">xxx 2012 con animales</a></li> <li><a href="313.html">youtube selena gomez funeral</a></li></ul></div> <br><p><a href="http://jobs.taaza.com/key-zara-job-opening-in-delhi" target="new">Zara Opening Jobs in Delhi | Taaza Jobs</a><div>Jobs 1 - 10 of 20 . Search and Apply for the latest and best Zara Opening jobs in Delhi on . AirlineWalk In at Delhi on 06th Nov 2012,Contact: 9810309378, 011 .</div><span>http://jobs.taaza.com/key-zara-job-opening-in-delhi</span></p></div> </div> <br> <ul class='pager'> <li class='next'> <a href="168.html">yachts luxury</a> </li> </ul> Related Videos: <ul class='thumbnails'> <li class='span4'> <a href="336.html" class="thumbnail"><img alt="Brooke Burke Interview" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/medium_l/brooke-burke-interview.jpg" src="yssusarternotr.gif"/> <div class='caption'>zara sale delhi 2012 Burke Interview</div> </a></li> </ul> <div class="remove_padding"><div id="content_rectangle" itemscope itemtype="http://schema.org/WPAdBlock"> </div></div> Embed Code: <pre class='embed'><p><a href="http://www.theatlantic.com/business/archive/2012/11/zaras-big-idea-what-the-worlds-top-fashion-retailer-tells-us-about-innovation/265126/" target="new">Zara&#39;s Big Idea: What the World&#39;s Top Fashion Retailer Tells Us ...</a><div>Nov 13, 2012 . Zara didn&#39;t have to invent a brand new product to become the world&#39;s biggest fashion retailer. . The company, now the largest fashion retailer on earth, has grown overall sales by about . Screen Shot 2012-04-13 at 10.42.19 AM.png . How the Indian dream died with the Delhi gang rape victim &middot; Why have .</div><span>http://www.theatlantic.com/business/archive/2012/11/zaras-big-idea-what-the-worlds-top-fashion-retailer-tells-us-about-innovation/265126/</span></p> <p><a href="http://bx.businessweek.com/zara/" target="new">Zara - Business Exchange</a><div>Zara racks up &pound;1.3bn in 2012: How the SamCam effect sent profits soari...more . Zara&#39;s semi-annual sale begins Friday, shop for holiday and winter mus...more . best one way taxi serervice from chandigarh to delhi and delhi to chandigarh at .</div><span>http://bx.businessweek.com/zara/</span></p></pre> <dl class='dl-horizontal'> <dt>Star:</dt> <dd> <a href="309.html">you tuberestos de janny rivera</a> </dd> <dt>Related Videos:</dt> <dd><a href="37.html">www.zurichna.com/nydbl to:</a></dd> <dt>Original Post:</dt> <dd itemprop='associatedArticle'><a href="54.html">xbox code 80151011</a></dd> <dt>Uploaded by:</dt> <dd><a href="240.html">young lolitas nudes</a></dd> <dt>Uploaded:</dt> <dd><time datetime="2012-11-08T00:00:00+00:00" itemprop="uploadDate">November 08, 2012</time></dd> <dt>Duration:</dt> <dd> <time datetime='PT3M9S' itemprop='duration'>189 seconds</time> </dd> </dl> <hr> <div id='comments'> <h3> Comments (1 Total) <a href="347.html">y su novia fakes</a> </h3> <a href="104.html">xvideos mujeres follando con perros</a> <div id='new_comment'> <form accept-charset="UTF-8" action="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/comments/" class="simple_form form-horizontal" data-remote="true" id="new_comment" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;"/><input name="authenticity_token" type="hidden" value="<KEY>="/></div> <div class='body'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <input name='page' type='hidden'> <input id="comment_parent_id" name="comment[parent_id]" type="hidden"/> <br> <p><p><a href="http://mumbai.burrp.com/listing/zara_lower-parel_mumbai_kids-clothing-stores-mens-clothing-stores-womens-clothing-stores/1825398227__UR__reviews" target="new">User Reviews of Zara, Lower Parel, Mumbai, Kid&#39;s Clothing Stores ...</a><div>Get User Reviews &amp; Ratings of Zara, Palladium Mall Lower Parel, Mumbai on burrp.com. Write a . Rude Staff ok quality.. not customised for India 2012-10-03 . I had recently been to the Zara Sale and have to admit it was nothing short of a nightmare. . Local search in cities : Mumbai| Bangalore| Chennai| Delhi| Pune| .</div><span>http://mumbai.burrp.com/listing/zara_lower-parel_mumbai_kids-clothing-stores-mens-clothing-stores-womens-clothing-stores/1825398227__UR__reviews</span></p></p> <div class='row-fluid'> <div class='span8'> <div class="control-group string optional"><label class="string optional control-label" for="comment_anon_name">Name</label><div class="controls"><input class="string optional" id="comment_anon_name" name="comment[anon_name]" size="50" type="text"/><p class="help-block">Your name will appear with your comment</p></div></div> <div class="control-group email optional"><label class="email optional control-label" for="comment_anon_email">Email</label><div class="controls"><input class="string email optional" id="comment_anon_email" name="comment[anon_email]" size="50" type="email"/><p class="help-block"><p><a href="http://www.tripadvisor.in/Hotel_Review-g1156430-d1585892-Reviews-Zara_s_Resort-Khandala_Maharashtra.html" target="new">Zara&#39;s Resort (Khandala) - Hotel reviews, photos, rates - TripAdvisor</a><div>Zara&#39;s Resort, Khandala: See 5 traveller reviews, 5 user photos and best deals for Zara&#39;s Resort, . Which Khandala hotels are on sale? . Reviewed 7 July 2012 .</div><span>http://www.tripadvisor.in/Hotel_Review-g1156430-d1585892-Reviews-Zara_s_Resort-Khandala_Maharashtra.html</span></p></p></div></div> </div> <div class='span4 providers'> <a href="10.html">www.wapdesi .com</a> <br> <a href="301.html">youtubenephew tommy prank call to financial secretary</a> <br> <a href="399.html">zastava pap m92 pv pistol, 7.62x39mm, 30 rnd mag</a> <br> </div> </div> <div class="control-group text optional"><label class="text optional control-label" for="comment_content">Content</label><div class="controls"><textarea class="text optional" cols="40" id="comment_content" name="comment[content]" rows="20" style="width:320px;height:80px"> </textarea></div></div> </div> <div class='form-actions'> <input class='btn cancel' href="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/#" style="display:none;" type='button' value='Cancel'> <input class="btn btn btn-primary" data-disable-with="Adding..." name="commit" type="submit" value="Add Comment"/> <br style="clear:both;"> </div> </form> </div> <div class='row-fluid'> <div class='span12'> <div class='comment' data-content='<EMAIL>' id='comment_403462' itemid='403462' itemprop='comment' itemscope itemtype='http://schema.org/UserComments'> <div class='comment_meta'> <div class='row-fluid'> <div class='span2'> <img alt="Avatar" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/missing/thumb/xavatar.png.pagespeed.ic.qjczMghcsC.jpg" style="float:left;margin-right:10px;" src="oiplitreendatwyv.gif"/> </div> <div class='span10'> <a href="76.html">ximsl.com wap.ua</a> <div class='author' itemprop='creator'>medo</div> <div class='created_at'><time datetime="2012-11-09T02:10:23-05:00" itemprop="commentTime"><p><a href="https://foursquare.com/v/zara/4c00d637df6c0f47d6fe8b22" target="new">Zara - Saket - New Delhi, Delhi</a><div>See 6 photos and 12 tips from 301 visitors to Zara. &quot;its an amazing place for . Zara. Press Enclave Marg, Pushp Vihar (Select City Walk), New Delhi, Delhi, India . Anubha G. September 14, 2012. Color, color . Sale is to die for!! However, do .</div><span>https://foursquare.com/v/zara/4c00d637df6c0f47d6fe8b22</span></p></time></div> </div> </div> </div> <div class='alert alert-message error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='comment_body'> <div class='content'> <p itemprop='commentText'><EMAIL></p> </div> </div> <div class='form-actions'> </div> <div class='reply_holder'> </div> </div> </div> </div> </div> </div> </div> <div class='span4' id='sidebar' itemscope itemtype='http://schema.org/WPSideBar'> <div id='sidebar_rectangle' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="144.html">xxx nude madhori,katrina,karishma pics fock photos</a></h4> <div class='clearfix' itemscope itemtype='http://schema.org/Person'> <a href="188.html" itemprop="image"><img alt="<NAME>" class="pull-left" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-nude.jpg.pagespeed.ic.Yp5z6xqFnh.jpg" style="margin-right:10px;" src="itridyotwiboocay.gif"/></a><p><a href="http://bpbweekend.com/shop/zara-sale" target="new">Sale at Zara - BPBWeekend</a><div>6 days ago . Also, bring a puzzle to solve while standing in long trial room and check-out lines at the Zara sale that started yesterday. We were there to find .</div><span>http://bpbweekend.com/shop/zara-sale</span></p><dl> <dt>Born</dt> <dd itemprop='birthDate'><time datetime="1971-09-08T00:00:00+00:00">September 08, 1971</time></dd> <dt>Full Name</dt> <dd itemprop='name'>zara sale delhi 2012 Burke</dd> </dl> </div> </div> <div class='widget'> <h4><a href="266.html">youtube change serpintine belts 2003 altima 3.5</a></h4> <ul class='nav'> <li> <a href="122.html" class="clearfix"><img alt="Brooke Burke Prepares For Cancer Surgery" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" style="margin:0 10px 0 0;float:left;" src="yohtepeeqy.gif"/> zara sale delhi 2012 Burke Prepares For Cancer Surgery </a></li> <li> <a href="232.html" class="clearfix"><img alt="Brooke Burke Has Thyroid Cancer" class="span3" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/thumb/brooke-burke-charvet-cancer-me.jpg" style="margin:0 10px 0 0;float:left;" src="gawyasuv.gif"/> zara sale delhi 2012 Burke Has Thyroid Cancer </a></li> <li> <a href="310.html" class="clearfix"><img alt="Brooke Burke Charvet Releases New Lingerie Line" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" style="margin:0 10px 0 0;float:left;" src="kourtoujendoaple.gif"/> zara sale delhi 2012 Burke Charvet Releases New Lingerie Line </a></li> </ul> </div> <div id='skyscraper' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="360.html">yummychan.org/jb/</a></h4> <ul class='thumbnails'> <li class='span4'> <a href="21.html" class="thumbnail"><img alt="Brooke Burke, Cancer Treatment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" src="utayploji.gif"/> </a></li> <li class='span4'> <a href="390.html" class="thumbnail"><img alt="Brooke Burke-Charvet Photo" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-charvet-photo.jpg.pagespeed.ic.eZcSwfCk1Z.jpg" src="treiwhoxu.gif"/> </a></li> <li class='span4'> <a href="208.html" class="thumbnail"><img alt="Brooke Burke Lingerie Line" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" src="wyalegualaf.gif"/> </a></li> <li class='span4'> <a href="58.html" class="thumbnail"><img alt="Brooke Burke and David Charvet" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-and-david-charvet.jpg.pagespeed.ic.iLiOSmNBgG.jpg" src="thywayhtyoch.gif"/> </a></li> <li class='span4'> <a href="299.html" class="thumbnail"><img alt="Brooke and Tom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-and-tom.jpg.pagespeed.ic.OfTSSeJdAZ.jpg" src="yokaywhyodooliwy.gif"/> </a></li> <li class='span4'> <a href="15.html" class="thumbnail"><img alt="The Naked Mom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/the-naked-mom.jpg.pagespeed.ce.2HxOs_fRpY.jpg" src="ooxoukynuakeyfoi.gif"/> </a></li> </ul> </div> <div class='widget'> <h4>Blog Archives</h4> <ul class='nav'> <li><a href="142.html">xxx negro teen anal sex with girls</a></li> <li><a href="298.html">youtube mujeres mexicanas cojiendo</a></li> <li><a href="409.html">zendaya follando xxx</a></li> <li><a href="209.html">youfotos de chikis rivera</a></li> <li><a href="7.html">www.walmartbenefits.com/mybenefits</a></li> <li><a href="405.html">zendaya actully naked</a></li> <li><a href="110.html">xxx 2012 con animales</a></li> <li><a href="index.html">home</a></li> </ul> </div> </div> </div> <div id='footer' itemscope itemtype='http://schema.org/WPFooter'> <div class='remove_padding'> <div id='footer_leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> </div> <p><p><a href="http://articles.economictimes.indiatimes.com/keyword/zara" target="new">Articles about Zara - Economic Times</a><div>Find breaking news, commentary, and archival information about Zara From The Economic Times. . July 24, 2012 | PTI . year and that day the South Delhi outlet recorded the largest single-day sale by an international retailer in the country.</div><span>http://articles.economictimes.indiatimes.com/keyword/zara</span></p></p> <p> <a href="227.html">youngest cp fuck movies</a> | <a href="32.html">www youtuve hiroin anuska shrma nangi phto</a> | <a href="353.html">yugo pap m85pv pistol</a> | <a href="2.html">www.usbankingonline</a> </p> <p>&copy; 2013 The Hollywood Gossip - Celebrity Gossip and Entertainment News</p> <p><a href="345.html" rel="nofollow"><img alt="Sheknows-entertainment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xsheknows-entertainment-0dfb1ed120378c4d8a98720390d31272.png.pagespeed.ic.841FJHTKbK.png" src="xerxozheethrey.gif"/></a></p> </div> </div> <img height="1" width="1" pagespeed_lazy_src="http://tags.bluekai.com/site/3113" alt="" src="rtuagoutrewhoizu.gif"/> </div> </body> </html> <file_sep><!DOCTYPE html> <html id='en' lang='en'> <head> <title>xxx jail bait non nude</title> <link href="ssoistoineypoagh.css" media="screen" rel="stylesheet" type="text/css"/> <link href="oopeinyroon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon"/> <link href="ouzeelouhtootw.jpg" rel='apple-touch-icon' sizes='144x144'> <link href="eytreyhoisefoaht.jpg" rel='apple-touch-icon' sizes='114x114'> <link href="ndyajeyssepuatr.jpg" rel='apple-touch-icon' sizes='72x72'> <link href="eychoopyatya.jpg" rel='apple-touch-icon'> <script type='text/javascript' src='eyzeywyazuneyhi.js'></script></head> <body itemscope itemtype='http://schema.org/WebPage'> <div id='header'> <div class='social visible-desktop'> <ul> <li class='twitter'><a href="185.html">yegua folladas por hombres fotos</a></li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com' data-size='medium'></div> </li> <li class='facebook'> <div class='fb-like' data-href='http://www.facebook.com/thehollywoodgossip' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> </ul> </div> <div id='banner'> <a href="234.html"><img alt="The Hollywood Gossip" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xheader-7629f5d243c1cdc904bf535b05ff849f.jpg.pagespeed.ic.CDQOMwZhbJ.jpg" src="stawhaghoix.gif"/></a> </div> <div class='sites visible-desktop'> <a href="244.html">young nymphets pissing pics</a> | <a href="184.html">ya se dio a conocer la carta de jenny rivera?</a> | <a href="184.html">ya se dio a conocer la carta de jenny rivera?</a> </div> <div class='login visible-desktop'> <a href="21.html">www.xxx.bahbi.hot.chudai.sex.stori.loud.net.com.</a> &nbsp;|&nbsp; <a href="140.html">xxx nakked animals fukking bollywood babes</a> </div> </div> <div id='wrapper'> <div class='remove_padding'> <div id='leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='navbar' itemscope itemtype='http://schema.org/WPHeader'> <div class='navbar-inner'> <div class='container-fluid'> <a href="386.html">zara sale</a> <div class='nav-collapse'> <ul class='nav'> <li class=''><a href="321.html">you tube ver fotos de mariana seoane</a></li> <li class=''><a href="145.html">xxx.photo indian actress download . in</a></li> <li class=''><a href="398.html">zastava pap m92</a></li> <li class=''><a href="358.html">yugo zastava m92pv krink ak pistol 7.62x39</a></li> <li class=''><a href="315.html">youtube stars nude fake</a></li> <li class=''><a href="376.html">zamora ghetto gaggers</a></li> <li class=''><a href="99.html">xvideos . com videos porno de niñas de 12 años de españa</a></li> <li class=''><a href="364.html">yu tube videos cachondos de jenni rivera</a></li> <li class='login hidden-desktop'><a href="25.html">www.xxxporn nangi fucking</a></li> <li class='login hidden-desktop'><a href="112.html">xxx 3 gp de aguelas con sus ñetos</a></li> </ul> <form action="http://www.thehollywoodgossip.com/search" class='navbar-form pull-right'> <input class="input-medium" id="q" name="q" placeholder="Search" type="search"/> <button class="btn" type="submit"></button> </form> </div> </div> </div> </div> </div> <div class='container-fluid'> <div class='row-fluid'> <div class='span8' id='content'> <ul class="breadcrumb" itemprop="breadcrumb"><li><a href="322.html">youtube video caseros calientes</a> /</li> <li><a href="331.html">youtube wire charms</a> /</li> <li><a href="83.html">xnxx</a> /</li> <li><p><a href="http://www.intporn.com/forums/amateur-pictures/3094407-non-nude-jailbait-3.html" target="new">Non-nude jailbait - Page 3</a><div>Nov 15, 2012 . Page 3- Non-nude jailbait Amateur Pictures. . Go Back, intporn.com - free porn forums &gt; XXX Pictures &gt; Amateur Pictures. Non-nude jailbait .</div><span>http://www.intporn.com/forums/amateur-pictures/3094407-non-nude-jailbait-3.html</span></p></li></ul> <div class='video' itemscope itemtype='http://schema.org/VideoObject'> <div class='page-header'> <h1><p><a href="http://www.kittygfs.com/viewtopic.php?f=5&amp;t=17" target="new">Stickam Captures, JailBait Girls, Amateur Porn Forum &#149; View topic ...</a><div>Non-Nude Teens (Jailbait). Post by lililoli80 &raquo; Sat Dec 01, 2012 8:50 am. Image. lililoli80: Posts: 123: Joined: Sat Dec 01, 2012 8:40 am. Top .</div><span>http://www.kittygfs.com/viewtopic.php?f=5&amp;t=17</span></p></h1> </div> <ul id='sharebar'> <li> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='box_count' data-send='false' data-show-faces='false' data-width='60'></div> </li> <li class='pinit'><a href="4.html" class="pin-it-button" count-layout="vertical" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="sterroizheizerth.gif"/></a></li> <li> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='tall'></div> </li> <li> <a href="224.html">young brook shields naked in videp caps</a> </li> <li class='comments'> <div class='count comment_count'>1</div> <a href="91.html">xoskeleton watch for sale craigslist</a> </li> </ul> <div class='sharebarx' style="display:none;"> <ul> <li class='facebook'> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='medium'></div> </li> <li class='twitter'> <a href="190.html">yisela avendano free sex videos</a> </li> <li class='pinterest'><a href="133.html" class="pin-it-button" count-layout="horizontal" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="eevuassyaqundee.gif"/></a></li> <li class='comments'> <a href="189.html">yiffy straight</a> 1 </li> </ul> </div> <div class='thumbnail'> <div style="max-width:640px;max-height:459px;margin:0 auto;"> <img src="http://2.bp.blogspot.com/_iq6ssKOaUBs/SmoxKeHoaSI/AAAAAAAAAaQ/3N9_uB_EWL8/s320/New+moon+sneak+peek+1+original+008_0001.jpg" width="640" height="459" /> </div> <div class='caption' itemprop='description'><p><a href="http://motherless.com/g/true_jailbait_babes" target="new">true jailbait babes - Motherless</a><div>this is a collection of pics and vids of true jailbait babes NO ANIMAL PORN! &#149; Group Home &#149; Images [46,973] Videos [4,747] Forum [119] Members [8,542] .</div><span>http://motherless.com/g/true_jailbait_babes</span></p></div> <div class='rating-form' id='rating_7611' itemprop='aggregateRating' itemscope itemtype='http://schema.org/AggregateRating'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='inline-rating'><ul class="star-rating"><li class="current-rating" style="width:100%;">5.0 / 5.0</li><li><a href="357.html">yugo zastava factory m92 parts kit</a></li> <li><a href="264.html">youtube brooke burke playboy</a></li> <li><a href="300.html">youtube nephew tommy prank calls uncut</a></li> <li><a href="80.html">xm80 ammo</a></li> <li><a href="284.html">youtube free women naked of wwe</a></li></ul></div> <br><p><a href="http://www.dailymotion.com/video/x7zqfx_3-jailbait-teens-get-completely-nak_sexy" target="new">3 jailbait teens get completely naked!!! - Video Dailymotion</a><div>Jan 10, 2009 . There is no nudity allowed on YouTube but there is on DailyTubeGirls! Link for first girl: . Jailbait Teen Dances Very Sexy + Gets Naked. 04:35. HOT Teen Pillow . Sexy Nude Teen Naked Teen Stripping Teen Tits Boobs XXX .</div><span>http://www.dailymotion.com/video/x7zqfx_3-jailbait-teens-get-completely-nak_sexy</span></p></div> </div> <br> <ul class='pager'> <li class='next'> <a href="12.html">www.wap,trick.phuddi photo.com</a> </li> </ul> Related Videos: <ul class='thumbnails'> <li class='span4'> <a href="367.html" class="thumbnail"><img alt="Brooke Burke Interview" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/medium_l/brooke-burke-interview.jpg" src="yssusarternotr.gif"/> <div class='caption'>xxx jail bait non nude Burke Interview</div> </a></li> </ul> <div class="remove_padding"><div id="content_rectangle" itemscope itemtype="http://schema.org/WPAdBlock"> </div></div> Embed Code: <pre class='embed'><p><a href="http://torrentz.eu/te/teen+nude+jailbait-q" target="new">Download teen nude jailbait torrent</a><div>Sponsored Links for teen nude jailbait. teen nude jailbait Full .</div><span>http://torrentz.eu/te/teen+nude+jailbait-q</span></p> <p><a href="http://lovejailbait.com/board4-jailbait/board7-jailbait-pictures-non-nude/10-pretty-young-jailbait-teens-non-nude/" target="new">Pretty Young Jailbait Teens (non nude) - Jailbait Pictures Non Nude ...</a><div>Dec 21, 2012 . Stickam Captures ,Omegle Captures, Jailbait Captures Forum, Webcam . LoveJailbait.com - jailbait webcams - jailbait video&#39;s - jailbait pictures &raquo;; Jailbait &raquo;; Jailbait Pictures Non Nude &raquo; . Passlist.net - The Best XXX Toplist .</div><span>http://lovejailbait.com/board4-jailbait/board7-jailbait-pictures-non-nude/10-pretty-young-jailbait-teens-non-nude/</span></p></pre> <dl class='dl-horizontal'> <dt>Star:</dt> <dd> <a href="83.html">xnxx</a> </dd> <dt>Related Videos:</dt> <dd><a href="1.html">www.urfreeoffer.com/burkeburke</a></dd> <dt>Original Post:</dt> <dd itemprop='associatedArticle'><a href="367.html">yututube yenifer lopes porno completo</a></dd> <dt>Uploaded by:</dt> <dd><a href="105.html">xvideos tahiry from love and hip hop</a></dd> <dt>Uploaded:</dt> <dd><time datetime="2012-11-08T00:00:00+00:00" itemprop="uploadDate">November 08, 2012</time></dd> <dt>Duration:</dt> <dd> <time datetime='PT3M9S' itemprop='duration'>189 seconds</time> </dd> </dl> <hr> <div id='comments'> <h3> Comments (1 Total) <a href="286.html">you tube imagenes de she mails follando</a> </h3> <a href="377.html">zander identify theft vs. lifelock</a> <div id='new_comment'> <form accept-charset="UTF-8" action="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/comments/" class="simple_form form-horizontal" data-remote="true" id="new_comment" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;"/><input name="authenticity_token" type="hidden" value="<KEY>="/></div> <div class='body'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <input name='page' type='hidden'> <input id="comment_parent_id" name="comment[parent_id]" type="hidden"/> <br> <p><p><a href="http://jbcams.org/board17-other/board27-trash/896-non-nude-teens-jailbait/" target="new">Non-Nude Teens ( Jailbait ) - TRASH - jbcams.org - Webcam and ...</a><div>Nov 17, 2012 . Welcome to jbcams.org. jbcams.org - Webcam and Jailbait Forum &raquo;; OTHER &raquo;; TRASH &raquo;. Non-Nude Teens ( Jailbait ). Skip user information .</div><span>http://jbcams.org/board17-other/board27-trash/896-non-nude-teens-jailbait/</span></p></p> <div class='row-fluid'> <div class='span8'> <div class="control-group string optional"><label class="string optional control-label" for="comment_anon_name">Name</label><div class="controls"><input class="string optional" id="comment_anon_name" name="comment[anon_name]" size="50" type="text"/><p class="help-block">Your name will appear with your comment</p></div></div> <div class="control-group email optional"><label class="email optional control-label" for="comment_anon_email">Email</label><div class="controls"><input class="string email optional" id="comment_anon_email" name="comment[anon_email]" size="50" type="email"/><p class="help-block"><p><a href="http://lovejailbait.com/board4-jailbait/board7-jailbait-pictures-non-nude/10-pretty-young-jailbait-teens-non-nude/index2.html" target="new">Pretty Young Jailbait Teens (non nude) - Page 2 - Jailbait Pictures ...</a><div>Jan 1, 2013 . LoveJailbait.com - jailbait webcams - jailbait video&#39;s - jailbait pictures . LoveJailbait.com - jailbait webcams - jailbait video&#39;s - jailbait pictures &raquo;; Jailbait &raquo;; Jailbait Pictures Non Nude &raquo; . Passlist.net - The Best XXX Toplist .</div><span>http://lovejailbait.com/board4-jailbait/board7-jailbait-pictures-non-nude/10-pretty-young-jailbait-teens-non-nude/index2.html</span></p></p></div></div> </div> <div class='span4 providers'> <a href="319.html">youtube upskirt stacy dash</a> <br> <a href="354.html">yugo pap m85pv pistol, krinkov style pistol, 5.56x45mm, zastava serbia</a> <br> <a href="10.html">www.wapdesi .com</a> <br> </div> </div> <div class="control-group text optional"><label class="text optional control-label" for="comment_content">Content</label><div class="controls"><textarea class="text optional" cols="40" id="comment_content" name="comment[content]" rows="20" style="width:320px;height:80px"> </textarea></div></div> </div> <div class='form-actions'> <input class='btn cancel' href="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/#" style="display:none;" type='button' value='Cancel'> <input class="btn btn btn-primary" data-disable-with="Adding..." name="commit" type="submit" value="Add Comment"/> <br style="clear:both;"> </div> </form> </div> <div class='row-fluid'> <div class='span12'> <div class='comment' data-content='<EMAIL>' id='comment_403462' itemid='403462' itemprop='comment' itemscope itemtype='http://schema.org/UserComments'> <div class='comment_meta'> <div class='row-fluid'> <div class='span2'> <img alt="Avatar" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/missing/thumb/xavatar.png.pagespeed.ic.qjczMghcsC.jpg" style="float:left;margin-right:10px;" src="oiplitreendatwyv.gif"/> </div> <div class='span10'> <a href="202.html">yoshi shiraki mens haircuts</a> <div class='author' itemprop='creator'>medo</div> <div class='created_at'><time datetime="2012-11-09T02:10:23-05:00" itemprop="commentTime"><p><a href="http://lovejailbait.com/board4-jailbait/board7-jailbait-pictures-non-nude/" target="new">Jailbait Pictures Non Nude - LoveJailbait.com - jailbait webcams ...</a><div>LoveJailbait.com - jailbait webcams - jailbait video&#39;s - jailbait pictures . Pretty Young Jailbait Teens (non nude) &middot; 1 &middot; 2 . Passlist.net - The Best XXX Toplist .</div><span>http://lovejailbait.com/board4-jailbait/board7-jailbait-pictures-non-nude/</span></p></time></div> </div> </div> </div> <div class='alert alert-message error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='comment_body'> <div class='content'> <p itemprop='commentText'><EMAIL></p> </div> </div> <div class='form-actions'> </div> <div class='reply_holder'> </div> </div> </div> </div> </div> </div> </div> <div class='span4' id='sidebar' itemscope itemtype='http://schema.org/WPSideBar'> <div id='sidebar_rectangle' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="311.html">youtube rick ross cherry bomb riding donk</a></h4> <div class='clearfix' itemscope itemtype='http://schema.org/Person'> <a href="335.html" itemprop="image"><img alt="Brooke Burke Nude" class="pull-left" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-nude.jpg.pagespeed.ic.Yp5z6xqFnh.jpg" style="margin-right:10px;" src="itridyotwiboocay.gif"/></a><p><a href="http://www.pinporn.com/all/jailbait/" target="new">jailbait All XXX Porn Pictures and Sex Video Movies | Pinporn.com</a><div>Non-Nude &middot; Panties &middot; Party &middot; Petite &middot; Pornstar &middot; Public Sex &middot; Pussy &middot; Red Head &middot; Selfshot &middot; Shemale &middot; Squirt &middot; Teen &middot; Threesome &middot; Toys &middot; Uniform &middot; Vintage .</div><span>http://www.pinporn.com/all/jailbait/</span></p><dl> <dt>Born</dt> <dd itemprop='birthDate'><time datetime="1971-09-08T00:00:00+00:00">September 08, 1971</time></dd> <dt>Full Name</dt> <dd itemprop='name'>xxx jail bait non nude Burke</dd> </dl> </div> </div> <div class='widget'> <h4><a href="390.html">zastava m85pv 223 5.56 hg3088-n ak-47</a></h4> <ul class='nav'> <li> <a href="97.html" class="clearfix"><img alt="Brooke Burke Prepares For Cancer Surgery" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" style="margin:0 10px 0 0;float:left;" src="yohtepeeqy.gif"/> xxx jail bait non nude Burke Prepares For Cancer Surgery </a></li> <li> <a href="137.html" class="clearfix"><img alt="Brooke Burke Has Thyroid Cancer" class="span3" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/thumb/brooke-burke-charvet-cancer-me.jpg" style="margin:0 10px 0 0;float:left;" src="gawyasuv.gif"/> xxx jail bait non nude Burke Has Thyroid Cancer </a></li> <li> <a href="index.html" class="clearfix"><img alt="Brooke Burke Charvet Releases New Lingerie Line" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" style="margin:0 10px 0 0;float:left;" src="kourtoujendoaple.gif"/> xxx jail bait non nude Burke Charvet Releases New Lingerie Line </a></li> </ul> </div> <div id='skyscraper' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="318.html">you tube theocratic ministry school review 2013</a></h4> <ul class='thumbnails'> <li class='span4'> <a href="402.html" class="thumbnail"><img alt="Brooke Burke, Cancer Treatment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" src="utayploji.gif"/> </a></li> <li class='span4'> <a href="310.html" class="thumbnail"><img alt="Brooke Burke-Charvet Photo" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-charvet-photo.jpg.pagespeed.ic.eZcSwfCk1Z.jpg" src="treiwhoxu.gif"/> </a></li> <li class='span4'> <a href="385.html" class="thumbnail"><img alt="Brooke Burke Lingerie Line" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" src="wyalegualaf.gif"/> </a></li> <li class='span4'> <a href="351.html" class="thumbnail"><img alt="<NAME> and <NAME>" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-and-david-charvet.jpg.pagespeed.ic.iLiOSmNBgG.jpg" src="thywayhtyoch.gif"/> </a></li> <li class='span4'> <a href="71.html" class="thumbnail"><img alt="Brooke and Tom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-and-tom.jpg.pagespeed.ic.OfTSSeJdAZ.jpg" src="yokaywhyodooliwy.gif"/> </a></li> <li class='span4'> <a href="375.html" class="thumbnail"><img alt="The Naked Mom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/the-naked-mom.jpg.pagespeed.ce.2HxOs_fRpY.jpg" src="ooxoukynuakeyfoi.gif"/> </a></li> </ul> </div> <div class='widget'> <h4>Blog Archives</h4> <ul class='nav'> <li><a href="382.html">zara apply online</a></li> <li><a href="352.html">yugo m92/m85 26mm flash hider</a></li> <li><a href="364.html">yu tube videos cachondos de jenni rivera</a></li> <li><a href="307.html">youtube pthc bath</a></li> <li><a href="138.html">xxx maribel guardia</a></li> <li><a href="83.html">xnxx</a></li> <li><a href="19.html">www. x hindi antarvasna kahani video</a></li> <li><a href="322.html">youtube video caseros calientes</a></li> </ul> </div> </div> </div> <div id='footer' itemscope itemtype='http://schema.org/WPFooter'> <div class='remove_padding'> <div id='footer_leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> </div> <p><p><a href="http://www.empflix.com/uprofile.php?UID=721807" target="new">kygygelepi&#39;s profile</a><div>We have a large porn hub of XXX, sex, porno, hardcore sex tube videos.. . lolita non nude girls photos nudist children lolitas . jail bait lolita girls 13 17 nn lolita .</div><span>http://www.empflix.com/uprofile.php?UID=721807</span></p></p> <p> <a href="248.html">young teen bbs gateway</a> | <a href="70.html">xerex pantasya stories download</a> | <a href="367.html">yututube yenifer lopes porno completo</a> | <a href="345.html">yovo fakes</a> </p> <p>&copy; 2013 The Hollywood Gossip - Celebrity Gossip and Entertainment News</p> <p><a href="45.html" rel="nofollow"><img alt="Sheknows-entertainment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xsheknows-entertainment-0dfb1ed120378c4d8a98720390d31272.png.pagespeed.ic.841FJHTKbK.png" src="xerxozheethrey.gif"/></a></p> </div> </div> <img height="1" width="1" pagespeed_lazy_src="http://tags.bluekai.com/site/3113" alt="" src="rtuagoutrewhoizu.gif"/> </div> </body> </html> <file_sep><!DOCTYPE html> <html id='en' lang='en'> <head> <title>youtube alicia machado porno completo</title> <link href="ssoistoineypoagh.css" media="screen" rel="stylesheet" type="text/css"/> <link href="oopeinyroon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon"/> <link href="ouzeelouhtootw.jpg" rel='apple-touch-icon' sizes='144x144'> <link href="eytreyhoisefoaht.jpg" rel='apple-touch-icon' sizes='114x114'> <link href="ndyajeyssepuatr.jpg" rel='apple-touch-icon' sizes='72x72'> <link href="eychoopyatya.jpg" rel='apple-touch-icon'> <script type='text/javascript' src='eyzeywyazuneyhi.js'></script></head> <body itemscope itemtype='http://schema.org/WebPage'> <div id='header'> <div class='social visible-desktop'> <ul> <li class='twitter'><a href="172.html">yahoo server unavailable on iphone 5</a></li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com' data-size='medium'></div> </li> <li class='facebook'> <div class='fb-like' data-href='http://www.facebook.com/thehollywoodgossip' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> </ul> </div> <div id='banner'> <a href="415.html"><img alt="The Hollywood Gossip" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xheader-7629f5d243c1cdc904bf535b05ff849f.jpg.pagespeed.ic.CDQOMwZhbJ.jpg" src="stawhaghoix.gif"/></a> </div> <div class='sites visible-desktop'> <a href="295.html">youtube minas en colales</a> | <a href="2.html">www.usbankingonline</a> | <a href="66.html">xdesi.mobi.bihara.actress</a> </div> <div class='login visible-desktop'> <a href="216.html">you got posted tiffany bannister</a> &nbsp;|&nbsp; <a href="267.html">youtube chapo guzman video</a> </div> </div> <div id='wrapper'> <div class='remove_padding'> <div id='leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='navbar' itemscope itemtype='http://schema.org/WPHeader'> <div class='navbar-inner'> <div class='container-fluid'> <a href="236.html">young jodie sweetin naked pics</a> <div class='nav-collapse'> <ul class='nav'> <li class=''><a href="190.html">yisela avendano free sex videos</a></li> <li class=''><a href="235.html">young jailbait non nude</a></li> <li class=''><a href="324.html">youtube videos bailando y ensenando</a></li> <li class=''><a href="184.html">ya se dio a conocer la carta de jenny rivera?</a></li> <li class=''><a href="149.html">xxx poringa</a></li> <li class=''><a href="160.html">xxx ver videos on line para nokia c3</a></li> <li class=''><a href="383.html">zara basic sandal black orange nude</a></li> <li class=''><a href="47.html">xaxor girls</a></li> <li class='login hidden-desktop'><a href="127.html">xxx druuna onionbooty.com</a></li> <li class='login hidden-desktop'><a href="252.html">youporn helen hunt sessions</a></li> </ul> <form action="http://www.thehollywoodgossip.com/search" class='navbar-form pull-right'> <input class="input-medium" id="q" name="q" placeholder="Search" type="search"/> <button class="btn" type="submit"></button> </form> </div> </div> </div> </div> </div> <div class='container-fluid'> <div class='row-fluid'> <div class='span8' id='content'> <ul class="breadcrumb" itemprop="breadcrumb"><li><a href="9.html">www wapdam big porn picthers bravoteens com</a> /</li> <li><a href="328.html">youtube. videos mujeres con animales gratis</a> /</li> <li><a href="34.html">www.zee tv's banu mein teri dulhan actres fake porn.com</a> /</li> <li><p><a href="http://www.youtube.com/watch?v=1iSzF04DtqI" target="new">biendo video porno de alicia machado - YouTube</a><div>11 Mar 2011 . biendo video porno de alicia machado . Alicia Machado en el Cachond&oacute;metro by AzAmericaFeatured18,422; Alicia Machado Como Decirte .</div><span>http://www.youtube.com/watch?v=1iSzF04DtqI</span></p></li></ul> <div class='video' itemscope itemtype='http://schema.org/VideoObject'> <div class='page-header'> <h1><p><a href="http://article.wn.com/view/2012/11/07/Imagenes_comicas_de_blacberry/" target="new">Imagenes comicas de blacberry - Worldnews.com</a><div>Nov 7, 2012 . good.is GOOD Magazine: Internet Porn Video: Max Joseph Music: Don C.. . O v&iacute;deo est&aacute; completo {quase duas horas} e todo legendado Cr&eacute;ditos . Please do and SHARE it in any way you can. www.youtube.com We are all Earthlings . . topless photos http://1d8x6h.one.pl/Ibpe.html Alicia machado h .</div><span>http://article.wn.com/view/2012/11/07/Imagenes_comicas_de_blacberry/</span></p></h1> </div> <ul id='sharebar'> <li> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='box_count' data-send='false' data-show-faces='false' data-width='60'></div> </li> <li class='pinit'><a href="8.html" class="pin-it-button" count-layout="vertical" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="sterroizheizerth.gif"/></a></li> <li> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='tall'></div> </li> <li> <a href="321.html">you tube ver fotos de mariana seoane</a> </li> <li class='comments'> <div class='count comment_count'>1</div> <a href="151.html">xxx.sex amy roloff</a> </li> </ul> <div class='sharebarx' style="display:none;"> <ul> <li class='facebook'> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='medium'></div> </li> <li class='twitter'> <a href="330.html">youtube watch v gr 017 sf214</a> </li> <li class='pinterest'><a href="246.html" class="pin-it-button" count-layout="horizontal" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="eevuassyaqundee.gif"/></a></li> <li class='comments'> <a href="356.html">yugo pap sbr</a> 1 </li> </ul> </div> <div class='thumbnail'> <div style="max-width:640px;max-height:459px;margin:0 auto;"> <img src="http://portada.cloud.noticias24.com/martinez440.jpg" width="640" height="459" /> </div> <div class='caption' itemprop='description'><p><a href="http://cineclubelgbt.wordpress.com/" target="new">CineclubeLGBT</a><div>Homem Completo, de <NAME>, traz a busca de homem em uma noite. . e &oacute;dio atrav&eacute;s de v&iacute;deos caseiros postados em seu canal do YouTube, Family Values Gay. . Alicia e Ver&oacute;nica s&atilde;o suas professoras em uma aula diferente, num lugar inusitado. . N&atilde;o confundam o CineclubeLGBT com cinema porn&ocirc;, ok!</div><span>http://cineclubelgbt.wordpress.com/</span></p></div> <div class='rating-form' id='rating_7611' itemprop='aggregateRating' itemscope itemtype='http://schema.org/AggregateRating'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='inline-rating'><ul class="star-rating"><li class="current-rating" style="width:100%;">5.0 / 5.0</li><li><a href="11.html">www.waptrack pakistani xxx.compk.</a></li> <li><a href="index.html">home</a></li> <li><a href="130.html">xxxfunny.mobi</a></li> <li><a href="119.html">xxx comic rich bitch #2: public toy</a></li> <li><a href="251.html">youporn.com/nn preteen models</a></li></ul></div> <br><p><a href="http://www.noticias24.com/" target="new">Noticias de Venezuela y Latinoam&eacute;rica en Noticias24</a><div>ver art&iacute;culo completo . Video: Youtube, 09 de enero de 2013 . <NAME> Machado: &#147;Las decisiones sobre el destino de Venezuela se est&aacute;n . El escote de <NAME> revoluciona Internet y logra 3.3 millones de visitas en su blog (+ fotos . Un noticiero sueco transmiti&oacute; un video porno durante diez minutos por error .</div><span>http://www.noticias24.com/</span></p></div> </div> <br> <ul class='pager'> <li class='next'> <a href="233.html">young gymnastics slips accidental nudity tumblr</a> </li> </ul> Related Videos: <ul class='thumbnails'> <li class='span4'> <a href="376.html" class="thumbnail"><img alt="Brooke Burke Interview" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/medium_l/brooke-burke-interview.jpg" src="yssusarternotr.gif"/> <div class='caption'>youtube alicia machado porno completo Burke Interview</div> </a></li> </ul> <div class="remove_padding"><div id="content_rectangle" itemscope itemtype="http://schema.org/WPAdBlock"> </div></div> Embed Code: <pre class='embed'><p><a href="http://interglobosfera.blogspot.com/" target="new">INTERGLOBOSFERA</a><div>VerAQUI COMPLETO. Video Porno hot de <NAME> y RonnyDance: Existen muchas busquedas del video prohibido de Mariana y Ronny, en internet es .</div><span>http://interglobosfera.blogspot.com/</span></p> <p><a href="http://www.youtube.com/watch?v=cZ_2eq9IxO0" target="new">Hot Sexy &amp; Spicy Actress Alicia Machado - YouTube</a><div>Jul 12, 2011 . video porno de alicia machadoby rodolfo37163,034,157 views &middot; Miss Universe . Sexo en GH2012 Victoria y Ezequiel - Video Completo HD .</div><span>http://www.youtube.com/watch?v=cZ_2eq9IxO0</span></p> <p><a href="http://www.youtube.com/watch?v=mLCJbH6tP6I" target="new">ALICIA MACHADO SEXO REALITY - YouTube</a><div>15 Ene 2011 . video porno de alicia machadoby rodolfo37163,043,352 views &middot; Lucero . Sexo no Big Brother 12 da Argentina - Completo sem Cortesby Filipe .</div><span>http://www.youtube.com/watch?v=mLCJbH6tP6I</span></p></pre> <dl class='dl-horizontal'> <dt>Star:</dt> <dd> <a href="410.html">zerobio mono drag</a> </dd> <dt>Related Videos:</dt> <dd><a href="379.html">zander insurance identity theft vs lifelock</a></dd> <dt>Original Post:</dt> <dd itemprop='associatedArticle'><a href="380.html">zanx</a></dd> <dt>Uploaded by:</dt> <dd><a href="378.html">zander id theft compaints</a></dd> <dt>Uploaded:</dt> <dd><time datetime="2012-11-08T00:00:00+00:00" itemprop="uploadDate">November 08, 2012</time></dd> <dt>Duration:</dt> <dd> <time datetime='PT3M9S' itemprop='duration'>189 seconds</time> </dd> </dl> <hr> <div id='comments'> <h3> Comments (1 Total) <a href="199.html">yolanda on ghetto gaggers full video</a> </h3> <a href="71.html">xerex sagad tukso</a> <div id='new_comment'> <form accept-charset="UTF-8" action="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/comments/" class="simple_form form-horizontal" data-remote="true" id="new_comment" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;"/><input name="authenticity_token" type="hidden" value="<KEY>></div> <div class='body'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <input name='page' type='hidden'> <input id="comment_parent_id" name="comment[parent_id]" type="hidden"/> <br> <p><p><a href="http://interglobosfera.blogspot.com/2012/09/video-casero-completo-de-concejala.html" target="new">Video Casero Completo de Concejala Socialista de los Yebenes ...</a><div>6 Sep 2012 . El video casero completo lo encuentras AQUI . Video Porno hot de Mariana Marino y... VIDEO Porno de Florencia Pe&ntilde;a COMPL... Enviar por .</div><span>http://interglobosfera.blogspot.com/2012/09/video-casero-completo-de-concejala.html</span></p></p> <div class='row-fluid'> <div class='span8'> <div class="control-group string optional"><label class="string optional control-label" for="comment_anon_name">Name</label><div class="controls"><input class="string optional" id="comment_anon_name" name="comment[anon_name]" size="50" type="text"/><p class="help-block">Your name will appear with your comment</p></div></div> <div class="control-group email optional"><label class="email optional control-label" for="comment_anon_email">Email</label><div class="controls"><input class="string email optional" id="comment_anon_email" name="comment[anon_email]" size="50" type="email"/><p class="help-block"><p><a href="http://www.filestube.com/a/alicia+machado+video+porno" target="new">Alicia machado video porno download</a><div>Results 1 - 9 of 9 . Alicia machado video porno free download - alicia machado video porno . Also try: alicia machado video porno completo ver video porno de .</div><span>http://www.filestube.com/a/alicia+machado+video+porno</span></p></p></div></div> </div> <div class='span4 providers'> <a href="179.html">yaqui guerrido</a> <br> <a href="326.html">youtube video scandle</a> <br> <a href="355.html">yugo pap m85pv review</a> <br> </div> </div> <div class="control-group text optional"><label class="text optional control-label" for="comment_content">Content</label><div class="controls"><textarea class="text optional" cols="40" id="comment_content" name="comment[content]" rows="20" style="width:320px;height:80px"> </textarea></div></div> </div> <div class='form-actions'> <input class='btn cancel' href="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/#" style="display:none;" type='button' value='Cancel'> <input class="btn btn btn-primary" data-disable-with="Adding..." name="commit" type="submit" value="Add Comment"/> <br style="clear:both;"> </div> </form> </div> <div class='row-fluid'> <div class='span12'> <div class='comment' data-content='<EMAIL>' id='comment_403462' itemid='403462' itemprop='comment' itemscope itemtype='http://schema.org/UserComments'> <div class='comment_meta'> <div class='row-fluid'> <div class='span2'> <img alt="Avatar" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/missing/thumb/xavatar.png.pagespeed.ic.qjczMghcsC.jpg" style="float:left;margin-right:10px;" src="oiplitreendatwyv.gif"/> </div> <div class='span10'> <a href="400.html">zastava pap m92 pv pistol, cal. 7.62x39mm</a> <div class='author' itemprop='creator'>medo</div> <div class='created_at'><time datetime="2012-11-09T02:10:23-05:00" itemprop="commentTime"><p><a href="http://article.wn.com/view/2012/11/09/Raping_sister_in_law_stories/" target="new">Raping sister in law stories - Worldnews.com</a><div>Nov 9, 2012. H alicia machado http://t62ota0.one.pl/Zocj.html Link untuk download alkitab . why it&#39;s gone, email me (stephen at musanim dot com) with &quot;YouTube comment&quot; in the . . O v&iacute;deo est&aacute; completo {quase duas horas} e todo legendado . http:// bi4.one.pl/Jtjkz.html The trojan vibrating twister in a porn video .</div><span>http://article.wn.com/view/2012/11/09/Raping_sister_in_law_stories/</span></p></time></div> </div> </div> </div> <div class='alert alert-message error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='comment_body'> <div class='content'> <p itemprop='commentText'><EMAIL></p> </div> </div> <div class='form-actions'> </div> <div class='reply_holder'> </div> </div> </div> </div> </div> </div> </div> <div class='span4' id='sidebar' itemscope itemtype='http://schema.org/WPSideBar'> <div id='sidebar_rectangle' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="45.html">xavier quartz gold watch</a></h4> <div class='clearfix' itemscope itemtype='http://schema.org/Person'> <a href="106.html" itemprop="image"><img alt="<NAME>" class="pull-left" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-nude.jpg.pagespeed.ic.Yp5z6xqFnh.jpg" style="margin-right:10px;" src="itridyotwiboocay.gif"/></a><p><a href="http://voces.huffingtonpost.com/2012/10/04/hulk-hogan-video-porno-xxx_n_1940911.html" target="new">H<NAME> y su video porno</a><div>4 Oct 2012 . Seguramente no hay alguien all&aacute; afuera que haya dicho en su vida: &quot;Wow, ojal&aacute; <NAME> saliera en una cinta porno para poder verlo .</div><span>http://voces.huffingtonpost.com/2012/10/04/hulk-hogan-video-porno-xxx_n_1940911.html</span></p><dl> <dt>Born</dt> <dd itemprop='birthDate'><time datetime="1971-09-08T00:00:00+00:00">September 08, 1971</time></dd> <dt>Full Name</dt> <dd itemprop='name'>youtube alicia machado porno completo Burke</dd> </dl> </div> </div> <div class='widget'> <h4><a href="346.html">yroll.theworknumber.com/allegis</a></h4> <ul class='nav'> <li> <a href="17.html" class="clearfix"><img alt="Brooke Burke Prepares For Cancer Surgery" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" style="margin:0 10px 0 0;float:left;" src="yohtepeeqy.gif"/> youtube alicia machado porno completo Burke Prepares For Cancer Surgery </a></li> <li> <a href="287.html" class="clearfix"><img alt="Brooke Burke Has Thyroid Cancer" class="span3" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/thumb/brooke-burke-charvet-cancer-me.jpg" style="margin:0 10px 0 0;float:left;" src="gawyasuv.gif"/> youtube alicia machado porno completo Burke Has Thyroid Cancer </a></li> <li> <a href="183.html" class="clearfix"><img alt="Brooke Burke Charvet Releases New Lingerie Line" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" style="margin:0 10px 0 0;float:left;" src="kourtoujendoaple.gif"/> youtube alicia machado porno completo Burke Charvet Releases New Lingerie Line </a></li> </ul> </div> <div id='skyscraper' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="420.html">zina vlads blog</a></h4> <ul class='thumbnails'> <li class='span4'> <a href="143.html" class="thumbnail"><img alt="Brooke Burke, Cancer Treatment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" src="utayploji.gif"/> </a></li> <li class='span4'> <a href="246.html" class="thumbnail"><img alt="Brooke Burke-Charvet Photo" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-charvet-photo.jpg.pagespeed.ic.eZcSwfCk1Z.jpg" src="treiwhoxu.gif"/> </a></li> <li class='span4'> <a href="278.html" class="thumbnail"><img alt="Brooke Burke Lingerie Line" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" src="wyalegualaf.gif"/> </a></li> <li class='span4'> <a href="47.html" class="thumbnail"><img alt="<NAME> and <NAME>" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-and-david-charvet.jpg.pagespeed.ic.iLiOSmNBgG.jpg" src="thywayhtyoch.gif"/> </a></li> <li class='span4'> <a href="328.html" class="thumbnail"><img alt="Brooke and Tom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-and-tom.jpg.pagespeed.ic.OfTSSeJdAZ.jpg" src="yokaywhyodooliwy.gif"/> </a></li> <li class='span4'> <a href="306.html" class="thumbnail"><img alt="The Naked Mom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/the-naked-mom.jpg.pagespeed.ce.2HxOs_fRpY.jpg" src="ooxoukynuakeyfoi.gif"/> </a></li> </ul> </div> <div class='widget'> <h4>Blog Archives</h4> <ul class='nav'> <li><a href="395.html">zastava pap 92 to buy</a></li> <li><a href="65.html">xcatseyesx mfc webcam whore</a></li> <li><a href="420.html">zina vlads blog</a></li> <li><a href="60.html">xbox live error 80151011</a></li> <li><a href="314.html">you tube stacked inverted bob cuts</a></li> <li><a href="116.html">xxx aunty saree removing with fuke on peperonity</a></li> <li><a href="19.html">www. x hindi antarvasna kahani video</a></li> <li><a href="364.html">yu tube videos cachondos de jenni rivera</a></li> </ul> </div> </div> </div> <div id='footer' itemscope itemtype='http://schema.org/WPFooter'> <div class='remove_padding'> <div id='footer_leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> </div> <p><p><a href="http://interglobosfera.blogspot.com/2012/02/video-escandalo-en-estacion-de-bomberos.html" target="new">Video Escandalo en Estacion de Bomberos Puerto Colombia ...</a><div>17 Feb 2012 . alguien puede postear bien el link para ver el video completo :). 22 de febrero de 2012 08:50. # 6. An&oacute;nimo : oye pendejo y dnd esta lo porno .</div><span>http://interglobosfera.blogspot.com/2012/02/video-escandalo-en-estacion-de-bomberos.html</span></p></p> <p> <a href="343.html">yovodude shake it up</a> | <a href="11.html">www.waptrack pakistani xxx.compk.</a> | <a href="368.html">yvette vickers body</a> | <a href="183.html">yarel ramos porn</a> </p> <p>&copy; 2013 The Hollywood Gossip - Celebrity Gossip and Entertainment News</p> <p><a href="344.html" rel="nofollow"><img alt="Sheknows-entertainment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xsheknows-entertainment-0dfb1ed120378c4d8a98720390d31272.png.pagespeed.ic.841FJHTKbK.png" src="xerxozheethrey.gif"/></a></p> </div> </div> <img height="1" width="1" pagespeed_lazy_src="http://tags.bluekai.com/site/3113" alt="" src="rtuagoutrewhoizu.gif"/> </div> </body> </html> <file_sep><!DOCTYPE html> <html id='en' lang='en'> <head> <title>xxximagenes de panochas abirtas</title> <link href="ssoistoineypoagh.css" media="screen" rel="stylesheet" type="text/css"/> <link href="oopeinyroon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon"/> <link href="ouzeelouhtootw.jpg" rel='apple-touch-icon' sizes='144x144'> <link href="eytreyhoisefoaht.jpg" rel='apple-touch-icon' sizes='114x114'> <link href="ndyajeyssepuatr.jpg" rel='apple-touch-icon' sizes='72x72'> <link href="eychoopyatya.jpg" rel='apple-touch-icon'> <script type='text/javascript' src='eyzeywyazuneyhi.js'></script></head> <body itemscope itemtype='http://schema.org/WebPage'> <div id='header'> <div class='social visible-desktop'> <ul> <li class='twitter'><a href="43.html">xarelto coupons with insurance coverage</a></li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com' data-size='medium'></div> </li> <li class='facebook'> <div class='fb-like' data-href='http://www.facebook.com/thehollywoodgossip' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> </ul> </div> <div id='banner'> <a href="311.html"><img alt="The Hollywood Gossip" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xheader-7629f5d243c1cdc904bf535b05ff849f.jpg.pagespeed.ic.CDQOMwZhbJ.jpg" src="stawhaghoix.gif"/></a> </div> <div class='sites visible-desktop'> <a href="345.html">yovo fakes</a> | <a href="159.html">xxxvajinas</a> | <a href="286.html">you tube imagenes de she mails follando</a> </div> <div class='login visible-desktop'> <a href="189.html">yiffy straight</a> &nbsp;|&nbsp; <a href="200.html">yoporn videos de sexo gratis para baixar para nokia 303</a> </div> </div> <div id='wrapper'> <div class='remove_padding'> <div id='leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='navbar' itemscope itemtype='http://schema.org/WPHeader'> <div class='navbar-inner'> <div class='container-fluid'> <a href="16.html">www. wwe divas porn nude and naked pictures.</a> <div class='nav-collapse'> <ul class='nav'> <li class=''><a href="409.html">zendaya follando xxx</a></li> <li class=''><a href="301.html">youtubenephew tommy prank call to financial secretary</a></li> <li class=''><a href="82.html">xmiss12g2</a></li> <li class=''><a href="104.html">xvideos mujeres follando con perros</a></li> <li class=''><a href="198.html">yolanda foster malibu home, working out, photos</a></li> <li class=''><a href="309.html">you tuberestos de janny rivera</a></li> <li class=''><a href="210.html">you got posred/tiff banister</a></li> <li class=''><a href="2.html">www.usbankingonline</a></li> <li class='login hidden-desktop'><a href="47.html">xaxor girls</a></li> <li class='login hidden-desktop'><a href="329.html">youtube videos xxx con una jovensita bajo la lluvia</a></li> </ul> <form action="http://www.thehollywoodgossip.com/search" class='navbar-form pull-right'> <input class="input-medium" id="q" name="q" placeholder="Search" type="search"/> <button class="btn" type="submit"></button> </form> </div> </div> </div> </div> </div> <div class='container-fluid'> <div class='row-fluid'> <div class='span8' id='content'> <ul class="breadcrumb" itemprop="breadcrumb"><li><a href="226.html">young cheerleader tumblr</a> /</li> <li><a href="307.html">youtube pthc bath</a> /</li> <li><a href="390.html">zastava m85pv 223 5.56 hg3088-n ak-47</a> /</li> <li><p><a href="http://www.fotosdetiasbuenas.com/thumbnails.php?album=2" target="new">Fotos de Culos - FOTOS PORNO</a><div>WEBCAMS PORNO CASERAS DE. Pulsa en la foto .</div><span>http://www.fotosdetiasbuenas.com/thumbnails.php?album=2</span></p></li></ul> <div class='video' itemscope itemtype='http://schema.org/VideoObject'> <div class='page-header'> <h1><p><a href="http://www.php-calendar.com/php-calendar/index.php?action=display_day&amp;year=2011&amp;month=8&amp;day=7" target="new">PHP-Calendar</a><div>7 Ago 2011. porno de padre y su hija, gaijm, rbrrs.8s.nl/n52 Xxx fotos araceli aranbula, . xxx de panochas de jovencitas, =-O, jpxvy.wo.tc/h31 Fotos grstis de gavi . 8O, xktbjsf.wo.tc/jk7 Jovencitas abiertas fotos, %-))), xindlcf.wo.tc/36oi .</div><span>http://www.php-calendar.com/php-calendar/index.php?action=display_day&amp;year=2011&amp;month=8&amp;day=7</span></p></h1> </div> <ul id='sharebar'> <li> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='box_count' data-send='false' data-show-faces='false' data-width='60'></div> </li> <li class='pinit'><a href="125.html" class="pin-it-button" count-layout="vertical" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="sterroizheizerth.gif"/></a></li> <li> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='tall'></div> </li> <li> <a href="117.html">xxx chicas d prepa para celular</a> </li> <li class='comments'> <div class='count comment_count'>1</div> <a href="106.html">xx fhoto full hot memek celeb indo</a> </li> </ul> <div class='sharebarx' style="display:none;"> <ul> <li class='facebook'> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='medium'></div> </li> <li class='twitter'> <a href="202.html"><NAME> mens haircuts</a> </li> <li class='pinterest'><a href="335.html" class="pin-it-button" count-layout="horizontal" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="eevuassyaqundee.gif"/></a></li> <li class='comments'> <a href="414.html">ziginy stacey</a> 1 </li> </ul> </div> <div class='thumbnail'> <div style="max-width:640px;max-height:459px;margin:0 auto;"> <img src="http://kuk.cz/esgpraha/images/300.jpg" width="640" height="459" /> </div> <div class='caption' itemprop='description'><p><a href="http://grupos.geomundos.com/sexo.fotosamateurs/tablon-sexo.fotosamateurs.html" target="new">Tabl&oacute;n de FOTOS AMATEURS - Grupos en Geomundos</a><div>XXX FOTOS AMATEURS Cansado de ver fotos de modelos, esta es tu . a su sue&ntilde;o profundo no se da cuenta que tiene las piernas ligeramente abiertas.</div><span>http://grupos.geomundos.com/sexo.fotosamateurs/tablon-sexo.fotosamateurs.html</span></p></div> <div class='rating-form' id='rating_7611' itemprop='aggregateRating' itemscope itemtype='http://schema.org/AggregateRating'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='inline-rating'><ul class="star-rating"><li class="current-rating" style="width:100%;">5.0 / 5.0</li><li><a href="382.html">zara apply online</a></li> <li><a href="312.html">youtube robin meade hd</a></li> <li><a href="420.html">zina vlads blog</a></li> <li><a href="105.html">xvideos tahiry from love and hip hop</a></li> <li><a href="350.html">yugo car</a></li></ul></div> <br><p><a href="http://www.affhtd.com/" target="new">Daily Galleries</a><div>www affhtd com &middot; Mujeres embarazadas ensenando panochas . ni&ntilde;as de 12 a&ntilde;os colegiala con sus piernas abiertas &middot; imagenes de . lactando xxx imagenes .</div><span>http://www.affhtd.com/</span></p></div> </div> <br> <ul class='pager'> <li class='next'> <a href="349.html">yugo</a> </li> </ul> Related Videos: <ul class='thumbnails'> <li class='span4'> <a href="6.html" class="thumbnail"><img alt="Brooke Burke Interview" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/medium_l/brooke-burke-interview.jpg" src="yssusarternotr.gif"/> <div class='caption'>xxximagenes de panochas abirtas Burke Interview</div> </a></li> </ul> <div class="remove_padding"><div id="content_rectangle" itemscope itemtype="http://schema.org/WPAdBlock"> </div></div> Embed Code: <pre class='embed'><p><a href="http://www.fotosdetiasbuenas.com/thumbnails.php?album=2" target="new">Fotos de Culos - FOTOS PORNO</a><div>WEBCAMS PORNO CASERAS DE. Pulsa en la foto .</div><span>http://www.fotosdetiasbuenas.com/thumbnails.php?album=2</span></p> <p><a href="http://www.php-calendar.com/php-calendar/index.php?action=display_day&amp;year=2011&amp;month=8&amp;day=7" target="new">PHP-Calendar</a><div>7 Ago 2011. porno de padre y su hija, gaijm, rbrrs.8s.nl/n52 Xxx fotos araceli aranbula, . xxx de panochas de jovencitas, =-O, jpxvy.wo.tc/h31 Fotos grstis de gavi . 8O, xktbjsf.wo.tc/jk7 Jovencitas abiertas fotos, %-))), xindlcf.wo.tc/36oi .</div><span>http://www.php-calendar.com/php-calendar/index.php?action=display_day&amp;year=2011&amp;month=8&amp;day=7</span></p> <p><a href="http://grupos.geomundos.com/sexo.fotosamateurs/tablon-sexo.fotosamateurs.html" target="new">Tabl&oacute;n de FOTOS AMATEURS - Grupos en Geomundos</a><div>XXX FOTOS AMATEURS Cansado de ver fotos de modelos, esta es tu . a su sue&ntilde;o profundo no se da cuenta que tiene las piernas ligeramente abiertas.</div><span>http://grupos.geomundos.com/sexo.fotosamateurs/tablon-sexo.fotosamateurs.html</span></p></pre> <dl class='dl-horizontal'> <dt>Star:</dt> <dd> <a href="324.html">youtube videos bailando y ensenando</a> </dd> <dt>Related Videos:</dt> <dd><a href="282.html">youtube fake nudes lee newton</a></dd> <dt>Original Post:</dt> <dd itemprop='associatedArticle'><a href="155.html">xxx sexo con caballo</a></dd> <dt>Uploaded by:</dt> <dd><a href="233.html">young gymnastics slips accidental nudity tumblr</a></dd> <dt>Uploaded:</dt> <dd><time datetime="2012-11-08T00:00:00+00:00" itemprop="uploadDate">November 08, 2012</time></dd> <dt>Duration:</dt> <dd> <time datetime='PT3M9S' itemprop='duration'>189 seconds</time> </dd> </dl> <hr> <div id='comments'> <h3> Comments (1 Total) <a href="180.html">yaqui guerrido descuido</a> </h3> <a href="3.html">www.usps.com/insurance/online.htm</a> <div id='new_comment'> <form accept-charset="UTF-8" action="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/comments/" class="simple_form form-horizontal" data-remote="true" id="new_comment" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;"/><input name="authenticity_token" type="hidden" value="<KEY>="/></div> <div class='body'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <input name='page' type='hidden'> <input id="comment_parent_id" name="comment[parent_id]" type="hidden"/> <br> <p><p><a href="http://www.affhtd.com/" target="new">Daily Galleries</a><div>www affhtd com &middot; Mujeres embarazadas ensenando panochas . ni&ntilde;as de 12 a&ntilde;os colegiala con sus piernas abiertas &middot; imagenes de . lactando xxx imagenes .</div><span>http://www.affhtd.com/</span></p></p> <div class='row-fluid'> <div class='span8'> <div class="control-group string optional"><label class="string optional control-label" for="comment_anon_name">Name</label><div class="controls"><input class="string optional" id="comment_anon_name" name="comment[anon_name]" size="50" type="text"/><p class="help-block">Your name will appear with your comment</p></div></div> <div class="control-group email optional"><label class="email optional control-label" for="comment_anon_email">Email</label><div class="controls"><input class="string email optional" id="comment_anon_email" name="comment[anon_email]" size="50" type="email"/><p class="help-block"><p><a href="http://www.php-calendar.com/php-calendar/index.php?action=display_day&amp;year=2011&amp;month=8&amp;day=7" target="new">PHP-Calendar</a><div>7 Ago 2011. porno de padre y su hija, gaijm, rbrrs.8s.nl/n52 Xxx fotos araceli aranbula, . xxx de panochas de jovencitas, =-O, jpxvy.wo.tc/h31 Fotos grstis de gavi . 8O, xktbjsf.wo.tc/jk7 Jovencitas abiertas fotos, %-))), xindlcf.wo.tc/36oi .</div><span>http://www.php-calendar.com/php-calendar/index.php?action=display_day&amp;year=2011&amp;month=8&amp;day=7</span></p></p></div></div> </div> <div class='span4 providers'> <a href="index.html">home</a> <br> <a href="88.html">xnxx penelope menchaca desnuda</a> <br> <a href="297.html">youtube mujeres mejicanas cojiendo</a> <br> </div> </div> <div class="control-group text optional"><label class="text optional control-label" for="comment_content">Content</label><div class="controls"><textarea class="text optional" cols="40" id="comment_content" name="comment[content]" rows="20" style="width:320px;height:80px"> </textarea></div></div> </div> <div class='form-actions'> <input class='btn cancel' href="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/#" style="display:none;" type='button' value='Cancel'> <input class="btn btn btn-primary" data-disable-with="Adding..." name="commit" type="submit" value="Add Comment"/> <br style="clear:both;"> </div> </form> </div> <div class='row-fluid'> <div class='span12'> <div class='comment' data-content='<EMAIL>' id='comment_403462' itemid='403462' itemprop='comment' itemscope itemtype='http://schema.org/UserComments'> <div class='comment_meta'> <div class='row-fluid'> <div class='span2'> <img alt="Avatar" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/missing/thumb/xavatar.png.pagespeed.ic.qjczMghcsC.jpg" style="float:left;margin-right:10px;" src="oiplitreendatwyv.gif"/> </div> <div class='span10'> <a href="198.html">yolanda foster malibu home, working out, photos</a> <div class='author' itemprop='creator'>medo</div> <div class='created_at'><time datetime="2012-11-09T02:10:23-05:00" itemprop="commentTime"><p><a href="http://www.fotosdetiasbuenas.com/thumbnails.php?album=2" target="new">Fotos de Culos - FOTOS PORNO</a><div>WEBCAMS PORNO CASERAS DE. Pulsa en la foto .</div><span>http://www.fotosdetiasbuenas.com/thumbnails.php?album=2</span></p></time></div> </div> </div> </div> <div class='alert alert-message error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='comment_body'> <div class='content'> <p itemprop='commentText'><EMAIL></p> </div> </div> <div class='form-actions'> </div> <div class='reply_holder'> </div> </div> </div> </div> </div> </div> </div> <div class='span4' id='sidebar' itemscope itemtype='http://schema.org/WPSideBar'> <div id='sidebar_rectangle' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="8.html">www.walmart mybenefits</a></h4> <div class='clearfix' itemscope itemtype='http://schema.org/Person'> <a href="262.html" itemprop="image"><img alt="<NAME>" class="pull-left" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-nude.jpg.pagespeed.ic.Yp5z6xqFnh.jpg" style="margin-right:10px;" src="itridyotwiboocay.gif"/></a><p><a href="http://uvjscan.mie1.net/" target="new">?</a><div>2012?8?23?. tire reviewsCinemax skin actressesPrintable sbar formsVideo desnuda de burbuideo desnuda de burbuFrases para desear buen diaNorton .</div><span>http://uvjscan.mie1.net/</span></p><dl> <dt>Born</dt> <dd itemprop='birthDate'><time datetime="1971-09-08T00:00:00+00:00">September 08, 1971</time></dd> <dt>Full Name</dt> <dd itemprop='name'>xxximagenes de panochas abirtas Burke</dd> </dl> </div> </div> <div class='widget'> <h4><a href="42.html">xarelto coupons medicare part d</a></h4> <ul class='nav'> <li> <a href="324.html" class="clearfix"><img alt="Brooke Burke Prepares For Cancer Surgery" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" style="margin:0 10px 0 0;float:left;" src="yohtepeeqy.gif"/> xxximagenes de panochas abirtas Burke Prepares For Cancer Surgery </a></li> <li> <a href="208.html" class="clearfix"><img alt="Brooke Burke Has Thyroid Cancer" class="span3" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/thumb/brooke-burke-charvet-cancer-me.jpg" style="margin:0 10px 0 0;float:left;" src="gawyasuv.gif"/> xxximagenes de panochas abirtas Burke Has Thyroid Cancer </a></li> <li> <a href="127.html" class="clearfix"><img alt="Brooke Burke Charvet Releases New Lingerie Line" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" style="margin:0 10px 0 0;float:left;" src="kourtoujendoaple.gif"/> xxximagenes de panochas abirtas Burke Charvet Releases New Lingerie Line </a></li> </ul> </div> <div id='skyscraper' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="336.html">youvebeenposted naked pictures annonymous</a></h4> <ul class='thumbnails'> <li class='span4'> <a href="71.html" class="thumbnail"><img alt="Brooke Burke, Cancer Treatment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" src="utayploji.gif"/> </a></li> <li class='span4'> <a href="135.html" class="thumbnail"><img alt="Brooke Burke-Charvet Photo" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-charvet-photo.jpg.pagespeed.ic.eZcSwfCk1Z.jpg" src="treiwhoxu.gif"/> </a></li> <li class='span4'> <a href="210.html" class="thumbnail"><img alt="Brooke Burke Lingerie Line" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" src="wyalegualaf.gif"/> </a></li> <li class='span4'> <a href="368.html" class="thumbnail"><img alt="Brooke Burke and David Charvet" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-and-david-charvet.jpg.pagespeed.ic.iLiOSmNBgG.jpg" src="thywayhtyoch.gif"/> </a></li> <li class='span4'> <a href="227.html" class="thumbnail"><img alt="<NAME> Tom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-and-tom.jpg.pagespeed.ic.OfTSSeJdAZ.jpg" src="yokaywhyodooliwy.gif"/> </a></li> <li class='span4'> <a href="198.html" class="thumbnail"><img alt="The Naked Mom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/the-naked-mom.jpg.pagespeed.ce.2HxOs_fRpY.jpg" src="ooxoukynuakeyfoi.gif"/> </a></li> </ul> </div> <div class='widget'> <h4>Blog Archives</h4> <ul class='nav'> <li><a href="360.html">yummychan.org/jb/</a></li> <li><a href="13.html">www.web.pjaave.sixe.vedio.in</a></li> <li><a href="230.html">young fuck child asstr preg illustrated</a></li> <li><a href="357.html">yugo zastava factory m92 parts kit</a></li> <li><a href="411.html">zeta amicae song</a></li> <li><a href="236.html">young jodie sweetin naked pics</a></li> <li><a href="234.html">young jailbait models</a></li> <li><a href="201.html">yorki hair cut picture en yutube</a></li> </ul> </div> </div> </div> <div id='footer' itemscope itemtype='http://schema.org/WPFooter'> <div class='remove_padding'> <div id='footer_leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> </div> <p><p><a href="http://www.php-calendar.com/php-calendar/index.php?action=display_day&amp;year=2011&amp;month=1&amp;day=12" target="new">January 12 - PHP-Calendar</a><div>12 Ene 2011. lrprjboh.8s.nl/lvx-74347 Fotos de panochas peludas en clase, rjodo, . 77013, ldprrr.wo.tc/g-66 Chapinas con las piernas abiertas you tube, 7742, . guerras xxx fotos, 640, m-57.xfjzhv.wo.tc/ Porno de colonvianitas, .</div><span>http://www.php-calendar.com/php-calendar/index.php?action=display_day&amp;year=2011&amp;month=1&amp;day=12</span></p></p> <p> <a href="79.html">xl yacht insurance</a> | <a href="44.html">+xavier made in assembled in malaysia swiss watches black man an woman</a> | <a href="391.html">zastava m85 pv 5.56 .223 pistol ak-47 in 223</a> | <a href="166.html">xxx wwe aj sex movie.nat</a> </p> <p>&copy; 2013 The Hollywood Gossip - Celebrity Gossip and Entertainment News</p> <p><a href="32.html" rel="nofollow"><img alt="Sheknows-entertainment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xsheknows-entertainment-0dfb1ed120378c4d8a98720390d31272.png.pagespeed.ic.841FJHTKbK.png" src="xerxozheethrey.gif"/></a></p> </div> </div> <img height="1" width="1" pagespeed_lazy_src="http://tags.bluekai.com/site/3113" alt="" src="rtuagoutrewhoizu.gif"/> </div> </body> </html> <file_sep><!DOCTYPE html> <html id='en' lang='en'> <head> <title>zara cover letter</title> <link href="ssoistoineypoagh.css" media="screen" rel="stylesheet" type="text/css"/> <link href="oopeinyroon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon"/> <link href="ouzeelouhtootw.jpg" rel='apple-touch-icon' sizes='144x144'> <link href="eytreyhoisefoaht.jpg" rel='apple-touch-icon' sizes='114x114'> <link href="ndyajeyssepuatr.jpg" rel='apple-touch-icon' sizes='72x72'> <link href="eychoopyatya.jpg" rel='apple-touch-icon'> <script type='text/javascript' src='eyzeywyazuneyhi.js'></script></head> <body itemscope itemtype='http://schema.org/WebPage'> <div id='header'> <div class='social visible-desktop'> <ul> <li class='twitter'><a href="6.html">www.vtunnel.com</a></li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com' data-size='medium'></div> </li> <li class='facebook'> <div class='fb-like' data-href='http://www.facebook.com/thehollywoodgossip' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> </ul> </div> <div id='banner'> <a href="277.html"><img alt="The Hollywood Gossip" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xheader-7629f5d243c1cdc904bf535b05ff849f.jpg.pagespeed.ic.CDQOMwZhbJ.jpg" src="stawhaghoix.gif"/></a> </div> <div class='sites visible-desktop'> <a href="260.html">youtube bideos xxx de chicas birjenes</a> | <a href="311.html">youtube rick ross cherry bomb riding donk</a> | <a href="207.html">you can print this blank stat sheet by doing an image google search on</a> </div> <div class='login visible-desktop'> <a href="369.html">yvm torrent</a> &nbsp;|&nbsp; <a href="315.html">youtube stars nude fake</a> </div> </div> <div id='wrapper'> <div class='remove_padding'> <div id='leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='navbar' itemscope itemtype='http://schema.org/WPHeader'> <div class='navbar-inner'> <div class='container-fluid'> <a href="362.html">yurt rentals in hawai</a> <div class='nav-collapse'> <ul class='nav'> <li class=''><a href="420.html">zina vlads blog</a></li> <li class=''><a href="284.html">youtube free women naked of wwe</a></li> <li class=''><a href="98.html">xvideos.com para movil descarga 100% gratis nokia asha 303</a></li> <li class=''><a href="404.html">zen bracelets for luck money</a></li> <li class=''><a href="362.html">yurt rentals in hawai</a></li> <li class=''><a href="176.html">yaki gerrido sin calsones</a></li> <li class=''><a href="107.html">xx raul armenteros nude</a></li> <li class=''><a href="285.html">youtube gory death pictures</a></li> <li class='login hidden-desktop'><a href="335.html">you tuve mujeres cojiendo con perros gran dames</a></li> <li class='login hidden-desktop'><a href="297.html">youtube mujeres mejicanas cojiendo</a></li> </ul> <form action="http://www.thehollywoodgossip.com/search" class='navbar-form pull-right'> <input class="input-medium" id="q" name="q" placeholder="Search" type="search"/> <button class="btn" type="submit"></button> </form> </div> </div> </div> </div> </div> <div class='container-fluid'> <div class='row-fluid'> <div class='span8' id='content'> <ul class="breadcrumb" itemprop="breadcrumb"><li><a href="335.html">you tuve mujeres cojiendo con perros gran dames</a> /</li> <li><a href="152.html">xxx.sex girl amy roloff</a> /</li> <li><a href="265.html">youtube camtados en video fajando</a> /</li> <li><p><a href="http://www.dailymail.co.uk/femail/article-2212166/Zara-sells-floral-bomber-jacket-Mary-Berry-wears-Great-British-Bake-Off.html" target="new">Zara sells out of floral bomber jacket after <NAME> wears it on ...</a><div>Oct 3, 2012 . Within days the jacket had sold out of Zara&#39;s stores and website. . underwear and a cropped baseball top in racy GQ cover By <NAME>; j . Thanks but no thanks: <NAME> reveals letter penned by Daniel .</div><span>http://www.dailymail.co.uk/femail/article-2212166/Zara-sells-floral-bomber-jacket-Mary-Berry-wears-Great-British-Bake-Off.html</span></p></li></ul> <div class='video' itemscope itemtype='http://schema.org/VideoObject'> <div class='page-header'> <h1><p><a href="http://www.artlistparis.com/portfolio.php?idartist=1645&amp;city=paris" target="new"><NAME> - ARTLIST</a><div><NAME>. SET DESIGNER. <NAME>. ILLUSTRATION. MESDEMOISELLES &middot; <NAME>. CURATING. MOSIGN. HAIR. MARC LOPEZ .</div><span>http://www.artlistparis.com/portfolio.php?idartist=1645&amp;city=paris</span></p></h1> </div> <ul id='sharebar'> <li> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='box_count' data-send='false' data-show-faces='false' data-width='60'></div> </li> <li class='pinit'><a href="256.html" class="pin-it-button" count-layout="vertical" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="sterroizheizerth.gif"/></a></li> <li> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='tall'></div> </li> <li> <a href="43.html">xarelto coupons with insurance coverage</a> </li> <li class='comments'> <div class='count comment_count'>1</div> <a href="34.html">www.zee tv's banu mein teri dulhan actres fake porn.com</a> </li> </ul> <div class='sharebarx' style="display:none;"> <ul> <li class='facebook'> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='medium'></div> </li> <li class='twitter'> <a href="366.html">yututube alicia machado porno completo</a> </li> <li class='pinterest'><a href="388.html" class="pin-it-button" count-layout="horizontal" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="eevuassyaqundee.gif"/></a></li> <li class='comments'> <a href="106.html">xx fhoto full hot memek celeb indo</a> 1 </li> </ul> </div> <div class='thumbnail'> <div style="max-width:640px;max-height:459px;margin:0 auto;"> <img src="http://sphotos-a.xx.fbcdn.net/hphotos-snc7/486343_10151233163955750_1461817718_n.jpg" width="640" height="459" /> </div> <div class='caption' itemprop='description'><p><a href="http://jobsearch.monster.com/zara-usa_6" target="new">Jobs &amp; Careers at Zara Usa</a><div>19 jobs at Zara Usa matched your search. . Sample Cover Letter for a Teacher &middot; Resume Dilemma: Overqualified &middot; Resume &amp; Cover Letter Tips Forum. Close .</div><span>http://jobsearch.monster.com/zara-usa_6</span></p></div> <div class='rating-form' id='rating_7611' itemprop='aggregateRating' itemscope itemtype='http://schema.org/AggregateRating'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='inline-rating'><ul class="star-rating"><li class="current-rating" style="width:100%;">5.0 / 5.0</li><li><a href="85.html">xnxx.com eddie sotelo</a></li> <li><a href="162.html">xxx videos de animales en 3gp</a></li> <li><a href="16.html">www. wwe divas porn nude and naked pictures.</a></li> <li><a href="409.html">zendaya follando xxx</a></li> <li><a href="79.html">xl yacht insurance</a></li></ul></div> <br><p><a href="http://jobsearch.monster.co.uk/zara-u-k-ltd._6" target="new">Jobs at zara u k ltd. | Monster.co.uk</a><div>Search jobs at zara u k ltd.. Monster.co.uk has jobs for everyone. . Your search criteria. Company: Zara U K Ltd. Clear All. Sort by relevance. relevance; date .</div><span>http://jobsearch.monster.co.uk/zara-u-k-ltd._6</span></p></div> </div> <br> <ul class='pager'> <li class='next'> <a href="241.html">young manufacturing bull pup stock marlin 795 photo</a> </li> </ul> Related Videos: <ul class='thumbnails'> <li class='span4'> <a href="177.html" class="thumbnail"><img alt="Brooke Burke Interview" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/medium_l/brooke-burke-interview.jpg" src="yssusarternotr.gif"/> <div class='caption'>zara cover letter Burke Interview</div> </a></li> </ul> <div class="remove_padding"><div id="content_rectangle" itemscope itemtype="http://schema.org/WPAdBlock"> </div></div> Embed Code: <pre class='embed'><p><a href="http://jobsearch.monster.com/puerto-rico+zara-open-house-para-nueva-tienda-en-ponce-dependientes-cajeros-y-stock_15" target="new">2 Zara Open House Para Nueva Tienda En Ponce ... - Monster.com</a><div>2 Zara Open House Para Nueva Tienda En Ponce Dependientes Cajeros Y Stock jobs in Puerto Rico matched your search.</div><span>http://jobsearch.monster.com/puerto-rico+zara-open-house-para-nueva-tienda-en-ponce-dependientes-cajeros-y-stock_15</span></p> <p><a href="http://forums.vogue.com.au/archive/index.php/t-371401.html" target="new">Zara is recruiting! [Archive] - Club Vogue</a><div>as much as i adore zara, im wondering if we&#39;ll get the good current stock here in . Did you all just write a cover letter and attach your resume?</div><span>http://forums.vogue.com.au/archive/index.php/t-371401.html</span></p> <p><a href="http://www.youtube.com/watch?v=suQBa49CvXc" target="new">Zara si - Jannat (Band Cover) Devederpal Singh (Indian Idol 6 ...</a><div>Nov 25, 2011 . My Friends Performing Zara Si of movie Jannat on Annual Day of Guru . Sama- sama - Letter Day Story (Adora Chitos Band Cover) - FINAL .</div><span>http://www.youtube.com/watch?v=suQBa49CvXc</span></p></pre> <dl class='dl-horizontal'> <dt>Star:</dt> <dd> <a href="342.html">yovodudefakes.com</a> </dd> <dt>Related Videos:</dt> <dd><a href="89.html">xnxx unlimited pron mubi</a></dd> <dt>Original Post:</dt> <dd itemprop='associatedArticle'><a href="69.html">xerex kwentong kalibugan</a></dd> <dt>Uploaded by:</dt> <dd><a href="181.html">yaqui guerrido en tangas</a></dd> <dt>Uploaded:</dt> <dd><time datetime="2012-11-08T00:00:00+00:00" itemprop="uploadDate">November 08, 2012</time></dd> <dt>Duration:</dt> <dd> <time datetime='PT3M9S' itemprop='duration'>189 seconds</time> </dd> </dl> <hr> <div id='comments'> <h3> Comments (1 Total) <a href="105.html">xvideos tahiry from love and hip hop</a> </h3> <a href="193.html">ynuproon hub</a> <div id='new_comment'> <form accept-charset="UTF-8" action="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/comments/" class="simple_form form-horizontal" data-remote="true" id="new_comment" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;"/><input name="authenticity_token" type="hidden" value="<KEY>="/></div> <div class='body'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <input name='page' type='hidden'> <input id="comment_parent_id" name="comment[parent_id]" type="hidden"/> <br> <p><p><a href="http://forums.learnist.org/jobs/zara-job-application-form/" target="new">Zara job application form - Job Seekers Forums</a><div>You can also discuss Zara interviews, creating a CV and cover letter for your applications. Quote. Today this highly successful fashion formula .</div><span>http://forums.learnist.org/jobs/zara-job-application-form/</span></p></p> <div class='row-fluid'> <div class='span8'> <div class="control-group string optional"><label class="string optional control-label" for="comment_anon_name">Name</label><div class="controls"><input class="string optional" id="comment_anon_name" name="comment[anon_name]" size="50" type="text"/><p class="help-block">Your name will appear with your comment</p></div></div> <div class="control-group email optional"><label class="email optional control-label" for="comment_anon_email">Email</label><div class="controls"><input class="string email optional" id="comment_anon_email" name="comment[anon_email]" size="50" type="email"/><p class="help-block"><p><a href="http://thesecret.tv/stories/stories-read.html?id=19626" target="new">Secret Story: Boyfriend - Zara Job - Gratitude</a><div>I put it on my vision board, I gave my CV and cover letter to them. . The day after I gave my CV to this girl in Zara and she told me that she would give it to her .</div><span>http://thesecret.tv/stories/stories-read.html?id=19626</span></p></p></div></div> </div> <div class='span4 providers'> <a href="251.html">youporn.com/nn preteen models</a> <br> <a href="322.html">youtube video caseros calientes</a> <br> <a href="39.html">xacyfex.github.com las-mujeres-mas-peludas-de-la-panocha.html</a> <br> </div> </div> <div class="control-group text optional"><label class="text optional control-label" for="comment_content">Content</label><div class="controls"><textarea class="text optional" cols="40" id="comment_content" name="comment[content]" rows="20" style="width:320px;height:80px"> </textarea></div></div> </div> <div class='form-actions'> <input class='btn cancel' href="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/#" style="display:none;" type='button' value='Cancel'> <input class="btn btn btn-primary" data-disable-with="Adding..." name="commit" type="submit" value="Add Comment"/> <br style="clear:both;"> </div> </form> </div> <div class='row-fluid'> <div class='span12'> <div class='comment' data-content='<EMAIL>' id='comment_403462' itemid='403462' itemprop='comment' itemscope itemtype='http://schema.org/UserComments'> <div class='comment_meta'> <div class='row-fluid'> <div class='span2'> <img alt="Avatar" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/missing/thumb/xavatar.png.pagespeed.ic.qjczMghcsC.jpg" style="float:left;margin-right:10px;" src="oiplitreendatwyv.gif"/> </div> <div class='span10'> <a href="index.html">home</a> <div class='author' itemprop='creator'>medo</div> <div class='created_at'><time datetime="2012-11-09T02:10:23-05:00" itemprop="commentTime"><p><a href="http://www.facebook.com/Zara" target="new">ZARA | Facebook</a><div>ZARA. 15886109 likes &middot; 109872 talking about this. . ZARA is on Facebook. To connect with ZARA, sign up for Facebook today. Sign UpLog In &middot; Cover Photo .</div><span>http://www.facebook.com/Zara</span></p></time></div> </div> </div> </div> <div class='alert alert-message error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='comment_body'> <div class='content'> <p itemprop='commentText'><EMAIL></p> </div> </div> <div class='form-actions'> </div> <div class='reply_holder'> </div> </div> </div> </div> </div> </div> </div> <div class='span4' id='sidebar' itemscope itemtype='http://schema.org/WPSideBar'> <div id='sidebar_rectangle' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="193.html">ynuproon hub</a></h4> <div class='clearfix' itemscope itemtype='http://schema.org/Person'> <a href="333.html" itemprop="image"><img alt="<NAME>" class="pull-left" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-nude.jpg.pagespeed.ic.Yp5z6xqFnh.jpg" style="margin-right:10px;" src="itridyotwiboocay.gif"/></a><p><a href="http://jobsearch.monster.com/puerto-rico+zara-usa_16" target="new">Jobs &amp; Careers at Zara Usa in Puerto Rico</a><div>Jobs at Zara Usa in Puerto Rico matched your search. . Get Results only for: Puerto Rico | zara usa. Your search has been saved. Send Me Jobs. We&#39;ll keep .</div><span>http://jobsearch.monster.com/puerto-rico+zara-usa_16</span></p><dl> <dt>Born</dt> <dd itemprop='birthDate'><time datetime="1971-09-08T00:00:00+00:00">September 08, 1971</time></dd> <dt>Full Name</dt> <dd itemprop='name'>zara cover letter Burke</dd> </dl> </div> </div> <div class='widget'> <h4><a href="41.html">xarelto and medicare</a></h4> <ul class='nav'> <li> <a href="152.html" class="clearfix"><img alt="Brooke Burke Prepares For Cancer Surgery" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" style="margin:0 10px 0 0;float:left;" src="yohtepeeqy.gif"/> zara cover letter Burke Prepares For Cancer Surgery </a></li> <li> <a href="61.html" class="clearfix"><img alt="Brooke Burke Has Thyroid Cancer" class="span3" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/thumb/brooke-burke-charvet-cancer-me.jpg" style="margin:0 10px 0 0;float:left;" src="gawyasuv.gif"/> zara cover letter Burke Has Thyroid Cancer </a></li> <li> <a href="196.html" class="clearfix"><img alt="Brooke Burke Charvet Releases New Lingerie Line" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" style="margin:0 10px 0 0;float:left;" src="kourtoujendoaple.gif"/> zara cover letter Burke Charvet Releases New Lingerie Line </a></li> </ul> </div> <div id='skyscraper' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="260.html">youtube bideos xxx de chicas birjenes</a></h4> <ul class='thumbnails'> <li class='span4'> <a href="209.html" class="thumbnail"><img alt="Brooke Burke, Cancer Treatment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" src="utayploji.gif"/> </a></li> <li class='span4'> <a href="382.html" class="thumbnail"><img alt="Brooke Burke-Charvet Photo" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-charvet-photo.jpg.pagespeed.ic.eZcSwfCk1Z.jpg" src="treiwhoxu.gif"/> </a></li> <li class='span4'> <a href="247.html" class="thumbnail"><img alt="Brooke Burke Lingerie Line" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" src="wyalegualaf.gif"/> </a></li> <li class='span4'> <a href="6.html" class="thumbnail"><img alt="<NAME> and <NAME>" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-and-david-charvet.jpg.pagespeed.ic.iLiOSmNBgG.jpg" src="thywayhtyoch.gif"/> </a></li> <li class='span4'> <a href="343.html" class="thumbnail"><img alt="<NAME>" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-and-tom.jpg.pagespeed.ic.OfTSSeJdAZ.jpg" src="yokaywhyodooliwy.gif"/> </a></li> <li class='span4'> <a href="374.html" class="thumbnail"><img alt="The Naked Mom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/the-naked-mom.jpg.pagespeed.ce.2HxOs_fRpY.jpg" src="ooxoukynuakeyfoi.gif"/> </a></li> </ul> </div> <div class='widget'> <h4>Blog Archives</h4> <ul class='nav'> <li><a href="77.html">xlola vika forum</a></li> <li><a href="344.html">yovodude.tumblr.com</a></li> <li><a href="306.html">youtube porn hud caliente</a></li> <li><a href="272.html">youtube connie stevens topless</a></li> <li><a href="190.html">yisela avendano free sex videos</a></li> <li><a href="190.html">yisela avendano free sex videos</a></li> <li><a href="339.html">yovodude</a></li> <li><a href="90.html">xoskeleton home office</a></li> </ul> </div> </div> </div> <div id='footer' itemscope itemtype='http://schema.org/WPFooter'> <div class='remove_padding'> <div id='footer_leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> </div> <p><p><a href="http://www.careerjet.co.uk/zara-jobs/south-east-england-70.html" target="new">zara jobs in South East England | careerjet.co.uk</a><div>Details of the offer, requirements, job functions - Stores - United Kingdom - Zara - Berkshire - Deputy Manager Menswear (maternity cover...) - Our ZARA Deputy .</div><span>http://www.careerjet.co.uk/zara-jobs/south-east-england-70.html</span></p></p> <p> <a href="404.html">zen bracelets for luck money</a> | <a href="346.html">yroll.theworknumber.com/allegis</a> | <a href="297.html">youtube mujeres mejicanas cojiendo</a> | <a href="143.html">xxxnina de 12 ano</a> </p> <p>&copy; 2013 The Hollywood Gossip - Celebrity Gossip and Entertainment News</p> <p><a href="386.html" rel="nofollow"><img alt="Sheknows-entertainment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xsheknows-entertainment-0dfb1ed120378c4d8a98720390d31272.png.pagespeed.ic.841FJHTKbK.png" src="xerxozheethrey.gif"/></a></p> </div> </div> <img height="1" width="1" pagespeed_lazy_src="http://tags.bluekai.com/site/3113" alt="" src="rtuagoutrewhoizu.gif"/> </div> </body> </html> <file_sep><!DOCTYPE html> <html id='en' lang='en'> <head> <title>youtube fake nudes lee newton</title> <link href="ssoistoineypoagh.css" media="screen" rel="stylesheet" type="text/css"/> <link href="oopeinyroon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon"/> <link href="ouzeelouhtootw.jpg" rel='apple-touch-icon' sizes='144x144'> <link href="eytreyhoisefoaht.jpg" rel='apple-touch-icon' sizes='114x114'> <link href="ndyajeyssepuatr.jpg" rel='apple-touch-icon' sizes='72x72'> <link href="eychoopyatya.jpg" rel='apple-touch-icon'> <script type='text/javascript' src='eyzeywyazuneyhi.js'></script></head> <body itemscope itemtype='http://schema.org/WebPage'> <div id='header'> <div class='social visible-desktop'> <ul> <li class='twitter'><a href="68.html"><NAME></a></li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com' data-size='medium'></div> </li> <li class='facebook'> <div class='fb-like' data-href='http://www.facebook.com/thehollywoodgossip' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> </ul> </div> <div id='banner'> <a href="14.html"><img alt="The Hollywood Gossip" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xheader-7629f5d243c1cdc904bf535b05ff849f.jpg.pagespeed.ic.CDQOMwZhbJ.jpg" src="stawhaghoix.gif"/></a> </div> <div class='sites visible-desktop'> <a href="84.html">xnxxanna nicole smith fucking</a> | <a href="238.html">young lolita nude</a> | <a href="415.html">zig zag cornrows</a> </div> <div class='login visible-desktop'> <a href="213.html">yougotposted.com</a> &nbsp;|&nbsp; <a href="377.html">zander identify theft vs. lifelock</a> </div> </div> <div id='wrapper'> <div class='remove_padding'> <div id='leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='navbar' itemscope itemtype='http://schema.org/WPHeader'> <div class='navbar-inner'> <div class='container-fluid'> <a href="126.html">xxx dormidas para movil</a> <div class='nav-collapse'> <ul class='nav'> <li class=''><a href="276.html">youtube deeann donovan</a></li> <li class=''><a href="278.html">youtube descuido de faldas</a></li> <li class=''><a href="286.html">you tube imagenes de she mails follando</a></li> <li class=''><a href="60.html">xbox live error 80151011</a></li> <li class=''><a href="188.html">yiff dominant female</a></li> <li class=''><a href="180.html">yaqui guerrido descuido</a></li> <li class=''><a href="84.html">xnxxanna nicole smith fucking</a></li> <li class=''><a href="188.html">yiff dominant female</a></li> <li class='login hidden-desktop'><a href="147.html">xxx pickers danielle tattoos</a></li> <li class='login hidden-desktop'><a href="43.html">xarelto coupons with insurance coverage</a></li> </ul> <form action="http://www.thehollywoodgossip.com/search" class='navbar-form pull-right'> <input class="input-medium" id="q" name="q" placeholder="Search" type="search"/> <button class="btn" type="submit"></button> </form> </div> </div> </div> </div> </div> <div class='container-fluid'> <div class='row-fluid'> <div class='span8' id='content'> <ul class="breadcrumb" itemprop="breadcrumb"><li><a href="51.html">xbox 360 voice changer headset</a> /</li> <li><a href="384.html">zara cover letter</a> /</li> <li><a href="257.html">youth extra large ayton fleece hooded jacket coat yxl hoody reviews</a> /</li> <li><p><a href="http://bleacherreport.com/articles/925894-the-50-biggest-wags-of-2011" target="new">The 50 Biggest WAGs of 2011 | Bleacher Report</a><div>Nov 7, 2011 . <NAME>: <NAME> . It is fake and worse than a soap opera. All they do is continue to repeat . She might not be a porn star, but she is good enough to increase Shockey&#39;s reputation level nowadays. . Go check out her Youtube videos and judge for yourself. . <NAME>: <NAME> .</div><span>http://bleacherreport.com/articles/925894-the-50-biggest-wags-of-2011</span></p></li></ul> <div class='video' itemscope itemtype='http://schema.org/VideoObject'> <div class='page-header'> <h1><p><a href="http://www.facebook.com/MessyMoo14" target="new"><NAME> | Facebook</a><div>Join Facebook to connect with <NAME> and others you may know. Facebook gives people the power to share and makes the world more open and .</div><span>http://www.facebook.com/MessyMoo14</span></p></h1> </div> <ul id='sharebar'> <li> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='box_count' data-send='false' data-show-faces='false' data-width='60'></div> </li> <li class='pinit'><a href="263.html" class="pin-it-button" count-layout="vertical" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="sterroizheizerth.gif"/></a></li> <li> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='tall'></div> </li> <li> <a href="286.html">you tube imagenes de she mails follando</a> </li> <li class='comments'> <div class='count comment_count'>1</div> <a href="index.html">home</a> </li> </ul> <div class='sharebarx' style="display:none;"> <ul> <li class='facebook'> <div class='fb-like' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-layout='button_count' data-send='false' data-show-faces='false' data-width='55'></div> </li> <li class='google'> <div class='g-plusone' data-href='http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/' data-size='medium'></div> </li> <li class='twitter'> <a href="373.html">zach nichols naked tumbler</a> </li> <li class='pinterest'><a href="119.html" class="pin-it-button" count-layout="horizontal" rel="nofollow"><img alt="Pinext" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.pinterest.com/images/PinExt.png.pagespeed.ce.q9J-vNQxkn.png" src="eevuassyaqundee.gif"/></a></li> <li class='comments'> <a href="406.html">zendaya coleman nude fakes</a> 1 </li> </ul> </div> <div class='thumbnail'> <div style="max-width:640px;max-height:459px;margin:0 auto;"> <img src="http://i.cocoperez.com/wp-content/uploads/2012/03/jessica-simpson-pregnant-elle-magazine-april-2012-cover__oPt.jpg" width="640" height="459" /> </div> <div class='caption' itemprop='description'><p><a href="http://rantsthoughtsmerde.com/2012/08/24/josh-hutcherson-nsfw-self-nude-bathroom-photo/" target="new"><NAME>: NSFW Self Nude Bathroom Photo &laquo; NativeNYker&#39;s ...</a><div>Aug 24, 2012 . So it&#39;s little surprise that a &#147;leaked&#148; self-nude photo of the young . video on youtube and it doesn&#39;t look fake. everyone takes nude pics this one .</div><span>http://rantsthoughtsmerde.com/2012/08/24/josh-hutcherson-nsfw-self-nude-bathroom-photo/</span></p></div> <div class='rating-form' id='rating_7611' itemprop='aggregateRating' itemscope itemtype='http://schema.org/AggregateRating'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='inline-rating'><ul class="star-rating"><li class="current-rating" style="width:100%;">5.0 / 5.0</li><li><a href="405.html">zendaya actully naked</a></li> <li><a href="351.html">yugo car company</a></li> <li><a href="199.html">yolanda on ghetto gaggers full video</a></li> <li><a href="247.html">youngstown mafia history</a></li> <li><a href="142.html">xxx negro teen anal sex with girls</a></li></ul></div> <br><p><a href="http://www.maxim.com/hot-100/update-the-most-popular-hot-100-write-ins-of-2012" target="new">UPDATE: The Most Popular &#39;Hot 100&#39; Write-Ins of 2012 | Maxim</a><div>Apr 2, 2012 . <NAME> Photo courtesy of YouTube | Licensed to Alpha Media Group 2012. It&#39;s no surprise that the host of YouTube show SourceFed has a .</div><span>http://www.maxim.com/hot-100/update-the-most-popular-hot-100-write-ins-of-2012</span></p></div> </div> <br> <ul class='pager'> <li class='next'> <a href="38.html">x3love.com</a> </li> </ul> Related Videos: <ul class='thumbnails'> <li class='span4'> <a href="273.html" class="thumbnail"><img alt="Brooke Burke Interview" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/medium_l/brooke-burke-interview.jpg" src="yssusarternotr.gif"/> <div class='caption'>youtube fake nudes lee newton Burke Interview</div> </a></li> </ul> <div class="remove_padding"><div id="content_rectangle" itemscope itemtype="http://schema.org/WPAdBlock"> </div></div> Embed Code: <pre class='embed'><p><a href="http://article.wn.com/view/2012/10/30/Mila_Kunis_I_like_childish_men/" target="new">Mila Kunis: I like childish men - Worldnews.com</a><div>Oct 30, 2012 . For more Hollywood news and gossip: www.youtube.com Subscribe at: . Digital Spy Demi Moore is allegedly upset after seeing half-naked photos of her . The only problem with not having an account is that there are fake accounts, . updates: bit.ly Remember to &quot;Write In&quot; Vote for Lee Newton to be on .</div><span>http://article.wn.com/view/2012/10/30/Mila_Kunis_I_like_childish_men/</span></p> <p><a href="http://www.dlisted.com/2012/05/30/kathie-lee-gifford-consummate-journalist" target="new"><NAME> Is A Consummate Journalist | Dlisted</a><div>May 30, 2012 . There are many reasons why I love absolute mess <NAME> . in her fake &quot;30 Love&quot; Foot Spray commercial (the shit is on YouTube).</div><span>http://www.dlisted.com/2012/05/30/kathie-lee-gifford-consummate-journalist</span></p></pre> <dl class='dl-horizontal'> <dt>Star:</dt> <dd> <a href="218.html">you got posted/tiff banister</a> </dd> <dt>Related Videos:</dt> <dd><a href="219.html">you got posted tiff bannister</a></dd> <dt>Original Post:</dt> <dd itemprop='associatedArticle'><a href="95.html">xvideo.combermudo</a></dd> <dt>Uploaded by:</dt> <dd><a href="59.html">xbox live codes</a></dd> <dt>Uploaded:</dt> <dd><time datetime="2012-11-08T00:00:00+00:00" itemprop="uploadDate">November 08, 2012</time></dd> <dt>Duration:</dt> <dd> <time datetime='PT3M9S' itemprop='duration'>189 seconds</time> </dd> </dl> <hr> <div id='comments'> <h3> Comments (1 Total) <a href="364.html">yu tube videos cachondos de jenni rivera</a> </h3> <a href="411.html">zeta amicae song</a> <div id='new_comment'> <form accept-charset="UTF-8" action="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/comments/" class="simple_form form-horizontal" data-remote="true" id="new_comment" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;"/><input name="authenticity_token" type="hidden" value="<KEY>></div> <div class='body'> <div class='alert alert-error error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <input name='page' type='hidden'> <input id="comment_parent_id" name="comment[parent_id]" type="hidden"/> <br> <p><p><a href="http://www.dlisted.com/2012/09/13/finally-proof-kristen-stewart-cheating-scandal-was-all-just-publicity-stunt" target="new">FINALLY! Proof That The Kristen Stewart Cheating Scandal Was All ...</a><div>Sep 13, 2012 . But what doesn&#39;t make sense to me is why would they fake the photos? . * waves*. http://www.youtube.com/watch?v=cN9jTnxv0RU .</div><span>http://www.dlisted.com/2012/09/13/finally-proof-kristen-stewart-cheating-scandal-was-all-just-publicity-stunt</span></p></p> <div class='row-fluid'> <div class='span8'> <div class="control-group string optional"><label class="string optional control-label" for="comment_anon_name">Name</label><div class="controls"><input class="string optional" id="comment_anon_name" name="comment[anon_name]" size="50" type="text"/><p class="help-block">Your name will appear with your comment</p></div></div> <div class="control-group email optional"><label class="email optional control-label" for="comment_anon_email">Email</label><div class="controls"><input class="string email optional" id="comment_anon_email" name="comment[anon_email]" size="50" type="email"/><p class="help-block"><p><a href="http://www.huffingtonpost.com/2011/12/19/beautiful-women-over-50_n_1154571.html" target="new">50 Women Over 50 Who Have Aged Gracefully (PHOTOS)</a><div>Dec 19, 2011 . 20 Most Beautiful Women Over 50 - YouTube . given truthful facts and findings instead of feeding the masses this fake story. . like <NAME> , <NAME>, <NAME> and <NAME> Curtis Now they have aged gracefully....... NOT LIke Cher,<NAME> , <NAME> and <NAME> !</div><span>http://www.huffingtonpost.com/2011/12/19/beautiful-women-over-50_n_1154571.html</span></p></p></div></div> </div> <div class='span4 providers'> <a href="69.html">xerex kwentong kalibugan</a> <br> <a href="380.html">zanx</a> <br> <a href="88.html">xnxx penelope menchaca desnuda</a> <br> </div> </div> <div class="control-group text optional"><label class="text optional control-label" for="comment_content">Content</label><div class="controls"><textarea class="text optional" cols="40" id="comment_content" name="comment[content]" rows="20" style="width:320px;height:80px"> </textarea></div></div> </div> <div class='form-actions'> <input class='btn cancel' href="http://www.thehollywoodgossip.com/videos/brooke-burke-charvet-cancer-me/#" style="display:none;" type='button' value='Cancel'> <input class="btn btn btn-primary" data-disable-with="Adding..." name="commit" type="submit" value="Add Comment"/> <br style="clear:both;"> </div> </form> </div> <div class='row-fluid'> <div class='span12'> <div class='comment' data-content='<EMAIL>' id='comment_403462' itemid='403462' itemprop='comment' itemscope itemtype='http://schema.org/UserComments'> <div class='comment_meta'> <div class='row-fluid'> <div class='span2'> <img alt="Avatar" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/missing/thumb/xavatar.png.pagespeed.ic.qjczMghcsC.jpg" style="float:left;margin-right:10px;" src="oiplitreendatwyv.gif"/> </div> <div class='span10'> <a href="395.html">zastava pap 92 to buy</a> <div class='author' itemprop='creator'>medo</div> <div class='created_at'><time datetime="2012-11-09T02:10:23-05:00" itemprop="commentTime"><p><a href="http://www.dlisted.com/2012/10/17/hot-slut-day" target="new">Hot Slut Of The Day! | Dlisted</a><div>Oct 17, 2012 . Forget my words, I&#39;ll let the YouTube comments speak for themselves. Yes . but obviously she finds the time to create dozens of fake YouTube .</div><span>http://www.dlisted.com/2012/10/17/hot-slut-day</span></p></time></div> </div> </div> </div> <div class='alert alert-message error' style="display:none;margin:10px;"></div> <div class='alert alert-success success' style="display:none;margin:10px;"></div> <div class='comment_body'> <div class='content'> <p itemprop='commentText'><EMAIL></p> </div> </div> <div class='form-actions'> </div> <div class='reply_holder'> </div> </div> </div> </div> </div> </div> </div> <div class='span4' id='sidebar' itemscope itemtype='http://schema.org/WPSideBar'> <div id='sidebar_rectangle' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="301.html">youtubenephew tommy prank call to financial secretary</a></h4> <div class='clearfix' itemscope itemtype='http://schema.org/Person'> <a href="6.html" itemprop="image"><img alt="<NAME>" class="pull-left" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-nude.jpg.pagespeed.ic.Yp5z6xqFnh.jpg" style="margin-right:10px;" src="itridyotwiboocay.gif"/></a><p><a href="http://www.maxim.com/hot-100/2012-hot-100" target="new">2012 Hot 100 | Maxim</a><div>Click here to see <NAME>&#39;s video. SEE THE FULL . killer in Scream 4, and this year she&#39;ll be hanging out in a porn shop in Adult World. Stay away from .</div><span>http://www.maxim.com/hot-100/2012-hot-100</span></p><dl> <dt>Born</dt> <dd itemprop='birthDate'><time datetime="1971-09-08T00:00:00+00:00">September 08, 1971</time></dd> <dt>Full Name</dt> <dd itemprop='name'>youtube fake nudes <NAME></dd> </dl> </div> </div> <div class='widget'> <h4><a href="167.html">xyooj aviaries</a></h4> <ul class='nav'> <li> <a href="296.html" class="clearfix"><img alt="Brooke Burke Prepares For Cancer Surgery" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" style="margin:0 10px 0 0;float:left;" src="yohtepeeqy.gif"/> youtube fake nudes lee newton Burke Prepares For Cancer Surgery </a></li> <li> <a href="293.html" class="clearfix"><img alt="Brooke Burke Has Thyroid Cancer" class="span3" pagespeed_lazy_src="http://assets.thehollywoodgossip.com/videos/thumb/brooke-burke-charvet-cancer-me.jpg" style="margin:0 10px 0 0;float:left;" src="gawyasuv.gif"/> youtube fake nudes lee newton Burke Has Thyroid Cancer </a></li> <li> <a href="49.html" class="clearfix"><img alt="Brooke Burke Charvet Releases New Lingerie Line" class="span3" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" style="margin:0 10px 0 0;float:left;" src="kourtoujendoaple.gif"/> youtube fake nudes lee newton Burke Charvet Releases New Lingerie Line </a></li> </ul> </div> <div id='skyscraper' itemscope itemtype='http://schema.org/WPAdBlock'></div> <div class='widget'> <h4><a href="136.html">xxx jaguar artwork</a></h4> <ul class='thumbnails'> <li class='span4'> <a href="381.html" class="thumbnail"><img alt="Brooke Burke, Cancer Treatment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-cancer-treatment.jpg.pagespeed.ic.xdoCKQKita.jpg" src="utayploji.gif"/> </a></li> <li class='span4'> <a href="224.html" class="thumbnail"><img alt="Brooke Burke-Charvet Photo" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-charvet-photo.jpg.pagespeed.ic.eZcSwfCk1Z.jpg" src="treiwhoxu.gif"/> </a></li> <li class='span4'> <a href="98.html" class="thumbnail"><img alt="Bro<NAME>ke Lingerie Line" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/brooke-burke-lingerie-line.jpg.pagespeed.ce.12sI5eMS44.jpg" src="wyalegualaf.gif"/> </a></li> <li class='span4'> <a href="206.html" class="thumbnail"><img alt="<NAME> and <NAME>" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-burke-and-david-charvet.jpg.pagespeed.ic.iLiOSmNBgG.jpg" src="thywayhtyoch.gif"/> </a></li> <li class='span4'> <a href="268.html" class="thumbnail"><img alt="<NAME>" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/xbrooke-and-tom.jpg.pagespeed.ic.OfTSSeJdAZ.jpg" src="yokaywhyodooliwy.gif"/> </a></li> <li class='span4'> <a href="47.html" class="thumbnail"><img alt="The Naked Mom" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/photos/thumb/the-naked-mom.jpg.pagespeed.ce.2HxOs_fRpY.jpg" src="ooxoukynuakeyfoi.gif"/> </a></li> </ul> </div> <div class='widget'> <h4>Blog Archives</h4> <ul class='nav'> <li><a href="223.html">youjiiz para telefonos nokia 201</a></li> <li><a href="75.html">ximena duque nude</a></li> <li><a href="336.html">youvebeenposted naked pictures annonymous</a></li> <li><a href="296.html">youtubemujeres enseñando tanga</a></li> <li><a href="387.html">zara sale delhi 2012</a></li> <li><a href="220.html">yougotposted video</a></li> <li><a href="381.html">zara 666 opening</a></li> <li><a href="84.html">xnxxanna nicole smith fucking</a></li> </ul> </div> </div> </div> <div id='footer' itemscope itemtype='http://schema.org/WPFooter'> <div class='remove_padding'> <div id='footer_leaderboard' itemscope itemtype='http://schema.org/WPAdBlock'></div> </div> <p><p><a href="http://wiki.answers.com/Q/What_are_some_goth_poser_or_fake_goth_bands" target="new">What are some goth poser or fake goth bands</a><div>Gothic posers misconstrue the bands music as being Gothic Rock because Amy Lee herself is a Victorian Goth. Amy Lee may be a Victorian Goth but a person&#39;s .</div><span>http://wiki.answers.com/Q/What_are_some_goth_poser_or_fake_goth_bands</span></p></p> <p> <a href="305.html">youtube pleyboy <NAME></a> | <a href="322.html">youtube video caseros calientes</a> | <a href="243.html">young nude jail bait girls models</a> | <a href="57.html">xbox error code 80151011 fix</a> </p> <p>&copy; 2013 The Hollywood Gossip - Celebrity Gossip and Entertainment News</p> <p><a href="34.html" rel="nofollow"><img alt="Sheknows-entertainment" pagespeed_lazy_src="http://1-ps.googleusercontent.com/x/www.thehollywoodgossip.com/assets.thehollywoodgossip.com/assets/xsheknows-entertainment-0dfb1ed120378c4d8a98720390d31272.png.pagespeed.ic.841FJHTKbK.png" src="xerxozheethrey.gif"/></a></p> </div> </div> <img height="1" width="1" pagespeed_lazy_src="http://tags.bluekai.com/site/3113" alt="" src="rtuagoutrewhoizu.gif"/> </div> </body> </html>
fc34eafd370c9054e5d1a22479899a8a684ec1e1
[ "Markdown", "Go", "HTML" ]
37
HTML
dahufileguco/dahufileguco.github.com
a7249fdbe1b8b3921ce90ab5ea605492f02b8485
8e8a6ceb702a35ee60f15d2e8076835ea247903e
refs/heads/master
<repo_name>GOKULNAIR94/VIKIv2<file_sep>/index.js module.exports = function( username, loginEncoded, req, res ) { const express = require('express'); const bodyParser = require('body-parser'); const restService = express(); var http = require('https'); var fs = require('fs'); var intentName = req.body.result.metadata.intentName; console.log( "intentName : " + intentName ); try{ http.get("https://vikinews.herokuapp.com"); http.get("https://vikiviki.herokuapp.com"); http.get("https://salty-tor-67194.herokuapp.com"); http.get("https://opty.herokuapp.com"); if( intentName == "Default Welcome Intent") { speech = "Hi " + username + "! My name is VIKI (Virtual Interactive Kinetic Intelligence) and I am here to help!"; return res.json({ speech: speech, displayText: speech }) } } catch(e) { console.log( "Error : " + e ); } var content; var speech = ''; var varHost = ''; var varPath = ''; console.log( "intentName : " + intentName); try { if( intentName == 'News' || intentName == 'News - link' ){ varHost = 'vikinews.herokuapp.com'; varPath = '/inputmsg'; } if( intentName == 'Budget' || intentName == 'Expense' ){ varHost = 'vikiviki.herokuapp.com'; varPath = '/inputmsg'; } if( intentName == 'reporting' ){ varHost = 'salty-tor-67194.herokuapp.com'; varPath = '/report'; } if( intentName == 'oppty' || intentName=='oppty - next' || intentName=='oppty - custom' || intentName=='oppty - News' ){ //varHost = 'polar-sea-99105.herokuapp.com'; varHost = 'opty.herokuapp.com'; varPath = '/oppty'; } console.log( "varHost : " + varHost ); console.log( "varPath : " + varPath); req.body["loginEncoded"] = loginEncoded; var newoptions = { host: varHost, path: varPath, data: req.body, method:'POST', headers: { 'Content-Type': 'application/json' } }; var body = ""; var responseObject; var post_req = http.request(newoptions, function(response) { response.on('data', function (chunk) { body += chunk; }); response.on('end', function() { //console.log( "Body -: " + body ); try { responseObject = JSON.parse(body); if( typeof responseObject.speech != "object") speech = responseObject.speech; else speech = responseObject.speech.speech; return res.json({ speech: speech, displayText: speech }) } catch(e){ speech = "Error occured!"; return res.json({ speech: speech, displayText: speech }) } }) }).on('error', function(e){ speech = "Error occured!"; return res.json({ speech: speech, displayText: speech }) }); post_req.write(JSON.stringify(req.body)); post_req.end(); } catch(e) { console.log("Error : " + e ); } }<file_sep>/loginOSC.js module.exports = function(req, res) { const express = require('express'); const bodyParser = require('body-parser'); const restService = express(); var http = require('https'); var fs = require('fs'); var sessionId = req.body.sessionId; console.log("sessionId : " + sessionId); var content; content = fs.readFileSync('login.json', 'utf8'); console.log("Content : " + content); content = JSON.parse(content); console.log("Login Intent"); var username = req.body.result.contexts[0].parameters['username.original']; var password = "<PASSWORD>"; // req.body.result.contexts[0].parameters['password.original']; var http = require('https'); options = { host: 'acs.crm.ap2.oraclecloud.com', path: "/crmCommonApi/resources/latest/accounts", headers: { 'Authorization': 'Basic ' + new Buffer(username + ':' + password).toString('base64') } }; var responseString = ''; var request = http.get(options, function(resx) { resx.on('data', function(data) { responseString += data; }); resx.on('end', function() { try{ console.log("Ecryt start"); var CryptoJS = require("crypto-js"); var loginEncoded = 'Basic ' + new Buffer(username + ':' + password).toString('base64'); var ciphertext = CryptoJS.AES.encrypt( loginEncoded, sessionId ); var resObj = JSON.parse(responseString); var jsonMap = { "ciphertext" : "" + ciphertext + "", "username" : username } content.items.OSC[sessionId] = jsonMap; console.log("Content :" + JSON.stringify(content) ); content = JSON.stringify( content, null, 2); fs.writeFile('login.json', content, function(){ speech = "Thank you " + username + "! You are logged in! What can I do for you?"; return res.json({ speech: speech, displayText: speech }) }); } catch(error){ speech = "Log in error! Make sure Credentials are correct!"; console.log( "Error : " + error); return res.json({ speech: speech, displayText: speech //source: 'webhook-OSC-oppty' }) } }); resx.on('error', function(e) { console.log("Got error: " + e.message); }); }); }<file_sep>/server.js 'use strict'; const express = require('express'); const bodyParser = require('body-parser'); const restService = express(); var http = require('https'); var fs = require('fs'); restService.use(bodyParser.urlencoded({ extended: true })); restService.use(bodyParser.json()); var Index = require("./index"); var Login = require("./loginOSC"); restService.post('/inputmsg', function(req, res) { var speech; var sessionId = req.body.sessionId; console.log("sessionId : " + sessionId); var content; content = fs.readFileSync('login.json', 'utf8'); console.log("Content : " + content); content = JSON.parse(content); console.log("Content :" + JSON.stringify(content.items)); var intentName = req.body.result.metadata.intentName; console.log("intentName : " + intentName); if (content.items.OSC[sessionId] != null) { var CryptoJS = require("crypto-js"); var username = content.items.OSC[sessionId].username; var ciphertext = content.items.OSC[sessionId].ciphertext; var bytes = CryptoJS.AES.decrypt( ciphertext.toString(), sessionId ); var loginEncoded = bytes.toString(CryptoJS.enc.Utf8); console.log("loginEncoded : " + loginEncoded ); Index( username, loginEncoded, req, res, function( result ) { console.log("Index Called"); }); } else { if (req.body.result.metadata.intentName == "Login") { console.log("Login Intent"); // var username = req.body.result.parameters['username']; // var password = req.body.result.parameters['password']; Login(req, res, function(result) { console.log("Login Called"); }); } else { if (intentName == "Default Welcome Intent") { speech = "Hi There! My name is VIKI (Virtual Interactive Kinetic Intelligence) and I am here to help! Please Login. Try saying: I am Gokul and password is <PASSWORD>"; } else { speech = "Hi There! Soory I missed that! Please login!"; } return res.json({ speech: speech, displayText: speech }) } // speech = "I will need your Sales Cloud Credentials. Try saying: I am Gokul and password is <PASSWORD>"; // return res.json({ // speech: speech, // displayText: speech // }) } }); restService.listen((process.env.PORT || 9000), function() { console.log("Server up and listening"); });
f649066784c0b19aee58b4f466b02e85c80089ba
[ "JavaScript" ]
3
JavaScript
GOKULNAIR94/VIKIv2
9bceccc1e4d6bb9f2fd8d90875f7f2f2d1318d81
1db86bc7480618e0196a7bda50746a90e0c6cd7d
refs/heads/master
<file_sep>#!/bin/bash cd /home/forge/go/src/github.com/michaeljoyner/octobot /home/forge/go/bin/octobot<file_sep>package main import ( "encoding/json" "io/ioutil" "log" "net/http" ) type MessengerEvent struct { Object string `json:"object"` Entry []EventEntry `json:"entry"` } type EventEntry struct { PageID string `json:"id"` Time int `json:"time"` Envelope []Envelope `json:"messaging"` } type Envelope struct { Sender Sender `json:"sender"` Recipient Recipient `json:"recipient"` Time int `json:"timestamp` Message Message `json:"message"` } type Sender struct { PSID string `json:"id"` } type Recipient struct { PageId string `json:"id"` } type Message struct { ID string `json:"mid"` Text string `json:"text"` } func main() { http.HandleFunc("/webhook", handler) log.Fatal(http.ListenAndServe(":8888", nil)) } func handler(w http.ResponseWriter, r *http.Request) { if r.Method == "GET" { handleGet(w, r) } if r.Method == "POST" { handlePost(r) } } func handleGet(w http.ResponseWriter, r *http.Request) { log.Println("getting it") verifyToken := "<PASSWORD>" query := r.URL.Query() token := query.Get("hub.verify_token") mode := query.Get("hub.mode") challenge := query.Get("hub.challenge") if mode == "subscribe" && token == verifyToken { w.Write([]byte(challenge)) } else { http.Error(w, "wicked beasty, thou shalt not pass", http.StatusForbidden) } } func handlePost(r *http.Request) { body, err := ioutil.ReadAll(r.Body) if err != nil { log.Fatal(err) } defer r.Body.Close() event := MessengerEvent{} err = json.Unmarshal(body, &event) if err != nil { log.Fatal(err) } log.Println(event.Entry[0].Envelope[0].Message.Text) }
fdc5b08333c04ce3fced5fd8edf1517f6ffcd30b
[ "Go", "Shell" ]
2
Shell
michaeljoyner/octobot
a04baec747131e9c8149b9a278363732d0de016f
f017711fdf2fa2066befa358133a75779b19c746
refs/heads/master
<file_sep>package skeyetech.xml_hero; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import android.widget.Toast; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.ExecutionException; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Check network connection final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo(); if (activeNetwork != null && activeNetwork.isConnected()) { // Device is connected try { // Set URL to XML file URL source = new URL("http://articlefeeds.nasdaq.com/nasdaq/symbols?symbol=GOOGL"); try { // Instantiate XML_loader LoadXML XML_Loader = new LoadXML(); // Load XML, then the XML document returned by loader Document XML_Doc = XML_Loader.execute(source).get(); // Make sure the XML doc is not null if(XML_Doc != null) { // Create a node list of all the items, or article, contained in the XML NodeList nodes = XML_Doc.getElementsByTagName("item"); // Loop through the node list, and retrieve the title of each item for (int i = 0; i < nodes.getLength(); i++) { Element element = (Element) nodes.item(i); NodeList title = element.getElementsByTagName("title"); // Push the title of each item to the UI with a TextView TextView titleView = (TextView) findViewById(R.id.title); titleView.setText(titleView.getText() + "\n \n" + title.item(0).getTextContent()); } } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } catch (MalformedURLException e) { e.printStackTrace(); } } else { // device is not connected to the internet, create a message to alert the user Toast.makeText(this, "No Internet Connection", Toast.LENGTH_LONG).show(); } } } <file_sep>package skeyetech.xml_hero; import android.os.AsyncTask; import org.w3c.dom.Document; import java.net.HttpURLConnection; import java.net.URL; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; // Start a new thread to move the network operations off the UI thread public class LoadXML extends AsyncTask <URL, Void, Document>{ @Override protected Document doInBackground(URL...url) { try { // Open network connection URL myURL = url[0]; HttpURLConnection conn = (HttpURLConnection) myURL.openConnection(); conn.connect(); // Build an XML Document by parsing the connection input stream DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(conn.getInputStream()); // Return the XML document back to the UI thread return doc; } catch (Exception e) { e.printStackTrace(); return null; } } }
a1b83d7be93ffd0eca3e03405c1306c76c45ac43
[ "Java" ]
2
Java
skeyetech/XML-HERO
fc1d272892197c9d69e1f27e940130f5ec8b835f
8333c882be49c3f212930cfdb4efbb9ff99c2324
refs/heads/master
<file_sep>package model; /** * This is the member class for creating objects of the type member. * Created by <NAME> 01-10-2015 */ public class Member { private String name1; private String name2; private String mid; private String pnr; private int nBoats; /* * Constructor for the member object. */ public Member(String firstName, String lastName, String memberID, String personalNumber, int numberOfBoats) { this.name1 = firstName; this.name2 = lastName; this.pnr = personalNumber; this.mid = memberID ; this.nBoats = numberOfBoats; } public Member() {} /** * Getters and setters for the member object parameters. */ public void setMemberFirstName(String firstName) { this.name1 = firstName; } public void setMemberLastName(String lastName) { this.name2 = lastName; } public void setMemberPersonalNumber(String pn) { this.pnr = pn; } public void setMemberID(String memID) { this.mid = memID; } public void setMemberNBoats(int nBoats) { this.nBoats = nBoats; } public String getMemberFirstName() { return this.name1; } public String getMemberLastName() { return this.name2; } public String getMemberPersonalNumber() { return this.pnr; } public String getMemberID() { return this.mid; } public int getMemberNBoats() { return this.nBoats; } } <file_sep>package model; import java.sql.SQLException; /** * Created by Daniel on 2015-10-22. */ public class MemberModel { /** * Method for storing in database. * @param newMember * @return */ public void saveMember(Member newMember) { SQLDAO.saveMember(newMember); } public void changeMember(Member mem) { try { SQLDAO.updateMember(mem); } catch(ClassNotFoundException | SQLException | InstantiationException | IllegalAccessException e){ System.out.println("Database connection error."); e.printStackTrace(); } } public void deleteMember(String id) { try { SQLDAO.deleteMember(id); } catch(ClassNotFoundException | SQLException | InstantiationException | IllegalAccessException e){ System.out.println("Database connection error."); e.printStackTrace(); } } } <file_sep>package view; import controller.Controller; import java.util.Scanner; /** * Created by Daniel on 2015-10-22. */ public class MainView { public void displayHeader() { System.out.println("====================================================="); //Header for program. System.out.println("Enter any of the commands to do various things."); System.out.println("Cmd: 'addmember' = add new member"); System.out.println("Cmd: 'editmember' = edit member"); System.out.println("Cmd: 'deletemember' = delete member"); System.out.println("Cmd: 'findmember' = look up a member"); System.out.println("Cmd: 'showallmembers' = show all members"); System.out.println("Cmd: 'addboat' = add new boat"); System.out.println("Cmd: 'editboat' = edit boat data"); System.out.println("Cmd: 'deleteboat' = delete boat"); System.out.println("Cmd: 'exit' = exit program"); } public String getInput() { Scanner sc = new Scanner(System.in); String entry = sc.nextLine(); return entry; } public void printMember(String n1, String n2, String ID, String pnr, int nBoats) { System.out.println("==========Member data=========="); System.out.println("Member first name: " + n1); System.out.println("Member last name: " + n2); System.out.println("Member ID: " + ID); System.out.println("Member personal number: " + pnr); System.out.println("Member number of boats: " + nBoats); } public void printMemberBoatLine(String id) { System.out.println("==========" + id + "boats=========="); } public void printCompactMember(String n1, String n2, String ID, int nb) { System.out.println("==========Member data=========="); System.out.println("Member first name: " + n1); System.out.println("Member last name: " + n2); System.out.println("Member ID: " + ID); System.out.println("Member number of boats: " + nb); } public void printMemberBoats(String bn, String bt, int bl) { System.out.println(); System.out.println("======================="); System.out.println("Boat name: " + bn); System.out.println("Boat type: " + bt); System.out.println("Boat length: " + bl); System.out.println("======================="); } public String getMemID() { //Called so the user can chose which member to access. System.out.println("Please enter the ID of the member you wish to access: "); String memID = getInput(); return memID; } public String getBoatName() { //called so the user can chose which boat to access. System.out.println("Please enter the name of the boat to be accessed: "); String boatName = getInput(); return boatName; } public boolean isVerbose(boolean verbose) { //Does the user want a verbose or compact list. System.out.println("Show compact or verbose member list?"); System.out.println("c = compact / v = verbose"); String choice = getInput(); if (choice.equals("v")) { verbose = true; return verbose; } else if (choice.equals("c")){ verbose = false; return verbose; } else { System.out.println("I'm terribly sorry, operator, but that doesn't answer my question."); return isVerbose(verbose); } } public void printMessages(String s) { //Method for printing proper and relevant error messages. if (s == "ab") { System.out.println("Boat added!"); } else if (s == "db") { System.out.println("Boat Deleted!"); } else if (s == "cb") { System.out.println("Boat data changed!"); } else if (s == "am") { System.out.println("Member Added!"); } else if (s == "dm") { System.out.println("Member Deleted!"); } else if (s == "cm") { System.out.println("Member data changed!"); } if (s == "nab") { System.out.println("Boat could not be added."); } else if (s == "ndb") { System.out.println("Boat could no be deleted."); } else if (s == "ncb") { System.out.println("Boat data could not be changed."); } else if (s == "nam") { System.out.println("Member could not be added."); } else if (s == "ndm") { System.out.println("Member could no be deleted."); } else if (s == "ncm") { System.out.println("Member data could not be changed."); } else if (s == "nmwi") { System.out.println("There is no member with that ID."); } else if (s == "mus") { System.out.println("Member data updated successfully!"); } else if (s == "nmf") { System.out.println("No such member found!"); } else if (s == "idiot") { System.out.println("Operator, there is no such command. The mental health service has been notified."); } else if (s == "emfn") { System.out.println("Enter the new member's first name: "); } else if (s == "emln") { System.out.println("Enter the new member's last name: "); } else if (s == "empnr") { System.out.println("Enter the new member's personal number: "); } else if (s == "cmfn") { System.out.println("Change member's first name to: "); } else if (s == "cmln") { System.out.println("Change member's last name to: "); } else if (s == "cmpnr") { System.out.println("Change member's personal number to: "); } else if (s == "sbn") { System.out.println("Set Boat Name"); } else if (s == "sbl") { System.out.println("Set Boat's Length"); } else if (s == "sbt") { System.out.println("Set Boat's Type"); } else if (s == "snbn") { System.out.println("Set a new Boat Name"); } else if (s == "snbl") { System.out.println("Set a new Boat Length"); } else if (s == "snbt") { System.out.println("Set a new Boat Type"); } } } <file_sep> DOWNLOAD LINK TO THE JAR FILE: http://www.filedropper.com/yachtclub MAKE SURE TO LAUNCH THE JAR FILE FROM TERMINAL IN ORDER FOR IT TO START. ALSO MAKE SURE TO INISTALL XAMPPP CONTROL PANEL V3 2.1 AND RUN THE APACHE AND MYSQL. SEQUENCE DIAGRAM ( FOR AN INPUT ): http://postimg.org/image/i9iq0q2it/ SEQUENCE DIAGRAM ( FOR AN OUTPUT ): http://postimg.org/image/j089edx69/ UML CLASS DIAGRAM: http://s000.tinyupload.com/index.php?file_id=93380147045367986862 IN ORDER FOR THE PROGRAM TO ACCESS THE DATABASE INCLUDE THIS FILE IN YOUR JAVA PROJECT FILES ( BY DOWNLOADING IT ): http://mvnrepository.com/artifact/mysql/mysql-connector-java/5.1.36 INSTRUCTIONS FOR SETTING UP XAMPP AND DATABASE FOR THE PROGRAM: http://s000.tinyupload.com/index.php?file_id=08083271586897792688 NOTE: If the jar file for some reason does not work on your system, clone the project code and run it on your personal java IDE. FOR TEACHER: Update: Here are the peer reviews, both the ones that we gave and the ones that we recived (updated 18 october since filedropper.com apperently does not hold on to youre files for more than 3 days). Recived: From Ola.F : http://s000.tinyupload.com/index.php?file_id=05940164786561571722 From Mauro.P : http://s000.tinyupload.com/index.php?file_id=25032793918468716111 Gave: To J.P: http://s000.tinyupload.com/index.php?file_id=46804233116681930751 To A.A: http://s000.tinyupload.com/index.php?file_id=02842134815775943250
96b181bc04f85d06939877c616de9f9af62c864e
[ "Markdown", "Java" ]
4
Java
DanielHammerin/YachtClub
45ea455c5ebb09ead97a0753d1168dd420de2f8f
31a3b4b4bf54b1674e225460fb711389c1133cfc
refs/heads/master
<repo_name>callmebill/Spottly<file_sep>/Spottly/SPYPhotoCell.swift // // SPYPhotoCell.swift // Spottly // // Created by HuangZhigang on 15/12/17. // Copyright © 2015年 Spottly. All rights reserved. // import Foundation import UIKit class SPYPhotoCell : UICollectionViewCell,ImagePresentAble { var imageView : UIImageView! override init(frame: CGRect) { super.init(frame: frame) setupImageView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { self.imageView.frame = self.bounds self.layer.borderColor = UIColor.blackColor().CGColor self.layer.borderWidth = 1.0 } } <file_sep>/Controller和View成对应组件仅负责展示.md *API* - 用户类 用户注册、登录、修改Profile、搜索、登出、注销等相关 - 用户关系类 关注,取消关注,好友关系查询、标记、取消标记 - 标签(用户)类 创建、修改、删除、获取 -- 前三个操作为管理员操作,后一个为普通用户 - 标签(城市)类 创建、修改、删除、获取、获取国家 -- 前三个操作为管理员操作,后两个为普通用户 - 标签(category)类 创建、修改、删除、获取、获取super-categories -- 前三个操作为管理员操作,后两个为普通用户 - 集合类 创建、修改、删除、查询、标记 -- 前四个操作为普通用户,后一个为管理员操作 - 地点类 查询、标记 -- 前一个操作为普通用户,后一个为管理员操作 - 笔记类 创建、修改、删除、查询、标记 -- 前四个操作为普通用户,后一个为管理员操作 - 通知类 发送、获取 -- 前一个操作为管理员操作,后一个为普通用户 - 杂项类 index **用户类** - 注册、登录 ***Request*** >Method: PUT >URI: /users >QueryParameters: >Headers: >Body: ``` {"token": "2.<PASSWORD>", "user-type": "sina|facebook|google", "platform": "iOS|web|Android", "platform-identity": "xyz", "platform-notification-token": "abc", "alt-ids": ["id0", "id1", ...]} ---or--- {"email": "<EMAIL>", "password": "<PASSWORD>", "user-type": "email", "platform": "iOS|web|Android", "platform-identity": "xyz", "platform-notification-token": "abc", "alt-ids": ["id0", "id1", ...]} ---or--- {"uid": "123", "password": "<PASSWORD>", "user-type": "password", "platform": "iOS|web|Android", "platform-identity": "xyz", "platform-notification-token": "abc", "alt-ids": ["id0", "id1", ...]} ``` ***Response*** >StatusLine: standard-HTTP >Headers: Set-Cookie: sessionId=sqw42fsfg24xzfw >Body: ``` { "meta": { "code": 200, "text": "Ok" }, "data": { "user": { "collections": { "count": 12 }, "ct": "2013-11-19T09:15:59Z", "description": "4209053857", "followers": { "count": 22 }, "following-collections": { "count": 52 }, "followings": { "count": 149 }, "head": "/uploader/5417de9cdf4e63373500aaf8.jpeg", "id": "95551582372079", "likes": { "count": 136 }, "location": "", "mt": "2015-10-15T07:30:51Z", "name": "charlottlechen", "notifications": { "count": 0 }, "platform": "iOS", "platform-identity": "xyz", "platform-notification-token": "abc", "posts": { "count": 0 }, "ref-id": "2094142662", "site": "http://spottly.com/CallmeBill和 v、", "tags": { "count": 1, "data-type": "tag", "relation": [ { "id": "95553450934276", "user-id": "95551582372079", "tag-id": "95553450934272", "ct": "2014-02-13T04:49:22Z" } ], "relation-type": "user-tag-map", "slice": [ { "id": "95553450934272", "name": "active-user", "type": "System" } ] }, "token": "", "uid": "CallmeBill", "uid-ignore-case": "callmebill", "user-type": "sina" } } } ``` - 登出 ***Request*** >Method: DELETE >URI: /sessions/me >QueryParameters: >Headers: Cookie: sessionId=...... >Body: ***Response*** >StatusLine: standard-HTTP >Headers: >Body: - 注销 ***Request*** >Method: DELETE >URI: /users/me >QueryParameters: >Headers: Cookie: sessionId=...... >Body: ***Response*** >StatusLine: standard-HTTP >Headers: >Body: - 修改Profile ***Request*** >Method: PATCH >URI: /users/me >QueryParameters: >Headers: Cookie: sessionId=...... >Body: ``` {"the-field-will-changed": "new-value", ...} ``` ***Response*** >StatusLine: standard-HTTP >Headers: >Body: - 搜索用户 ***Request*** >Method: GET >URI: /users >QueryParameters:filter={conditions}&count=n >Headers: Cookie: sessionId=...... >Body: 注:{conditions}为JSON格式的过滤条件,有两种形式:{"name": "value"}和{"name": {"op": "compareOperator", "value": "value"}}。采用UTF-8编码的Unicode字符集。过滤条件用URLEncoding编码。 ***Response*** >StatusLine: standard-HTTP >Headers: >Body: **用户关系类** - 关注 ***Request*** >Method: POST >URI: /friends >QueryParameters: >Headers: Cookie: sessionId=...... >Body: ``` {"to-id": "followed-user-id"} ``` 注:{conditions}为JSON格式的过滤条件,有两种形式:{"name": "value"}和{"name": {"op": "compareOperator", "value": "value"}}。采用UTF-8编码的Unicode字符集。过滤条件用URLEncoding编码。 ***Response*** >StatusLine: standard-HTTP >Headers: >Body: ``` {"meta": {"code": nnn, "text": "...."}, "data": {"id": "followed-id", "from-id": "self-id", "to-id": ".."}} ``` - 取消关注 ***Request*** >Method: DELETE >URI: /friends/{followed-id} >QueryParameters: >Headers: Cookie: sessionId=...... >Body: 注:{followed-id}为关注某人时返回的id。 ***Response*** >StatusLine: standard-HTTP >Headers: >Body: ``` {"id": "followed-id", "from-id": "self-id", "to-id": ".."} ``` - 好友关系查询 ***Request*** >Method: GET >URI: /users/me/followings /users/me/followers >QueryParameters: >Headers: Cookie: sessionId=...... >Body: 注:其中的me可以改变为某用户的id,表明获取该用户的followings或者followers ***Response*** >StatusLine: standard-HTTP >Headers: >Body: ``` {"meta": {"code": nnn, "text": "...."}, "data": {"count": xx, "users": [following or follower user info], "friends": [{"id": "followed-id", "from-id": "self-id", "to-id": ".."}, ...]} ``` - 标记 ***Request*** >Method: PUT >URI: /users/me/tags >QueryParameters: >Headers: Cookie: sessionId=...... >Body: ``` {"tag-id": "tag's id"} ``` ***Response*** >StatusLine: standard-HTTP >Headers: >Body: - 取消标记 ***Request*** >Method: DELETE >URI: /users/me/tags/{tag-id} >QueryParameters: >Headers: Cookie: sessionId=...... >Body: ***Response*** >StatusLine: standard-HTTP >Headers: >Body: **标签(用户)类** - 创建 - 修改 - 删除 - 获取 ***Request*** >Method: GET >URI: /tags >QueryParameters: >Headers: Cookie: sessionId=...... >Body: ***Response*** >StatusLine: standard-HTTP >Headers: >Body: ``` {"meta": {"code": nnn, "text": "...."}, "data": [all user tag]} ``` **标签(城市)类** - 创建 - 修改 - 删除 - 获取 ***Request*** >Method: GET >URI: /cities >QueryParameters: >Headers: Cookie: sessionId=...... >Body: ***Response*** >StatusLine: standard-HTTP >Headers: >Body: ``` {"meta": {"code": nnn, "text": "...."}, "data": [all cities]} ``` - 获取国家 ***Request*** >Method: GET >URI: /cities/counties >QueryParameters: >Headers: Cookie: sessionId=...... >Body: ***Response*** >StatusLine: standard-HTTP >Headers: >Body: ``` {"meta": {"code": nnn, "text": "...."}, "data": [all counties]} ``` **标签(category)类** - 创建 - 修改 - 删除 - 获取 ***Request*** >Method: GET >URI: /categories >QueryParameters: >Headers: Cookie: sessionId=...... >Body: ***Response*** >StatusLine: standard-HTTP >Headers: >Body: ``` {"meta": {"code": nnn, "text": "...."}, "data": [all categories]} ``` - 获取super-categories ***Request*** >Method: GET >URI: /categories/supers >QueryParameters: >Headers: Cookie: sessionId=...... >Body: ***Response*** >StatusLine: standard-HTTP >Headers: >Body: ``` {"meta": {"code": nnn, "text": "...."}, "data": [all super categories]} ``` **集合类** - 创建 ***Request*** >Method: POST >URI: /collections >QueryParameters: >Headers: Cookie: sessionId=...... >Body: ``` {"name": "collection-name", "description": "desc"} ``` ***Response*** >StatusLine: standard-HTTP >Headers: >Body: ``` {"meta": {"code": nnn, "text": "...."}, "data": {collection-info}} ``` - 修改 ***Request*** >Method: PATCH >URI: /collections/{collection-id} >QueryParameters: >Headers: Cookie: sessionId=...... >Body: ``` {"name": "new-collection-name", "description": "new-desc"} ``` ***Response*** >StatusLine: standard-HTTP >Headers: >Body: ``` {"meta": {"code": nnn, "text": "...."}, "data": {collection-info}} ``` - 删除 ***Request*** >Method: DELETE >URI: /collections/{collection-id} >QueryParameters: >Headers: Cookie: sessionId=...... >Body: ***Response*** >StatusLine: standard-HTTP >Headers: >Body: ``` {"meta": {"code": nnn, "text": "...."}} ``` - 标记 **地点类** - 查询 ***Request*** >Method: GET >URI: /places?filter={conditions}&count=n >QueryParameters: >Headers: Cookie: sessionId=...... >Body: ***Response*** >StatusLine: standard-HTTP >Headers: >Body: ``` {"meta": {"code": nnn, "text": "...."}, "data": [place that match conditions]} ``` - 标记 **笔记类** - 创建 ***Request*** >Method: POST >URI: /posts >QueryParameters: >Headers: Cookie: sessionId=...... >Body: ``` {"place": {place-info}, "collection-id": "...", "client-id": "...", "message": "...", "medias": [{image-or-video info}, ...]} ---or--- {"from-id": "from post id"} ``` ***Response*** >StatusLine: standard-HTTP >Headers: >Body: ``` {"meta": {"code": nnn, "text": "...."}, "data": {the notes info}} ``` - 修改 ***Request*** >Method: PATCH >URI: /posts/{post-id} >QueryParameters: >Headers: Cookie: sessionId=...... >Body: ``` {"place": {place-info}, "collection-id": "...", "client-id": "...", "message": "...", "medias": [{image-or-video info}, ...]} ``` ***Response*** >StatusLine: standard-HTTP >Headers: >Body: ``` {"meta": {"code": nnn, "text": "...."}, "data": {the notes info}} ``` - 删除 ***Request*** >Method: DELETE >URI: /posts/{post-id} >QueryParameters: >Headers: Cookie: sessionId=...... >Body: ***Response*** >StatusLine: standard-HTTP >Headers: >Body: ``` {"meta": {"code": nnn, "text": "...."}} ``` - 查询 ***Request*** >Method: GET >URI: /posts?filter={conditions}&count=n >QueryParameters: >Headers: Cookie: sessionId=...... >Body: ***Response*** >StatusLine: standard-HTTP >Headers: >Body: ``` {"meta": {"code": nnn, "text": "...."}, "data": [the post match by conditions]} ``` - 标记 **通知类** - 发送 - 获取 ***Request*** >Method: GET >URI: /notifications?filter={conditions} >QueryParameters: >Headers: Cookie: sessionId=...... >Body: 注:{conditions}是{is_read: true|false},或者干脆就没有filter参数 ***Response*** >StatusLine: standard-HTTP >Headers: >Body: ``` {"meta": {"code": nnn, "text": "...."}, "data": [the notification match by conditions]} ``` **杂项类** - index ***Request*** >Method: GET >URI: /index >QueryParameters: >Headers: Cookie: sessionId=...... >Body: ***Response*** >StatusLine: standard-HTTP >Headers: >Body: ``` {api description} ``` <file_sep>/Spottly/SPYCollectionCellModel.swift // // SPYCollectionCellModel.swift // Spottly // // Created by HuangZhigang on 16/3/24. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation struct SPYCollectionCellModel { let collection : Collection var postsFRC: SPYFetchedResultsController init(collection:Collection){ self.collection = collection print("self.collection.posts :\(collection.posts?.count)") self.postsFRC = SPYFetchedResultsController(fetchRequest: self.collection.threePostsFR()) } }<file_sep>/Spottly/SPYExploreCategoreViewParallaxHeader.swift // // SPYExploreCategorieViewParallaxHeader.swift // Spottly // // Created by HuangZhigang on 16/5/11. // Copyright © 2016年 Spottly. All rights reserved. // // // SPYExploreViewParallaxHeader.swift // Spottly // // Created by HuangZhigang on 16/4/26. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import RxSwift class SPYExploreCategorieViewParallaxHeader: UICollectionReusableView { let disposeBag = DisposeBag() let imageView = UIImageView().then{ $0.backgroundColor = UIColor.whiteColor() $0.contentMode = .ScaleAspectFill $0.clipsToBounds = true } let city = UILabel().then{ $0.font = UIFont.spyHelveticaNeueBold(42) $0.textAlignment = .Center $0.textColor = UIColor.whiteColor() $0.backgroundColor = UIColor.clearColor() } let categore = UILabel().then{ $0.font = UIFont.spyHelveticaNeueBold(42) $0.textAlignment = .Center $0.textColor = UIColor.whiteColor() $0.backgroundColor = UIColor.clearColor() } override init(frame: CGRect) { super.init(frame: frame) self.frame = CGRect(x: 0, y: 0, width: 375, height: 200) self.setupSubviews() self.clipsToBounds = false self.backgroundColor = UIColor.yellowColor() } override func layoutSubviews() { super.layoutSubviews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupSubviews() { let centerView = UIView() centerView.addSubview(city) centerView.addSubview(categore) imageView.addSubview(centerView) self.addSubview(imageView) constrain(self,imageView,centerView){ box, bg , center in bg.size == box.size bg.center == box.center center.centerX == bg.centerX center.centerY == bg.centerY+15 } constrain(centerView,city,categore){ box, city,cate in city.top == box.top city.left == box.left city.right == box.right city.bottom == cate.top + 5 cate.left == box.left cate.right == box.right cate.bottom == box.bottom } self.setNeedsLayout() self.layoutIfNeeded() } func configureCell(viewModel:SPYExploreHeaderViewModel) { let categorie = viewModel.mainCategory as! Categorie imageView.kf_setImageWithURL(NSURL(string:categorie.image!)!) city.text = categorie.cityName categore.text = categorie.name // if viewModel.mainCategory is Categorie // { // }else{ // // } } } <file_sep>/Spottly/SPYVideoRangeEditerView.swift // // SPYVideoEditerView.swift // Spottly // // Created by HuangZhigang on 16/4/28. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import UIKit import CoreLocation import imglyKit class SPYVideoRangeEditerView: UIViewController { //MARK: Life Ciclye init(asset:AVAsset){ self.asset = asset super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() configureNavBar() configureViewHierarchy() configureViewConstraints() self.view.backgroundColor = UIColor.blackColor() } func configureNavBar() { self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "Check"), style: .Plain, target: self, action: #selector(SPYVideoRangeEditerView.nextAction)) self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "BackWhite"), style: UIBarButtonItemStyle.Plain, target: self, action: #selector(SPYVideoRangeEditerView.backAction)) self.navigationItem.title = "Edit Video" self.navigationController?.navigationBar.tintColor = UIColor.whiteColor() } private func configureViewHierarchy() { cameraPreView.addSubview(rangeSlider) self.view.addSubview(cameraPreView) bottom.addSubview(okButton) self.view.addSubview(bottom) } private func configureViewConstraints() { constrain( self.view , cameraPreView ,bottom ) { box, camera,bottom in camera.top == box.top + 64 camera.height == box.width camera.width == box.width camera.centerX == box.centerX distribute(by: 0, vertically: camera, bottom) bottom.width == box.width bottom.bottom == box.bottom } constrain(bottom,okButton){ box,ok in ok.height == 82 ok.width == 82 ok.center == box.center } constrain(cameraPreView,rangeSlider){ box,range in range.size == box.size range.center == box.center } } //MARK: Action func backAction(){ self.navigationController?.popViewControllerAnimated(true); } func nextAction() { okAction() } func okAction() { let converter = MCVideoConverter(asset: self.asset) let start = CMTimeMakeWithSeconds(self.startTime, asset.duration.timescale); let duration = CMTimeMakeWithSeconds(self.endTime - self.startTime, asset.duration.timescale); let range = CMTimeRangeMake(start, duration); converter.timeRange = range; converter.location = nil converter.startProgressSheetWithURL(self.tmpVideoPath) { if converter.success { let c = SPYVideoChooseCoverView(videoURL: self.tmpVideoPath) self.navigationController?.pushViewController(c, animated: true) }else{ showAlert("Converter Failure") } } } //MARK: property var cameraPreView = UIView() var bottom = UIView() lazy var tmpVideoPath : NSURL = { let str = NSTemporaryDirectory().stringByAppendingString("tempVideo.mp4") return NSURL(fileURLWithPath: str) }() let asset: AVAsset lazy var rangeSlider : SAVideoRangeSlider = { let rangeSlider = SAVideoRangeSlider(asset: self.asset) rangeSlider.delegate = self; let duration = CMTimeGetSeconds(self.asset.duration) if(duration > 15.0){ rangeSlider.minGap = 3.0; rangeSlider.maxGap = 15.0; }else{ if (duration < 3.0) { rangeSlider.minGap = 0.0; }else{ rangeSlider.minGap = 3.0; } rangeSlider.maxGap = duration; } return rangeSlider }() lazy var okButton : UIButton = { let btn = UIButton() btn.setImage(UIImage(named: "selectedCover"),forState:UIControlState.Normal) btn.addTarget(self, action: #selector(SPYVideoRangeEditerView.okAction), forControlEvents: UIControlEvents.TouchUpInside) return btn }() var location : CLLocation? lazy var startTime = NSTimeInterval(0) lazy var endTime : NSTimeInterval = { return CMTimeGetSeconds(self.asset.duration) }() } extension SPYVideoRangeEditerView: SAVideoRangeSliderDelegate{ func videoRange(videoRange: SAVideoRangeSlider!, didChangeLeftPosition leftPosition: CGFloat, rightPosition: CGFloat) { self.startTime = NSTimeInterval(leftPosition) self.endTime = NSTimeInterval(rightPosition) } func videoRange(videoRange: SAVideoRangeSlider!, didGestureStateEndedLeftPosition leftPosition: CGFloat, rightPosition: CGFloat) { self.startTime = NSTimeInterval(leftPosition) self.endTime = NSTimeInterval(rightPosition) } } <file_sep>/Spottly/SPYCollectionTitleCell.swift // // SPYCollectionTitleCell.swift // Spottly // // Created by HuangZhigang on 16/2/21. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import UIKit class SPYCollectionTitleCell : UICollectionViewCell { var label: UILabel! override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.whiteColor() self.label = UILabel().then{ $0.backgroundColor = UIColor.clearColor() $0.textColor = UIColor.spyTextColor() $0.font = UIFont.spyAvenirNextMedium(12) $0.textAlignment = .Center } self.addSubview(self.label) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { self.label.frame = self.bounds } } <file_sep>/Spottly/SPYExploreViewParallaxHeader.swift // // SPYExploreViewParallaxHeader.swift // Spottly // // Created by HuangZhigang on 16/4/26. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import RxSwift class SPYExploreViewParallaxHeader: UICollectionReusableView { let disposeBag = DisposeBag() let imageView = UIImageView().then{ $0.backgroundColor = UIColor.whiteColor() $0.contentMode = .ScaleAspectFill $0.clipsToBounds = true //TODO: 怎么把 ScaleAspectFill 和 Bottom 合并 } // let searchBall = UIImageView().then{ // $0.backgroundColor = UIColor.spyBlueColor() // $0.image = UIImage(named: "SearchIcon") // $0.contentMode = .Center // $0.layer.cornerRadius = 50/2 // $0.clipsToBounds = true // } let cityName = UILabel().then{ $0.font = UIFont.spyHelveticaNeueBold(80) $0.textColor = UIColor.whiteColor() $0.adjustsFontSizeToFitWidth = true $0.textAlignment = .Center $0.backgroundColor = UIColor.clearColor() } let hello = UILabel().then{ $0.font = UIFont.spyHelveticaNeueRegular(22) $0.textColor = UIColor.whiteColor() $0.textAlignment = .Center $0.backgroundColor = UIColor.clearColor() } let goTrip1 = UILabel().then{ $0.font = UIFont.spyHelveticaNeueRegular(14) $0.textColor = UIColor.whiteColor() $0.textAlignment = .Center $0.backgroundColor = UIColor.clearColor() } let goTrip2 = UILabel().then{ $0.font = UIFont.spyHelveticaNeueRegular(14) $0.textColor = UIColor.whiteColor() $0.textAlignment = .Center $0.backgroundColor = UIColor.clearColor() } var cityView : UICollectionView! override init(frame: CGRect) { super.init(frame: frame) let layout = UICollectionViewFlowLayout() layout.scrollDirection = .Horizontal layout.itemSize = CGSize(width: 75,height: 75) layout.sectionInset = UIEdgeInsetsMake(0, 12, 0, 12) cityView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout) cityView.backgroundColor = UIColor.whiteColor() cityView.showsHorizontalScrollIndicator = false cityView.registerClass(SPYCityCell.self, forCellWithReuseIdentifier: "SPYCityCell") self.frame = CGRect(x: 0, y: 0, width: 375, height: 400) self.setupSubviews() self.clipsToBounds = false self.backgroundColor = UIColor.yellowColor() } override func layoutSubviews() { super.layoutSubviews() // print("SPYExploreViewParallaxHeader : \(self.frame)") // imageView.frame = self.bounds // imageView.top -= 64 // imageView.height += 64 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupSubviews() { let suggestLine = UILabel().then{ $0.text = "SUGGESTED CITIES" $0.backgroundColor = UIColor.whiteColor() $0.textAlignment = .Center $0.font = UIFont.spyAvenirNextMedium(10) $0.textColor = UIColor.spyGrayColor() } let popularLine = UILabel().then{ $0.text = "POPULAR" $0.backgroundColor = UIColor.whiteColor() $0.textAlignment = .Center $0.font = UIFont.spyAvenirNextMedium(10) $0.textColor = UIColor.spyGrayColor() } self.addSubviews(imageView,suggestLine,cityView,popularLine) constrain(imageView,suggestLine,cityView,popularLine){ image,suggest,citys,popular in let box = image.superview! image.top == box.top distribute(by: 0, vertically:image,suggest,citys,popular) align(right:box,image,suggest,citys,popular) align(left:box,image,suggest,citys,popular) image.height == 300 citys.height == 75 suggest.height == 40 popular.height == 40 popular.bottom == box.bottom } imageView.addSubviews(cityName,hello,goTrip1,goTrip2) constrain(imageView,cityName,hello,goTrip1,goTrip2){ box ,city,hello,trip1,trip2 in city.center == box.center city.width <= box.width - 40 trip2.left == box.left trip2.right == box.right trip2.bottom == box.bottom - 10 trip2.top == trip1.bottom trip1.top == hello.bottom align(left: hello,trip1,trip2) align(right: hello,trip1,trip2) } self.setNeedsLayout() self.layoutIfNeeded() } func configureCell(viewModel:SPYExploreHeaderViewModel) { let mainCategory = viewModel.mainCategory let userName = SPYUserViewModel.shareMe.input?.name ?? "" if mainCategory is String{ let region = mainCategory as! String //world self.hello.text = "Hello \(userName)" self.goTrip1.text = "Plan a trip anywhere in the world," self.goTrip2.text = "save your favorite places." self.imageView.image = UIImage(named:region ) }else if mainCategory is City { let city = (mainCategory as! City) self.imageView.kf_setImageWithURL(NSURL(string:city.image!)!) self.cityName.text = city.name! self.hello.text = "Hello \(userName)" self.goTrip1.text = "Plan a trip \(city.name!)," self.goTrip2.text = "save your favorite places." }else if mainCategory is NearbyItem { let nearby = mainCategory as! NearbyItem self.imageView.image = UIImage(named: "NearbyBig") self.cityName.text = "\(nearby.exploreName)" // self.goTrip1.text = "Plan a trip \(city.name)," // self.goTrip2.text = "save your favorite places." } viewModel.rx_category .drive(self.cityView.rx_itemsWithCellIdentifier("SPYCityCell", cellType: SPYCityCell.self)){ (_, category, cell: SPYCityCell) in switch category.exploreType { case .City , .Life: cell.imageView.kf_setImageWithURL(NSURL(string: category.exploreImageName)!) cell.label.text = category.exploreName case .Nearby: cell.imageView.image = UIImage(named: category.exploreImageName) cell.label.text = category.exploreName case .Search: cell.imageView.image = UIImage(named: category.exploreImageName) cell.label.text = "" } }.addDisposableTo(disposeBag) self.cityView.rx_modelSelected(ExploreCategory) .asDriver() .driveNext{ category -> Void in switch category.exploreType { case .City: let c = mainStoryboard().instantiateViewControllerWithIdentifier("SPYExploreView") as! SPYExploreView let placesURL = SPYRouter.City((category as! City).id!, .Places) .fullPath .orderBy(.Rating(.Desc)) let collectionsUrl = SPYRouter.City((category as! City).id!, .Collections) .fullPath .orderBy(.Rating(.Desc)) c.viewModel = SPYExploreViewModel(input: ( mainCategory:category , subCategory: categorys, menuItems:[SPYMenuAction.Place(.Hot),SPYMenuAction.Place(.Following),SPYMenuAction.Details,SPYMenuAction.Collection(.Hot)], placesUrl: placesURL, collectionsUrl: collectionsUrl)) SPYNavigationController().pushViewController(c, animated: true) case .Life: let c = SPYExploreCategoreView() if viewModel.mainCategory is City { let cityId = (viewModel.mainCategory as! City).id! let cityName = (viewModel.mainCategory as! City).name! let categoryId = (category as! Categorie).id! (category as! Categorie).cityName = cityName let placesURL = SPYRouter.City(cityId , .Places) .fullPath .filter([SPYFilter.CategoryId(categoryId)]) .orderBy(SPYOrder.Rating(.Desc)) c.viewModel = SPYExploreViewModel(input: ( mainCategory:category , subCategory: [], menuItems:[SPYMenuAction.Place(.Hot),SPYMenuAction.Place(.Following)], placesUrl: placesURL, collectionsUrl: "")) }else if viewModel.mainCategory is NearbyItem{ let categoriesID = (category as! Categorie).id! (category as! Categorie).cityName = "Nearby" guard let coordinate = GeolocationService.instance.locationValue else { showAlert("地理位置未能获取") return } let placesURL = SPYRouter.Category(categoriesID) .fullPath .filter([.Coordinate(coordinate)]) .orderBy(.Distance(.Asc)) c.viewModel = SPYExploreViewModel(input: ( mainCategory:category , subCategory: [], menuItems:[SPYMenuAction.Place(.Nearby),SPYMenuAction.Place(.Following)], placesUrl: placesURL, collectionsUrl: "")) } SPYNavigationController().pushViewController(c, animated: true) case .Nearby: let c = mainStoryboard().instantiateViewControllerWithIdentifier("SPYExploreView") as! SPYExploreView guard let coordinate = GeolocationService.instance.locationValue else { showAlert("地理位置未能获取") return } let placesURL = SPYRouter.NearBy(.Places) .fullPath .filter([.Coordinate(coordinate)]) .orderBy(.Distance(.Asc)) let collectionsUrl = SPYRouter.NearBy(.Collections) .fullPath .filter([.Coordinate(coordinate)]) .orderBy(.Distance(.Asc)) c.viewModel = SPYExploreViewModel(input: ( mainCategory:category , subCategory: categorys, menuItems:[SPYMenuAction.Place(.Hot),SPYMenuAction.Place(.Following),SPYMenuAction.Collection(.Hot)], placesUrl: placesURL, collectionsUrl: collectionsUrl)) SPYNavigationController().pushViewController(c, animated: true) case .Search: print("Search") } }.addDisposableTo(disposeBag) } } <file_sep>/Spottly/String+CoreData.swift // // String+CoreData.swift // SpottlyCoreData // // Created by HuangZhigang on 15/10/10. // Copyright © 2015年 Spottly. All rights reserved. // import Foundation extension String{ func dateSelector(ct:String) -> NSComparisonResult { return NSDate.spyParseRFC3339(self ).compare(NSDate.spyParseRFC3339(ct)) } } <file_sep>/Spottly/UIImageView+SD.swift // // UIImageView+SD.swift // Spottly // // Created by HuangZhigang on 16/4/12. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import SDWebImage let placeholderImage = UIImage(named: "gray"); extension UIImageView { func URL(str:String) { guard let url = NSURL(string:str) else{ showAlert("Image URL ERROR: \(str)") return } self.sd_setImageWithURL(url, placeholderImage:placeholderImage , options: SDWebImageOptions.ProgressiveDownload) } }<file_sep>/Spottly/SPYUserHeaderView.swift // // SPYUserHeaderView.swift // Spottly // // Created by HuangZhigang on 16/4/26. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import RxSwift class SPYUserHeaderView: UICollectionReusableView { let disposeBag = DisposeBag() private var headImage = UIImageView().then{ $0.layer.cornerRadius = 75.0/2.0 $0.clipsToBounds = true } private var followingsNum = UILabel().then{ $0.backgroundColor = UIColor.clearColor() $0.textAlignment = .Center $0.font = UIFont.spyAvenirNextDemiBold(20) $0.textColor = UIColor.spyTextColor() $0.text = "00" } private var followersNum = UILabel().then{ $0.backgroundColor = UIColor.clearColor() $0.font = UIFont.spyAvenirNextDemiBold(20) $0.textColor = UIColor.spyTextColor() $0.textAlignment = .Center $0.text = "00" } private var followingsBox = UIButton().then{ $0.backgroundColor = UIColor.clearColor() $0.layer.borderWidth = 1 $0.layer.borderColor = UIColor.clearColor().CGColor $0.layer.cornerRadius = 3 } private var followersBox = UIButton().then{ $0.backgroundColor = UIColor.clearColor() $0.layer.borderWidth = 1 $0.layer.borderColor = UIColor.clearColor().CGColor $0.layer.cornerRadius = 3 } private let following = UILabel().then{ $0.text = "following".uppercaseString $0.font = UIFont.spyAvenirNextRegular(12) $0.textColor = UIColor.spyTextColor() } private let follower = UILabel().then{ $0.text = "follower".uppercaseString $0.font = UIFont.spyAvenirNextRegular(12) $0.textColor = UIColor.spyTextColor() } private var realname = UILabel().then{ $0.backgroundColor = UIColor.whiteColor() $0.textAlignment = .Center $0.font = UIFont.spyAvenirNextRegular(14) $0.textColor = UIColor.spyTextColor() $0.numberOfLines = 1 } private var editBtn = UIButton().then{ $0.setTitle("Edit", forState: .Normal) $0.setTitleColor(UIColor.spyBlueColor(), forState: .Normal) $0.setTitleColor(UIColor.spyDisabledColor(), forState: .Disabled) $0.setTitleColor(UIColor.whiteColor(), forState: .Highlighted) $0.titleLabel!.font = UIFont.spyHelveticaNeueRegular(12) $0.backgroundColor = UIColor.clearColor() $0.layer.borderWidth = 1 $0.layer.borderColor = UIColor.spyBlueColor().CGColor $0.layer.cornerRadius = 3 } private var moreBtn = UIButton().then{ $0.setTitle("More", forState: .Normal) $0.setTitleColor(UIColor.spyBlueColor(), forState: .Normal) $0.setTitleColor(UIColor.spyDisabledColor(), forState: .Disabled) $0.setTitleColor(UIColor.whiteColor(), forState: .Highlighted) $0.titleLabel!.font = UIFont.spyHelveticaNeueRegular(12) $0.backgroundColor = UIColor.clearColor() $0.layer.borderWidth = 1 $0.layer.borderColor = UIColor.spyBlueColor().CGColor $0.layer.cornerRadius = 3 } private var bio = UILabel().then{ $0.backgroundColor = UIColor.whiteColor() $0.font = UIFont.spyAvenirNextMedium(12) $0.textColor = UIColor.spyTextColor() } private var site = UILabel().then{ $0.numberOfLines = 0 $0.text = "" $0.font = UIFont.spyAvenirNextMedium(12) $0.textColor = UIColor.spyTextColor() $0.textAlignment = .Center } override init(frame: CGRect) { super.init(frame: frame) self.setupSubviews() self.configureSubviews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var handlerAfterLayout : HandlerAfterLayout? func configureSubviews() { editBtn .rx_observe(Bool.self , "highlighted") .subscribeNext { [unowned self] (highlighted) -> Void in self.moreBtn.backgroundColor = highlighted! ? UIColor.spyBlueColor() : UIColor.clearColor() }.addDisposableTo(self.disposeBag) editBtn .rx_observe(Bool.self , "enabled") .subscribeNext { [unowned self] (enabled) -> Void in self.moreBtn.layer.borderColor = enabled! ? UIColor.spyBlueColor().CGColor : UIColor.spyDisabledColor().CGColor }.addDisposableTo(self.disposeBag) followingsBox.rx_tap.subscribeNext { }.addDisposableTo(self.disposeBag) followingsBox .rx_observe(Bool.self , "highlighted") .subscribeNext { [unowned self] (highlighted) -> Void in self.followingsBox.layer.borderColor = highlighted! ? UIColor.spyBlueColor().CGColor : UIColor.clearColor().CGColor }.addDisposableTo(self.disposeBag) followersBox .rx_observe(Bool.self , "highlighted") .subscribeNext { [unowned self] (highlighted) -> Void in self.followersBox.layer.borderColor = highlighted! ? UIColor.spyBlueColor().CGColor : UIColor.clearColor().CGColor }.addDisposableTo(self.disposeBag) followersBox.rx_tap.subscribeNext { }.addDisposableTo(self.disposeBag) } func setupSubviews() { let profile = UIView().then { $0.backgroundColor = UIColor.whiteColor() } self.backgroundColor = UIColor.whiteColor(); self.addSubview(profile) constrain(self,profile){box,profile in box.width == UIScreen.width profile.edges == inset(box.edges, 10,10,10,10) } let headBox = UIView() let btnBox = UIView() profile.addSubviews(headBox,realname,btnBox,bio,site) constrain(headBox,realname,btnBox,bio,site){head,name,btn,bio,site in let box = head.superview! head.top == box.top head.left == box.left head.width == box.width align(left: head,name,bio,site) align(right: head,name,bio,site) align(centerX: head,name,btn,bio,site) distribute(by: 10, vertically:head,name,btn,bio) bio.bottom == site.top - 2 site.bottom == box.bottom } btnBox.addSubviews(editBtn,moreBtn) constrain(editBtn,moreBtn){edit,more in let box = edit.superview! edit.top == box.top edit.left == box.left edit.bottom == box.bottom edit.right == more.left - 10 more.right == box.right edit.height == 30 edit.width == 90 edit.size == more.size align(centerY:box, edit, more) } headBox.addSubviews(followingsBox,headImage,followersBox) constrain(followingsBox,headImage,followersBox){following,head,followers in let box = head.superview! box.top == head.top box.bottom == head.bottom head.height == 75 head.width == 75 head.centerX == box.centerX align(centerY: following,head,followers) distribute(by: 25, horizontally: following,head,followers) } followingsBox.addSubviews(followingsNum,following) constrain(followingsNum,following){num , label in let box = num.superview! num.top == box.top num.left == box.left num.width == box.width align(left: num,label) align(right: num,label) distribute(by: -4, vertically:num,label) label.bottom == box.bottom } followersBox.addSubviews(followersNum,follower) constrain(followersNum,follower){num , label in let box = num.superview! num.top == box.top num.left == box.left num.width == box.width align(left: num,label) align(right: num,label) distribute(by: -4, vertically:num,label) label.bottom == box.bottom } self.setNeedsLayout() self.layoutIfNeeded() } func configureCell(viewModel:SPYUserHeaderViewModel) { viewModel.userFRC?.performFetchIfNeed.rxFetchedObjects .filter{ $0.count > 0 } .subscribeNext{ [unowned self] (fetchedObjects) -> Void in let user = fetchedObjects.first as! User self.headImage.setImageWithURL(NSURL(string:user.head!.sizeIs())!) self.realname.text = user.name! self.bio.text = user.bio ?? "" self.site.text = user.site ?? "" if let num = user.followingsCount?.integerValue{ self.followingsNum.text = String(num) } if let num = user.followersCount?.integerValue{ self.followersNum.text = String(num) } let size = self.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize); if let hand = self.handlerAfterLayout{ hand!(size) } }.addDisposableTo(self.disposeBag) } } <file_sep>/Spottly/UISearchBar+CancelButton.swift // // UISearchBar+CancelButton.swift // Spottly // // Created by HuangZhigang on 16/4/19. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation extension UISearchBar { func setCancelImage(image: UIImage) { _ = self.subviews[0].subviews.map { (view) -> Void in if view is UIButton { let btn = view as! UIButton btn.setImage(image, forState: UIControlState.Normal) btn.setImage(image, forState: UIControlState.Selected) btn.setImage(image, forState: UIControlState.Highlighted) btn.setTitle("", forState: UIControlState.Normal) btn.setTitle("", forState: UIControlState.Selected) btn.setTitle("", forState: UIControlState.Highlighted) btn.tintColor = UIColor.whiteColor() } } } }<file_sep>/Spottly/SPYFetchedResultsController.swift // // SPYFetchedResultsControllerDelegate.swift // SpottlyCoreData // // Created by HuangZhigang on 15/10/13. // Copyright © 2015年 Spottly. All rights reserved. // import Foundation import CoreData import Groot import Alamofire import RxCocoa import RxSwift import RxBlocking import SwiftyJSON let moreCount = 36 public class RxFetchedResultsControllerDelegateProxy : DelegateProxy , NSFetchedResultsControllerDelegate , DelegateProxyType { private var _fetchedObjectsSubject: ReplaySubject<[AnyObject]>? /** Typed parent object. */ public weak private(set) var controller: NSFetchedResultsController? /** Optimized version used for observing content offset changes. */ internal var fetchedObjectsSubject: Observable<[AnyObject]> { if _fetchedObjectsSubject == nil { let replaySubject = ReplaySubject<[AnyObject]>.create(bufferSize: 1) _fetchedObjectsSubject = replaySubject replaySubject.on(.Next(self.controller?.fetchedObjects ?? [])) } return _fetchedObjectsSubject! } /** Initializes `RxScrollViewDelegateProxy` - parameter parentObject: Parent object for delegate proxy. */ public required init(parentObject: AnyObject) { self.controller = (parentObject as! NSFetchedResultsController) super.init(parentObject: parentObject) } // MARK: delegate methods /** For more information take a look at `DelegateProxyType`. */ public func controllerDidChangeContent(controller: NSFetchedResultsController){ if let fetchedObjects = _fetchedObjectsSubject { if let nonNilFetchedObjects = controller.fetchedObjects{ fetchedObjects.on(.Next(nonNilFetchedObjects)) }else{ fetchedObjects.on(.Next([])) } } self._forwardToDelegate?.controllerDidChangeContent?(controller) } // MARK: delegate proxy /** For more information take a look at `DelegateProxyType`. */ public override class func createProxyForObject(object: AnyObject) -> AnyObject { let controller = (object as! NSFetchedResultsController) return controller.rx_createDelegateProxy() } /** For more information take a look at `DelegateProxyType`. */ public class func setCurrentDelegate(delegate: AnyObject?, toObject object: AnyObject) { let controller : NSFetchedResultsController = object as! NSFetchedResultsController controller.delegate = delegate as? NSFetchedResultsControllerDelegate // let collectionView: UIScrollView = castOrFatalError(object) // collectionView.delegate = castOptionalOrFatalError(delegate) } /** For more information take a look at `DelegateProxyType`. */ public class func currentDelegateFor(object: AnyObject) -> AnyObject? { let controller : NSFetchedResultsController = object as! NSFetchedResultsController return controller.delegate } deinit { if let fetchedObjects = _fetchedObjectsSubject { fetchedObjects.on(.Completed) } } } extension String { var type : String { if self.containsString("user"){ return "User" }else if self.containsString("post"){ return "Post" }else if self.containsString("collection"){ return "Collection" // }else if self.containsString("friend"){ // return "friend" // }else if self.containsString("comment"){ // return "comment" }else if self.containsString("place"){ return "Place" }else if self.containsString("cities"){ return "City" }else { return "" } } var isArray : Bool { return self.hasSuffix("s") } } extension NSFetchedResultsController { public var rx_delegate: DelegateProxy { return proxyForObject(RxFetchedResultsControllerDelegateProxy.self, self) } func rx_createDelegateProxy() -> RxFetchedResultsControllerDelegateProxy { return RxFetchedResultsControllerDelegateProxy(parentObject: self) } // public var rx_fetchedObjects: ControlEvent<[AnyObject]> { // let source = rx_delegate.observe("controllerDidChangeContent:") // .map { a -> [AnyObject] in // let controller = a[0] as! NSFetchedResultsController // guard let nonNilFetchedObjects = controller.fetchedObjects else // { // return [] // } // return nonNilFetchedObjects // } // // return ControlEvent(events: source) // } public var performFetch : NSFetchedResultsController { do { try self.performFetch() }catch { print("error \(error)") } return self } public var performFetchIfNeed : NSFetchedResultsController { if self.fetchedObjects == nil{ do { try self.performFetch() }catch { print("error \(error)") } } return self } public var rxFetchedObjects: ControlProperty<[AnyObject]> { let proxy = proxyForObject(RxFetchedResultsControllerDelegateProxy.self, self) return ControlProperty(values: proxy.fetchedObjectsSubject, valueSink: AnyObserver { event in }) } } enum RequestType { case Refresh case More } enum RequestState { case None case Loading case Completed(RequestType) case Error(Int) case Offline } extension String { var spyItemsType: String? { let nsString = self as NSString let wenhaoArray = nsString.componentsSeparatedByString("?") let xiegangArray = (wenhaoArray.first! as NSString).componentsSeparatedByString("/") let type = xiegangArray.last! if type.hasSuffix("s"){ return type }else{ return nil } } var removeCount: String { let nsString = self as NSString let offsetIndex = nsString.rangeOfString("offset") if offsetIndex.location != NSNotFound{ return nsString.substringToIndex(offsetIndex.location) }else{ return nsString as String } } } class SPYFetchedResultsController : NSFetchedResultsController,NSFetchedResultsControllerDelegate { var nextUrl: String? var sourceUrl: String? var rx_requestState = Variable(RequestState.None) convenience init(fetchRequest: SPYFetchRequest){ self.init(fetchRequest: fetchRequest, managedObjectContext: SPYMainMoc(), sectionNameKeyPath: nil, cacheName: nil) } func loadMore() { if let url = nextUrl{ requestUrl(url) } } func refresh() { guard let http = self.spyFetchRequest.httpInfo else{ return } var url = http["URL"] as! String if url.hasSuffix("s") || url.containsString("timeline"){//timeline和以s结尾 url = url + "?count=\(moreCount)" }else if url.containsString("s?")//请求集合类 { url = url + "&count=\(moreCount)" } // if url.containsString("?"){//自身有一些参数的情况 // url = url + "&count=\(moreCount)" // }else{//自身没有参数的情况 // url = url + "?count=\(moreCount)" // } // } self.sourceUrl = url self.requestUrl(sourceUrl!) } func parseNextURL(URL:NSURL,count:Int) -> String { var parameters = URL.queryItems if let offset = parameters?["offset"] { parameters?["offset"] = "\(Int(offset)! + count)" }else{ parameters?["offset"] = "\(count)" } let newURL = NSURL(scheme: URL.scheme, host: "staging.spottly.com:6666", path: URL.path!) if let query = parameters?.queryString{ let newString = newURL!.debugDescription + "?\(query)" return newString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! }else{ let newString = newURL!.debugDescription return newString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! } } func requestUrl(url:String) { rx_requestState.value = .Loading //这里可以优化下解析器 SPYLog().info("send url : \(url) frc:\(self)") Alamofire.request(.GET, url).response(queue: dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), responseSerializer: Request.JSONResponseSerializer(options: .AllowFragments), completionHandler: { response -> Void in switch response.result { case .Success: if let value = response.result.value { if let offset = response.request?.URL?.queryItems?["offset"] where offset != "0" { self.rx_requestState.value = .Completed(.More) }else{ self.rx_requestState.value = .Completed(.Refresh) } let json = JSON(value) if !response.response!.isSuccess{ self.rx_requestState.value = .Error(response.response!.statusCode) SPYLog().error("error : \(response.response!.statusCode) \(json["meta"]["text"].stringValue)") // showAlert("网络错误: \(response.response!.statusCode) \(json["meta"]["text"].stringValue)") return ; }else{ SPYLog().info("url : \(url) **** meta : \(json["meta"].dictionaryObject!) **** size \(response.data?.length) ***json[data]: \(json["data"])") if response.response!.isSuccess{ if json["data"] == nil{ // showAlert("服务器错误: 返回状态:\(response.response!.statusCode) 返回结果是:\(json["data"])") } } } let data = json["data"] if let type = response.request!.URL!.pathComponents?.last { if type.hasSuffix("s") { self.nextUrl = self.parseNextURL(response.request!.URL!,count: data[type].count) // SPYLog().info("self.nextUrl :\(self.nextUrl)") } } CoreDataManager.threadContext?.performBlock({ () -> Void in do{ for (key,subJson):(String, JSON) in data { guard key.type.characters.count != 0 else { continue } let managedObjects = try objectsWithEntityName(key.type, fromJSONArray: (key.isArray ? subJson.arrayObject! : [subJson.dictionaryObject as! AnyObject]) , inContext: CoreDataManager.threadContext!) // print("managedObjects : \(managedObjects.count)") var url = self.spyFetchRequest.httpInfo?["URL"] as! String url = url.removeCount if key.type == "Post" { //先存贮上等 退出app时 执行清除spot.relatedUrl _ = managedObjects.map{ (managedObject) -> Void in let spot = managedObject as! Post if !spot.relatedUrl.containsString(url){ spot.relatedUrl = spot.relatedUrl + "\(url) " } } } if key.type == "Collection" { //先存贮上等 退出app时 执行清除spot.relatedUrl _ = managedObjects.map{ (managedObject) -> Void in let collection = managedObject as! Collection if !collection.relatedUrl.containsString(url){ collection.relatedUrl = collection.relatedUrl + "\(url) " } } } if key.type == "Place" { //先存贮上等 退出app时 执行清除spot.relatedUrl _ = managedObjects.map{ (managedObject) -> Void in let place = managedObject as! Place if !place.relatedUrl.containsString(url){ place.relatedUrl = place.relatedUrl + "\(url) " } } } } CoreDataManager.threadContext?.saveOrLogError() }catch { fatalError("objectsWithEntityName \(error)") } }) } case .Failure(let error): self.rx_requestState.value = .Error(error.code) showAlert("网络错误:\(error)") SPYLog().error("error : \(error)") // self.rx_requestState.value = .Offline //huang // self.rx_requestState.value = .Error //huang } }) } override func performFetch() throws { try super.performFetch() refresh() } var spyFetchRequest : SPYFetchRequest { get{ return self.fetchRequest as! SPYFetchRequest } } var controllerDidChangeBlock : (() -> Void)? { didSet{ self.delegate = self if let request = self.fetchRequest as? SPYFetchRequest { request.errorHandleBlock = controllerDidChangeBlock //huang 内存循环引用!和SPYFetchRequest } } } func controllerDidChangeContent(controller: NSFetchedResultsController){ self.controllerDidChangeBlock?() } } <file_sep>/Spottly/SPYSiteCell.swift // // SPYSiteCell.swift // Spottly // // Created by HuangZhigang on 16/2/18. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import UIKit class SPYSiteCell : UICollectionViewCell { var title: UILabel! var detail: UILabel! override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.blackColor() self.title = UILabel().then{ $0.text = "title" $0.backgroundColor = UIColor.clearColor() $0.textColor = UIColor.whiteColor() $0.font = UIFont.spyHelveticaNeueRegular(22) } self.detail = UILabel().then{ $0.text = "detail" $0.backgroundColor = UIColor.clearColor() $0.textColor = UIColor.whiteColor() $0.numberOfLines = 0 $0.font = UIFont.spyAvenirNextRegular(14) } self.addSubviews(self.title,self.detail) constrain(self,self.title,self.detail){ box,title,detail in title.top == box.top + 8 title.left == box.left + 16 title.right == box.right - 16 detail.top == title.bottom detail.left == title.left detail.right == title.right detail.bottom == box.bottom - 8 } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() } func configureCell(place:PlaceStruct){ self.title.text = place.name self.detail.text = place.address } } <file_sep>/Spottly/SPYCreatPostView.swift // // SPYCreatPostView.swift // Spottly // // Created by HuangZhigang on 16/1/9. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import UIKit import RxSwift import Kingfisher import RxCocoa import imglyKit import Then import Groot import Photos typealias SPYCreatPostSection = HashableSectionModel<SPYCreatPostParallaxHeaderViewModel, PlaceStruct> struct SPYCreatPostParallaxHeaderViewModel:Hashable { var hashValue: Int { return 1.hashValue } } func == (lhs: SPYCreatPostParallaxHeaderViewModel, rhs: SPYCreatPostParallaxHeaderViewModel) -> Bool { return lhs.hashValue == rhs.hashValue } class SPYSearchHeader: UICollectionReusableView { var searchBar = SPYSearchBar().then{ $0.barStyle = .Black $0.placeholder = "Search" $0.barTintColor = UIColor.blackColor() $0.backgroundColor = UIColor.blackColor() _ = $0.subviews.map { _ = $0.subviews.map{ if $0.dynamicType == NSClassFromString("UISearchBarTextField"){ $0.backgroundColor = UIColor.whiteColor() } } } } let fromWeb = UILabel().then { $0.text = "FROM THE WEB" $0.textAlignment = .Center $0.backgroundColor = UIColor.blackColor() $0.font = UIFont.spyAvenirNextRegular(10) $0.textColor = UIColor.whiteColor() } override init(frame: CGRect) { super.init(frame: frame) self.addSubviews(fromWeb,searchBar) constrain(self,fromWeb,searchBar){box, web,bar in web.top == box.top web.left == box.left web.right == box.right web.height == 30 bar.top == web.bottom bar.left == web.left bar.width == web.width bar.height == 40 bar.bottom == box.bottom } self.setNeedsLayout() self.layoutIfNeeded() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() } } class SPYCreatPostView: UIViewController ,UISearchBarDelegate { var header : SPYSearchHeader? var parallaxHeader : SPYCreatPostParallaxHeader? var collection = SPYCollectionViewSubClass.spyRegisterClass(SPYSiteCell.self) var dataSourceForPlaceStruct : RxCollectionViewSectionedReloadDataSource<SPYCreatPostSection>! var layout : CSStickyHeaderFlowLayout{ return self.collection.collectionViewLayout as!CSStickyHeaderFlowLayout } var disposeBag = DisposeBag() var bag = DisposeBag() var keyBoardBag = DisposeBag() var places = [PlaceStruct]() var searchInputing : Driver<Void>? override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } // MARK: - view override func viewDidAppear(animated: Bool) { self.parallaxHeader?.reLayoutCamera() } override func viewDidLoad() { configureDataSourceForPlaceStruct() configureNavBar() configureCollection() } func configureNavBar() { self.navigationController?.navigationBar.barTintColor = UIColor.blackColor() self.navigationController?.navigationBar.barStyle = .Black self.navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName :UIFont.spyHelveticaNeueLight(18), NSForegroundColorAttributeName:UIColor.whiteColor()] self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named:"cancel"), style: UIBarButtonItemStyle.Plain, target: self, action: #selector(SPYCreatPostView.gotoTabBarcontroller)) self.navigationItem.leftBarButtonItem!.tintColor = UIColor.whiteColor() } func reloadLayout() { guard let layout = self.collection.collectionViewLayout as? CSStickyHeaderFlowLayout else{ return } layout.parallaxHeaderReferenceSize = CGSizeMake(UIScreen.width, 400); layout.parallaxHeaderMinimumReferenceSize = CGSize(width: UIScreen.width, height: 400) layout.itemSize = CGSizeMake(UIScreen.width, layout.itemSize.height); layout.headerReferenceSize = CGSize(width: UIScreen.width, height: 80) } func gotoTabBarcontroller(){ self.performSegueWithIdentifier("unwindToTabBarController", sender: self) } // MARK: - DataSource func configureCollection() { NSNotificationCenter.defaultCenter().addObserverForName("UIKeyboardWillShowNotification", object: nil, queue: NSOperationQueue.mainQueue()) { (notify) -> Void in self.collection.setContentOffset(CGPoint(x:0,y:400), animated: true) } self.reloadLayout() self.collection.backgroundColor = UIColor.blackColor() self.collection.top = 64 self.view.addSubviews(collection) self.collection.clipsToBounds = false self.collection.registerClass(SPYCreatPostParallaxHeader.self, forSupplementaryViewOfKind: CSStickyHeaderParallaxHeader, withReuseIdentifier: "SPYCreatPostParallaxHeader") self.collection.registerClass(SPYSearchHeader.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "SPYSearchHeader") let headerViewModel = SPYCreatPostParallaxHeaderViewModel() let items = Driver.just([PlaceStruct]()) Driver.combineLatest(Driver.just(headerViewModel),items) { h,items in return [SPYCreatPostSection(model: h, items: items)] } .drive(self.collection.rx_itemsWithDataSource(dataSourceForPlaceStruct)) .addDisposableTo(bag) self.collection.keyboardDismissMode = .OnDrag self.collection.handleAfterReloadData = { [unowned self] in if let header = self.header{ if header.searchBar.canBecomeFristRespond{ header.searchBar.becomeFirstResponder() } } } } func configureSearchBar() { let dd = self.header!.searchBar .rx_text .asDriver() .throttle(0.3) .distinctUntilChanged() .flatMapLatest { [unowned self] (query) -> Driver<[PlaceStruct]> in self.header?.searchBar.canBecomeFristRespond = !query.isEmpty return Spottly.API.searchFoursqPlace(query.isEmpty ? "*":query ,coordinate:CLLocationCoordinate2D(latitude: 36, longitude: 136)) .retry(3) .startWith([]) .asDriver(onErrorJustReturn: []) } .asDriver(onErrorJustReturn: [PlaceStruct]()) self.bag = DisposeBag() let headerViewModel = SPYCreatPostParallaxHeaderViewModel() Driver.combineLatest(Driver.just(headerViewModel),dd) { h,items in return [SPYCreatPostSection(model: h, items: items)] } .drive(self.collection.rx_itemsWithDataSource(dataSourceForPlaceStruct)) .addDisposableTo(bag) collection.rx_itemSelected .asDriver() .driveNext{ [weak self] indexPath in let place = self!.dataSourceForPlaceStruct.itemAtIndexPath(indexPath) let c = mainStoryboard().instantiateViewControllerWithIdentifier("SPYPhotoPicker") as! SPYPhotoPicker c.viewModel = SPYPhotoPickerViewModel(place: place, api: InstagramDefaultAPI()) SPYNavigationController().pushViewController(c, animated: true) } .addDisposableTo(bag) } func configureDataSourceForPlaceStruct() { let dataSource = RxCollectionViewSectionedReloadDataSource<SPYCreatPostSection>() dataSource.cellFactory = { (cv, ip, item)in let cell = cv.dequeueReusableCellWithReuseIdentifier("SPYSiteCell", forIndexPath: ip) as! SPYSiteCell cell.configureCell(item) return cell } dataSource.supplementaryViewFactory = { [unowned self] (cv, kind, ip) in if kind == UICollectionElementKindSectionHeader{ if self.header == nil{ self.header = cv.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SPYSearchHeader", forIndexPath: ip) as? SPYSearchHeader self.header!.searchBar.delegate = self self.configureSearchBar() } return self.header! }else if kind == CSStickyHeaderParallaxHeader{ if self.parallaxHeader == nil{ self.parallaxHeader = cv.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SPYCreatPostParallaxHeader", forIndexPath: ip) as? SPYCreatPostParallaxHeader } return self.parallaxHeader! }else{ fatalError("kind 未识别") } } self.dataSourceForPlaceStruct = dataSource } // MARK: - searchBarDelegate func searchBarSearchButtonClicked(searchBar: UISearchBar) { searchBar.resignFirstResponder() } } // MARK: - helper func imageWithMediaURL(url:NSURL)->(UIImage) { let urlAsset = AVURLAsset(URL: url, options: [AVURLAssetPreferPreciseDurationAndTimingKey : NSNumber(bool: false)]) let generator = AVAssetImageGenerator(asset: urlAsset) generator.appliesPreferredTrackTransform = true; generator.maximumSize = CGSizeMake(600, 450); var img : CGImageRef? do{ img = try generator.copyCGImageAtTime(CMTimeMake(0, 10000) , actualTime: nil) }catch{ } return UIImage(CGImage: img!) } <file_sep>/Spottly/SPYQuickSave.swift // // SPYQuickSave.swift // Spottly // // Created by HuangZhigang on 16/2/21. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import UIKit import RxCocoa import RxSwift import Alamofire import SwiftyJSON class SPYQuickSave: UIViewController { var disposeBag = DisposeBag() var successSegue: UIStoryboardSegue? var photo: UIImage? var videoUrl: NSURL? var rePost: Post? { didSet{ self.placeName.text = rePost!.place!.name self.locName.text = rePost!.place!.address } } var place: PlaceStruct? { didSet{ self.placeName.text = place!.name self.locName.text = place!.city } } var dissButton = UIButton().then{ $0.setImage(UIImage(named: "BackCancel"),forState:.Normal) $0.setImage(UIImage(named: "BackCancel"),forState:.Highlighted) $0.backgroundColor = UIColor.clearColor() } var addButton = UIButton(type: .ContactAdd).then{ $0.backgroundColor = UIColor.clearColor() } var image = UIImageView().then { $0.backgroundColor = UIColor.redColor() } var placeName = UILabel().then{ $0.text = "placeName" $0.backgroundColor = UIColor.clearColor() $0.font = UIFont.spyAvenirNextMedium(14) $0.textColor = UIColor.whiteColor() } var locName = UILabel().then{ $0.text = "locName" $0.backgroundColor = UIColor.clearColor() $0.font = UIFont.spyAvenirNextMedium(12) $0.textColor = UIColor.whiteColor() } var beenHere = UIButton().then{ $0.setTitle("been Here", forState: .Normal) $0.setTitleColor(UIColor.spyTextColor(), forState: .Normal) $0.setTitleColor(UIColor.spyBlueColor(), forState: .Selected) $0.setTitleColor(UIColor.spyBlueColor(), forState: .Highlighted) $0.titleLabel!.font = UIFont.spyAvenirNextMedium(12) $0.backgroundColor = UIColor.clearColor() $0.selected = true $0.layer.borderWidth = 1 $0.layer.borderColor = UIColor.spyBgColor().CGColor $0.layer.cornerRadius = 3 } var wantTogo = UIButton().then{ $0.setTitle("Want To go", forState: .Normal) $0.setTitleColor(UIColor.spyTextColor(), forState: .Normal) $0.setTitleColor(UIColor.spyBlueColor(), forState: .Selected) $0.setTitleColor(UIColor.spyBlueColor(), forState: .Highlighted) $0.titleLabel!.font = UIFont.spyAvenirNextMedium(12) $0.backgroundColor = UIColor.clearColor() $0.layer.borderWidth = 1 $0.layer.borderColor = UIColor.spyBgColor().CGColor $0.layer.cornerRadius = 3 } var inputMsg = UITextView().then{ $0.font = UIFont.spyAvenirNextRegular(12) $0.text = "say something.." $0.textColor = UIColor.spyGrayColor() $0.backgroundColor = UIColor.clearColor() $0.layer.borderWidth = 1 $0.layer.borderColor = UIColor.spyBgColor().CGColor $0.layer.cornerRadius = 3 } var inputCollectionName = UITextField().then{ $0.placeholder = "Creat a Collection" $0.font = UIFont.spyAvenirNextRegular(12) $0.textColor = UIColor.spyBlackColor() $0.backgroundColor = UIColor.clearColor() $0.layer.borderWidth = 1 $0.layer.borderColor = UIColor.spyBgColor().CGColor $0.layer.cornerRadius = 3 } var label = UILabel().then{ $0.text = "CHOOSE A COLLECTION" $0.textAlignment = .Center $0.font = UIFont.spyAvenirNextRegular(10) $0.textColor = UIColor.spyBlackColor() $0.backgroundColor = UIColor.clearColor() } var creat = UIView().then{ $0.backgroundColor = UIColor.spyBgColor() } var collectionView: UICollectionView? func configureImageLoc(){ self.image.image = self.photo self.dissButton.rx_tap.asDriver().driveNext { () -> Void in self.dismissViewControllerAnimated(true, completion: { () -> Void in }) }.addDisposableTo(self.disposeBag) } override func viewDidLoad() { var rect = self.view.frame rect.size = CGSizeMake(UIScreen.width*343/375, UIScreen.height*500/667) self.view.frame = rect let layout = UICollectionViewFlowLayout() layout.itemSize = CGSizeMake(300, 30) layout.scrollDirection = .Vertical collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout) collectionView?.backgroundColor = UIColor.whiteColor() collectionView?.registerClass(SPYCollectionTitleCell.self, forCellWithReuseIdentifier: "SPYCollectionTitleCell") self.view.addSubviews(image,beenHere,wantTogo,inputMsg,label,collectionView!,creat) constrain(image,beenHere,wantTogo,inputMsg,label){image,beenHere,wantTogo,input,label in let box = image.superview! image.top == box.top image.left == box.left image.width == box.width image.height == 178 beenHere.top == image.bottom beenHere.left == box.left + 15 beenHere.width == wantTogo.width beenHere.height == wantTogo.height beenHere.height == 34 wantTogo.top == image.bottom beenHere.right == wantTogo.left wantTogo.right == box.right - 15 input.top == beenHere.bottom + 22 input.left == box.left + 15 input.right == box.right - 15 input.height == 48 label.top == input.bottom + 25 label.left == box.left label.right == box.right label.height == 28 } creat.addSubviews(inputCollectionName,addButton) constrain(label,collectionView!,creat,inputCollectionName,addButton){ label,collection,creat,name,add in let box = label.superview! distribute(by: 0, vertically: label,collection,creat) align(left: collection,label,creat) align(right: collection,label,creat) creat.height == 45 name.edges == inset(creat.edges, 10,10,10,40) creat.bottom == box.bottom add.width == 25 add.height == 25 add.right == creat.right - 10 add.bottom == creat.bottom - 10 } image.addSubviews(dissButton) image.userInteractionEnabled = true constrain(image,dissButton){ box , diss in diss.top == box.top + 12 diss.right == box.right - 12 diss.width == 30 diss.height == 30 } let pin = UIImageView(image: UIImage(named: "profileIconH")) let placeAndLoc = UIView().then{ $0.backgroundColor = UIColor.clearColor() } placeAndLoc.addSubviews(locName,placeName) constrain(placeAndLoc,locName,placeName){ box,loc,place in place.top == box.top place.left == box.left place.right == box.right place.bottom == loc.top + 4 loc.bottom == box.bottom loc.left == box.left loc.right == box.right } self.image.addSubviews(pin,placeAndLoc) constrain(image,pin,placeAndLoc){ box,pin,placeAndLoc in pin.bottom == box.bottom - 16 pin.left == box.left + 10 pin.height == 19 pin.width == 10 placeAndLoc.centerY == pin.centerY placeAndLoc.left == box.left + 27 placeAndLoc.width == UIScreen.width - 120 } self.view.setNeedsLayout() self.view.layoutIfNeeded() self.configureImageLoc() self.configureBtns() let doneButton = UIButton().then{ $0.setTitle("Done", forState: .Normal) $0.setTitleColor(UIColor.spyTextColor(), forState: .Normal) $0.setTitleColor(UIColor.spyBlueColor(), forState: .Selected) $0.setTitleColor(UIColor.spyBlueColor(), forState: .Highlighted) $0.titleLabel!.font = UIFont.spyAvenirNextMedium(12) $0.backgroundColor = UIColor.clearColor() $0.layer.borderWidth = 1 $0.layer.borderColor = UIColor.spyBgColor().CGColor $0.layer.cornerRadius = 3 } doneButton.rx_tap.asDriver().driveNext { () -> Void in self.inputMsg.resignFirstResponder() self.inputCollectionName.resignFirstResponder() }.addDisposableTo(disposeBag) let doneButtonAccessoryView = UIView().then{ $0.backgroundColor = UIColor.whiteColor() $0.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: 40) } doneButtonAccessoryView.addSubview(doneButton) constrain(doneButtonAccessoryView, doneButton) { (box, button) -> () in button.centerY == box.centerY button.right == box.right - 20 button.height == 30 button.width == 40 } doneButtonAccessoryView.setNeedsLayout() doneButtonAccessoryView.layoutIfNeeded() self.inputMsg.inputAccessoryView = doneButtonAccessoryView SPYUserViewModel.shareMe.collectionsFRC? .performFetchIfNeed .rxFetchedObjects .bindTo(collectionView!.rx_itemsWithCellIdentifier("SPYCollectionTitleCell")){ (_, collection, cell: SPYCollectionTitleCell) in let collection = collection as! Collection cell.label.text = collection.name }.addDisposableTo(self.disposeBag) collectionView!.rx_modelSelected(AnyObject) .asDriver() .driveNext{ collection -> Void in let collection = collection as! Collection print("collection.name : \(collection.name)") if self.rePost != nil{ self.reCreatPost(collection.id,postid:self.rePost!.id) }else{ if let url = self.videoUrl{ self.updateVideoToPost(collection.id) }else{ self.updatePost(collection.id) } } }.addDisposableTo(self.disposeBag) } func reCreatPost(collectionid:String,postid:String) { let parameters = ["from-id":postid,"collection-id":collectionid,"message":self.inputMsg.text] Alamofire.request(SPYRouter.CreatPost(parameters)).responseJSON { (response) -> Void in guard let jsonData = response.result.value , isSuccess = response.response?.isSuccess where isSuccess == true else{ print("response.result.error :\(response.result.error)") fatalError("ERROR: SPYRouter.CreatPost") } print("jsonData :\(jsonData)") self.dismissViewControllerAnimated(true, completion: { () -> Void in }) } } func updateVideoToPost(collectionid:String) { let imageRequest = NSMutableURLRequest(URL: NSURL(string: "http://staging.spottly.com:6666/medias")!) imageRequest.HTTPMethod = "POST" imageRequest.HTTPBody = UIImageJPEGRepresentation(self.image.image!,0.9)! imageRequest.addValue("image/jpeg", forHTTPHeaderField: "Content-Type") Alamofire.request(imageRequest).responseJSON { (response) -> Void in guard let jsonData = response.result.value , isSuccess = response.response?.isSuccess where isSuccess == true else{ print("response.result.error :\(response.response!.statusCode) ") fatalError("ERROR: http://staging.spottly.com:6666/medias") } print("json ; \(jsonData)"); print("self.place!.foursqPlace : \(self.place!.info)"); guard let imageMedia = JSON(jsonData)["data"].dictionaryObject else { fatalError("ERROR: SPYRouter.CreatPost no media") return; } let videoRequest = NSMutableURLRequest(URL: NSURL(string: "http://staging.spottly.com:6666/medias")!) videoRequest.HTTPMethod = "POST" videoRequest.HTTPBody = NSData(contentsOfURL: self.videoUrl!) videoRequest.addValue("video/mp4", forHTTPHeaderField: "Content-Type") Alamofire.request(videoRequest).responseJSON { (response) -> Void in guard let jsonData = response.result.value , isSuccess = response.response?.isSuccess where isSuccess == true else{ print("response.result.error :\(response.response!.statusCode) ") fatalError("ERROR: http://staging.spottly.com:6666/medias") } print("json ; \(jsonData)"); print("self.place!.foursqPlace : \(self.place!.info)"); guard let videoMedia = JSON(jsonData)["data"].dictionaryObject else { fatalError("ERROR: SPYRouter.CreatPost no media") return } let parameters = ["medias":[imageMedia,videoMedia],"place":self.place!.orginInfo,"collection-id":collectionid,"message":self.inputMsg.text] Alamofire.request(SPYRouter.CreatPost(parameters as! [String : AnyObject])).responseJSON { (response) -> Void in guard let jsonData = response.result.value , isSuccess = response.response?.isSuccess where isSuccess == true else{ // showAlert("code:\(response.response!.statusCode)") print("code:\(response.response!.statusCode) response.result.error :\(response.result.error) ") // fatalError("ERROR: SPYRouter.CreatPost") return } print("jsonData :\(jsonData)") self.successSegue?.perform() } } } } func updatePost(collectionid:String) { let request = NSMutableURLRequest(URL: NSURL(string: "http://staging.spottly.com:6666/medias")!) request.HTTPMethod = "POST" request.HTTPBody = UIImageJPEGRepresentation(self.image.image!,0.9)! request.addValue("image/jpeg", forHTTPHeaderField: "Content-Type") Alamofire.request(request).responseJSON { (response) -> Void in guard let jsonData = response.result.value , isSuccess = response.response?.isSuccess where isSuccess == true else{ print("response.result.error :\(response.response!.statusCode) ") fatalError("ERROR: http://staging.spottly.com:6666/medias") } print("json ; \(jsonData)"); print("self.place!.foursqPlace : \(self.place!.info)"); if let media = JSON(jsonData)["data"].dictionaryObject { let parameters = ["medias":[media],"place":self.place!.orginInfo,"collection-id":collectionid,"message":self.inputMsg.text] Alamofire.request(SPYRouter.CreatPost(parameters as! [String : AnyObject])).responseJSON { (response) -> Void in guard let jsonData = response.result.value , isSuccess = response.response?.isSuccess where isSuccess == true else{ print("code:\(response.response!.statusCode) response.result.error :\(response.result.error) ") // showAlert("code:\(response.response!.statusCode)") fatalError("ERROR: SPYRouter.CreatPost") } print("jsonData :\(jsonData)") self.successSegue?.perform() } }else{ fatalError("ERROR: SPYRouter.CreatPost no media") } } } func configureBtns() { beenHere.rx_tap.asDriver().driveNext { () -> Void in self.beenHere.selected = !self.beenHere.selected if self.beenHere.selected{ self.wantTogo.selected = false } }.addDisposableTo(self.disposeBag) wantTogo.rx_tap.asDriver().driveNext{ () -> Void in self.wantTogo.selected = !self.wantTogo.selected if self.wantTogo.selected{ self.beenHere.selected = false } }.addDisposableTo(self.disposeBag) } }<file_sep>/Spottly/SPYCityCell.swift // // SPYCityCell.swift // Spottly // // Created by HuangZhigang on 16/2/16. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import UIKit class SPYCityCell : UICollectionViewCell { var imageView : UIImageView! var label: UILabel! override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.blackColor() self.imageView = UIImageView(frame:self.bounds ) // self.imageView.backgroundColor = UIColor.grayColor() self.addSubview(self.imageView) self.label = UILabel().then{ $0.backgroundColor = UIColor.clearColor() $0.textColor = UIColor.whiteColor() $0.font = UIFont.spyAvenirNextMedium(12) $0.textAlignment = .Center } self.imageView.addSubview(self.label) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { self.imageView.frame = self.bounds self.imageView.clipsToBounds = true self.clipsToBounds = true self.label.sizeToFit() var rect = self.label.frame rect.size.width = self.bounds.size.width self.label.frame = rect self.label.center = self.imageView.center self.layer.cornerRadius = self.bounds.width/2 // print("self.label : \(self.label)") } } <file_sep>/SpottlyTests/ContentAPITests.swift // // SeverContentAPITests.swift // Spottly // // Created by HuangZhigang on 16/5/5. // Copyright © 2016年 Spottly. All rights reserved. // import XCTest import Alamofire import SwiftyJSON import RxSwift import RxBlocking import RxCocoa @testable import Spottly class ContentAPITests: XCTestCase { let cityID = "95551579422772" let collectionID = "95551746015300" let placeID = "95551731532104" let categoriesID = "95551579750669"//food let userID = "95551582372079" let postID = "95551852904511" let coordinate = CLLocation(latitude: 39.9345408981, longitude: 116.4464434002) let namePara = "edwy" let tag = "Food" override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testFollowedCollections() { let URL = SPYRouter.FollowedCollections(userID) .fullPath .orderBy(.CreateTime(.Desc)) .count(2) let expectation = expectationWithDescription("Get: \(URL)") Alamofire.request(.GET, URL).responseJSON { response in expectation.fulfill() print("testFollowedCollections : \(URL) \n ERROR : \(response.result.error)") XCTAssertLessThan(response.response!.statusCode,400,"返回错误") XCTAssertNotNil(response.result.value, "返回数据不应该为空") let json = JSON(response.result.value!) XCTAssertNotNil(json["data"], "返回数据不应该为空") let array = json["data"]["collections"].array XCTAssertNotNil(array, "返回数据不应该为空") if let a = array{ XCTAssertGreaterThan(a.count, 0) print(" \(a.first)") } } waitForExpectationsWithTimeout(15) { (error) in if error != nil{ XCTFail("❌") } } } func testFollowerFromUser() { let URL = SPYRouter.FollowerFromUser(userID) .fullPath .orderBy(.CreateTime(.Desc)) .count(2) let expectation = expectationWithDescription("Get: \(URL)") Alamofire.request(.GET, URL).responseJSON { response in expectation.fulfill() print("testFollowerFromUser : \(URL) \n ERROR : \(response.result.error)") XCTAssertLessThan(response.response!.statusCode,400,"返回错误") XCTAssertNotNil(response.result.value, "返回数据不应该为空") let json = JSON(response.result.value!) XCTAssertNotNil(json["data"], "返回数据不应该为空") let array = json["data"]["users"].array XCTAssertNotNil(array, "返回数据不应该为空") if let a = array{ XCTAssertGreaterThan(a.count, 0) print(" \(a.first)") } } waitForExpectationsWithTimeout(15) { (error) in if error != nil{ XCTFail("❌") } } } func testFollowingToUser() { let URL = SPYRouter.FollowingToUser(userID) .fullPath .orderBy(.CreateTime(.Desc)) .count(2) let expectation = expectationWithDescription("Get: \(URL)") Alamofire.request(.GET, URL).responseJSON { response in expectation.fulfill() print("testFollowingToUser : \(URL) \n ERROR : \(response.result.error)") XCTAssertLessThan(response.response!.statusCode,400,"返回错误") XCTAssertNotNil(response.result.value, "返回数据不应该为空") let json = JSON(response.result.value!) XCTAssertNotNil(json["data"], "返回数据不应该为空") let array = json["data"]["users"].array XCTAssertNotNil(array, "返回数据不应该为空") if let a = array{ XCTAssertGreaterThan(a.count, 0) print(" \(a.first)") } } waitForExpectationsWithTimeout(15) { (error) in if error != nil{ XCTFail("❌") } } } func testCollectionsFromUser() { let URL = SPYRouter.CollectionsFromUser(userID) .fullPath .orderBy(.CreateTime(.Desc)) .count(2) let expectation = expectationWithDescription("Get: \(URL)") Alamofire.request(.GET, URL).responseJSON { response in expectation.fulfill() print("testCollectionsFromUser : \(URL) \n ERROR : \(response.result.error)") XCTAssertLessThan(response.response!.statusCode,400,"返回错误") XCTAssertNotNil(response.result.value, "返回数据不应该为空") let json = JSON(response.result.value!) XCTAssertNotNil(json["data"], "返回数据不应该为空") let array = json["data"]["collections"].array XCTAssertNotNil(array, "返回数据不应该为空") if let a = array{ XCTAssertGreaterThan(a.count, 0) print(" \(a.first)") } } waitForExpectationsWithTimeout(15) { (error) in if error != nil{ XCTFail("❌") } } } func testPlacesFromUser_recently() { let URL = SPYRouter.PlacesFromUser(userID) .fullPath .orderBy(.CreateTime(.Desc)) .count(2) let expectation = expectationWithDescription("Get: \(URL)") Alamofire.request(.GET, URL).responseJSON { response in expectation.fulfill() print("testPlacesFromUser_recently : \(URL) \n ERROR : \(response.result.error)") XCTAssertLessThan(response.response!.statusCode,400,"返回错误") XCTAssertNotNil(response.result.value, "返回数据不应该为空") let json = JSON(response.result.value!) XCTAssertNotNil(json["data"], "返回数据不应该为空") let array = json["data"]["places"].array XCTAssertNotNil(array, "返回数据不应该为空") if let a = array{ XCTAssertGreaterThan(a.count, 0) } print("testPlacesFromUser_recently \(json)") } waitForExpectationsWithTimeout(15) { (error) in if error != nil{ XCTFail("❌") } } } func testPlacesFromUser_nearby() { let URL = SPYRouter.PlacesFromUser(userID) .fullPath .filter([.Coordinate(coordinate)]) .orderBy(.Distance(.Asc)) .count(2) let expectation = expectationWithDescription("Get: \(URL)") Alamofire.request(.GET, URL).responseJSON { response in expectation.fulfill() print("testPlacesFromUser_nearby : \(URL) \n ERROR : \(response.result.error)") XCTAssertLessThan(response.response!.statusCode,400,"返回错误") XCTAssertNotNil(response.result.value, "返回数据不应该为空") let json = JSON(response.result.value!) XCTAssertNotNil(json["data"], "返回数据不应该为空") let array = json["data"]["places"].array XCTAssertNotNil(array, "返回数据不应该为空") if let a = array{ XCTAssertGreaterThan(a.count, 0) print("testPlacesFromUser_nearby \(json)") } } waitForExpectationsWithTimeout(15) { (error) in if error != nil{ XCTFail("❌") } } } func testCollectionRelatedPlace() { let URL = SPYRouter.CollectionRelatedPlace(placeID) .fullPath .orderBy(.CreateTime(.Desc)) .count(2) let expectation = expectationWithDescription("Get: \(URL)") Alamofire.request(.GET, URL).responseJSON { response in expectation.fulfill() print("testCollectionRelatedPlace : \(URL) \n ERROR : \(response.result.error)") XCTAssertLessThan(response.response!.statusCode,400,"返回错误") XCTAssertNotNil(response.result.value, "返回数据不应该为空") let json = JSON(response.result.value!) XCTAssertNotNil(json["data"], "返回数据不应该为空") let array = json["data"]["collections"].array XCTAssertNotNil(array, "返回数据不应该为空") if let a = array{ XCTAssertGreaterThan(a.count, 0) print(" \(a.first)") } print("testCollectionRelatedPlace \(json)") } waitForExpectationsWithTimeout(15) { (error) in if error != nil{ XCTFail("❌") } } } func testPostsInPlaces() { let URL = SPYRouter.PostsInPlaces(placeID) .fullPath .orderBy(.CreateTime(.Desc)) .count(2) let expectation = expectationWithDescription("Get: \(URL)") Alamofire.request(.GET, URL).responseJSON { response in expectation.fulfill() print("testPostsInPlaces : \(URL) \n ERROR : \(response.result.error)") XCTAssertLessThan(response.response!.statusCode,400,"返回错误") XCTAssertNotNil(response.result.value, "返回数据不应该为空") let json = JSON(response.result.value!) XCTAssertNotNil(json["data"], "返回数据不应该为空") let array = json["data"]["posts"].array XCTAssertNotNil(array, "返回数据不应该为空") if let a = array{ XCTAssertGreaterThan(a.count, 0) print(" \(a.first)") } print("testPostsInPlaces \(json)") } waitForExpectationsWithTimeout(15) { (error) in if error != nil{ XCTFail("❌") } } } } <file_sep>/Spottly/SPYHTTPSession.swift // // SPYHTTPSession.swift // SpottlyCoreData // // Created by HuangZhigang on 15/6/23. // Copyright (c) 2015年 Spottly. All rights reserved. // import UIKit import AFNetworking private let SPYAPIBaseURLString = "http://api.spottly.com/" private let singleInstace = SPYHTTPSession() class SPYHTTPSession : AFHTTPSessionManager{ class var share : SPYHTTPSession{ return singleInstace } override init(baseURL url: NSURL!, sessionConfiguration configuration: NSURLSessionConfiguration!) { super.init(baseURL: NSURL(string: SPYAPIBaseURLString), sessionConfiguration: configuration) super.requestSerializer = AFJSONRequestSerializer() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } <file_sep>/Spottly/SPYBaseModel/City+CoreDataProperties.swift // // City+CoreDataProperties.swift // Spottly // // Created by HuangZhigang on 16/5/10. // Copyright © 2016年 Spottly. All rights reserved. // // Choose "Create NSManagedObject Subclass…" from the Core Data editor menu // to delete and recreate this implementation file for your updated model. // import Foundation import CoreData extension City { @NSManaged var alias: String? @NSManaged var countryId: String? @NSManaged var id: String? @NSManaged var image: String? @NSManaged var latitude: NSNumber? @NSManaged var longitude: NSNumber? @NSManaged var name: String? @NSManaged var wikipedia: String? @NSManaged var wikitravel: String? } <file_sep>/Spottly/SPYBaseModel/Media+CoreDataProperties.swift // // Media+CoreDataProperties.swift // Spottly // // Created by HuangZhigang on 16/2/1. // Copyright © 2016年 Spottly. All rights reserved. // // Choose "Create NSManagedObject Subclass…" from the Core Data editor menu // to delete and recreate this implementation file for your updated model. // import Foundation import CoreData extension Media { @NSManaged var id: String @NSManaged var sourceType: String? @NSManaged var mimeType: String? @NSManaged var storePath: String? @NSManaged var ext: String? @NSManaged var post: Post? } <file_sep>/Spottly/SPYBaseModel/Collection.swift // // Collection.swift // Spottly // // Created by HuangZhigang on 16/2/1. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import CoreData class Collection: NSManagedObject { func selfFR() -> SPYFetchRequest { let fr = SPYFetchRequest() fr.entity = NSEntityDescription.entityForName("Collection", inManagedObjectContext: SPYMainMoc()) let method = SPYRouter.Collection(collectionid: self.id).method.rawValue let path = SPYRouter.Collection(collectionid: self.id).fullPath fr.httpInfo = ["METHOD" : method , "URL" : path] fr.predicate = NSPredicate(format: "id = %@",self.id) fr.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)] return fr } func postsFR() -> SPYFetchRequest { let fr = SPYFetchRequest() fr.entity = NSEntityDescription.entityForName("Post", inManagedObjectContext: SPYMainMoc()) let method = SPYRouter.PostsFromCollection(collectionid: self.id).method.rawValue let path = SPYRouter.PostsFromCollection(collectionid: self.id).fullPath fr.httpInfo = ["METHOD" : method , "URL" : path] fr.predicate = NSPredicate(format: "collection.id = %@",self.id) fr.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)] return fr } func threePostsFR() -> SPYFetchRequest { let fr = SPYFetchRequest() fr.entity = NSEntityDescription.entityForName("Post", inManagedObjectContext: SPYMainMoc()) fr.predicate = NSPredicate(format: "collection.id = %@",self.id) fr.fetchLimit = 3 fr.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)] return fr } } <file_sep>/Spottly/SPYExploreView.swift // // FirstViewController.swift // Spottly // // Created by HuangZhigang on 15/12/4. // Copyright © 2015年 Spottly. All rights reserved. // import UIKit import RxSwift import CoreData import RxCocoa import TFTransparentNavigationBar import PullToRefresh import ObjectiveC typealias SPYExplorePlaceSection = HashableSectionModel<SPYExploreHeaderViewModel, Place> typealias SPYExploreCollectionSection = HashableSectionModel<SPYExploreHeaderViewModel, Collection> typealias SPYExploreWebSection = HashableSectionModel<SPYExploreHeaderViewModel, String> struct SPYExploreHeaderViewModel:Hashable { var rx_category: Driver<[ExploreCategory]> var mainCategory: Any var menuItems: [SPYMenuAction] var hashValue: Int { if mainCategory is String{ return (mainCategory as! String) .hashValue }else if mainCategory is City { return (mainCategory as! City).name!.hashValue }else if mainCategory is Categorie { return (mainCategory as! Categorie).name!.hashValue } return 1 } } func == (lhs: SPYExploreHeaderViewModel, rhs: SPYExploreHeaderViewModel) -> Bool { return lhs.hashValue == rhs.hashValue } var locationValue : CLLocationCoordinate2D? extension UICollectionView { } class SPYExploreView: UIViewController { override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // print("self.collection : \(self.collection.frame)") // print("self.view : \(self.view.frame)") } // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() configureDataSourceForPlace() configureDataSourceForCollection() configureDataSourceForWeb() configureCollection() configureSearchBar() GeolocationService.instance .location .driveNext { _ in} .addDisposableTo(disposeBag) if let _ = viewModel{ }else{ self.viewModel = SPYExploreViewModel.wrold } doMenuAction(.Place(.Hot)) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) configureNavBar() self.changeNavBarColor(self.collection.contentOffset) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.changeNavBarColor(self.collection.contentOffset) } override func viewWillDisappear(animated: Bool) { self.navigationController?.navigationBar.lt_reset() self.navigationItem.titleView = nil } func reloadLayout() { guard let layout = self.collection.collectionViewLayout as? CSStickyHeaderFlowLayout else{ return } layout.parallaxHeaderReferenceSize = CGSizeMake(UIScreen.width, 450); layout.parallaxHeaderMinimumReferenceSize = CGSize(width: UIScreen.width, height: 449) layout.itemSize = CGSizeMake(UIScreen.width, layout.itemSize.height); layout.headerReferenceSize = CGSize(width: UIScreen.width, height: 40) layout.footerReferenceSize = CGSize(width: UIScreen.width, height: 40) layout.spyHeaderAddedOrginY = 64 } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } func configureNavBar(){ self.navigationItem.titleView = self.searchBar self.navigationController?.navigationBar.barStyle = .Black self.navigationController?.navigationBar.tintColor = UIColor.whiteColor() self.navigationController?.navigationBar.lt_setBackgroundColor(UIColor.clearColor()) self.navigationController?.navigationBar.shadowImage = UIImage() } func configureSearchBar() { self.searchResult = SPYSearchResultView(searchBar: searchBar) self.searchBar.rx_delegate.setForwardToDelegate(self, retainDelegate: false) self.view.addSubviews(searchResult!.view) searchResult?.view.hidden = true } func changeNavBarColor(offset:CGPoint ) { if offset.y > 64 { var alpha = min(1, 1 - ((64 + 64 - offset.y) / 64)) // alpha = 0.5 self.navigationController?.navigationBar.lt_setBackgroundColor(UIColor.spyLogoColor().colorWithAlphaComponent(alpha)) self.searchBar.alpha = alpha }else{ self.navigationController?.navigationBar.lt_setBackgroundColor(UIColor.spyLogoColor().colorWithAlphaComponent(0)) self.searchBar.alpha = 0 } } func configureCollection() { self.reloadLayout() self.view.addSubviews(collection) constrain(self.view,collection){ box,collection in collection.top == box.top collection.left == box.left collection.right == box.right collection.bottom == box.bottom - 48 } // self.view.backgroundColor = UIColor.whiteColor() // collection.backgroundColor = UIColor.whiteColor() collection.clipsToBounds = false collection.scrollIndicatorInsets = UIEdgeInsetsMake(64, 0, 0, 0) // let refresher = PullToRefresh() // self.collection.addPullToRefresh(refresher) {[unowned self] () -> () in // delay(2, closure: { () -> () in // self.collection.endRefreshing() // }) // } collection.registerClass(SPYExploreViewParallaxHeader.self, forSupplementaryViewOfKind: CSStickyHeaderParallaxHeader, withReuseIdentifier: "SPYExploreViewParallaxHeader") collection.registerClass(SPYMenuHeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "SPYMenuHeaderView") collection.registerClass(SPYMoreFooterView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "SPYMoreFooterView") collection.rx_contentOffset .asDriver() .driveNext {[weak self] (offset) in self?.changeNavBarColor(offset) }.addDisposableTo(disposeBag) collection.rx_contentOffset .asDriver() .filter{ UIScrollView.needMore(self.collection, offset: $0) } .throttle(0.2) .driveNext { [weak self] point in self?.doMore(self!.header!.menu.rx_selectedSegment.value!) }.addDisposableTo(disposeBag) } // MARK: - DataSource func configureDataSourceForPlace() { let dataSource = RxCollectionViewSectionedReloadDataSource<SPYExplorePlaceSection>() dataSource.cellFactory = { (cv, ip, item)in let cell = cv.dequeueReusableCellWithReuseIdentifier("SPYPlaceCell", forIndexPath: ip) as! SPYPlaceCell cell.configureCell(item) return cell } dataSource.supplementaryViewFactory = { [unowned dataSource,unowned self] (cv, kind, ip) in if kind == UICollectionElementKindSectionHeader{ if self.header == nil { self.header = cv.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SPYMenuHeaderView", forIndexPath: ip) as? SPYMenuHeaderView self.header?.configureCell(dataSource.sectionAtIndex(ip.section).model.menuItems) self.header?.delegate = self } return self.header! }else if kind == CSStickyHeaderParallaxHeader{ if self.parallaxHeader == nil { self.parallaxHeader = cv.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SPYExploreViewParallaxHeader", forIndexPath: ip) as? SPYExploreViewParallaxHeader self.parallaxHeader?.configureCell(dataSource.sectionAtIndex(ip.section).model) } return self.parallaxHeader! }else{ if self.footer == nil { self.footer = cv.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SPYMoreFooterView", forIndexPath: ip) as? SPYMoreFooterView } return self.footer! } } self.dataSourceForPlace = dataSource } func configureDataSourceForCollection() { let dataS = RxCollectionViewSectionedReloadDataSource<SPYExploreCollectionSection>() dataS.cellFactory = { (cv, ip, item)in let cell = cv.dequeueReusableCellWithReuseIdentifier("SPYCollectionCell", forIndexPath: ip) as! SPYCollectionCell cell.configureCell(item) return cell } dataS.supplementaryViewFactory = { [unowned dataS,unowned self] (cv, kind, ip) in if kind == UICollectionElementKindSectionHeader{ if self.header == nil { self.header = cv.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SPYMenuHeaderView", forIndexPath: ip) as? SPYMenuHeaderView self.header?.delegate = self self.header?.configureCell(dataS.sectionAtIndex(ip.section).model.menuItems) } return self.header! }else if kind == CSStickyHeaderParallaxHeader{ if self.parallaxHeader == nil { self.parallaxHeader = cv.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SPYExploreViewParallaxHeader", forIndexPath: ip) as? SPYExploreViewParallaxHeader self.parallaxHeader?.configureCell(dataS.sectionAtIndex(ip.section).model) } return self.parallaxHeader! }else { if self.footer == nil { self.footer = cv.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SPYMoreFooterView", forIndexPath: ip) as? SPYMoreFooterView } return self.footer! } } self.dataSourceForCollection = dataS } func configureDataSourceForWeb() { let dataS = RxCollectionViewSectionedReloadDataSource<SPYExploreWebSection>() dataS.cellFactory = { (cv, ip, item)in let cell = cv.dequeueReusableCellWithReuseIdentifier("SPYWebCell", forIndexPath: ip) as! SPYWebCell cell.configureCell(item) // cell.handlerAfterLayout = { [unowned self] size in // self.layout.itemSize = size // } return cell } dataS.supplementaryViewFactory = { [unowned dataS,unowned self] (cv, kind, ip) in if kind == UICollectionElementKindSectionHeader{ if self.header == nil { self.header = cv.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SPYMenuHeaderView", forIndexPath: ip) as? SPYMenuHeaderView self.header?.delegate = self self.header?.configureCell(dataS.sectionAtIndex(ip.section).model.menuItems) } return self.header! }else if kind == CSStickyHeaderParallaxHeader{ if self.parallaxHeader == nil { self.parallaxHeader = cv.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SPYExploreViewParallaxHeader", forIndexPath: ip) as? SPYExploreViewParallaxHeader self.parallaxHeader?.configureCell(dataS.sectionAtIndex(ip.section).model) } return self.parallaxHeader! }else { if self.footer == nil { self.footer = cv.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SPYMoreFooterView", forIndexPath: ip) as? SPYMoreFooterView } return self.footer! } } self.dataSourceForWeb = dataS } func doMore(value: SPYMenuAction) { self.footer?.startAnimating() switch value { case .Place : self.viewModel?.placesFRC?.loadMore() case .Collection: self.viewModel?.collectionsFRC?.loadMore() default: break } } // MARK: - Property var header : SPYMenuHeaderView? var footer : SPYMoreFooterView? var parallaxHeader : SPYExploreViewParallaxHeader? var collection = SPYCollectionViewSubClass.spyRegisterClass(SPYPlaceCell.self,SPYCollectionCell.self,SPYWebCell.self) var dataSourceForWeb : RxCollectionViewSectionedReloadDataSource<SPYExploreWebSection>! var dataSourceForPlace : RxCollectionViewSectionedReloadDataSource<SPYExplorePlaceSection>! var dataSourceForCollection : RxCollectionViewSectionedReloadDataSource<SPYExploreCollectionSection>! var layout : CSStickyHeaderFlowLayout{ return self.collection.collectionViewLayout as!CSStickyHeaderFlowLayout } var disposeBag = DisposeBag() var bag = DisposeBag() var searchInputing : Driver<Void>? var searchResult : SPYSearchResultView? var searchBar = SPYSearchBar().then{ $0.alpha = 0; $0.tintColor = UIColor.spyLogoColor() $0.barTintColor = UIColor.spyLogoColor() $0.showsCancelButton = false } var viewModel : SPYExploreViewModel? var searchBarBackground = UIView().then{ $0.frame = CGRectMake(0,0,50,50) $0.backgroundColor = UIColor.whiteColor() $0.hidden = true } } extension SPYExploreView : SPYMenuActionDelegate{ func headerFlowLayout() -> CSStickyHeaderFlowLayout { return self.collection.collectionViewLayout as! CSStickyHeaderFlowLayout } func doMenuAction(menuAction:SPYMenuAction) { self.bag = DisposeBag() self.searchBar.resignFirstResponder() switch menuAction { case .Place(_) : let headerViewModel = SPYExploreHeaderViewModel(rx_category: viewModel!.rx_category, mainCategory: viewModel!.mainCategory, menuItems: viewModel!.menuItems) let items = viewModel!.placesFRC!.performFetchIfNeed.rxFetchedObjects.asDriver() Driver.combineLatest(Driver.just(headerViewModel),items) { h,items in return [SPYExplorePlaceSection(model: h, items: items as! [Place])] } .drive(self.collection.rx_itemsWithDataSource(dataSourceForPlace)) .addDisposableTo(bag) self.collection .rx_itemSelected.asDriver() .driveNext{ [weak self] indexPath in let c = mainStoryboard().instantiateViewControllerWithIdentifier("SPYPostView") as! SPYPostView let place = self!.dataSourceForPlace.itemAtIndexPath(indexPath) c.viewModel = SPYPostViewModel(input:place.relatedPost!) self!.navigationController?.pushViewController(c, animated: true) } .addDisposableTo(bag) layout.spyConfigureLayoutForPlaces() // self.layout.invalidateLayout() SPYScrollMenuHeaderToTop(self.header,collection:self.collection ,layout:self.layout) SPYObserveRequestState(self.collection, frc: viewModel?.placesFRC, dataType: .Place, bag: bag) case .Collection(let type) : let headerViewModel = SPYExploreHeaderViewModel(rx_category: viewModel!.rx_category, mainCategory: viewModel!.mainCategory,menuItems: viewModel!.menuItems) let items = viewModel!.collectionsFRC!.performFetchIfNeed.rxFetchedObjects.asDriver() Driver.combineLatest(Driver.just(headerViewModel),items){ h,items in return [SPYExploreCollectionSection(model: h, items: items as! [Collection])] }.drive(self.collection.rx_itemsWithDataSource(dataSourceForCollection)) .addDisposableTo(bag) collection.rx_itemSelected .asDriver() .driveNext{ [weak self] indexPath in let c = mainStoryboard().instantiateViewControllerWithIdentifier("SPYCollectionView") as! SPYCollectionView let collection = self!.dataSourceForCollection.itemAtIndexPath(indexPath) c.viewModel = SPYCollectionViewModel(input:collection) self!.navigationController?.pushViewController(c, animated: true) } .addDisposableTo(bag) layout.spyConfigureLayoutForCollections() // self.layout.invalidateLayout() SPYScrollMenuHeaderToTop(self.header!,collection:self.collection ,layout:self.layout) SPYObserveRequestState(self.collection, frc: viewModel?.collectionsFRC, dataType: .Collection, bag: bag) case .Details : let headerViewModel = SPYExploreHeaderViewModel(rx_category: viewModel!.rx_category, mainCategory: viewModel!.mainCategory,menuItems: viewModel!.menuItems) let items = Driver.just([viewModel!.cityDetailUrl!]) Driver.combineLatest(Driver.just(headerViewModel),items){ h,items in return [SPYExploreWebSection(model: h, items: items )] }.drive(self.collection.rx_itemsWithDataSource(dataSourceForWeb)) .addDisposableTo(bag) layout.spyConfigureLayoutForWeb() // self.layout.invalidateLayout() SPYScrollMenuHeaderToTop(self.header!,collection:self.collection ,layout:self.layout) SPYObserveRequestState(self.collection, frc: viewModel?.collectionsFRC, dataType: .Detail, bag: bag) default: break } } } extension SPYExploreView : UISearchBarDelegate{ func searchBarCancelButtonClicked(searchBar: UISearchBar) { searchResult?.view.hidden = true searchBar.resignFirstResponder() } func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { searchResult?.view.hidden = false } func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool { searchResult?.view.hidden = false return true } //// func hidden() //// { //// if !self.searchBarBackground.hidden{ //// UIView.animateWithDuration(0.1, delay: 0, options: .CurveEaseOut, animations: { () -> Void in //// self.searchBar.frame = CGRectMake(0, 0, 50, 50) //// }, completion: { a -> Void in //// self.searchBar.hidden = true //// }) //// UIView.animateWithDuration(0.08, delay: 0, options: .CurveEaseOut, animations: { () -> Void in //// self.searchBarBackground.frame = CGRectMake(0, 0, 50, 50) //// }, completion: { a -> Void in //// self.searchBarBackground.hidden = true //// }) //// } //// } //// //// func show() //// { //// if self.searchBarBackground.hidden //// { //// self.searchBar.hidden = false //// UIView.animateWithDuration(0.1, delay: 0, options: .CurveEaseOut, animations: { () -> Void in //// self.searchBar.frame = CGRectMake(0, 0, UIScreen.width, 50) //// }, completion: { a -> Void in //// self.searchBar.hidden = true //// }) //// self.searchBarBackground.hidden = false //// UIView.animateWithDuration(0.08, delay: 0, options: .CurveEaseOut, animations: { () -> Void in //// self.searchBarBackground.frame = CGRectMake(0, 0, UIScreen.width, 50) //// }, completion: { a -> Void in //// //// }) //// } //// } // func scrollViewDidScroll(scrollView: UIScrollView) // { // if scrollView.contentOffset.y > 200-20 // { // show() // }else{ // hidden() // } // } // func navigationControllerBarPushStyle() -> TFNavigationBarStyle { // return .Transparent // } }<file_sep>/Spottly/SPYViewModelProtocols.swift // // SPYViewModelProtocol.swift // Spottly // // Created by HuangZhigang on 16/3/17. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation <file_sep>/Spottly/SPYPostHeaderView.swift // // SPYPostHeaderView.swift // Spottly // // Created by HuangZhigang on 16/5/16. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import UIKit import RxSwift import Kingfisher import RxCocoa import STPopup import Then import Groot import YYKit import PullToRefresh import MapKit class SPYPostHeaderView: UICollectionReusableView { var bag = DisposeBag() var post: Post? var image = UIImageView().then{ $0.backgroundColor = UIColor.spyGrayColor() } var placeName = UILabel().then{ $0.numberOfLines = 1 $0.text = "PlaceName" $0.textColor = UIColor.spyTextColor() $0.font = UIFont.spyAvenirNextRegular(14) } var locName = UILabel().then{ $0.numberOfLines = 1 $0.text = "LocName" $0.textColor = UIColor.spyTextColor() $0.font = UIFont.spyAvenirNextMedium(12) } var head = UIImageView().then{ $0.backgroundColor = UIColor.brownColor() $0.layer.cornerRadius = 25/2 $0.clipsToBounds = true } var username = UILabel().then{ $0.backgroundColor = UIColor.clearColor() $0.text = "@userName" $0.textColor = UIColor.spyTextColor() $0.font = UIFont.spyAvenirNextRegular(12) } var collectionName = UILabel().then{ $0.backgroundColor = UIColor.clearColor() $0.text = "@collectionName" $0.textColor = UIColor.spyTextColor() $0.font = UIFont.spyAvenirNextRegular(12) } var time = UILabel().then{ $0.backgroundColor = UIColor.clearColor() $0.text = "1d" $0.textAlignment = .Right $0.textColor = UIColor.spyGrayColor() $0.font = UIFont.spyAvenirNextRegular(10) } var from = UILabel().then{ $0.backgroundColor = UIColor.clearColor() $0.text = "From instagram.com/tenpasteleven" $0.textColor = UIColor.spyTextColor() $0.font = UIFont.spyAvenirNextMediumItalic(10) } var msg = YYLabel().then{ $0.backgroundColor = UIColor.clearColor() $0.textColor = UIColor.spyTextColor() $0.font = UIFont.spyAvenirNextRegular(12) $0.text = "Chambray readymade art party tofu stumptown, blue bottle trust fund yuccie neutra. Godard occupy ennui seitan, whatever tumblr jean shorts. Pickled #Paris disappeared." $0.numberOfLines = 0 // $0.layer.borderColor = UIColor.spyGrayColor().CGColor // $0.layer.borderWidth = 1.0 } var comment = YYLabel().then{ $0.backgroundColor = UIColor.clearColor() $0.textColor = UIColor.spyGrayColor() $0.font = UIFont.spyAvenirNextRegular(10) $0.text = "VIEW ALL 5 COMMENTS OR LEAVE A COMMENT" $0.numberOfLines = 1 // $0.layer.borderColor = UIColor.spyGrayColor().CGColor // $0.layer.borderWidth = 1.0 } var quickInfo = UIView() var mapView = MKMapView().then{ $0.userInteractionEnabled = false } var goMap = UIButton().then{ $0.setTitle("Get directions", forState: .Normal) $0.backgroundColor = UIColor.spyBgColor() $0.setTitleColor(UIColor.spyBlackColor(), forState: .Normal) $0.titleLabel!.font = UIFont.spyAvenirNextMedium(12) $0.layer.cornerRadius = 3 } var uberBtn = UIButton().then{ $0.setImage(UIImage(named:"Uber"),forState: .Normal) $0.setTitle("Ride there with Uber", forState: .Normal) $0.backgroundColor = UIColor(rgba: "#0F3846") $0.setTitleColor(UIColor.whiteColor(), forState: .Normal) $0.titleLabel!.font = UIFont.spyAvenirNextMedium(12) $0.layer.cornerRadius = 3 } var msgHeight : ConstraintGroup! var commentHeight : ConstraintGroup! func setupSubviews() { let upline = line() self.addSubviews(image,placeName,locName,upline) constrain(image,placeName,locName,upline){ image,place,loc,line in let box = image.superview! box.width == UIScreen.width image.top == box.top image.left == box.left image.height == box.width image.width == box.width place.top == image.bottom + 10 place.left == image.left + 15 place.right == image.right - 15 loc.top == place.bottom + 1 line.top == loc.bottom + 7 line.height == 1 align(right: place,loc,line) align(left: place,loc,line) } self.addSubviews(head,username,collectionName,time) constrain(upline,head,username,collectionName,time){ line,head,user,collection,time in let box = head.superview! head.top == line.top + 8 head.left == box.left + 15 head.height == 25 head.width == 25 user.top == head.top user.left == head.right + 8 user.width == 200 time.top == user.top time.left == user.right time.right == box.right - 15 collection.left == user.left collection.top == user.bottom + 4 collection.right == box.right - 15 } let downline = line() self.addSubviews(from,msg,comment,downline) constrain(head,from,msg,comment,downline){ head,from,msg,comment,line in let box = head.superview! from.top == head.bottom + 20 from.left == head.left from.right == box.right msg.top == from.bottom + 10 msg.left == box.left + 15 msg.right == box.right - 15 comment.top == msg.bottom + 10 comment.left == msg.left + 10 comment.right == msg.right line.top == comment.bottom + 10 line.right == msg.right + 4 line.left == msg.left - 4 line.height == 1 } msgHeight = constrain(msg) { msg in msg.height == 0 } commentHeight = constrain(comment) { comment in comment.height == 0 } self.addSubview(quickInfo) constrain(downline,quickInfo){ line, info in let box = line.superview! info.top == line.bottom + 10 info.left == box.left + 0 info.right == box.right - 0 info.bottom == box.bottom } quickInfo.addSubviews(mapView,goMap,uberBtn) constrain(quickInfo,mapView,goMap,uberBtn){box, mapView,goMap,uberBtn in mapView.height == 120 mapView.top == box.top mapView.right == box.right mapView.left == box.left mapView.bottom == goMap.top - 10 goMap.right == box.right - 40 goMap.left == box.left + 40 goMap.height == 58 goMap.bottom == uberBtn.top - 10 uberBtn.right == box.right - 40 uberBtn.left == box.left + 40 uberBtn.height == 58 uberBtn.bottom == box.bottom - 10 } self.setNeedsLayout() self.layoutIfNeeded() } override init(frame: CGRect) { super.init(frame: frame) self.setupSubviews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var handlerAfterLayout : HandlerAfterLayout? func configureCell(viewModel:SPYPostHeaderViewModel) { viewModel.postViewModel.ownerFRC!.performFetchIfNeed.rxFetchedObjects .filter{ $0.count > 0 } .subscribeNext{ [unowned self] (fetchedObjects) -> Void in let owner = fetchedObjects.first as? User self.username.text = owner?.uid ?? "" if let head = owner?.head?.sizeIs(){ self.head.kf_setImageWithURL(NSURL(string:head)!) } }.addDisposableTo(self.bag) viewModel.postViewModel.postFRC!.performFetchIfNeed.rxFetchedObjects .filter{ $0.count > 0 } .subscribeNext{ [unowned self] (fetchedObjects) -> Void in let post = fetchedObjects.first as! Post self.post = post var message = post.message // message = "Chambray readymade art party tofu stumptown, blue bottle trust fund yuccie neutra. Godard occupy ennui seitan, whatever tumblr jean shorts. Pickled #Paris disappeared." self.image.kf_setImageWithURL(NSURL(string: post.imageUrl!.sizeIs(.post))!) let Coordinate = CLLocationCoordinate2DMake(self.post!.latitude!.doubleValue, self.post!.longitude!.doubleValue) self.mapView.addAnnotation(SPYAnnotation(coordinate: Coordinate )) self.mapView.setRegion(MKCoordinateRegionMakeWithDistance(Coordinate, 2000, 2000), animated: true) self.mapView.centerCoordinate = Coordinate self.collectionName.text = post.collection?.name self.placeName.text = post.place?.name ?? "还是不行" self.locName.text = post.place?.address ?? "还是不行" let attributedText = NSMutableAttributedString(string: message! ,attributes: [NSFontAttributeName :UIFont.spyAvenirNextRegular(12), NSForegroundColorAttributeName:UIColor.spyTextColor()]) let userRangs = attributedText.string.parse(userRegexp) let tagRangs = attributedText.string.parse(tagRegexp) let urlRangs = attributedText.string.parse(urlRegexp) _ = userRangs.map{ range in attributedText.setTextHighlightRange(range, color: UIColor.spyLogoColor(), backgroundColor: UIColor.spyLogoColor(), tapAction: { (_, attributedString, _, _) -> Void in let string = attributedString.string print("user: \(string.substringWithNSRange(NSMakeRange(range.location + 1, range.length - 1) ))") }) } _ = tagRangs.map{ range in attributedText.setTextHighlightRange(range, color: UIColor.spyLogoColor(), backgroundColor: UIColor.spyLogoColor(), tapAction: { (_, attributedString, _, _) -> Void in let string = attributedString.string print("tag: \(string.substringWithNSRange(NSMakeRange(range.location + 1, range.length - 1) ))") }) } _ = urlRangs.map{ range in attributedText.setTextHighlightRange(range, color: UIColor.spyLogoColor(), backgroundColor: UIColor.spyLogoColor(), tapAction: { (_, attributedString, _, _) -> Void in let string = attributedString.string print("url: \(string.substringWithNSRange(NSMakeRange(range.location + 1, range.length - 1) ))") }) } self.msg.attributedText = attributedText let size = CGSizeMake(self.msg.frame.width, CGFloat.max) let layout = YYTextLayout(containerSize: size, text: attributedText) constrain(self.msg, replace: self.msgHeight) { msg in msg.height == layout!.textBoundingSize.height; } constrain(self.comment, replace: self.commentHeight) { comment in comment.height == (true ? 20 : 0) ; } let sizee = self.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize); if let hand = self.handlerAfterLayout{ hand!(sizee) } }.addDisposableTo(self.bag) } } <file_sep>/Spottly/SPYPostCell.swift // // SPYPostCell.swift // Spottly // // Created by HuangZhigang on 16/1/15. // Copyright © 2016年 Spottly. All rights reserved. // import UIKit import RxCocoa import RxSwift import YYKit class SPYPostCell : UICollectionViewCell { private var disposeBag = DisposeBag() var head = UIImageView().then{ $0.backgroundColor = UIColor.grayColor() $0.layer.cornerRadius = 25/2 } var username = UILabel().then{ $0.backgroundColor = UIColor.clearColor() $0.text = "@userName" $0.textColor = UIColor.spyTextColor() $0.font = UIFont.spyAvenirNextRegular(12) } var collectionName = UILabel().then{ $0.backgroundColor = UIColor.clearColor() $0.text = "@collectionName" $0.textColor = UIColor.spyTextColor() $0.font = UIFont.spyAvenirNextRegular(12) } var time = UILabel().then{ $0.backgroundColor = UIColor.clearColor() $0.text = "1d" $0.textColor = UIColor.spyGrayColor() $0.font = UIFont.spyAvenirNextRegular(10) } var image = UIImageView().then{ $0.backgroundColor = UIColor.grayColor() } var msg = YYLabel().then{ $0.backgroundColor = UIColor.clearColor() $0.textColor = UIColor.spyTextColor() $0.font = UIFont.spyAvenirNextRegular(12) $0.text = "msg msg msg msg msg msg msg msg msg " $0.numberOfLines = 0 // $0.layer.borderColor = UIColor.brownColor().CGColor // $0.layer.borderWidth = 2.0 } var placeName = UILabel().then{ $0.numberOfLines = 1 $0.text = "PlaceName" $0.textColor = UIColor.spyGrayColor() $0.font = UIFont.spyAvenirNextMedium(14) } var locName = UILabel().then{ $0.numberOfLines = 1 $0.text = "LocName" $0.textColor = UIColor.spyGrayColor() $0.font = UIFont.spyAvenirNextMedium(12) } var star = UILabel().then{ $0.text = "✨✨✨✨✨✨" $0.numberOfLines = 1 $0.backgroundColor = UIColor.clearColor() } //矫情(),乏味(),关心不必要 private var like = UIButton().then{ $0.setImage(UIImage(named: "likeIcon"),forState:.Normal) $0.backgroundColor = UIColor.clearColor() } private var comment = UIButton().then{ $0.setImage(UIImage(named: "commentIcon"),forState:.Normal) $0.backgroundColor = UIColor.clearColor() } private var share = UIButton().then{ $0.setImage(UIImage(named: "sendIcon"),forState:.Normal) $0.backgroundColor = UIColor.clearColor() } private var more = UIButton().then{ $0.setImage(UIImage(named: "moreInfo"),forState:.Normal) $0.backgroundColor = UIColor.clearColor() } private var save = UIButton().then{ $0.setTitle("Save", forState: .Normal) $0.setTitleColor(UIColor.spyBlueColor(), forState: .Normal) $0.setTitleColor(UIColor.spyDisabledColor(), forState: .Disabled) $0.setTitleColor(UIColor.whiteColor(), forState: .Highlighted) $0.titleLabel!.font = UIFont.spyHelveticaNeueRegular(12) $0.backgroundColor = UIColor.clearColor() $0.layer.borderWidth = 1 $0.layer.borderColor = UIColor.spyBlueColor().CGColor $0.layer.cornerRadius = 3 } override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.whiteColor() save .rx_observe(Bool.self , "highlighted") .subscribeNext { [unowned self] (highlighted) -> Void in self.save.backgroundColor = highlighted! ? UIColor.spyBlueColor() : UIColor.clearColor() }.addDisposableTo(disposeBag) self.addSubviews(head,username,collectionName,time) constrain(head,username,collectionName,time){ head,user,collection,time in let box = head.superview! user.top == box.top + 8 user.left == head.right + 10 align(left: user,collection) align(right: user,collection) collection.top == user.bottom collection.bottom == head.bottom + 10 - 8 time.right == box.right - 16 align(centerY: head,time) user.right == time.left - 8 } time.setContentHuggingPriority(UILayoutPriorityDefaultHigh, forAxis: UILayoutConstraintAxis.Horizontal) let upline = line() self.addSubviews(image,placeName,locName,upline) constrain(head,image,placeName,locName,upline){head,image,place,loc ,line in let box = head.superview! head.top == box.top + 10 head.left == box.left + 10 head.width == 25 head.height == 25 image.top == head.bottom + 10 image.left == box.left image.width == box.width image.height == image.width place.top == image.bottom + 10 place.left == image.left + 15 place.right == image.right - 15 loc.top == place.bottom + 1 line.top == loc.bottom + 7 line.height == 1 align(right: place,loc,line) align(left: place,loc,line) } let downline = line() self.addSubviews(upline,star,msg,downline,like) constrain(upline,star,msg,downline,like){upline,star,msg,downline,like in let box = upline.superview! align(left: upline,star,msg,downline,like) align(right: upline,star,msg,downline) distribute(by: 6, vertically: upline,star,msg) distribute(by: 16, vertically: msg,downline,like) downline.height == 1 like.bottom == box.bottom - 16 like.height == 25 like.width == 25 } msg.setContentHuggingPriority(UILayoutPriorityDefaultLow-1, forAxis: .Vertical) self.addSubviews(comment,share,more,save) constrain(like,comment,share,more,save){ like,comment,share,more,save in let box = like.superview! distribute(by: 20, leftToRight: like,comment,share,more) align(centerY: like,comment,share,more,save) like.size == comment.size like.size == share.size like.size == more.size save.height == 30 save.width == 90 save.right == box.right - 10 } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { // self.layer.borderColor = UIColor.brownColor().CGColor // self.layer.borderWidth = 2.0 } }<file_sep>/Spottly/SPYExploreCategoreView.swift // // FirstViewController.swift // Spottly // // Created by HuangZhigang on 15/12/4. // Copyright © 2015年 Spottly. All rights reserved. // import UIKit import RxSwift import CoreData import RxCocoa import TFTransparentNavigationBar import PullToRefresh import ObjectiveC class SPYExploreCategoreView: UIViewController { // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() configureDataSourceForPlace() configureNavBar() configureSearchBar() configureCollection() doMenuAction(.Place(.Hot)) } override func viewWillAppear(animated: Bool) { } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.navigationItem.titleView = self.searchBar self.searchBar.alpha = 0.0 } override func viewWillDisappear(animated: Bool) { self.navigationController?.navigationBar.lt_reset() self.navigationItem.titleView = nil } func reloadLayout() { guard let layout = self.collection.collectionViewLayout as? CSStickyHeaderFlowLayout else{ return } layout.parallaxHeaderReferenceSize = CGSizeMake(UIScreen.width,200); layout.parallaxHeaderMinimumReferenceSize = CGSize(width: UIScreen.width, height: 199) layout.itemSize = CGSizeMake(UIScreen.width, layout.itemSize.height); layout.headerReferenceSize = CGSize(width: UIScreen.width, height: SPYSortBarHeight) layout.footerReferenceSize = CGSize(width: UIScreen.width, height: 40) layout.spyHeaderAddedOrginY = 64 } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } func configureNavBar(){ self.navigationController?.navigationBar.barStyle = .Black self.navigationController?.navigationBar.lt_setBackgroundColor(UIColor.clearColor()) self.navigationController?.navigationBar.shadowImage = UIImage() self.collection.rx_contentOffset.asDriver().driveNext { (offset) in if offset.y > 64 { var alpha = min(1, 1 - ((64 + 64 - offset.y) / 64)) self.navigationController?.navigationBar.lt_setBackgroundColor(UIColor.spyLogoColor().colorWithAlphaComponent(alpha)) self.searchBar.alpha = alpha }else{ self.navigationController?.navigationBar.lt_setBackgroundColor(UIColor.spyLogoColor().colorWithAlphaComponent(0)) self.searchBar.alpha = 0 } }.addDisposableTo(disposeBag) } func configureSearchBar() { self.searchResult = SPYSearchResultView(searchBar: searchBar) self.searchBar.rx_delegate.setForwardToDelegate(self, retainDelegate: false) searchResult?.view.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.height - 64 - 49) self.view.addSubviews(searchResult!.view) searchResult?.view.hidden = true } func configureCollection() { self.reloadLayout() self.view.addSubviews(collection) self.view.backgroundColor = UIColor.whiteColor() self.collection.backgroundColor = UIColor.whiteColor() constrain(self.view,collection){ box,collection in collection.top == box.top collection.left == box.left collection.right == box.right collection.bottom == box.bottom - 48 } self.collection.clipsToBounds = false // let refresher = PullToRefresh() // self.collection.addPullToRefresh(refresher) {[weak self] () -> () in // delay(2, closure: { () -> () in // self?.collection.endRefreshing() // }) // } self.collection.registerClass(SPYExploreCategorieViewParallaxHeader.self, forSupplementaryViewOfKind: CSStickyHeaderParallaxHeader, withReuseIdentifier: "SPYExploreCategorieViewParallaxHeader") self.collection.registerClass(SPYSortHeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "SPYSortHeaderView") collection.registerClass(SPYMoreFooterView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "SPYMoreFooterView") collection.rx_contentOffset .asDriver() .filter{ UIScrollView.needMore(self.collection, offset: $0) } .throttle(0.2) .driveNext { [weak self] point in self?.doMore() }.addDisposableTo(disposeBag) } // MARK: - DataSource func configureDataSourceForPlace() { let dataSource = RxCollectionViewSectionedReloadDataSource<SPYExplorePlaceSection>() dataSource.cellFactory = { (cv, ip, item)in let cell = cv.dequeueReusableCellWithReuseIdentifier("SPYPlaceCell", forIndexPath: ip) as! SPYPlaceCell cell.configureCell(item) return cell } dataSource.supplementaryViewFactory = { [unowned dataSource,unowned self] (cv, kind, ip) in if kind == UICollectionElementKindSectionHeader{ if self.header == nil { self.header = cv.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SPYSortHeaderView", forIndexPath: ip) as? SPYSortHeaderView self.header?.configureCell(dataSource.sectionAtIndex(ip.section).model.menuItems) self.header?.delegate = self } return self.header! }else if kind == CSStickyHeaderParallaxHeader{ if self.parallaxHeader == nil { self.parallaxHeader = cv.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SPYExploreCategorieViewParallaxHeader", forIndexPath: ip) as? SPYExploreCategorieViewParallaxHeader self.parallaxHeader?.configureCell(dataSource.sectionAtIndex(ip.section).model) } return self.parallaxHeader! }else { if self.footer == nil { self.footer = cv.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SPYMoreFooterView", forIndexPath: ip) as? SPYMoreFooterView } return self.footer! } } self.dataSourceForPlace = dataSource } func doMore() { self.footer?.startAnimating() self.viewModel?.placesFRC?.loadMore() } // MARK: - Property var header : SPYSortHeaderView? var footer : SPYMoreFooterView? var parallaxHeader : SPYExploreCategorieViewParallaxHeader? var collection = SPYCollectionViewSubClass.spyRegisterClass(SPYPlaceCell.self,SPYCollectionCell.self) var dataSourceForPlace : RxCollectionViewSectionedReloadDataSource<SPYExplorePlaceSection>! var layout : CSStickyHeaderFlowLayout{ return self.collection.collectionViewLayout as!CSStickyHeaderFlowLayout } var disposeBag = DisposeBag() var bag = DisposeBag() var searchInputing : Driver<Void>? var searchResult : SPYSearchResultView? var searchBar = SPYSearchBar().then{ $0.alpha = 0 $0.tintColor = UIColor.spyLogoColor() $0.barTintColor = UIColor.spyLogoColor() $0.showsCancelButton = false } var viewModel : SPYExploreViewModel? { didSet{ // spyLoadViewIfNeeded() // doMenuAction(.Post(.Hot)) } } var searchBarBackground = UIView().then{ $0.frame = CGRectMake(0,0,50,50) $0.backgroundColor = UIColor.whiteColor() $0.hidden = true } } extension SPYExploreCategoreView : SPYMenuActionDelegate{ func headerFlowLayout() -> CSStickyHeaderFlowLayout { return self.collection.collectionViewLayout as! CSStickyHeaderFlowLayout } func doMenuAction(menuAction:SPYMenuAction) { self.bag = DisposeBag() self.searchBar.resignFirstResponder() switch menuAction { case .Place(_) : let headerViewModel = SPYExploreHeaderViewModel(rx_category: viewModel!.rx_category, mainCategory: viewModel!.mainCategory, menuItems: viewModel!.menuItems) let items = viewModel!.placesFRC!.performFetchIfNeed.rxFetchedObjects.asDriver() Driver.combineLatest(Driver.just(headerViewModel),items) { h,items in return [SPYExplorePlaceSection(model: h, items: items as! [Place])] } .drive(self.collection.rx_itemsWithDataSource(dataSourceForPlace)) .addDisposableTo(bag) self.collection .rx_itemSelected.asDriver() .driveNext{ [weak self] indexPath in let c = mainStoryboard().instantiateViewControllerWithIdentifier("SPYPostView") as! SPYPostView let place = self!.dataSourceForPlace.itemAtIndexPath(indexPath) let post = (place as! Place).relatedPost c.viewModel = SPYPostViewModel(input:post!) self!.navigationController?.pushViewController(c, animated: true) } .addDisposableTo(bag) layout.spyConfigureLayoutForPlaces() SPYScrollMenuHeaderToTop(self.header,collection:self.collection ,layout:self.layout) SPYObserveRequestState(self.collection, frc: viewModel?.placesFRC, dataType: .Place, bag: bag) default: break } } } extension SPYExploreCategoreView : UISearchBarDelegate{ func searchBarCancelButtonClicked(searchBar: UISearchBar) { searchResult?.view.hidden = true searchBar.resignFirstResponder() } func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { searchResult?.view.hidden = false } func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool { searchResult?.view.hidden = false return true } }<file_sep>/Spottly/SwiftURL.swift import Foundation // Creates URLPathSegmentAllowedCharacterSet same as URLPathAllowedCharacterSet - "/" private func _createURLPathSegmentAllowedCharacterSet() -> NSCharacterSet { let pathSegmentCharacterSet = NSCharacterSet .URLPathAllowedCharacterSet() .mutableCopy() as! NSMutableCharacterSet pathSegmentCharacterSet.removeCharactersInString("/") return pathSegmentCharacterSet } // Global var with URLPathSegmentAllowedCharacterSet to reduce private let _URLPathSegmentAllowedCharacterSet = _createURLPathSegmentAllowedCharacterSet() private func _pathSegmentsToPath(segments: [AnyObject]?) -> String? { guard let segments = segments else { return nil } return segments.map { $0.description .stringByAddingPercentEncodingWithAllowedCharacters(_URLPathSegmentAllowedCharacterSet) ?? $0.description }.joinWithSeparator("/") } // Encode complex key/value objects in NSRULQueryItem pairs private func _queryItems(key: String, _ value: AnyObject?) -> [NSURLQueryItem] { var result = [] as [NSURLQueryItem] if let dictionary = value as? [String: AnyObject] { for (nestedKey, value) in dictionary { result += _queryItems("\(key)[\(nestedKey)]", value) } } else if let array = value as? [AnyObject] { let arrKey = key + "[]" for value in array { result += _queryItems(arrKey, value) } } else if let _ = value as? NSNull { result.append(NSURLQueryItem(name: key, value: nil)) } else { result.append(NSURLQueryItem(name: key, value: value?.description)) } return result } // Encodes complex [String: AnyObject] params into array of NSURLQueryItem private func _paramsToQueryItems(params: [String: AnyObject]?) -> [NSURLQueryItem]? { guard let params = params else { return nil } var result = [] as [NSURLQueryItem] for (key, value) in params { result += _queryItems(key, value) } return result.sort({ $0.name < $1.name }) } public extension NSURLComponents { // MARK: path as String @nonobjc convenience init(path: String, query: String?, fragment: String? = nil) { self.init() self.path = path self.query = query self.fragment = fragment } @nonobjc convenience init(path: String, queryItems: [NSURLQueryItem]?, fragment: String? = nil) { self.init() self.path = path self.queryItems = queryItems self.fragment = fragment } @nonobjc convenience init(path: String, query: [String: AnyObject]?, fragment: String? = nil) { self.init() self.path = path self.queryItems = _paramsToQueryItems(query) self.fragment = fragment } // MARK: path as array of segments @nonobjc convenience init(path segments: [AnyObject]?, query: String?, fragment: String? = nil) { self.init() self.percentEncodedPath = _pathSegmentsToPath(segments) self.query = query self.fragment = fragment } @nonobjc convenience init(path segments: [AnyObject]?, query: [String: AnyObject]?, fragment: String? = nil) { self.init() self.percentEncodedPath = _pathSegmentsToPath(segments) self.queryItems = _paramsToQueryItems(query) self.fragment = fragment } } public extension NSURL { @nonobjc static func build(baseURL: NSURL? = nil, components: NSURLComponents) -> NSURL? { return components.URLRelativeToURL(baseURL)?.absoluteURL } @nonobjc final func build(components: NSURLComponents) -> NSURL? { return components.URLRelativeToURL(self)?.absoluteURL } @nonobjc static func build(baseURL: NSURL? = nil, path: String, query: String, fragment: String? = nil) -> NSURL? { return build(baseURL, components: NSURLComponents(path: path, query: query, fragment: fragment)) } @nonobjc final func build(path: String, query: String, fragment: String? = nil) -> NSURL? { return build(NSURLComponents(path: path, query: query, fragment: fragment)) } @nonobjc static func build(baseURL: NSURL? = nil, path: String, query: [String: AnyObject]? = nil, fragment: String? = nil) -> NSURL? { return build(baseURL, components: NSURLComponents(path: path, query: query, fragment: fragment)) } @nonobjc final func build(path: String, query: [String: AnyObject]? = nil, fragment: String? = nil) -> NSURL? { return build(NSURLComponents(path: path, query: query, fragment: fragment)) } @nonobjc static func build(baseURL: NSURL? = nil, path: [AnyObject]? = nil, query: String, fragment: String? = nil) -> NSURL? { return build(baseURL, components: NSURLComponents(path: path, query: query, fragment: fragment)) } @nonobjc final func build(path: [AnyObject]? = nil, query: String, fragment: String? = nil) -> NSURL? { return build(NSURLComponents(path: path, query: query, fragment: fragment)) } @nonobjc static func build(baseURL: NSURL? = nil, path: [AnyObject]? = nil, query: [String: AnyObject]? = nil, fragment: String? = nil) -> NSURL? { return build(baseURL, components: NSURLComponents(path: path, query: query, fragment: fragment)) } @nonobjc final func build(path: [AnyObject]? = nil, query: [String: AnyObject]? = nil, fragment: String? = nil) -> NSURL? { return build(NSURLComponents(path: path, query: query, fragment: fragment)) } @nonobjc static func build(scheme scheme: String?, host: String? = nil, port: UInt? = nil, path: String, query: [String: AnyObject]? = nil, fragment: String? = nil) -> NSURL? { let components = NSURLComponents(path: path, query: query, fragment: fragment) components.scheme = scheme components.host = host components.port = port return components.URL } @nonobjc static func build(scheme scheme: String?, host: String? = nil, port: UInt? = nil, path: [AnyObject]? = nil, query: [String: AnyObject]? = nil, fragment: String? = nil) -> NSURL? { let components = NSURLComponents(path: path, query: query, fragment: fragment) components.scheme = scheme components.host = host components.port = port return components.URL } } <file_sep>/ViewModel放一切非UIKit可重用逻辑.md view model是一个放置用户输入验证逻辑,视图显示逻辑,发起网络请求和其他各种各样的代码的极好的地方。有一件事情不应归入view model,那就是任何视图本身的引用。view model的概念同时适用于于iOS和OS X。(换句话说,不要在view model中使用 #import UIKit.h) 由于展示逻辑(presentation logic)放在了view model中(比如model的值映射到一个格式化的字符串),视图控制器本身就会不再臃肿。当你开始使用MVVM的最好方式是,可以先将一小部分逻辑放入视图模型,然后当你逐渐习惯于使用这个范式的时候再迁移更多的逻辑到视图模型中。 以前在Controller中又有 业务逻辑(network,verification,action)和表示逻辑(loaction/city/country)在里面. 而这些在版本迭代更新中是可以继续保留的可以把他们留下啦。他们是最适合放在ViewModel中的 ViewModel是MVVM架构中最重要的部分,ViewModel中包含属性,命令,方法,事件,属性验证等逻辑。为了与View以及Model更好的交互来满足MVVM架构,ViewModel的设计需要注意一些事项或者约束: ViewModel的属性:ViewModel的属性是View数据的来源。这些属性可由三部分组成: 一部分是Model的复制属性。 另一部分用于控制UI状态。例如一个弹出窗口的控件可能有一个IsClose的属性,当操作完成时可以通过这个属性更改通知View做相应的UI变换或者后面提到的事件通知。 第三部分是一些方法的参数,可以将这些方法的参数设置成相应的属性绑定到View中的某个控件,然后在执行方法的时候获取这些属性,所以一般方法不含参数。 ViewModel的命令:ViewModel中的命令用于接受View的用户输入,并做相应的处理。我们也可以通过方法实现相同的功能。 ViewModel的事件: ViewModel中的事件主要用来通知View做相应的UI变换。它一般在一个处理完成之后触发,随后需要View做出相应的非业务的操作。所以一般ViewModel中的事件的订阅者只是View,除非其他自定义的非View类之间的交互。 ViewModel的方法:有些事件是没有直接提供命令调用的,如自定义的事件。这时候我们可以通过CallMethodAction来调用ViewModel中的方法来完成相应的操作。 View Model一般有以下三个部分组成   1、属性:一个事物,它的类型可以是一个字符型,也可以是一个对象。实现接口INotifyPropertyChanged,那么任何UI元素绑定到这个属性,不管这个属性什么时候改变都能自动和UI层交互。   2、集合:事物的集合,它的类型一般是ObservableCollection,因此,任何UI元素绑定到它,不管这个集合什么时候改变,都可以自动的与UI交互。<file_sep>/Spottly/SPYIncrementalStore.swift // // File.swift // SpottlyCoreData // // Created by HuangZhigang on 15/3/30. // Copyright (c) 2015年 Spottly. All rights reserved. // //每次从Store取出来时Object会记录一个"Store里的数据"快照。当被保存时会查看那个Store里的值和当时的快照对比,如果相同,代表从取出来这个Object到保存。这期间这个Store里相应的值没有被改变过。所以可以成功保存新的数据,执行保存操作。但是如果不同。那么代表这个Store被其他Moc更改了。保存操作将停止,产生一个冲突。这个冲突可以由预先设计的merge策略来解决。NSMergeByPropertyStoreTrumpMergePolicy 取Store里的。NSMergeByPropertyObjectTrumpMergePolicy取新的内存里的。 import Foundation import CoreData import Groot import Alamofire public func cacheLog(items: Any..., separator: String = "|", terminator: String = "\n") { // print("\n\n-----------------------缓存信息-----------------------") // SPYLog().debug(items) // print("-----------------------------------------------\n\n\n") } public func netWorkLog(items: Any..., separator: String = "|", terminator: String = "\n") { // print("\n\n-----------------------网络返回结果-----------------------") // SPYLog().info(items) // print("-----------------------------------------------\n\n\n") } public func fetchLog(items: Any...,isBackContext:Bool = false, separator: String = "|", terminator: String = "\n") { // let msg = isBackContext ? "后台搜索结果" : "前台搜索结果" // print("\n\n-----------------------\(msg)-----------------------") // SPYLog().info(items) // print("-----------------------------------------------\n\n\n") } enum SPYIncrementalStoreError : ErrorType { case NotFoundRelationshipInBackingStore case NotFoundIDInBackingStore case RequestError } typealias InsertOrUpdateCompletion = (managedObjects:AnyObject, backingObjects:AnyObject) -> Void // swiftlint:disable type_body_length class SPYIncrementalStore : NSIncrementalStore{ private let nodeCache = NSCache() private let valueCache = NSCache() private let backingObjectIDCache = NSCache() private let backingRelationShipsCache = NSCache() class var storeType: String { return NSStringFromClass(SPYIncrementalStore.self) } override class func initialize() { NSPersistentStoreCoordinator.registerStoreClass(self, forStoreType:self.storeType) let _ = SPYIncrementalStoreValueTransformer() } override func loadMetadata() throws { let uuid = NSProcessInfo.processInfo().globallyUniqueString self.metadata = [NSStoreTypeKey : SPYIncrementalStore.storeType, NSStoreUUIDKey: uuid] } override init(persistentStoreCoordinator root: NSPersistentStoreCoordinator?, configurationName name: String?, URL url: NSURL, options: [NSObject : AnyObject]?) { self.nodeCache.name = "Node缓存" self.valueCache.name = "Value缓存" self.backingObjectIDCache.name = "BackObjectID缓存";//? self.backingRelationShipsCache.name = "BackRelation缓存";//? self.nodeCache.countLimit = 300;//1000 self.valueCache.countLimit = 300;//1000 self.backingObjectIDCache.countLimit = 300;//? self.backingRelationShipsCache.countLimit = 300;//? self.nodeCache.delegate = cacheDelegate self.valueCache.delegate = cacheDelegate self.backingObjectIDCache.delegate = cacheDelegate self.backingRelationShipsCache.delegate = cacheDelegate super.init(persistentStoreCoordinator: root, configurationName: name, URL: url, options: options) } lazy var backingPersistentStoreCoordinator: NSPersistentStoreCoordinator = { let coordinator = NSPersistentStoreCoordinator(managedObjectModel: CoreDataManager.sharedManager.managedObjectModel) coordinator.name = "SPYBackCoordinator" var error: NSError? = nil let storeType = NSSQLiteStoreType let url = NSURL.applicationDocumentsDirectory().URLByAppendingPathComponent("SpottlyCoreData.sqlite") let options = [NSMigratePersistentStoresAutomaticallyOption: NSNumber(bool: true), NSInferMappingModelAutomaticallyOption: NSNumber(bool: true)]; do { try coordinator.addPersistentStoreWithType(storeType, configuration: nil, URL: url, options: options) #if !(TARGET_OS_EMBEDDED) let url = NSURL.applicationDocumentsDirectory().URLByAppendingPathComponent("SpottlyCoreData.sqlite").absoluteString let modelFilePath = NSBundle.mainBundle().URLForResource("SpottlyCoreData", withExtension: "momd")!.absoluteString let project:NSDictionary = [ "storeFilePath": url, "storeFormat" : NSNumber(integer: 1), "modelFilePath": modelFilePath, "v" : "1" ] let projectFile = "/users/huangzhigang/desktop/\(NSBundle.mainBundle().infoDictionary![kCFBundleNameKey as String]!).cdp" project.writeToFile(projectFile, atomically: true) #endif } catch var error1 as NSError { error = error1 if let code = error?.code { if code == NSMigrationMissingMappingModelError { SPYLog().error("Error, migration failed. Delete model at \(url)") } else { SPYLog().error("Error creating persistent store: \(error?.description)") } } abort() } catch { fatalError() } return coordinator }() /// The managed object context for the backing store lazy var backingManagedObjectContext: NSManagedObjectContext = { let context = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.PrivateQueueConcurrencyType) context.persistentStoreCoordinator = self.backingPersistentStoreCoordinator context.undoManager = nil context.name = "后台MOC" context.retainsRegisteredObjects = true return context }() override func executeRequest(request: NSPersistentStoreRequest, withContext context: NSManagedObjectContext?) throws -> AnyObject { if request.requestType == .FetchRequestType { return try self.executeFetchRequest(request, withContext: context) }else if request.requestType == .SaveRequestType{ return try self.executeSaveRequest(request, withContext: context) }else{ fatalError("NOT SUPPORTS BatchUpdateRequestType") } } func executeFetchRequest(request: NSPersistentStoreRequest!, withContext context: NSManagedObjectContext!) throws -> [AnyObject] { print("executeFetchRequest - Thread Info : \(NSThread.currentThread())") // if context === SPYMainMoc() // { // if let fetchRequest = request as? SPYFetchRequest where fetchRequest.ignore == true // { // print("SPYMainMoc todo executeFetchRequest : \(fetchRequest)") // return [] // } // } var fetchRequest = request.copy() as! NSFetchRequest if let fetchRequest = request as? SPYFetchRequest where fetchRequest.containHttpRequest { self.fetchRemoteObjectsWithRequest(fetchRequest, context: context) } if fetchRequest.resultType == .ManagedObjectResultType { var (managedObjects ,noMoreFetch) = executeFetchRequestInIDCache(&fetchRequest, toContext: context) if noMoreFetch{ return managedObjects } do { managedObjects += try executeFetchRequestInBack(fetchRequest.copy() as! NSFetchRequest, toContext: context) }catch{ SPYLog().error("error \(error)") } fetchLog(managedObjects) return managedObjects; }else if fetchRequest.resultType == .ManagedObjectIDResultType{ var (managedObjectIDs ,noMoreFetch) = executeFetchRequestInIDCache(&fetchRequest, toContext: context,isManagedObjectID:true) if noMoreFetch{ return managedObjectIDs } do { managedObjectIDs += try executeFetchRequestInBack(fetchRequest.copy() as! NSFetchRequest, toContext: context, isManagedObjectID:true) }catch{ SPYLog().error("error \(error)") } fetchLog(managedObjectIDs) return managedObjectIDs; }else if fetchRequest.resultType == .CountResultType || fetchRequest.resultType == .DictionaryResultType { do { return try backingManagedObjectContext.executeFetchRequest(fetchRequest)//huang- } catch { throw SPYIncrementalStoreError.RequestError } }else{ return [] } } func executeFetchRequestInIDCache(inout request:NSFetchRequest, toContext context:NSManagedObjectContext , isManagedObjectID:Bool = false)-> (result:[AnyObject],noMoreFetch:Bool) //managedObjectIDs 全部捕获到 { var result = [AnyObject]() var noMoreFetch = false if request.isIDFetch() { let IDs = request.IDsInFetch() var missIDs = Set<String>() let _ = IDs.map({ (ID) -> Void in let key = self.newObjectIDForEntity(request.entity!, referenceObject: ID) if let _ = self.backingObjectIDCache.objectForKey(key){ if isManagedObjectID{ result.append(key) }else{ result.append(context.objectWithID(key)) } }else{ missIDs.insert(ID) } }) if missIDs.isEmpty{ noMoreFetch = true }else{ request.updateIDsInFetch(missIDs) } } return (result,noMoreFetch) } func executeFetchRequestInBack(request:NSFetchRequest, toContext context:NSManagedObjectContext , isManagedObjectID:Bool = false) throws -> [AnyObject] { print("executeFetchRequestInBack - Thread Info : \(NSThread.currentThread())") var results = NSArray() let backMOC = backingManagedObjectContext backMOC.performBlockAndWait({ () -> Void in request.entity = NSEntityDescription.entityForName(request.entityName!, inManagedObjectContext: backMOC) request.resultType = .DictionaryResultType do { results = try backMOC.executeFetchRequest(request)//huang- }catch{ SPYLog().error("error \(error)") } fetchLog(results, isBackContext: true) self.valueCache.insertValues(results as! [NSDictionary]) }) let spyIDKey = request.entity!.spyIDKey let IDs = results.valueForKeyPath(spyIDKey) as! [NSString] let managedObjects = IDs.map({ (ID: NSString) -> AnyObject in // self.contextIDMaps.insert(ID as String) let moID = self.newObjectIDForEntity(request.entity!, referenceObject: ID) if isManagedObjectID{ return moID; }else{ return context.objectWithID(moID); } }) return managedObjects } override func newValuesForObjectWithID(objectID: NSManagedObjectID, withContext context: NSManagedObjectContext) throws -> NSIncrementalStoreNode { print("newValuesForObjectWithID - Thread Info : \(NSThread.currentThread())") if let node = nodeFromCache(objectID) { return node } else if let backManangedObject = self.backingDictionaryWithSPYID(objectID) { self.valueCache.insertValues([backManangedObject]) let node = nodeFromCache(objectID) if node == nil { print("node : \(node)") } return node! } else { SPYLog().warning("newValuesForObjectWithID : nodeCache缓存和backContext中都没找到:\(objectID)\n") throw SPYIncrementalStoreError.NotFoundIDInBackingStore } } override func newValueForRelationship(relationship: NSRelationshipDescription, forObjectWithID objectID: NSManagedObjectID, withContext context: NSManagedObjectContext?) throws -> AnyObject { print("newValueForRelationship - Thread Info : \(NSThread.currentThread())") let referenceObject = self.referenceObjectForObjectID(objectID) as! String var relationShipObjectID = backingRelationShipsCache.objectForKey(referenceObject+relationship.name) if relationShipObjectID != nil { return relationShipObjectID! } guard let backObjectID = self.backingObjectIDWithSPYID(objectID) else { throw SPYIncrementalStoreError.NotFoundIDInBackingStore } self.backingManagedObjectContext.performBlockAndWait { () -> Void in let backManagedObject = self.backingManagedObjectContext.objectWithID(backObjectID) // if backManagedObject.fault { // 是否可靠 // self.valueCache.insertValues([backManagedObject.attributeValues]) // } if let relationShipObject = backManagedObject.valueForKey(relationship.name) as? NSManagedObject { if let referenceObject = relationShipObject.spyID { relationShipObjectID = self.newObjectIDForEntity(relationship.destinationEntity!, referenceObject: referenceObject) self.backingRelationShipsCache.setObject(relationShipObjectID!, forKey: referenceObject+relationship.name) }else{ SPYLog().warning("newValueForRelationship 从后台中查找 \(backManagedObject.entity.name) 的 \(relationship.name) 这个关系是一个没有 ID \n") } }else{ SPYLog().warning("newValueForRelationship 从后台中查找\(backManagedObject.entity.name) 的 \(relationship.name) 关系是 nil \n") } } if relationShipObjectID != nil { return relationShipObjectID! }else{ throw SPYIncrementalStoreError.NotFoundIDInBackingStore } } func backingDictionaryWithSPYID(objectID: NSManagedObjectID)->NSDictionary? { print("backingDictionaryWithSPYID - Thread Info : \(NSThread.currentThread())") let fetchRequest = NSFetchRequest(entityName: objectID.entity.name!) fetchRequest.resultType = NSFetchRequestResultType.DictionaryResultType fetchRequest.fetchLimit = 1 fetchRequest.includesSubentities = false fetchRequest.returnsObjectsAsFaults = false let refObj = self.referenceObjectForObjectID(objectID) as! NSString let predicate = NSPredicate(format: "%K = %@",objectID.entity.spyIDKey,refObj) fetchRequest.predicate = predicate var results: [AnyObject]? = nil let privateContext = self.backingManagedObjectContext privateContext.performBlockAndWait(){ do{ results = try privateContext.executeFetchRequest(fetchRequest) } catch let error as NSError { SPYLog().error(error) } } return results?.last as? NSDictionary } func backingObjectIDWithSPYID(objectID: NSManagedObjectID)->NSManagedObjectID? { var backingObjectId: NSManagedObjectID? = backingObjectIDCache.objectForKey(objectID) as? NSManagedObjectID if backingObjectId != nil { return backingObjectId } print("backingObjectIDWithSPYID - Thread Info : \(NSThread.currentThread())") let fetchRequest = NSFetchRequest(entityName: objectID.entity.name!) fetchRequest.resultType = NSFetchRequestResultType.ManagedObjectIDResultType fetchRequest.fetchLimit = 1 let predicate = NSPredicate(format: "%K = %@",objectID.entity.spyIDKey, self.referenceObjectForObjectID(objectID) as! String) fetchRequest.predicate = predicate let privateContext = self.backingManagedObjectContext privateContext.performBlockAndWait() { do { let results = try privateContext.executeFetchRequest(fetchRequest) backingObjectId = results.last as? NSManagedObjectID } catch { SPYLog().error(error) } } if backingObjectId != nil { backingObjectIDCache.setObject(backingObjectId!, forKey: objectID) } return backingObjectId } func insertOrUpdateObjects(result: [AnyObject]?, fetchRequest request: SPYFetchRequest, context: NSManagedObjectContext, completion: InsertOrUpdateCompletion) -> Bool { print("insertOrUpdateObjects 0 - Thread Info : \(NSThread.currentThread())") guard let jsons = result else{ return false } netWorkLog(jsons) if let jsons = jsons as? [NSDictionary] { var managedObjects = [NSManagedObject]() var backingObjects = Set<NSManagedObject>() let backingContext = self.backingManagedObjectContext backingContext.performBlockAndWait(){ do { try objectsWithEntityName(request.entity!.name!, fromJSONArray: jsons, inContext: backingContext) backingObjects = backingContext.updatedObjects.union(backingContext.insertedObjects) print("insertOrUpdateObjects 1 - Thread Info : \(NSThread.currentThread())") }catch{ SPYLog().error("程鹏 给我的JSON 不对 \(error)") } } context.performBlockAndWait({ () -> Void in do{ managedObjects = try objectsWithEntityName(request.entity!.name!, fromJSONArray: jsons, inContext: context) print("insertOrUpdateObjects 2 - Thread Info : \(NSThread.currentThread())") if request.entity!.name! == "Spot" { _ = managedObjects.map{ (managedObject) -> Void in if let spot = managedObject as? Post { if let url = request.httpInfo?["URL"] { spot.relatedUrl = spot.relatedUrl + "\(url) " // spot.relatedUrl = "timeline" } } } } }catch{ SPYLog().error("程鹏 给我的JSON 不对 \(error)") } }) completion(managedObjects: managedObjects, backingObjects: backingObjects) } return true } func fetchRemoteObjectsWithRequest(fetchRequest: SPYFetchRequest, context: NSManagedObjectContext) -> Void { print("fetchRemoteObjectsWithRequest - Thread Info : \(NSThread.currentThread())") let responseHandler: (NSDictionary -> Void) = {(json) in context.performBlockAndWait(){ print("responseHandler - Thread Info : \(NSThread.currentThread()) ") print("responseHandler - context :: \(context)") let childContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType) childContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy childContext.parentContext = context childContext.name = "网络返回处理数据的子MOC"//隔离数据的作用 childContext.performBlockAndWait(){ print("childContext.performBlockAndWait - Thread Info : \(NSThread.currentThread()) ") print("childContext.performBlockAndWait - childContext :: \(childContext) ") var objects : [AnyObject] if let slice: AnyObject = json.objectForKey("slice") { objects = slice as! [AnyObject] }else{ objects = [json] } self.insertOrUpdateObjects(objects, fetchRequest: fetchRequest, context: childContext, completion:{(managedObjects: AnyObject, backingObjects: AnyObject) -> Void in print("insertOrUpdateObjects - Thread Info : \(NSThread.currentThread()) ") self.backingManagedObjectContext.performBlockAndWait() {//AndWait print("backingManagedObjectContext.performBlockAndWait - Thread Info : \(NSThread.currentThread()) ") self.backingManagedObjectContext.saveOrLogError() let caches = (backingObjects as! Set<NSManagedObject>).map({ mo -> NSDictionary in let ID = self.newObjectIDForEntity(mo.entity, referenceObject: mo.valueForKey(mo.spyIDKey!)!) self.backingObjectIDCache.setObject(mo.objectID, forKey: ID) return mo.attributeValues }) self.valueCache.insertValues(caches) self.nodeCache.updateNodes(caches) } do { let childObjects = childContext.registeredObjects as NSSet try childContext.obtainPermanentIDsForObjects(childObjects.allObjects as! [NSManagedObject]) }catch{ SPYLog().error(error) fatalError("获得永久ID时发生错误") } print("childContext.saveOrLogError(1)") childContext.saveOrLogError() print("childContext.saveOrLogError(2)") context.performBlockAndWait() { print("context.performBlockAndWait - Thread Info : \(NSThread.currentThread()) ") let _ = childContext.registeredObjects.map({ (obj: AnyObject) -> Void in let childObject = obj as! NSManagedObject let parentObject = context.objectWithID(childObject.objectID) context.refreshObject(parentObject, mergeChanges: true)//合并内存里的新值,不然在childcontext里修改并提交,parentcontext里是看不到的,只能看到他原来的内存中的值。//huang? 也不对,因为child的save之后改变会自动提交到parent里。为何这里又重新刷新一次。如果不是父子关系。那确实应该 }) } }) } } } let url = fetchRequest.httpInfo?["URL"] as! String let method = fetchRequest.httpInfo?["METHOD"] as! String if method == "GET"{ let beign = NSDate() Alamofire.request(.GET, url) .response(queue: dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), completionHandler: { (request, response, data, error) -> Void in print("Alamofire.response - Thread Info : \(NSThread.currentThread()) ") print("MarkTime : \(NSDate().timeIntervalSinceDate(beign)*1000)ms\n") if let data = data { let JSON = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) fetchRequest.httpState = JSON as? [String : AnyObject] guard fetchRequest.isSuccess else { fetchRequest.errorHandleBlock?(); return } responseHandler(JSON as! NSDictionary) } }) } } /* func insertedObjectsForBackingContext(managedObjects : NSSet) { managedObjects.enumerateObjectsUsingBlock { (object, spot) -> Void in let managedObject = object as! NSManagedObject let backingContext = self.backingManagedObjectContext let json = JSONDictionaryFromObject(managedObject) do { try GRTJSONSerialization.objectWithEntityName(managedObject.entity.name!, fromJSONDictionary: json, inContext: backingContext) as? NSManagedObject } catch { } } } func deletedObjectsForBackingContext(managedObjects : NSSet) { managedObjects.enumerateObjectsUsingBlock { (object, spot) -> Void in let managedObject = object as! NSManagedObject let fetchRequest = NSFetchRequest(entityName: managedObject.entity.name!) fetchRequest.resultType = NSFetchRequestResultType.ManagedObjectResultType fetchRequest.fetchLimit = 1 fetchRequest.includesSubentities = false let predicate = NSPredicate(format: "%K = %@",managedObject.spyIDKey!,managedObject.spyID!) fetchRequest.predicate = predicate var error: NSError? = nil var results: [AnyObject]? = nil let privateContext = self.backingManagedObjectContext privateContext.performBlockAndWait(){ do { results = try privateContext.executeFetchRequest(fetchRequest) } catch let error1 as NSError { error = error1 results = nil } catch { fatalError() } let backingManagedObject = results?.first as! NSManagedObject privateContext.deleteObject(backingManagedObject) } } } func updatedObjectsForBackingContext(managedObjects : NSSet) { managedObjects.enumerateObjectsUsingBlock { (object, spot) -> Void in let managedObject = object as! NSManagedObject print(managedObject.objectID); print(managedObject.entity.userInfo); var url = managedObject.entity.userInfo?["URL"] as! String let index = url.startIndex.advancedBy(23) url = url.substringFromIndex(index) let json = JSONDictionaryFromObject(managedObject) as NSDictionary SPYHTTPSession.share.PUT(url, parameters: json, success: { (task, JSON) -> Void in do { try GRTJSONSerialization.objectWithEntityName(managedObject.entity.name!, fromJSONDictionary: json as! [NSObject:AnyObject], inContext: self.backingManagedObjectContext) } catch{ } self.backingManagedObjectContext.performBlockAndWait() { self.backingManagedObjectContext.saveOrLogError() } managedObject.managedObjectContext!.performBlockAndWait() { managedObject.managedObjectContext!.refreshObject(managedObject, mergeChanges: true) } }, failure: { (task, error) -> Void in print("cao : error\(error)") }); } } */ func executeSaveRequest(request: NSPersistentStoreRequest!, withContext context: NSManagedObjectContext!) throws -> AnyObject { //仅仅处理 deletedObjects // self.updatedObjectsForBackingContext(context.updatedObjects); // self.deletedObjectsForBackingContext(context.deletedObjects); // self.insertedObjectsForBackingContext(context.insertedObjects); // print("executeSaveRequest context:\(context)") // self.backingManagedObjectContext.performBlockAndWait { () -> Void in // let objectSet = context.updatedObjects.union(context.insertedObjects) // let _ = objectSet.map { (mo) -> Void in // do{ // if let name = mo.entity.name where name == "Spot" { // mo.setValue("", forKey: "relatedUrl") // } // try objectWithEntityName(mo.entity.name!, fromJSONDictionary: mo.attributeValues as! JSONDictionary, inContext: self.backingManagedObjectContext) // }catch{ // fatalError("咋回事!前台的对象没有在数据库里面?") // } // } // self.backingManagedObjectContext.saveOrLogError(); // } //看来只能在ManagedObject里发送请求。并从服务器 刷新 修改后的数据回来。再更新本地。 //操作全都放到ManagedObject里 把修改好的ManagedObject save下来。同步跟backPresisXX保存 //上层可以传下来deletedObjects/insertedObjects/updatedObjects 同步修改backPresisXX // put 执行N次结果一样 作用在一个资源上 客户端已知ID // api[@"me"] 增加列表 // like[@"edit"][@"href"] like a spot // list[@"edit"][@"href"] creat a list // spot[@"edit"][@"href"] creat a spot // follow[@"edit"][@"href"] follow a user/list // post 有很多 login不用管 作用在一个集合上(类型) 由服务器生产新ID // api[@"list"] 增加列表 // api[@"uploader"] 上传图片 // api[@"blob"] 上传视频 // api[@"places"] 上传地点 // spot[@"repost"][@"href"] 转发 // spot[@"share"][@"href"] 分享 // place[@"me"][@"href"] 上传spot // delect logout不用管 // list[@"edit"][@"href"] // like[@"edit"][@"href"] // spot[@"edit"][@"href"] // follow[@"edit"][@"href"] /* println("context.updatedObjects\(context.updatedObjects)") println("context.insertedObjects\(context.insertedObjects)") println("context.deletedObjects\(context.deletedObjects)") println("context.registeredObjects\(context.registeredObjects)") */ return true } override func obtainPermanentIDsForObjects(array: [NSManagedObject]) throws -> [NSManagedObjectID] { let moids = array.map { (mo : NSManagedObject) -> NSManagedObjectID in if mo.objectID.temporaryID { return self.newObjectIDForEntity(mo.entity, referenceObject: mo.spyID!) }else{ return mo.objectID } } return moids } func nodeFromCache(objectID:NSManagedObjectID)->NSIncrementalStoreNode? { let spyID = self.referenceObjectForObjectID(objectID) as! String if let node = nodeCache.objectForKey(spyID) { cacheLog("\(nodeCache.name) 捕获到 \(objectID.entity.name!) :\(spyID)\n") return node as? NSIncrementalStoreNode } if let nodeValue = valueCache.objectForKey(spyID) as? [NSObject:AnyObject] { cacheLog("\(valueCache.name) 捕获到 \(objectID.entity.name!) :\(spyID)\n") let node = NSIncrementalStoreNode(objectID: objectID, withValues: nodeValue as! [String : AnyObject] , version: UInt64(1)) nodeCache.setObject(node, forKey: spyID) cacheLog("\(nodeCache.name) 添加了 \(objectID.entity.name!) :\(spyID)\n") return node }else{ cacheLog("\(valueCache.name)和\(nodeCache.name) 没找到 \(objectID.entity.name!) : \(spyID)\n") return nil } } // override func managedObjectContextDidRegisterObjectsWithIDs(objectIDs: [NSManagedObjectID]) { // print("managedObjectContextDidRegisterObjectsWithIDs \(objectIDs.count) beign: \n---------------------------------------------\n \(objectIDs)\n---------------------------------------------managedObjectContextDidRegisterObjectsWithIDs end\n") // super.managedObjectContextDidRegisterObjectsWithIDs(objectIDs) // } // // override func managedObjectContextDidUnregisterObjectsWithIDs(objectIDs: [NSManagedObjectID]) { // print("managedObjectContextDidUnregisterObjectsWithIDs \(objectIDs.count) beign: \n---------------------------------------------\n \(objectIDs)\n---------------------------------------------managedObjectContextDidUnregisterObjectsWithIDs end\n") // super.managedObjectContextDidUnregisterObjectsWithIDs(objectIDs) // } } extension NSEntityDescription { var spyIDKey : String{ get{ let attributes = self.attributesByName as NSDictionary let keys = attributes.allKeys as NSArray return keys.containsObject("id") ? "id":"href" } } } func lookFor(obj:AnyObject,geter:(NSDictionary) -> Void) { if let array = obj as? NSArray { for item in array { lookFor(item,geter: geter) } }else if let dict = obj as? NSDictionary { geter(dict) for (_ , v) in dict { lookFor(v,geter: geter) } } } public func attributeValuesFrom(dict:NSDictionary)-> [NSDictionary] { var end = [NSDictionary]() let getAttributeValues = {(dict:NSDictionary) -> Void in let attributeValues = NSMutableDictionary() for ( k , v ) in dict { if (v is NSDictionary) || (v is NSArray){ }else{ attributeValues.setObject(v, forKey: k as! String) } } end.append(attributeValues) } lookFor(dict,geter: getAttributeValues) return end } func cachesFrom(jsons:[NSDictionary])->[NSDictionary] { var caches = [NSDictionary]() jsons.map { (json) -> Void in let attributeValues = attributeValuesFrom(json) caches.appendContentsOf(attributeValues) } return caches } extension NSDictionary{ var spyID : String? { get{ if let Id = self.objectForKey("id") as? String{ return Id }else{ if let href = self.objectForKey("href") as? String{ return href }else{ assertionFailure("SPYIncrementalStoreException-NO id||href in SPYSourceDataDictionary") return nil } } } } } extension NSManagedObject{ var attributeValues : [NSObject : AnyObject]{ get { var dictValue = [NSObject : AnyObject]() for attributeName in self.entity.attributesByName.keys { if let attributeValue = self.valueForKey(attributeName) { dictValue[attributeName] = attributeValue; } } return dictValue } } var spyIDKey : String?{ get{ let keys = self.entity.attributesByName.keys //huang .array if keys.contains("id") { return "id" }else if keys.contains("href") { return "href" }else{ assertionFailure("SPYIncrementalStoreException-NO id||href in NSManagedObject") return nil } } } var spyID : String?{ get { if let id = self.valueForKey(self.spyIDKey!) as? String { return id }else { fatalError("\(self) \n这个对象 没有找到 ID") return nil } } } } extension NSManagedObjectContext { func saveOrLogError() -> Void { // guard self.hasChanges == true else { return } do { try self.save() } catch { fatalError("error saving context: \(error)") } } } extension NSCache { func insertValues(values: [NSDictionary]) { let _ = values.map { (value) -> Void in if let spyID = value.spyID { ///------- if let _ = self.objectForKey(spyID) { cacheLog("\(self.name) 更新了 \(spyID) \n") }else{ cacheLog("\(self.name) 添加了 \(spyID) \n") } ///------- self.setObject(value, forKey: spyID) } } } func updateNodes(nodeValues: [NSDictionary]) { let _ = nodeValues.map { (value) -> Void in if let spyID = value.spyID , node = self.objectForKey(spyID) { (node as! NSIncrementalStoreNode).updateWithValues(value as! [String : AnyObject], version: node.version)//huang cacheLog("\(self.name) 更新了:\(spyID) \n") } } } } extension NSFetchRequest { func isIDFetch() -> Bool { guard let format = self.predicate?.predicateFormat else { return false } return format .containsString(" IN {\"") } func IDsInFetch() -> Set<String> { let string = self.predicate!.predicateFormat as NSString let beign = NSMaxRange(string.rangeOfString("IN {\"")) let end = string.rangeOfString("\"}").location guard beign != NSNotFound && end != NSNotFound else { return [] } let IDString = string.substringWithRange(NSRange(location: beign,length: end - beign)) as NSString let IDs = IDString.componentsSeparatedByString("\", \"") as [String] var IDsSet = Set<String>() let _ = IDs.map { (ID) -> Void in IDsSet.insert(ID) } return IDsSet } func updateIDsInFetch(IDs:Set<String>) -> NSFetchRequest { let string = self.predicate!.predicateFormat as NSString let beign = string.rangeOfString(" IN {\"").location guard beign == NSNotFound else { return self } let spyKey = string.substringToIndex(beign) self.predicate = NSPredicate(format: "%K IN %@", spyKey, IDs) return self } } let cacheDelegate = SPYCacheDelegate() class SPYCacheDelegate : NSObject , NSCacheDelegate { func cache(cache: NSCache, willEvictObject obj: AnyObject) { cacheLog("\(cache.name) 清除 \(obj)") } } // swiftlint:enable type_body_length <file_sep>/Spottly/SPYSNSLogin.swift // // SPYSNSLogin.swift // Spottly // // Created by HuangZhigang on 16/3/6. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import RxSwift import RxCocoa import CoreData import Groot import FBSDKLoginKit <file_sep>/Spottly/SPYSortHeaderView.swift // // SPYMenuHeaderCell.swift // Spottly // // Created by HuangZhigang on 16/4/26. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import RxSwift class SPYSortHeaderView: UICollectionReusableView { var disposeBag = DisposeBag() var menuItems = [SPYMenuAction]() let sort = SPYSortBar(items: []) var delegate : SPYMenuActionDelegate? override init(frame: CGRect) { super.init(frame: frame) self.addSubview(sort) constrain(self,sort) { box,sort in sort.top == box.top sort.right == box.right sort.left == box.left sort.height == SPYSortBarHeight } self.backgroundColor = UIColor.whiteColor() self.sort .rx_selectedSegment .asObservable() .subscribeNext({ [weak self] (maybeAction) in guard let sortAction = maybeAction else{ return } let action = SPYMenuAction.fixItem((self?.menuItems.first!)!, type: sortAction) self?.delegate?.doMenuAction(action!) }).addDisposableTo(disposeBag) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() } func configureCell(menuItems:[SPYMenuAction]){ self.menuItems = menuItems self.sort.items = SPYMenuAction.subItems(menuItems,mainItem:menuItems.first!) } } <file_sep>/Spottly/SPYRegisterView.swift // // SPYRegisterFaceBook.swift // Spottly // // Created by HuangZhigang on 16/2/23. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import RxSwift import RxCocoa import UIKit import CoreData import FBSDKLoginKit import Groot class SPYRegisterView: UIViewController { var disposeBag = DisposeBag() var snsLoginViewModel : SPYSNSLoginViewModel! var emailLoginViewModel: SPYEmailLoginViewModel! var snsBtn = UIButton().then{ if inChina { $0.setTitle("Sign in with Wechat", forState: .Normal) $0.backgroundColor = UIColor(rgba: "#2dc100") }else{ $0.setTitle("Sign in with Facebook", forState: .Normal) $0.backgroundColor = UIColor(rgba: "#0f228d") } $0.setTitleColor(UIColor.whiteColor(), forState: .Normal) $0.titleLabel!.font = UIFont.spyAvenirNextMedium(12) $0.layer.cornerRadius = 3 } var userNameField = UITextField().then{ $0.placeholder = "email" $0.layer.borderWidth = 1 $0.layer.borderColor = UIColor.spyTextColor().CGColor $0.layer.cornerRadius = 3 } var passwordField = UITextField().then{ $0.placeholder = "<PASSWORD>" $0.layer.borderWidth = 1 $0.layer.borderColor = UIColor.spyTextColor().CGColor $0.layer.cornerRadius = 3 } var register = UIButton().then{ $0.setTitle("Register", forState: .Normal) $0.setTitleColor(UIColor.whiteColor(), forState: .Normal) $0.titleLabel!.font = UIFont.spyAvenirNextMedium(12) $0.backgroundColor = UIColor.spyTextColor() $0.layer.cornerRadius = 3 } func setupViews() { let logo = UIImageView(image: UIImage(named: "Logo")!) let title = UILabel().then{ $0.text = "Welcome to the community that's finding the world's best places." $0.textAlignment = .Center $0.backgroundColor = UIColor.clearColor() $0.font = UIFont.spyAvenirNextRegular(16) $0.textColor = UIColor.spyTextColor() $0.numberOfLines = 0 } let snsText = UILabel().then{ $0.text = "We will never post anything without your permission" $0.backgroundColor = UIColor.clearColor() $0.font = UIFont.spyAvenirNextRegular(10) $0.textColor = UIColor.spyTextColor() $0.numberOfLines = 1 } let emailTitle = UILabel().then{ $0.text = "REGISTER WITH EMAIL" $0.textAlignment = .Center $0.backgroundColor = UIColor.clearColor() $0.font = UIFont.spyAvenirNextRegular(10) $0.textColor = UIColor.spyTextColor() $0.numberOfLines = 0 } self.view.addSubviews(logo,title,snsBtn,snsText,emailTitle,userNameField,passwordField,register) constrain(logo,title,snsBtn,snsText){ logo,title,snsBtn,snsText in let box = logo.superview! logo.top == box.top + 37 logo.height == 30 logo.width == 90 logo.centerX == box.centerX title.top == logo.bottom title.left == box.left + 16 title.right == box.right - 16 title.bottom == snsBtn.top snsBtn.left == title.left snsBtn.width == title.width snsBtn.height == 40 snsText.top == snsBtn.bottom + 7 snsText.left == title.left snsText.width == title.width } title.setContentHuggingPriority(UILayoutPriorityDefaultLow, forAxis: UILayoutConstraintAxis.Vertical) constrain(snsText,emailTitle,userNameField,passwordField,register){ snsText,emailTitle,userName,password,register in let box = snsText.superview! emailTitle.top == snsText.bottom + 20 emailTitle.left == box.left + 12 emailTitle.right == box.right - 12 emailTitle.bottom == userName.top - 30 userName.left == box.left + 35 userName.right == box.right - 35 userName.height == 35 userName.bottom == password.top - 10 password.left == userName.left password.right == userName.right password.height == 35 password.bottom == register.top - 20 register.left == box.left + 16 register.right == box.right - 16 register.height == 40 register.bottom == box.bottom - 5 } self.view.setNeedsLayout() self.view.layoutIfNeeded() } override func viewDidLoad() { setupViews() emailLoginViewModel = SPYEmailLoginViewModel(input: (username: userNameField.rx_text.asDriver(), password: <PASSWORD>Field.rx_text.asDriver(), loginTaps: self.register.rx_tap.asDriver()), api: Spottly.API) emailLoginViewModel.signedIn.driveNext{[weak self] loginResult in if let user = loginResult.user { SPYUserViewModel.shareMe.isMe = true SPYUserViewModel.shareMe.input = user self?.popupController?.dismiss() }else{ switch loginResult.statusCode { case 404 : DefaultWireframe.presentAlert("404") case 999 : DefaultWireframe.presentAlert("No Wifi") default : DefaultWireframe.presentAlert("default") } } }.addDisposableTo(disposeBag) snsLoginViewModel = SPYSNSLoginViewModel( input: ( facebookTap: (inChina ? UIButton():snsBtn).rx_tap.asObservable(), sinaTap: UIButton().rx_tap.asObservable(), wechatTap: (inChina ? snsBtn:UIButton()).rx_tap.asObservable()), dependency: ( loginApi: Spottly.API, sns:RxSNS.sharedSNS ) ) (inChina ? snsLoginViewModel.tokenOK_wechat : snsLoginViewModel.tokenOK_fb).subscribe(onNext: { (B) -> Void in print("tokenOK_fb : \(B)") }, onError: { (error) -> Void in print("tokenOK_fb -error : \(error)") }) { () -> Void in }.addDisposableTo(self.disposeBag) //huang sina wechat snsLoginViewModel.spyLoginOK.subscribe(onNext: { (B) -> Void in print("spyLoginOK : \(B)") }, onError: { (er) -> Void in print("spyLoginOK - er : \(er)") switch er as! SPYLoginError { case .UsernameConflict : DefaultWireframe.presentAlert("UsernameConflict") case .Unknown : DefaultWireframe.presentAlert("Unknow") case .NoInternet : DefaultWireframe.presentAlert("NoInternet") default : DefaultWireframe.presentAlert("default") } }, onCompleted: { () -> Void in }) { () -> Void in } .addDisposableTo(self.disposeBag) snsLoginViewModel.userInfoOK.observeOn(MainScheduler.instance).subscribe(onNext: { (LoginResult) -> Void in print("userInfoOK : \(LoginResult)") SPYUserViewModel.shareMe.isMe = true SPYUserViewModel.shareMe.input = LoginResult.user self.popupController?.dismiss() }, onError: { (er) -> Void in }, onCompleted: { () -> Void in }) { () -> Void in } .addDisposableTo(self.disposeBag) } }<file_sep>/Spottly/NSURL+Directories.swift // // NSURL+Directories.swift // Palettes // // Created by <NAME> on 12/17/14. // Copyright (c) 2014 <NAME>. All rights reserved. // import Foundation extension NSURL { class func applicationDocumentsDirectory() -> NSURL { let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls [urls.count - 1] } } extension NSURL { var queryItems: [String: String]? { return NSURLComponents(URL: self, resolvingAgainstBaseURL: false)? .queryItems? .reduce([:], combine: { (var params: [String: String], item) -> [String: String] in params[item.name] = item.value return params }) } } extension Dictionary { // return (components.map { "\($0)=\($1)" } as [String]).joinWithSeparator("&") var queryString:String? { return (self.map { "\($0)=\($1)" } as [String]).joinWithSeparator("&") } }<file_sep>/Spottly/SPYBaseModel/Categorie.swift // // Categorie.swift // Spottly // // Created by HuangZhigang on 16/5/10. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import CoreData class Categorie: NSManagedObject { var cityName = "" // Insert code here to add functionality to your managed object subclass } <file_sep>/Spottly/SPYBaseModel/User.swift // // ME.swift // // // Created by HuangZhigang on 15/6/30. // // import Foundation import CoreData import AFNetworking @objc(User) public class User: NSManagedObject { class func idFR(id: String) -> SPYFetchRequest { let fr = SPYFetchRequest() fr.entity = NSEntityDescription.entityForName("User", inManagedObjectContext: SPYMainMoc()) fr.predicate = NSPredicate(format: "id = %@",id) fr.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)] return fr } func userFR() -> SPYFetchRequest { let fr = SPYFetchRequest() // let method = SPYRouter.User(id).method.rawValue // let path = SPYRouter.User(id).fullPath // fr.httpInfo = ["METHOD" : method , "URL" : path] fr.entity = NSEntityDescription.entityForName("User", inManagedObjectContext:SPYMainMoc()) fr.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)] fr.predicate = NSPredicate(format: "id = %@",self.id) return fr } func placesFR() -> SPYFetchRequest { let fr = SPYFetchRequest() fr.entity = NSEntityDescription.entityForName("Place", inManagedObjectContext:SPYMainMoc()) let path = SPYRouter.PlacesFromUser(id) .fullPath .orderBy(.CreateTime(.Desc)) let method = SPYRouter.PlacesFromUser(id).method.rawValue fr.httpInfo = ["METHOD" : method , "URL" : path] fr.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)] fr.predicate = NSPredicate(format: "relatedUrl CONTAINS %@",path) return fr } func postsFR() -> SPYFetchRequest { let fr = SPYFetchRequest() fr.entity = NSEntityDescription.entityForName("Post", inManagedObjectContext:SPYMainMoc()) let method = SPYRouter.PostsFromUser(userid: id).method.rawValue let path = SPYRouter.PostsFromUser(userid: id).fullPath fr.httpInfo = ["METHOD" : method , "URL" : path] fr.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)] fr.predicate = NSPredicate(format: "owner.id = %@",id) return fr } func collectionsFR() -> SPYFetchRequest { let fr = SPYFetchRequest() fr.entity = NSEntityDescription.entityForName("Collection", inManagedObjectContext:SPYMainMoc()) let method = SPYRouter.CollectionsFromUser(id).method.rawValue let path = SPYRouter.CollectionsFromUser(id).fullPath fr.httpInfo = ["METHOD" : method , "URL" : path] fr.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)] fr.predicate = NSPredicate(format: "owner.id = %@",id) return fr } // class func meFR(id: String) -> SPYFetchRequest // { // let fr = SPYFetchRequest() // fr.entity = NSEntityDescription.entityForName("User", inManagedObjectContext: SPYMainMoc()) // fr.predicate = NSPredicate(format: "id = 95258845708299") // fr.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)] // return fr // } func notificationFR() -> SPYFetchRequest { let fr = SPYFetchRequest() fr.entity = NSEntityDescription.entityForName("Notification", inManagedObjectContext:SPYMainMoc()) let url = "http://staging.spottly.com:6666/users/me/notifications" fr.httpInfo = ["METHOD" : "GET" , "URL" : url] fr.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)] fr.predicate = NSPredicate(format: "receiverid = %@",self.id) return fr } func feedFR() -> SPYFetchRequest { let fr = SPYFetchRequest() fr.entity = NSEntityDescription.entityForName("Post", inManagedObjectContext:SPYMainMoc()) let method = SPYRouter.TimeLine.method.rawValue let path = SPYRouter.TimeLine.fullPath fr.httpInfo = ["METHOD" : method , "URL" : path] fr.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)] fr.predicate = NSPredicate(format: "relatedUrl CONTAINS %@",path) return fr } func followingUsersFR() -> SPYFetchRequest { let fr = SPYFetchRequest() fr.entity = NSEntityDescription.entityForName("Follow", inManagedObjectContext:SPYMainMoc()) let method = SPYRouter.FollowingToUser(self.id).method.rawValue let path = SPYRouter.FollowingToUser(self.id).fullPath fr.httpInfo = ["METHOD" : method , "URL" : path] fr.predicate = NSPredicate(format: "from.id == %@",self.id) fr.relationshipKeyPathsForPrefetching = ["to"] fr.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)] return fr } func followersFR() -> SPYFetchRequest { let fr = SPYFetchRequest() fr.entity = NSEntityDescription.entityForName("Follow", inManagedObjectContext:SPYMainMoc()) let method = SPYRouter.FollowerFromUser(self.id).method.rawValue let path = SPYRouter.FollowerFromUser(self.id).fullPath fr.httpInfo = ["METHOD" : method , "URL" : path] fr.predicate = NSPredicate(format: "from.id == %@",self.id) fr.relationshipKeyPathsForPrefetching = ["to"] fr.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)] return fr } func followingColloctionsFR() -> SPYFetchRequest { let fr = SPYFetchRequest() fr.entity = NSEntityDescription.entityForName("Collectionfollowing", inManagedObjectContext:SPYMainMoc()) fr.relationshipKeyPathsForPrefetching = ["Collection"] let method = SPYRouter.FollowedCollections(self.id).method.rawValue let path = SPYRouter.FollowedCollections(self.id).path fr.httpInfo = ["METHOD" : method , "URL" : path] fr.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)] fr.predicate = NSPredicate(format: "user.id = %@",self.id) return fr } // func CurthreadMocSpotsFR() -> SPYFetchRequest // { // let fr = SPYFetchRequest() // fr.entity = NSEntityDescription.entityForName("Post", inManagedObjectContext:SPYWorkMoc()) // // fr.httpInfo = ["METHOD" : "GET" , "URL" : self.spots!.href!] // fr.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)] // fr.predicate = NSPredicate(format: "user.id = %@",self.id) // return fr // } func likesFR() -> SPYFetchRequest { let fr = SPYFetchRequest() fr.entity = NSEntityDescription.entityForName("Like", inManagedObjectContext:SPYMainMoc()) let method = SPYRouter.Likes(self.id).method.rawValue let path = SPYRouter.Likes(self.id).path fr.httpInfo = ["METHOD" : method , "URL" : path] // fr.httpInfo = ["METHOD" : "GET" , "URL" : self.likes!.href!] fr.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)] fr.predicate = NSPredicate(format: "user.id = %@",self.id) return fr } } <file_sep>/Spottly/SPYBaseModel/SPYFetchSection.swift // // SPYFetchSection.swift // SpottlyCoreData // // Created by HuangZhigang on 15/10/12. // Copyright © 2015年 Spottly. All rights reserved. // import Foundation import CoreData class SPYFetchSection:NSObject, NSFetchedResultsControllerDelegate{ var managedObjectContext: NSManagedObjectContext? var sectionNameKeyPath: String? var cacheName: String? var controller : NSFetchedResultsController? var fetch : SPYFetchRequest? var otherFetch : SPYFetchRequest? init(fetch:SPYFetchRequest , otherFetch:SPYFetchRequest , managedObjectContext: NSManagedObjectContext, sectionNameKeyPath: String?, cacheName: String?, fetchBlock:(NSFetchedResultsController)->Void) { self.controller = NSFetchedResultsController(fetchRequest: fetch, managedObjectContext: managedObjectContext, sectionNameKeyPath: sectionNameKeyPath, cacheName: cacheName) self.otherFetch = otherFetch; self.fetch = fetch; self.managedObjectContext = managedObjectContext; self.sectionNameKeyPath = sectionNameKeyPath self.cacheName = cacheName } func performFetch() { do{ self.controller!.delegate = self; try controller!.performFetch() }catch{ } } func controllerDidChangeContent(controller: NSFetchedResultsController) { if controller.fetchRequest == self.fetch{ print("controller.fetchRequest :\(controller.fetchedObjects?.description)") print("controller.fetchRequest : \(controller.fetchedObjects?.count)") }else if controller.fetchRequest == self.otherFetch { } } } <file_sep>/Spottly/SPYBaseModel/Post.swift // // Post.swift // Spottly // // Created by HuangZhigang on 16/2/1. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import CoreData @objc(Post) class Post: NSManagedObject { } extension Post { func ownerFR()-> SPYFetchRequest { let fr = SPYFetchRequest() fr.entity = NSEntityDescription.entityForName("User", inManagedObjectContext: SPYMainMoc()) let path = SPYRouter.User(self.owner!.id) .fullPath let method = SPYRouter.User(self.owner!.id).method.rawValue fr.httpInfo = ["METHOD" : method , "URL" : path] fr.predicate = NSPredicate(format: "id = %@",self.owner!.id) fr.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)] return fr } // func placeFR() -> SPYFetchRequest // { // let fr = SPYFetchRequest() // fr.entity = NSEntityDescription.entityForName("Place", inManagedObjectContext: SPYMainMoc()) // fr.predicate = NSPredicate(format: "id = %@",self.place!.id) // fr.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)] // return fr // } func selfFR() -> SPYFetchRequest { let fr = SPYFetchRequest() fr.entity = NSEntityDescription.entityForName("Post", inManagedObjectContext: SPYMainMoc()) fr.predicate = NSPredicate(format: "id = %@",self.id) fr.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)] return fr } var imageUrl : String? { let maybeImageMedias = self.medias!.filter{ (maybeMedia) -> Bool in guard let media = maybeMedia as? Media else{ return false } return media.mimeType!.hasPrefix("image") } guard let media = maybeImageMedias.first as? Media else{ return nil } return media.storePath! } }<file_sep>/Spottly/SPYVideoProgressBar.swift // // SPYVideoProgressBar.swift // Spottly // // Created by HuangZhigang on 16/4/13. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation protocol SPYVideoProgressBarProtocol { func finish()->Void } class SPYVideoProgressBar: UIView { var stack = [NSTimeInterval]([0.0]) var max = NSTimeInterval(15.0) var min = NSTimeInterval(3.0) var new = NSTimeInterval(0.0) { didSet{ if self.total + new >= max{ new = max - self.total } push(new) } } func start() { } func finish() { } var isEnough : Bool { return total > min } var safeTime :NSTimeInterval{ return max - total } var total : NSTimeInterval{ return stack.reduce(0, combine: +) } func push(time:NSTimeInterval)->Void { if total < max{ stack.append(time) } } func pop()-> NSTimeInterval { if stack.count > 0 { return stack.removeLast() }else{ return 0.0 } } func reLayout() { } }<file_sep>/Spottly/Controller成对应组件仅负责展示.md Controller在MVVM中,一方面负责View和ViewModel之间的绑定,另一方面也负责常规的UI逻辑处理。 getter和setter全部都放在最后 因为一个ViewController很有可能会有非常多的view,就像上面给出的代码样例一样,如果getter和setter写在前面,就会把主要逻辑扯到后面去,其他人看的时候就要先划过一长串getter和setter,这样不太好。然后要求业务工程师写代码的时候按照顺序来分配代码块的位置,先是life cycle,然后是Delegate方法实现,然后是event response,然后才是getters and setters。这样后来者阅读代码时就能省力很多。 每一个delegate都把对应的protocol名字带上,delegate方法不要到处乱写,写到一块区域里面去 比如UITableViewDelegate的方法集就老老实实写上#pragma mark - UITableViewDelegate。这样有个好处就是,当其他人阅读一个他并不熟悉的Delegate实现方法时,他只要按住command然后去点这个protocol名字,Xcode就能够立刻跳转到对应这个Delegate的protocol定义的那部分代码去,就省得他到处找了。 event response专门开一个代码区域 所有button、gestureRecognizer的响应事件都放在这个区域里面,不要到处乱放。 关于private methods,正常情况下ViewController里面不应该写 不是delegate方法的,不是event response方法的,不是life cycle方法的,就是private method了。对的,正常情况下ViewController里面一般是不会存在private methods的,这个private methods一般是用于日期换算、图片裁剪啥的这种小功能。这种小功能要么把它写成一个category,要么把他做成一个模块,哪怕这个模块只有一个函数也行。 ViewController基本上是大部分业务的载体,本身代码已经相当复杂,所以跟业务关联不大的东西能不放在ViewController里面就不要放。另外一点,这个private method的功能这时候只是你用得到,但是将来说不定别的地方也会用到,一开始就独立出来,有利于将来的代码复用。<file_sep>/Spottly/SPYEmailLoginViewModel.swift // // SPYLoginViewModel.swift // SpottlyCoreData // // Created by HuangZhigang on 15/11/15. // Copyright © 2015年 Spottly. All rights reserved. // import Foundation import RxSwift import RxCocoa import CoreData import Groot func URLEscape(pathSegment: String) -> String { return pathSegment.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())! } enum ValidationResult { case OK(message: String) case Empty case Validating case Failed(message: String) } extension ValidationResult { var isValid: Bool { switch self { case .OK: return true default: return false } } } public enum LoginResult { case None case OK(user: User) case JSONOK(json: NSDictionary) case Failed(statueCode: Int) } extension LoginResult { var statusCode : Int { switch self { case .OK , .JSONOK ,None: return 0 case .Failed(let code): return code } } var json : NSDictionary? { switch self { case .JSONOK(let json): return json case .Failed ,.OK ,None: return nil } } var user : User? { switch self { case .OK(let user): return user case .Failed ,.JSONOK , None: return nil } } } enum SignupState { case SignedUp(signedUp: Bool) } class SPYEmailLoginViewModel : NSObject, NSFetchedResultsControllerDelegate { var userFr : SPYFetchedResultsController? let validatedUsername: Driver<ValidationResult> let validatedPassword: Driver<ValidationResult> var signupEnabled: Driver<Bool> // Has user signed in let signedIn: Driver<LoginResult> // Is signing process in progress var signingIn: Driver<Bool> init( input:( username: Driver<String>, password: Driver<String>, loginTaps: Driver<Void> ), api:Spottly ){ validatedUsername = input.username .flatMapLatest { username in return api.validateUsername(username) .asDriver(onErrorJustReturn: .Failed(message: "Error contacting server")) } validatedPassword = input.password .map { password in return api.validatePassword(password) } let usernameAndPassword = Driver.combineLatest(input.username, input.password) { ($0, $1) } signedIn = input.loginTaps.withLatestFrom(usernameAndPassword) .flatMapLatest { (username, password) in return api.signup(username, password: <PASSWORD>).asDriver(onErrorJustReturn: .Failed(statueCode: 999)) } .flatMapLatest { loginResult -> Driver<LoginResult> in return Observable.create({ (observer) -> Disposable in if loginResult.statusCode != 0 { observer.on(.Next(.Failed(statueCode: loginResult.statusCode))) observer.on(.Completed) }else{ var user : User do { user = try objectFromJSONDictionary(loginResult.json!["user"] as! JSONDictionary, inContext: CoreDataManager.sharedManager.mainContext!) loginUserID(user.id) CoreDataManager.sharedManager.mainContext?.saveOrLogError() observer.on(.Next(.OK(user:user))) observer.on(.Completed) }catch{ print("error:\(error)") } } return AnonymousDisposable {} }).asDriver(onErrorJustReturn: .Failed(statueCode: 999)) } signingIn = Observable.just(false).asDriver(onErrorJustReturn: false) signupEnabled = Driver.combineLatest( validatedUsername, validatedPassword, signingIn ) { username, password, signingIn in username.isValid && password.isValid && !signingIn } .distinctUntilChanged() } } <file_sep>/Spottly/SPYPostViewModel.swift // // SPYCollectionViewModel.swift // Spottly // // Created by HuangZhigang on 16/1/18. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import RxSwift import RxCocoa import CoreData class SPYPostViewModel { var postFRC,postsFRC,ownerFRC,collectionsFRC,collectionFRC: SPYFetchedResultsController? var placeDetailUrl : String private var dispose = DisposeBag() var input : Post init(input:Post){ self.input = input // self.placeFRC = SPYFetchedResultsController(fetchRequest: self.input.selfFR()) self.placeDetailUrl = "http://spottly-web.5xruby.tw/places/\(input.place!.id!)/detail" self.postsFRC = SPYFetchedResultsController(fetchRequest: self.input.place!.postsFR())//相同place的post self.collectionsFRC = SPYFetchedResultsController(fetchRequest: self.input.place!.collectionsFR())//相关的collections self.postFRC = SPYFetchedResultsController(fetchRequest: self.input.selfFR()) self.ownerFRC = SPYFetchedResultsController(fetchRequest: self.input.ownerFR()) self.collectionFRC = SPYFetchedResultsController(fetchRequest: self.input.selfFR()) } func moreSpots() { } func moreCollections() { } }<file_sep>/Spottly/SPYSettingCell.swift // // SPYSettingCell.swift // Spottly // // Created by HuangZhigang on 16/3/12. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import UIKit class SPYSettingCell : UITableViewCell{ var title = UILabel().then{ $0.text = "title" $0.backgroundColor = UIColor.clearColor() $0.textColor = UIColor.spyBlackColor() $0.font = UIFont.spyAvenirNextMedium(12) } var arrow = UIImageView(image: UIImage(named: "SettingsArrow")) var version = UILabel().then{ $0.text = "title" $0.textAlignment = .Right $0.backgroundColor = UIColor.clearColor() $0.textColor = UIColor.spyBlackColor() $0.font = UIFont.spyAvenirNextMedium(12) } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style,reuseIdentifier:reuseIdentifier) self.backgroundColor = UIColor.clearColor() self.addSubviews(title,arrow,version) constrain(self,title,arrow,version){ box,title,arrow,v in align(top: box,title,arrow,v) align(bottom: box,title,arrow,v) title.left == box.left + 16 title.right == v.left v.right == box.right - 16 ~ 900 arrow.right == box.right - 16 ~ 900 arrow.width == 7.2 arrow.height == 14.5 } self.setNeedsLayout() self.layoutIfNeeded() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() self.contentView.frame = self.bounds self.contentView.setNeedsLayout() self.contentView.layoutIfNeeded() } } <file_sep>/Spottly/SPYIncrementalStoreValueTransformer.swift // // SPYIncrementalStoreValueTransformer.swift // SpottlyCoreData // // Created by HuangZhigang on 15/10/10. // Copyright © 2015年 Spottly. All rights reserved. // import Foundation import SwiftyJSON class SPYIncrementalStoreValueTransformer { init(){ NSValueTransformer.grt_setValueTransformerWithName("StringToDate", transformBlock: { (string) -> AnyObject? in return NSDate.spyParseRFC3339(string as! String) }) { (date) -> AnyObject? in return date.spyRFC3339String() } NSValueTransformer.grt_setDictionaryTransformerWithName("PostVerification") { (let jsondata) -> [NSObject : AnyObject]? in var json = JSON(jsondata) json["latitude"] = json["coordinate"]["latitude"] json["longitude"] = json["coordinate"]["longitude"] if let ownerId = json["owner-id"].string{ json["owner"] = ["id":ownerId] } if let originerId = json["origin-user-id"].string where originerId != "0"{ json["originer"] = ["id":originerId] } if let fromUserId = json["from-user-id"].string where fromUserId != "0"{ json["fromer"] = ["id":fromUserId] } if let collectionId = json["collection-id"].string{ json["collection"] = ["id":collectionId] } if let placeId = json["place-id"].string{ json["place"] = ["id":placeId] } // if let fromId = json["from-id"].string{ // json["from"] = ["id":fromId] // } // if let originId = json["origin-id"].string{ // json["origin"] = ["id":originId] // } return json.dictionaryObject } NSValueTransformer.grt_setDictionaryTransformerWithName("UserVerification") { (let jsonData) -> [NSObject : AnyObject]? in var json = JSON(jsonData) json["collectionsCount"] = json["collections"]["count"] json["followersCount"] = json["followers"]["count"] json["followingcollectionsCount"] = json["following-collections"]["count"] json["followingsCount"] = json["followings"]["count"] json["likesCount"] = json["likes"]["count"] json["postsCount"] = json["posts"]["count"] if let id = json["id"].int{ json["id"].string = String(id) } if let uid = json["identity"].string{ json["uid"].string = uid } return json.dictionaryObject } NSValueTransformer.grt_setDictionaryTransformerWithName("PlaceVerification") { (let jsonData) -> [NSObject : AnyObject]? in var json = JSON(jsonData) json["latitude"] = json["coordinate"]["latitude"] json["longitude"] = json["coordinate"]["longitude"] if let userId = json["user-id"].string{ json["user"] = ["id":userId] } if let cityId = json["city-id"].string { json["city"] = ["id":cityId] } return json.dictionaryObject } NSValueTransformer.grt_setDictionaryTransformerWithName("CityVerification") { (let jsonData) -> [NSObject : AnyObject]? in var json = JSON(jsonData) json["latitude"] = json["coordinate"]["latitude"] json["longitude"] = json["coordinate"]["longitude"] var aliasString = "" for i in json["alias"].array!{ aliasString = aliasString + i.stringValue } json["aliasString"] = JSON(aliasString) return json.dictionaryObject } NSValueTransformer.grt_setDictionaryTransformerWithName("CollectionVerification") { (let jsonData) -> [NSObject : AnyObject]? in var json = JSON(jsonData) if let ownerId = json["owner-id"].string{ json["owner"] = ["id":ownerId] } return json.dictionaryObject } } }<file_sep>/Spottly/SPYCreatPostParallaxHeader.swift // // SPYCreatPostParallaxHeader.swift // Spottly // // Created by HuangZhigang on 16/4/26. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import UIKit import RxSwift import Kingfisher import RxCocoa import imglyKit import Then import Groot import Photos class SPYCreatPostParallaxHeader :UICollectionReusableView { override init(frame: CGRect) { super.init(frame: frame) self.cameraBtn.addTarget(self, action: #selector(SPYCreatPostParallaxHeader.gotoCameraView), forControlEvents: UIControlEvents.TouchUpInside) self.myPhotos.registerClass(SPYPhotoCell.self, forCellWithReuseIdentifier: "SPYPhotoCell") self.setupSubviews() self.configurePhotos() self.configureLocImage() self.configureCamera() self.configureLibraryButton() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupSubviews(){ let yourOwnPicture = UILabel().then { $0.text = "YOUR OWN PICTURE" $0.backgroundColor = UIColor(rgba: "#212121") $0.font = UIFont.spyAvenirNextRegular(10) $0.textColor = UIColor.whiteColor() $0.textAlignment = .Center } self.addSubviews(yourOwnPicture,camera,locImage,myPhotos,openLibrary) constrain(yourOwnPicture,camera,locImage,myPhotos,openLibrary){ your,camera,locImage,myPhotos,openLibrary in let box = your.superview! your.top == box.top your.width == box.width your.height == 40 your.left == box.left distribute(by: 0, vertically: your,camera,myPhotos,openLibrary) align(left: your,camera,myPhotos,openLibrary) align(right: your,myPhotos,openLibrary) camera.top == your.bottom camera.left == box.left camera.height == 150 camera.width == 150 camera.right == locImage.left camera.top == locImage.top camera.height == locImage.height locImage.right == box.right myPhotos.height == 150 openLibrary.height == 60 openLibrary.bottom == box.bottom } camera.addSubview(cameraBtn) constrain(camera,cameraBtn){ camera,btn in camera.size == btn.size btn.center == camera.center } } func configurePhotos() { let options = PHFetchOptions() options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]; if #available(iOS 9.0, *) { options.fetchLimit = 10 } let result = PHAsset.fetchAssetsWithOptions(options) photos = Observable.create{ observer in let min = result.count > 10 ? 10 : result.count let assets = result.objectsAtIndexes(NSIndexSet(indexesInRange: NSRange(location: 0, length: min))) as! [PHAsset] observer.onNext(assets) return AnonymousDisposable {} }.asDriver(onErrorJustReturn: []) as Driver<[PHAsset]> photos! .drive(self.myPhotos.rx_itemsWithCellIdentifier("SPYPhotoCell", cellType: SPYPhotoCell.self)) { (_, asset, cell) in let manager = PHImageManager.defaultManager() manager.requestImageForAsset(asset, targetSize: CGSize(width: 150.0, height: 150.0), contentMode: .AspectFill, options: nil) { (result, _) in cell.imageView?.image = result } } .addDisposableTo(disposeBag) self.myPhotos.rx_modelSelected(PHAsset) .asDriver() .driveNext{ [weak self] asset -> Void in self?.gotoEditerView(asset) if let loc = asset.location{ self?.location = loc } }.addDisposableTo(disposeBag) } func configureLibraryButton() { self.openLibrary.rx_tap.asDriver().driveNext{ n in let c = mainStoryboard().instantiateViewControllerWithIdentifier("SPYPhotoPicker") as! SPYPhotoPicker c.viewModel = SPYPhotoPickerViewModel(album: c.album.asObservable()) SPYNavigationController().pushViewController(c, animated: true) }.addDisposableTo(self.disposeBag) } func configureLocImage(){ let options = PHFetchOptions() options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]; if #available(iOS 9.0, *) { options.fetchLimit = 1 } let result = PHAsset.fetchAssetsWithOptions(options) if result.count >= 1{ let assets = result.objectsAtIndexes(NSIndexSet(indexesInRange: NSRange(location: 0, length: 1))) as! [PHAsset] PHImageManager.defaultManager().requestImageForAsset(assets.first!, targetSize: CGSize(width: 150.0, height: 150.0), contentMode: .AspectFill, options: nil) { (result, _) in self.locImage.image = result } }else{ //默认图片 self.locImage.image = nil } } func reLayoutCamera() { dispatch_async(dispatch_get_main_queue(), { self.previewLayer?.removeFromSuperlayer() self.previewLayer = AVCaptureVideoPreviewLayer(session: self.captureSession!) self.camera.layer.masksToBounds = true let previewBounds = self.camera.layer.bounds self.previewLayer!.bounds = previewBounds self.previewLayer!.videoGravity = AVLayerVideoGravityResizeAspectFill; self.previewLayer!.position = CGPointMake(CGRectGetMidX(previewBounds), CGRectGetMidY(previewBounds)) self.camera.layer.insertSublayer(self.previewLayer!, atIndex: 0) }) } func gotoCameraView() { PhotoEffect.allEffects = effects let configuration = Configuration() { builder in // Customize the navigation bar using UIAppearance // UINavigationBar.appearance().titleTextAttributes = [ NSForegroundColorAttributeName: UIColor.blueColor(), // NSFontAttributeName: UIFont(name: "DINCondensed-Bold", size: 20)! ] builder.backgroundColor = UIColor.blackColor() customizeCameraController(builder) customizePhotoEditorViewController(builder) customizeCropToolController(builder) customizeOrientationViewController(builder) } let cameraViewController = CameraViewController(configuration: configuration) cameraViewController.completionBlock = { (maybeImage, maybeUrl) in dispatch_async(dispatch_get_main_queue(), { let c = mainStoryboard().instantiateViewControllerWithIdentifier("SPYPlacePicker") as! SPYPlacePicker if let url = maybeUrl{ c.photo = imageWithMediaURL(url) c.videoUrl = url UISaveVideoAtPathToSavedPhotosAlbum(url.path!, self, nil, nil) c.location = self.location! cameraViewController.dismissViewControllerAnimated(true, completion: { SPYNavigationController().pushViewController(c, animated: true) }) } if let img = maybeImage{ c.photo = img cameraViewController.dismissViewControllerAnimated(true, completion: { c.location = self.location! SPYNavigationController().pushViewController(c, animated: true) }) } }) } if let window = UIApplication.sharedApplication().delegate?.window! { window.tintColor = UIColor.whiteColor() } SPYNavigationController().presentViewController(cameraViewController, animated: true, completion: nil) } func gotoEditerView(asset:PHAsset) { if let window = UIApplication.sharedApplication().delegate?.window! { window.tintColor = UIColor.whiteColor() } let manager = PHImageManager.defaultManager() let options = PHImageRequestOptions() options.synchronous = true options.deliveryMode = .FastFormat options.resizeMode = .Exact manager.requestImageForAsset(asset,targetSize: CGSize(width: 2000, height: 2000), contentMode: .AspectFit, options: options) { (result, info) in dispatch_async(dispatch_get_main_queue(), { let configuration = Configuration() { builder in builder.backgroundColor = UIColor.blackColor() customizePhotoEditorViewController(builder) customizeCropToolController(builder) customizeOrientationViewController(builder) } let photoEditViewController = PhotoEditViewController(photo: result!,configuration: configuration) let toolStackController = ToolStackController(photoEditViewController: photoEditViewController) toolStackController.delegate = self SPYNavigationController().presentViewController(toolStackController, animated: true, completion: nil) }) } } func configureCamera() { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), { () -> Void in self.captureSession = AVCaptureSession() self.captureSession!.sessionPreset = AVCaptureSessionPreset640x480; var captureDevice : AVCaptureDevice! let devices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo) for device in devices{ if let d = device as? AVCaptureDevice{ if d.position == .Back{ captureDevice = d } } } if captureDevice.hasTorch{ do { try captureDevice.lockForConfiguration() if captureDevice.isTorchModeSupported(AVCaptureTorchMode.Off){ captureDevice.torchMode = AVCaptureTorchMode.Off } captureDevice.unlockForConfiguration() }catch{ } } self.videoInput = try! AVCaptureDeviceInput(device: captureDevice) if self.captureSession!.canAddInput(self.videoInput){ self.captureSession?.addInput(self.videoInput) } else{ fatalError("摄像头初始化错误") } self.captureSession?.startRunning() self.reLayoutCamera() }) } //MARK: - Property var photos : Driver<[PHAsset]>? var disposeBag = DisposeBag() var captureSession : AVCaptureSession? var videoInput: AVCaptureDeviceInput? var previewLayer :AVCaptureVideoPreviewLayer? var camera = UIImageView().then{ $0.userInteractionEnabled = true $0.backgroundColor = UIColor.redColor() } var locImage = UIImageView().then{ $0.backgroundColor = UIColor.blueColor() } var myPhotos = UICollectionView.photo.then{ $0.backgroundColor = UIColor.yellowColor() } var cameraBtn = UIButton().then{ $0.setImage(UIImage(named: "CameraIconLayer"),forState:UIControlState.Normal ) $0.backgroundColor = UIColor(rgba: "#21212155") } private var effects : [PhotoEffect] { let names = "Goblin,Hicon,Identity,K1,K2,K6" as NSString let nameArray = names.componentsSeparatedByString(",") var effect = nameArray.map{ (name) -> PhotoEffect in PhotoEffect(identifier: name, lutURL: NSBundle.imglyKitBundle.URLForResource(name, withExtension: "png"), displayName: name) } let none = PhotoEffect(identifier: "None", CIFilterName: nil, lutURL: nil, displayName: "None", options: nil) effect.insert(none, atIndex: 0) return effect } var openLibrary = UIButton().then{ $0.setTitle("OPEN PHOTO LIBRARY",forState:.Normal) $0.titleLabel!.font = UIFont.spyAvenirNextRegular(14) $0.backgroundColor = UIColor(rgba: "#212121") } //TODO: 设置当前坐标为默认值 var location: CLLocation? } extension SPYCreatPostParallaxHeader: ToolStackControllerDelegate { func toolStackController(toolStackController: ToolStackController, didFinishWithImage image: UIImage) { toolStackController.dismissViewControllerAnimated(true, completion: { let c = mainStoryboard().instantiateViewControllerWithIdentifier("SPYPlacePicker") as! SPYPlacePicker c.photo = image c.location = self.location! SPYNavigationController().pushViewController(c, animated: true) }) } func toolStackControllerDidFail(toolStackController: ToolStackController) { toolStackController.dismissViewControllerAnimated(true, completion: nil) } func toolStackControllerDidCancel(toolStackController: ToolStackController) { toolStackController.dismissViewControllerAnimated(true, completion: nil) } } <file_sep>/Spottly/SPYCollectionView.swift // // SPYCollectionViewController.swift // Spottly // // Created by HuangZhigang on 16/1/18. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import UIKit import RxSwift import Kingfisher import RxCocoa import PullToRefresh import Then class SPYCollectionView : UIViewController { var collection = SPYCollectionViewSubClass.spyRegisterClass(SPYPlaceCell.self) var disposeBag = DisposeBag() var layout : UICollectionViewFlowLayout{ return self.collection.collectionViewLayout as!UICollectionViewFlowLayout } var viewModel : SPYCollectionViewModel? { didSet{ self.spyLoadViewIfNeeded() self.viewModel?.collectionFRC?.performFetchIfNeed.rxFetchedObjects .filter{ $0.count > 0 } .subscribeNext{ (fetchedObjects) -> Void in let collection = fetchedObjects.first as! Collection self.name.text = collection.owner!.name self.head.setImageWithURL(NSURL(string: $ + collection.owner!.head! + "?size=head_2x")!) self.collectionName.text = collection.name! self.postsNum.text = "25" self.msg.text = collection.desc ?? "" self.headView.setNeedsLayout() self.headView.layoutIfNeeded() self.layout.headerReferenceSize.height = self.headView.height }.addDisposableTo(self.disposeBag) } } var headView = UIView().then{ $0.backgroundColor = UIColor.whiteColor() } private var head = UIImageView().then{ $0.layer.cornerRadius = 25/2 $0.clipsToBounds = true } private var name = UILabel().then{ $0.backgroundColor = UIColor.clearColor() $0.text = "user" $0.font = UIFont.spyAvenirNextRegular(12) $0.textColor = UIColor.spyTextColor() } private var postsNum = UILabel().then{ $0.backgroundColor = UIColor.clearColor() $0.text = "88" $0.textAlignment = .Right $0.font = UIFont.spyAvenirNextRegular(10) $0.textColor = UIColor.spyGrayColor() } private var collectionName = UILabel().then{ $0.text = "collectionName" $0.backgroundColor = UIColor.clearColor() $0.font = UIFont.spyAvenirNextDemiBold(18) $0.textColor = UIColor.spyTextColor() $0.textAlignment = .Center $0.numberOfLines = 0 } private var msg = UILabel().then{ $0.text = "msg" $0.numberOfLines = 0 $0.font = UIFont.spyAvenirNextMedium(14) $0.textColor = UIColor.spyGrayColor() $0.backgroundColor = UIColor.clearColor() } func layoutHeadView() { let upLine = line() let downLine = line() headView.addSubviews(head,upLine,collectionName,downLine,msg) constrain(head,upLine,collectionName,downLine,msg){ head,up,name,down,msg in let box = head.superview! box.width == UIScreen.width head.top == box.top + 10 head.left == box.left + 15 head.height == 25 head.width == 25 up.top == head.bottom + 10 up.left == box.left + 10 up.right == box.right - 10 up.height == 1 name.top == up.bottom + 14 name.left == box.left + 18 name.right == box.right - 18 down.top == name.bottom + 5 down.left == box.left + 130 down.right == box.right - 130 down.height == 1 msg.top == down.bottom + 5 msg.left == box.left + 18 msg.right == box.right - 18 msg.bottom == box.bottom - 18 } headView.addSubviews(name,postsNum) constrain(headView,head,name,postsNum){ box,head,name,num in align(centerY: head,name,num) distribute(by: 8, leftToRight: head,name,num) num.right == box.right - 17 } headView.setNeedsLayout() headView.layoutIfNeeded() } // override func viewWillAppear(animated: Bool) { // if let _ = self.userViewModel{ // }else{ // self.userViewModel = SPYUserViewModel.shareMe // } // } override func viewDidLoad() { super.viewDidLoad() self.layoutHeadView() self.collection.addSubview(self.headView) self.view.addSubview(self.collection) constrain(self.view,self.collection, self.headView) { (box,collection, head) -> () in collection.width == UIScreen.width collection.top == box.top + 64 collection.left == box.left head.top == collection.top head.left == collection.left collection.height == box.height - 64 - 49 } layout.spyConfigureLayoutForPlaces() viewModel?.postsFRC? .performFetch .rxFetchedObjects .bindTo(self.collection.rx_itemsWithCellIdentifier("SPYPlaceCell")){ (_, spot, cell: SPYPlaceCell) in cell.configureCell(spot as! Place) }.addDisposableTo(disposeBag) collection.rx_modelSelected(AnyObject) .asDriver() .driveNext{ spot -> Void in print("Taped spot : \(spot)") }.addDisposableTo(disposeBag) SPYObserveRequestState(self.collection, frc: viewModel?.postsFRC, dataType: .Post, bag: disposeBag) // SPYSetupFooterViewFor(self.collection, frc: viewModel?.postsFRC, dataType: .Post, bag: bag) } func doMore(value:Int) { switch value { case 0 : viewModel?.postsFRC?.loadMore() case 1 : viewModel?.collectionsFRC?.loadMore() default : break } } }<file_sep>/Spottly/SPYFetchRequest.swift // // SPYFetchRequest.swift // SpottlyCoreData // // Created by HuangZhigang on 15/10/9. // Copyright © 2015年 Spottly. All rights reserved. // import Foundation import CoreData protocol NSCopying { func copyWithZone(zone: NSZone) -> AnyObject! } class SPYFetchRequest : NSFetchRequest{ var containHttpRequest : Bool{ get{ return httpInfo?.count > 1 } } override func copyWithZone(zone: NSZone) -> AnyObject { let fr = super.copyWithZone(zone) as! SPYFetchRequest fr.httpInfo = self.httpInfo fr.httpState = self.httpState return fr } var httpInfo : [String : AnyObject]? var errorHandleBlock : (() -> Void)? var httpState : [String : AnyObject]? var ignore = false var isSuccess : Bool { get{ guard let state = httpState else{ return true }//没被设置状态的 是 本地搜索 guard let code = state["code"] as? Int else{// 网络搜索 return false } return code >= 200 && code < 300 } } }<file_sep>/Spottly/SPYSearchResultCell.swift // // SPYSearchCell.swift // Spottly // // Created by HuangZhigang on 16/3/14. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import UIKit class SPYSearchResultCell: UICollectionViewCell { let head = UIImageView().then{ $0.contentMode = .ScaleAspectFill } let title = UILabel().then{ $0.backgroundColor = UIColor.clearColor() $0.text = "@title" $0.textColor = UIColor.whiteColor() $0.font = UIFont.spyHelveticaNeueRegular(22) $0.numberOfLines = 1 } let detail = UILabel().then{ $0.backgroundColor = UIColor.clearColor() $0.text = "@detail" $0.textColor = UIColor.whiteColor() $0.font = UIFont.spyAvenirNextRegular(12) $0.numberOfLines = 1 } override init(frame: CGRect) { super.init(frame: frame) let texts = UIView() texts.addSubviews(self.title,self.detail) constrain(texts,title,detail){ box,title,detail in align(left: box,title,detail) align(right: box,title,detail) distribute(by: 0,vertically:title,detail) title.top == box.top detail.bottom == box.bottom } self.addSubviews(head,texts) self.backgroundColor = UIColor(rgba: "#212121") constrain(self,head,texts){ box ,head , texts in align(centerY: box ,head , texts) head.left == box.left + 20 texts.left == head.right + 10 texts.right == box.right - 20 head.height == 40 head.width == 40 } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() // print("title :\(title.frame)") } func configureCell(viewModel:Any) { if let user = viewModel as? User{ head.kf_setImageWithURL(NSURL(string: user.head!.headSize)!) head.layer.cornerRadius = 20 head.clipsToBounds = true head.contentMode = .ScaleAspectFill title.text = user.name detail.text = user.uid } if let place = viewModel as? Place{ head.image = UIImage(named: "bigPin") head.layer.cornerRadius = 2 head.contentMode = .Center title.text = place.name detail.text = place.address } if let city = viewModel as? City{ head.image = UIImage(named: "bigPin") head.layer.cornerRadius = 2 head.contentMode = .Center title.text = city.name detail.text = "" } if let top = viewModel as? Top{ head.image = nil head.contentMode = .ScaleAspectFill head.layer.cornerRadius = 2 title.text = top.name detail.text = nil } } }<file_sep>/Spottly/SPYUserView.swift // // SPYUserViewController.swift // Spottly // // Created by HuangZhigang on 15/12/5. // Copyright © 2015年 Spottly. All rights reserved. // import Foundation import UIKit import RxSwift import Kingfisher import RxCocoa import Then import Groot import PullToRefresh typealias SPYUserPlaceSection = HashableSectionModel<SPYUserHeaderViewModel, Place> typealias SPYUserCollectionSection = HashableSectionModel<SPYUserHeaderViewModel, Collection> struct SPYUserHeaderViewModel:Hashable { var userFRC: SPYFetchedResultsController? var menuItems: [SPYMenuAction] var hashValue: Int { return menuItems.first!.stringValue.hash } } func == (lhs: SPYUserHeaderViewModel, rhs: SPYUserHeaderViewModel) -> Bool { return lhs.menuItems.first!.stringValue == rhs.menuItems.first!.stringValue } class SPYUserView: UIViewController , SPYMenuActionDelegate , UISearchBarDelegate{ var header : SPYMenuHeaderView? var footer : SPYMoreFooterView? var parallaxHeader : SPYUserHeaderView? var collection = SPYCollectionViewSubClass.spyRegisterClass(SPYPlaceCell.self,SPYCollectionCell.self) var dataSourceForPlace : RxCollectionViewSectionedReloadDataSource<SPYUserPlaceSection>! var dataSourceForCollection : RxCollectionViewSectionedReloadDataSource<SPYUserCollectionSection>! var layout : CSStickyHeaderFlowLayout{ return self.collection.collectionViewLayout as!CSStickyHeaderFlowLayout } var disposeBag = DisposeBag() var bag = DisposeBag() @IBOutlet weak var settingButton: UIBarButtonItem! private var searchBar = UISearchBar().then{ $0.text = " " $0.setSearchFieldBackgroundImage(UIImage(named:"SearchBg"),forState:UIControlState.Normal) } var searchInputing : Driver<Void>? // var searchResult = SPYSearchResultView func settingAction() { let c = mainStoryboard().instantiateViewControllerWithIdentifier("SPYSettingView") as! SPYSettingView self.navigationController?.pushViewController(c, animated: true) } var isMe = false var viewModel : SPYUserViewModel? { didSet{ } } override func viewWillAppear(animated: Bool) { // let back = UIBarButtonItem(image: UIImage(named: "BackBlack"), style: UIBarButtonItemStyle.Plain, target: self, action: #selector(SPYUserView.backAction)) // self.navigationItem.leftBarButtonItems = [back] self.navigationController?.navigationBar.barStyle = .Default self.navigationController?.navigationBar.tintColor = UIColor.spyBlackColor() self.navigationController?.navigationBar.shadowImage = UIImage() self.navigationController?.navigationBar.lt_setBackgroundColor(UIColor.whiteColor()) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) // self.navigationController?.navigationBar.lt_reset() } override func viewDidLoad() { super.viewDidLoad() configureDataSourceForCollection() configureDataSourceForPlace() self.navigationItem.titleView = searchBar self.reloadLayout() // collection.top = 64 // collection.height = self.view.height - 49 self.view.addSubviews(collection) constrain(self.view,collection){ box,collection in collection.top == box.top collection.left == box.left collection.right == box.right collection.bottom == box.bottom - 48 } self.collection.clipsToBounds = false let refresher = PullToRefresh() self.collection.addPullToRefresh(refresher) {[unowned self] () -> () in delay(2, closure: { () -> () in self.collection.endRefreshing() }) } self.collection.registerClass(SPYUserHeaderView.self, forSupplementaryViewOfKind: CSStickyHeaderParallaxHeader, withReuseIdentifier: "SPYUserHeaderView") self.collection.registerClass(SPYMenuHeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "SPYMenuHeaderView") collection.registerClass(SPYMoreFooterView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "SPYMoreFooterView") if let _ = self.viewModel{ }else{ self.viewModel = SPYUserViewModel.shareMe self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named:"SettingsIcon"), style: UIBarButtonItemStyle.Plain, target: self, action: #selector(SPYUserView.settingAction)) } doMenuAction(.Place(.Hot)) collection.rx_contentOffset .asDriver() .filter{ UIScrollView.needMore(self.collection, offset: $0) } .throttle(0.2) .driveNext { point in self.doMore(self.header!.menu.rx_selectedSegment.value!) }.addDisposableTo(disposeBag) // self.searchBar.delegate = self // searchResult.view.frame = CGRect(x: 0, y: 64, width: UIScreen.width, height: UIScreen.height - 64 - 49) // self.view.addSubviews(searchResult.view) // searchResult.view.hidden = true } func reloadLayout() { guard let layout = self.collection.collectionViewLayout as? CSStickyHeaderFlowLayout else{ return } layout.parallaxHeaderReferenceSize = CGSizeMake(UIScreen.width, 300); layout.parallaxHeaderMinimumReferenceSize = CGSize(width: UIScreen.width, height: 300) layout.itemSize = CGSizeMake(UIScreen.width, layout.itemSize.height); layout.headerReferenceSize = CGSize(width: UIScreen.width, height: 40) layout.footerReferenceSize = CGSize(width: UIScreen.width, height: 40) } // MARK: - DataSource func configureDataSourceForPlace() { let dataSource = RxCollectionViewSectionedReloadDataSource<SPYUserPlaceSection>() dataSource.cellFactory = { (cv, ip, item)in let cell = cv.dequeueReusableCellWithReuseIdentifier("SPYPlaceCell", forIndexPath: ip) as! SPYPlaceCell cell.configureCell(item) return cell } dataSource.supplementaryViewFactory = { [unowned dataSource,unowned self] (cv, kind, ip) in if kind == UICollectionElementKindSectionHeader{ if self.header == nil { self.header = cv.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SPYMenuHeaderView", forIndexPath: ip) as? SPYMenuHeaderView self.header?.configureCell(dataSource.sectionAtIndex(ip.section).model.menuItems) self.header?.delegate = self } return self.header! }else if kind == CSStickyHeaderParallaxHeader{ if self.parallaxHeader == nil { self.parallaxHeader = cv.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SPYUserHeaderView", forIndexPath: ip) as? SPYUserHeaderView self.parallaxHeader?.handlerAfterLayout = { [unowned self] size in self.layout.parallaxHeaderReferenceSize = size self.layout.parallaxHeaderMinimumReferenceSize = size } self.parallaxHeader?.configureCell(dataSource.sectionAtIndex(ip.section).model) } return self.parallaxHeader! }else { if self.footer == nil { self.footer = cv.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SPYMoreFooterView", forIndexPath: ip) as? SPYMoreFooterView } return self.footer! } } self.dataSourceForPlace = dataSource } func configureDataSourceForCollection() { let dataS = RxCollectionViewSectionedReloadDataSource<SPYUserCollectionSection>() dataS.cellFactory = { (cv, ip, item)in let cell = cv.dequeueReusableCellWithReuseIdentifier("SPYCollectionCell", forIndexPath: ip) as! SPYCollectionCell cell.configureCell(item) return cell } dataS.supplementaryViewFactory = { [unowned dataS,unowned self] (cv, kind, ip) in if kind == UICollectionElementKindSectionHeader{ if self.header == nil { self.header = cv.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SPYMenuHeaderView", forIndexPath: ip) as? SPYMenuHeaderView self.header?.delegate = self self.header?.configureCell(dataS.sectionAtIndex(ip.section).model.menuItems) } return self.header! }else if kind == CSStickyHeaderParallaxHeader{ if self.parallaxHeader == nil { self.parallaxHeader = cv.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SPYUserHeaderView", forIndexPath: ip) as? SPYUserHeaderView self.parallaxHeader?.handlerAfterLayout = { [unowned self] size in self.layout.parallaxHeaderReferenceSize = size self.layout.parallaxHeaderMinimumReferenceSize = size } self.parallaxHeader?.configureCell(dataS.sectionAtIndex(ip.section).model) } return self.parallaxHeader! }else { if self.footer == nil { self.footer = cv.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SPYMoreFooterView", forIndexPath: ip) as? SPYMoreFooterView } return self.footer! } } self.dataSourceForCollection = dataS } func headerFlowLayout() -> CSStickyHeaderFlowLayout { return self.collection.collectionViewLayout as! CSStickyHeaderFlowLayout } func backAction() { self.navigationController?.popViewControllerAnimated(true) } func doMenuAction(menuAction:SPYMenuAction) { self.bag = DisposeBag() switch menuAction { case .Place(let type) : let headerViewModel = SPYUserHeaderViewModel(userFRC: viewModel!.userFRC, menuItems: [.Place(.Hot),.Collection(.Hot)]) let items = viewModel!.placesFRC!.performFetchIfNeed.rxFetchedObjects.asDriver() Driver.combineLatest(Driver.just(headerViewModel),items){ h,items in return [SPYUserPlaceSection(model: h, items: items as! [Place])] }.drive(self.collection.rx_itemsWithDataSource(dataSourceForPlace)) .addDisposableTo(bag) collection.rx_itemSelected .asDriver() .driveNext{ [weak self] indexPath in let c = mainStoryboard().instantiateViewControllerWithIdentifier("SPYPostView") as! SPYPostView let place = self!.dataSourceForPlace.itemAtIndexPath(indexPath) if let post = place.relatedPost{ c.viewModel = SPYPostViewModel(input:post) self!.navigationController?.pushViewController(c, animated: true) }else{ showAlert("post 找不到") } } .addDisposableTo(bag) layout.spyConfigureLayoutForPlaces() SPYScrollMenuHeaderToTop(self.header,collection:self.collection ,layout:self.layout) SPYObserveRequestState(self.collection, frc: viewModel?.placesFRC, dataType: .Post, bag: bag) case .Collection(let type) : let headerViewModel = SPYUserHeaderViewModel(userFRC: viewModel!.userFRC, menuItems: [.Place(.Hot),.Collection(.Hot)]) let items = viewModel!.collectionsFRC!.performFetchIfNeed.rxFetchedObjects.asDriver() Driver.combineLatest(Driver.just(headerViewModel),items){ h,items in return [SPYUserCollectionSection(model: h, items: items as! [Collection])] } .drive(self.collection.rx_itemsWithDataSource(dataSourceForCollection)) .addDisposableTo(bag) collection.rx_itemSelected .asDriver() .driveNext{ [weak self] indexPath in let c = mainStoryboard().instantiateViewControllerWithIdentifier("SPYCollectionView") as! SPYCollectionView let collection = self!.dataSourceForCollection.itemAtIndexPath(indexPath) c.viewModel = SPYCollectionViewModel(input:collection) self!.navigationController?.pushViewController(c, animated: true) } .addDisposableTo(bag) layout.spyConfigureLayoutForCollections() SPYScrollMenuHeaderToTop(self.header!,collection:self.collection ,layout:self.layout) SPYObserveRequestState(self.collection, frc: viewModel?.collectionsFRC, dataType: .Collection, bag: bag) default: break } } func doMore(value: SPYMenuAction) { self.footer?.startAnimating() switch value { case .Place : self.viewModel?.placesFRC?.loadMore() case .Collection: self.viewModel?.collectionsFRC?.loadMore() default: break } } } <file_sep>/Spottly/SPYCellProtocols.swift // // SPYCellProtocol.swift // Spottly // // Created by HuangZhigang on 16/3/17. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import UIKit protocol ImagePresentAble:class { var imageView : UIImageView! {get set} func setupImageView() } extension ImagePresentAble where Self:UIView { func setupImageView(){ imageView = UIImageView() imageView.backgroundColor = UIColor.grayColor() self.addSubview(imageView) } } <file_sep>/Spottly/SPYVideoChooseCoverView.swift // // SPYVideoChooseCoverView.swift // Spottly // // Created by HuangZhigang on 16/4/29. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import UIKit import CoreLocation import imglyKit import Photos class SPYVideoChooseCoverView: UIViewController { //MARK: Life Ciclye init(videoURL:NSURL){ self.videoURL = videoURL self.asset = AVAsset(URL: videoURL) super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() configureNavBar() configureViewHierarchy() configureViewConstraints() self.view.backgroundColor = UIColor.blackColor() setLastImageFromRollAsPreview() } private func configureNavBar() { self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "Check"), style: .Plain, target: self, action: #selector(SPYVideoChooseCoverView.nextAction)) self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "BackWhite"), style: UIBarButtonItemStyle.Plain, target: self, action: #selector(SPYVideoChooseCoverView.backAction)) self.navigationItem.title = "Choose a Cover" self.navigationController?.navigationBar.tintColor = UIColor.whiteColor() } private func configureViewHierarchy() { cameraPreView.addSubview(coverSlider) self.view.addSubview(cameraPreView) bottom.addSubview(okButton) bottom.addSubview(cameraRollButton) self.view.addSubview(bottom) } private func configureViewConstraints() { constrain( self.view , cameraPreView ,bottom ) { box, camera,bottom in camera.top == box.top + 64 camera.height == box.width camera.width == box.width camera.centerX == box.centerX distribute(by: 0, vertically: camera, bottom) bottom.width == box.width bottom.bottom == box.bottom } constrain(bottom,okButton,cameraRollButton){ box,ok,camera in ok.height == 82 ok.width == 82 ok.center == box.center camera.height == 47 camera.width == 47 camera.centerY == ok.centerY camera.left == box.left + 20 } constrain(cameraPreView,coverSlider){ box,cover in cover.size == box.size cover.center == box.center } } //MARK: Action func backAction(){ self.navigationController?.popViewControllerAnimated(true); } func nextAction() { okAction() } func okAction() { let c = mainStoryboard().instantiateViewControllerWithIdentifier("SPYPlacePicker") as! SPYPlacePicker // c.location = self.location //huang c.photo = self.coverImage self.navigationController?.pushViewController(c, animated: true) } func setLastImageFromRollAsPreview() { let fetchOptions = PHFetchOptions() fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)] let fetchResult = PHAsset.fetchAssetsWithMediaType(.Image, options: fetchOptions) if let lastAsset = fetchResult.lastObject as? PHAsset { PHImageManager.defaultManager().requestImageForAsset(lastAsset, targetSize: CGSize(width: 40, height: 40), contentMode: PHImageContentMode.AspectFill, options: PHImageRequestOptions()) { (result, info) -> Void in self.cameraRollButton.setImage(result, forState: UIControlState.Normal) } } } func showCameraRoll() { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary // imagePicker.mediaTypes = [String(kUTTypeImage)] imagePicker.allowsEditing = false self.presentViewController(imagePicker, animated: true, completion: nil) } func showEditorWithImage(image:UIImage) { if let window = UIApplication.sharedApplication().delegate?.window! { window.tintColor = UIColor.whiteColor() } dispatch_async(dispatch_get_main_queue(), { let configuration = Configuration() { builder in builder.backgroundColor = UIColor.blackColor() customizePhotoEditorViewController(builder) customizeCropToolController(builder) customizeOrientationViewController(builder) } let photoEditViewController = PhotoEditViewController(photo: image,configuration: configuration) let toolStackController = ToolStackController(photoEditViewController: photoEditViewController) toolStackController.delegate = self SPYNavigationController().presentViewController(toolStackController, animated: true, completion: nil) }) } //MARK: property var cameraPreView = UIView() var bottom = UIView() let videoURL: NSURL let asset : AVAsset var coverImage: UIImage? var location : CLLocation? lazy var coverSlider : SAVideoRangeSlider = { let coverSlider = SAVideoRangeSlider(asset: self.asset) coverSlider.delegate = self; coverSlider.isCover = true; return coverSlider }() lazy var okButton : UIButton = { let btn = UIButton() btn.setImage(UIImage(named: "selectedCover"),forState:UIControlState.Normal) btn.addTarget(self, action: #selector(SPYVideoChooseCoverView.okAction), forControlEvents: UIControlEvents.TouchUpInside) return btn }() lazy var cameraRollButton: UIButton = { let button = UIButton() button.translatesAutoresizingMaskIntoConstraints = false button.setImage(UIImage(named: "white"), forState: .Normal) button.imageView?.contentMode = .ScaleAspectFill button.layer.cornerRadius = 3 button.clipsToBounds = true button.addTarget(self, action: #selector(SPYVideoChooseCoverView.showCameraRoll), forControlEvents: .TouchUpInside) return button }() } extension SPYVideoChooseCoverView: UIImagePickerControllerDelegate, UINavigationControllerDelegate { /** :nodoc: */ func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { let image = info[UIImagePickerControllerOriginalImage] as? UIImage self.dismissViewControllerAnimated(true, completion: { if let image = image { self.showEditorWithImage(image) } }) } /** :nodoc: */ func imagePickerControllerDidCancel(picker: UIImagePickerController) { self.dismissViewControllerAnimated(true, completion: nil) } } extension SPYVideoChooseCoverView: ToolStackControllerDelegate { func toolStackController(toolStackController: ToolStackController, didFinishWithImage image: UIImage) { toolStackController.dismissViewControllerAnimated(true, completion: { self.coverImage = image self.coverSlider.imageView.image = image }) } func toolStackControllerDidFail(toolStackController: ToolStackController) { toolStackController.dismissViewControllerAnimated(true, completion: nil) } func toolStackControllerDidCancel(toolStackController: ToolStackController) { toolStackController.dismissViewControllerAnimated(true, completion: nil) } } extension SPYVideoChooseCoverView: SAVideoRangeSliderDelegate{ func videoRange(videoRange: SAVideoRangeSlider!, didChangeCoverPosition coverPosition: CGFloat, cover: UIImage!) { self.coverImage = cover } } <file_sep>/SpottlyTests/SearchAPITests.swift // // SeverContentAPITests.swift // Spottly // // Created by HuangZhigang on 16/5/5. // Copyright © 2016年 Spottly. All rights reserved. // import XCTest import Alamofire import SwiftyJSON import RxSwift import RxBlocking import RxCocoa //case SearchPlacesInUser(let userID,let objects): //return "/users/\(userID)/\(objects.rawValue)" //case .TimeLine: //return "/posts/timeline" @testable import Spottly class SearchAPITests: XCTestCase { let cityID = "95551579422772" let collectionID = "95551746015300" let placeID = "95551731532104" let categoriesID = "95551579750669"//food let userID = "95551582372079" let postID = "95551852904511" let coordinate = CLLocation(latitude: 39.9345408981, longitude: 116.4464434002) let namePara = "edwy" let cityPara = "bei" let placeName = "coffee" let tag = "Food" override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testTimeLine() { let URL = SPYRouter.TimeLine .fullPath .count(2) let expectation = expectationWithDescription("Get: \(URL)") Alamofire.request(.GET, URL).responseJSON { response in expectation.fulfill() print("testTimeLine : \(URL) \n ERROR : \(response.result.error)") XCTAssertLessThan(response.response!.statusCode,400,"返回错误") XCTAssertNotNil(response.result.value, "返回数据不应该为空") let json = JSON(response.result.value!) XCTAssertNotNil(json["data"], "返回数据不应该为空") let array = json["data"]["posts"].array XCTAssertNotNil(array, "返回数据不应该为空") if let a = array{ XCTAssertGreaterThan(a.count, 0) } } waitForExpectationsWithTimeout(15) { (error) in if error != nil{ XCTFail("❌") } } } func testSearchInUser_place_name() { let URL = SPYRouter.SearchPlacesInUser(userID) .fullPath .filter([.NameQuery(placeName)]) .orderBy(.Distance(.Asc)) .count(2) let expectation = expectationWithDescription("Get: \(URL)") Alamofire.request(.GET, URL).responseJSON { response in expectation.fulfill() print("testSearchInUser_place_name : \(URL) \n ERROR : \(response.result.error)") XCTAssertLessThan(response.response!.statusCode,400,"返回错误") XCTAssertNotNil(response.result.value, "返回数据不应该为空") let json = JSON(response.result.value!) XCTAssertNotNil(json["data"], "返回数据不应该为空") let array = json["data"]["places"].array XCTAssertNotNil(array, "返回数据不应该为空") if let a = array{ XCTAssertGreaterThan(a.count, 0) } print("testSearchInUser_place_name : \(json)") } waitForExpectationsWithTimeout(15) { (error) in if error != nil{ XCTFail("❌") } } } func testSearchInUser_place_Tag() { let URL = SPYRouter.SearchPlacesInUser(userID) .fullPath .filter([.TagQuery(tag)]) .orderBy(.Distance(.Asc)) .count(2) let expectation = expectationWithDescription("Get: \(URL)") Alamofire.request(.GET, URL).responseJSON { response in expectation.fulfill() print("testSearchInUser_place_Tag : \(URL) \n ERROR : \(response.result.error)") XCTAssertLessThan(response.response!.statusCode,400,"返回错误") XCTAssertNotNil(response.result.value, "返回数据不应该为空") let json = JSON(response.result.value!) XCTAssertNotNil(json["data"], "返回数据不应该为空") let array = json["data"]["places"].array XCTAssertNotNil(array, "返回数据不应该为空") if let a = array{ XCTAssertGreaterThan(a.count, 0) } print("testSearchInUser_place_Tag : \(json)") } waitForExpectationsWithTimeout(15) { (error) in if error != nil{ XCTFail("❌") } } } func testSearchInUser_collection() { let URL = SPYRouter.SearchPlacesInUser(userID) .fullPath .filter([.NameQuery(placeName)]) .count(2) let expectation = expectationWithDescription("Get: \(URL)") Alamofire.request(.GET, URL).responseJSON { response in expectation.fulfill() print("testSearchInUser_collection : \(URL) \n ERROR : \(response.result.error)") XCTAssertLessThan(response.response!.statusCode,400,"返回错误") XCTAssertNotNil(response.result.value, "返回数据不应该为空") let json = JSON(response.result.value!) XCTAssertNotNil(json["data"], "返回数据不应该为空") let array = json["data"]["collections"].array XCTAssertNotNil(array, "返回数据不应该为空") if let a = array{ XCTAssertGreaterThan(a.count, 0) } print("testSearchInUser_collection : \(json)") } waitForExpectationsWithTimeout(15) { (error) in if error != nil{ XCTFail("❌") } } } func testSearchPlacesInCity_Name() { let URL = SPYRouter.SearchPlacesInCity(cityID) .fullPath .filter([.NameQuery(placeName)]) .orderBy(.Rating(.Desc)) .count(2) let expectation = expectationWithDescription("Get: \(URL)") Alamofire.request(.GET, URL).responseJSON { response in expectation.fulfill() print("testSearchPlacesInCity_Name : \(URL) \n ERROR : \(response.result.error)") XCTAssertLessThan(response.response!.statusCode,400,"返回错误") XCTAssertNotNil(response.result.value, "返回数据不应该为空") let json = JSON(response.result.value!) XCTAssertNotNil(json["data"], "返回数据不应该为空") let array = json["data"]["places"].array XCTAssertNotNil(array, "返回数据不应该为空") if let a = array{ XCTAssertGreaterThan(a.count, 0) } } waitForExpectationsWithTimeout(15) { (error) in if error != nil{ XCTFail("❌") } } } func testSearchPlacesInCity_Tag() { let URL = SPYRouter.SearchPlacesInCity(cityID) .fullPath .filter([.TagQuery(tag)]) .orderBy(.Rating(.Desc)) .count(2) let expectation = expectationWithDescription("Get: \(URL)") Alamofire.request(.GET, URL).responseJSON { response in expectation.fulfill() print("testSearchPlacesInCity_Tag : \(URL) \n ERROR : \(response.result.error)") XCTAssertLessThan(response.response!.statusCode,400,"返回错误") XCTAssertNotNil(response.result.value, "返回数据不应该为空") let json = JSON(response.result.value!) XCTAssertNotNil(json["data"], "返回数据不应该为空") let array = json["data"]["places"].array XCTAssertNotNil(array, "返回数据不应该为空") if let a = array{ XCTAssertGreaterThan(a.count, 0) } print("testSearchPlacesInCity_Tag : \(json)") } waitForExpectationsWithTimeout(15) { (error) in if error != nil{ XCTFail("❌") } } } func testSearchPlaces_Nearby_Name() { let URL = SPYRouter.SearchPlacesNearby .fullPath .filter([.Coordinate(coordinate),.NameQuery(placeName)]) .orderBy(.Distance(.Asc)) .count(2) let expectation = expectationWithDescription("Get: \(URL)") Alamofire.request(.GET, URL).responseJSON { response in expectation.fulfill() print("testSearchPlaces_Nearby_Name : \(URL) \n ERROR : \(response.result.error)") XCTAssertLessThan(response.response!.statusCode,400,"返回错误") XCTAssertNotNil(response.result.value, "返回数据不应该为空") let json = JSON(response.result.value!) XCTAssertNotNil(json["data"], "返回数据不应该为空") let array = json["data"]["places"].array XCTAssertNotNil(array, "返回数据不应该为空") if let a = array{ XCTAssertGreaterThan(a.count, 0) } print("testSearchPlaces_Nearby_Name : \(json)") } waitForExpectationsWithTimeout(15) { (error) in if error != nil{ XCTFail("❌") } } } func testSearchPlaces_Nearby_Tag() { let URL = SPYRouter.SearchPlacesNearby .fullPath .filter([.Coordinate(coordinate),.TagQuery(placeName)]) .orderBy(.Distance(.Asc)) .count(2) let expectation = expectationWithDescription("Get: \(URL)") Alamofire.request(.GET, URL).responseJSON { response in expectation.fulfill() print("testSearchPlaces_Nearby_Tag : \(URL) \n ERROR : \(response.result.error)") XCTAssertLessThan(response.response!.statusCode,400,"返回错误") XCTAssertNotNil(response.result.value, "返回数据不应该为空") let json = JSON(response.result.value!) XCTAssertNotNil(json["data"], "返回数据不应该为空") let array = json["data"]["places"].array XCTAssertNotNil(array, "返回数据不应该为空") if let a = array{ XCTAssertGreaterThan(a.count, 0) } print("testSearchPlaces_Nearby_Tag : \(json)") } waitForExpectationsWithTimeout(15) { (error) in if error != nil{ XCTFail("❌") } } } func testSearchCollection() { let URL = SPYRouter.Search(.Collections) .fullPath .filter([.NameQuery(tag)]) .orderBy(.Rating(.Desc)) .count(2) let expectation = expectationWithDescription("Get: \(URL)") Alamofire.request(.GET, URL).responseJSON { response in expectation.fulfill() print("testSearchCollection : \(URL) \n ERROR : \(response.result.error)") XCTAssertLessThan(response.response!.statusCode,400,"返回错误") XCTAssertNotNil(response.result.value, "返回数据不应该为空") let json = JSON(response.result.value!) XCTAssertNotNil(json["data"], "返回数据不应该为空") let array = json["data"]["collections"].array XCTAssertNotNil(array, "返回数据不应该为空") if let a = array{ XCTAssertGreaterThan(a.count, 0) } print("testSearchCollection : \(json)") } waitForExpectationsWithTimeout(15) { (error) in if error != nil{ XCTFail("❌") } } } func testSearchPlace_tag(){ let URL = SPYRouter.Search(.Places) .fullPath .filter([.TagQuery(tag)]) .orderBy(.Distance(.Asc)) .count(2) let expectation = expectationWithDescription("Get: \(URL)") Alamofire.request(.GET, URL).responseJSON { response in expectation.fulfill() print("testSearchPlace_tag : \(URL) \n ERROR : \(response.result.error)") XCTAssertLessThan(response.response!.statusCode,400,"返回错误") XCTAssertNotNil(response.result.value, "返回数据不应该为空") let json = JSON(response.result.value!) XCTAssertNotNil(json["data"], "返回数据不应该为空") let array = json["data"]["places"].array XCTAssertNotNil(array, "返回数据不应该为空") if let a = array{ XCTAssertGreaterThan(a.count, 0) } print("testSearchPlace_tag : \(json)") } waitForExpectationsWithTimeout(15) { (error) in if error != nil{ XCTFail("❌") } } } func testSearchPlace_name(){ let URL = SPYRouter.Search(.Places) .fullPath .filter([.NameQuery(cityPara)]) .orderBy(.Distance(.Asc)) .count(2) let expectation = expectationWithDescription("Get: \(URL)") Alamofire.request(.GET, URL).responseJSON { response in expectation.fulfill() print("testSearchPlace_name : \(URL) \n ERROR : \(response.result.error)") XCTAssertLessThan(response.response!.statusCode,400,"返回错误") XCTAssertNotNil(response.result.value, "返回数据不应该为空") let json = JSON(response.result.value!) XCTAssertNotNil(json["data"], "返回数据不应该为空") let array = json["data"]["places"].array XCTAssertNotNil(array, "返回数据不应该为空") if let a = array{ XCTAssertGreaterThan(a.count, 0) } print("testSearchPlace_name : \(json)") } waitForExpectationsWithTimeout(15) { (error) in if error != nil{ XCTFail("❌") } } } func testSearchCity() { let URL = SPYRouter.Search(.Citys) .fullPath .filter([.NameQuery(cityPara)]) .count(2) let expectation = expectationWithDescription("Get: \(URL)") Alamofire.request(.GET, URL).responseJSON { response in expectation.fulfill() print("testSearchCity : \(URL) \n ERROR : \(response.result.error)") XCTAssertLessThan(response.response!.statusCode,400,"返回错误") XCTAssertNotNil(response.result.value, "返回数据不应该为空") let json = JSON(response.result.value!) XCTAssertNotNil(json["data"], "返回数据不应该为空") let array = json["data"]["cities"].array XCTAssertNotNil(array, "返回数据不应该为空") if let a = array{ XCTAssertGreaterThan(a.count, 0) } } waitForExpectationsWithTimeout(15) { (error) in if error != nil{ XCTFail("❌") } } } func testSearchUser() { let URL = SPYRouter.Search(.Users) .fullPath .filter([.NameQuery(namePara)]) .count(2) let expectation = expectationWithDescription("Get: \(URL)") Alamofire.request(.GET, URL).responseJSON { response in expectation.fulfill() print("testSearchUser : \(URL) \n ERROR : \(response.result.error)") XCTAssertLessThan(response.response!.statusCode,400,"返回错误") XCTAssertNotNil(response.result.value, "返回数据不应该为空") let json = JSON(response.result.value!) XCTAssertNotNil(json["data"], "返回数据不应该为空") let array = json["data"]["users"].array XCTAssertNotNil(array, "返回数据不应该为空") if let a = array{ XCTAssertGreaterThan(a.count, 0) } } waitForExpectationsWithTimeout(15) { (error) in if error != nil{ XCTFail("❌") } } } } <file_sep>/Spottly/SPYSortMenu.swift // // SPYSortMenu.swift // Spottly // // Created by HuangZhigang on 16/5/11. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import UIKit let SPYSortMenuItemHeight = CGFloat(30) let SPYSortMenuItemWidth = CGFloat(100) typealias SPYSortMenuHander = SPYSortType -> () class SPYSortMenu: UIView { var items: [SPYSortType] var menu = UIView().then{ $0.backgroundColor = UIColor.whiteColor() } let complete: SPYSortMenuHander var rectFromBtn = CGRectZero init(frame: CGRect ,items: [SPYSortType],complete: SPYSortMenuHander) { self.items = items self.complete = complete super.init(frame:UIScreen.mainScreen().bounds) self.backgroundColor = UIColor.clearColor() self.configureViewHierarchy() self.configureViewConstraints() self.menu.layer.cornerRadius = 5 self.setNeedsLayout() self.layoutIfNeeded() let sublayer = CALayer() sublayer.backgroundColor = UIColor.whiteColor().CGColor; sublayer.shadowOffset = CGSizeMake(0, 2); sublayer.shadowRadius = 5.0; sublayer.shadowColor = UIColor.grayColor().CGColor; sublayer.shadowOpacity = 0.8; sublayer.frame = menu.bounds; sublayer.cornerRadius = 5; self.menu.layer.insertSublayer(sublayer, atIndex: 0) } convenience init(items: [SPYSortType],complete: SPYSortMenuHander) { self.init(frame:CGRectZero,items:items,complete: complete) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configureViewHierarchy() { self.addSubview(menu) _ = items.map { item in let btn = UIButton() btn.setTitle(item.stringValue, forState: UIControlState.Normal) btn.titleLabel?.textAlignment = .Right btn.setTitleColor(UIColor.grayColor(), forState: UIControlState.Normal) btn.setTitleColor(UIColor.spyBlueColor(), forState: UIControlState.Highlighted) btn.titleLabel!.font = UIFont.spyAvenirNextMedium(12) btn.addTarget(self, action: #selector(SPYSortMenu.buttonAction(_:)), forControlEvents: UIControlEvents.TouchUpInside) let index = items.indexOf{$0 == item}! btn.tag = (Int)(index) + (Int)(1) // btn.layer.borderColor = UIColor.blueColor().CGColor // btn.layer.borderWidth = 1 btn.contentHorizontalAlignment = .Right; btn.contentEdgeInsets = UIEdgeInsetsMake(0,0, 0, 10); menu.addSubview(btn) } } func configureViewConstraints() { menu.translatesAutoresizingMaskIntoConstraints = false constrain(menu.subviews){ subviewsLayout in for (index,subview) in subviewsLayout.enumerate(){ subview.left == subview.superview!.left subview.right == subview.superview!.right subview.width == SPYSortMenuItemWidth subview.height == SPYSortMenuItemHeight var pre : LayoutProxy? var aft : LayoutProxy? if index - 1 >= 0 { pre = subviewsLayout[index - 1] } if index + 1 <= (subviewsLayout.count - 1) { aft = subviewsLayout[index + 1] } if pre == nil{ subview.top == subview.superview!.top + 5 }else { subview.top == pre!.bottom } if aft == nil { subview.bottom == subview.superview!.bottom - 5 } } } menu.setNeedsLayout() menu.layoutIfNeeded() print("menu :\(menu.subviews)") } func dismiss() { menu.removeFromSuperview() self.removeFromSuperview() } func showFrom(button:UIButton) { let window = UIApplication.sharedApplication().keyWindow rectFromBtn = button.superview!.convertRect(button.frame, toView:window) constrain(self,menu) { (box,menu) in menu.top == box.top + CGRectGetMaxY(rectFromBtn) menu.left == box.left + CGRectGetMaxX(rectFromBtn) - SPYSortMenuItemWidth } self.setNeedsLayout() self.layoutIfNeeded() window?.addSubview(self) } func buttonAction(button:UIButton) { self.complete(self.items[button.tag - 1]) self.dismiss() } override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool { let ok = CGRectContainsPoint(menu.frame, point); if !ok { self.performSelectorOnMainThread(#selector(dismiss), withObject: nil, waitUntilDone: false) } if CGRectContainsPoint(rectFromBtn, point){ return true }//如果点到fromBtn 要把这个事件屏蔽掉 不要再探出来menu return (ok); } } <file_sep>/Spottly/SPYViewController.swift // // SPYViewController.swift // Spottly // // Created by HuangZhigang on 15/12/17. // Copyright © 2015年 Spottly. All rights reserved. // import Foundation import UIKit import RxSwift import Kingfisher import RxCocoa extension UICollectionViewFlowLayout { func spyConfigureLayoutForPlaces(){ self.scrollDirection = .Vertical self.itemSize = CGSize(width: (UIScreen.width-3)/3.0,height: (UIScreen.width-3)/3.0) self.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0) self.minimumLineSpacing = 1 self.minimumInteritemSpacing = 1 } func spyConfigureLayoutForCollections(){ self.scrollDirection = .Vertical self.itemSize = CGSize(width: UIScreen.width,height: 40 + UIScreen.width * (2/3) + 80) self.sectionInset = UIEdgeInsetsMake(1, 1, 1, 1) self.minimumLineSpacing = 0 self.minimumInteritemSpacing = 0 } func spyConfigureLayoutForWeb(){ self.scrollDirection = .Vertical self.itemSize = CGSize(width: UIScreen.width,height: 880) self.sectionInset = UIEdgeInsetsMake(1, 1, 1, 1) self.minimumLineSpacing = 0 self.minimumInteritemSpacing = 0 } func spyConfigureLayoutForSearchResults(){ self.scrollDirection = .Vertical self.itemSize = CGSize(width: UIScreen.width,height: 70) self.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0) self.minimumLineSpacing = 0 self.minimumInteritemSpacing = 0 } func spyConfigureLayoutForHeader(headTop:CGFloat){ guard let collectionView = self.collectionView else{ return } if collectionView.contentOffset.y > headTop{ collectionView.contentOffset.y = headTop } } } class SPYCollectionViewSubClass: UICollectionView { typealias handle = () -> Void var handleAfterReloadData : handle? override func reloadData() { super.reloadData() handleAfterReloadData?() } class func spyRegisterClass(classes:AnyClass ...) -> SPYCollectionViewSubClass { let c = SPYCollectionViewSubClass(frame: CGRect(origin: CGPointZero, size: CGSizeZero), collectionViewLayout: CSStickyHeaderFlowLayout()) c.backgroundColor = UIColor.whiteColor() _ = classes.map { (classType) -> Void in c.registerClass(classType, forCellWithReuseIdentifier: String(classType)) } return c } } class SPYSearchBar : UISearchBar { var canBecomeFristRespond = false } extension UIViewController { func SPYScrollMenuHeaderToTop(meun:UIView?,collection:UICollectionView,layout:CSStickyHeaderFlowLayout)//为了解决CSSticky reloadData之后menu位置不对 { if collection.contentOffset.y > layout.parallaxHeaderReferenceSize.height - layout.spyHeaderAddedOrginY{ collection.contentOffset.y = layout.parallaxHeaderReferenceSize.height - layout.spyHeaderAddedOrginY } meun?.top = layout.parallaxHeaderReferenceSize.height } func SPYObserveRequestState(collection:UICollectionView,frc:SPYFetchedResultsController?, dataType: SPYType , bag:DisposeBag){ frc? .rx_requestState.asDriver() .driveNext({ (state) -> Void in switch state{ case .Loading : break case .Offline : break case .Error(let code) : break case .Completed(let type) : switch type { case .More: let maybeFooter = collection.subviews.filter{ $0 is SPYMoreFooterView }.first if let footer = maybeFooter as? SPYMoreFooterView{ footer.stopAnimating() } case .Refresh: collection.endRefreshing() } default: return }}) .addDisposableTo(bag) } } extension UIViewController{ func cancelDownloadTask(){ self.view.subviewsWithBlock { (view) -> Void in guard let imageView = view as? UIImageView else { return } imageView.kf_cancelDownloadTask() } } func spyLoadViewIfNeeded() { if #available(iOS 9.0, *) { self.loadViewIfNeeded() } else { self.view.backgroundColor = self.view.backgroundColor } } } extension UICollectionView{ class var spy : UICollectionView { let c = UICollectionView(frame: CGRect(origin: CGPointZero, size: UIScreen.size), collectionViewLayout: UICollectionViewFlowLayout.spy) c.backgroundColor = UIColor.spyBgColor() return c } class var photo : UICollectionView { let c = UICollectionView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout.photo) c.backgroundColor = UIColor.blackColor() return c } } extension UICollectionViewFlowLayout { class var spy : UICollectionViewFlowLayout { return UICollectionViewFlowLayout().then{ $0.spyConfigureLayoutForPlaces() } } class var photo : UICollectionViewFlowLayout { return UICollectionViewFlowLayout().then{ $0.scrollDirection = .Horizontal $0.itemSize = CGSize(width: 150,height: 150) $0.sectionInset = UIEdgeInsetsMake(1, 1, 1, 1) $0.minimumLineSpacing = 0 } } } //extension UICollectionViewFlowLayout //{ // override public func prepareForCollectionViewUpdates(updateItems: [UICollectionViewUpdateItem]) // { // // } // override public func finalizeCollectionViewUpdates() // { // // } // override public func initialLayoutAttributesForAppearingItemAtIndexPath(itemIndexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? // { // let attr = super.initialLayoutAttributesForAppearingItemAtIndexPath(itemIndexPath) // attr?.alpha = 1 // return attr // } // override public func finalLayoutAttributesForDisappearingItemAtIndexPath(itemIndexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? // { // let attr = super.finalLayoutAttributesForDisappearingItemAtIndexPath(itemIndexPath) // attr?.alpha = 0 // return attr // } //} <file_sep>/Spottly/SPYPhotoPicker.swift // // SPYCityView.swift // Spottly // // Created by HuangZhigang on 16/2/15. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import UIKit import RxSwift import Kingfisher import RxCocoa import imglyKit import Then import Groot import Photos class SPYPhotoPicker: UIViewController { //MARK: Life Ciclye override func viewDidLoad() { self.configureHeadView() self.configureCollection() self.configureAlbum() self.configureNavBar() } func configureNavBar() { self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "Check"), style: UIBarButtonItemStyle.Plain, target: self, action: #selector(SPYPhotoPicker.nextAction)) self.navigationItem.rightBarButtonItem?.tintColor = UIColor.whiteColor() self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "BackWhite"), style: UIBarButtonItemStyle.Plain, target: self, action: #selector(SPYPhotoPicker.backAction)) self.navigationItem.leftBarButtonItem?.tintColor = UIColor.whiteColor() self.title = "Picker a Place" self.navigationItem.titleView = self.btn } func configureHeadView() { self.view.addSubview(headView); btn.rx_tap.asDriver().driveNext { [unowned self] () -> Void in self.btn.selected = !self.btn.selected if !self.btn.selected { self.closeAlbum() }else{ self.showAlbum() } } .addDisposableTo(disposeBag) self.viewModel?.photos?.asDriver(onErrorJustReturn: []).driveNext { (photos) -> Void in if let first = photos.first{ first.setBigImageFor(self.headView) self.location = first.location self.selectedAsset = first } }.addDisposableTo(disposeBag) } func configureCollection() { let layout = UICollectionViewFlowLayout() layout.spyConfigureLayoutForPlaces() collection = UICollectionView(frame: CGRectMake(0, 44 + 20 + UIScreen.width, UIScreen.width, UIScreen.height - 44 - 20 - UIScreen.width), collectionViewLayout: layout) collection?.registerClass(SPYPhotoCell.self, forCellWithReuseIdentifier: "SPYPhotoCell") self.view.addSubviews(collection!) self.viewModel?.photos?.asDriver(onErrorJustReturn: []) .drive(self.collection!.rx_itemsWithCellIdentifier("SPYPhotoCell", cellType: SPYPhotoCell.self)) { (_, photo, cell) in photo.setImageFor(cell.imageView!) } .addDisposableTo(disposeBag) self.collection?.rx_modelSelected(Photo) .asDriver() .driveNext{ [unowned self] photo -> Void in photo.setBigImageFor(self.headView) self.location = photo.location self.selectedAsset = photo }.addDisposableTo(disposeBag) } func configureAlbum() { self.albumView.registerClass(SPYAlbumCell.self, forCellReuseIdentifier: "SPYAlbumCell") self.view.addSubview(self.albumView) self.viewModel?.albums?.asDriver(onErrorJustReturn: []) .drive(self.albumView.rx_itemsWithCellIdentifier("SPYAlbumCell", cellType: SPYAlbumCell.self)){ (_, assetCollection, cell) in let manager = PHImageManager.defaultManager() cell.textLabel?.text = assetCollection.localizedTitle cell.textLabel?.textColor = UIColor.whiteColor() cell.textLabel?.backgroundColor = UIColor.clearColor() cell.contentView.backgroundColor = UIColor.blackColor() let options = PHFetchOptions() options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]; let result = PHAsset.fetchAssetsInAssetCollection(assetCollection, options: options) cell.numLabel.text = String(result.count) if result.count > 1{ manager.requestImageForAsset(result[0] as! PHAsset, targetSize: CGSize(width: 150.0, height: 150.0), contentMode: .AspectFill, options: nil) { (result, _) in cell.imageView?.image = result } }else{ cell.imageView?.image = UIImage(named: "World") } }.addDisposableTo(disposeBag) self.albumView.rx_modelSelected(PHAssetCollection) .asDriver() .driveNext{ assetCollection -> Void in self.closeAlbum() self.btn.selected = !self.btn.selected self.viewModel!.album!.value = assetCollection }.addDisposableTo(disposeBag) } //MARK: Action func backAction(){ self.navigationController?.popViewControllerAnimated(true); } func nextAction() { if let asset = self.selectedAsset { switch asset.mediaType { case .Video: self.gotoVideoEditerView(asset.asPHAsset()) case .Image: self.gotoPhotoEditerView(asset.asPHAsset()) default: showAlert("This media type not be support!") return } } } func showAlbum() { self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "cancel"), style: UIBarButtonItemStyle.Plain, target: self, action: #selector(SPYPhotoPicker.closeAlbum)) self.navigationItem.rightBarButtonItem?.tintColor = UIColor.whiteColor() self.albumView.frame = hideRect UIView.animateWithDuration(0.2, delay: 0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in self.albumView.frame = showRect }, completion: { (finish) -> Void in }) } func closeAlbum() { self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "forward"), style: UIBarButtonItemStyle.Plain, target: self, action: #selector(SPYPhotoPicker.nextAction)) self.navigationItem.rightBarButtonItem?.tintColor = UIColor.whiteColor() self.albumView.frame = showRect UIView.animateWithDuration(0.2, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in self.albumView.frame = hideRect }, completion: { (finish) -> Void in }) } func gotoVideoEditerView(asset:PHAsset) { let manager = PHImageManager.defaultManager() let options = PHVideoRequestOptions() options.networkAccessAllowed = true options.deliveryMode = .FastFormat manager.requestAVAssetForVideo(asset, options: options) { (asset, _ , info) in dispatch_async(dispatch_get_main_queue(), { let c = SPYVideoRangeEditerView(asset: asset!) c.location = self.location SPYNavigationController().pushViewController(c, animated: true) }) } } func gotoPhotoEditerView(asset:PHAsset) { if let window = UIApplication.sharedApplication().delegate?.window! { window.tintColor = UIColor.whiteColor() } let manager = PHImageManager.defaultManager() let options = PHImageRequestOptions() options.synchronous = true options.deliveryMode = .FastFormat options.resizeMode = .Exact manager.requestImageForAsset(asset,targetSize: CGSize(width: 2000, height: 2000), contentMode: .AspectFit, options: options) { (result, info) in dispatch_async(dispatch_get_main_queue(), { let configuration = Configuration() { builder in builder.backgroundColor = UIColor.blackColor() customizePhotoEditorViewController(builder) customizeCropToolController(builder) customizeOrientationViewController(builder) } let photoEditViewController = PhotoEditViewController(photo: result!,configuration: configuration) let toolStackController = ToolStackController(photoEditViewController: photoEditViewController) toolStackController.delegate = self SPYNavigationController().presentViewController(toolStackController, animated: true, completion: nil) }) } } //MARK: Property var disposeBag = DisposeBag() var viewModel : SPYPhotoPickerViewModel? var collection: UICollectionView? var album = Variable(PHAssetCollection.fetchAssetCollectionsWithType(PHAssetCollectionType.SmartAlbum, subtype: PHAssetCollectionSubtype.SmartAlbumRecentlyAdded, options: nil).firstObject as! PHAssetCollection) var headView = UIImageView().then{ $0.layer.borderColor = UIColor.blackColor().CGColor $0.layer.borderWidth = 2.0 $0.top = 44 + 20; $0.height = UIScreen.width; $0.width = UIScreen.width; } var place : CLLocation? var location : CLLocation? var selectedAsset : Photo? var albumView = UITableView(frame: CGRectZero, style: UITableViewStyle.Plain).then{ $0.rowHeight = 44 $0.separatorStyle = .None $0.separatorColor = UIColor.clearColor() $0.backgroundColor = UIColor.blackColor() $0.backgroundView = UIView().then{ $0.backgroundColor = UIColor.blackColor() } } var btn = UIButton().then{ $0.frame = CGRect(x: 0, y: 0, width: 100, height: 30) $0.setTitle("Album", forState: .Normal) $0.setTitleColor(UIColor.whiteColor(), forState: .Normal) $0.titleLabel!.font = UIFont.spyAvenirNextMedium(12) $0.backgroundColor = UIColor(rgba: "#03a9f4") $0.layer.cornerRadius = 3 } } extension SPYPhotoPicker: ToolStackControllerDelegate { func toolStackController(toolStackController: ToolStackController, didFinishWithImage image: UIImage) { toolStackController.dismissViewControllerAnimated(true, completion: { let c = mainStoryboard().instantiateViewControllerWithIdentifier("SPYPlacePicker") as! SPYPlacePicker c.photo = image if let loc = self.location{ c.location = loc } SPYNavigationController().pushViewController(c, animated: true) }) } func toolStackControllerDidFail(toolStackController: ToolStackController) { toolStackController.dismissViewControllerAnimated(true, completion: nil) } func toolStackControllerDidCancel(toolStackController: ToolStackController) { toolStackController.dismissViewControllerAnimated(true, completion: nil) } } let hideRect = CGRectMake(0, UIScreen.height, UIScreen.width, UIScreen.height - 64) let showRect = CGRectMake(0, 64, UIScreen.width, UIScreen.height - 64) <file_sep>/Spottly/SPYSearchResultMenuHeader.swift // // SPYSearchResultMenuHeader.swift // Spottly // // Created by HuangZhigang on 16/5/10. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import UIKit import RxSwift import Kingfisher import RxCocoa import imglyKit import Then import Groot import Photos class SPYSearchResultMenuHeader: UICollectionReusableView { var disposeBag = DisposeBag() var menu = SPYMenuBar(items: [.Top,.City,.Place(.Hot),.User]).then{ $0.separator.backgroundColor = UIColor.clearColor() } var subMenu = SPYMenuBar(items: [.Post(.Hot),.Collection(.Hot)]).then{ $0.separator.backgroundColor = UIColor.clearColor() } var delegate : SPYMenuActionDelegate? var group: ConstraintGroup? var needShowPlaces = false var query: String? let button = UIButton().then{ $0.backgroundColor = UIColor(rgba: "#212121") } let title = UILabel().then{ $0.text = "Are you looking for ..." $0.textAlignment = .Center $0.backgroundColor = UIColor.clearColor() $0.font = UIFont.spyAvenirNextRegular(16) $0.textColor = UIColor.whiteColor() $0.numberOfLines = 0 } let detail = UILabel().then{ $0.text = "coffee" $0.textAlignment = .Center $0.backgroundColor = UIColor.clearColor() $0.font = UIFont.spyAvenirNextRegular(16) $0.textColor = UIColor.whiteColor() $0.numberOfLines = 0 } func showDetail() { constrain(self,button,subMenu,replace: group!) { box,button,sub in box.height == 40+70 ~ 900 button.height == 70 sub.height == 40 } button.hidden = false subMenu.hidden = false detail.text = self.query self.setNeedsLayout() self.layoutIfNeeded() } func closeDetail() { constrain(self,button,subMenu,replace: group!) {box, button,sub in box.height == 40 ~ 900 button.height == 0 sub.height == 0 } button.hidden = true subMenu.hidden = true self.setNeedsLayout() self.layoutIfNeeded() } override init(frame: CGRect) { super.init(frame: frame) self.addSubview(menu) self.backgroundColor = UIColor.blackColor() button.addSubviews(title,detail) constrain(button,title,detail){box, title,detail in title.top == box.top + 5 detail.top == title.bottom detail.bottom == box.bottom - 5 align(left: box,title,detail) align(right: box,title,detail) } subMenu.backgroundColor = UIColor.blackColor() self.addSubviews(button,subMenu) constrain(self,button,menu,subMenu){ box,button,menu,subMenu in box.width == UIScreen.width menu.top == box.top menu.left == box.left menu.width == box.width menu.height == 40 button.top == menu.bottom button.left == box.left button.width == box.width subMenu.top == button.bottom subMenu.left == button.left subMenu.width == box.width subMenu.bottom == box.bottom } group = constrain(self,button,subMenu) { box,button,sub in box.height == 40 ~ 900 button.height == 0 sub.height == 0 } self.button.hidden = true self.subMenu.hidden = true button.rx_tap.asDriver().driveNext{ [unowned self] in constrain(self,self.button,self.subMenu,replace: self.group!) { box,button,sub in box.height == 40 ~ 900 button.height == 0 sub.height == 0 } self.button.hidden = true self.subMenu.hidden = true self.setNeedsLayout() self.layoutIfNeeded() self.needShowPlaces = true self.menu.rx_selectedSegment.value = SPYMenuAction.Place(.Hot) } .addDisposableTo(self.disposeBag) Driver.of(menu.rx_selectedSegment.asDriver(), subMenu.rx_selectedSegment.asDriver()) .merge() .filter{$0 != nil} .distinctUntilChanged { $0! == $1! } .driveNext{ [weak self](maybeAction) -> Void in guard let action = maybeAction else{ return } self?.delegate?.doMenuAction(action) }.addDisposableTo(disposeBag) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() // print("self.button.frame : \(self.button.frame)") // print("self.subMenu.frame : \(self.subMenu.frame)") } func configureCell(menuItems:[SPYMenuAction]) { self.menu.items = menuItems } }<file_sep>/Spottly/SPYSignInView.swift // // SPYAllTypeLoginView.swift // Spottly // // Created by HuangZhigang on 16/3/6. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import RxSwift import RxCocoa import UIKit class SPYSignInView: UIViewController { var disposeBag = DisposeBag() var snsLoginViewModel : SPYSNSLoginViewModel! var emailLoginViewModel: SPYEmailLoginViewModel! var facebookBtn = UIButton().then{ $0.setTitle("Sign in with Facebook", forState: .Normal) $0.backgroundColor = UIColor(rgba: "#0f228d") $0.setTitleColor(UIColor.whiteColor(), forState: .Normal) $0.titleLabel!.font = UIFont.spyAvenirNextMedium(12) $0.layer.cornerRadius = 3 } var wechatBtn = UIButton().then{ $0.setTitle("Sign in with Wechat", forState: .Normal) $0.backgroundColor = UIColor(rgba: "#2dc100") $0.setTitleColor(UIColor.whiteColor(), forState: .Normal) $0.titleLabel!.font = UIFont.spyAvenirNextMedium(12) $0.layer.cornerRadius = 3 } var sinaBtn = UIButton().then{ $0.setTitle("Sign in with sina", forState: .Normal) $0.backgroundColor = UIColor(rgba: "#d52a2c") $0.setTitleColor(UIColor.whiteColor(), forState: .Normal) $0.titleLabel!.font = UIFont.spyAvenirNextMedium(12) $0.layer.cornerRadius = 3 } var userNameField = UITextField().then{ $0.placeholder = "email" $0.layer.borderWidth = 1 $0.layer.borderColor = UIColor.spyTextColor().CGColor $0.layer.cornerRadius = 3 } var passwordField = UITextField().then{ $0.placeholder = "<PASSWORD>" $0.layer.borderWidth = 1 $0.layer.borderColor = UIColor.spyTextColor().CGColor $0.layer.cornerRadius = 3 } var register = UIButton().then{ $0.setTitle("Register", forState: .Normal) $0.setTitleColor(UIColor.whiteColor(), forState: .Normal) $0.titleLabel!.font = UIFont.spyAvenirNextMedium(12) $0.backgroundColor = UIColor.spyTextColor() $0.layer.cornerRadius = 3 } func setupViews() { let logo = UIImageView(image: UIImage(named: "Logo")!) let title = UILabel().then{ $0.text = "Welcome back to the communtiy!" $0.textAlignment = .Center $0.backgroundColor = UIColor.clearColor() $0.font = UIFont.spyAvenirNextRegular(16) $0.textColor = UIColor.spyTextColor() $0.numberOfLines = 0 } let emailTitle = UILabel().then{ $0.text = "REGISTER WITH EMAIL" $0.textAlignment = .Center $0.backgroundColor = UIColor.clearColor() $0.font = UIFont.spyAvenirNextRegular(10) $0.textColor = UIColor.spyTextColor() $0.numberOfLines = 0 } self.view.addSubviews(logo,title,facebookBtn,wechatBtn,sinaBtn,emailTitle,userNameField,passwordField,register) constrain(logo,title,facebookBtn,wechatBtn,sinaBtn){ logo,title,facebook,wechat,sina in let box = logo.superview! logo.top == box.top + 37 logo.height == 30 logo.width == 90 logo.centerX == box.centerX title.top == logo.bottom title.left == box.left + 16 title.right == box.right - 16 title.bottom == facebook.top facebook.height == 40 facebook.size == wechat.size wechat.size == sina.size align(left: title,facebook, wechat,sina) align(right: title,facebook, wechat,sina) distribute(by: 10, vertically: facebook, wechat,sina) } title.setContentHuggingPriority(UILayoutPriorityDefaultLow, forAxis: UILayoutConstraintAxis.Vertical) constrain(sinaBtn,emailTitle,userNameField,passwordField,register){ sina,emailTitle,userName,password,register in let box = sina.superview! emailTitle.top == sina.bottom + 20 emailTitle.left == box.left + 12 emailTitle.right == box.right - 12 emailTitle.bottom == userName.top - 30 userName.left == box.left + 35 userName.right == box.right - 35 userName.height == 35 userName.bottom == password.top - 10 password.left == userName.left password.right == userName.right password.height == 35 password.bottom == register.top - 20 register.left == box.left + 16 register.right == box.right - 16 register.height == 40 register.bottom == box.bottom - 5 } self.view.setNeedsLayout() self.view.layoutIfNeeded() } override func viewDidLoad() { setupViews() emailLoginViewModel = SPYEmailLoginViewModel(input: (username: userNameField.rx_text.asDriver(), password: <PASSWORD>Field.rx_text.asDriver(), loginTaps: self.register.rx_tap.asDriver()), api: Spottly.API) emailLoginViewModel.signedIn.driveNext{[weak self] loginResult in if let user = loginResult.user { SPYUserViewModel.shareMe.isMe = true SPYUserViewModel.shareMe.input = user self?.popupController?.dismiss() }else{ switch loginResult.statusCode { case 404 : DefaultWireframe.presentAlert("404") case 999 : DefaultWireframe.presentAlert("No Wifi") default : DefaultWireframe.presentAlert("default") } } }.addDisposableTo(disposeBag) snsLoginViewModel = SPYSNSLoginViewModel( input: ( facebookTap: facebookBtn.rx_tap.asObservable(), sinaTap: sinaBtn.rx_tap.asObservable(), wechatTap: wechatBtn.rx_tap.asObservable()), dependency: ( loginApi: Spottly.API, sns:RxSNS.sharedSNS ) ) snsLoginViewModel.tokenOK_fb.subscribe(onNext: { (B) -> Void in print("tokenOK_fb : \(B)") }, onError: { (error) -> Void in print("tokenOK_fb -error : \(error)") }) { () -> Void in }.addDisposableTo(self.disposeBag) snsLoginViewModel.tokenOK_sina.subscribe(onNext: { (B) -> Void in print("tokenOK_sina : \(B)") }, onError: { (error) -> Void in print("tokenOK_sina -error : \(error)") }) { () -> Void in }.addDisposableTo(self.disposeBag) snsLoginViewModel.tokenOK_wechat.subscribe(onNext: { (B) -> Void in print("tokenOK_wechat : \(B)") }, onError: { (error) -> Void in print("tokenOK_wechat -error : \(error)") }) { () -> Void in }.addDisposableTo(self.disposeBag) snsLoginViewModel.spyLoginOK.subscribe(onNext: { (B) -> Void in print("spyLoginOK : \(B)") }, onError: { (er) -> Void in print("spyLoginOK - er : \(er)") switch er as! SPYLoginError { case .UsernameConflict : DefaultWireframe.presentAlert("UsernameConflict") case .Unknown : DefaultWireframe.presentAlert("Unknow") case .NoInternet : DefaultWireframe.presentAlert("NoInternet") default : DefaultWireframe.presentAlert("default") } }, onCompleted: { () -> Void in }) { () -> Void in } .addDisposableTo(self.disposeBag) snsLoginViewModel.userInfoOK.observeOn(MainScheduler.instance).subscribe(onNext: { (LoginResult) -> Void in print("userInfoOK : \(LoginResult)") SPYUserViewModel.shareMe.isMe = true SPYUserViewModel.shareMe.input = LoginResult.user self.popupController?.dismiss() }, onError: { (er) -> Void in }, onCompleted: { () -> Void in }) { () -> Void in } .addDisposableTo(self.disposeBag) } }<file_sep>/Spottly/SPYSortBar.swift // // SPYSortView.swift // Spottly // // Created by HuangZhigang on 16/5/11. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import UIKit import RxSwift import RxCocoa import RxBlocking let SPYSortBarHeight = CGFloat(30) enum SPYSortType{ case Recently case Nearby case Following case Hot case None var stringValue : String { switch self { case Recently: return "Recently" case Nearby: return "Nearby" case Following: return "Following" case Hot: return "Hot" case None: return "None" } } } public class SPYSortBar: UIView { var rx_selectedSegment : Variable<SPYSortType?> lazy var mapBtn : UIButton = { let btn = UIButton() btn.setTitle("Map", forState: UIControlState.Normal) btn.setTitleColor(UIColor.grayColor(), forState: UIControlState.Normal) btn.setTitleColor(UIColor.spyBlueColor(), forState: UIControlState.Selected) btn.titleLabel!.font = UIFont.spyAvenirNextMedium(12) btn.addTarget(self, action: #selector(SPYSortBar.mapAction), forControlEvents: UIControlEvents.TouchUpInside) return btn }() lazy var sortBtn : UIButton = { let btn = UIButton() btn.setTitle("Sort", forState: UIControlState.Normal) btn.setTitleColor(UIColor.grayColor(), forState: UIControlState.Normal) btn.setTitleColor(UIColor.spyBlueColor(), forState: UIControlState.Selected) btn.titleLabel!.font = UIFont.spyAvenirNextMedium(12) btn.addTarget(self, action: #selector(SPYSortBar.sortAction(_:)), forControlEvents: UIControlEvents.TouchUpInside) return btn }() var items : [SPYSortType] { didSet { if let first = items.first { self.sortBtn.setTitle(first.stringValue, forState: UIControlState.Normal) } } } init(frame: CGRect ,items:[SPYSortType] ) { self.items = items self.rx_selectedSegment = Variable(items.first) super.init(frame:frame) self.configureViewHierarchy() self.configureViewConstraints() self.setNeedsLayout() self.layoutIfNeeded() } convenience init(items:[SPYSortType]) { self.init(frame: CGRectZero ,items:items) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func configureViewHierarchy() { self.addSubview(mapBtn) self.addSubview(sortBtn) } private func configureViewConstraints() { constrain(self,mapBtn,sortBtn) { box,map,sort in box.width == UIScreen.width box.height == SPYSortBarHeight map.height == SPYSortBarHeight map.left == box.left + 10 map.top == box.top sort.height == SPYSortBarHeight sort.right == box.right - 10 sort.top == box.top } } func mapAction() { } func sortAction(button:UIButton) { let menu = SPYSortMenu(items: self.items) { sortType in self.rx_selectedSegment.value = sortType self.sortBtn.setTitle(sortType.stringValue, forState: UIControlState.Normal) } menu.showFrom(button) } } <file_sep>/Spottly/SPYCameraView.swift // // SPYCamera.swift // Spottly // // Created by HuangZhigang on 16/3/7. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import UIKit import RxSwift import RxCocoa enum CameraModel { case Camera case Video } class SPYCameraView: UIViewController { // let dispose = DisposeBag() // let cameraBox = UIView().then{ // $0.backgroundColor = UIColor.blackColor() // } // // let buttonBox = UIView().then{ // $0.backgroundColor = UIColor(rgba: "#25272A") // } // let model = Variable(CameraModel.Camera) // let menu = SPYMenuBar(items: ["Photo","Video"]).then{ // $0.normalTextColor = UIColor.whiteColor() // $0.backgroundColor = UIColor.blackColor() // } // // let action = UIButton().then{ // $0.setImage(UIImage(named: "cameraBtn"),forState:UIControlState.Normal) // } // // override func viewDidLoad() { // super.viewDidLoad() // setupSubviews() // menu.rx_value.asObservable().subscribeNext { [unowned self] (value) -> Void in // if value == 0 {//camera // self.action.setImage(UIImage(named: "cameraBtn"),forState:UIControlState.Normal) // // }else{//video // self.action.setImage(UIImage(named: "videoBtn"),forState:UIControlState.Normal) // // } // }.addDisposableTo(dispose) // } // func setupSubviews() // { // self.view.addSubviews(cameraBox,buttonBox,menu) // constrain(self.view, cameraBox,buttonBox,menu) { // box,camera,btn,menu in // camera.top == box.top + 44 + 20; // camera.left == box.left // camera.width == UIScreen.width // camera.height == UIScreen.width // btn.top == camera.bottom // btn.left == box.left // btn.width == UIScreen.width // btn.bottom == menu.top // menu.height == 40 // menu.left == box.left // menu.width == UIScreen.width // menu.bottom == box.bottom // } // self.buttonBox.addSubview(action) // constrain(self.buttonBox,action){ box,action in // action.center == box.center // action.width == 90 // action.height == 90 // } // // self.view.setNeedsLayout() // self.view.layoutIfNeeded() // } }<file_sep>/Spottly/String+URL.swift // // String.swift // Spottly // // Created by HuangZhigang on 16/1/6. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation extension String { var URLEscaped: String { return self.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet()) ?? "" } } <file_sep>/Spottly/SPYSNSLoginViewModel.swift // // SPYSNSLoginViewModel.swift // Spottly // // Created by HuangZhigang on 16/3/6. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import RxSwift import RxCocoa import CoreData import Groot import FBSDKLoginKit import Alamofire import SwiftyJSON enum FacebookTokenResult : ErrorType { case OK(token: String) case IsCancelled case Error(error: ErrorType) } class SPYSNSLoginViewModel { let tokenOK_fb: Observable<String> let tokenOK_sina: Observable<String> let tokenOK_wechat: Observable<String> private let spyLoginOK_fb: Observable<LoginResult> private let spyLoginOK_sina: Observable<LoginResult> private let spyLoginOK_wechat: Observable<LoginResult> private let userInfoOK_fb: Observable<LoginResult> private let userInfoOK_sina: Observable<LoginResult> private let userInfoOK_wechat: Observable<LoginResult> let spyLoginOK: Observable<LoginResult> let userInfoOK: Observable<LoginResult> init(input:( facebookTap: Observable<Void>, sinaTap: Observable<Void>, wechatTap: Observable<Void> ), dependency: ( loginApi:Spottly, sns:RxSNS ) ) { tokenOK_fb = input.facebookTap.flatMapLatest{ _ -> Observable<String> in dependency.sns.facebookLogin() }.shareReplay(1) spyLoginOK_fb = tokenOK_fb .filter {$0.characters.count > 0} .flatMapLatest { token in Spottly.API.signup(token, userType: "facebook") }.shareReplay(1) userInfoOK_fb = spyLoginOK_fb .flatMapLatest { loginResult -> Observable<LoginResult> in return creatUser(loginResult.json!["user"] as! JSONDictionary) }.shareReplay(1) tokenOK_sina = input.sinaTap.flatMapLatest{ dependency.sns.sinaLogin() }.shareReplay(1) spyLoginOK_sina = tokenOK_sina .filter {$0.characters.count > 0} .flatMapLatest { token in Spottly.API.signup(token, userType: "sina")//huang }.shareReplay(1) userInfoOK_sina = spyLoginOK_sina .flatMapLatest { loginResult -> Observable<LoginResult> in return creatUser(loginResult.json!["user"] as! JSONDictionary) }.shareReplay(1) tokenOK_wechat = input.wechatTap.flatMapLatest{ dependency.sns.wechatLogin() }.shareReplay(1) spyLoginOK_wechat = tokenOK_wechat .filter {$0.characters.count > 0} .flatMapLatest { token in Spottly.API.signup(token, userType: "wechat")//huang }.shareReplay(1) userInfoOK_wechat = spyLoginOK_wechat .flatMapLatest { loginResult -> Observable<LoginResult> in return creatUser(loginResult.json!["user"] as! JSONDictionary) }.shareReplay(1) spyLoginOK = Observable.of(spyLoginOK_fb,spyLoginOK_sina , spyLoginOK_wechat) .merge() userInfoOK = Observable.of(userInfoOK_fb, userInfoOK_sina ,userInfoOK_wechat ) .merge() } } public func creatUser(json: JSONDictionary)->Observable<LoginResult> { return Observable.create({ (observer) -> Disposable in var user : User do { user = try objectFromJSONDictionary(json, inContext: CoreDataManager.sharedManager.mainContext!) loginUserID(user.id) CoreDataManager.sharedManager.mainContext?.saveOrLogError() observer.on(.Next(.OK(user:user))) observer.on(.Completed) }catch{ print("user objectFromJSONDictionary error:\(error)") } return AnonymousDisposable {} }) } class RxSNS:NSObject, WeiboSDKDelegate,WXApiDelegate{ var sinaObserver : AnyObserver<String>? var wechatObserver : AnyObserver<String>? static let weibo_app_id = "3411442139" static let wechat_app_id = "wxe797015e51bf1f1a" static let wechat_app_secret = "2e00a0b0394eca900ae36867fbe81392" static let sharedSNS = RxSNS() func facebookLogin()->Observable<String> { return Observable.create({ (observer) -> Disposable in let fb = FBSDKLoginManager() fb.loginBehavior = .Native fb.logInWithReadPermissions(["public_profile"], fromViewController: SPYVisibleViewController(), handler: { (loginResult, error) -> Void in if loginResult.token.tokenString.characters.count > 0{ let request = FBSDKGraphRequest(graphPath: "me", parameters: ["fields" : "first_name,name,last_name,middle_name,gender,locale,timezone,updated_time,link,birthday"]) request.startWithCompletionHandler({ ( connection, user, error) -> Void in if error != nil{ print("facebook error \(error)") observer.onError(SPYSNSError.UnKnown) }else{ let name = user["name"] //huang // birthday = "12/31/1988"; // "first_name" = "<NAME>"; // gender = male; // id = 100004170512713; // "last_name" = "<NAME>"; // link = "https://www.facebook.com/app_scoped_user_id/100004170512713/"; // locale = "zh_CN"; // name = "<NAME>"; // timezone = 8; // "updated_time" = "2014-09-16T09:33:06+0000"; observer.on(.Next(loginResult.token.tokenString)) observer.on(.Completed) } }) }else if loginResult.isCancelled { observer.onError(SPYSNSError.UserCancelled) }else { print("facebook error \(error)") observer.onError(SPYSNSError.UnKnown) } }) return AnonymousDisposable {} }) } func sinaLogin()->Observable<String> { WeiboSDK.enableDebugMode(false) WeiboSDK.registerApp(RxSNS.weibo_app_id) return Observable.create({ (observer) -> Disposable in let request = WBAuthorizeRequest() request.redirectURI = "https://api.spottly.com/oauth2callback" request.scope = "all"; WeiboSDK.sendRequest(request) self.sinaObserver = observer return AnonymousDisposable {} }) } @objc func didReceiveWeiboRequest(request: WBBaseRequest!) { } @objc func didReceiveWeiboResponse(response: WBBaseResponse!) { if let authorizeResponse = response as? WBAuthorizeResponse { if authorizeResponse.statusCode == WeiboSDKResponseStatusCode.Success { let userID = authorizeResponse.userID let token = authorizeResponse.accessToken WBHttpRequest(forUserProfile: userID, withAccessToken: token, andOtherProperties: [NSObject : AnyObject](), queue: NSOperationQueue.mainQueue(), withCompletionHandler: { (request, result, error) -> Void in if error != nil{ print("sina error \(error)") self.sinaObserver!.onError(SPYSNSError.UnKnown) }else{ print("result : \(result)") let user = result as! WeiboUser let userName = user.name //huang self.sinaObserver!.on(.Next(token)) self.sinaObserver!.on(.Completed) } }) } else if authorizeResponse.statusCode == WeiboSDKResponseStatusCode.UserCancel{ self.sinaObserver!.onError(SPYSNSError.UserCancelled) } else if authorizeResponse.statusCode == WeiboSDKResponseStatusCode.AuthDeny{ self.sinaObserver!.onError(SPYSNSError.UnKnown) } } } func wechatLogin()->Observable<String> { WXApi.registerApp(RxSNS.wechat_app_id) return Observable.create({ (observer) -> Disposable in let req = SendAuthReq() req.scope = "snsapi_userinfo" req.state = "123" WXApi.sendReq(req) self.wechatObserver = observer return AnonymousDisposable {} }) } // MARK: - LOGIN func onReq(req: BaseReq!) { print("onReq\(onReq)") } func onResp(resp: BaseResp!) { if (resp is SendAuthResp) { let respTemp = resp as! SendAuthResp if respTemp.errCode != 0{ print("微信授权未成功 \(respTemp.errCode)") self.wechatObserver!.onError(SPYSNSError.StateCode(Int(respTemp.errCode))) }else{ self.loginWX(respTemp.code) } } } func loginWX(code:String) { let URL = NSURL(string: "https://api.weixin.qq.com/sns/oauth2/access_token?appid=\(RxSNS.wechat_app_id)&secret=\(RxSNS.wechat_app_secret)&code=\(code)&grant_type=authorization_code")! Alamofire.request(.GET, URL).responseJSON { (response) -> Void in guard let _ = response.response, jsonData = response.result.value else { if response.result.error != nil { self.wechatObserver!.onError(SPYSNSError.Error(response.result.error!)) }else{ self.wechatObserver!.onError(SPYSNSError.UnKnown) } return } let json = JSON(jsonData) if let openID = json["openid"].string, access_token = json["access_token"].string { self .getWXUserInfo(openID, accessToken: access_token) } } } func getWXUserInfo(openID:String,accessToken:String) { let URL = NSURL(string: "https://api.weixin.qq.com/sns/userinfo?access_token=\(accessToken)&openid=\(openID)")! Alamofire.request(.GET, URL).responseJSON { (response) -> Void in guard let _ = response.response, jsonData = response.result.value else { if response.result.error != nil { self.wechatObserver!.onError(SPYSNSError.Error(response.result.error!)) }else{ self.wechatObserver!.onError(SPYSNSError.UnKnown) } return } let json = JSON(jsonData) if let _ = json["unionid"].string { print("WXJSON : \(json)") self.wechatObserver!.on(.Next("")) self.wechatObserver!.on(.Completed) } } } func application(application: UIApplication, handleOpenURL url: NSURL) -> Bool { return WeiboSDK.handleOpenURL(url, delegate: RxSNS.sharedSNS) || WXApi.handleOpenURL(url, delegate: RxSNS.sharedSNS) } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool { return FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation) || WeiboSDK.handleOpenURL(url, delegate: RxSNS.sharedSNS) || WXApi.handleOpenURL(url, delegate: RxSNS.sharedSNS) } }<file_sep>/Spottly/SPYNewCell.swift // // SPYNewCell.swift // Spottly // // Created by HuangZhigang on 15/12/19. // Copyright © 2015年 Spottly. All rights reserved. // import Foundation import UIKit class SPYNewCell : UICollectionViewCell { var name : UILabel! override init(frame: CGRect) { super.init(frame: frame) self.name = UILabel(frame: self.bounds) self.addSubview(self.name) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { self.name.frame = self.bounds } } <file_sep>/Spottly/SPYLoginView.swift // // SPYLoginFaceBook.swift // Spottly // // Created by HuangZhigang on 16/2/22. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import RxSwift import RxCocoa import UIKit let inChina = false class SPYLoginView: UIViewController { var disposeBag = DisposeBag() var snsViewModel : SPYSNSLoginViewModel! var snsBtn = UIButton().then{ if inChina { $0.setTitle("Sign in with Wechat", forState: .Normal) $0.backgroundColor = UIColor(rgba: "#2dc100") }else{ $0.setTitle("Sign in with Facebook", forState: .Normal) $0.backgroundColor = UIColor(rgba: "#0f228d") } $0.setTitleColor(UIColor.whiteColor(), forState: .Normal) $0.titleLabel!.font = UIFont.spyAvenirNextMedium(12) $0.layer.cornerRadius = 3 } var register = UIButton().then{ $0.setTitle("Register a new account", forState: .Normal) $0.setTitleColor(UIColor.whiteColor(), forState: .Normal) $0.titleLabel!.font = UIFont.spyAvenirNextMedium(12) $0.backgroundColor = UIColor(rgba: "#03a9f4") $0.layer.cornerRadius = 3 } var signIn = UIButton().then{ $0.setTitle("Sign in with Email", forState: .Normal) $0.setTitleColor(UIColor.whiteColor(), forState: .Normal) $0.titleLabel!.font = UIFont.spyAvenirNextMedium(12) $0.backgroundColor = UIColor.spyTextColor() $0.layer.cornerRadius = 3 } func setupViews() { let logo = UIImageView(image: UIImage(named: "Logo")!) let title = UILabel().then{ $0.text = "Welcome to the community that's finding the world's best places." $0.textAlignment = .Center $0.backgroundColor = UIColor.clearColor() $0.font = UIFont.spyAvenirNextRegular(16) $0.textColor = UIColor.spyTextColor() $0.numberOfLines = 0 } let fbText = UILabel().then{ $0.text = "We will never post anything without your permission" $0.backgroundColor = UIColor.clearColor() $0.font = UIFont.spyAvenirNextRegular(10) $0.textColor = UIColor.spyTextColor() $0.numberOfLines = 1 } let signInText = UILabel().then{ $0.text = "(Use Email. Wechat or weibo to sign in)" $0.backgroundColor = UIColor.clearColor() $0.font = UIFont.spyAvenirNextRegular(10) $0.textColor = UIColor.spyTextColor() $0.numberOfLines = 1 } self.view.addSubviews(logo,title,snsBtn,fbText,register,signIn,signInText) constrain(logo,title,snsBtn){ logo,title,snsBtn in let box = logo.superview! logo.top == box.top + 37 logo.height == 30 logo.width == 90 logo.centerX == box.centerX title.top == logo.bottom title.left == box.left + 16 title.right == box.right - 16 title.bottom == snsBtn.top snsBtn.left == title.left snsBtn.width == title.width snsBtn.height == 40 } title.setContentHuggingPriority(UILayoutPriorityDefaultLow, forAxis: UILayoutConstraintAxis.Vertical) constrain(snsBtn,fbText,register,signIn,signInText){ snsBtn,fbText,register,signIn,signInText in let box = snsBtn.superview! fbText.top == snsBtn.bottom + 7 fbText.bottom == register.top - 30 register.bottom == signIn.top - 15 signIn.bottom == signInText.top - 7 signInText.bottom == box.bottom - 10 align(left: snsBtn,fbText,register,signIn,signInText) align(right: snsBtn,fbText,register,signIn,signInText) } self.view.setNeedsLayout() self.view.layoutIfNeeded() } override func viewDidLoad() { setupViews() snsViewModel = SPYSNSLoginViewModel( input: ( facebookTap: (inChina ? UIButton():snsBtn).rx_tap.asObservable(), sinaTap: UIButton().rx_tap.asObservable(), wechatTap: (inChina ? snsBtn:UIButton()).rx_tap.asObservable()), dependency: ( loginApi: Spottly.API, sns:RxSNS.sharedSNS ) ) snsViewModel.tokenOK_fb.subscribe(onNext: { (B) -> Void in print("tokenOK_fb : \(B)") }, onError: { (error) -> Void in print("tokenOK_fb -error : \(error)") }) { () -> Void in }.addDisposableTo(self.disposeBag) //huang sina wechat snsViewModel.spyLoginOK.subscribe(onNext: { (B) -> Void in print("spyLoginOK : \(B)") }, onError: { (er) -> Void in print("spyLoginOK - er : \(er)") switch er as! SPYLoginError { case .UsernameConflict : DefaultWireframe.presentAlert("UsernameConflict") case .Unknown : DefaultWireframe.presentAlert("Unknow") case .NoInternet : DefaultWireframe.presentAlert("NoInternet") default : DefaultWireframe.presentAlert("default") } }, onCompleted: { () -> Void in }) { () -> Void in } .addDisposableTo(self.disposeBag) snsViewModel.userInfoOK.observeOn(MainScheduler.instance).subscribe(onNext: { (LoginResult) -> Void in print("userInfoOK : \(LoginResult)") SPYUserViewModel.shareMe.isMe = true SPYUserViewModel.shareMe.input = LoginResult.user self.popupController?.dismiss() }, onError: { (er) -> Void in }, onCompleted: { () -> Void in }) { () -> Void in } .addDisposableTo(self.disposeBag) self.signIn.rx_tap.asDriver().driveNext { let c = mainStoryboard().instantiateViewControllerWithIdentifier("SPYSignInView") as! SPYSignInView self.popupController?.pushViewController(c, animated: true) }.addDisposableTo(self.disposeBag) self.register.rx_tap.asDriver().driveNext { let c = mainStoryboard().instantiateViewControllerWithIdentifier("SPYRegisterView") as! SPYRegisterView self.popupController?.pushViewController(c, animated: true) }.addDisposableTo(self.disposeBag) } }<file_sep>/Spottly/SPYBaseModel/NSManagedObject+Extension.swift // // NSManagedObject+Extension.swift // Spottly // // Created by HuangZhigang on 16/4/6. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import CoreData let relatedUrlKey = "relatedUrlKey" extension NSManagedObject { // var relatedUrl: String?{ // get{ // if let url = objc_getAssociatedObject(self, relatedUrlKey) as? String { // return url // } // return nil // } // set{ // objc_setAssociatedObject(self, relatedUrlKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) // } // } }<file_sep>/Podfile source 'https://github.com/CocoaPods/Specs.git' platform :ios, '8.0' use_frameworks! pod 'Alamofire', '~> 3.2.1' pod 'Loggerithm', '~> 1.3' use_frameworks! pod 'Groot' use_frameworks! pod 'RxSwift', '~> 2.0.0-beta' pod 'RxCocoa', '~> 2.0.0-beta' pod 'RxBlocking', '~> 2.0.0-beta' use_frameworks! platform :ios, '8.0' pod 'SDWebImage', '~>3.7' use_frameworks! pod 'FontAwesome.swift' pod 'Kingfisher', '~> 1.8' use_frameworks! pod 'PullToRefresher', '~> 1.0' pod 'Then', '~> 0.3' pod 'TFTransparentNavigationBar' pod 'YYKit' platform :ios, '8.0' use_frameworks! target 'Spottly' do pod 'SwiftyJSON', :git => 'https://github.com/SwiftyJSON/SwiftyJSON.git' end pod 'WeiboSDK', :git => 'https://github.com/sinaweibosdk/weibo_ios_sdk.git' pod 'STPopup' post_install do |installer| `rm -rf Pods/Headers/Private` `find Pods -regex 'Pods\/.*\.modulemap' -print0 | xargs -0 sed -i '' 's/private header.*//'` `find Pods -regex 'Pods/pop.*\\.h' -print0 | xargs -0 sed -i '' 's/\\(<\\)pop\\/\\(.*\\)\\(>\\)/\\"\\2\\"/'` end post_install do |installer| installer.pods_project.build_configuration_list.build_configurations.each do |configuration| configuration.build_settings['CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES'] = 'YES' end end <file_sep>/Spottly/SPYImglyConfigure.swift // // SPYImglyConfigure.swift // Spottly // // Created by HuangZhigang on 16/4/28. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import imglyKit // MARK: - customization func customizeCameraController(builder: ConfigurationBuilder) { builder.configureCameraViewController { options in // Enable/Disable some features options.cropToSquare = false options.maximumVideoLength = 15 options.showFilterIntensitySlider = false options.tapToFocusEnabled = false options.showCameraRoll = true options.showFilters = false options.allowedTorchModes = [.Off] // Use closures to customize the different view elements options.cameraRollButtonConfigurationClosure = { button in button.layer.borderWidth = 2.0 button.layer.borderColor = UIColor.whiteColor().CGColor } options.recordingModeButtonConfigurationClosure = { photo, _ in photo.setTitleColor(UIColor.whiteColor(), forState: .Normal) photo.backgroundColor = UIColor.blackColor() photo.setTitleColor(UIColor.redColor(), forState: .Selected) } // Force a selfie camera options.allowedCameraPositions = [ .Back ] // Disable flash options.allowedFlashModes = [ .Off ] } } func customizePhotoEditorViewController(builder: ConfigurationBuilder) { // Customize the main editor builder.configurePhotoEditorViewController { options in options.title = "Selfie-Editor" options.allowedPhotoEditorActions = [ .Crop, .Orientation, .Filter, .Adjust] options.actionButtonConfigurationClosure = { cell, action in cell.captionLabel.textColor = UIColor.whiteColor() } } } func customizeCropToolController(builder: ConfigurationBuilder) { builder.configureCropToolController { options in let bundle = NSBundle.imglyKitBundle let oneToOneCropRatio = CropRatio(ratio: 1, title: "1:1", accessibilityLabel: "1 to 1", icon: UIImage(named: "imgly_icon_option_crop_square", inBundle: bundle, compatibleWithTraitCollection: nil)?.imageWithRenderingMode(.AlwaysTemplate)) options.allowedCropRatios = [oneToOneCropRatio] options.discardButtonConfigurationClosure = { discardButton in discardButton.hidden = true } } } func customizeOrientationViewController(builder: ConfigurationBuilder) { builder.configureOrientationToolController { options in options.orientationActionButtonConfigurationClosure = { cell, action in cell.captionLabel.textColor = UIColor.whiteColor() } options.didEnterToolClosure = { print("did enter orientation tool") } options.willLeaveToolClosure = { print("will leave orientation tool") } options.orientationActionSelectedClosure = { action in switch action { case .RotateLeft: print("rotate left") case .RotateRight: print("rotate right") case .FlipVertically: print("flip vertical") case .FlipHorizontally: print("flip horizontal") case .Separator: print("Separator") } } options.allowedOrientationActions = [ .RotateLeft, .RotateRight] } } <file_sep>/Spottly/UIView+Block.swift // // UIView+Block.swift // Spottly // // Created by HuangZhigang on 16/1/7. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import UIKit extension UIView { func subviewsWithBlock(block: (UIView)-> Void) { block(self) _ = self.subviews.map { (subview) -> Void in subview.subviewsWithBlock(block) } } } <file_sep>/Spottly/SPYMoreFooterView.swift // // SPYMoreFooterView.swift // Spottly // // Created by HuangZhigang on 16/5/17. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import UIKit class SPYMoreFooterView: UICollectionReusableView { func startAnimating() { activity.startAnimating() } func stopAnimating() { activity.stopAnimating() } let activity = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray) override init(frame: CGRect) { super.init(frame: frame) // activity.frame = CGRect(x: 0, y: 0, width: 40, height: 40) self.backgroundColor = UIColor.clearColor() self.addSubview(activity) constrain(self,activity) { (box,act) in act.center == box.center } } override func layoutSubviews() { super.layoutSubviews() print("activity : \(activity.frame)") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } <file_sep>/Spottly/SPYSettingView.swift // // SPYSettingView.swift // Spottly // // Created by HuangZhigang on 16/3/12. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import RxSwift import RxCocoa import UIKit class SPYSettingView: UIViewController { var disposeBag = DisposeBag() var tableView = UITableView(frame: CGRectZero, style: .Plain) var headView = UIView() var imageView = UIImageView().then{ $0.layer.cornerRadius = 25.0 $0.backgroundColor = UIColor.grayColor() } var uidLabel = UILabel().then{ $0.text = "uid" $0.font = UIFont.spyAvenirNextMedium(12) $0.textColor = UIColor.spyBlackColor() $0.backgroundColor = UIColor.clearColor() } var realnameLabel = UILabel().then{ $0.text = "realName" $0.font = UIFont.spyAvenirNextRegular(12) $0.textColor = UIColor.spyBlackColor() $0.backgroundColor = UIColor.clearColor() } var footView = UIView().then{ let logout = UIButton().then{ $0.setTitle("Log out", forState: .Normal) $0.setTitleColor(UIColor.spyBlackColor(), forState: .Normal) $0.titleLabel!.font = UIFont.spyAvenirNextMedium(12) $0.backgroundColor = UIColor(rgba: "#f5f5f5") $0.layer.cornerRadius = 3 } $0.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: 120) $0.backgroundColor = UIColor.whiteColor() logout.frame = CGRectInset($0.frame,30,30) $0.addSubview(logout) } func setupHeadView(){ let user = UIView().then{ $0.backgroundColor = UIColor.whiteColor() } let arrow = UIImageView(image: UIImage(named: "SettingsArrow")) user.addSubviews(imageView,uidLabel,realnameLabel,arrow) constrain(user, imageView,uidLabel,realnameLabel,arrow) { box, image,uid,name,arrow in image.height == 50 image.width == 50 image.left == box.left + 16 image.top == box.top + 20 uid.top == box.top + 28 uid.left == box.left + 80 uid.width == box.width - 80*2 name.left == box.left + 80 name.width == box.width - 80*2 name.bottom == box.bottom - 37 arrow.width == 7.2 arrow.height == 14.5 arrow.right == box.right - 30 arrow.centerY == image.centerY } headView.addSubviews(user) constrain(headView, user) { (box, user) -> () in box.height == 100 box.width == UIScreen.width user.edges == box.edges } headView.setNeedsLayout() headView.layoutIfNeeded() } override func viewWillAppear(animated: Bool) { self.tableView.tableFooterView = self.footView } override func viewDidLoad() { self.tableView.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.height) self.setupHeadView() self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell") self.tableView.rowHeight = 45 self.tableView.tableHeaderView = self.headView self.tableView.backgroundColor = UIColor.whiteColor() self.view.addSubviews(self.tableView) let settings = ["Find people to follow","Rate Spottly on Appstore","Credits","Terms of use","Privacy policy","FAQ","Feedback & Comments","Version"] Observable.of(settings).asDriver(onErrorJustReturn: ["11"]).drive(self.tableView.rx_itemsWithCellIdentifier("UITableViewCell", cellType: UITableViewCell.self)){ (_, item, cell) in cell.textLabel?.text = item cell.textLabel!.font = UIFont.spyAvenirNextMedium(12) if item == "Version"{ cell.accessoryView = UILabel().then{ $0.text = "3.0.2" $0.textAlignment = .Right $0.backgroundColor = UIColor.clearColor() $0.textColor = UIColor.spyBlackColor() $0.font = UIFont.spyAvenirNextMedium(12) $0.sizeToFit() } }else{ cell.accessoryView = UIImageView(image: UIImage(named: "SettingsArrow")) } } .addDisposableTo(disposeBag) } }<file_sep>/Spottly/SPYBaseModel/Media.swift // // Media.swift // Spottly // // Created by HuangZhigang on 16/2/1. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import CoreData class Media: NSManagedObject { // Insert code here to add functionality to your managed object subclass } <file_sep>/Spottly/NSManagedObject+Dictionary.swift // // NSManagedObject+Dictionary.swift // SpottlyCoreData // // Created by HuangZhigang on 15/4/18. // Copyright (c) 2015年 Spottly. All rights reserved. // import Foundation import CoreData extension NSManagedObject { func transform(dictionary:NSDictionary){ for key in dictionary.allKeys { self.setValue((dictionary.objectForKey(key) as! String), forKey: key as! String) } } }<file_sep>/Spottly/SPYExploreViewModel.swift // // SPYExploreViewModel.swift // Spottly // // Created by HuangZhigang on 16/2/16. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import RxSwift import RxCocoa import CoreData import SwiftyJSON enum CategoryType{ case City case Nearby case Search case Life } struct SearchItem: ExploreCategory { var exploreName = "Search" var exploreImageName = "searchBall" var exploreType = CategoryType.Search } struct NearbyItem: ExploreCategory { var exploreName = "NearBy" var exploreImageName = "NearbyBall" var exploreType = CategoryType.Nearby } protocol ExploreCategory { var exploreName: String {get} var exploreImageName: String {get} var exploreType : CategoryType {get} } extension Categorie : ExploreCategory { var exploreName: String { get { return self.name! } } var exploreImageName: String { get { return self.image! } } var exploreType : CategoryType { get { return .Life } } } extension City : ExploreCategory { var exploreName: String { get { return self.name! } } var exploreImageName: String { get { return self.image! } } var exploreType : CategoryType { get { return .City } } } let categorys = getCategorie() func getCategorie() -> [ExploreCategory] { let Food = NSEntityDescription.insertNewObjectForEntityForName("Categorie", inManagedObjectContext: CoreDataManager.sharedManager.mainContext!) as! Categorie Food.name = "Food" Food.id = "95551579750669" Food.image = "https://api.spottly.com/uploader/560411e8df4e63476600008b.png" let Hotels = NSEntityDescription.insertNewObjectForEntityForName("Categorie", inManagedObjectContext: CoreDataManager.sharedManager.mainContext!) as! Categorie Hotels.name = "Hotels" Hotels.id = "95551579750671" Hotels.image = "https://api.spottly.com/uploader/56041289df4e6347660000a5.png" let Shopping = NSEntityDescription.insertNewObjectForEntityForName("Categorie", inManagedObjectContext: CoreDataManager.sharedManager.mainContext!) as! Categorie Shopping.name = "Shopping" Shopping.id = "95551579750673" Shopping.image = "https://api.spottly.com/uploader/560412e4df4e6347660000b0.png" let ThingsToDo = NSEntityDescription.insertNewObjectForEntityForName("Categorie", inManagedObjectContext: CoreDataManager.sharedManager.mainContext!) as! Categorie ThingsToDo.name = "ThingsToDo" ThingsToDo.id = "95551579750672" ThingsToDo.image = "https://api.spottly.com/uploader/560412a3df4e6347660000a7.png" let Coffee = NSEntityDescription.insertNewObjectForEntityForName("Categorie", inManagedObjectContext: CoreDataManager.sharedManager.mainContext!) as! Categorie Coffee.name = "Coffee" Coffee.id = "95551579750675" Coffee.image = "https://api.spottly.com/uploader/56042be8df4e6347660004c0.png" return [Food as ExploreCategory, Hotels as ExploreCategory, Shopping as ExploreCategory, ThingsToDo as ExploreCategory, Coffee as ExploreCategory ] } func getACity() -> City { let Tokyo = NSEntityDescription.insertNewObjectForEntityForName("City", inManagedObjectContext: CoreDataManager.sharedManager.mainContext!) as! City Tokyo.name = "Tokyo" Tokyo.id = "95530516807712" Tokyo.image = "https://api.spottly.com/uploader/545b9cf2df4e63251c04752a.png" Tokyo.countryId = "0" Tokyo.wikitravel = "http://wikitravel.org/en/Tokyo" Tokyo.wikipedia = "https://en.wikipedia.org/wiki/Tokyo" return Tokyo } func getCity() -> [ExploreCategory] { let Tokyo = NSEntityDescription.insertNewObjectForEntityForName("City", inManagedObjectContext: CoreDataManager.sharedManager.mainContext!) as! City Tokyo.name = "Tokyo" Tokyo.id = "95530516807712" Tokyo.image = "https://api.spottly.com/uploader/545b9cf2df4e63251c04752a.png" Tokyo.countryId = "0" Tokyo.wikitravel = "http://wikitravel.org/en/Tokyo" Tokyo.wikipedia = "https://en.wikipedia.org/wiki/Tokyo" let SanFrancisco = NSEntityDescription.insertNewObjectForEntityForName("City", inManagedObjectContext: CoreDataManager.sharedManager.mainContext!) as! City SanFrancisco.name = "San Francisco" SanFrancisco.id = "95530516807722" SanFrancisco.image = "https://api.spottly.com/uploader/545b9cc0df4e63251c047522.png" SanFrancisco.countryId = "0" SanFrancisco.wikitravel = "http://wikitravel.org/en/San_Francisco" SanFrancisco.wikipedia = "https://en.wikipedia.org/wiki/San_Francisco" let hongkong = NSEntityDescription.insertNewObjectForEntityForName("City", inManagedObjectContext: CoreDataManager.sharedManager.mainContext!) as! City hongkong.name = "Hong Kong" hongkong.id = "95530516807703" hongkong.image = "https://api.spottly.com/uploader/52dca627df4e63487e000c61.jpeg" hongkong.countryId = "0" hongkong.wikipedia = "https://en.wikipedia.org/wiki/Hong_Kong" hongkong.wikitravel = "http://wikitravel.org/en/Hong_Kong" let Singapore = NSEntityDescription.insertNewObjectForEntityForName("City", inManagedObjectContext: CoreDataManager.sharedManager.mainContext!) as! City Singapore.name = "Singapore" Singapore.id = "95530516807735" Singapore.image = "https://api.spottly.com/uploader/544ca174df4e63251c01487f.png" Singapore.countryId = "0" Singapore.wikipedia = "https://en.wikipedia.org/wiki/Singapore" Singapore.wikitravel = "http://wikitravel.org/en/Singapore" let London = NSEntityDescription.insertNewObjectForEntityForName("City", inManagedObjectContext: CoreDataManager.sharedManager.mainContext!) as! City London.name = "London" London.id = "95530516807733" London.image = "https://api.spottly.com/uploader/545b992fdf4e63251c0474c7.png" London.countryId = "0" London.wikipedia = "https://en.wikipedia.org/wiki/London" London.wikitravel = "http://wikitravel.org/en/London" let New_York = NSEntityDescription.insertNewObjectForEntityForName("City", inManagedObjectContext: CoreDataManager.sharedManager.mainContext!) as! City New_York.name = "New York" New_York.id = "95530516807767" New_York.image = "https://api.spottly.com/uploader/54586b73df4e63251c03cab2.png" New_York.countryId = "0" New_York.wikipedia = "https://en.wikipedia.org/wiki/New_York_City" New_York.wikitravel = "http://wikitravel.org/en/New_York_City" return [SearchItem() as ExploreCategory, NearbyItem() as ExploreCategory, Tokyo as ExploreCategory, SanFrancisco as ExploreCategory, hongkong as ExploreCategory, Singapore as ExploreCategory, London as ExploreCategory, New_York as ExploreCategory] } let citys = getCity() func postsFR(url :String) -> SPYFetchRequest { let fr = SPYFetchRequest() fr.entity = NSEntityDescription.entityForName("Place", inManagedObjectContext:SPYMainMoc()) let method = "GET" let path = url fr.httpInfo = ["METHOD" : method , "URL" : path] fr.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)] fr.predicate = NSPredicate(format: "relatedUrl CONTAINS %@",path) return fr } func collectionsFR(url :String) -> SPYFetchRequest { let fr = SPYFetchRequest() fr.entity = NSEntityDescription.entityForName("Collection", inManagedObjectContext:SPYMainMoc()) let method = "GET" let path = url fr.httpInfo = ["METHOD" : method , "URL" : path] fr.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)] fr.predicate = NSPredicate(format: "relatedUrl CONTAINS %@",path) return fr } class SPYExploreViewModel : NSObject, NSFetchedResultsControllerDelegate { var placesFRC,collectionsFRC : SPYFetchedResultsController? private let disposeBag = DisposeBag() var rx_category: Driver<[ExploreCategory]>! let menuItems: [SPYMenuAction] var cityDetailUrl: String? var mainCategory: Any init( input:( mainCategory: Any, subCategory:[ExploreCategory], menuItems: [SPYMenuAction], placesUrl:String, collectionsUrl:String ) ) { self.mainCategory = input.mainCategory self.rx_category = [input.subCategory].toObservable().asDriver(onErrorJustReturn: [getACity()]) self.menuItems = input.menuItems self.placesFRC = SPYFetchedResultsController(fetchRequest: postsFR(input.placesUrl)) self.collectionsFRC = SPYFetchedResultsController(fetchRequest: collectionsFR(input.collectionsUrl)) if mainCategory is City{ let city = (mainCategory as! City).name!.URLEscaped cityDetailUrl = "http://spottly-web.5xruby.tw/c/\(city)/detail-only" } } static var wrold : SPYExploreViewModel { return SPYExploreViewModel(input: ( mainCategory: "World", subCategory: citys, menuItems: [SPYMenuAction.Place(.Hot),SPYMenuAction.Collection(.Hot)], placesUrl: "http://staging.spottly.com:6666/categories/95551579750692/posts", collectionsUrl: "http://staging.spottly.com:6666/categories/95551579750692/collections")) } }<file_sep>/Spottly/SPYPlaceCell.swift // // SPYPlaceCell.swift // Spottly // // Created by HuangZhigang on 15/12/13. // Copyright © 2015年 Spottly. All rights reserved. // import Foundation import UIKit class SPYPlaceCell : UICollectionViewCell,ImagePresentAble { var imageView : UIImageView! var button : UIButton! override init(frame: CGRect) { super.init(frame: frame) setupImageView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { self.imageView.frame = self.bounds } func configureCell(placeOrPost:Any) { if placeOrPost is Place{ if let post = (placeOrPost as! Place).relatedPost { imageView.kf_setImageWithURL(NSURL(string: post.imageUrl!.sizeIs(.head))!) } }else if placeOrPost is Post{ let post = (placeOrPost as! Post) imageView.kf_setImageWithURL(NSURL(string: post.imageUrl!.sizeIs(.head))!) } // imageView.URL(post.imageUrl!.post2xSize) } }<file_sep>/Spottly/SPYBaseModel/City.swift // // City.swift // Spottly // // Created by HuangZhigang on 16/4/6. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import CoreData class City: NSManagedObject { // Insert code here to add functionality to your managed object subclass } <file_sep>/Spottly/SPYMenuBar.swift // // SPYMenu.swift // Spottly // // Created by HuangZhigang on 16/5/9. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import UIKit import RxSwift import RxCocoa import RxBlocking func == (lhs:SPYMenuAction , rhs:SPYMenuAction) -> Bool{ return lhs.stringValue == rhs.stringValue && lhs.typeValue == rhs.typeValue } func != (lhs:SPYMenuAction , rhs:SPYMenuAction) -> Bool{ return !(lhs == rhs) } enum SPYMenuAction { case Post(SPYSortType) case Collection(SPYSortType) case Place(SPYSortType) case Top case City case User case Recent case Photos case Details case Related case None var stringValue : String { switch self { case Post: return "Post" case Collection: return "Collection" case Place: return "Place" case Top: return "Top" case City: return "City" case User: return "User" case Recent: return "Recent" case Photos: return "Photos" case Details: return "Details" case Related: return "Related" case None: return "" } } var typeValue : SPYSortType? { switch self { case Post(let type): return type case Collection(let type): return type case Place(let type): return type default: return nil } } static func mainItems(allItems:[SPYMenuAction]) -> [SPYMenuAction] { return allItems.reduce([SPYMenuAction](), combine: { (var array, item) -> [SPYMenuAction] in let sameItem = array.filter{$0.stringValue == item.stringValue} if sameItem.count == 0{ array.append(item) } return array }) } static func subItems(allItems:[SPYMenuAction],mainItem:SPYMenuAction) -> [SPYSortType] { return allItems .filter { $0.stringValue == mainItem.stringValue } .flatMap { $0.typeValue } } static func isHaveSubtype(allItems:[SPYMenuAction]) -> Bool { return allItems.count > SPYMenuAction.mainItems(allItems).count } static func fixItem(item:SPYMenuAction, type:SPYSortType) -> SPYMenuAction? { switch item { case Post: return Post(type) case Collection: return Collection(type) case Place: return Place(type) default: return nil } } static func beTopItem(inout allItems:[SPYMenuAction],destItem:SPYMenuAction) { let oldTopIndex = allItems.indexOf { $0.stringValue == destItem.stringValue } let oldDestIndex = allItems.indexOf { $0 == destItem } let item = allItems.removeAtIndex(oldDestIndex!) allItems.insert(item, atIndex: oldTopIndex!) } } protocol SPYMenuActionDelegate { func doMenuAction(menuAction:SPYMenuAction) func headerFlowLayout() -> CSStickyHeaderFlowLayout } let SPYMenuBarHeight = CGFloat(40) public class SPYMenuBar: UIView { init(frame: CGRect ,items:[SPYMenuAction]) { self.items = items self.rx_selectedSegment = Variable(items.first) super.init(frame:frame) self.configureViewHierarchy() self.configureViewConstraints() self.setNeedsLayout() self.layoutIfNeeded() // self.layer.borderWidth = 2 // self.layer.borderColor = UIColor.redColor().CGColor self.rx_selectedSegment.asDriver().driveNext { [weak self] (maybeAction) in guard let action = maybeAction else{ return } let maybeIndex = self!.mainItems.indexOf({ action == $0 }) if let index = maybeIndex{ _ = self!.btns.map { (btn) -> Void in btn.selected = btn == (self!.viewWithTag(index + 1) as! UIButton) } } }.addDisposableTo(disposeBag) } convenience init(items:[SPYMenuAction]) { self.init(frame: CGRectZero ,items:items) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func configureViewHierarchy() { _ = mainItems.map { item in let btn = UIButton() btn.setTitle(item.stringValue, forState: UIControlState.Normal) btn.setTitleColor(normalTextColor, forState: UIControlState.Normal) btn.setTitleColor(selectedTextColor, forState: UIControlState.Selected) btn.titleLabel!.font = UIFont.spyAvenirNextMedium(12) let index = mainItems.indexOf{$0 == item}! btn.tag = (Int)(index) + (Int)(1) btn.addTarget(self, action: #selector(SPYMenuBar.buttonAction(_:)), forControlEvents: UIControlEvents.TouchUpInside) btn.selected = (index == 0) self.btns.append(btn) mainBar.addSubview(btn) } self.addSubview(mainBar) self.addSubview(separator) if SPYMenuAction.isHaveSubtype(self.items){ self.addSubview(openBtn) } } private func configureViewConstraints() { constrain(self,mainBar,separator){ box,main,separator in box.width == UIScreen.width main.top == box.top main.left == box.left main.width == box.width main.height == SPYMenuBarHeight - 1 separator.top == main.bottom separator.left == box.left separator.height == 1 separator.width == box.width } constrain(mainBar.subviews){ subviewsLayout in let width = UIScreen.width/CGFloat(subviewsLayout.count) let height = SPYMenuBarHeight for (index,subview) in subviewsLayout.enumerate(){ subview.top == subview.superview!.top subview.bottom == subview.superview!.bottom subview.width == width subview.height == height var pre : LayoutProxy? var aft : LayoutProxy? if index - 1 >= 0 { pre = subviewsLayout[index - 1] } if index + 1 <= (subviewsLayout.count - 1) { aft = subviewsLayout[index + 1] } if pre == nil{ subview.left == subview.superview!.left }else { pre!.right == subview.left } if aft == nil { subview.right == subview.superview!.right } } } if SPYMenuAction.isHaveSubtype(self.items){ constrain(self, openBtn){ box, open in open.width == SPYMenuBarHeight open.height == SPYMenuBarHeight open.right == box.right open.top == box.top } } } var selectedSegmentIndexForButton = 0 { didSet{ _ = btns.map { (btn) -> Void in btn.selected = btn == (self.viewWithTag(selectedSegmentIndexForButton + 1) as! UIButton) } } } func buttonAction(button : UIButton) { _ = btns.map { (btn) -> Void in btn.selected = btn == button } self.rx_selectedSegment.value = mainItems[button.tag - 1] } var disposeBag = DisposeBag() var mainHeight = ConstraintGroup() var rx_selectedSegment : Variable<SPYMenuAction?> let mainBar = UIView() var btns = [UIButton]() lazy var openBtn : UIButton = { let btn = UIButton() btn.setImage(UIImage(named:"Close"), forState: UIControlState.Normal) btn.setImage(UIImage(named:"Close45"), forState: UIControlState.Selected) btn.addBlockForControlEvents(UIControlEvents.TouchUpInside, block: { _ in // let imageview = btn.subviews.filter({ $0 is UIImageView }).first! // let image = (imageview as! UIImageView).image // imageview.layer.borderWidth = 1 // imageview.layer.borderColor = UIColor.blueColor().CGColor // imageview.transform = CGAffineTransformRotate(imageview.transform, CGFloat(M_PI_4)) // imageview.transform = CGAffineTransformConcat(imageview.transform, CGAffineTransformMakeRotation(CGFloat(M_PI_4))); // let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z") // rotationAnimation.toValue = M_PI_4; // rotationAnimation.duration = 0.1; // btn.layer.addAnimation(rotationAnimation, forKey: "rotationAnimation") }) return btn }() let separator = UIView().then{ $0.backgroundColor = UIColor.spyLightGrayColor() } var normalTextColor = UIColor.grayColor() { didSet{ _ = btns.map { (btn) -> Void in btn.setTitleColor(normalTextColor, forState: UIControlState.Normal) } } } var selectedTextColor = UIColor.spyBlueColor() { didSet{ _ = btns.map { (btn) -> Void in btn.setTitleColor(selectedTextColor, forState: UIControlState.Selected) } } } var items : [SPYMenuAction] { didSet { self.removeAllSubviews() self.mainBar.removeAllSubviews() self.configureViewHierarchy() self.configureViewConstraints() self.setNeedsLayout() self.layoutIfNeeded() if let first = items.first { self.rx_selectedSegment.value = first } } } var mainItems : [SPYMenuAction]{ get { return SPYMenuAction.mainItems(items) } } } <file_sep>/Spottly/SPYCollectionViewModel.swift // // SPYCollectionViewModel.swift // Spottly // // Created by HuangZhigang on 16/1/18. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import RxSwift import RxCocoa import CoreData class SPYCollectionViewModel { var postsFRC,collectionsFRC,collectionFRC: SPYFetchedResultsController? private var dispose = DisposeBag() var input : Collection init(input:Collection){ self.input = input self.collectionFRC = SPYFetchedResultsController(fetchRequest: self.input.selfFR()) self.postsFRC = SPYFetchedResultsController(fetchRequest: self.input.postsFR()) } }<file_sep>/Spottly/SPYBaseModel/Collection+CoreDataProperties.swift // // Collection+CoreDataProperties.swift // Spottly // // Created by HuangZhigang on 16/3/25. // Copyright © 2016年 Spottly. All rights reserved. // // Choose "Create NSManagedObject Subclass…" from the Core Data editor menu // to delete and recreate this implementation file for your updated model. // import Foundation import CoreData extension Collection { @NSManaged var ct: NSDate? @NSManaged var desc: String? @NSManaged var id: String @NSManaged var mt: NSDate? @NSManaged var name: String? @NSManaged var relatedUrl: String @NSManaged var postsCount: NSNumber? @NSManaged var owner: User? @NSManaged var posts: NSOrderedSet? } <file_sep>/Spottly/SPYMenuHeaderView.swift // // SPYMenuHeaderCell.swift // Spottly // // Created by HuangZhigang on 16/4/26. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import RxSwift class SPYMenuHeaderView: UICollectionReusableView { var disposeBag = DisposeBag() let menu = SPYMenuBar(items: []) let sort = SPYSortBar(items: []) var delegate : SPYMenuActionDelegate? override init(frame: CGRect) { super.init(frame: frame) self.addSubview(menu) self.addSubview(sort) constrain(self,menu,sort) { box,menu,sort in menu.top == box.top menu.right == box.right menu.left == box.left menu.height == SPYMenuBarHeight sort.height == SPYSortBarHeight sort.right == box.right sort.left == box.left sort.bottom == box.bottom } sort.hidden = true self.backgroundColor = UIColor.whiteColor() self.menu .rx_selectedSegment .asObservable() .subscribeNext({ [weak self] (maybeAction) in guard let action = maybeAction else{ return } self?.delegate?.doMenuAction(action) self?.sort.items = SPYMenuAction.subItems(self!.menu.items,mainItem:action) }).addDisposableTo(disposeBag) self.sort .rx_selectedSegment .asObservable() .subscribeNext({ [weak self] (maybeAction) in guard let sortAction = maybeAction else{ return } let action = SPYMenuAction.fixItem(self!.menu.rx_selectedSegment.value!, type: sortAction) self?.delegate?.doMenuAction(action!) SPYMenuAction.beTopItem(&self!.menu.items, destItem: action!) }).addDisposableTo(disposeBag) self.menu.openBtn.addTarget(self, action: #selector(SPYMenuHeaderView.openAction(_:)), forControlEvents: UIControlEvents.TouchUpInside) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() } func configureCell(menuItems:[SPYMenuAction]){ menu.items = menuItems } func openAction(button:UIButton) { button.selected = !button.selected if button.selected { sort.hidden = false let layout = self.delegate!.headerFlowLayout() layout.headerReferenceSize = CGSize(width: UIScreen.width, height: 70) }else{ sort.hidden = true let layout = self.delegate!.headerFlowLayout() layout.headerReferenceSize = CGSize(width: UIScreen.width, height: 40) } self.setNeedsLayout() self.layoutIfNeeded() } } <file_sep>/Spottly/SPYCreatPostViewModel.swift // // SPYCreatPostViewModel.swift // Spottly // // Created by HuangZhigang on 16/2/18. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import RxSwift import RxCocoa //struct Photo { // var image : UIImage //} //class SPYCreatPostViewModel { // let photos: Driver<[Photo]> // let places: Driver<[String : AnyObject]> // init(input:Driver<String>) // { // // } //}<file_sep>/Spottly/SPYBaseModel/Categorie+CoreDataProperties.swift // // Categorie+CoreDataProperties.swift // Spottly // // Created by HuangZhigang on 16/5/10. // Copyright © 2016年 Spottly. All rights reserved. // // Choose "Create NSManagedObject Subclass…" from the Core Data editor menu // to delete and recreate this implementation file for your updated model. // import Foundation import CoreData extension Categorie { @NSManaged var id: String? @NSManaged var name: String? @NSManaged var image: String? @NSManaged var superId: String? } <file_sep>/Spottly/SPYNotificaionCell.swift // // SPYNotificaionCell.swift // Spottly // // Created by HuangZhigang on 15/12/19. // Copyright © 2015年 Spottly. All rights reserved. // import Foundation import UIKit class SPYNotificaionCell : UICollectionViewCell,ImagePresentAble { var imageView : UIImageView! var head = UIImageView().then { $0.backgroundColor = UIColor.yellowColor() } var msg = UILabel().then{ $0.backgroundColor = UIColor.purpleColor() $0.numberOfLines = 2 $0.text = "@msg" } var time = UILabel().then{ $0.backgroundColor = UIColor.purpleColor() $0.text = "@time" $0.numberOfLines = 1 } override init(frame: CGRect) { super.init(frame: frame) let msgBox = UIView() msgBox.backgroundColor = UIColor.redColor() setupImageView() self.addSubviews(head,msgBox,imageView) constrain(head,msgBox,imageView){ head,msg,image in let box = head.superview! distribute(by: 10, leftToRight: head,msg,image) align(centerY: box,head,msg,image) head.left == box.left + 10 head.width == 40 head.height == 40 image.width == 60 image.height == 60 image.right == box.right } msgBox.addSubviews(msg,time) constrain(msg,time){ msg,time in let box = msg.superview! distribute(by: 0, vertically: msg,time) align(left: box,msg,time) align(right: box,msg,time) msg.top == box.top time.bottom == box.bottom } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { self.layer.borderColor = UIColor.brownColor().CGColor self.layer.borderWidth = 2.0 } } <file_sep>/Spottly/SPYCollectionMenu.swift // // SPYSegment.swift // Spottly // // Created by HuangZhigang on 15/12/16. // Copyright © 2015年 Spottly. All rights reserved. // import Foundation import UIKit import RxSwift import RxCocoa import RxBlocking public class SPYCollectionMenu : UIView { var btns = [UIButton]() var normalTextColor = UIColor.grayColor() { didSet{ _ = btns.map { (btn) -> Void in btn.setTitleColor(normalTextColor, forState: UIControlState.Normal) } } } var selectedTextColor = UIColor.spyBlueColor() { didSet{ _ = btns.map { (btn) -> Void in btn.setTitleColor(selectedTextColor, forState: UIControlState.Selected) } } } var items : [String]! { didSet{ self.btns.removeAll() _ = self.subviews.map { (subView) -> Void in subView.removeFromSuperview() } guard items.count != 0 else{ return } let itemWidth = CGFloat(Int(UIScreen.width)/items.count) for i in items.enumerate() { let btn = UIButton(frame: CGRectMake((CGFloat)(i.index) * itemWidth , 0, itemWidth, SPYMenuBarHeight)) btn.setTitle(items[i.index], forState: UIControlState.Normal) btn.setTitleColor(normalTextColor, forState: UIControlState.Normal) btn.setTitleColor(selectedTextColor, forState: UIControlState.Selected) btn.titleLabel!.font = UIFont.spyAvenirNextMedium(12) btn.tag = (Int)(i.index) + (Int)(1) btn.addTarget(self, action: #selector(SPYCollectionMenu.buttonAction(_:)), forControlEvents: UIControlEvents.TouchUpInside) btn.selected = (i.index == 0) self.addSubview(btn) self.btns.append(btn) } } } var selectedSegmentIndex = 0 { didSet{ _ = btns.map { (btn) -> Void in btn.selected = btn == (self.viewWithTag(selectedSegmentIndex + 1) as! UIButton) } } } override init(frame: CGRect) { super.init(frame:frame) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } convenience init(items:[String]) { self.init() defer { self.items = items } guard items.count != 0 else{ return } let itemWidth = CGFloat(Int(UIScreen.width)/items.count) for i in items.enumerate() { let btn = UIButton(frame: CGRectMake((CGFloat)(i.index) * itemWidth , 0, itemWidth, SPYMenuBarHeight)) btn.setTitle(items[i.index], forState: UIControlState.Normal) btn.setTitleColor(normalTextColor, forState: UIControlState.Normal) btn.setTitleColor(selectedTextColor, forState: UIControlState.Selected) btn.titleLabel!.font = UIFont.spyAvenirNextMedium(12) btn.tag = (Int)(i.index) + (Int)(1) btn.addTarget(self, action: #selector(SPYCollectionMenu.buttonAction(_:)), forControlEvents: UIControlEvents.TouchUpInside) btn.selected = (i.index == 0) self.addSubview(btn) self.btns.append(btn) self.backgroundColor = UIColor.whiteColor() } self.items = items self.backgroundColor = UIColor.whiteColor() } var disposeBag = DisposeBag() var rx_value = PublishSubject<Int>() var value = 0 func buttonAction(button : UIButton) { _ = btns.map { (btn) -> Void in btn.selected = btn == button } self.selectedSegmentIndex = button.tag - 1 rx_value.onNext(button.tag - 1) self.value = button.tag - 1 } override public func layoutSubviews() { // self.layer.borderColor = UIColor.spyBgColor().CGColor // self.layer.borderColor = UIColor.redColor().CGColor // self.layer.borderWidth = 2.0 _ = btns.map { (btn) -> Void in var rect = btn.frame rect.origin.y = 0 // rect.size.height = SPYMenuBarHeight rect.size.height = self.height btn.frame = rect } } } <file_sep>/Spottly/SPYTabBarController.swift // // SPYTabBarController.swift // Spottly // // Created by HuangZhigang on 16/1/9. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import UIKit class SPYTabBarController: UITabBarController { @IBAction func unwindToTabBarController(segue: UIStoryboardSegue) { } }<file_sep>/Spottly/SPYBaseModel/User+CoreDataProperties.swift // // User+CoreDataProperties.swift // Spottly // // Created by HuangZhigang on 16/2/1. // Copyright © 2016年 Spottly. All rights reserved. // // Choose "Create NSManagedObject Subclass…" from the Core Data editor menu // to delete and recreate this implementation file for your updated model. // import Foundation import CoreData extension User { @NSManaged var bio: String? @NSManaged var head: String? @NSManaged var id: String @NSManaged var loc: String? @NSManaged var mt: String? @NSManaged var name: String? @NSManaged var site: String? @NSManaged var uid: String? @NSManaged var followersCount: NSNumber? @NSManaged var followingsCount: NSNumber? @NSManaged var likesCount: NSNumber? @NSManaged var postsCount: NSNumber? @NSManaged var collectionsCount: NSNumber? @NSManaged var followingcollectionsCount: NSNumber? @NSManaged var ct: NSDate? @NSManaged var collections: NSSet? @NSManaged var inverseOriginer: Post? @NSManaged var inverseFromer: Post? @NSManaged var posts: NSSet? } <file_sep>/Spottly/SPYBaseModel/Place+CoreDataProperties.swift // // Place+CoreDataProperties.swift // Spottly // // Created by HuangZhigang on 16/5/11. // Copyright © 2016年 Spottly. All rights reserved. // // Choose "Create NSManagedObject Subclass…" from the Core Data editor menu // to delete and recreate this implementation file for your updated model. // import Foundation import CoreData extension Place { @NSManaged var address: String? @NSManaged var ct: NSDate? @NSManaged var id: String? @NSManaged var latitude: NSNumber? @NSManaged var longitude: NSNumber? @NSManaged var mt: NSDate? @NSManaged var name: String? @NSManaged var relatedUrl: String @NSManaged var telephone: String? @NSManaged var url: String? @NSManaged var inversePost: Post? @NSManaged var user: User? } <file_sep>/Spottly/CoreDataManager.swift // // CoreDataManager.swift // Ascent // // Created by <NAME> on 12/10/14. // Copyright (c) 2014 <NAME>. All rights reserved. // import CoreData private let threadContextKey = "ThreadContextKey" private let manager = CoreDataManager() class CoreDataManager: NSObject { var store: NSPersistentStore? class var sharedManager: CoreDataManager { return manager } override class func initialize() { let _ = SPYIncrementalStoreValueTransformer() } override init() { super.init() NSNotificationCenter.defaultCenter().addObserverForName(NSManagedObjectContextDidSaveNotification, object: nil, queue: nil) { (note) -> Void in SPYLog().debug("NSManagedObjectContextDidSaveNotification :") let info = note.userInfo! if let updated = info["updated"] as? NSSet{ // SPYLog().debug("info[updated] : \(updated)") // updated.flatMap({ (maneageObject) -> Void in // if maneageObject is Place{ // if let relatedUrl = maneageObject.valueForKey("relatedUrl") // { // print("relatedUrl : \(relatedUrl)") // } // } // }) } if let inserted = info["inserted"] as? NSSet{ SPYLog().debug("info[inserted] : \(inserted.count)") } // guard let context = note.object as? NSManagedObjectContext where context.name == "ThreadContextKey" else { return } CoreDataManager.sharedManager.mainContext?.performBlock({ () -> Void in CoreDataManager.sharedManager.mainContext?.mergeChangesFromContextDidSaveNotification(note) }) } } lazy var workContext: NSManagedObjectContext = { let context = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType) context.persistentStoreCoordinator = CoreDataManager.sharedManager.persistentStoreCoordinator context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy context.name = "WorkContext" context.undoManager = nil return context }() class var threadContext: NSManagedObjectContext? { if NSThread.isMainThread(){ return CoreDataManager.sharedManager.mainContext! }else{ var threadContext = NSThread.currentThread().threadDictionary.objectForKey(threadContextKey) as? NSManagedObjectContext if threadContext == nil { threadContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType) threadContext!.persistentStoreCoordinator = CoreDataManager.sharedManager.persistentStoreCoordinator threadContext!.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy threadContext!.name = "Context(Thread:\(NSThread.currentThread().description))" threadContext!.undoManager = nil NSThread.currentThread().threadDictionary.setObject(threadContext!, forKey: threadContextKey) } return threadContext! } } lazy var mainContext: NSManagedObjectContext? = { var mainContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) mainContext.persistentStoreCoordinator = self.persistentStoreCoordinator mainContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy mainContext.name = "MainContext" mainContext.undoManager = nil return mainContext }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { let coordinator = NSPersistentStoreCoordinator(managedObjectModel: CoreDataManager.sharedManager.managedObjectModel) coordinator.name = "SPYBackCoordinator" var error: NSError? = nil let storeType = NSSQLiteStoreType let url = NSURL.applicationDocumentsDirectory().URLByAppendingPathComponent("SpottlyCoreData.sqlite") let options = [NSMigratePersistentStoresAutomaticallyOption: NSNumber(bool: true), NSInferMappingModelAutomaticallyOption: NSNumber(bool: true)]; do { try coordinator.addPersistentStoreWithType(storeType, configuration: nil, URL: url, options: options) #if !(TARGET_OS_EMBEDDED) let url = NSURL.applicationDocumentsDirectory().URLByAppendingPathComponent("SpottlyCoreData.sqlite").absoluteString let modelFilePath = NSBundle.mainBundle().URLForResource("SpottlyCoreData", withExtension: "momd")!.absoluteString let project: NSDictionary = [ "storeFilePath": url, "storeFormat": NSNumber(integer: 1), "modelFilePath": modelFilePath, "v": "1" ] let projectFile = "/users/huangzhigang/desktop/\(NSBundle.mainBundle().infoDictionary![kCFBundleNameKey as String]!).cdp" let ok = project.writeToFile(projectFile, atomically: true) #endif } catch var error1 as NSError { error = error1 if let code = error?.code { if code == NSMigrationMissingMappingModelError { SPYLog().error("Error, migration failed. Delete model at \(url)") } else { SPYLog().error("Error creating persistent store: \(error?.description)") } } abort() } catch { fatalError() } return coordinator }() lazy var managedObjectModel: NSManagedObjectModel = { let modelURL = NSBundle.mainBundle().URLForResource("SpottlyCoreData", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() #if !(TARGET_OS_EMBEDDED) func createCoreDataDebugProjectWithType(storeFormat: NSNumber, storeURL: String, modelFilePath: String) { let project: NSDictionary = [ "storeFilePath": storeURL, "storeFormat" : storeFormat, "modelFilePath": modelFilePath, "v" : "1" ] let projectFile = "/tmp/\(NSBundle.mainBundle().infoDictionary![kCFBundleNameKey as String]!).cdp" project.writeToFile(projectFile, atomically: true) } #endif var applicationDocumentsDirectory: NSURL { let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.endIndex-1] as NSURL } /* private lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { let storeType = SPYIncrementalStore.storeType var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), { () -> Void in var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." let options = [NSMigratePersistentStoresAutomaticallyOption: NSNumber(bool: true), NSInferMappingModelAutomaticallyOption: NSNumber(bool: true)]; let store: NSPersistentStore? do { store = try coordinator!.addPersistentStoreWithType(storeType, configuration: nil, URL: nil, options: options) } catch { fatalError("NSPersistentStore Error: \(error)") } if store == nil { coordinator = nil if let code = error?.code { if code == NSMigrationMissingMappingModelError { print("Error, migration failed. Delete model at ") } else { print("Error creating persistent store: \(error?.description)") } } abort() }else{ self.store = store } // }) return coordinator }() */ } <file_sep>/Spottly/SPYBaseModel/Place.swift // // Place.swift // Spottly // // Created by HuangZhigang on 16/2/10. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import CoreData class Place: NSManagedObject { let relatedPostCache = [Post]() func relatedPost(url:String) -> Post? { let posts = relatedPostCache.filter { $0.relatedUrl == url } if let post = posts.first{ return post }else{ let fr = NSFetchRequest(entityName: "Post") let idPredicate = NSPredicate(format: "place.id = %@",self.id!) let urlPredicates = (self.relatedUrl as NSString).componentsSeparatedByString(" ").map{ url -> NSPredicate in return NSPredicate(format: "relatedUrl CONTAINS %@",url) } let urlPredicate = NSCompoundPredicate(orPredicateWithSubpredicates: urlPredicates) fr.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [urlPredicate,idPredicate]) var post = nil as Post? CoreDataManager.sharedManager.mainContext!.performBlockAndWait({ do { let result = try? CoreDataManager.sharedManager.mainContext!.executeFetchRequest(fr) post = result!.first as? Post } catch let error as NSError{ SPYLog().error("relatedPost Error :\(error)") } }) return post } } lazy var relatedPost: Post? = { let fr = NSFetchRequest(entityName: "Post") let idPredicate = NSPredicate(format: "place.id = %@",self.id!) let urlPredicates = (self.relatedUrl as NSString).componentsSeparatedByString(" ").map{ url -> NSPredicate in return NSPredicate(format: "relatedUrl CONTAINS %@",url) } let urlPredicate = NSCompoundPredicate(orPredicateWithSubpredicates: urlPredicates) fr.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [urlPredicate,idPredicate]) var post = nil as Post? CoreDataManager.sharedManager.mainContext!.performBlockAndWait({ do { let result = try? CoreDataManager.sharedManager.mainContext!.executeFetchRequest(fr) post = result!.first as? Post } catch let error as NSError{ SPYLog().error("relatedPost Error :\(error)") } }) if post == nil{ print("fr.predicate :\(fr.predicate)") } return post }() func postsFR() -> SPYFetchRequest { let fr = SPYFetchRequest() fr.entity = NSEntityDescription.entityForName("Post", inManagedObjectContext: SPYMainMoc()) let path = SPYRouter.PostsInPlaces(self.id!) .fullPath .orderBy(.CreateTime(.Desc)) let method = SPYRouter.PostsInPlace(self.id!).method.rawValue fr.httpInfo = ["METHOD" : method , "URL" : path] fr.predicate = NSPredicate(format: "place.id = %@",self.id!) fr.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)] return fr } func collectionsFR() -> SPYFetchRequest { let fr = SPYFetchRequest() fr.entity = NSEntityDescription.entityForName("Collection", inManagedObjectContext: SPYMainMoc()) let path = SPYRouter.CollectionRelatedPlace(self.id!) .fullPath .orderBy(.CreateTime(.Desc)) let method = SPYRouter.CollectionRelatedPlace(self.id!).method.rawValue fr.httpInfo = ["METHOD" : method , "URL" : path] fr.predicate = NSPredicate(format: "relatedUrl CONTAINS %@",path) fr.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)] return fr } func collectionFR() -> SPYFetchRequest { let fr = SPYFetchRequest() fr.entity = NSEntityDescription.entityForName("Collection", inManagedObjectContext: SPYMainMoc()) //huang // let path = SPYRouter.CollectionRelatedPlace(self.id!) // .fullPath // .orderBy(.CreateTime(.Desc)) // let method = SPYRouter.CollectionRelatedPlace(self.id!).method.rawValue // fr.httpInfo = ["METHOD" : method , "URL" : path] // fr.predicate = NSPredicate(format: "relatedUrl CONTAINS %@",path) // fr.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)] return fr } // Insert code here to add functionality to your managed object subclass } <file_sep>/Spottly/SPYPlacePicker.swift // // SPYPlacePicker.swift // Spottly // // Created by HuangZhigang on 16/2/21. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import UIKit import RxSwift import Kingfisher import RxCocoa import Then import Groot import Photos import STPopup import MapKit func CoordinateFromJSON(json: NSDictionary) -> CLLocationCoordinate2D { let lat = json.objectForKey("lat") as! Double let lon = json.objectForKey("lon") as! Double return CLLocationCoordinate2D(latitude: lat, longitude: lon) } func CoordinateFromJSON(json: NSDictionary, withKeyPath keypath: String) -> CLLocationCoordinate2D { let locjson = json.valueForKeyPath(keypath) as! NSDictionary return CoordinateFromJSON(locjson) } class SPYPlacePicker:UIViewController { var headView = UIView().then{ $0.backgroundColor = UIColor(rgba: "#212121") } var collection = SPYCollectionViewSubClass.spyRegisterClass(SPYSiteCell.self) var disposeBag = DisposeBag() @IBOutlet weak var backButton: UIBarButtonItem! var photo : UIImage? var videoUrl : NSURL? var location = CLLocation(latitude: 36.00, longitude: 126.00) //huang 默认值是当前位置 var map = MKMapView().then{ $0.backgroundColor = UIColor.grayColor() } var locImage = UIImageView().then{ $0.backgroundColor = UIColor.blueColor() } var cityPicker = UIButton().then{ $0.setTitle("in Paris France",forState:.Normal) $0.titleLabel!.font = UIFont.spyAvenirNextRegular(14) $0.backgroundColor = UIColor(rgba: "#171717") } var cityInfo = UILabel().then { $0.text = "Searching only in Paris, France…" $0.backgroundColor = UIColor(rgba: "#212121") $0.font = UIFont.spyAvenirNextRegular(10) $0.textColor = UIColor.whiteColor() $0.textAlignment = .Center } var searchBar = SPYSearchBar().then{ $0.placeholder = "Just input a 'c' " $0.barStyle = .Black $0.placeholder = "Search" $0.barTintColor = UIColor(rgba: "#171717") $0.backgroundColor = UIColor(rgba: "#171717") _ = $0.subviews.map { _ = $0.subviews.map{ if $0.dynamicType == NSClassFromString("UISearchBarTextField"){ $0.backgroundColor = UIColor.whiteColor() } } } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // self.headView.top = 0 print("self.headView.frame :\(self.headView.frame)") print("self.collection.frame :\(self.collection.frame)") print("self.view.frame :\(self.view.frame)") } func setupHeadView(){ let fromTheWeb = UILabel().then { $0.text = "FROM THE WEB" $0.backgroundColor = UIColor(rgba: "#212121") $0.font = UIFont.spyAvenirNextRegular(10) $0.textColor = UIColor.whiteColor() $0.textAlignment = .Center } headView.addSubviews(map,fromTheWeb,searchBar,cityPicker,cityInfo) constrain(map,fromTheWeb,searchBar,cityPicker,cityInfo){ map,web,search,picker,info in let box = map.superview! box.width == UIScreen.width map.top == box.top map.width == box.width map.height == 88 map.left == box.left distribute(by: 0, vertically: map,web,search) align(left: map,web,search,picker,info) align(right: map,web,search,picker,info) web.height == 40 search.height == 30 picker.top == search.bottom + 16 picker.height == 40 info.top == picker.bottom info.height == 20 info.bottom == box.bottom } headView.setNeedsLayout() headView.layoutIfNeeded() } func configureCollection() { searchBar .rx_text .asDriver() .throttle(0.3) .distinctUntilChanged() .flatMapLatest { (query) -> Driver<[PlaceStruct]> in self.searchBar.canBecomeFristRespond = !query.isEmpty return Spottly.API.searchFoursqPlace(query.isEmpty ? "*":query ,coordinate:self.location.coordinate) .retry(3) .startWith([]) .asDriver(onErrorJustReturn: []) } .drive(self.collection.rx_itemsWithCellIdentifier("SPYSiteCell", cellType: SPYSiteCell.self)) { (_, place, cell) in cell.title.text = place.name cell.detail.text = place.address } .addDisposableTo(disposeBag) let layout = self.collection.collectionViewLayout as! UICollectionViewFlowLayout layout.itemSize = CGSize(width: UIScreen.width,height: 60) layout.headerReferenceSize = CGSize(width: UIScreen.width,height: 240) self.collection.rx_modelSelected(PlaceStruct) .asDriver() .driveNext{ place -> Void in let c = mainStoryboard().instantiateViewControllerWithIdentifier("SPYQuickSave") as! SPYQuickSave c.place = place c.photo = self.photo c.videoUrl = self.videoUrl c.successSegue = UIStoryboardSegue(identifier: "dd", source: self, destination: rootViewController()){ self.performSegueWithIdentifier("toTabBar", sender: self) } let st = STPopupController(rootViewController: c) st.containerView.layer.cornerRadius = 10 if (NSClassFromString("UIBlurEffect") != nil){ st.backgroundView = UIVisualEffectView(effect: UIBlurEffect(style: .Dark)) st.backgroundView.alpha = 0.8 st.navigationBarHidden = true } st.presentInViewController(self) }.addDisposableTo(self.disposeBag) } func configureNavBar() { self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "BackWhite"), style: UIBarButtonItemStyle.Plain, target: self, action: #selector(SPYPlacePicker.backAction)) self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "cancel"), style: UIBarButtonItemStyle.Plain, target: self, action: #selector(SPYPlacePicker.gotoTabbarController)) self.navigationItem.rightBarButtonItem?.tintColor = UIColor.whiteColor() self.navigationItem.leftBarButtonItem?.tintColor = UIColor.whiteColor() self.title = "Picker a Place" } func backAction(){ self.navigationController?.popViewControllerAnimated(true); } func gotoTabbarController() { self.performSegueWithIdentifier("unwindToTabBarController", sender: self) } override func viewDidLoad() { self.setupHeadView() self.configureNavBar() self.collection.addSubview(self.headView) self.view.addSubview(self.collection) constrain(self.view,self.collection, self.headView) { (box,collection, head) -> () in collection.width == UIScreen.width collection.top == box.top + 64 collection.left == box.left head.top == collection.top head.left == collection.left collection.height == box.height } configureCollection() self.collection.backgroundColor = UIColor.blackColor() self.collection.handleAfterReloadData = { if self.searchBar.canBecomeFristRespond{ self.searchBar.becomeFirstResponder() } } self.collection.rx_contentOffset .asDriver() .filter{ UIScrollView.needMore(self.collection, offset: $0)} .throttle(0.2) .driveNext { point in self.doMore() } .addDisposableTo(disposeBag) map.setRegion(MKCoordinateRegionMakeWithDistance(self.location.coordinate, 5000, 5000),animated: false) map.addAnnotation(SPYAnnotation(coordinate: self.location.coordinate)) } func doMore() { } } class SPYAnnotation :NSObject, MKAnnotation { var coordinate: CLLocationCoordinate2D var title: String? var subtitle: String? init(coordinate:CLLocationCoordinate2D) { self.coordinate = coordinate super.init() } }<file_sep>/Spottly/SPYAlbumCell.swift // // SPYAlbumCell.swift // Spottly // // Created by HuangZhigang on 16/3/10. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation let numLabelWidth = CGFloat(50.0) class SPYAlbumCell: UITableViewCell { var numLabel = UILabel().then{ $0.text = "dsds" $0.textAlignment = .Right $0.textColor = UIColor.whiteColor() } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) let rect = CGRectMake(UIScreen.width - numLabelWidth - 30,0, numLabelWidth, self.height) numLabel.frame = rect self.addSubview(numLabel) } override func layoutSubviews() { super.layoutSubviews() self.imageView?.frame = CGRectMake(0, 0, self.height, self.height) self.imageView?.backgroundColor = UIColor.grayColor() self.textLabel?.frame = CGRectMake(self.height + 8, 0, UIScreen.width - 40 - 8 - numLabelWidth - 30, self.height) for view in self.contentView.superview!.subviews{ let className = NSStringFromClass(view.dynamicType) if className.hasSuffix("SeparatorView"){ view.hidden = true } } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }<file_sep>/SpottlyTests/ExploreAPITests.swift // // SpottlyTests.swift // SpottlyTests // // Created by HuangZhigang on 15/12/23. // Copyright © 2015年 Spottly. All rights reserved. // import XCTest import Alamofire import SwiftyJSON import RxSwift import RxBlocking import RxCocoa @testable import Spottly class ExploreAPITests: XCTestCase { let cityID = "95551579422772" let collectionID = "95551746015300" let placeID = "95551731532104" let categoriesID = "95551579750669"//food let userID = "95551582372079" let postID = "95551852904511" let coordinate = CLLocationCoordinate2D(latitude: 39.9345408981, longitude: 116.4464434002) let namePara = "edwy" let tag = "Food" override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testPlacesInCollection_nearby() { let URL = SPYRouter.PlacesInCollection(collectionID) .fullPath .filter([.Coordinate(coordinate)]) .orderBy(.Distance(.Asc)) .count(2) let expectation = expectationWithDescription("Get: \(URL)") Alamofire.request(.GET, URL).responseJSON { response in expectation.fulfill() print("testPlacesInCollection_nearby : \(URL) \n ERROR : \(response.result.error)") XCTAssertLessThan(response.response!.statusCode,400,"返回错误") XCTAssertNotNil(response.result.value, "返回数据不应该为空") let json = JSON(response.result.value!) XCTAssertNotNil(json["data"], "返回数据不应该为空") let array = json["data"]["places"].array XCTAssertNotNil(array, "返回数据不应该为空") if let a = array{ XCTAssertGreaterThan(a.count, 0) } } waitForExpectationsWithTimeout(15) { (error) in if error != nil{ XCTFail("❌") } } } func testPlacesInCollection_recently() { let URL = SPYRouter.PlacesInCollection(collectionID) .fullPath .filter([.Coordinate(coordinate)]) .orderBy(.CreateTime(.Asc)) .count(2) let expectation = expectationWithDescription("Get: \(URL)") Alamofire.request(.GET, URL).responseJSON { response in expectation.fulfill() print("testPlacesInCollection_recently : \(URL) \n ERROR : \(response.result.error)") XCTAssertLessThan(response.response!.statusCode,400,"返回错误") XCTAssertNotNil(response.result.value, "返回数据不应该为空") let json = JSON(response.result.value!) XCTAssertNotNil(json["data"], "返回数据不应该为空") let array = json["data"]["places"].array XCTAssertNotNil(array, "返回数据不应该为空") if let a = array{ XCTAssertGreaterThan(a.count, 0) } } waitForExpectationsWithTimeout(15) { (error) in if error != nil{ XCTFail("❌") } } } func testCity_category_places_follow() { let URL = SPYRouter.City(cityID, .Places) .fullPath .filter([SPYFilter.CategoryId(categoriesID),.FollowIs(true)]) .orderBy(SPYOrder.Rating(.Desc)) .count(2) let expectation = expectationWithDescription("Get: \(URL)") Alamofire.request(.GET, URL).responseJSON { response in expectation.fulfill() print("testCity_category_places_follow : \(URL) \n ERROR : \(response.result.error)") XCTAssertLessThan(response.response!.statusCode,400,"返回错误") XCTAssertNotNil(response.result.value, "返回数据不应该为空") let json = JSON(response.result.value!) XCTAssertNotNil(json["data"], "返回数据不应该为空") let array = json["data"]["places"].array XCTAssertNotNil(array, "返回数据不应该为空") if let a = array{ XCTAssertGreaterThan(a.count, 0) }else{ print("ERROR : \(response.result.error)") } } waitForExpectationsWithTimeout(15) { (error) in if error != nil{ XCTFail("❌") } } } func testCity_category_places() { let URL = SPYRouter.City(cityID, .Places) .fullPath .filter([SPYFilter.CategoryId(categoriesID)]) .orderBy(SPYOrder.Rating(.Desc)) .count(2) let expectation = expectationWithDescription("Get: \(URL)") Alamofire.request(.GET, URL).responseJSON { response in expectation.fulfill() print("testCity_category_places : \(URL) \n ERROR : \(response.result.error)") XCTAssertLessThan(response.response!.statusCode,400,"返回错误") XCTAssertNotNil(response.result.value, "返回数据不应该为空") let json = JSON(response.result.value!) XCTAssertNotNil(json["data"], "返回数据不应该为空") let array = json["data"]["places"].array XCTAssertNotNil(array, "返回数据不应该为空") if let a = array{ XCTAssertGreaterThan(a.count, 0) } } waitForExpectationsWithTimeout(15) { (error) in if error != nil{ XCTFail("❌") } } } func testCity_Collections() { let URL = SPYRouter.City(cityID, .Collections) .fullPath .count(2) let expectation = expectationWithDescription("Get: \(URL)") Alamofire.request(.GET, URL).responseJSON { response in expectation.fulfill() XCTAssertLessThan(response.response!.statusCode,400,"返回错误") XCTAssertNotNil(response.result.value, "返回数据不应该为空") let json = JSON(response.result.value!) XCTAssertNotNil(json["data"], "返回数据不应该为空") let array = json["data"]["collections"].array XCTAssertNotNil(array, "返回数据不应该为空") if let a = array{ XCTAssertGreaterThan(a.count, 0) }else{ print("testCity_Collections : \(URL) \n ERROR : \(response.result.error)") } } waitForExpectationsWithTimeout(15) { (error) in if error != nil{ XCTFail("❌") } } } func testCity_Places() { let URL = SPYRouter.City(cityID, .Places) .fullPath .orderBy(.Rating(.Desc)) .count(2) let expectation = expectationWithDescription("Get: \(URL)") Alamofire.request(.GET, URL).responseJSON { response in expectation.fulfill() XCTAssertLessThan(response.response!.statusCode,400,"返回错误") XCTAssertNotNil(response.result.value, "返回数据不应该为空") let json = JSON(response.result.value!) XCTAssertNotNil(json["data"], "返回数据不应该为空") let array = json["data"]["places"].array XCTAssertNotNil(array, "返回数据不应该为空") if let a = array{ XCTAssertGreaterThan(a.count, 0) }else{ print("testCity_Places : \(URL) \n ERROR : \(response.result.error)") } } waitForExpectationsWithTimeout(15) { (error) in if error != nil{ XCTFail("❌") } } } func testCity_Places_follow() { let URL = SPYRouter.City(cityID, .Places) .fullPath .filter([.FollowIs(true)]) .orderBy(.Rating(.Desc)) .count(2) let expectation = expectationWithDescription("Get: \(URL)") Alamofire.request(.GET, URL).responseJSON { response in expectation.fulfill() print("testCity_Places_follow : \(URL) \n ERROR : \(response.result.error)") XCTAssertLessThan(response.response!.statusCode,400,"返回错误") XCTAssertNotNil(response.result.value, "返回数据不应该为空") let json = JSON(response.result.value!) XCTAssertNotNil(json["data"], "返回数据不应该为空") let array = json["data"]["places"].array XCTAssertNotNil(array, "返回数据不应该为空") if let a = array{ XCTAssertGreaterThan(a.count, 0) } } waitForExpectationsWithTimeout(15) { (error) in if error != nil{ XCTFail("❌") } } } func testNearby_Categories_follow(){ let URL = SPYRouter.Category(categoriesID) .fullPath .filter([.Coordinate(coordinate),.FollowIs(true)]) .orderBy(.Distance(.Asc)) .count(2) let expectation = expectationWithDescription("Get: \(URL)") Alamofire.request(.GET, URL).responseJSON { response in expectation.fulfill() XCTAssertLessThan(response.response!.statusCode,400,"返回错误") XCTAssertNotNil(response.result.value, "返回数据不应该为空") let json = JSON(response.result.value!) XCTAssertNotNil(json["data"], "返回数据不应该为空") let array = json["data"]["places"].array XCTAssertNotNil(array, "返回数据不应该为空") if let a = array{ XCTAssertGreaterThan(a.count, 0) }else{ print("testNearby_Categories_follow : \(URL) \n ERROR : \(response.result.error)") } } waitForExpectationsWithTimeout(15) { (error) in if error != nil{ XCTFail("❌") } } } func testNearby_Categories(){ let URL = SPYRouter.Category(categoriesID) .fullPath .filter([.Coordinate(coordinate)]) .orderBy(.Distance(.Asc)) .count(2) let expectation = expectationWithDescription("Get: \(URL)") Alamofire.request(.GET, URL).responseJSON { response in expectation.fulfill() XCTAssertNotNil(response.result.value, "返回数据不应该为空") XCTAssertLessThan(response.response!.statusCode,400,"返回错误") let json = JSON(response.result.value!) XCTAssertNotNil(json["data"], "返回数据不应该为空") if let array = json["data"]["places"].array{ XCTAssertGreaterThan(array.count, 0) if array.count == 0{ print("testNearby_Categories : \(URL)") } }else{ print("testNearby_Categories : \(URL)") print("testNearby_Categories : \(response.result.error)") XCTFail("❌") } } waitForExpectationsWithTimeout(15) { (error) in if error != nil{ XCTFail("❌") } } } func testNearby_Collection(){ let URL = SPYRouter.NearBy(.Collections) .fullPath .filter([.Coordinate(coordinate)]) .orderBy(.Distance(.Asc)) .count(2) let expectation = expectationWithDescription("testNearby_place: \(URL)") Alamofire.request(.GET, URL).responseJSON { response in expectation.fulfill() XCTAssertNotNil(response.result.value, "返回数据不应该为空") XCTAssertLessThan(response.response!.statusCode,400,"返回错误") let json = JSON(response.result.value!) XCTAssertNotNil(json["data"], "返回数据不应该为空") if let array = json["data"]["collections"].array{ XCTAssertGreaterThan(array.count, 0) }else{ print("testNearby_Collection : \(URL)") print("testNearby_Collection : \(response.result.error)") XCTFail("❌") } } waitForExpectationsWithTimeout(15) { (error) in if error != nil{ XCTFail("❌") } } } func testNearby_place(){ let URL = SPYRouter.NearBy(.Places) .fullPath .filter([.Coordinate(coordinate),.FollowIs(true)]) .orderBy(.Distance(.Asc)) .count(2) let expectation = expectationWithDescription("testNearby_place: \(URL)") Alamofire.request(.GET, URL).responseJSON { response in expectation.fulfill() XCTAssertNotNil(response.result.value, "返回数据不应该为空") XCTAssertLessThan(response.response!.statusCode,400,"返回错误") let json = JSON(response.result.value!) XCTAssertNotNil(json["data"], "返回数据不应该为空") if let array = json["data"]["places"].array{ XCTAssertGreaterThan(array.count, 0) }else{ print("testNearby_place : \(URL)") print("testNearby_place : \(response.result.error)") XCTFail("❌") } } waitForExpectationsWithTimeout(15) { (error) in if error != nil{ XCTFail("❌") } } } func testNewNoreworthy_Collection(){ let URL = SPYRouter.NewNoteworthy(.Collections) .fullPath .count(2) let expectation = expectationWithDescription("get: \(URL)") Alamofire.request(.GET, URL).responseJSON { response in expectation.fulfill() XCTAssertNotNil(response.result.value, "返回数据不应该为空") XCTAssertLessThan(response.response!.statusCode,400,"返回错误") let json = JSON(response.result.value!) XCTAssertNotNil(json["data"], "返回数据不应该为空") if let array = json["data"]["collections"].array{ XCTAssertGreaterThan(array.count, 0) }else{ print("testNewNoreworthy_Collection : \(URL)") print("testNewNoreworthy_Collection : \(response.result.error)") XCTFail("❌") } } waitForExpectationsWithTimeout(5) { (error) in if error != nil{ XCTFail("❌") } } } func testNewNoreworthy_Post(){ let URL = SPYRouter.NewNoteworthy(.Posts) .fullPath .count(2) let expectation = expectationWithDescription("testNewNoreworthy_Post: \(URL)") Alamofire.request(.GET, URL).responseJSON { response in expectation.fulfill() XCTAssertNotNil(response.result.value, "返回数据不应该为空") XCTAssertLessThan(response.response!.statusCode,400,"返回错误") let json = JSON(response.result.value!) XCTAssertNotNil(json["data"], "返回数据不应该为空") if let array = json["data"]["posts"].array{ XCTAssertGreaterThan(array.count, 0) }else{ print("testNewNoreworthy_Post : \(URL)") print("testNewNoreworthy_Post : \(response.result.error)") XCTFail("❌") } } waitForExpectationsWithTimeout(5) { (error) in if error != nil{ XCTFail("❌") } } } func testPlacesInCity() { let URL = SPYRouter.PlacesInCity(cityID) .fullPath .orderBy(.Rating(.Desc)) .count(2) let expectation = expectationWithDescription("GET \(URL)") Alamofire.request(.GET, URL).responseJSON { response in expectation.fulfill() XCTAssertNotNil(response.result.value, "返回数据不应该为空") XCTAssertLessThan(response.response!.statusCode,400,"返回错误") let json = JSON(response.result.value!) XCTAssertNotNil(json["data"], "返回数据不应该为空") if let array = json["data"]["places"].array{ XCTAssertGreaterThan(array.count, 0) }else{ print("testPlacesInCity : \(URL)") print("testPlacesInCity : \(response.result.error)") XCTFail("❌") } } waitForExpectationsWithTimeout(5) { (error) in if error != nil{ XCTFail("❌") } } } } <file_sep>/Spottly/AppDelegate.swift // // AppDelegate.swift // Spottly // // Created by HuangZhigang on 15/12/4. // Copyright © 2015年 Spottly. All rights reserved. // import UIKit import FBSDKLoginKit import FBSDKCoreKit import STPopup import Fabric import Crashlytics @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate,UITabBarControllerDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { window?.makeKeyAndVisible() Fabric.with([Crashlytics.self]) // var d = UIFont.fontNamesForFamilyName("Helvetica Neue") // print("UIFont.familyNames() \(d)") // d = UIFont.fontNamesForFamilyName("Avenir Next") // print("UIFont.familyNames() \(d)") // print("UIFont.familyNames() \(UIFont.familyNames())") if !SPYUserViewModel.shareMe.isLogined{ let c = mainStoryboard().instantiateViewControllerWithIdentifier("SPYLoginView") as! SPYLoginView c.setValue(NSValue(CGSize: CGSize(width: i6H(300),height: i6V(500-44))), forKeyPath: "contentSizeInPopup") let st = STPopupController(rootViewController: c) st.backgroundView = UIImageView(image: UIImage(named: "loginBg")) st.transitionStyle = .SlideVertical // st.navigationBarHidden = true st.containerView.layer.cornerRadius = 10 st.presentInViewController(window!.rootViewController!,completion:nil) } let tabBarController = window!.rootViewController! as! UITabBarController tabBarController.tabBar.tintColor = UIColor.spyLogoColor() tabBarController.delegate = self let c = UIViewController() c.tabBarItem = UITabBarItem(title: "", image: UIImage(named: "cameraIcon"), tag: 2) tabBarController.viewControllers?.insert(c, atIndex: 2) FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions) initSpottlyStyle() return true } func initSpottlyStyle() { UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName: UIFont.spyHelveticaNeueLight(16), NSForegroundColorAttributeName: UIColor.spyLogoColor(), NSShadowAttributeName: NSShadow()] UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(0, -60), forBarMetrics: .Default) UINavigationBar.appearance().tintColor = UIColor.whiteColor() // UINavigationBar.appearance().barTintColor = UIColor.whiteColor() UITabBar.appearance().itemPositioning = .Centered _ = rootViewController().tabBar.items!.map({ (item) -> Void in item.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0) }) } func tabBarController(tabBarController: UITabBarController, shouldSelectViewController viewController: UIViewController) -> Bool { if viewController === tabBarController.selectedViewController { return true } if viewController === tabBarController.viewControllers![2] { // window?.rootViewController?.performSegueWithIdentifier("toLogin", sender: window!.rootViewController!) window?.rootViewController?.performSegueWithIdentifier("toCreatPost", sender: window!.rootViewController!) return false }else { return true } } func application(application: UIApplication, handleOpenURL url: NSURL) -> Bool { return RxSNS.sharedSNS.application(application, handleOpenURL: url) } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool { return RxSNS.sharedSNS.application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation) } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { FBSDKAppEvents.activateApp() // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } } <file_sep>/Spottly/SPYPostView.swift // // SPYPostViewController.swift // Spottly // // Created by HuangZhigang on 16/1/18. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import UIKit import RxSwift import Kingfisher import RxCocoa import STPopup import Then import Groot import YYKit import PullToRefresh typealias SPYPostSectionForPost = HashableSectionModel<SPYPostHeaderViewModel, Post> typealias SPYPostSectionForCollection = HashableSectionModel<SPYPostHeaderViewModel, Collection> typealias SPYPostSectionForString = HashableSectionModel<SPYPostHeaderViewModel, String> struct SPYPostHeaderViewModel:Hashable { var postViewModel: SPYPostViewModel var menuItems: [SPYMenuAction] var hashValue: Int { return menuItems.first!.stringValue.hash } } func == (lhs: SPYPostHeaderViewModel, rhs: SPYPostHeaderViewModel) -> Bool { return lhs.hashValue == rhs.hashValue } class SPYPostView : UIViewController,SPYMenuActionDelegate , UISearchBarDelegate { var header : SPYMenuHeaderView? var parallaxHeader : SPYPostHeaderView? var collection = SPYCollectionViewSubClass.spyRegisterClass(SPYPlaceCell.self,SPYCollectionCell.self,SPYWebCell.self) var dataSourceForPost : RxCollectionViewSectionedReloadDataSource<SPYPostSectionForPost>! var dataSourceForString : RxCollectionViewSectionedReloadDataSource<SPYPostSectionForString>! var dataSourceForCollection : RxCollectionViewSectionedReloadDataSource<SPYPostSectionForCollection>! var layout : CSStickyHeaderFlowLayout{ return self.collection.collectionViewLayout as!CSStickyHeaderFlowLayout } var disposeBag = DisposeBag() var bag = DisposeBag() var viewModel : SPYPostViewModel? { didSet{ // self.spyLoadViewIfNeeded() } } private var saveBtn = UIButton().then{ $0.setTitle("Save", forState: .Normal) $0.setTitleColor(UIColor.whiteColor(), forState: .Normal) $0.setTitleColor(UIColor.spyDisabledColor(), forState: .Disabled) $0.setTitleColor(UIColor.whiteColor(), forState: .Highlighted) $0.titleLabel!.font = UIFont.spyHelveticaNeueRegular(12) $0.backgroundColor = UIColor.spyLogoColor() $0.frame = CGRectMake(0,0,90,30) $0.layer.borderWidth = 1 $0.layer.borderColor = UIColor.spyLogoColor().CGColor $0.layer.cornerRadius = 3 } // MARK: - View func configureNavBar() { saveBtn .rx_observe(Bool.self , "highlighted") .subscribeNext { [unowned self] (highlighted) -> Void in self.saveBtn.backgroundColor = highlighted! ? UIColor.spyBlueColor() : UIColor.spyLogoColor() }.addDisposableTo(bag) saveBtn .rx_observe(Bool.self , "enabled") .subscribeNext { [unowned self] (enabled) -> Void in self.saveBtn.layer.borderColor = enabled! ? UIColor.spyLogoColor().CGColor : UIColor.spyDisabledColor().CGColor }.addDisposableTo(bag) self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: saveBtn) let back = UIBarButtonItem(image: UIImage(named: "BackBlack"), style: UIBarButtonItemStyle.Plain, target: self, action: #selector(SPYPostView.backAction)) let like = UIBarButtonItem(image: UIImage(named: "thumbsUp"), style: UIBarButtonItemStyle.Plain, target: self, action: #selector(SPYPostView.likeAction)) let share = UIBarButtonItem(image: UIImage(named: "sendIconS"), style: UIBarButtonItemStyle.Plain, target: self, action: #selector(SPYPostView.shareAction)) let more = UIBarButtonItem(image: UIImage(named: "moreInfo"), style: UIBarButtonItemStyle.Plain, target: self, action: #selector(SPYPostView.moreAction)) self.navigationItem.leftBarButtonItems = [back,like,share,more] self.navigationController?.navigationBar.barStyle = .Default self.navigationController?.navigationBar.tintColor = UIColor(rgba: "#444444") self.navigationController?.navigationBar.lt_setBackgroundColor(UIColor.whiteColor()) saveBtn.rx_tap.subscribeNext { [weak self]() -> Void in let c = mainStoryboard().instantiateViewControllerWithIdentifier("SPYQuickSave") as! SPYQuickSave c.rePost = self!.parallaxHeader!.post! c.photo = self!.parallaxHeader!.image.image let st = STPopupController(rootViewController: c) st.containerView.layer.cornerRadius = 10 if (NSClassFromString("UIBlurEffect") != nil){ st.backgroundView = UIVisualEffectView(effect: UIBlurEffect(style: .Dark)) st.backgroundView.alpha = 0.8 st.navigationBarHidden = true } st.presentInViewController(self) }.addDisposableTo(disposeBag) } func backAction() { self.navigationController?.popViewControllerAnimated(true) } func shareAction() { } func moreAction() { } func likeAction() { } func configureCollection() { self.reloadLayout() self.view.addSubviews(collection) constrain(self.view,collection){ box,collection in collection.top == box.top collection.left == box.left collection.right == box.right collection.bottom == box.bottom } self.view.backgroundColor = UIColor.whiteColor() collection.backgroundColor = UIColor.whiteColor() self.collection.clipsToBounds = false // collection.scrollIndicatorInsets = UIEdgeInsetsMake(64, 0, 0, 0) // let refresher = PullToRefresh() // self.collection.addPullToRefresh(refresher) {[unowned self] () -> () in // delay(2, closure: { () -> () in // self.collection.endRefreshing() // }) // } self.collection.registerClass(SPYPostHeaderView.self, forSupplementaryViewOfKind: CSStickyHeaderParallaxHeader, withReuseIdentifier: "SPYPostHeaderView") self.collection.registerClass(SPYMenuHeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "SPYMenuHeaderView") doMenuAction(.Photos) } override func viewWillDisappear(animated: Bool) { self.navigationController?.navigationBar.lt_reset() } override func viewDidLoad() { super.viewDidLoad() configureDataSourceForCollection() configureDataSourceForPost() configureDataSourceForString() configureNavBar() configureCollection() } func reloadLayout() { guard let layout = self.collection.collectionViewLayout as? CSStickyHeaderFlowLayout else{ return } layout.parallaxHeaderReferenceSize = CGSizeMake(UIScreen.width, 100); layout.parallaxHeaderMinimumReferenceSize = CGSize(width: UIScreen.width, height: 100) layout.itemSize = CGSizeMake(UIScreen.width, layout.itemSize.height); layout.headerReferenceSize = CGSize(width: UIScreen.width, height: 40) } // MARK: - DataSource func configureDataSourceForPost() { let dataSource = RxCollectionViewSectionedReloadDataSource<SPYPostSectionForPost>() dataSource.cellFactory = { (cv, ip, item)in let cell = cv.dequeueReusableCellWithReuseIdentifier("SPYPlaceCell", forIndexPath: ip) as! SPYPlaceCell cell.configureCell(item) return cell } dataSource.supplementaryViewFactory = { [unowned dataSource,unowned self] (cv, kind, ip) in if kind == UICollectionElementKindSectionHeader{ if self.header == nil { self.header = cv.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SPYMenuHeaderView", forIndexPath: ip) as? SPYMenuHeaderView self.header?.configureCell(dataSource.sectionAtIndex(ip.section).model.menuItems) self.header?.delegate = self } return self.header! }else if kind == CSStickyHeaderParallaxHeader{ if self.parallaxHeader == nil { self.parallaxHeader = cv.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SPYPostHeaderView", forIndexPath: ip) as? SPYPostHeaderView self.parallaxHeader?.handlerAfterLayout = { [unowned self] size in self.layout.parallaxHeaderReferenceSize = size self.layout.parallaxHeaderMinimumReferenceSize = size } self.parallaxHeader?.configureCell(dataSource.sectionAtIndex(ip.section).model) } return self.parallaxHeader! }else{ fatalError("kind 未识别") } } self.dataSourceForPost = dataSource } func configureDataSourceForCollection() { let dataS = RxCollectionViewSectionedReloadDataSource<SPYPostSectionForCollection>() dataS.cellFactory = { (cv, ip, item)in let cell = cv.dequeueReusableCellWithReuseIdentifier("SPYCollectionCell", forIndexPath: ip) as! SPYCollectionCell cell.configureCell(item) return cell } dataS.supplementaryViewFactory = { [unowned dataS,unowned self] (cv, kind, ip) in if kind == UICollectionElementKindSectionHeader{ if self.header == nil { self.header = cv.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SPYMenuHeaderView", forIndexPath: ip) as? SPYMenuHeaderView self.header?.delegate = self self.header?.configureCell(dataS.sectionAtIndex(ip.section).model.menuItems) } return self.header! }else if kind == CSStickyHeaderParallaxHeader{ if self.parallaxHeader == nil { self.parallaxHeader = cv.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SPYPostHeaderView", forIndexPath: ip) as? SPYPostHeaderView self.parallaxHeader?.handlerAfterLayout = { [unowned self] size in self.layout.parallaxHeaderReferenceSize = size self.layout.parallaxHeaderMinimumReferenceSize = size } self.parallaxHeader?.configureCell(dataS.sectionAtIndex(ip.section).model) } return self.parallaxHeader! }else{ fatalError("kind 未识别") } } self.dataSourceForCollection = dataS } func configureDataSourceForString() { let dataS = RxCollectionViewSectionedReloadDataSource<SPYPostSectionForString>() dataS.cellFactory = { (cv, ip, item)in let cell = cv.dequeueReusableCellWithReuseIdentifier("SPYWebCell", forIndexPath: ip) as! SPYWebCell cell.configureCell(item) cell.handlerAfterLayout = { [unowned self] size in self.layout.itemSize = size } return cell } dataS.supplementaryViewFactory = { [unowned dataS,unowned self] (cv, kind, ip) in if kind == UICollectionElementKindSectionHeader{ if self.header == nil { self.header = cv.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SPYMenuHeaderView", forIndexPath: ip) as? SPYMenuHeaderView self.header?.delegate = self self.header?.configureCell(dataS.sectionAtIndex(ip.section).model.menuItems) } return self.header! }else if kind == CSStickyHeaderParallaxHeader{ if self.parallaxHeader == nil { self.parallaxHeader = cv.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SPYPostHeaderView", forIndexPath: ip) as? SPYPostHeaderView self.parallaxHeader?.handlerAfterLayout = { [unowned self] size in self.layout.parallaxHeaderReferenceSize = size self.layout.parallaxHeaderMinimumReferenceSize = size } self.parallaxHeader?.configureCell(dataS.sectionAtIndex(ip.section).model) } return self.parallaxHeader! }else{ fatalError("kind 未识别") } } self.dataSourceForString = dataS } func headerFlowLayout() -> CSStickyHeaderFlowLayout { return self.collection.collectionViewLayout as! CSStickyHeaderFlowLayout } func doMenuAction(menuAction:SPYMenuAction) { self.bag = DisposeBag() switch menuAction { case .Photos : let headerViewModel = SPYPostHeaderViewModel(postViewModel: viewModel!, menuItems: [.Photos,.Details,.Related]) let items = viewModel!.postsFRC!.performFetchIfNeed.rxFetchedObjects.asDriver() Driver.combineLatest(Driver.just(headerViewModel),items){ h,items in return [SPYPostSectionForPost(model: h, items: items as! [Post])] } .drive(self.collection.rx_itemsWithDataSource(dataSourceForPost)) .addDisposableTo(bag) collection.rx_itemSelected .asDriver() .driveNext{ [weak self] indexPath in // let c = mainStoryboard().instantiateViewControllerWithIdentifier("SPYPostView") as! SPYPostView // let post = self!.dataSourceForPost.itemAtIndexPath(indexPath) // c.viewModel = SPYPostViewModel(input:post) // self!.navigationController?.pushViewController(c, animated: true) } .addDisposableTo(bag) layout.spyConfigureLayoutForPlaces() SPYScrollMenuHeaderToTop(self.header,collection:self.collection ,layout:self.layout) SPYObserveRequestState(self.collection, frc: viewModel?.postsFRC, dataType: .Post, bag: bag) case .Related : let headerViewModel = SPYPostHeaderViewModel(postViewModel: viewModel!, menuItems: [.Photos,.Details,.Related]) let items = viewModel!.collectionsFRC!.performFetchIfNeed.rxFetchedObjects.asDriver() Driver.combineLatest(Driver.just(headerViewModel),items){ h,items in return [SPYPostSectionForCollection(model: h, items: items as! [Collection])] } .drive(self.collection.rx_itemsWithDataSource(dataSourceForCollection)) .addDisposableTo(bag) collection.rx_itemSelected .asDriver() .driveNext{ [weak self] indexPath in let c = mainStoryboard().instantiateViewControllerWithIdentifier("SPYCollectionView") as! SPYCollectionView let collection = self!.dataSourceForCollection.itemAtIndexPath(indexPath) c.viewModel = SPYCollectionViewModel(input:collection) self!.navigationController?.pushViewController(c, animated: true) } .addDisposableTo(bag) layout.spyConfigureLayoutForCollections() SPYScrollMenuHeaderToTop(self.header!,collection:self.collection ,layout:self.layout) SPYObserveRequestState(self.collection, frc: viewModel?.collectionsFRC, dataType: .Collection, bag: bag) case .Details : let headerViewModel = SPYPostHeaderViewModel(postViewModel: viewModel!, menuItems: [.Photos,.Details,.Related]) let items = Driver.just([viewModel!.placeDetailUrl]) Driver.combineLatest(Driver.just(headerViewModel),items){ h,items in return [SPYPostSectionForString(model: h, items: items )] } .drive(self.collection.rx_itemsWithDataSource(dataSourceForString)) .addDisposableTo(bag) layout.spyConfigureLayoutForWeb() SPYScrollMenuHeaderToTop(self.header!,collection:self.collection ,layout:self.layout) default: break } } func doMore(value:Int) { switch value { case 0 : viewModel?.postsFRC?.loadMore() case 1 : viewModel?.collectionsFRC?.loadMore() default : break } } }<file_sep>/Spottly/SpottlyAPI.swift // // SpottlyAPI.swift // Spottly // // Created by HuangZhigang on 16/1/6. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import RxSwift import Alamofire import SwiftyJSON import MapKit import CoreLocation import YYKit private let instance = Spottly() public let $ = "http://api.spottly.com" extension Dictionary { var spyDescription : String { get { return self.description.stringByReplacingOccurrencesOfString("[", withString: "{").stringByReplacingOccurrencesOfString("]", withString: "}").stringByReplacingOccurrencesOfString(" ", withString: "") } } } enum SPYFilter{ case FollowIs(Bool) case ReadIs(Bool) case CategoryId(String) case Coordinate(CLLocationCoordinate2D) case NameQuery(String) case TagQuery(String) var dict: [String:AnyObject] { switch self { case FollowIs(let value): return ["follow" : NSNumber(bool: value)] case ReadIs(let value): return ["is-read" : NSNumber(bool: value)] case CategoryId(let value): return ["category-id" : value] case Coordinate(let loc): let lon = NSNumber(double: loc.longitude) let lat = NSNumber(double: loc.latitude) return ["coordinate": ["longitude": lon, "latitude": lat]] case NameQuery(let name): return ["name": ["op": "similar", "value": name]] case TagQuery(let tag): return ["tags": ["op": "include", "value": tag]] } } } enum Order: String{ case Asc = "asc" //升 case Desc = "desc" //降 } enum SPYObject: String{ case User = "user" case City = "city" case Post = "post" case Place = "place" case Collection = "collection" } enum SPYObjects: String{ case Users = "users" case Citys = "cities" case Posts = "posts" case Places = "places" case Collections = "collections" } enum SPYOrder{ case Distance(Order) case Rating(Order) case CreateTime(Order) var description: String { switch self { case Distance(let order) : return ["distance":order.rawValue].spyDescription case .Rating(let order) : return ["rating":order.rawValue].spyDescription case .CreateTime(let order) : return ["create-time":order.rawValue].spyDescription } } } extension String { func filter(filter:[SPYFilter]) -> String{ let filterDict = filter.reduce([String:AnyObject]()) { (dict, element) -> [String:AnyObject] in let nsdict = NSMutableDictionary(dictionary: dict) nsdict.addEntriesFromDictionary(element.dict) return nsdict as! [String:AnyObject] } let jsonPrettyStringEncoded = (filterDict as NSDictionary).jsonStringEncoded()!.URLEscaped return self + "?" + "filter=\(jsonPrettyStringEncoded)" } func orderBy(order:SPYOrder) -> String{ if self.containsString("?") { return self + "&" + "orderBy=\(order.description.URLEscaped)" }else { return self + "?" + "orderBy=\(order.description.URLEscaped)" } } func count(count:Int) -> String { if self.containsString("?") { return self + "&" + "count=2" }else { return self + "?" + "count=2" } } } let categoryID = "95551579750692" typealias ID = String enum SPYRouter: URLRequestConvertible { static let baseURLString = "http://staging.spottly.com:6666" case Login([String: AnyObject]) case Collection(collectionid: ID) case User(String) case PostsFromUser(userid :ID) case PostsFromCollection(collectionid :ID) case TimeLine case Likes(ID) case UploadImageData(NSData) case CreatPost([String: AnyObject]) case PlacesInCity(ID) case PostsInPlace(ID) case SearchUser(ID) case SearchPost(ID) case SearchCollection(ID) case SearchPlace(ID) case SearchCity(ID) case NewNoteworthy(SPYObjects) case NearBy(SPYObjects) case Category(String) case City(ID,SPYObjects) case PlacesInCollection(ID) case PostsInPlaces(ID) case CollectionRelatedPlace(ID) case PlacesFromUser(ID) case CollectionsFromUser(ID) case FollowingToUser(ID) case FollowerFromUser(ID) case FollowedCollections(ID) case Search(SPYObjects) case SearchPlacesInCity(ID) case SearchPlacesNearby case SearchPlacesInUser(ID) // case DestroyUser(String) var method: Alamofire.Method { switch self { case .Login: return .PUT case .UploadImageData , .CreatPost: return .POST default : return .GET } } var path: String { switch self { case .User(let userid) : return "/users/\(userid)" case .Collection(let collectionid): return "/collections/\(collectionid)" case .Login: return "/users" case .PostsFromUser(let userid): return "/users/\(userid)/posts" case .PostsFromCollection(let collectionid): return "/collections/\(collectionid)/posts" case .Likes(let userid): return "/users/\(userid)/likes" case .FollowingToUser(let userid): return "/users/\(userid)/followings" case .FollowerFromUser(let userid): return "/users/\(userid)/followers" case .FollowedCollections(let userid): return "/users/\(userid)/followed-collections" case .PlacesInCity(let cityid): return "/cities/\(cityid)/places" case .UploadImageData(let data): return "/medias" case .CreatPost: return "/posts" case .SearchUser(let query): let filter = "{\"name\":{\"op\":\"ilike\",\"value\":\"\(query)\"}}".URLEscaped return "/users?filter=\(filter)" case .SearchPost(let query): let filter = "{\"message\":{\"op\":\"ilike\",\"value\":\"\(query)\"}}".URLEscaped return "/posts?filter=\(filter)" case .SearchCollection(let query): let filter = "{\"name\":{\"op\":\"ilike\",\"value\":\"\(query)\"}}".URLEscaped return "/collections?filter=\(filter)" case .SearchPlace(let query): let filter = "{\"name\":{\"op\":\"ilike\",\"value\":\"\(query)\"}}".URLEscaped return "/places?filter=\(filter)" case .SearchCity(let query): let filter = "{\"name\":{\"op\":\"ilike\",\"value\":\"\(query)\"}}".URLEscaped return "/cities?filter=\(filter)" case .PostsInPlace(let placeId): return "/cities?filter=\(placeId)" case .NewNoteworthy(let objects): return "/categories/\(categoryID)/\(objects.rawValue)" case .NearBy(let objects): return "/\(objects.rawValue)" case .Category(let categoryID): return "/categories/\(categoryID)/places" case .City(let cityID,let objects): return "/cities/\(cityID)/\(objects.rawValue)" case .PlacesInCollection(let collectionID): return "/collections/\(collectionID)/places" case .PostsInPlaces(let placeID): return "/places/\(placeID)/posts" case .CollectionRelatedPlace(let placeID): return "/places/\(placeID)/relatedCollections" case .PlacesFromUser(let userID): return "/users/\(userID)/places" case .CollectionsFromUser(let userID): return "/users/\(userID)/collections" case .FollowingToUser(let userID): return "/users/\(userID)/followings" case .FollowerFromUser(let userID): return "/users/\(userID)/followers" case .FollowedCollections(let collectionID): return "/users/\(collectionID)/followedCollections" case Search(let objects): return "/\(objects.rawValue)" case SearchPlacesInCity(let cityID): return "/cities/\(cityID)/places" case SearchPlacesNearby: return "/places" case SearchPlacesInUser(let userID): return "/users/\(userID)/places" case .TimeLine: return "/posts/timeline" } } var fullPath : String { return SPYRouter.baseURLString + self.path } // MARK: URLRequestConvertible var URLRequest: NSMutableURLRequest { let URL = NSURL(string: SPYRouter.baseURLString)! let mutableURLRequest = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(path)) mutableURLRequest.HTTPMethod = method.rawValue switch self { case .CreatPost(let parameters): return Alamofire.ParameterEncoding.JSON.encode(mutableURLRequest, parameters: parameters).0 case .Login(let parameters): return Alamofire.ParameterEncoding.JSON.encode(mutableURLRequest, parameters: parameters).0 default: return mutableURLRequest } } } public enum SPYSNSError: ErrorType { case NoInternet case UserCancelled case UnKnown case Error(ErrorType) case StateCode(Int) } public enum SPYLoginError: ErrorType { case NoInternet case UsernameConflict case Unknown case Error(ErrorType) case StateCode(Int) } public enum SPYCocoaURLError : ErrorType { /** Unknown error occurred. */ case Unknown /** Response is not NSHTTPURLResponse */ case NonHTTPResponse(response: NSURLResponse) /** Response is not successful. (not in `200 ..< 300` range) */ case HTTPRequestFailed(response: NSHTTPURLResponse, data: NSData?) /** Deserialization error. */ case DeserializationError(error: ErrorType) } func exampleError(error: String, location: String = "\(__FILE__):\(__LINE__)") -> NSError { showAlert(error) return NSError(domain: "ExampleError", code: -1, userInfo: [NSLocalizedDescriptionKey: "\(location): \(error)"]) } struct PlaceStruct { let id: String let address: String let city: String let loc: [String:Float] let name: String let info: [String:AnyObject] let orginInfo: [String:AnyObject] init(foursqVenue venue:[String:AnyObject]){ let v = JSON(venue) address = v["location"]["address"].string ?? "NoAddress" city = v["location"]["city"].string ?? "NoCity" let lat = v["location"]["lat"].float ?? 0.0 let lon = v["location"]["lng"].float ?? 0.0 loc = ["lat":lat,"lon":lon] name = v["name"].string ?? "" id = v["id"].stringValue info = ["id" : v["id"].stringValue , "name":name , "location":v["location"].dictionaryObject!] orginInfo = venue } } extension PlaceStruct : Hashable { var hashValue: Int { return self.name.hashValue } } func == (lhs:PlaceStruct,rhs:PlaceStruct)-> Bool { return lhs.name == rhs.name && lhs.city == rhs.city } class Spottly { class var API: Spottly { return instance } private func rx_JSON(URL: NSURL) -> Observable<AnyObject> { return Dependencies.sharedDependencies.URLSession .rx_JSON(URL) } func searchFoursqPlace(query: String , coordinate: CLLocationCoordinate2D) -> Observable<[PlaceStruct]> { let FoursquareAppid = "MQWTVUOKYJ0SAROF5UOHIFSXD4YQCF1UQWSTPOVDP3HR04OI" let FoursquareSecret = "<KEY>" let escapedQuery = query.URLEscaped // let urlContent = "http://api.spottly.com/search-place?q=\(escapedQuery)&lat=\(String(coordinate.latitude))&lon=\(String(coordinate.longitude))" let urlContent = "https://api.foursquare.com/v2/venues/search?client_id=\(FoursquareAppid)&client_secret=\(FoursquareSecret)&llAcc=100&query=\(escapedQuery)&ll=\(String(coordinate.latitude)),\(String(coordinate.longitude))&v=20130101&limit=50" let url = NSURL(string: urlContent)! return rx_JSON(url) .observeOn(Dependencies.sharedDependencies.backgroundWorkScheduler) .map { json in // guard let json = json as? [AnyObject] else { // throw exampleError("Parsing error") // } let jsonModel = JSON(json) let venues = jsonModel["response"]["venues"] // print("venues : \(venues)") var places = [PlaceStruct]() for (_,subJson):(String, JSON) in venues { places.append(PlaceStruct(foursqVenue: subJson.dictionaryObject!)) } return places } .observeOn(Dependencies.sharedDependencies.mainScheduler) } func validateUsername(username: String) -> Observable<ValidationResult> { return Observable.just(.OK(message: "Username available"))//huang if username.characters.count == 0 { return Observable.just(.Empty) } // this obviously won't be if username.rangeOfCharacterFromSet(NSCharacterSet.alphanumericCharacterSet().invertedSet) != nil { return Observable.just(.Failed(message: "Username can only contain numbers or digits")) } let loadingValue = ValidationResult.Validating return self .usernameAvailable(username) .map { available in if available { return .OK(message: "Username available") } else { return .Failed(message: "Username already taken") } } .startWith(loadingValue) } func validatePassword(password: String) -> ValidationResult { return .OK(message: "Username available")//huang let numberOfCharacters = password.characters.count if numberOfCharacters == 0 { return .Empty } if numberOfCharacters < 5 { return .Failed(message: "Password must be at least \(5) characters") } return .OK(message: "Password acceptable") } func validateRepeatedPassword(password: String, repeatedPassword: String) -> ValidationResult { return .OK(message: "Username available")//huang if repeatedPassword.characters.count == 0 { return .Empty } if repeatedPassword == password { return .OK(message: "Password repeated") } else { return .Failed(message: "Password different") } } func usernameAvailable(username: String) -> Observable<Bool> { let URL = NSURL(string: "https://github.com/\(username.URLEscaped)")! return Observable.create { observer in Alamofire.request(.GET, URL).responseJSON { (response) -> Void in guard let _ = response.response, _ = response.data else { observer.on(.Error(response.result.error ?? SPYCocoaURLError.Unknown)) return } observer.on(.Next(response.response?.statusCode == 404)) observer.on(.Completed) } return AnonymousDisposable {} } } //201是注册,200是登录。 func signup(token: String, userType: String) -> Observable<LoginResult> { // let data = ["email": "<EMAIL>", "password": "1", "user-type": "email"] let data = ["token": token, "user-type": userType, "platform": "iOS", "platform-identity": "xyz", "platform-notification-token": "abc"] // let data = ["platform": "iOS", "platform-notification-token": "abc", "token": "<KEY>", "user-type": "facebook", "platform-identity": "xyz"]//edwyn facebook // let data = ["platform": "iOS", "platform-notification-token": "abc", "token": "<KEY>", "user-type": "facebook", "platform-identity": "xyz"]//bill facebook // let data = ["token": "2.00YKoiRC_wDsiDa41e9d01d3loOShC", "user-type": "sina", "platform": "iOS", "platform-identity": "xyz", "platform-notification-token": "abc"] print("data : \(data)") return Observable.create { observer in Alamofire.request(SPYRouter.Login(data)).responseJSON { (response) -> Void in print("Login response : \(response.response.debugDescription)") guard let _ = response.response, _ = response.data , json = response.result.value as? NSDictionary else { if let r = response.result.error{ print("response.result.error : \(r)") // observer.on(.Error(SPYLoginError.Unknown))//huang } if let r = response.response{ print("response.data : \(r)") print("response.response : \(r)") observer.on(.Error(SPYLoginError.UsernameConflict))//huang }else{ observer.on(.Error(SPYLoginError.NoInternet)) } return } print("json ; \(json) : \(json["data"])") observer.on(.Next(.JSONOK(json: json["data"] as! NSDictionary))) observer.on(.Completed) } return AnonymousDisposable {} } } //201是注册,200是登录。 func signup(username: String, password: String) -> Observable<LoginResult> { // let data = ["email": username, "password": <PASSWORD>, "user-type": "email"] let data = ["email": username, "password": <PASSWORD>, "user-type": "email","platform": "iOS", "platform-identity": "xyz", "platform-notification-token": "abc"] // let data = ["token": "2.<PASSWORD>", "user-type": "sina", "platform": "iOS", "platform-identity": "xyz", "platform-notification-token": "abc"] print("data : \(data)") return Observable.create { observer in Alamofire.request(SPYRouter.Login(data)).responseJSON { (response) -> Void in guard let _ = response.response, _ = response.data , json = response.result.value as? NSDictionary else { if let r = response.response{ observer.on(.Next(.Failed(statueCode: r.statusCode))) }else{ print(response.result.error); observer.on(.Error(SPYCocoaURLError.Unknown)) } return } observer.on(.Next(.JSONOK(json: json["data"] as! NSDictionary))) observer.on(.Completed) } return AnonymousDisposable {} } } } extension NSHTTPURLResponse{ var isSuccess : Bool { return self.statusCode >= 200 && statusCode < 300 } } <file_sep>/Spottly/SPYWebCell.swift // // SPYWebCell.swift // Spottly // // Created by HuangZhigang on 16/5/16. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import UIKit import RxSwift import Kingfisher import RxCocoa class SPYWebCell : UICollectionViewCell { var disposeBag = DisposeBag() var webView = UIWebView() var handlerAfterLayout : HandlerAfterLayout? override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.whiteColor() self.addSubview(webView) constrain(self,webView) { (box,web) in web.width == UIScreen.width - 2 web.top == box.top web.left == box.left web.bottom == box.bottom } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configureCell(url:String) { self.disposeBag = DisposeBag() print("Web URL :\(url)") // let temp = "http://spottly-web.5xruby.tw/places/95551731532104/detail" // let temp = "http://spottly-web.5xruby.tw/c/Tokyo/detail-only" webView.loadRequest(NSURLRequest(URL: NSURL(string:url)!)) webView.scrollView.scrollEnabled = false webView.scalesPageToFit = true webView.delegate = self; } } extension SPYWebCell:UIWebViewDelegate { func webViewDidFinishLoad(webView: UIWebView) { NSUserDefaults.standardUserDefaults().setInteger(0, forKey: "WebKitCacheModelPreferenceKey") let contentSize = webView.scrollView.contentSize; let viewSize = webView.bounds.size; let rw = viewSize.width / contentSize.width; webView.scrollView.minimumZoomScale = rw; webView.scrollView.maximumZoomScale = rw; webView.scrollView.zoomScale = rw; if let handler = handlerAfterLayout{ handler!(contentSize) } } func webView(webView: UIWebView, didFailLoadWithError error: NSError?) { print("webView error : \(error)") } func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { let url = request.URLString print("webView loaded URL :\(url)") if url.hasPrefix("http://spottly-web.5xruby.tw") || url.hasPrefix("http://wikitravel.org/wiki/en/index.php") || url.hasPrefix("https://en.wikipedia.org/w/index.php") { return true }else if url.hasPrefix("https://googleads") || url.hasPrefix("http://tpc.googlesyndication.com"){ return false } UIApplication.sharedApplication().openURL(request.URL!) return false } }<file_sep>/Spottly/SPYSearchViewModel.swift // // SPYSearchViewModel.swift // Spottly // // Created by HuangZhigang on 16/3/14. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import CoreData import RxSwift import RxCocoa func topFetchRequest() -> SPYFetchRequest{ return SPYFetchRequest() } func cityFetchRequest() -> SPYFetchRequest{ return SPYFetchRequest() } class SPYSearchViewModel { var topFRC,cityFRC,placeFRC,postFRC,collectionFRC,userFRC:SPYFetchedResultsController? var frc: SPYFetchedResultsController? var disposeBag = DisposeBag() init(searchQuery: Driver<String>, searchType:Driver<SPYMenuAction>) { Driver.combineLatest(searchQuery, searchType) { (query, type) -> SPYFetchedResultsController in let fr = SPYFetchRequest(entityName: "User") let method = SPYRouter.SearchUser(query).method.rawValue let path = SPYRouter.SearchUser(query).fullPath fr.httpInfo = ["METHOD" : method , "URL" : path] fr.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)] fr.predicate = NSPredicate(format: "relatedUrl CONTAINS %@",path) return SPYFetchedResultsController(fetchRequest: fr) }.driveNext { [weak self](newFrc) -> Void in self?.frc = newFrc }.addDisposableTo(disposeBag) } }<file_sep>/Spottly/SPYPhotoPickerViewModel.swift // // SPYPhotoPickerViewModel.swift // Spottly // // Created by HuangZhigang on 16/4/12. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import RxSwift import RxCocoa import PhotosUI class InstagramDefaultAPI: InstagramAPI { func pickerPhotos(placeId:String ,loadNextPageTrigger: Observable<Void>) -> Observable<[UIImage]> { let url = NSURL(string: "https://api.github.com/search/repositories?q=\(placeId)")! return Observable.just([UIImage]()) } private func loadURL(URL: NSURL) -> Observable<([UIImage],String)> { return NSURLSession.sharedSession() .rx_response(NSURLRequest(URL: URL)) .retry(3) // .observeOn(Dependencies.sharedDependencies.backgroundWorkScheduler) .map { data, httpResponse -> ([UIImage],String) in // if httpResponse.statusCode > 400 { // return [] // } return ([UIImage()],"nextUrl") } // .retryOnBecomesReachable(.ServiceOffline, reachabilityService: ReachabilityService.sharedReachabilityService) } } protocol InstagramAPI { func pickerPhotos(placeId:String ,loadNextPageTrigger: Observable<Void>) -> Observable<[UIImage]> } @objc protocol Photo { func setImageFor(imageView: UIImageView)->Void func setBigImageFor(imageView: UIImageView)->Void var location: CLLocation? {get} var mediaType: PHAssetMediaType {get} func asPHAsset() -> PHAsset } //struct InstagramPhoto:Photo { // // var image: UIImage // var location: CLLocation? // // func setImageFor(imageView: UIImageView)->Void{ // imageView.image = image // } // func setBigImageFor(imageView: UIImageView)->Void{ // imageView.image = image // } //} extension PHAsset:Photo { func asPHAsset() -> PHAsset { return self } func setImageFor(imageView: UIImageView)->Void { let manager = PHImageManager.defaultManager() manager.requestImageForAsset(self, targetSize: CGSize(width: 150.0, height: 150.0), contentMode: .AspectFill, options: nil) { (result, _) in imageView.image = result } } func setBigImageFor(imageView: UIImageView)->Void { let manager = PHImageManager.defaultManager() manager.requestImageForAsset(self, targetSize: CGSize(width: 480, height: 480), contentMode: .AspectFill, options: nil) { (result, _) in imageView.image = result } } } class SPYPhotoPickerViewModel { var place: PlaceStruct? var album: Variable<PHAssetCollection>? var photos: Observable<[Photo]>? var albums: Observable<[PHAssetCollection]>? init(place:PlaceStruct,api: InstagramAPI){ self.place = place; // self.photos = api // .pickerPhotosFromIns("id") // .map{ (images) -> [Photo] in // } } init(album:Observable<PHAssetCollection>){ self.album = Variable(PHAssetCollection.fetchAssetCollectionsWithType(PHAssetCollectionType.SmartAlbum, subtype: PHAssetCollectionSubtype.SmartAlbumRecentlyAdded, options: nil).firstObject as! PHAssetCollection) self.albums = Observable.create{ observer in let r = PHAssetCollection.fetchAssetCollectionsWithType(PHAssetCollectionType.SmartAlbum, subtype: PHAssetCollectionSubtype.AlbumRegular, options: nil) let assets = r.objectsAtIndexes(NSIndexSet(indexesInRange: NSRange(location: 0, length: r.count))) as! [PHAssetCollection] observer.onNext(assets) return AnonymousDisposable {} } self.photos = self.album?.asObservable() .map{ assetCollection -> [Photo] in let result = PHAsset.fetchAssetsInAssetCollection(assetCollection, options: nil) let assets = result.objectsAtIndexes(NSIndexSet(indexesInRange: NSRange(location: 0, length: result.count))) as! [PHAsset] return assets } } } //let options = PHFetchOptions() //options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]; //let result = PHAsset.fetchAssetsWithOptions(options) //let photos = Observable.create{ observer in // let assets = result.objectsAtIndexes(NSIndexSet(indexesInRange: NSRange(location: 0, length: result.count))) as! [PHAsset] // observer.onNext(assets) // return AnonymousDisposable {} // }.asDriver(onErrorJustReturn: []) as Driver<[PHAsset]> <file_sep>/Spottly/SPYNotificationsView.swift // // SPYNotificationsViewController.swift // Spottly // // Created by HuangZhigang on 15/12/5. // Copyright © 2015年 Spottly. All rights reserved. // import UIKit import RxSwift import RxCocoa class SPYNotificationsView: UIViewController { var headViewTopMargin = CGFloat(0) var menuTopMarginWhenScroll = CGFloat(0) var collection = SPYCollectionViewSubClass.spyRegisterClass(SPYNotificaionCell.self) var loadingView : UIView? var layout : UICollectionViewFlowLayout! var disposeBag = DisposeBag() var bag = DisposeBag() var viewModel : SPYUserViewModel? { didSet{ self.spyLoadViewIfNeeded() } } override func viewWillAppear(animated: Bool) { if let _ = viewModel{ }else{ self.viewModel = SPYUserViewModel.shareMe } } override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "Notifications" // self.SPYLayoutCollection(self.disposeBag) } func doShow(value: Int) { self.bag = DisposeBag() switch value { case 0: layout?.itemSize = CGSize(width: UIScreen.width,height: 88) self.viewModel?.notificationsFRC?.performFetchIfNeed.rxFetchedObjects.asDriver(onErrorJustReturn: []).drive(self.collection.rx_itemsWithCellIdentifier("SPYNotificaionCell")){ (_, notificaion, cell: SPYNotificaionCell) in // cell.name.text = "个人消息" }.addDisposableTo(self.bag) viewModel?.notificationsFRC?.rx_requestState.asDriver().driveNext({ (state) -> Void in switch state{ case .Loading : break case .Offline : break case .Error(let code) : break case .Completed : self.collection.endRefreshing() default: return }}) self.collection.rx_modelSelected(AnyObject) .asDriver().driveNext{ spot -> Void in }.addDisposableTo(self.bag) default : break } } func doMore(value: Int) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }<file_sep>/Spottly/SPYUserViewModel.swift // // SPYUserViewModel.swift // SpottlyCoreData // // Created by HuangZhigang on 15/11/3. // Copyright © 2015年 Spottly. All rights reserved. // import Foundation import RxSwift import RxCocoa import CoreData private let meViewModel = SPYUserViewModel() class SPYUserViewModel : NSObject, NSFetchedResultsControllerDelegate { var userFRC,postsFRC,placesFRC,collectionsFRC,newsFrc,notificationsFRC,followingcollectionsFRC,followingUsersFRC,feedFRC: SPYFetchedResultsController? var isMe = false private var dispose = DisposeBag() private var tickerObservable : Observable<Int64>! var input : User? { didSet{ userFRC = SPYFetchedResultsController(fetchRequest: self.input!.userFR()) postsFRC = SPYFetchedResultsController(fetchRequest: self.input!.postsFR()) placesFRC = SPYFetchedResultsController(fetchRequest: self.input!.placesFR()) collectionsFRC = SPYFetchedResultsController(fetchRequest: self.input!.collectionsFR()) if isMe { notificationsFRC = SPYFetchedResultsController(fetchRequest: self.input!.notificationFR()) feedFRC = SPYFetchedResultsController(fetchRequest: self.input!.feedFR()) followingUsersFRC = SPYFetchedResultsController(fetchRequest: self.input!.followingUsersFR()) followingcollectionsFRC = SPYFetchedResultsController(fetchRequest: self.input!.followingColloctionsFR()) } } } class var shareMe : SPYUserViewModel { meViewModel.isMe = true return meViewModel } var isLogined : Bool { get{ if SPYUserViewModel.shareMe.input != nil{ return true } guard let id = userID() else{ return false } let reasult = try? SPYMainMoc().executeFetchRequest(User.idFR(id)) if let me = reasult?.first as? User{ SPYUserViewModel.shareMe.isMe = true SPYUserViewModel.shareMe.input = me return true }else{ return false } } } convenience init(input:User) { self.init() self.input = input userFRC = SPYFetchedResultsController(fetchRequest: self.input!.userFR()) // postsFRC = SPYFetchedResultsController(fetchRequest: self.input!.postsFR()) placesFRC = SPYFetchedResultsController(fetchRequest: self.input!.placesFR()) collectionsFRC = SPYFetchedResultsController(fetchRequest: self.input!.collectionsFR()) // tickerObservable = interval(5, MainScheduler.instance) // tickerObservable.subscribeNext { (_) -> Void in // self.doUserTest(user) // } } func loadMore(frc:SPYFetchedResultsController){ frc.loadMore() } func doUserTest(user:User) { let result = try! SPYMainMoc().executeFetchRequest(user.userFR()) if let aUser = result.first as? User { if let bio = aUser.bio where bio.characters.count > 0 { aUser.bio = "" }else{ aUser.bio = "12345890" } } try! SPYMainMoc().save() } } <file_sep>/Spottly/SPYFeedView.swift // // SecondViewController.swift // Spottly // // Created by HuangZhigang on 15/12/4. // Copyright © 2015年 Spottly. All rights reserved. // import UIKit import RxSwift import RxCocoa import YYKit import FontAwesome_swift import PullToRefresh class SPYFeedView: UIViewController,UICollectionViewDelegateFlowLayout { var collection = SPYCollectionViewSubClass.spyRegisterClass(SPYPostCell.self) var layout : CSStickyHeaderFlowLayout{ return self.collection.collectionViewLayout as!CSStickyHeaderFlowLayout } var disposeBag = DisposeBag() var cell = SPYPostCell() var footer : SPYMoreFooterView? var viewModel : SPYUserViewModel? { didSet{ configureDataSource() } } // MARK: - View override func viewWillAppear(animated: Bool) { if let _ = viewModel{ }else{ self.viewModel = SPYUserViewModel.shareMe } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() } override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "From people you follow" self.navigationController?.navigationBar.translucent = false self.view.addSubviews(collection) constrain(self.view,collection){ box,collection in collection.top == box.top collection.left == box.left collection.right == box.right collection.bottom == box.bottom - 48 } let layout = collection.collectionViewLayout as! UICollectionViewFlowLayout layout.footerReferenceSize = CGSize(width: UIScreen.width,height: 40) collection.scrollIndicatorInsets = UIEdgeInsetsMake(64, 0, 0, 0) let refresher = PullToRefresh() self.collection.addPullToRefresh(refresher) {[unowned self] () -> () in delay(2, closure: { () -> () in self.collection.endRefreshing() }) } collection.registerClass(SPYMoreFooterView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "SPYMoreFooterView") collection.rx_contentOffset .asDriver() .filter{ UIScrollView.needMore(self.collection, offset: $0) } .throttle(0.2) .driveNext { [weak self] point in self?.doMore() }.addDisposableTo(disposeBag) collection.rx_setDelegate(self).addDisposableTo(self.disposeBag) } func starString() -> NSMutableAttributedString { let textAttributes = [NSFontAttributeName: UIFont.systemFontOfSize(10),NSForegroundColorAttributeName:UIColor.spyGrayColor()] let imgAttributes = [NSFontAttributeName: UIFont.fontAwesomeOfSize(10),NSForegroundColorAttributeName:UIColor.spyGrayColor()] let string = NSMutableAttributedString() let blank = NSMutableAttributedString(string: " ", attributes: textAttributes) let saveImg = NSMutableAttributedString(string: String.fontAwesomeIconWithName(.Plus), attributes: imgAttributes) let saveText = NSMutableAttributedString(string: "10", attributes: textAttributes) let commentImg = NSMutableAttributedString(string: String.fontAwesomeIconWithName(.Comment), attributes: imgAttributes) let commentText = NSMutableAttributedString(string: "10", attributes: textAttributes) let likeImg = NSMutableAttributedString(string: String.fontAwesomeIconWithName(.Heart), attributes: imgAttributes) let likeText = NSMutableAttributedString(string: "10", attributes: textAttributes) let star = NSMutableAttributedString(string: String.fontAwesomeIconWithName(.Star), attributes: imgAttributes) let staro = NSMutableAttributedString(string: String.fontAwesomeIconWithName(.StarO), attributes: imgAttributes) string.appendAttributedString(saveImg) string.appendAttributedString(blank) string.appendAttributedString(saveText) string.appendAttributedString(blank) string.appendAttributedString(blank) string.appendAttributedString(commentImg) string.appendAttributedString(blank) string.appendAttributedString(commentText) string.appendAttributedString(blank) string.appendAttributedString(blank) string.appendAttributedString(likeImg) string.appendAttributedString(blank) string.appendAttributedString(likeText) string.appendAttributedString(blank) string.appendAttributedString(blank) for _ in 0...65{ string.appendAttributedString(blank) } string.appendAttributedString(star) string.appendAttributedString(blank) string.appendAttributedString(star) string.appendAttributedString(blank) string.appendAttributedString(star) string.appendAttributedString(blank) string.appendAttributedString(star) string.appendAttributedString(blank) string.appendAttributedString(staro) return string } @IBAction func addNewFriends(sender: AnyObject) { } // MARK: - dataSource func doMore() { self.footer?.startAnimating() self.viewModel?.postsFRC?.loadMore() } func configureDataSource() { self.viewModel?.feedFRC?.performFetchIfNeed .rxFetchedObjects .bindTo(self.collection.rx_itemsWithCellIdentifier("SPYPostCell")){ (_, post, cell: SPYPostCell) in let post = post as! Post cell.head.kf_setImageWithURL(NSURL(string:post.owner!.head!.sizeIs(.head))!) cell.image.kf_setImageWithURL(NSURL(string: post.imageUrl!.sizeIs(.post))!) cell.username.text = post.owner?.uid cell.collectionName.text = post.collection?.name cell.placeName.text = post.place?.name ?? "还是不行" cell.locName.text = post.place?.address ?? "还是不行" cell.star.attributedText = self.starString() let attributedText = NSMutableAttributedString(string: post.message! ,attributes: [NSFontAttributeName :UIFont.spyAvenirNextRegular(12), NSForegroundColorAttributeName:UIColor.spyTextColor()]) let userRangs = attributedText.string.parse(userRegexp) let tagRangs = attributedText.string.parse(tagRegexp) let urlRangs = attributedText.string.parse(urlRegexp) _ = userRangs.map{ range in attributedText.setTextHighlightRange(range, color: UIColor.spyLogoColor(), backgroundColor: UIColor.spyLogoColor(), tapAction: { (_, attributedString, _, _) -> Void in let string = attributedString.string print("user: \(string.substringWithNSRange(NSMakeRange(range.location + 1, range.length - 1) ))") }) } _ = tagRangs.map{ range in attributedText.setTextHighlightRange(range, color: UIColor.spyLogoColor(), backgroundColor: UIColor.spyLogoColor(), tapAction: { (_, attributedString, _, _) -> Void in let string = attributedString.string print("tag: \(string.substringWithNSRange(NSMakeRange(range.location + 1, range.length - 1) ))") }) } _ = urlRangs.map{ range in attributedText.setTextHighlightRange(range, color: UIColor.spyLogoColor(), backgroundColor: UIColor.spyLogoColor(), tapAction: { (_, attributedString, _, _) -> Void in let string = attributedString.string print("url: \(string.substringWithNSRange(NSMakeRange(range.location + 1, range.length - 1) ))") }) } cell.msg.attributedText = attributedText }.addDisposableTo(disposeBag) SPYObserveRequestState(self.collection, frc: viewModel?.feedFRC, dataType: .Post, bag: disposeBag) } func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { if self.footer == nil { self.footer = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SPYMoreFooterView", forIndexPath: indexPath) as? SPYMoreFooterView } return self.footer! } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{ guard let post = self.viewModel?.feedFRC?.fetchedObjects?[indexPath.row] as? Post else{ return CGSizeZero } guard let msg = post.message else{ return CGSizeMake(UIScreen.width, UIScreen.width ) } let size = CGSizeMake(UIScreen.width - 15*2, CGFloat.max) let attributedString = NSAttributedString(string: post.message!, attributes: [NSFontAttributeName: UIFont.spyAvenirNextRegular(12),NSForegroundColorAttributeName: UIColor.redColor()]) let layout = YYTextLayout(containerSize: size, text: attributedString) // let rect = msg.boundingRectWithSize(CGSizeMake(UIScreen.width, 999), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [ // NSFontAttributeName: UIFont.spyAvenirNextRegular(12), // NSForegroundColorAttributeName: UIColor.redColor(), // ], context: nil) return CGSizeMake(UIScreen.width, layout!.textBoundingSize.height + 598 - 20) } } <file_sep>/Spottly/SPYCollectionCell.swift // // SPYCollectionCell.swift // Spottly // // Created by HuangZhigang on 15/12/14. // Copyright © 2015年 Spottly. All rights reserved. // import Foundation import UIKit import RxSwift import Kingfisher import RxCocoa class SPYCollectionCell : UICollectionViewCell { var disposeBag = DisposeBag() var username = UILabel().then{ $0.text = "@userName" $0.font = UIFont.spyAvenirNextRegular(12) $0.textColor = UIColor.spyTextColor() } var post = UILabel().then{ $0.backgroundColor = UIColor.whiteColor() $0.text = "25Posts" $0.font = UIFont.spyAvenirNextRegular(10) $0.textColor = UIColor.spyGrayColor() } var head = UIImageView().then{ $0.backgroundColor = UIColor.brownColor() } var bigImage = UIImageView().then{ $0.backgroundColor = UIColor.grayColor() } var rightUpImage = UIImageView().then{ $0.backgroundColor = UIColor.grayColor() } var rightDownImage = UIImageView().then{ $0.backgroundColor = UIColor.grayColor() } var collectionName = UILabel().then{ $0.numberOfLines = 0 $0.text = "CollectionName" $0.textAlignment = .Center $0.font = UIFont.spyAvenirNextDemiBold(18) $0.textColor = UIColor.spyTextColor() } override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.whiteColor() self.contentView.addSubviews(head,username,post) constrain(head,username,post){head,name,post in let cell = head.superview! head.left == cell.left + 8 head.top == cell.top + 8 head.height == 25 head.width == 25 align(centerY: head,name,post) distribute(by: 16, leftToRight: head,name,post) post.right == cell.right - 8 } head.layer.cornerRadius = 25/2 head.clipsToBounds = true self.contentView.addSubviews(bigImage,rightUpImage,rightDownImage) constrain(head,bigImage,rightUpImage,rightDownImage){ head,big,up,down in let cell = head.superview! big.left == cell.left big.top == head.bottom + 8 big.height == cell.width * 2/3 big.width == big.height up.top == big.top up.left == big.right up.right == cell.right up.height == down.height down.top == up.bottom down.left == big.right down.right == cell.right down.bottom == big.bottom } let collectionNameBox = UIView() collectionNameBox.backgroundColor = UIColor.clearColor() self.addSubviews(collectionNameBox) constrain(bigImage,collectionNameBox){ big,name in let cell = big.superview! name.top == big.bottom name.left == big.left name.right == cell.right name.bottom == cell.bottom } collectionNameBox.addSubviews(collectionName) constrain(collectionNameBox,collectionName){ box,name in name.centerX == box.centerX name.centerY == box.centerY name.left == box.left + 2 * 8 name.right == box.right - 2 * 8 } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configureCell(collection:Collection) { self.disposeBag = DisposeBag() self.collectionName.text = collection.name self.username.text = collection.owner?.name if let headUrl = collection.owner?.head?.sizeIs(.head) { self.head.kf_setImageWithURL(NSURL(string:headUrl)!) }else{ SPYLog().error("collection.owner : 异常 :\(collection.owner)") } self.post.text = "\(collection.postsCount!.integerValue)POST" // viewModel.postsFRC.performFetchIfNeed.rxFetchedObjects.asDriver().driveNext { (posts) -> Void in let posts = collection.posts if posts?.count > 0{ let post = posts?[0] as! Post self.bigImage.kf_setImageWithURL(NSURL(string: post.imageUrl!.sizeIs(.head))!) } if posts?.count > 1{ let post = posts?[1] as! Post self.rightUpImage.kf_setImageWithURL(NSURL(string: post.imageUrl!.sizeIs(.head))!) }else{ self.rightUpImage.image = nil; } if posts?.count > 2{ let post = posts?[2] as! Post self.rightDownImage.kf_setImageWithURL(NSURL(string: post.imageUrl!.sizeIs(.head))!) }else{ self.rightDownImage.image = nil; } // }.addDisposableTo(self.disposeBag) } override func layoutSubviews() { // self.layer.borderColor = UIColor.brownColor().CGColor // self.layer.borderWidth = 2.0 } }<file_sep>/Spottly/SPYSearchResultView.swift // // SPYSearchView.swift // Spottly // // Created by HuangZhigang on 16/3/14. // Copyright © 2016年 Spottly. All rights reserved. // import Foundation import UIKit import RxSwift import Kingfisher import RxCocoa import Then import Groot typealias SPYSearchRecentSection = HashableSectionModel<SPYSearchHeaderViewModel, Top> typealias SPYSearchTopSection = HashableSectionModel<SPYSearchHeaderViewModel, Top> typealias SPYSearchCitySection = HashableSectionModel<SPYSearchHeaderViewModel, City> typealias SPYSearchPlaceSection = HashableSectionModel<SPYSearchHeaderViewModel, Place> typealias SPYSearchPostSection = HashableSectionModel<SPYSearchHeaderViewModel, Post> typealias SPYSearchCollectionSection = HashableSectionModel<SPYSearchHeaderViewModel, Collection> typealias SPYSearchUserSection = HashableSectionModel<SPYSearchHeaderViewModel, User> struct SPYSearchHeaderViewModel:Hashable { var menuItems: [SPYMenuAction] var hashValue: Int { return menuItems.first!.stringValue.hash } } //struct City : Hashable { // var name: String // var hashValue: Int // { // return name.hashValue // } //} struct Top: Hashable { var name: String var hashValue: Int { return name.hashValue } } func == (lhs: Top, rhs: Top) -> Bool { return lhs.name == rhs.name } func == (lhs: SPYSearchHeaderViewModel, rhs: SPYSearchHeaderViewModel) -> Bool { return lhs.hashValue == rhs.hashValue } class SPYSearchResultView : UIViewController , SPYMenuActionDelegate { var query: Driver<String> var searchBar: UISearchBar var viewModel: SPYSearchViewModel? var needShowPlace = false var header : SPYSearchResultMenuHeader? { didSet{ let type = Driver.of(header!.subMenu.rx_selectedSegment.asDriver(), header!.menu.rx_selectedSegment.asDriver()) .merge().filter{$0 != nil} Driver.combineLatest(query.filter{ _ in self.view.hidden == false }, type) { [weak self] (query, type) -> (SPYFetchedResultsController,SPYMenuAction,String) in let frc = self?.configureFrc(query,menuAction: type!) return (frc!,type!,query) }.driveNext { [weak self](newFrc,type,query) -> Void in if self!.header!.needShowPlaces == false && type == SPYMenuAction.Place(.Hot) { self?.doMenuAction(type) let reallyAction = SPYMenuAction.Post(.Hot) self?.frc = self?.configureFrc(query,menuAction:reallyAction ) self?.doMenuAction(reallyAction) }else{ self?.frc = newFrc self?.doMenuAction(type) } }.addDisposableTo(disposeBag) query.driveNext { [weak self](q) -> Void in self?.header!.query = q }.addDisposableTo(disposeBag) header!.rx_observe(CGRect.self, "frame") .subscribeNext { [weak self] (rect) -> Void in self?.layout.headerReferenceSize = rect!.size }.addDisposableTo(disposeBag) header!.rx_observe(CGRect.self, "bounds") .subscribeNext { [weak self] (rect) -> Void in self?.layout.headerReferenceSize = rect!.size }.addDisposableTo(disposeBag) } } var dataSoucreForRecent : RxCollectionViewSectionedReloadDataSource<SPYSearchRecentSection>! var dataSoucreForTop : RxCollectionViewSectionedReloadDataSource<SPYSearchTopSection>! var dataSoucreForCity : RxCollectionViewSectionedReloadDataSource<SPYSearchCitySection>! var dataSoucreForPlace : RxCollectionViewSectionedReloadDataSource<SPYSearchPlaceSection>! var dataSoucreForPost : RxCollectionViewSectionedReloadDataSource<SPYSearchPostSection>! var dataSoucreForCollection : RxCollectionViewSectionedReloadDataSource<SPYSearchCollectionSection>! var dataSoucreForUser : RxCollectionViewSectionedReloadDataSource<SPYSearchUserSection>! var collection = SPYCollectionViewSubClass.spyRegisterClass(SPYSearchResultCell.self,SPYPlaceCell.self,SPYCollectionCell.self) var layout : CSStickyHeaderFlowLayout{ return self.collection.collectionViewLayout as!CSStickyHeaderFlowLayout } var headerViewModel : SPYSearchHeaderViewModel? var disposeBag = DisposeBag() var bag = DisposeBag() var frc: SPYFetchedResultsController? // MARK: - View init(searchBar:UISearchBar) { self.searchBar = searchBar query = searchBar.rx_text.asDriver(onErrorJustReturn: "") viewModel = SPYSearchViewModel(searchQuery: query, searchType: Driver.just(SPYMenuAction.User)) super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.view.frame = CGRect(x: 0, y: 64, width: UIScreen.width, height: UIScreen.height - 64 - 49) self.collection.frame = self.view.bounds } override func viewDidLoad() { super.viewDidLoad() self.view.addSubview(self.collection) self.collection.backgroundColor = UIColor(rgba: "#212121") configureDataSoucreForTop() configureDataSoucreForUser() configureDataSoucreForRecent() configureDataSoucreForPlace() configureDataSoucreForPost() configureDataSoucreForCollection() configureDataSoucreForCity() headerViewModel = SPYSearchHeaderViewModel(menuItems: [.Top,.City,.Place(.Hot),.User]) self.collection.registerClass(SPYSearchResultMenuHeader.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "SPYSearchResultMenuHeader") self.reloadLayout() doMenuAction(.Recent) query .driveNext { [weak self] s in if s.characters.count > 0 && self?.header?.menu.items.count == 1{ self?.header?.menu.items = [.Top,.City,.Place(.Hot),.User] } if s.characters.count == 0 { self?.header?.menu.items = [.Recent] } self?.header?.closeDetail() }.addDisposableTo(disposeBag) self.view.rx_observe(Bool.self, "hidden").subscribeNext { [weak self] (value) in self?.searchBar.showsCancelButton = !value! self?.searchBar.setCancelImage(UIImage(named: "cancel")!) }.addDisposableTo(disposeBag) self.collection.panGestureRecognizer.addActionBlock{ [weak self] (_) in self?.searchBar.resignFirstResponder() } } func reloadLayout() { guard let layout = self.collection.collectionViewLayout as? CSStickyHeaderFlowLayout else{ return } layout.parallaxHeaderReferenceSize = CGSizeZero layout.parallaxHeaderMinimumReferenceSize = CGSizeZero layout.itemSize = CGSizeMake(UIScreen.width, 70); layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.headerReferenceSize = CGSize(width: UIScreen.width, height: 40) } // MARK: - DataSoucre func configureDataSoucreForRecent() { let dataSource = RxCollectionViewSectionedReloadDataSource<SPYSearchRecentSection>() dataSource.cellFactory = {(cv, ip, item)in let cell = cv.dequeueReusableCellWithReuseIdentifier("SPYSearchResultCell", forIndexPath: ip) as! SPYSearchResultCell cell.configureCell(item) return cell } dataSource.supplementaryViewFactory = { [unowned dataSource,unowned self] (cv, kind, ip) in if kind == UICollectionElementKindSectionHeader{ if self.header == nil { self.header = cv.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SPYSearchResultMenuHeader", forIndexPath: ip) as? SPYSearchResultMenuHeader self.header?.configureCell([.Recent]) } return self.header! }else{ fatalError("kind 未识别") } } self.dataSoucreForRecent = dataSource } func configureDataSoucreForTop() { let dataSource = RxCollectionViewSectionedReloadDataSource<SPYSearchTopSection>() dataSource.cellFactory = {(cv, ip, item)in let cell = cv.dequeueReusableCellWithReuseIdentifier("SPYSearchResultCell", forIndexPath: ip) as! SPYSearchResultCell cell.configureCell(item) return cell } dataSource.supplementaryViewFactory = { [unowned dataSource,unowned self] (cv, kind, ip) in if kind == UICollectionElementKindSectionHeader{ if self.header == nil { self.header = cv.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SPYSearchResultMenuHeader", forIndexPath: ip) as? SPYSearchResultMenuHeader self.header?.configureCell(dataSource.sectionAtIndex(ip.section).model.menuItems) } return self.header! }else{ fatalError("kind 未识别") } } self.dataSoucreForTop = dataSource } func configureDataSoucreForCity() { let dataSource = RxCollectionViewSectionedReloadDataSource<SPYSearchCitySection>() dataSource.cellFactory = {(cv, ip, item)in let cell = cv.dequeueReusableCellWithReuseIdentifier("SPYSearchResultCell", forIndexPath: ip) as! SPYSearchResultCell cell.configureCell(item) return cell } dataSource.supplementaryViewFactory = { [unowned dataSource,unowned self] (cv, kind, ip) in if kind == UICollectionElementKindSectionHeader{ if self.header == nil { self.header = cv.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SPYSearchResultMenuHeader", forIndexPath: ip) as? SPYSearchResultMenuHeader self.header?.configureCell(dataSource.sectionAtIndex(ip.section).model.menuItems) } return self.header! }else{ fatalError("kind 未识别") } } self.dataSoucreForCity = dataSource } func configureDataSoucreForPlace() { let dataSource = RxCollectionViewSectionedReloadDataSource<SPYSearchPlaceSection>() dataSource.cellFactory = {(cv, ip, item)in let cell = cv.dequeueReusableCellWithReuseIdentifier("SPYSearchResultCell", forIndexPath: ip) as! SPYSearchResultCell cell.configureCell(item) return cell } dataSource.supplementaryViewFactory = { [unowned dataSource,unowned self] (cv, kind, ip) in if kind == UICollectionElementKindSectionHeader{ if self.header == nil { self.header = cv.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SPYSearchResultMenuHeader", forIndexPath: ip) as? SPYSearchResultMenuHeader self.header?.configureCell(dataSource.sectionAtIndex(ip.section).model.menuItems) } return self.header! }else{ fatalError("kind 未识别") } } self.dataSoucreForPlace = dataSource } func configureDataSoucreForPost() { let dataSource = RxCollectionViewSectionedReloadDataSource<SPYSearchPostSection>() dataSource.cellFactory = {(cv, ip, item)in let cell = cv.dequeueReusableCellWithReuseIdentifier("SPYPlaceCell", forIndexPath: ip) as! SPYPlaceCell cell.configureCell(item) return cell } dataSource.supplementaryViewFactory = { [unowned dataSource,unowned self] (cv, kind, ip) in if kind == UICollectionElementKindSectionHeader{ if self.header == nil { self.header = cv.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SPYSearchResultMenuHeader", forIndexPath: ip) as? SPYSearchResultMenuHeader self.header?.configureCell(dataSource.sectionAtIndex(ip.section).model.menuItems) } return self.header! }else { fatalError("kind 未识别") } } self.dataSoucreForPost = dataSource } func configureDataSoucreForCollection() { let dataSource = RxCollectionViewSectionedReloadDataSource<SPYSearchCollectionSection>() dataSource.cellFactory = {(cv, ip, item)in let cell = cv.dequeueReusableCellWithReuseIdentifier("SPYCollectionCell", forIndexPath: ip) as! SPYCollectionCell cell.configureCell(item) return cell } dataSource.supplementaryViewFactory = { [unowned dataSource,unowned self] (cv, kind, ip) in if kind == UICollectionElementKindSectionHeader{ if self.header == nil { self.header = cv.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SPYSearchResultMenuHeader", forIndexPath: ip) as? SPYSearchResultMenuHeader self.header?.configureCell(dataSource.sectionAtIndex(ip.section).model.menuItems) } return self.header! }else { fatalError("kind 未识别") } } self.dataSoucreForCollection = dataSource } func configureDataSoucreForUser() { let dataSource = RxCollectionViewSectionedReloadDataSource<SPYSearchUserSection>() dataSource.cellFactory = {(cv, ip, item)in let cell = cv.dequeueReusableCellWithReuseIdentifier("SPYSearchResultCell", forIndexPath: ip) as! SPYSearchResultCell cell.configureCell(item) return cell } dataSource.supplementaryViewFactory = { [unowned dataSource,unowned self] (cv, kind, ip) in if kind == UICollectionElementKindSectionHeader{ if self.header == nil { self.header = cv.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SPYSearchResultMenuHeader", forIndexPath: ip) as? SPYSearchResultMenuHeader self.header?.configureCell(dataSource.sectionAtIndex(ip.section).model.menuItems) } return self.header! }else { fatalError("kind 未识别") } } self.dataSoucreForUser = dataSource } // MARK: - Action func doMore(value:Int) {} func headerFlowLayout() -> CSStickyHeaderFlowLayout { return CSStickyHeaderFlowLayout() } func doMenuAction(menuAction:SPYMenuAction) { self.bag = DisposeBag() switch menuAction { case .Recent: let items = Driver.just([Top]()) layout.spyConfigureLayoutForSearchResults() Driver.combineLatest(Driver.just(headerViewModel), items){ h , items in return [SPYSearchTopSection(model: h!, items: items)] } .drive(self.collection.rx_itemsWithDataSource(self.dataSoucreForRecent)) .addDisposableTo(bag) self.collection .rx_itemSelected.asDriver() .driveNext{ [weak self] indexPath in self?.header!.menu.items = [.Recent] let recent = self?.dataSoucreForRecent.itemAtIndexPath(indexPath) } .addDisposableTo(bag) case .Top: self.header?.closeDetail() layout.spyConfigureLayoutForSearchResults() let items = Driver.just([Top]()) Driver.combineLatest(Driver.just(headerViewModel), items){ h , items in return [SPYSearchTopSection(model: h!, items: items)] } .drive(self.collection.rx_itemsWithDataSource(self.dataSoucreForTop)) .addDisposableTo(bag) self.collection .rx_itemSelected.asDriver() .driveNext{ [weak self] indexPath in let top = self?.dataSoucreForTop.itemAtIndexPath(indexPath) self?.header!.menu.items = [.Recent] } .addDisposableTo(bag) case .City: self.header?.closeDetail() layout.spyConfigureLayoutForSearchResults() let items = frc! .performFetchIfNeed .rxFetchedObjects .map{ (AnyObjects) -> [City] in return AnyObjects as! [City] }.asDriver(onErrorJustReturn: [City]()) Driver.combineLatest(Driver.just(headerViewModel), items){ h , items in return [SPYSearchCitySection(model: h!, items: items)] } .drive(self.collection.rx_itemsWithDataSource(self.dataSoucreForCity)) .addDisposableTo(bag) self.collection .rx_itemSelected.asDriver() .driveNext{ [weak self] indexPath in let city = self?.dataSoucreForCity.itemAtIndexPath(indexPath) let placesURL = SPYRouter.City(city!.id!, .Places) .fullPath .orderBy(.Rating(.Desc)) let collectionsUrl = SPYRouter.City(city!.id!, .Collections) .fullPath .orderBy(.Rating(.Desc)) let c = mainStoryboard().instantiateViewControllerWithIdentifier("SPYExploreView") as! SPYExploreView c.viewModel = SPYExploreViewModel(input: ( mainCategory:city, subCategory: categorys, menuItems:[SPYMenuAction.Place(.Hot),SPYMenuAction.Place(.Following),SPYMenuAction.Details,SPYMenuAction.Collection(.Hot)], placesUrl: placesURL, collectionsUrl: collectionsUrl)) SPYNavigationController().pushViewController(c, animated: true) } .addDisposableTo(bag) case .Place: if self.header!.needShowPlaces == false { self.header?.showDetail() self.header?.subMenu.rx_selectedSegment.value = SPYMenuAction.Post(.Hot) }else{ self.header!.needShowPlaces = false self.header?.closeDetail() layout.spyConfigureLayoutForSearchResults() let items = frc! .performFetchIfNeed .rxFetchedObjects .map{ (AnyObjects) -> [Place] in return AnyObjects as! [Place] }.asDriver(onErrorJustReturn: [Place]()) Driver.combineLatest(Driver.just(headerViewModel), items){ h , items in return [SPYSearchPlaceSection(model: h!, items: items)] } .drive(self.collection.rx_itemsWithDataSource(self.dataSoucreForPlace)) .addDisposableTo(bag) self.collection .rx_itemSelected.asDriver() .driveNext{ [weak self] indexPath in let place = self?.dataSoucreForPlace.itemAtIndexPath(indexPath) let c = mainStoryboard().instantiateViewControllerWithIdentifier("SPYPostView") as! SPYPostView let post = place!.relatedPost c.viewModel = SPYPostViewModel(input:post!) SPYNavigationController().pushViewController(c, animated: true) } .addDisposableTo(bag) } case .User: self.header?.closeDetail() layout.spyConfigureLayoutForSearchResults() let items = frc! .performFetchIfNeed .rxFetchedObjects .map{ (AnyObjects) -> [User] in return AnyObjects as! [User] }.asDriver(onErrorJustReturn: [User]()) Driver.combineLatest(Driver.just(headerViewModel), items){ h , items in return [SPYSearchUserSection(model: h!, items: items)] } .drive(self.collection.rx_itemsWithDataSource(self.dataSoucreForUser)) .addDisposableTo(bag) self.collection .rx_itemSelected.asDriver() .driveNext{ [weak self] indexPath in let user = self?.dataSoucreForUser.itemAtIndexPath(indexPath) let c = mainStoryboard().instantiateViewControllerWithIdentifier("SPYUserView") as! SPYUserView c.viewModel = SPYUserViewModel(input:user!) SPYNavigationController().pushViewController(c, animated: true) } .addDisposableTo(bag) case .Post: let items = frc! .performFetchIfNeed .rxFetchedObjects .map{ (AnyObjects) -> [Post] in return AnyObjects as! [Post] }.asDriver(onErrorJustReturn: [Post]()) layout.spyConfigureLayoutForPlaces() Driver.combineLatest(Driver.just(headerViewModel), items){ h , items in return [SPYSearchPostSection(model: h!, items: items)] } .drive(self.collection.rx_itemsWithDataSource(self.dataSoucreForPost)) .addDisposableTo(bag) self.collection .rx_itemSelected.asDriver() .driveNext{ [weak self] indexPath in let post = self?.dataSoucreForPost.itemAtIndexPath(indexPath) let c = mainStoryboard().instantiateViewControllerWithIdentifier("SPYPostView") as! SPYPostView c.viewModel = SPYPostViewModel(input:post!) SPYNavigationController().pushViewController(c, animated: true) } .addDisposableTo(bag) case .Collection: let items = frc! .performFetchIfNeed .rxFetchedObjects .map{ (AnyObjects) -> [Collection] in return AnyObjects as! [Collection] }.asDriver(onErrorJustReturn: [Collection]()) layout.spyConfigureLayoutForCollections() Driver.combineLatest(Driver.just(headerViewModel), items){ h , items in return [SPYSearchCollectionSection(model: h!, items: items)] } .drive(self.collection.rx_itemsWithDataSource(self.dataSoucreForCollection)) .addDisposableTo(bag) self.collection .rx_itemSelected.asDriver() .driveNext{ [weak self] indexPath in if let c = mainStoryboard().instantiateViewControllerWithIdentifier("SPYCollectionView") as? SPYCollectionView{ let collection = self?.dataSoucreForCollection.itemAtIndexPath(indexPath) c.viewModel = SPYCollectionViewModel(input: collection! ) SPYNavigationController().pushViewController(c, animated: true) } } .addDisposableTo(bag) default : break } SPYScrollMenuHeaderToTop(self.header,collection:self.collection ,layout:self.layout) } // MARK: - Helpers func configureFrc(query:String,menuAction:SPYMenuAction) -> SPYFetchedResultsController? { if query.characters.count == 0 { let fr = SPYFetchRequest(entityName: "Place") let method = SPYRouter.SearchPlace(query).method.rawValue let path = SPYRouter.SearchPlace(query).fullPath fr.httpInfo = ["METHOD" : method , "URL" : path] fr.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)] fr.predicate = NSPredicate(format: "name CONTAINS[cd] %@",query) return SPYFetchedResultsController(fetchRequest: fr) } switch menuAction { //TODO: 创建新的top数据结构 case .Top: let fr = SPYFetchRequest(entityName: "City") let method = SPYRouter.SearchCity(query).method.rawValue let path = SPYRouter.SearchCity(query).fullPath fr.httpInfo = ["METHOD" : method , "URL" : path] fr.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)] fr.predicate = NSPredicate(format: "name CONTAINS[cd] %@",query) return SPYFetchedResultsController(fetchRequest: fr) case .City: let fr = SPYFetchRequest(entityName: "City") let method = SPYRouter.SearchCity(query).method.rawValue let path = SPYRouter.SearchCity(query).fullPath fr.httpInfo = ["METHOD" : method , "URL" : path] fr.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)] fr.predicate = NSPredicate(format: "name CONTAINS[cd] %@",query) return SPYFetchedResultsController(fetchRequest: fr) case .User: let fr = SPYFetchRequest(entityName: "User") let method = SPYRouter.SearchUser(query).method.rawValue let path = SPYRouter.SearchUser(query).fullPath fr.httpInfo = ["METHOD" : method , "URL" : path] fr.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)] fr.predicate = NSPredicate(format: "name CONTAINS[cd] %@",query) return SPYFetchedResultsController(fetchRequest: fr) case .Post: let fr = SPYFetchRequest(entityName: "Post") let method = SPYRouter.SearchPost(query).method.rawValue let path = SPYRouter.SearchPost(query).fullPath fr.httpInfo = ["METHOD" : method , "URL" : path] fr.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)] fr.predicate = NSPredicate(format: "message CONTAINS[cd] %@",query) return SPYFetchedResultsController(fetchRequest: fr) case .Collection: let fr = SPYFetchRequest(entityName: "Collection") let method = SPYRouter.SearchCollection(query).method.rawValue let path = SPYRouter.SearchCollection(query).fullPath fr.httpInfo = ["METHOD" : method , "URL" : path] fr.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)] fr.predicate = NSPredicate(format: "name CONTAINS[cd] %@",query) return SPYFetchedResultsController(fetchRequest: fr) case .Place: let fr = SPYFetchRequest(entityName: "Place") let method = SPYRouter.SearchPlace(query).method.rawValue let path = SPYRouter.SearchPlace(query).fullPath fr.httpInfo = ["METHOD" : method , "URL" : path] fr.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)] fr.predicate = NSPredicate(format: "name CONTAINS[cd] %@",query) return SPYFetchedResultsController(fetchRequest: fr) case .Recent: let fr = SPYFetchRequest(entityName: "Place") let method = SPYRouter.SearchPlace(query).method.rawValue let path = SPYRouter.SearchPlace(query).fullPath fr.httpInfo = ["METHOD" : method , "URL" : path] fr.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)] fr.predicate = NSPredicate(format: "name CONTAINS[cd] %@",query) return SPYFetchedResultsController(fetchRequest: fr) default :break } return nil } }
6aacd796ad81b9a80716cc965fd2b3e3390bea99
[ "Swift", "Ruby", "Markdown" ]
100
Swift
callmebill/Spottly
7a80f2bb3e0d736eccb357345bf662f305649d95
1f3f28b1e69aea9dd14de9912c522b0bf5e83c65
refs/heads/master
<repo_name>edwardry/VendingMachine<file_sep>/test/ScreenTest.java import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class ScreenTest { private Screen screen; private Transaction transaction; private String expectedResult; private String actualResult; @Before public void setUp() { screen = new Screen(); transaction = new Transaction(); TestUtil.addCoins(5, CommonTestConstants.quarter, transaction); } @Test public void WhenScreenIsUpdatedWithTransactionInProgressThenSetScreenToCurrentTransactionTotal() { expectedResult = "$1.25"; screen.updateDisplay(transaction); actualResult = screen.getDisplay(); assertEquals(expectedResult, actualResult); } } <file_sep>/test/TransactionTest.java import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class TransactionTest { private Transaction transaction; private Double expectedResult; private Double actualResult; @Before public void setUp() { transaction = new Transaction(); } @Test public void WhenANewTransactionHasItsTotalUpdatedTheNewTotalIsTheValueThatWasPassed() { expectedResult = 0.25; transaction.update(CommonTestConstants.quarter); actualResult = CoinUtil.getTotal(transaction); assertEquals(expectedResult, actualResult); } @Test public void WhenANonEmptyTransactionHasItsTotalUpdatedTheNewTotalIsTheSumOfThePreviousTotalPlusTheNewlyPassedValue() { expectedResult = 1.00; TestUtil.addCoins(3, CommonTestConstants.quarter, transaction); TestUtil.addCoins(2, CommonTestConstants.dime, transaction); transaction.update(CommonTestConstants.nickel); actualResult = CoinUtil.getTotal(transaction); assertEquals(expectedResult, actualResult); } @Test public void WhenANonEmptyTransactionIsClearedThenTheNewTotalIsZero() { expectedResult = 0.0; TestUtil.addCoins(3, CommonTestConstants.quarter, transaction); TestUtil.addCoins(2, CommonTestConstants.dime, transaction); transaction.clear(); actualResult = CoinUtil.getTotal(transaction); assertEquals(expectedResult, actualResult); } @Test public void WhenAnEmptyTransactionIsClearedThenTheTotalRemainsZero() { expectedResult = CoinUtil.getTotal(transaction); transaction.clear(); actualResult = CoinUtil.getTotal(transaction); assertEquals(expectedResult, actualResult); } } <file_sep>/test/VendingMachineBankTest.java import org.junit.Before; import org.junit.Test; import java.util.Arrays; import static org.junit.Assert.assertEquals; public class VendingMachineBankTest { private VendingMachineBank bank; private Transaction transaction; private Product product; private Double expectedResult; private Double actualResult; private Inventory inventory; @Before public void setUp() { transaction = new Transaction(); product = CommonTestConstants.cola; bank = new VendingMachineBank(TestUtil.createBankFunds(3, 3, 3)); inventory = new Inventory(Arrays.asList(CommonTestConstants.cola, CommonTestConstants.chips, CommonTestConstants.candy)); } @Test public void WhenDetermineCoinValueIsPassedACoinWithNickelWeightAndDiameterReturnsValueOfNickel() { expectedResult = 0.05; actualResult = VendingMachineBank.determineValue(CommonTestConstants.nickel); assertEquals(expectedResult, actualResult); } @Test public void WhenDetermineCoinValueIsPassedACoinWithDimeWeightAndDiameterReturnsValueOfDime() { expectedResult = 0.10; actualResult = VendingMachineBank.determineValue(CommonTestConstants.dime); assertEquals(expectedResult, actualResult); } @Test public void WhenDetermineCoinValueIsPassedACoinWithQuarterWeightAndDiameterReturnsValueOfQuarter() { expectedResult = 0.25; actualResult = VendingMachineBank.determineValue(CommonTestConstants.quarter); assertEquals(expectedResult, actualResult); } @Test public void WhenDetermineCoinValueIsPassedAnInvalidCoinThenReturnsValueOfZero() { Coin coin = new Coin(2.5, 19.05); expectedResult = 0.0; actualResult = VendingMachineBank.determineValue(coin); assertEquals(expectedResult, actualResult); } @Test public void WhenDepositMoneyIsPassedATransactionWithTotalSameAsProductThenAllMoneyInTheTransactionIsDeposited() { TestUtil.addCoins(4, CommonTestConstants.quarter, transaction); expectedResult = CoinUtil.getTotal(bank) + 1.00; bank.depositMoney(transaction, product); actualResult = CoinUtil.getTotal(bank); assertEquals(expectedResult, actualResult); } @Test public void WhenDepositMoneyIsPassedATransactionWithTotalMoreThanProductThenRemainingMoneyIsStillInTransaction() { TestUtil.addCoins(8, CommonTestConstants.quarter, transaction); expectedResult = CoinUtil.getTotal(transaction) - 1.00; bank.depositMoney(transaction, product); actualResult = CoinUtil.getTotal(transaction); assertEquals(expectedResult, actualResult); } @Test public void WhenAttemptingToDepositATransactionWithNoMoneyThenNothingIsDeposited() { expectedResult = CoinUtil.getTotal(transaction); bank.depositMoney(transaction, product); actualResult = CoinUtil.getTotal(transaction); assertEquals(expectedResult, actualResult); } @Test public void WhenDepositingMoneyFromATransactionWithABalanceButProductHasNoPriceThenNothingIsDeposited() { expectedResult = CoinUtil.getTotal(transaction); Product freeProduct = new Product("Chips", 0.00, 1); bank.depositMoney(transaction, freeProduct); actualResult = CoinUtil.getTotal(transaction); assertEquals(expectedResult, actualResult); } @Test public void WhenBankHasSufficientChangeThenReturnTrue() { Boolean actualResult = bank.hasSufficientChange(inventory); assertEquals(true, actualResult); } @Test public void WhenBankDoesNotHaveSufficientDimesThenReturnFalse() { bank = new VendingMachineBank(TestUtil.createBankFunds(3, 0, 3)); Boolean actualResult = bank.hasSufficientChange(inventory); assertEquals(false, actualResult); } @Test public void WhenBankDoesNotHaveSufficientNickelsThenReturnFalse() { bank = new VendingMachineBank(TestUtil.createBankFunds(0, 3, 3)); Boolean actualResult = bank.hasSufficientChange(inventory); assertEquals(false, actualResult); } @Test public void WhenBankDoesNotHaveSufficientQuartersThenReturnFalse() { bank = new VendingMachineBank(TestUtil.createBankFunds(3, 3, 0)); Boolean actualResult = bank.hasSufficientChange(inventory); assertEquals(false, actualResult); } } <file_sep>/test/ButtonPanelTest.java import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class ButtonPanelTest { private ButtonPanel buttons; private Transaction transaction; private Product product; private Boolean expectedResult; private Boolean actualResult; private Coin nickel; private Coin dime; private Coin quarter; @Before public void setUp() { buttons = new ButtonPanel(); transaction = new Transaction(); nickel = new Coin(CommonTestConstants.NICKEL_MASS, CommonTestConstants.NICKEL_DIAMETER, CommonTestConstants.NICKEL_VALUE); dime = new Coin(CommonTestConstants.DIME_MASS, CommonTestConstants.DIME_DIAMETER, CommonTestConstants.DIME_VALUE); quarter = new Coin(CommonTestConstants.QUARTER_MASS, CommonTestConstants.QUARTER_DIAMETER, CommonTestConstants.QUARTER_VALUE); } @Test public void WhenTransactionHasJustEnoughCoinsToBuyProductThenPressingButtonReturnsTrue() { expectedResult = true; product = new Product("Cola", 1.00, 1); TestUtil.addCoins(4, quarter, transaction); actualResult = buttons.press(product, transaction); assertEquals(expectedResult, actualResult); } @Test public void WhenTransactionHasMoreThanEnoughCoinsToBuyProductThenPressingButtonReturnsTrue() { expectedResult = true; product = new Product("Cola", 1.00, 1); TestUtil.addCoins(8, quarter, transaction); actualResult = buttons.press(product, transaction); assertEquals(expectedResult, actualResult); } @Test public void WhenTransactionDoesNotHaveEnoughCoinsToBuyProductThenPressingButtonReturnsFalse() { expectedResult = false; product = new Product("Cola", 1.00, 1); TestUtil.addCoins(3, quarter, transaction); TestUtil.addCoins(2, dime, transaction); actualResult = buttons.press(product, transaction); assertEquals(expectedResult, actualResult); } } <file_sep>/src/VendingMachineBank.java import java.util.HashMap; import java.util.List; import java.util.Map; public class VendingMachineBank { private Map<Double, List<Coin>> funds; public VendingMachineBank() { funds = new HashMap<>(); } public VendingMachineBank(Map<Double, List<Coin>> coins) { funds = coins; } public void depositMoney(Transaction transaction, Product product) { Double valueToDeposit = product.getPrice(); Double amountDeposited = 0.0; Map<Double, List<Coin>> coins = transaction.getCoins(); for(Double coinValue : coins.keySet()) { if(!coins.get(coinValue).isEmpty()) { amountDeposited = calculateHowManyToDeposit(coinValue, transaction, amountDeposited, valueToDeposit); } } } private Double calculateHowManyToDeposit(Double value, Transaction transaction, Double amountDeposited, Double valueToDeposit) { int numberOfCoinsRemoved = 0; for(Coin coin : transaction.getCoins().get(value)) { if(value + amountDeposited <= valueToDeposit) { amountDeposited += value; addFunds(coin); numberOfCoinsRemoved++; } } removeCoinsFromTransaction(value, numberOfCoinsRemoved, transaction); return amountDeposited; } private void addFunds(Coin coin) { CoinUtil.store(coin, funds); } private void removeCoinsFromTransaction(Double value, int numberOfCoinsRemoved, Transaction transaction) { for(int i=0;i < numberOfCoinsRemoved;i++) { transaction.remove(value); } } public boolean hasSufficientChange(Inventory inventory) { for(Product product : inventory.getProducts()) { for(Coin coin : ValidCoins.coins) { Double remainder = product.getPrice() % coin.getValue(); List<Coin> coinsAvailable = funds.get(coin.getValue()); if (remainder != 0 && coinsAvailable.size() == 0) { return false; } } } return true; } public static Double determineValue(Coin coin) { Double coinMass = coin.getMass(); Double coinDiameter = coin.getDiameter(); for(Coin validCoin : ValidCoins.coins) { Double validCoinMass = validCoin.getMass(); Double validCoinDiameter = validCoin.getDiameter(); if(coinMass.equals(validCoinMass) && coinDiameter.equals(validCoinDiameter)) { return validCoin.getValue(); } } return Coin.VALUELESS; } public Map<Double, List<Coin>> getFunds() { return funds; } }<file_sep>/src/ButtonPanel.java public class ButtonPanel { public boolean press(Product product, Transaction transaction) { Double productValue = product.getPrice(); Double transactionTotal = CoinUtil.getTotal(transaction); if(transactionTotal >= productValue) { transaction.setStatus(Screen.THANK_YOU); return true; } else { transaction.setStatus(Screen.PRICE + ": " + CoinUtil.convertValueToString(product.getPrice())); return false; } } } <file_sep>/src/CoinUtil.java import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.List; import java.util.Map; public class CoinUtil { public static String convertValueToString(Double total) { NumberFormat formatter = NumberFormat.getCurrencyInstance(); return formatter.format(total); } public static Double getTotal(Transaction transaction) { return calculateTotal(transaction.getCoins()); } public static Double getTotal(VendingMachineBank bank) { return calculateTotal(bank.getFunds()); } public static void store(Coin coin, Map<Double, List<Coin>> coins) { Double value = coin.getValue(); List<Coin> coinsAtValue = new ArrayList<>(); if(!coins.isEmpty() && coins.get(value) != null) { coinsAtValue = coins.get(value); } coinsAtValue.add(coin); coins.put(value, coinsAtValue); } private static Double calculateTotal(Map<Double, List<Coin>> coins) { Double totalFunds = 0.0; for(Double key : coins.keySet()) { int numberOfCoins = coins.get(key).size(); Double coinValue = key; totalFunds += coinValue * numberOfCoins; } DecimalFormat formatter = new DecimalFormat("0.00"); return Double.valueOf(formatter.format(totalFunds)); } } <file_sep>/test/VendingMachineTest.java import org.junit.Before; import org.junit.Test; import java.util.*; import static org.junit.Assert.assertEquals; public class VendingMachineTest { private VendingMachine vendingMachine; private VendingMachineBank bank; private Product product; private Inventory inventory; private Coin coin; private String expectedResult = ""; private String actualResult = ""; private List<Coin> coins; private List<String> expectedResults; @Before public void setUp() { Map<Double, List<Coin>> bankFunds = TestUtil.createBankFunds(3, 3, 3); bank = new VendingMachineBank(bankFunds); inventory = new Inventory(Arrays.asList(CommonTestConstants.cola, CommonTestConstants.chips, CommonTestConstants.candy)); vendingMachine = new VendingMachine(bank, inventory); coins = new ArrayList<>(); expectedResults = new ArrayList<>(); } @Test public void WhenCustomerInsertsAValidCoinAsFirstTransactionInBankThenValueOfCoinIsDisplayedOnScreen() { coin = new Coin(CommonTestConstants.NICKEL_MASS, CommonTestConstants.NICKEL_DIAMETER); expectedResult = "$0.05"; vendingMachine.insertCoin(coin); actualResult = vendingMachine.checkDisplay(); assertEquals(expectedResult, actualResult); } @Test public void WhenCustomerInsertsAnInvalidCoinInBankThenScreenDisplaysInsertCoinAndCoinIsPlacedInCoinReturn() { coin = new Coin(2.5, 19.05); expectedResult = Screen.INSERT_COIN; vendingMachine.insertCoin(coin); actualResult = vendingMachine.checkDisplay(); assertEquals(expectedResult, actualResult); } @Test public void WhenCustomerInsertsTwoValidCoinsInBankThenScreenDisplaysSumOfCoinValue() { coins.add(0, new Coin(CommonTestConstants.NICKEL_MASS, CommonTestConstants.NICKEL_DIAMETER)); expectedResults.add(0, "$0.05"); coins.add(1, new Coin(CommonTestConstants.DIME_MASS, CommonTestConstants.DIME_DIAMETER)); expectedResults.add(1, "$0.15"); int finalExpectedResult = coins.size() - 1; for (Coin coin : coins) { vendingMachine.insertCoin(coin); actualResult = vendingMachine.checkDisplay(); } assertEquals(expectedResults.get(finalExpectedResult), actualResult); } @Test public void WhenSufficientMoneyAndProductSelectedThenDisplaysThankYouAndMoneyIsDepositedInBankAndTransactionReset() { coin = new Coin(CommonTestConstants.QUARTER_MASS, CommonTestConstants.QUARTER_DIAMETER); int numberOfCoins = 3; product = inventory.getProduct(CommonTestConstants.CHIPS); String initialExpectedResult = Screen.THANK_YOU; expectedResult = Screen.INSERT_COIN; for (int i = 0; i < numberOfCoins; i++) { vendingMachine.insertCoin(coin); } vendingMachine.pressButton(product); String initialActualResult = vendingMachine.checkDisplay(); actualResult = vendingMachine.checkDisplay(); assertEquals(initialExpectedResult, initialActualResult); assertEquals(expectedResult, actualResult); } @Test public void WhenInsufficientMoneyAndProductSelectedThenDisplaysPriceAndMoneyIsNotDeposited() { coin = new Coin(CommonTestConstants.QUARTER_MASS, CommonTestConstants.QUARTER_DIAMETER); int numberOfCoins = 3; product = inventory.getProduct(CommonTestConstants.COLA); expectedResult = Screen.PRICE + ": $1.00"; for (int i = 0; i < numberOfCoins; i++) { vendingMachine.insertCoin(coin); } vendingMachine.pressButton(product); actualResult = vendingMachine.checkDisplay(); assertEquals(expectedResult, actualResult); } @Test public void AfterPriceIsDisplayedDueToInsufficientFundsThenScreenDisplaysCurrentTransactionTotal() { coin = new Coin(CommonTestConstants.QUARTER_MASS, CommonTestConstants.QUARTER_DIAMETER); int numberOfCoins = 3; product = inventory.getProduct(CommonTestConstants.COLA); String initialExpectedResult = Screen.PRICE + ": $1.00"; expectedResult = "$0.75"; for (int i = 0; i < numberOfCoins; i++) { vendingMachine.insertCoin(coin); } vendingMachine.pressButton(product); String initialActualResult = vendingMachine.checkDisplay(); actualResult = vendingMachine.checkDisplay(); assertEquals(initialExpectedResult, initialActualResult); assertEquals(expectedResult, actualResult); } @Test public void WhenCustomerSelectsAProductWithNoMoneyInsertedThenProductPriceIsDisplayedAndThenInsertCoinIsDisplayed() { String initialExpectedResult = Screen.PRICE + ": $1.00"; product = inventory.getProduct(CommonTestConstants.COLA); expectedResult = Screen.INSERT_COIN; vendingMachine.pressButton(product); String initialActualResult = vendingMachine.checkDisplay(); actualResult = vendingMachine.checkDisplay(); assertEquals(initialExpectedResult, initialActualResult); assertEquals(expectedResult, actualResult); } @Test public void WhenProductIsSelectedThatCostsLessThanTransactionTotalThenRemainingTotalAfterPurchaseIsPlacedInCoinReturn() { coin = new Coin(CommonTestConstants.QUARTER_MASS, CommonTestConstants.QUARTER_DIAMETER); int numberOfCoins = 5; product = inventory.getProduct(CommonTestConstants.COLA); Double transactionFunds = 1.25; Double productCost = product.getPrice(); Double extraFunds = transactionFunds - productCost; Double expected = 0.25; for (int i = 0; i < numberOfCoins; i++) { vendingMachine.insertCoin(coin); } vendingMachine.pressButton(product); assertEquals(expected, extraFunds); } @Test public void WhenCoinReturnButtonIsPressedThenTransactionTotalIsSentToCoinReturnAndScreenDisplaysInsertCoin() { coin = new Coin(CommonTestConstants.QUARTER_MASS, CommonTestConstants.QUARTER_DIAMETER); int numberOfCoins = 3; expectedResult = Screen.INSERT_COIN; for (int i = 0; i < numberOfCoins; i++) { vendingMachine.insertCoin(coin); } vendingMachine.returnCoins(); actualResult = vendingMachine.checkDisplay(); assertEquals(expectedResult, actualResult); } @Test public void WhenProductIsSelectedThatIsSoldOutThenDisplaysSoldOutAndThenTransactionTotalIsDisplayed() { coin = new Coin(CommonTestConstants.QUARTER_MASS, CommonTestConstants.QUARTER_DIAMETER); int numberOfCoins = 4; List<Product> products = Arrays.asList(new Product(CommonTestConstants.CANDY, 0.65, 0)); Inventory inventory = new Inventory(products); product = inventory.getProduct(CommonTestConstants.CANDY); String initialExpectedResult = Screen.SOLD_OUT; expectedResult = "$1.00"; for (int i = 0; i < numberOfCoins; i++) { vendingMachine.insertCoin(coin); } vendingMachine.pressButton(product); String initialActualResult = vendingMachine.checkDisplay(); actualResult = vendingMachine.checkDisplay(); assertEquals(initialExpectedResult, initialActualResult); assertEquals(expectedResult, actualResult); } @Test public void WhenProductIsSelectedThatIsSoldOutAndTransactionTotalIsEmptyThenScreenDisplaysSoldOutAndThenInsertCoin() { List<Product> products = Arrays.asList(new Product(CommonTestConstants.CANDY, 0.65, 0)); Inventory inventory = new Inventory(products); product = inventory.getProduct(CommonTestConstants.CANDY); String initialExpectedResult = Screen.SOLD_OUT; expectedResult = Screen.INSERT_COIN; vendingMachine.pressButton(product); String initialActualResult = vendingMachine.checkDisplay(); actualResult = vendingMachine.checkDisplay(); assertEquals(initialExpectedResult, initialActualResult); assertEquals(expectedResult, actualResult); } @Test public void WhenVendingMachineIsNotAbleToMakeExactChangeForAnyProductThenExactChangeOnlyIsDisplayedInsteadOfInsertCoin() { expectedResult = Screen.EXACT_CHANGE; bank = new VendingMachineBank(TestUtil.createBankFunds(3, 0, 3)); vendingMachine = new VendingMachine(bank, inventory); actualResult = vendingMachine.checkDisplay(); assertEquals(expectedResult, actualResult); } @Test public void WhenVendingMachineIsNotAbleToMakeExactChangeThenCustomerDepositsCoinsAndNoLongerNeedsExactChange() { int numberOfCoins = 5; expectedResult = Screen.EXACT_CHANGE; bank = new VendingMachineBank(TestUtil.createBankFunds(3, 0, 3)); vendingMachine = new VendingMachine(bank, inventory); actualResult = vendingMachine.checkDisplay(); assertEquals(expectedResult, actualResult); for(int i=0;i<numberOfCoins;i++) { vendingMachine.insertCoin(CommonTestConstants.dime); } expectedResult = Screen.THANK_YOU; vendingMachine.pressButton(CommonTestConstants.chips); actualResult = vendingMachine.checkDisplay(); assertEquals(expectedResult, actualResult); expectedResult = Screen.INSERT_COIN; actualResult = vendingMachine.checkDisplay(); assertEquals(expectedResult, actualResult); } }
9b6c08ba63a012b9f8fe3c9eabcaef5c40b6814b
[ "Java" ]
8
Java
edwardry/VendingMachine
cdd40f5d6fc44c2bcf574fd9c48b430b7915a40b
2802a591dd5260750eb16f17b83d3070526f1ab4
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace calculadora { class Calproceso { string valor1; string valor2; public Calproceso(string pvalor1, string pvalor2) { this.valor1 = pvalor1; this.valor2 = pvalor2; } public string sumar() { int resultado = Convert.ToInt32(valor1) + Convert.ToInt32(valor2); return Convert.ToString(resultado); } public string resta() { int resultado = Convert.ToInt32(valor1) - Convert.ToInt32(valor2); return Convert.ToString(resultado); } public string dividir() { int resultado = Convert.ToInt32(valor1) / Convert.ToInt32(valor2); return Convert.ToString(resultado); } public string multiplicacion() { int resultado = Convert.ToInt32(valor1) * Convert.ToInt32(valor2); return Convert.ToString(resultado); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace calculadora { public partial class calculadora : Form { public calculadora() { InitializeComponent(); } private void button5_Click(object sender, EventArgs e) { } private void calculadora_Load(object sender, EventArgs e) { } private void btnResultado_Click(object sender, EventArgs e) { bool tieneSuma = tbxResultado.Text.Contains("+"); if (tieneSuma) { string[] values = tbxResultado.Text.Split('+'); string val1 = values[0]; string val2 = values[1]; Calproceso metodoSuma = new Calproceso(val1,val2); tbxResultado.Text = metodoSuma.sumar(); } bool tieneResta = tbxResultado.Text.Contains("-"); if (tieneResta) { string[] values = tbxResultado.Text.Split('-'); string val1 = values[0]; string val2 = values[1]; Calproceso metodoResta = new Calproceso(val1, val2); tbxResultado.Text = metodoResta.resta(); } bool tieneDividir = tbxResultado.Text.Contains("/"); if (tieneDividir) { string[] values = tbxResultado.Text.Split('/'); string val1 = values[0]; string val2 = values[1]; Calproceso metodoDividir = new Calproceso(val1, val2); tbxResultado.Text = metodoDividir.dividir(); } bool tieneMultiplicar = tbxResultado.Text.Contains("*"); if (tieneMultiplicar) { string[] values = tbxResultado.Text.Split('*'); string val1 = values[0]; string val2 = values[1]; Calproceso metodoMultiplicar = new Calproceso(val1, val2); tbxResultado.Text = metodoMultiplicar.multiplicacion(); } } private void tbxResultado_TextChanged(object sender, EventArgs e) { } private void btnUno_Click(object sender, EventArgs e) { tbxResultado.Text = tbxResultado.Text + "1"; } private void btnDos_Click(object sender, EventArgs e) { tbxResultado.Text = tbxResultado.Text + "2"; } private void btnTres_Click(object sender, EventArgs e) { tbxResultado.Text = tbxResultado.Text + "3"; } private void btnCuatro_Click(object sender, EventArgs e) { tbxResultado.Text = tbxResultado.Text + "4"; } private void btnCinco_Click(object sender, EventArgs e) { tbxResultado.Text = tbxResultado.Text + "5"; } private void btnSeis_Click(object sender, EventArgs e) { tbxResultado.Text = tbxResultado.Text + "6"; } private void btnSiete_Click(object sender, EventArgs e) { tbxResultado.Text = tbxResultado.Text + "7"; } private void btnOcho_Click(object sender, EventArgs e) { tbxResultado.Text = tbxResultado.Text + "8"; } private void btnNueve_Click(object sender, EventArgs e) { tbxResultado.Text = tbxResultado.Text + "9"; } private void btnCero_Click(object sender, EventArgs e) { tbxResultado.Text = tbxResultado.Text + "0"; } private void btnSumar_Click(object sender, EventArgs e) { tbxResultado.Text = tbxResultado.Text + "+"; } private void btnRestar_Click(object sender, EventArgs e) { tbxResultado.Text = tbxResultado.Text + "-"; } private void btnMultiplicar_Click(object sender, EventArgs e) { tbxResultado.Text = tbxResultado.Text + "*"; } private void btnDividir_Click(object sender, EventArgs e) { tbxResultado.Text = tbxResultado.Text + "/"; } private void btnOff_Click(object sender, EventArgs e) { Application.Exit(); } private void btnBorraall_Click(object sender, EventArgs e) { int hasta = tbxResultado.Text.Length - 1; string resultado = tbxResultado.Text.Substring(0, hasta); tbxResultado.Text = ""; } private void btnBorrar_Click(object sender, EventArgs e) { int hasta = tbxResultado.Text.Length - 1; string resultado = tbxResultado.Text.Substring(0, hasta); tbxResultado.Text= resultado; } } }
bf7d7152aeaee72526f8801a8e584c0196043f75
[ "C#" ]
2
C#
delgadoguadamuz/calculadora
344eb7cbc42367cf63c1efa9b5a96d5928e45bce
4fafd6ce2962368b0b8afa3e5cc5743e1882fa2d
refs/heads/master
<file_sep><?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * Dealer 的注释 * * @作者 roy */ class Dealer extends Eloquent { protected $table = 'dealer'; protected $primaryKey = 'dealer_id'; public static function getByCustomerId($customer_id) { $dealer_id = DB::table('dealer_customer') ->where('customer_id', '=',$customer_id) ->where('dc_relat_type','=', 1) ->select('dealer_id') ->first()->dealer_id; return Dealer::find($dealer_id); } } <file_sep><?php // autoload_classmap.php @generated by Composer $vendorDir = dirname(dirname(__FILE__)); $baseDir = dirname($vendorDir); return array( 'BaseController' => $baseDir . '/app/controllers/BaseController.php', 'Business\\busOrderds' => $baseDir . '/app/business/busOrderds.php', 'Business\\busPinyin' => $baseDir . '/app/business/busPinyin.php', 'Business\\busSms' => $baseDir . '/app/business/busSms.php', 'Business\\busUlitity' => $baseDir . '/app/business/busUlitity.php', 'Contact' => $baseDir . '/app/models/Contact.php', 'Coupon' => $baseDir . '/app/models/Coupon.php', 'Customer' => $baseDir . '/app/models/Customer.php', 'DatabaseSeeder' => $baseDir . '/app/database/seeds/DatabaseSeeder.php', 'Dealer' => $baseDir . '/app/models/Dealer.php', 'HomeController' => $baseDir . '/app/controllers/HomeController.php', 'IlluminateQueueClosure' => $vendorDir . '/laravel/framework/src/Illuminate/Queue/IlluminateQueueClosure.php', 'Login' => $baseDir . '/app/models/Login.php', 'Order' => $baseDir . '/app/models/Order.php', 'OrderController' => $baseDir . '/app/controllers/OrderController.php', 'OrderDiscount' => $baseDir . '/app/models/OrderDiscount.php', 'OrderDishFlash' => $baseDir . '/app/models/OrderDishFlash.php', 'OrderStatusMessage' => $baseDir . '/app/models/OrderStatusMessage.php', 'Pic' => $baseDir . '/app/models/Pic.php', 'Product' => $baseDir . '/app/models/Product.php', 'ProductCategory' => $baseDir . '/app/models/ProductCategory.php', 'ProductCategoryRelation' => $baseDir . '/app/models/ProductCategoryRelation.php', 'ProductController' => $baseDir . '/app/controllers/ProductController.php', 'SessionHandlerInterface' => $vendorDir . '/symfony/http-foundation/Symfony/Component/HttpFoundation/Resources/stubs/SessionHandlerInterface.php', 'Symfony\\Component\\HttpFoundation\\Resources\\stubs\\FakeFile' => $vendorDir . '/symfony/http-foundation/Symfony/Component/HttpFoundation/Resources/stubs/FakeFile.php', 'TestCase' => $baseDir . '/app/tests/TestCase.php', 'UserController' => $baseDir . '/app/controllers/UserController.php', 'Whoops\\Module' => $vendorDir . '/filp/whoops/src/deprecated/Zend/Module.php', 'Whoops\\Provider\\Zend\\ExceptionStrategy' => $vendorDir . '/filp/whoops/src/deprecated/Zend/ExceptionStrategy.php', 'Whoops\\Provider\\Zend\\RouteNotFoundStrategy' => $vendorDir . '/filp/whoops/src/deprecated/Zend/RouteNotFoundStrategy.php', ); <file_sep><?php namespace Business; /* * 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. */ /** * busUlitity 的注释 * * @作者 roy */ class busUlitity { static function arrayToObject($e) { if (gettype($e) != 'array') return; foreach ($e as $k => $v) { if (gettype($v) == 'array' || getType($v) == 'object') { $e[$k] = (object) self::arrayToObject($v); } } return (object) $e; } static function objectToArray($e) { $e = (array) $e; foreach ($e as $k => $v) { if (gettype($v) == 'resource') return; if (gettype($v) == 'object' || gettype($v) == 'array') $e[$k] = (array) self::objectToArray($v); } return $e; } /** * 检测是否手机号 * @param type $mobile * @return type */ static function is_mobile($mobile) { return preg_match("/^[1][358]\d{9}$/", $mobile); } /** * * @param string $url */ static function get($url) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 获取数据返回 curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回 return curl_exec($ch); } /** * 发送post请求 * @param type $url * @param type $data * @return type */ static function post($url, $data = array()) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // post数据 curl_setopt($ch, CURLOPT_POST, 1); // post的变量 curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $output = curl_exec($ch); curl_close($ch); return $output; } /** * 上传图片 * @param type $imgFile * @param int $pictype 图片类型 1 商家logo;2 菜品图片; * @param int $entity_id 实体id * @param int $biztype 具体业务内的类型 1 商家logo 或 菜品图片 */ static function UploadImg($imgFile, $pictype, $entity_id, $biztype) { if (isset($imgFile)) { $filetype = $imgFile->type; $extensionName = $imgFile->extensionName; $pos = strpos($filetype, 'image'); if ($pos === false) { //提示不是图片 return '上传的文件不是图片'; } elseif ($pos == 0) { //上传图片 $pic = pic::model()->findByAttributes(array('entity_id' => $entity_id, 'pic_type' => $pictype)); $filefullpach = ''; if (!isset($pic)) {//图片信息在数据库中不存在 //判断文件夹是否存在 图片文件夹格式 参数img_upload_dir+图片类型_id_具体业务内的类型 $dir_date = date("Ym"); $dir_full = Yii::app()->params['img_upload_dir'] . 'upload/' . $dir_date . '/'; if (!is_dir($dir_full)) { mkdir($dir_full); } $newfilename = $pictype . '_' . $entity_id . '_' . $biztype . '.' . $extensionName; $relpath = 'upload/' . $dir_date . '/' . $newfilename; //相对路径 用于图片保存数据库 $pic = new Pic; $pic->entity_id = $entity_id; $pic->pic_type = $pictype; $pic->pic_url = $relpath; $pic->save(); $filefullpach = $dir_full . $newfilename; } else { $filefullpach = Yii::app()->params['img_upload_dir'] . $pic->pic_url; } if ($imgFile->saveAs($filefullpach) == FALSE) { //提示保存文件错误 return '保存文件出错,请联系管理员'; } else {//保存文件对象到数据库 } } } else { return -3; } return '上传图片成功'; } /** * 格式化金钱类型的字符串,保留两位小数 * @param string $model * @return string */ static function formatMoney($money) { $s = floatval($money); $money = sprintf("%.2f", $s); return $money; } /** * 格式化日期类型字符串 将字符串格式化为 y-M-d h:m * @param string $date * @return string */ static function formatDate($date) { return busUlitity::getDatestr($date, 0, 16); } /** * 格式化日期类型字符串 将字符串格式化仅有时间 格式为 h:m * @param string $date * @return string */ static function formatOnlyTime($date) { return busUlitity::getDatestr($date, 11, 5); } /** * 格式化日期时间字符串 * @param string $date 待格式化的原始字符串 * @param int $index 起始索引 * @param int $length 长度 * @return string */ static function getDatestr($date, $index, $length) { if (isset($date) == FALSE) { return ''; } elseif (strlen($date) == 19) { return substr($date, $index, $length); } else { return $date; } } /** * 隐藏字符串中的数字 * @param type $model * @return type */ static function hideNumber($model) { for ($i = 0; $i < 10; $i++) { $model = str_replace($i, '*', $model); } return $model; } static function array_insert($myarray, $value, $position = 0) { $fore = ($position == 0) ? array() : array_splice($myarray, 0, $position); $fore[] = $value; $ret = array_merge($fore, $myarray); return $ret; } /** * 列表控件如果没有数据需要显示的提示 * @param type $data 列表控件的数据源 */ static function dataEmptyMessage($data) { if ($data->itemCount == 0) { echo '<div class="emptyArea">' . DATAEMPTYMESSAGE . '</div>'; } } /** * 将两个json字符串连接到一起 * [{ "firstName": "Brett" }] 和 [{ "secondName": "bill" }] 连接后为[{ "firstName": "Brett" },{ "secondName": "bill" }] * @param string $json_a * @param string $json_b * @return string */ static function joinjson($json_a, $json_b) { if ($json_a == '[]' && $json_b == '[]') { return '[]'; } elseif ($json_a == '[]') { return $json_b; } elseif ($json_b == '[]') { return $json_a; } else { $json_a = substr($json_a, 0, strlen($json_a) - 1); $json_b = substr($json_b, 1, strlen($json_b)); return $json_a . ',' . $json_b; } } /** * 时间差 * @param string $beginDate_str * @param string $endDate_str * @return int 天数 */ static function DateSubDay($beginDate_str, $endDate_str) { $beginDate = strtotime($beginDate_str); $endDate = strtotime($endDate_str); $day = floor(($endDate - $beginDate) / 86400); return $day; } /** * 报表使用的x轴时间列表,如果为时间差大于一天显示日期格式,其他情况显示一天的小时格式。 * @param type $beginDate * @param type $endDate * @return type json格式,不包含最外层的中括号 */ static function X_reportjsArray($beginDate, $endDate) { $list = array(); $days_sub = busUlitity::DateSubDay($beginDate, $endDate); if ($days_sub > 0) {//日期格式 $beginDate_time = strtotime($beginDate); for ($i = 0; $i < $days_sub + 1; $i++) { $time_temp = date('m-d', strtotime('+' . $i . ' day', $beginDate_time)); array_push($list, '\'' . $time_temp . '\''); } } else {//小时格式 for ($i = 0; $i < 24; $i++) { array_push($list, $i); } } $list = implode(',', $list); return $list; } private static $static_server_idx = 1; /** * 获得静态文件服务器地址,不带"http:",以/结尾,适用js、css; * @return string */ public static function get_static_url() { $default_url = '//192.168.2.10:8002/'; if (Yii::app()->params['local_test'] === FALSE) { if (self::$static_server_idx > 5) { self::$static_server_idx = 1; } $url = '//img' . self::$static_server_idx . '.dacaipu.cn/'; self::$static_server_idx++; return $url; } else { return $default_url; } } /** * 获得静态文件服务器地址,不带"http:",以/结尾,适用img; * @return type */ public static function get_http_static_url() { return 'http:' . busUlitity::get_static_url(); } } <file_sep><?php /** * order 的注释 * * @作者 roy */ class Order extends Eloquent { protected $table = 'orders'; protected $primaryKey = 'order_id'; public $timestamps = false; /** * 获取待处理订单 * @param type $dealer_id * @return type */ public static function getWaitProcessOrders($dealer_id) { $sql = 'SELECT orders.order_id, orders.order_paid, orders.order_dinnertime, orders.order_type, orders.order_createtime, orders.order_status, contact.contact_addr, contact.contact_name, contact.contact_tel, ( SELECT SUM(order_count) FROM order_dish_flash WHERE order_dish_flash.order_id = orders.order_id ) AS dish_count FROM orders INNER JOIN contact ON orders.contact_id = contact.contact_id WHERE orders.order_type in (1,2) and orders.order_status in (2,3,5,6,7) and orders.dealer_id=:dealer_id'; $list = DB::select($sql, array(':dealer_id' => $dealer_id)); return $list; } public static function getHistoryOrders($dealer_id, $start) { $sql = 'SELECT count(1) as rows FROM orders INNER JOIN contact ON orders.contact_id = contact.contact_id where orders.order_type in (1,2) and orders.dealer_id=:dealer_id and orders.order_status in (8,9)'; $total_count = DB::selectOne($sql, array(':dealer_id' => $dealer_id))->rows; $sql = 'SELECT orders.order_id, orders.order_paid, orders.order_dinnertime, orders.order_type, orders.order_createtime, orders.order_status, contact.contact_addr, contact.contact_name, contact.contact_tel, ( SELECT SUM(order_count) FROM order_dish_flash WHERE order_dish_flash.order_id = orders.order_id ) AS dish_count FROM orders INNER JOIN contact ON orders.contact_id = contact.contact_id where orders.order_type in (1,2) and orders.dealer_id=:dealer_id and orders.order_status in (8,9) order by orders.order_id desc limit ' . $start . ',10'; $list = DB::select($sql, array(':dealer_id' => $dealer_id)); $result = new stdClass(); $result->total_count = $total_count; $result->list = $list; return $result; } } <file_sep> var page = 1; var http_static_url = 'http://img2.dacaipu.cn/'; $(document).ready(function() { get_Content(); $('#category_id').on('change', function() { page=1; get_Content(); }); $('#name').on('pressup', function(){ page=1; get_Content(); }); $('#product_img').uploadify({ 'formData': { 'timestamp': new Date().getMilliseconds() }, 'swf': '/js/uploadify/uploadify.swf', 'buttonText': '选择图片', 'buttonImage': http_static_url + '60_60/mobile/img/dish_default.png', 'height': 60, 'width': 60, 'uploader': '/product_img', 'onUploadSuccess': function(file, data, response) { var obj = JSON.parse(data); //$('#dish_img').attr('src', obj.file_path); $('#product_img_url').attr('value', obj.new_path); $('#product_img-button').css('backgroundImage', 'url(' + obj.file_path + ') 100% 100%'); }, 'onUploadError': function(file, errorCode, errorMsg, errorString) { alert('The file ' + file.name + ' could not be uploaded: ' + errorString); } }); $('#product_form_layer form').validate({ errorClass: 'text-danger', submitHandler: function(form) { if ($('#edit_category_id').val() == '0') { $('#edit_category_msg').html('请选择所属类别'); return false; } if ($(form).valid()) { var args = $(form).serialize(); $.post('/save_product', args, function(obj) { get_Content(); $.fancybox.close(); }, 'json'); } } }); $('#product_add_form_layer form').validate({ errorClass: 'text-danger', submitHandler: function(form) { if ($(form).valid()) { var args = $(form).serialize(); $.post('/add_product', args, function(obj) { get_Content(); $.fancybox.close(); }, 'json'); } } }); }); function edit_product(product_id) { clear_form(); $('#product_id').attr('value', product_id); if (product_id != -1) { $.post('/product_item.json', {"product_id": product_id}, function(obj) { $('#edit_product_name').val(obj.dish_name); $('#edit_category_id').val(obj.category_id); $('#product_price').val(obj.dish_price); $('#product_count').val(obj.dish_count); $('#alert_count').val(obj.alert_count); $('#product_status').val(obj.dish_status); $('#product_img_url').val(obj.pic_url); $('#product_memo').val(obj.dish_introduction); $('#product_presell').val(obj.is_presell); $('#product_img-button').css('background-image', 'url(' + http_static_url + obj.pic_url + ')'); $.fancybox($('#product_form_layer')); }, 'JSON'); } else { $.fancybox($('#product_form_layer')); } } function clear_form() { $('#product_id').attr('value', '0'); $('#edit_product_name').val(''); $('#edit_category_id').val('0'); $('#product_price').val(''); $('#product_count').val(''); $('#alert_count').val(''); $('#product_memo').val(''); } function go(to_page) { page = to_page; get_Content(); } function get_Content() { $.post('/product_paged_list?page=' + page, { 'category_id': $('#category_id').val(), 'product_name': $.trim($('#product_name').val()) }, function(data) { $('#h3_msg').hide(); $('#contents').html(data); $('.pagination li a').each(function(idx, a) { var url = $(this).attr('href'); var datas = url.split('?')[1].split('&'); var page = 1; for (var i = 0; i < datas.length; i++) { var d = datas[i].split('='); page = d[1]; } $(this).attr('onclick', 'go(' + page + ');'); $(this).attr('href', 'javascript:void(0);'); }); }); } function add_product(product_id) { $('#add_product_id').attr('value', product_id); $.post('/product_item.json', {"product_id": product_id}, function(obj) { $('#add_product_name').html(obj.dish_name); $('#add_product_count').html(obj.dish_count); $('#add_count').val(''); $.fancybox($('#product_add_form_layer')); }, 'JSON'); } function change_product_status(product_id, status_code) { $('#btn_'+product_id).addClass('disabled'); $.post('/change_product_status', { 'product_id': product_id, 'status_code': status_code }, function(obj) { if (obj.code == 0) { $('#btn_' + product_id).attr('value', status_code == 0 ? '上架' : '下架'); $('#btn_' + product_id).removeAttr('onclick'); $('#btn_' + product_id).attr('onclick', 'change_product_status(' + product_id + ',' + (status_code == 0 ? 1 : 0) + ');'); $('#cell_' + product_id).html(status_code == 1 ? '上架' : '下架'); $('#btn_'+product_id).removeClass('disabled'); } },'json'); }<file_sep><?php class HomeController extends BaseController { /* |-------------------------------------------------------------------------- | Default Home Controller |-------------------------------------------------------------------------- | | You may wish to use controllers instead of, or in addition to, Closure | based routes. That's great! Here is an example controller method to | get you started. To route to this controller, just add the route: | | Route::get('/', 'HomeController@showWelcome'); | */ public function login() { ob_clean(); ob_flush(); if(Request::isMethod('GET')) { return View::make('home.login'); } else { $rules = array( 'username' => array('required'), 'passwd' => array('required'), 'captcha' => array('required', 'captcha')); $messages = array( 'username.required' => '用户名必须填写', 'passwd.required' => '<PASSWORD>', 'captcha.required' => '验证码必须填写', 'captcha.captcha' => '验证码错误', ); $validator = Validator::make(Input::all(), $rules, $messages); if ($validator->fails()) { $mb = $validator->getMessageBag(); return Redirect::route('login')->withErrors($mb)->withInput(); } else { $username = Input::get('username'); $passwd = Input::get('<PASSWORD>'); $remember = Input::has('remember'); $mb = new \Illuminate\Support\MessageBag(); $encry_pwd = md5($username . $passwd); $customer = Customer::where('customer_name', $username)->first(); if (empty($customer)) { $mb->add('username', '该用户不存在'); return Redirect::route('login')->withErrors($mb)->withInput(); } if ($customer->customer_pwd != $encry_pwd) { $mb->add('passwd', '密码错误'); return Redirect::route('login')->withErrors($mb)->withInput(); } Auth::login($customer,$remember); return Redirect::intended(); } } } public function logout() { Auth::logout(); return Redirect::to('/'); } } <file_sep><?php /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It's a breeze. Simply tell Laravel the URIs it should respond to | and give it the Closure to execute when that URI is requested. | */ //Route::match(array('GET','POST'),'/', 'HomeController@Login'); Route::get('/',function() { if(!Auth::check()) { return View::make('home.login'); } else { return Redirect::to('new_orders'); } }); Route::match(array('GET','POST'),'/login', array('as' => 'login', 'uses' => 'HomeController@Login')); Route::get('logout', 'HomeController@logout'); Route::group(array('before' => 'auth',), function() { /* Route::get('/', array('as' => '/', function(){ return Redirect::to('new_orders'); })); * */ Route::get('new_orders.json', 'OrderController@new_orders_json'); Route::get('new_orders', 'OrderController@new_orders'); Route::get('history_orders.json', 'OrderController@history_orders_json'); Route::get('history_orders', 'OrderController@history_orders'); Route::post('change_order_status', 'OrderController@change_order_status'); Route::get('category', 'ProductController@product_category'); Route::post('change_category_status','ProductController@change_category_status'); Route::post('save_category','ProductController@save_category'); Route::post('product_paged_list','ProductController@product_paged'); Route::get('product','ProductController@product'); Route::post('save_product','ProductController@save_product'); Route::post('product_item.json', 'ProductController@product_item_json'); Route::post('add_product','ProductController@add_product'); Route::post('change_product_status','ProductController@change_product_status'); }); Route::post('product_img', 'ProductController@upload_product_img'); Route::get('flushcache', function(){ Cache::flush(); }); <file_sep><?php namespace Business; /** * 电商下单相关业务 * @作者 roy */ class busOrderds { /** * * @param type $result * $result->order_id 订单id; * $result->reason 订单拒绝原因; * @return type */ public function order_status_notice($result) { $bs = new busSms(); $order = \Order::find($result->order_id); if (!isset($order)) { Log::info('订单状态通知失败:订单不存在。订单号:' . $result->order_id); return false; } $dealer = \Dealer::find($order->dealer_id); $order_status = $order->order_status; $contact = \Contact::find($order->contact_id); $msg = ''; if ($order->order_type == 1) { switch ($order_status) { /* * 等待付款 */ case 1: { } break; /* * 等待处理 */ case 2: { } break; /* * 处理中 */ case 3: { $msg = sprintf("您的订单【订单号:%s】已开始备货!", $result->order_id); } break; /* * 已拒绝 */ case 4: { $msg = sprintf("非常抱歉,您的订单【订单号:%s】被店家拒绝了,拒绝原因是 %s", $result->order_id, $result->reason); } break; /* * 等待配送 */ case 5: { $msg = sprintf("您的订单【订单号:%s】备货完毕,准备配送!", $result->order_id); } break; /* * 等待自取 */ case 6: { $msg = sprintf("您的订单【订单号:%s】已备货完毕,请尽快来取货!", $result->order_id); } break; /* * 配送中 */ case 7: { $msg = sprintf("您的订单【订单号:%s】已在配送途中,请准备收货!", $result->order_id); } break; /* * 完成订单 */ case 8: { //$msg = sprintf("您的订单【订单号:%s】已完成,感谢您的支持!", $result->order_id); } break; /* * 订单结束 */ case 9: { } break; default: break; } } else if ($order->order_type == 2) { switch ($order_status) { /* * 等待付款 */ case 1: { } break; /* * 等待处理 */ case 2: { } break; /* * 处理中 */ case 3: { $msg = sprintf("您的订单【订单号:%s】已开始备货,请于%s到%s自取。地址:%s,电话:%s。", $result->order_id, date("Y年m月d日 H点i分", strtotime($order->order_dinnertime)), $dealer->dealer_name, $dealer->dealer_addr, $dealer->dealer_tel); } break; /* * 已拒绝 */ case 4: { $msg = sprintf("非常抱歉,您的订单【订单号:%s】被店家拒绝了,拒绝原因是 %s", $result->order_id, $result->reason); } break; /* * 完成订单 */ case 8: { //$msg = sprintf("您的订单【订单号:%s】已完成,感谢您的支持!", $result->order_id); } break; /* * 订单结束 */ case 9: { } break; default: break; } } if (!empty($msg)) { $bs->send($contact->contact_tel, $msg, $dealer->dealer_name); } return true; } } <file_sep><?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * Login 的注释 * * @作者 roy */ class Login { public $username; public $passwd; public $valicode; } <file_sep> cur_page = 1; max_page = 0; $(document).ready(function() { $(document).on('click', '.row_order', function() { $('.row_detail').addClass('hidden'); $('.row_order').removeClass('bg-info'); $(this).addClass('bg-info'); var id = $(this).attr('id').replace('row_order_', ''); $('#row_detail_' + id).removeClass('hidden'); }); getOrders(); }); function pre() { if (cur_page > 1) { cur_page--; getOrders(); } } function next() { if (cur_page != max_page) { cur_page++; getOrders(); } } function go(page) { cur_page = page; getOrders(); } function getOrders() { $.getJSON('/history_orders.json?ts=' + new Date().getMilliseconds(), {'page': cur_page}, function(data) { $('.pagination').empty(); $('.pagination').append('<li onclick="pre();"><a href="javascript:void(0);">&laquo;</a></li>'); var total_page = Math.ceil(data.total_count / 10); max_page = total_page; for (var i = 1; i <= total_page; i++) { $('.pagination').append('<li class="' + (i == cur_page ? "active" : "") + '"><a href="javascript:void(0);" onclick="go(' + i + ');">' + i + '</a></li>'); } $('.pagination').append('<li onclick="next();"><a href="javascript:void(0);">&raquo;</a></li>'); var list = $('#order_list'); $(list).empty(); var title = '<tr><th class="text-center">订单编号</th><th class="text-center">订单用户</th><th class="text-center">订单类别</th><th class="text-center">订单总价</th><th class="text-center">订单状态</th><th class="text-center">下单时间</th></tr>'; $(list).append(title); if (data.length == 0) { $('#h3_msg').html('还没有订单。'); } else { $('#h3_msg').hide(); $(list).removeClass('hidden'); } $(data.list).each(function(index, obj) { var str = '<tr id="row_order_' + obj.order_id + '" class="row_order">'; str += '<td class="text-center">'; str += obj.order_id; str += '<input type="hidden" value="' + obj.order_id + '"/>'; str += '</td><td class="text-left">'; str += obj.contact_name + '<br/>'; str += obj.contact_tel + '<br/>'; str += obj.contact_addr + '<br/>'; str += '</td><td class="text-center">'; str += obj.order_type == 1 ? '送货上门' : '到店自取'; str += '</td><td class="text-center">'; str += '¥' + obj.order_paid; str += '</td><td class="text-center">'; str += obj.status == 8 ? '已完成' : '已结束'; str += '</td><td class="text-center">'; str += obj.order_createtime; str += '</td></tr>'; str += '<tr id="row_detail_' + obj.order_id + '" class="row_detail hidden">'; str += '<td colspan="3">'; str += '订 单 号: ' + obj.order_id; str += '&nbsp;&nbsp;<a href="#" onclick="return printOrder(' + obj.order_id + ');">'; str += '<img src="//img1.dacaipu.cn/pc/images/icon_printer-alt.png" width="16px" height="16px" border="0" alt="打印" title="打印">'; str += '</a>'; str += '<br/>'; if (obj.order_type == 1) { str += '收货时间:' + obj.order_dinnertime; } else { str += '取货时间:' + obj.order_dinnertime; } str += '<br/>用户备注:' + obj.memo; str += '<br/>'; str += '</td>'; str += '<td colspan="3">'; str += '<table class="table table-bordered"><tr><td colspan="3"><strong>订单详情</strong></td></tr><tr><td>商品</td><td>数量</td><td>单价</td></tr>'; // $(obj.products).each(function(idx, product) { str += '<tr><td>'; str += product.dish_name; str += '</td><td>' + product.order_count; str += '</td><td>'; str += $.money((parseFloat(product.dish_price) + parseFloat(product.dish_package_fee))) + '</td>'; str += '</tr>'; }); $(obj.discount).each(function(idx, discount) { str += '<tr><td>' + discount.discount_name + '</td><td></td><td>-' + discount.discount_money_value + '</td></tr>'; }); if (obj.coupon) { str += '<tr><td>优惠券(' + obj.coupon.coupon_code + ')</td><td></td><td>-' + obj.coupon.coupon_value + '</td></tr>'; } if (obj.order_type == 1) { str += '<tr><td>配送费</td><td>1</td><td>' + obj.express_fee + '</td></tr>'; } str += '<tr><td colspan="2">总计</td><td>' + obj.order_paid + ' 元</td></tr>'; str += '</td></tr>'; $(list).append(str); }); }); }<file_sep><?php use Business\busOrderds; /** * OrderController 的注释 * * @作者 roy */ class OrderController extends BaseController { /** * 获得今日订单 * @return array */ public function new_orders_json() { $ods = array(); $orders = Order::getWaitProcessOrders($this->dealer->dealer_id); foreach ($orders as $order) { $products = OrderDishFlash::where('order_id', '=', $order->order_id)->get(); $order->products = $products; $order->express_fee = $this->dealer->dealer_express_fee; $order_dis = OrderDiscount::where('order_id', '=', $order->order_id)->get(); $order->discount = $order_dis; $coupon = Coupon::where('order_id', '=', $order->order_id)->first(); $order->coupon = $coupon; $msg = OrderStatusMessage::where('order_id', '=', $order->order_id) ->where('cur_order_status', '=', 2) ->first(); $order->memo = $msg->memo; array_push($ods, $order); } return $ods; } public function new_orders() { //\Debugbar::disable(); return View::make('orders.newlist'); } public function change_order_status() { $result = new stdClass(); $order_id = Input::get('order_id'); $order_status = Input::get('order_status'); $new_status = Input::get('new_status'); $reason = Input::get('reason', ''); if($new_status == 4 && empty($reason)) { $result->code = -2; $result->msg = 'reason is must.'; return json_encode($result); } $order = Order::find($order_id); if (empty($order)) { $result->code = -1; $result->msg = 'order not exist'; return json_encode($result); } if ($order_status != $order->order_status) { $result->code = -1; $result->msg = '该订单已被处理,请刷新!'; return json_encode($result); } try { DB::beginTransaction(); $order->order_status = $new_status; $order->update(); $osm = new OrderStatusMessage(); $osm->order_id = $order->order_id; $osm->cur_order_status = $new_status; $osm->memo = $reason; $osm->modifier_id = Auth::user()->cusetomer_id; $osm->save(); if($new_status == 4) { $products = OrderDishFlash::where('order_id','=',$order_id)->get(); foreach($products as $product) { $dish = Product::find($product->dish_id); $dish->dish_count = $dish->dish_count + $product->order_count; $dish->update(); } } $notice_obj = new stdClass(); $notice_obj->order_id = $order_id; $notice_obj->reason = $reason; $bo = new busOrderds(); $bo->order_status_notice($notice_obj); DB::commit(); $result->code = 0; return json_encode($result); } catch (Exception $e) { DB::rollBack(); Log::debug($e->getLine() . $e->getMessage()); Log::debug($e->getTraceAsString()); $result->code = -1; $result->msg = $e->getMessage(); return json_encode($result); } } public function history_orders_json() { $page = Input::get('page',1); $start = ($page - 1) * 10 + 1; $result = Order::getHistoryOrders($this->dealer->dealer_id, $start); $ods = array(); foreach ($result->list as $order) { $products = OrderDishFlash::where('order_id', '=', $order->order_id)->get(); $order->products = $products; $order->express_fee = $this->dealer->dealer_express_fee; $order_dis = OrderDiscount::where('order_id', '=', $order->order_id)->get(); $order->discount = $order_dis; $coupon = Coupon::where('order_id', '=', $order->order_id)->first(); $order->coupon = $coupon; $msg = OrderStatusMessage::where('order_id', '=', $order->order_id) ->where('cur_order_status', '=', 2) ->first(); $order->memo = $msg->memo; array_push($ods, $order); } $result->list = $ods; return json_encode($result); } public function history_orders() { return View::make('orders.historylist'); } } <file_sep><?php use Illuminate\Auth\UserTrait; use Illuminate\Auth\UserInterface; use Illuminate\Auth\Reminders\RemindableInterface; /** * Customer 的注释 * * @作者 roy */ class Customer extends Eloquent implements UserInterface { use UserTrait; protected $table = 'customer'; protected $primaryKey = 'customer_id'; protected $username = 'customer_name'; public $timestamps = false; /** * The attributes excluded from the model's JSON form. * * @var array */ protected $hidden = array('customer_pwd',); protected $fillable = array('customer_name','customer_mobile','customer_email','customer_pwd'); protected $guarded = array('customer_pwd'); } <file_sep><?php use Carbon\Carbon; /** * ProductController 的注释 * * @作者 roy */ class ProductController extends BaseController { public function product_category() { $categories = ProductCategory::where('dealer_id', '=', $this->dealer->dealer_id)->orderBy('category_id', 'desc')->get(); return View::make('product.category')->with('categories', $categories); } public function change_category_status() { $result = new stdClass(); DB::transaction(function() { $category_id = Input::get('category_id'); $status = Input::get('status_code'); $category = ProductCategory::find($category_id); $category->category_status = $status; $category->update(); $results = DB::select('select * from dish_category_relation where category_id = ?', array($category_id)); if (isset($results)) { foreach ($results as $key => $value) { $dish = Product::find($value->dish_id); $dish->dish_status = $status; $dish->update(); } } }); $result->code = 0; return json_encode($result); } public function save_category() { $result = new stdClass(); $category_id = Input::get('category_id', 0); $category_name = Input::get('category_name'); if (empty($category_name)) { $result->code = -1; return json_encode($result); } if ($category_id == 0) { $category = new ProductCategory(); $category->category_name = $category_name; $category->category_status = 0; $category->dealer_id = $this->dealer->dealer_id; $category->category_parent_id = -1; $category->save(); $new_id = $category->category_id; $result->category_id = $new_id; $result->code = 0; return json_encode($result); } else { $category = ProductCategory::find($category_id); $category->category_name = $category_name; $category->update(); $result->code = 0; return json_encode($result); } } public function product_paged() { $category_id = Input::get('category_id', 0); $name = Input::get('product_name', null); //product list. $list = Product::getProducts($this->dealer->dealer_id, $category_id, $name); return View::make('product.product_paged_list', array('list' => $list)); } public function product_item_json() { $product_id = Input::get('product_id'); $product = Product::find($product_id); $cate = ProductCategoryRelation::where('dish_id', '=', $product_id)->first(); $product->category_id = $cate->category_id; $pic = Pic::where('entity_id', '=', $product_id) ->where('pic_type', '=', 2) ->first(); $product->pic_url = $pic->pic_url; return json_encode($product); } public function upload_product_img() { $result = new stdClass(); $tempFile = $_FILES['Filedata']['tmp_name']; $fileTypes = array('jpg', 'jpeg', 'gif', 'png'); $fileParts = pathinfo($_FILES['Filedata']['name']); //\Debugbar::disable(); if (!in_array($fileParts['extension'], $fileTypes)) { $result->code = -1; $result->msg = 'eror file type.'; return json_encode($result); } $path = Config::get('site.img_upload_path') . date('Ym', time()) . '/'; if (!File::exists($path)) { File::makeDirectory($path, 0777); } $new_file_name = "1_" . Carbon::now()->getTimestamp() . '_1.' . $fileParts['extension']; move_uploaded_file($tempFile, $path . $new_file_name); $result->code = 0; $result->new_path = 'upload/' . date('Ym', time()) . '/' . $new_file_name; $result->name = $new_file_name; $result->file_path = Config::get('site.img_http_path') . 'upload/' . date('Ym', time()) . '/' . $new_file_name; Cache::flush(); return json_encode($result); } public function product() { $categories_cache_key = 'categories_' . $this->dealer->dealer_id; $cates = Cache::get($categories_cache_key, null); if (!isset($categories)) { $categories = ProductCategory::whereRaw('dealer_id = :dealer_id and category_status = 1', array(':dealer_id' => $this->dealer->dealer_id)) ->select(array('category_id', 'category_name')) ->get(); $cates = array(); $cates[0] = '请选择'; foreach ($categories as $k => $category) { $cates[$category->category_id] = $category->category_name; } Cache::put($categories_cache_key, $cates, 200); } return View::make('product.product_list', array('categories' => $cates)); } public function product_json() { return Product::getProducts($this->dealer->dealer_id); //paginate(10)->toArray(); } public function save_product() { $result = new stdClass(); $product_name = Input::get('edit_product_name'); $product_id = Input::get('product_id'); $product_category = Input::get('edit_category_id'); $product_count = Input::get('product_count', 0); $product_price = Input::get('product_price', 0); $alert_count = Input::get('alert_count', 0); $product_status = Input::get('product_status'); $product_img_url = Input::get('product_img_url'); $product_presell = Input::get('product_presell'); $product_memo = Input::get('product_memo'); if (empty($product_name) || empty($product_category) || (!is_numeric($product_count)) || (!is_numeric($product_price))) { $result->code = (empty($product_name) || empty($product_category) || (!is_numeric($product_count)) || (!is_numeric($product_price)) ); $result->msg = "args invalid."; return json_encode($result); } DB::beginTransaction(); try { $product = null; if ($product_id == -1) { $product = Product::whereRaw('dealer_id=:dealer_id and dish_name = :dish_name', array(':dealer_id' => $this->dealer->dealer_id, ':dish_name' => $product_name))->first(); if (!isset($product)) { $product = new Product(); } } else { $product = Product::find($product_id); } $py = new Business\busPinyin(); $jp = $py->getFirstPY($product_name); $qp = $py->getAllPY($product_name); $product->dish_name = $product_name; $product->dish_jianpin = $py->getFirstPY($product_name); $product->dish_quanpin = $py->getAllPY($product_name); $product->dish_recommend = 0; $product->dish_package_fee = 0; $product->dish_is_vaget = 0; $product->dish_spicy_level = 0; $product->dish_introduction = $product_memo; $product->dish_status = $product_status; $product->dish_createtime = Carbon::now()->getTimestamp(); $product->dish_mode = 1; $product->dish_modifytime = Carbon::now()->getTimestamp(); $product->dish_price = $product_price; $product->dish_count = $product_count; $product->alert_count = $alert_count; $product->is_presell = $product_presell; $product->dealer_id = $this->dealer->dealer_id; $product->save(); $dr = DB::table('dish_category_relation') ->where('dish_id', '=', $product->dish_id) //->where('category_id', '=', $product_category) ->first(); if (!isset($dr)) { DB::table('dish_category_relation') ->insert(array('dish_id' => $product->dish_id, 'category_id' => $product_category)); } else { DB::update(' update dish_category_relation set category_id=:category_id where dish_id=:dish_id', array(':category_id' => $product_category, ':dish_id' => $product->dish_id)); } if (!empty($product_img_url)) { $pic = Pic::whereRaw('entity_id=:product_id and pic_type=2', array(':product_id' => $product->dish_id)) ->first(); if (isset($pic)) { $pic->pic_url = $product_img_url; $pic->update(); } else { $pic = new Pic(); $pic->entity_id = $product->dish_id; $pic->pic_type = 2; $pic->pic_url = $product_img_url; $pic->save(); } } DB::commit(); Cache::flush(); $result->code = 0; } catch (Exception $e) { DB::rollBack(); Log::error($e->getMessage()); Log::error($e->getTraceAsString()); $result->msg = $e->getMessage(); $result->code = -1; } return json_encode($result); } public function add_product() { $product_id = Input::get('add_product_id'); $add_count = Input::get('add_count'); $result = new stdClass(); if (!(is_numeric($product_id) && $product_id > 0 && is_numeric($add_count))) { $result->code = -1; $result->msg = 'args error.'; return json_encode($result); } $product = Product::find($product_id); $product->dish_count += intval($add_count); $product->update(); $result->code = 0; Cache::flush(); return json_encode($result); } public function change_product_status() { $result = new stdClass(); $product_id = Input::get('product_id'); $status = Input::get('status_code'); $product = Product::find($product_id); $product->dish_status = $status; $product->update(); Cache::flush(); $result->code = 0; return json_encode($result); } } <file_sep>/* * js data struct of dictionary key-value map. * to use like this: * var dic = new Dictionary(); * dic.add('a',1); * dic.contains('a'); * dic.remove('a'); * */ function KVStuct(k,v) { this.k = k; this.v = v; } function Dictionary() { this.key_list = Array(); this.map = Array(); } Dictionary.prototype.contains = function(k) { var i = this.key_list.length; while (i--) { if (this.key_list[i] === k) { return true; } } return false; } Dictionary.prototype.add = function(k, v) { for (var i = 0; i < this.key_list.length; i++) { if (this.key_list[i] === k) { this.map[i].v = v; return; } } this.key_list[this.key_list.length] = k; this.map[this.map.length] = new KVStuct(k, v); } Dictionary.prototype.remove = function(k) { var key,v; for (var i = 0; i < this.key_list.length; i++) { key = this.key_list.pop(); v = this.map.pop(); if (key === k) { continue; } this.key_list.unshift(key); this.map.unshift(v); } } Dictionary.prototype.get = function(k) { for(var i = 0;i < this.key_list.length; i++) { if(this.key_list[i] === k) { return this.map[i]; } } }<file_sep><?php class BaseController extends Controller { /** * Setup the layout used by the controller. * * @return void */ protected function setupLayout() { if ( ! is_null($this->layout)) { $this->layout = View::make($this->layout); } } protected $dealer = null; public function __construct() { if(Auth::check()) { $dealer = Session::get('dealer_info', null); if(empty($this->dealer)) { $dealer = Dealer::getByCustomerId(Auth::user()->customer_id); $this->dealer = $dealer; } } } }
fd365d42546d6ba5194ad520faee13e788c30d6c
[ "JavaScript", "PHP" ]
15
PHP
timjoke/dacaipu_ds
726fa7bd0bfa4e16372a6604513908773a4a5a78
cc3c1a125a79d1da3281b09d6f37cdfa2e89da44
refs/heads/master
<repo_name>ognjetina/mergeimages<file_sep>/README.md # Mergeimages mergeimages is a pip script for merging screenshots in one image for easier sharing ## Install and use #### installation: ```pip install mergeimages``` ====== #### usage: navigate to folder where your screenshots are and just run ```mergeimages``` ====== or run mergeimages with folder path of images ```mergeimages ~/Desktop/folderWithMyImages``` ====== it will take all png images and combine them in one<file_sep>/mergeimages/mergeimages #!/usr/bin/python import sys from PIL import Image import glob import os images_folder_path = sys.argv[1:] images = [] if not images_folder_path: print("You did not provide path will merge images from here!") images_folder_path = os.getcwd().__str__() print(images_folder_path) else: images_folder_path = images_folder_path[0].__str__() for file in glob.glob(images_folder_path + "/*.png"): im = Image.open(file) images.append(im) if images: widths, heights = zip(*(i.size for i in images)) total_width = sum(widths) max_height = max(heights) new_im = Image.new('RGB', (total_width, max_height)) x_offset = 0 for im in images: new_im.paste(im, (x_offset, 0)) x_offset += im.size[0] print("saving to:" + images_folder_path) new_im.save(images_folder_path + '/merged-' + len(images).__str__() + '-Images.jpg') else: print("Did not find any .png images") <file_sep>/setup.py from setuptools import setup setup( name='mergeimages', author='ognjetina', author_email='<EMAIL>', version='0.1', scripts=['mergeimages/mergeimages'], install_requires=['image', 'olefile', 'Pillow', 'pytz'], )
7eb79203c7132c9c2340460d67b1756bd283d258
[ "Markdown", "Python" ]
3
Markdown
ognjetina/mergeimages
ab77220519ed8fbc27906bd323a746d44699f991
fdeab5d6e26892236380d4e3341139ba1c6f6ace
refs/heads/master
<repo_name>Carlos-Blandino/swift-challenge-problems<file_sep>/README.md # swift-challenge-problems Solving practice problems in Swift <file_sep>/fibonacci.playground/Contents.swift import UIKit import UIKit func fibonacci(n: Int) { var result = [0,1] let totalIndex = n - 1 var firstNum = 0 var secondNum = 1 var nextNum = 0 var currentIndex = 2 if n == 0 { print("not valid") return } else if n == 1 { print(result[0]) } else if n == 2 { print(result[0...1]) } else { //Write your code here. for num in currentIndex...totalIndex { nextNum = firstNum + secondNum result.append(nextNum) firstNum = secondNum secondNum = nextNum } print(result) } } fibonacci(n: 1)
0242549384623e4a8ba6c15ed17fd4f925dca788
[ "Markdown", "Swift" ]
2
Markdown
Carlos-Blandino/swift-challenge-problems
3aed4903aaa85194d90b99e94c478fb5bb5b67aa
f7ad53f47abff33cc0ddcc5d2dd7673a362558f6
refs/heads/master
<file_sep>## Install Install project dependencies ``` sudo apt install python3-tk ``` ``` pip install -r requirements.txt ``` ## Run ``` python3 main.py ``` ## Use ![certificate generator photo](screenshot/screenshot.png) **Certificate template**: accepts .JPG or .PNG formats. **Input spreadsheet: accepts** .csv or .xlsx formats. **Certificate text**: the spreadsheet information is filled in using `{}` or `{0}` corresponding to the column index, which represents data from the file line as you can see in the example image. **Font**: Select a font that is installed on your system. **Output folder**: folder where you will save the certificates.<file_sep>import os import traceback from io import BytesIO from pathlib import Path import matplotlib.font_manager as fontman from PIL import Image from utils import image_utils def find_font_file(query): matches = list(filter(lambda path: query in os.path.basename(path), fontman.findSystemFonts())) return matches def scale_to_width(dimensions, width): height = (width * dimensions[1]) / dimensions[0] return int(width), int(height) def open_image(path): im = Image.open(path) pixel_data = im.load() if im.mode == "RGBA": # If the image has an alpha channel, convert it to white # Otherwise we'll get weird pixels for y in range(im.size[1]): # For each row ... for x in range(im.size[0]): # Iterate through each column ... # Check if it's opaque if pixel_data[x, y][3] < 255: # Replace the pixel data with the colour white pixel_data[x, y] = (255, 255, 255, 255) return im def generate_certificate(text, certificate: Image or Path or str, pos_x, pos_y, width, font_size, line_spacing, alignment, color, font, data=None, preview=True): # TODO: there's gotta be a better way! font_path = font if isinstance(certificate, (str, Path)): im = open_image(certificate) else: im = certificate text_y = im.height * pos_y / 100 text_x = im.width * pos_x / 100 text_width = im.width * width / 100 im = image_utils.ImageText(im) if data: try: text = text.format(*data.values()) except Exception as e: traceback.print_exc() im.write_text_box(text_x, text_y, box_width=text_width, font_filename=str(font_path), text=text, font_size=font_size, line_spacing=line_spacing, color=color, place=alignment) if preview: size = scale_to_width(im.image.size, 400) b = BytesIO() im.image.resize(size, Image.BICUBIC).convert('RGB').save(b, format='PNG') return b.getvalue(), size else: output = BytesIO() im.image.convert("RGB").save(output, format='PDF') output.seek(0) return output <file_sep>import os import gettext import PySimpleGUI as sg import matplotlib.font_manager as fontman import pandas as pd import locale from utils import certificate gt = gettext.translation('main', localedir='locale', languages=[locale.getlocale()[0]], fallback=True) gt.install() font_list = sorted(fontman.findSystemFonts(fontpaths=None, fontext='ttf')) col_left = [[sg.Text(_('Certificate model image')), sg.Input(key='path_model'), sg.FileBrowse(_('Search'), target='path_model', file_types=((_('JPG images'), '*.jpg'), (_('PNG images'), '*.png'),))], [sg.Text(_('Input sheet')), sg.Input(key='path_sheet'), sg.FileBrowse(_('Search'), target='path_sheet')], [sg.Text(_('Certificate text')), sg.Multiline(key='certificate_text'), sg.In(key='color', visible=False), sg.ColorChooserButton(_('Text color'), target='color')], [sg.Text(_('Font')), sg.Combo(font_list, key='font', readonly=True, default_value=font_list[0])], [sg.Text(_('Font size')), sg.Slider(range=(12, 172), orientation='h', size=(48, 20), change_submits=True, key='slider_font')], [sg.Text(_('Line spacing')), sg.Slider(range=(1, 50), orientation='h', size=(44, 20), default_value=10.0, change_submits=True, key='slider_linespacing')], [sg.Text(_('Text alignment')), sg.Radio(_('Left'), "alignment", key='align_left'), sg.Radio(_('Right'), "alignment", key='align_right'), sg.Radio(_('Center'), "alignment", key='align_center'), sg.Radio(_('Justified'), "alignment", key='align_justify', default=True), ], [sg.Text(_('Position X (%)')), sg.Slider(range=(1, 100), orientation='h', size=(50, 20), resolution=0.5, change_submits=False, default_value=15.0, key='slider_x')], [sg.Text(_('Position Y (%)')), sg.Slider(range=(1, 100), orientation='h', size=(50, 20), resolution=0.5, change_submits=False, default_value=35.0, key='slider_y')], [sg.Text(_('Width (%)')), sg.Slider(range=(1, 100), orientation='h', default_value=70.0, size=(51, 20), resolution=0.5, change_submits=False, key='width')], [sg.Text(_('Output folder')), sg.Input(key='path_output'), sg.FolderBrowse(_('Search'), target='path_output')], ] col_right = [[sg.Text(_('Preview:'))], [sg.Image(data='', size=(400, 309), key='preview')]] layout = [ [sg.Column(col_left), sg.Column(col_right)], [sg.OK(), sg.Cancel(_('Close'))], ] window = sg.Window(_("Mass certificate generator")).Layout(layout) # Event Loop current_values = None cache = {} while True: event, values = window.Read(timeout=300) if current_values is None: current_values = values if event is None: break path = values['path_model'] path_data = values['path_sheet'] path_output = values['path_output'] alignment = [x[0].split('_')[1] for x in values.items() if 'align_' in x[0] and x[1] is True][0] color = values['color'].lstrip('#') if values.get('color') else '000000' color = tuple(int(color[i:i + 2], 16) for i in (0, 2, 4)) if path and os.path.exists(path) and not os.path.isdir(path) and current_values != values: current_values = values if path not in cache.keys(): cache[path] = certificate.open_image(path) example_data = None if path_data and os.path.exists(path_data) and not os.path.isdir(path_data) and path_data not in cache.keys(): if path_data.lower().endswith('.xlsx'): cache[path_data] = pd.read_excel(path_data).to_dict('records') elif path_data.lower().endswith('.csv'): cache[path_data] = pd.read_csv(path_data).to_dict('records') if path_data in cache.keys(): example_data = cache[path_data][0] im, size = certificate.generate_certificate(values['certificate_text'], cache[path].copy(), values['slider_x'], values['slider_y'], values['width'], int(values['slider_font']), int(values['slider_linespacing']), alignment, color, values['font'], example_data, True) window.FindElement('preview').Update(data=im, size=size) if event == 'Generate': if path_data and os.path.exists(path_data) and not os.path.isdir( path_data) and path_output and os.path.exists(path_output) and os.path.isdir(path_output): for i, x in enumerate(cache[path_data]): sg.OneLineProgressMeter(_('Processing certificates'), i + 1, len(cache[path_data]), 'meter', _('Please wait...')) cert_data = certificate.generate_certificate(values['certificate_text'], cache[path].copy(), values['slider_x'], values['slider_y'], values['width'], int(values['slider_font']), int(values['slider_linespacing']), alignment, color, values['font'], x, False) with open(os.path.join(path_output, "{:04d}.pdf".format(i)), 'wb') as f: f.write(cert_data.read())
0fbaab0cffef60c4f63a84b7c6e11b76c9a0e095
[ "Markdown", "Python" ]
3
Markdown
ElectricityBoy/certificados
49ffcdb33adf5faf5eb833917bc019f73d294e4e
0185e1b8921870df4c730ec6bb4ee30d7772303f
refs/heads/master
<file_sep>package com.project.autoreg.repository; import com.project.autoreg.model.Regulador; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface ReguladorRepository extends JpaRepository <Regulador, Long> { Page<Regulador> findByCodeContainingAndRegionContainingAndFeederContainingAndBusContainingOrderByCodeDesc(String code, String region, String feeder, String bus, Pageable pageable); }<file_sep>package com.project.autoreg.security.jwt; import java.util.ArrayList; import java.util.List; import com.project.autoreg.model.User; import com.project.autoreg.security.enums.ProfileEnum; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; // Classe para converter nosso usuário em um usuário reconhecido pelo spring security// public class JwtUserFactory { private JwtUserFactory() { } // Método para criar um JwtUser com base nos dados do usuário // public static JwtUser create(User user) { return new JwtUser( user.getId(), user.getEmail(), user.getPassword(), mapToGrantedAuthorities(user.getProfile()) ); } // Método que converte o perfil do usuário para o formato utilizado no spring security // private static List<GrantedAuthority> mapToGrantedAuthorities(ProfileEnum profileEnum) { List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); authorities.add(new SimpleGrantedAuthority(profileEnum.toString())); return authorities ; } }<file_sep>package com.project.autoreg.controller; import java.util.Optional; import javax.servlet.http.HttpServletRequest; import com.project.autoreg.model.Regulador; import com.project.autoreg.response.Response; import com.project.autoreg.service.ReguladorService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DuplicateKeyException; import org.springframework.data.domain.Page; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.validation.ObjectError; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/reguladores") @CrossOrigin(origins = "*") public class ReguladorController { /* Injeção de dependencia do reguladorService */ @Autowired private ReguladorService reguladorService; /* Metodo para listar todos os reguladores*/ @GetMapping(value = "/{page}/{count}") public ResponseEntity<Response<Page<Regulador>>>listAll(HttpServletRequest request, @PathVariable int page, @PathVariable int count) { Response<Page<Regulador>> response = new Response<Page<Regulador>>(); Page<Regulador> regulador = null; regulador = reguladorService.listAll(page, count); response.setData(regulador); return ResponseEntity.ok(response); } /* Método para encontrar um regulador pelo seu id */ @GetMapping(value = "/{id}") public ResponseEntity<Response<Regulador>>findById(@PathVariable Long id) { Response<Regulador> response = new Response<Regulador>(); Regulador regulador = reguladorService.findById(id).get(); if(regulador == null) { response.getErrors().add("Regulador não encontrado"); return ResponseEntity.badRequest().body(response); } response.setData(regulador); return ResponseEntity.ok(response); } /* Metodo para filtrar um equipamento por algum parametro */ @GetMapping(value = "/{page}/{count}/{code}/{region}/{feeder}/{bus}") public ResponseEntity<Response<Page<Regulador>>>findByParameters(HttpServletRequest request, @PathVariable int page, @PathVariable int count, @PathVariable String code, @PathVariable String region, @PathVariable String feeder, @PathVariable String bus) { code = code.equals("uniformed")? "" : code; region = region.equals("uniformed")? "" : region; feeder = feeder.equals("uniformed")? "" : feeder; bus = bus.equals("uniformed")? "" : bus; Response<Page<Regulador>> response = new Response<Page<Regulador>>(); Page<Regulador> regulador = null; regulador = reguladorService.findByParameters(code, region, feeder, bus, page, count); response.setData(regulador); return ResponseEntity.ok(response); } /* Metodo para criar um novo equipamento */ @PostMapping() public ResponseEntity<Response<Regulador>> createRegulador(HttpServletRequest request, @RequestBody Regulador regulador, BindingResult result) { Response<Regulador> response = new Response<Regulador>(); try { validateCreateRegulador(regulador, result); if(result.hasErrors()) { result.getAllErrors().forEach(error -> response.getErrors().add(error.getDefaultMessage())); return ResponseEntity.badRequest().body(response); } Regulador reguladorPersisted = (Regulador) reguladorService.createRegulador(regulador); response.setData(reguladorPersisted); } catch(DuplicateKeyException duplicateKeyException) { response.getErrors().add("E-mail já registrado"); return ResponseEntity.badRequest().body(response); } catch (Exception exception) { response.getErrors().add(exception.getMessage()); return ResponseEntity.badRequest().body(response); } return ResponseEntity.ok(response); } private void validateCreateRegulador(Regulador regulador, BindingResult result) { if (regulador.getCode() == null) { result.addError(new ObjectError("Regulador", "Código do regulador não informado")); return; } } /* Método para deletar um regulador */ @DeleteMapping(value = "/{id}") public ResponseEntity<Response<Long>> deleteRegulador (@PathVariable Long id ) { Response<Long> response = new Response<Long>(); Optional<Regulador> reguladorOptional = reguladorService.findById(id); Regulador regulador = reguladorOptional.get(); if(regulador == null) { response.getErrors().add("Registro não encontrado"); return ResponseEntity.badRequest().body(response); } reguladorService.deleteRegulador(regulador); return ResponseEntity.ok(new Response<Long>()); } /* Método para editar os dados de um regulador */ @PutMapping(value = "/{id}") public ResponseEntity<Response<Regulador>> editRegulador (@PathVariable Long id, HttpServletRequest request, @RequestBody Regulador regulador, BindingResult result) { Response<Regulador> response = new Response<Regulador>(); try { validateUpdateRegulador(regulador, result); if(result.hasErrors()) { result.getAllErrors().forEach(error -> response.getErrors().add(error.getDefaultMessage())); return ResponseEntity.badRequest().body(response); } regulador.setCode(regulador.getCode()); regulador.setRegion(regulador.getRegion()); regulador.setFeeder(regulador.getFeeder()); regulador.setBus(regulador.getBus()); regulador.setModel(regulador.getModel()); regulador.setVoltage(regulador.getVoltage()); regulador.seteCurrent(regulador.geteCurrent()); regulador.setVoltage(regulador.getlVoltage()); regulador.setManufacturer(regulador.getManufacturer()); regulador.setYearManufacture(regulador.getYearManufacture()); regulador.setDateEnergization(regulador.getDateEnergization()); regulador.setLastInspetion(regulador.getLastInspetion()); regulador.setLastUpdate(regulador.getLastUpdate()); Regulador reguladorPersisted = (Regulador) reguladorService.createRegulador(regulador); response.setData(reguladorPersisted); } catch (Exception exception) { response.getErrors().add(exception.getMessage()); return ResponseEntity.badRequest().body(response); } return ResponseEntity.ok(response); } private void validateUpdateRegulador (Regulador regulador, BindingResult result) { if (regulador.getCode() == null) { result.addError(new ObjectError("Regulador", "Código não encontrado")); return; } if (regulador.getId() == null) { result.addError(new ObjectError("Regulador", "Id não encontrado")); return; } } }<file_sep> spring.jpa.hibernate.ddl-auto=update spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/autoreg spring.datasource.username=root spring.datasource.password=<PASSWORD> jwt.secret = autoreg_api jwt.expiration = 86400 <file_sep>package com.project.autoreg.service; import java.util.Optional; import com.project.autoreg.model.Regulador; import org.springframework.data.domain.Page; import org.springframework.stereotype.Component; @Component public interface ReguladorService { Page<Regulador> listAll(int page, int count); /* achará um lista (List) de regualdores */ Optional<Regulador> findById(Long id); /* achará um regulador pelo seu id*/ Regulador createRegulador(Regulador regulador); /* salvará um regulador no banco de dados */ void deleteRegulador(Regulador regulador); /*deletará um regulador do banco de dados */ Page<Regulador> findByParameters(String code, String region, String feeder, String bus, int page, int count); /* achará um regulador pelo código do equipamento */ /* teste List<Regulador> findAll2(); */ }<file_sep>package com.project.autoreg.service.serviceimpl; import java.util.Optional; import com.project.autoreg.model.User; import com.project.autoreg.repository.UserRepository; import com.project.autoreg.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; @Service public class UserServiceImpl implements UserService { @Autowired /* Ponto de injeção do repositório */ UserRepository userRepository; @Override public Optional<User> findById(Long id) { return userRepository.findById(id); } @Override public User createUser(User user) { return userRepository.save(user); } @Override public void deleteUser(User user) { this.userRepository.delete(user); } @Override public User findByEmail(String email) { return userRepository.findByEmail(email); } @Override public Page<User> listAll(int page, int count) { PageRequest pages = PageRequest.of(page, count); return this.userRepository.findAll(pages); } }<file_sep>package com.project.autoreg.controller; import java.util.Optional; import javax.servlet.http.HttpServletRequest; import com.project.autoreg.model.User; import com.project.autoreg.response.Response; import com.project.autoreg.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DuplicateKeyException; import org.springframework.data.domain.Page; import org.springframework.http.ResponseEntity; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.validation.BindingResult; import org.springframework.validation.ObjectError; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/usuarios") @CrossOrigin(origins = "*") public class UserController { /* Injeção de dependencia do userService */ @Autowired private UserService userService; /* Injeção de dependencia para encriptar as senhas */ @Autowired private PasswordEncoder passEnconder; /* Método para mostrar todos os usuários */ @GetMapping(value = "/{page}/{count}") public ResponseEntity<Response<Page<User>>> listAll(HttpServletRequest request, @PathVariable int page, @PathVariable int count) { Response<Page<User>> response = new Response<Page<User>>(); Page<User> user = null; user = userService.listAll(page, count); response.setData(user); return ResponseEntity.ok(response); } /* Método para encontrar um usuário pelo id */ @GetMapping(value="/{id}") public ResponseEntity<Response<User>>findById(@PathVariable Long id) { Response<User> response = new Response<User>(); User user = userService.findById(id).get(); if (user == null) { response.getErrors().add("Usuário não encontrado"); ResponseEntity.badRequest().body(response); } response.setData(user); return ResponseEntity.ok(response); } /* Método para deletar um usuário */ @DeleteMapping(value = "/{id}") public ResponseEntity<Response<Long>> deleteUser(@PathVariable Long id){ Response<Long> response = new Response<Long>(); Optional<User> userOptional = userService.findById(id); User user = userOptional.get(); if(user == null) { response.getErrors().add("Registro não encontrado"); return ResponseEntity.badRequest().body(response); } userService.deleteUser(user); return ResponseEntity.ok(new Response<Long>()); } /* Método para criar um novo usuário */ @PostMapping public ResponseEntity<Response<User>> createUser(HttpServletRequest request,@RequestBody User user, BindingResult result) { Response<User> response = new Response<User>(); try { validateCreateUser(user, result); if (result.hasErrors()) { result.getAllErrors().forEach(error -> response.getErrors().add(error.getDefaultMessage())); return ResponseEntity.badRequest().body(response); } user.setPassword(<PASSWORD>(user.<PASSWORD>())); User userPersisted = (User) userService.createUser(user); response.setData(userPersisted); } catch (DuplicateKeyException duplicateKeyException) { response.getErrors().add("E-mail já registrado"); return ResponseEntity.badRequest().body(response); } catch (Exception exception) { response.getErrors().add(exception.getMessage()); return ResponseEntity.badRequest().body(response); } return ResponseEntity.ok(response); } /* Método auxiliar para validar se o e-mail de cadastro está vazio */ private void validateCreateUser(User user, BindingResult result) { if(user.getEmail() == null) { result.addError(new ObjectError("User", "E-mail não informado")); return; } } /* Método para atualizar um novo usuário */ @PutMapping(value = "/{id}") public ResponseEntity<Response<User>> editUser (@PathVariable Long id, HttpServletRequest request, @RequestBody User user, BindingResult result) { Response<User> response = new Response<User>(); try { validateUpdateUser(user, result); if(result.hasErrors()) { result.getAllErrors().forEach(error -> response.getErrors().add(error.getDefaultMessage())); return ResponseEntity.badRequest().body(response); } user.setEmail(user.getEmail()); user.setPassword(<PASSWORD>.encode(user.getPassword())); user.setProfile(user.getProfile()); User userPersisted = (User) userService.createUser(user); response.setData(userPersisted); } catch (Exception exception) { response.getErrors().add(exception.getMessage()); return ResponseEntity.badRequest().body(response); } return ResponseEntity.ok(response); } /* Método auxiliar para validar se o e-mail de cadastro está vazio */ private void validateUpdateUser (User user, BindingResult result) { if (user.getId() == null) { result.addError(new ObjectError("user", "Id não encontrado")); return; } if (user.getEmail() == null) { result.addError(new ObjectError("user", "E-mail não encontrado")); return; } } }<file_sep>package com.project.autoreg.service; import java.util.Optional; import com.project.autoreg.model.User; import org.springframework.data.domain.Page; import org.springframework.stereotype.Component; @Component public interface UserService { Page<User> listAll(int page, int count); /* Método para lsitar todos os usuários cadastrados */ User findByEmail(String email); /* Método para procurar um usuário pelo email */ void deleteUser(User user); /* Método para deletar um usuário */ User createUser(User user); /* Método para salvar um novo usuário */ Optional<User> findById(Long id); /* Método para achar usuário pelo id */ }<file_sep># autoreg Projeto backend em spring para estudo
d7f51e4c9bcd1c13f665cd6b16de803a5f59e7bd
[ "Markdown", "Java", "INI" ]
9
Java
pessoadavi/autoreg-backend
2a518808c024154465f57a33585514c85893a43f
c12a152840fed0678ffdb6f213300037194c716d
refs/heads/master
<file_sep>--- title: "Get Started" permalink: docs/get_started.html toplevel: "Getting Started: Quick Guide" --- > Electrode Environment Setup Requirements: <br> > * Latest [Node LTS binary](https://nodejs.org/en/) (at least v4.2 required), tip: use [nvm](https://github.com/creationix/nvm) to manage your nodejs versions. > * [npm v3](https://github.com/npm/npm/releases/tag/v3.0.0) - Install the latest [npm](https://www.npmjs.com/) version `npm install -g npm` > please checkout [requirements docs](http://www.electrode.io/docs/requirements.html) for detailed setup instructions. #### Quick Guide Are you ready to build your first Electrode App? Please make sure to have all the [environment requirements](http://www.electrode.io/docs/requirements.html) ready & setup before proceeding to the next step. First, install [Yeoman](http://yeoman.io/) and the [Electrode Generator] ```bash $ npm install -g yo gulp generator-electrode ** NOTE: You may need sudo depending on your machine permissions. ** ``` Make a new directory for your awesome app, then generate your new project: ```bash $ mkdir your-awesome-app $ cd your-awesome-app $ yo electrode ``` Fill out the Electrode App generator with your information: ![generator-app](/img/generator-application.png) Run one simple command to start the server. Presto! ```bash $ gulp dev ``` Now open [localhost:3000](http://localhost:3000) in your browser to access the app. Hello Electrode! To view all the gulp tasks available type `gulp`. To build your app's client bundle for production use ```bash gulp build ``` followed by ```bash npm run prod ``` --- ##### Project Structure Let's take a quick high level overview of our file structure and what `generator-electrode` gives you out the box. Read through our [What's Inside section](whats_inside.html) for a more detailed description. - `src/client/` Contains your client side code and our favs, React, Redux + CSS modules. - `app.jsx` The entry point for the client. It contains powerful Electrode modules that we will leverage as we build out functionality. - `routes.jsx` The shared routes between client and server are defined here for use with react-router. - `components/` This is the folder for your React components. We love React and how it helps us to manage User Interface complexity. Read more in the Explore section. - `styles/` This is the folder for your CSS files. We will use CSS Modules: a CSS file in which all class names and animation names are scoped locally by default. - `src/server/` Contains your server-side code. Electrode-Server gives you a powerful plugin capable of SSR out the box. Learn more in the [What's Inside section](whats_inside.html). - `config/` Your environment specific configuration files go here and are managed by the versatile [electrode-confippet](confippet.html) module, including a preset config that you can customize and extend. - `node_modules/` Other Javascript files contained in modules that we will use in this application, including Electrode modules that create your out-the-box Universal app. This folder is managed directy by `npm`. - `.babelrc` Where we extend our app babel configuration to allow us to use the presets and any additional babel settings. - `.gitignore` A file that tell git what files (or patterns) to ignore when you commit. - `.ismorphic-loader-config.json` A webpack loader, plugin and library to make NodeJS `require` work with complex files like images when we are doing server-side rendering. - `.travis.yml` A file where you can customize any process in the Travis default build environment. - `gulpfile.js` A file that stores all your Gulp configurations. We will explore this more in [Getting Started: Intermediate](create_reusable_component.html). - `package.json` Contains the metadata for `your-awesome-app` and a list of your dependencies to install when running `npm install`. - `README.md` Info you want users to know about your app (installation instructions, licensing, contributors, etc.). --- Let's continue to build by modifying our component and deploying in [Quick Start: Build Component](build_component.html). [Electrode Generator]: https://github.com/electrode-io/electrode#yeoman-generator <file_sep>--- title: "Generate Docs" permalink: docs/generate_docs.html toplevel: "Getting Started: Intermediate" --- #### Generating documentation One of the final steps to creating a reusable component is writing the correct documentation, in the form of `component.json` and `component.md`. The Electrode team has automated this step for you, using [Electrode-Docgen]. This is a custom metadata extractor for the Electrode framework. The commands have been built into the tasks of `<your-awesome-component>/gulpfile.js`: ```javascript const tasks = { "demo": ["generate", "server-dev"], "demo-iso": ["dev-iso"], "generate": ["generate-metadata", "generate-documentation"], "generate-documentation": () => exec(`electrode-docgen --package ./package.json --src ./src --markdown components.md`), "generate-metadata": () => exec(`electrode-docgen --package ./package.json --src ./src --metadata components.json`), "prepublish": ["npm:prepublish"], "preversion": ["check-cov"] }; ``` Simply run the commands below to auto generate the necessary docs: To generate metadata: ```bash $ gulp generate-metadata ``` To generate documentation: ```bash $ gulp generate-documentation ``` Or, to run both simultaneously, you can just run: ```bash $ gulp generate ``` Now that we've run our tests and they've passed, let's publish our component on npm so we can use it again. You will need to [sign up] for an account if you don't have one, and follow the steps in the [npm documentation]. Let's continue to build more by creating our own [Hapi server plugin], incorporating routes and adding some awesome CSS modules. [Electrode-Docgen]: https://github.com/electrode-io/electrode-docgen [npm]: https://docs.npmjs.com/getting-started/publishing-npm-packages [sign up]: https://www.npmjs.com/signup [npm documentation]: https://docs.npmjs.com/getting-started/creating-node-modules [Hapi server plugin]: build_server_plugin.html <file_sep>var stickAtHeight = 2130; var toggleTools = 3000; $(window).bind('scroll', function () { if ($(window).scrollTop() > stickAtHeight) { $('#electrode-core-logo-li').removeClass('active-inner-link').addClass('inactive-inner-link'); $('#electrode-modules-logo-li').removeClass('inactive-inner-link').addClass('active-inner-link'); $('#second-nav').addClass('navbar-fixed-top'); } else { $('#electrode-tools-logo-li').removeClass('inactive-inner-link active-inner-link'); $('#electrode-modules-logo-li').removeClass('active-inner-link').addClass('inactive-inner-link'); $('#electrode-core-logo-li').removeClass('inactive-inner-link').addClass('active-inner-link') $('#second-nav').removeClass('navbar-fixed-top'); } }); $(window).bind('scroll', function () { if ($(window).scrollTop() > toggleTools) { $('#electrode-modules-logo-li').removeClass('active-inner-link').addClass('inactive-inner-link'); $('#electrode-tools-logo-li').removeClass('inactive-inner-link').addClass('active-inner-link'); } else { $('#electrode-tools-logo-li').removeClass('active-inner-link').addClass('inactive-inner-link'); $('#electrode-modules-logo-li').addClass('active-inner-link'); } }); <file_sep>## Module: [{{ include.moduleId }}](https://github.com/electrode-io/{{ include.moduleId }}) ### Install via `npm` ```bash $ npm install --save {{ include.moduleId }} ``` ### Example Applications * [Electrode Boilerplate](https://github.com/electrode-io/electrode-boilerplate-universal-react-node#{{ include.moduleId }}) {% if include.express == true %} * [Express Example with Standalone Modules](https://github.com/docs-code-examples-electrode-io/express-example-with-standalone-electrode-modules#{{ include.moduleId }}) {% endif %} {% if include.express_react_redux == true %} * [Express React Redux Webpack Example](https://github.com/docs-code-examples-electrode-io/express-react-redux-webpack#{{ include.moduleId }}) {% endif %} {% if include.hapi == true %} * [Hapi Example with Standalone Modules](https://github.com/docs-code-examples-electrode-io/hapijs-example-with-standalone-electrode-modules#{{ include.moduleId }}) {% endif %} {% if include.hapi_react_redux == true %} * [Hapi React Redux Example](https://github.com/docs-code-examples-electrode-io/hapi-react-redux#{{ include.moduleId }}) {% endif %} ## Usage <file_sep>--- title: "Stand Alone Modules" permalink: docs/stand_alone_modules.html toplevel: "Getting Started: Advanced" --- ###Leveraging Stand Alone Modules Our flexible modules are dedicated to optimizing performance in specific areas based on your application's needs. By "stand alone", we mean that these Electrode modules are agnostic of one another; use one or all of them in any Node platform to enhance your application's capabilities. Use our guides and examples below to plug them in: * [Confippet](confippet.html) is a versatile and flexible utility for managing configurations of Node.js applications. * [Above the Fold Rendering](above_fold_rendering.html) is a React component wrapper that allows expensive components to skip Server Side Rendering. * [Server Side Render Cache + Profiling](server_side_render_cache.html) is a module used to profile React Server Side Rendering performance and then cache expensive components to help you speed up SSR. * [Stateless CSRF Validation](stateless_csrf_validation.html) is a Hapi plugin or Express middleware that enables stateless CSRF protection in case your app does not depend on server side persistence. * [Electrode Redux Router Engine](redux_router_engine.html) is a Hapi plugin or Express middleware that handles async data for React Server Side Rendering using [react-router](https://github.com/ReactTraining/react-router), Redux and the [Redux Server Rendering](http://redux.js.org/docs/recipes/ServerRendering.html) pattern. ###Bringing It All Together in an Advanced Electrode App By following the steps in the Getting Started: Advanced, you will have a fully loaded Electrode Application. It will consist of a Universal React and Node core, optimized module and powerful tools that have solved some of our most challenging problems when it comes to Walmart's scale and market demands. Take a deeper look into our [Electrode Boilerplate](electrode_boilerplate.html) after you walk through our Stand Alone Modules and [Tools](electrode_tools.html). <file_sep>var dropDownMenuState= false, electrodeNav = document.getElementById("electrode-nav"), ernHeader = document.getElementById("ern-header"); function changeMobileNav(){ dropDownMenuState = !dropDownMenuState; if(dropDownMenuState){ if (electrodeNav) { document.getElementById("electrode-nav").style.backgroundColor = "#000e23"; } else { document.getElementById("ern-header").style.backgroundImage = "none"; } document.getElementById("electrode-mobile-nav").style.backgroundColor = "#000e23"; document.getElementById("mob-header-icon").setAttribute("src", "/img/mob-close.svg"); document.getElementById("walmart-header-logo").style.display = "none"; } else { if (electrodeNav) { document.getElementById("electrode-nav").style.backgroundColor = "#00294b"; } else { document.getElementById("ern-header").style.backgroundImage = "url('/img/mobile-page/ern_bkgd_nav.png')"; document.getElementById("electrode-mobile-nav").style.backgroundColor = "transparent"; } document.getElementById("mob-header-icon").setAttribute("src", "/img/mob-menu.svg"); document.getElementById("walmart-header-logo").style.display = "block"; } }; var windowWidth = window.innerWidth; function changeDesktopColor() { if (window.innerWidth > 767) { if (electrodeNav) { document.getElementById("electrode-nav").style.backgroundColor = "#00294b"; } else { document.getElementById("electrode-mobile-nav").style.backgroundColor = "transparent"; document.getElementById("ern-header").style.backgroundImage = "url('/img/mobile-page/ern_bkgd_nav.png')"; } document.getElementById("walmart-header-logo").style.display = "block"; } else { if (dropDownMenuState) { if (electrodeNav) { document.getElementById("electrode-nav").style.backgroundColor = "#000e23"; } else { document.getElementById("ern-header").style.backgroundImage = "url('/img/mobile-page/ern_bkgd_nav.png')"; document.getElementById("electrode-mobile-nav").style.backgroundColor = "#000e23"; } document.getElementById("walmart-header-logo").style.display = "none"; } } } window.addEventListener("resize", changeDesktopColor); <file_sep>"use strict"; function GitRepos() { } GitRepos.prototype.getRepos = function() { var electrodeReposUrl = "https://api.github.com/orgs/electrode-io/repos"; return $.ajax({ url: electrodeReposUrl, method: "GET" }); }; GitRepos.prototype.getIssuesApi = function(repo) { var numberId = "{/number}"; return repo.issues_url.replace(numberId, ""); }; GitRepos.prototype.getIssuesUrl = function(repo) { var api = "api."; return repo.issues_url.replace(api, ""); }; <file_sep>--- title: "Glossary" permalink: docs/glossary.html toplevel: "Resources" --- <br /> * **Archetypes** - Archetypes are encapsulated boilerplates for centralizing your project configurations, workflows and dependencies. An archetype is an npm module template, which is a “superclass” of a module, think inheritance for npm modules but not one that is used to generate code files and then discarded. * **Caching** - is a process of storing data locally in order to speed up subsequent retrievals. * **Child component** - is any component that is contained in a parent component. * **Container based technology** - is an approach to virtualization in which the virtualization layer runs as an application within the operating system (OS). In this approach, the operating system's kernel runs on the hardware node with several isolated guest virtual machines (VMs) installed on top of it. The isolated guests are called containers. * **Cross Site Request Forgery (CSRF)** - is an attack that forces an end user to execute unwanted actions on a web application in which they're currently authenticated. CSRF attacks specifically target state-changing requests, not theft of data, since the attacker has no way to see the response to the forged request. * **Hashing** - is the transformation of a string of characters into a usually shorter fixed-length value or key that represents the original string. * **Linting** - is the process of running a program that will analyze code for potential errors. * **Local scope** - is a CSS Modules feature that keeps classes local to the specified file, and does not pollute the global namespace. * **Markup** - a notation used to annotate a document's content to give information regarding the structure of the text or instructions for how it is to be displayed. * **Metadata extractor** - is a type of tooling that retrieves meta data information from various packages. * **Module tree** - is a directory tree like structure of all the package dependencies of a particular npm/node module. * **Multi instance** - is a type of architecture where multiple customers run their own separate instance of an application and operating system running on a separate virtual machine, all on a common hardware platform. * **Platform agnostic** - is software was runs on any combination of operating system and underlying processor architecture. * **Predictable state container** - is an object that stores the state of the entire app where the only way to change the state tree is to emit an action. Also known as Redux. * **Profiling** - is a form of dynamic program analysis that measures, for example, the space (memory) or time complexity of a program, the usage of particular instructions, or the frequency and duration of function calls. * **Promise** - is an object used for asynchronous computations It represents a value that may be available now, in the future or never. * **React Data Id** - is a custom attribute used so that React can uniquely identify its components within the Document Object Model(DOM). * **Rendering Engine** - is a program that renders marked up content. * **Route Handler** - is a method or function that is executed when a certain route was requested. It usually handles the request and returns the necessary HTML to the client. * **Routing** - is the process of selecting the best paths in a network. * **Scaffolding tool** - is a tool used to generate a set of files, folders and configurations that follow the most common best practices to start a new project or component. * **Server Side Rendering** - a process where the initial request loads the page, layout, CSS, JavaScript and content. For subsequent updates to the page, the client-side rendering approach repeats the steps it used to get the initial content. * **Stub** - is a piece of code used to stand in for some other programming functionality. * **Transform** - to change in composition or structure. * **Transpile** - is a type of compilation process that takes the source code of a program written in one programming language as its input and produces the equivalent source code in another programming language. <file_sep>--- title: "Community" permalink: docs/community.html toplevel: "Contributing" --- ### Connecting with Electrode We look forward to the open source community engaging with us: Please use the following forums to report any questions, feature requests and issues about electrode: ##### 1. [Github Issues](https://github.com/electrode-io/electrode/issues) ##### 2. [Gitter](https://gitter.im/electrode-io/electrode) Also follow us on [Twitter](https://twitter.com/electrode_io) for news and updates about the project <file_sep>--- title: "Bundle Analyzer" permalink: docs/bundle_analyzer.html toplevel: "Stand Alone Modules" --- A [webpack](https://webpack.github.io) bundle analyzer that gives you a detail list of all the files that went into your deduped and minified bundle JS file. ## Installation ## Bundle Analyzer lives on [npm](https://www.npmjs.com/package/electrode-bundle-), so if you haven't already, make sure you have [node](http://nodejs.org/) installed on your machine first. Installing should then be as easy as: ``` bash $ sudo npm install -g electrode-bundle-analyzer ``` {% include module_usage.md moduleId="electrode-bundle-analyzer" %} Bundle Analyzer expects a particular set of data for it to work. Bundle Analyzer looks for the webpack module ID comment that normally looks something like this: ```js /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { ``` You can find more information about it in the Bundle Analyzer [readme](https://github.com/electrode-io/electrode-bundle-analyzer#generating-the-necessary-data) file. ## Command-Line Interface ## ``` bash Usage: analyze-bundle --bundle [bundle.js] --stats [stats.json] --dir [output_dir] --rewrite Options: -b, --bundle JS bundle file from webpack [required] -s, --stats stats JSON file from webpack[default: "dist/server/stats.json"] -r, --rewrite rewrite the bundle file with module ID comments removed -d, --dir directory to write the analyze results [default: ".etmp"] -h, --help Show help [boolean] ``` When you install Bundle Analyzer globally, `analyze-bundle` command-line tool is made available as the quickest means of checking out your bundle. If you don't specify an output directory, a default one `.etmp` will be created and a `.gitignore` file is also added there to avoid git picking it up. Two files will be written to the output directory: - `bundle.analyze.json` - `bundle.analyze.tsv` The `tsv` file is a Tab Separated Values text file that you can easily import into a spreadsheet for viewing. For example: ``` Module ID Full Path Identity Path Size (bytes) 0 ./client/app.jsx ./client/app.jsx 328 1 ./~/react/react.js ~/react/react.js 46 2 ./~/react/lib/React.js ~/react/lib/React.js 477 3 ./~/object-assign/index.js ~/object-assign/index.js 984 4 ./~/react/lib/ReactChildren.js ~/react/lib/ReactChildren.js 1344 ``` You can view an example [`bundle.analyze.tsv`](https://docs.google.com/spreadsheets/d/1IomT2fYCKEwVY0CO-0jImc7CBj_uAmgy70Egsm4CnVE/edit?usp=sharing&rm=minimal) output using the [Electrode Boilerplate](https://github.com/electrode-io/electrode/tree/d4142ee0c938cbf973a429ee8467052aa4e1c9be/samples/universal-react-node#electrode-bundle-analyzer) code. <file_sep>--- title: "More Deployments" permalink: docs/more_deployments.html toplevel: "Getting Started: Intermediate" --- Deploying in an efficient, organized and seamless way is the key to success. A wise man once said, ["Your deploys should be as boring, straightforward, and stress-free as possible"]. We have assembled a few more best-in-class software deployment options with tutorials in this section: * [Docker], a new container based technology that is designed to make applications easier to [create, deploy and run]. * [Google Kubernetes], "an open-source system for automating deployment, scaling, and management of [containerized applications]." ["Your deploys should be as boring, straightforward, and stress-free as possible"]: https://zachholman.com/posts/deploying-software [Docker]: docker.html [create, deploy and run]: https://cloud.docker.com [Google Kubernetes]: kubernetes.html [containerized applications]: http://kubernetes.io/ <file_sep>--- title: "Stateless CSRF Validation" permalink: docs/stateless_csrf_validation.html toplevel: "Stand Alone Modules" --- The [electrode-csrf-jwt](https://github.com/electrode-io/electrode-csrf-jwt) plugin enables stateless CSRF protection using [JWT](https://github.com/auth0/node-jsonwebtoken) in Electrode, Express, or Hapi applications. ### Why do we need this module? Protection against [CSRF](https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)) is a very important security feature. Traditional anti-CSRF techniques use tokens issued by the server that the client has to post back. The server validates the request by comparing the token with its own, stored copy. But what if your application does not rely on server-side session persistence? Protecting users against CSRF attacks when your application does not use back-end sessions can be tricky. The Stateless CSRF JWT Validation module addresses this need. This module is a stand-alone module and can be configured to work in any [Electrode](#electrode), [Express](#express), or [Hapi](#hapi) application. #### How do we validate requests? ***Double JWT CSRF tokens*** This Stateless CSRF Validation module is able to validate the authenticity of the client's request by relying on the fact that cross-site requests cannot set headers. Using two JWT CSRF tokens takes advantage of this. Both tokens are generated on the server side with the same payload but different types: one for the HTTP header, one for the cookie. Note that when a client makes a request, the JWT token must be sent in the headers. ```js headerPayload = { type: "header", UUID: "12345" }; cookiePayload = { type: "cookie", UUID: "12345" }; ``` Once *both* tokens are received by the server, they are decoded and validated to make sure the payloads match. The disadvantage is that this method relies on the client making all requests through AJAX. {% include module_usage.md moduleId="electrode-csrf-jwt" express=true hapi=true %} ### Configuration This module can be configured to work in any [Electrode](#electrode), [Express](#express), or [Hapi](#hapi) application. Whichever platform you are using, an `options` property with a secret key is required: >**options** >* `secret`: **Required**. A string or buffer containing either the secret for HMAC algorithms, or the PEM encoded private key for RSA and ECDSA. Other config properties are optional and follow the [same usage as jsonwebtoken](https://github.com/auth0/node-jsonwebtoken/blob/master/README.md#usage) * `algorithm` * `expiresIn` * `notBefore` * `audience` * `subject` * `issuer` * `jwtid` * `subject` * `noTimestamp` * `headers` ### Electrode All server configurations in [Electrode apps](http://www.electrode.io/docs/what_is_electrode.html) are handled by the versatile [confippet](http://www.electrode.io/docs/confippet.html) module. The Stateless CSRF JWT Validation module can be easily configured by adding the following property to `config/default.json`: ```json { "plugins": { "electrode-csrf-jwt": { "options": { "secret": "shhhhh", "expiresIn": 60 } } } } ``` ### Express #### Example `app.js` configuration ```js const csrfMiddleware = require("electrode-csrf-jwt").expressMiddleware; const express = require("express"); const app = express(); const options = { secret: "shhhhh", expiresIn: 60 }; app.use(csrfMiddleware(options)); ``` ### Hapi #### Example `server/index.js` configuration ```js const csrfPlugin = require("electrode-csrf-jwt").register; const Hapi = require("hapi"); const server = new Hapi.Server(); const options = { secret: "shhhhh", expiresIn: 60 }; server.register({register: csrfPlugin, options}, (err) => { if (err) { throw err; } }); ``` ### Usage Example With the configuration shown above, your app is now ready to use Stateless CSRF JWT Validation. At this point, server endpoints do not require any additional configuration for protection to be enabled. Your `GET` endpoints will automatically return a CSRF cookie *and* header, and your `POST` endpoints will require the same. Let's see a simple [example](https://github.com/electrode-io/electrode/blob/d4142ee0c938cbf973a429ee8467052aa4e1c9be/samples/universal-react-node/README.md#electrode-csrf-jwt) to show how the CSRF tokens are automatically configured: **Server Endpoint Setup** ```js server.route({ method: "GET", path: "/1", handler: (req, reply) => reply("valid") }); server.route({ method: "POST", path: "/2", handler: (req, reply) => reply("valid") }); ``` Here we set up two simple endpoints: - a `GET` endpoint, `/1`, to which the module automatically adds a csrf token header - a `POST` endpoint, `/2`, to which the module ensures the presence of a valid token in the request headers Let's see how to access them from the client: **Client AJAX Setup** ```js //A simple post Fn that now requires a csrf token to be passed in the header function doPost(csrfToken) { fetch("/2", { credentials: "same-origin", method: "POST", headers: { "Accept": "application/json", "Content-Type": "application/json", "x-csrf-jwt": csrfToken }, body: JSON.stringify({message: "hello"}) }) .then((resp) => console.log(resp) } function doGet() { fetch("/1", {credentials: "same-origin"}) .then((resp) => { if (resp.status === "200") { const token = resp.headers.get("x-csrf-jwt"); if (token !== "") { console.log("Got CSRF token OK"); doPost(token); } } }) } ``` In this example a `POST` request to `/2` can be made using the token retrieved from the `/1` endpoint. You can checkout our [Electrode Boilerplate React Application](https://github.com/electrode-io/electrode#boilerplate-universal-react-node) for a more detailed example <file_sep>--- title: "Build with material-ui" permalink: docs/build_with_material_ui.html toplevel: "Getting Started: Intermediate" --- [material-ui] is a set of React components that implement Google's material design. It's a great choice to help you quickly develop your web app with a sophisticated look and feel UI that is designed to be responsive. It's very simple to add material-ui components to an Electrode app. We've built a sample with step-by-step instructions to show you how. ![screenshot][screenshot] ## Installation ### Prerequisites Make sure you have installed NodeJS >= 4.x and npm >= 3.x, and [gulp]. ```bash $ node -v v6.6.0 $ npm -v 3.10.3 $ npm install -g gulp ``` ### Check it out To try out this ready made sample app, use git to clone the repo: ```sh $ git clone https://github.com/electrode-io/electrode.git $ cd electrode/samples/universal-material-ui $ npm install $ gulp dev ``` Now navigate your browser to `http://localhost:3000` to see the sample app with material-ui components. ## About This app was created with the following steps. ### Generate an Electrode App The first part of the process is to generate an Electrode Universal App using the [Yeoman] generator. Follow the steps below: 1. First, generate the Electrode Universal App with the following commands: ```bash $ npm install -g yo generator-electrode $ mkdir react-sample-material-ui $ cd react-sample-material-ui $ yo electrode # ... answer questions and wait for app to be generated and npm install completed ... ``` 2. Run `gulp dev` in the newly generated app 3. Navigate to `http://localhost:3000` to make sure the app is working. ### Add material-ui The second part of the process is to add material-ui dependencies. Follow the steps below: 1. Stop the app and install material-ui dependencies ```bash $ npm install material-ui react-tap-event-plugin --save ``` 1. Restart `gulp dev` and reload browser to make sure things are still working. 1. Add material-ui's required font, *Roboto*, to `server/plugins/webapp/index.html` 1. Update `client/styles/base.css` with styles for material-ui. 1. Test your material-ui component by adding a [RaisedButton] to `client/components/home.jsx` 1. Watch [webpack-dev-server] update your bundle and refresh your browser to see the changes. 1. Add `global.navigator.userAgent` to `server/index.js`, as required by material-ui for [Server Rendering]. 1. Watch [webpack-dev-server] update your bundle and refresh your browser to see the changes. ### Add material-ui Examples Now we are ready to add some of the [material-ui examples] to the app. #### Enable tapping First we have to add the resolution for an [issue in material-ui]. Add the following code to `client/app.jsx` ```js import injectTapEventPlugin from "react-tap-event-plugin"; window.webappStart = () => { injectTapEventPlugin(); // https://github.com/callemall/material-ui/issues/4670 }; ``` #### IconMenu AppBar example First add the IconMenu [AppBar example] by following the steps below. 1. Copy the source from the example into `client/components/AppBarExampleIconMenu.jsx` 2. Replace the `Hello Electrode` and the RaisedButton content in `client/components/home.jsx` with `<AppBarExampleIconMenu />`; 3. Watch [webpack-dev-server] update your bundle and refresh your browser to see the changes. 4. If the AppBar shows up, click on the right menu button. You should see a menu pop up. #### BottomNavigation example Next, add the [BottomNavigation example]: 1. Copy the source from the example into `client/components/BottomNavigationExampleSimple.jsx` 2. Import the component in `client/components/home.jsx` and add it to `render` after the `AppBarExampleIconMenu` component. 3. Watch [webpack-dev-server] update your bundle and refresh your browser to see the changes. 4. You should see AppBar and BottomNavigation show up. You should be able to interact with the buttons on the BottomNavigation component. #### Card example In this section we add the [Card example]. 1. Copy the source from the Card example into `client/components/CardExampleWithAvatar.jsx` 2. Import the component in `client/components/home.jsx` and add it to `render` after the `AppBarExampleIconMenu` component. 3. Watch [webpack-dev-server] update your bundle and refresh your browser to see the changes. 4. You should see Card show up, but with broken images. > You can replace the image URLs with full URLs by adding > `http://www.material-ui.com/` to them to fix the broken images, but we will > explore isomorphic images next. #### Isomorphic Images Electrode core comes with isomorphic images support built in using [isomorphic-loader]. In this section we explore using that feature to load the images for the [Card example]. 1. Create a directory called `client/images` and copy the following images there: - `http://www.material-ui.com/images/nature-600-337.jpg` - `http://www.material-ui.com/images/jsa-128.jpg` (Or your own favorite 128x128 Avatar image) - In my sample, I use `jchip-128.jpg` as my avatar. 1. In `client/components/CardExampleWithAvatar.jsx`, import the images: ```javascript import natureJpg from "../images/nature-600-337.jpg"; import avatarJpg from "../images/jsa-128.jpg"; ``` 1. Replace the URLs for `avatar` and `CarMedia` as follows: ``` ... avatar={avatarJpg} ... src={natureJpg} ``` 1. In `server/index.js`, activate [isomorphic-loader]'s `extend-require` by changing the last line to: ```javascript supports.isomorphicExtendRequire().then(() => { require("electrode-server")(config, [staticPathsDecor()]); }); ``` 1. Watch [webpack-dev-server] update your bundle and refresh your browser to see the changes. > Note that you will see the message `Warning: Unknown prop onTouchTap on > <button> tag.` show up on the server side rendering because of the tapping > event plugin, which we don't need on the server. [material-ui]: http://www.material-ui.com/ [RaisedButton]: http://www.material-ui.com/#/components/raised-button [webpack-dev-server]: https://webpack.github.io/docs/webpack-dev-server.html [Server Rendering]: http://www.material-ui.com/#/get-started/server-rendering [gulp]: http://gulpjs.com/ [material-ui examples]: http://www.material-ui.com/#/components/app-bar [AppBar example]: http://www.material-ui.com/#/components/app-bar [BottomNavigation example]: http://www.material-ui.com/#/components/bottom-navigation [yeoman]: http://yeoman.io/ [Card example]: http://www.material-ui.com/#/components/card [isomorphic-loader]: https://github.com/electrode-io/isomorphic-loader [screenshot]: https://cloud.githubusercontent.com/assets/5876741/19024379/377359ec-88b7-11e6-863b-a41133cc42ef.png [issue in material-ui]: https://github.com/callemall/material-ui/issues/4670 <file_sep>--- title: "Deploy Your App" permalink: docs/deploy_app.html toplevel: "Getting Started: Quick Guide" --- We're almost finished with our Quick Start. The final step is to deploy `your-awesome-app` and share it with your fellow developers using [Heroku](https://devcenter.heroku.com/categories/deployment). We have listed the steps below, but feel free to learn more about Heroku [here](https://devcenter.heroku.com/articles/getting-started-with-nodejs#introduction). These instructions assume you have a GitHub account. Navigate to your GitHub and create a new empty repo 'Your-Awesome-App'. Hit the `clone your-awesome-repo` and follow the steps below in order: ```bash $ git init $ git add . $ git commit -m 'first commit' $ git remote add origin https://github.com/your-Github-name/your-awesome-app.git $ git push -u origin master ``` Navigate to the [Heroku site](https://signup.heroku.com/dc) and set up a free account. This will help streamline our deployment process (we will do this several times). Next, let's quickly deploy `your-awesome-app` from the command line. [Click here](https://devcenter.heroku.com/articles/getting-started-with-nodejs#set-up") to download and install the Heroku CLI for your machine. When you are finished installing, log in using the email address and password you used when creating your Heroku account. ```bash $ heroku login ``` Enter your Heroku credentials: ```bash Email: <EMAIL> Password: ``` You should see a terminal message `Logged in as <EMAIL>`. Now, let's deploy! You'll need to specify the [version of node](https://devcenter.heroku.com/articles/node-best-practices) and npm you are using on your machine into our `package.json`. Add the code below to your `package.json`. Make sure to change `"node": "4.2.x"`, and `"npm": 3.10.x` to your actual node and npm version. To find out what versions you have, run `node -v` and `npm -v` in the command line ```json "engines": { "node": "4.2.x", "npm": "3.10.x" } ``` It should now look similar to this: ```json { "name": "your-awesome-app", "version": "0.0.1", "description": "your-app-description", "homepage": "your-awesome-app", "author": { "name": "your-name", "email": "<EMAIL>", "url": "your-app-url" }, "engines": { "node": "^4.x.x || ^6.x.x", "npm": ">= 3.x.x" }, "contributors": [], "files": [ "server", "client", "test" ], "main": "server/index.js", "keywords": [], "repository": { "type": "git", "url": "your-repo-url" }, "license": "Apache-2.0", "scripts": { "start": "if test \"$NODE_ENV\" = \"production\"; then npm run prod; else gulp dev; fi", "test": "gulp test", "coverage": "gulp check", "prod": "echo 'Starting standalone server in PROD mode'; node .", "heroku-postbuild": "gulp build" }, "dependencies": { "bluebird": "^3.4.6", "electrode-archetype-react-app": "^1.0.0", "electrode-confippet": "^1.0.0", "electrode-redux-router-engine": "^1.2.2", "electrode-server": "^1.0.0", "electrode-static-paths": "^1.0.0", "lodash": "^4.10.1" }, "devDependencies": { "electrode-archetype-react-app-dev": "^1.0.0", "gulp": "^3.9.1" } } ``` Use the following commands to commit your changes: ```bash $ git add . $ git commit -m "Updates package.json with node version" ``` Create an app on Heroku (which prepares Heroku to receive your source code). This will also create a git remote called `heroku` and generate a random name: ```bash $ heroku create ``` Alternatively, you can also create an app that will generate a your app's name (if it is available): ```bash $ heroku create your-awesome-app ``` Use the command below to set a configuration so that Heroku installs Your-Awesome-App's devDependencies: ```bash $ heroku config:set NPM_CONFIG_PRODUCTION=false ``` Use the command below to set a configuration for [production.js](https://github.com/electrode-io/electrode/blob/148a4f4a2e8d78443eb3bdc1cf62f4d74bf49755/packages/generator-electrode/generators/app/templates/config/production.js#L11), only set this if you intend to serve static files with a CDN. ```bash $ heroku config:set STATIC_FILES_OFF=true ``` Now deploy your code: ```bash $ git push heroku master ``` Visit the app at the generated URL by using this command: ```bash $ heroku open ``` And...you did it! [Click here](https://first-electrode-example-app.herokuapp.com) for our deployed Heroku version. We will build even more in our [Getting Started: Intermediate](create_reusable_component.html) and cover complex topics like routing, server plugins and other powerful deployment software. <file_sep>--- title: "Confippet" permalink: docs/confippet.html toplevel: "Stand Alone Modules" --- <!-- define reference links --> [confippet]: https://github.com/electrode-io/electrode-confippet [node-config npm module]: https://github.com/lorenwest/node-config [node-config files]: https://github.com/lorenwest/node-config/wiki/Configuration-Files [store]: https://github.com/electrode-io/electrode-confippet/blob/master/store.md [composeConfig]: https://github.com/electrode-io/electrode-confippet/blob/master/compose.md [processConfig]: https://github.com/electrode-io/electrode-confippet/blob/master/templates.md [default compose options]: https://github.com/electrode-io/electrode-confippet/blob/master/lib/default-compose-opts.js [Confippet] is a versatile, flexible utility for managing configurations of Node.js applications. It's simple to get started and can be customized and extended to meet the needs of your app. [Confippet] can be used as a standalone module in your favorite Node.js web server framework or application. ### Features * **Simple** - Confippet's `presetConfig` automatically composes a single config object from multiple files. For most applications, no further customization isnecessary. * **Flexible** - Supports JSON, YAML, and JavaScript config files. * **Powerful** - Handles complex multi-instance enterprise deployments. * **Platform Agnostic** - This module is platform agnostic and can be plugged into any Node.js application, including those run on Electrode, Express.js and Hapi.js {% include module_usage.md moduleId="electrode-confippet" express=true hapi=true %} * [Getting Started](#getting-started) * [Config Composition](#config-composition) * [Environment Variables](#environment-variables) * [Using Templates](#using-templates) * [Usage in Node Modules](#usage-in-node-modules) * [Customization](#customization) ### Getting Started Confippet can be integrated seamlessly into any existing [Express](#express-setup), [Hapi](#hapi-setup) or [Electrode](#electrode-setup) application. For example, let's say that in our application we need to access a database that is running locally in our development environment but is running on a specific hostname in our production environment. We would like to be able to get the correct hostname in our code based on the current environment. Confippet can help us with this. Follow the setup instructions for this example depending on your app's framework: * [Electrode](#electrode-setup) * [Express](#express-setup) * [Hapi](#hapi-setup) #### ***Electrode Setup*** Electrode applications that were generated using `yo electrode` have already been bootstrapped with the necessary config files to set up [Confippet]. Let's take a look at the following files: ``` config |_ default.json |_ development.json |_ production.json ``` First, let's update the default settings for our database connection by adding the following setting to `default.json`: ```json { "settings": { "db": { "host": "localhost", "port": 5432, "database": "clients" } } } ``` Then we will set up the development and production environments. ##### ***Development Environment*** We want our database to be served from different hostnames depending on the environment. So let's update `development.json` to include the following settings: ```json { "server": { "connections": { "compression": false }, "debug": { "log": ["error"], "request": ["error"] } }, "connections": { "default": { "port": 3000 } }, "settings": { "db": { "host": "dev-db-server" } } } ``` Now, while `NODE_ENV=development` : - Server log errors that may be beneficial for debugging will now be shown with content encoding *disabled* - The server is being run in port 3000 - The database is hosted from dev-db-server ##### ***Production Environment*** Similarly, update `production.json` to include the following settings: ```json { "server": { "connections": { "compression": true }, "debug": { "log": false, "request": false } }, "connections": { "default": { "port": 8000 } }, "settings": { "db": { "host": "prod-db-server" } } } ``` Now, while `NODE_ENV=production` : - Server log errors are *disabled* and content encoding is *enabled* - Server is run in port 8000 - The database will be hosted from prod-db-server Additionally, here are some notes about the settings you just copied: - The server related configs are from hapi.js. More config options can be found here: http://hapijs.com/api - The connections property is specific to [electrode server](https://github.com/electrode-io/electrode-server/tree/master/lib/config) - Any settings that exist in the `config/default.json` that are *also* in the other environment configs will be replaced by the environment specific versions ##### ***Electrode Configuration*** Last step! Let's set up our Electrode application to use the new database settings by adding the following line to `server/index.js`: ``` const db = config.$("settings.db"); ``` #### ***Express Setup*** Confippet requires a config directory to pull settings from: ``` mkdir config cd config ``` Let's add the following files to the `config` directory: ``` config |_ default.json |_ development.json |_ production.json ``` Then update `default.json` to include the following settings: ```json { "server": { "viewCache": false, "xPoweredBy": true, "port": 4000 }, "settings": { "db": { "host": "localhost", "port": 5432, "database": "clients" } } } ``` Now we can set up the development and production specific settings. ##### ***Development Environment*** Update `config/development.json` to have the following settings: ```json { "server": { "viewCache": false, "xPoweredBy": true, "port": 4000 }, "settings": { "db": { "host": "dev-db-server" } } } ``` Now, while `NODE_ENV=development`: - the view cache is *disabled* - the x-powered-by header is *enabled* - the server is run in port 4000 - the databse is hosted from dev-db-server ##### ***Production Environment*** Update `config/production.json` to have the following settings: ```json { "server": { "viewCache": true, "xPoweredBy": false, "port": 8000 }, "settings": { "db": { "host": "prod-db-server" } } } ``` Now, while `NODE_ENV=production` : - the view cache is *enabled* - the x-powered-by header is *disabled* - the server is run in port 8000 - the database is hosted from prod-db-server ##### ***Express Configuration*** To require the confippet settings, simply add the following to `app.js`: ``` const {config} = require("electrode-confippet"); const db = config.$("settings.db"); app.set("view cache", config.server.viewCache); app.set("x-powered-by", config.server.xPoweredBy); app.listen(config.server.port); ``` #### ***Hapi Setup*** Confippet requires a config directory to pull settings from: ``` mkdir config cd config ``` Let's add the following files to the `config` directory: ``` config |_ default.json |_ development.json |_ production.json ``` Then update `default.json` to include the following settings: ```json { "connection": { "port": 3000 }, "settings": { "db": { "host": "localhost", "port": 5432, "database": "clients" } } } ``` Now we can set up the development and production specific settings. ##### ***Development Environment*** Update `config/development.json` to have the following settings: ```json { "connection": { "port": 4000 }, "settings": { "db": { "host": "dev-db-server" } } } ``` Now, while `NODE_ENV=development` : - The above settings run the server in port 4000 - The database is hosted from dev-db-server ##### ***Production Environment*** Update the `config/production.json` to have the following settings: ```json { "connection": { "port": 8000 }, "settings": { "db": { "host": "prod-db-server" } } } ``` Now, while `NODE_ENV=production`: - The above settings run the server in port 8000 - The database is hosted from prod-db-server ##### ***Hapi Configuration*** To require the confippet settings, simply add the following to `app.js`: ``` const {config} = require("electrode-confippet"); const db = config.$("settings.db"); ``` ### Config Composition Confippet's `presetConfig` composes together files in the `config/` directory, in the following order: 1. `default.EXT` 1. `default-{instance}.EXT` 1. `{deployment}.EXT` 1. `{deployment}-{instance}.EXT` 1. `{short_hostname}.EXT` 1. `{short_hostname}-{instance}.EXT` 1. `{short_hostname}-{deployment}.EXT` 1. `{short_hostname}-{deployment}-{instance}.EXT` 1. `{full_hostname}.EXT` 1. `{full_hostname}-{instance}.EXT` 1. `{full_hostname}-{deployment}.EXT` 1. `{full_hostname}-{deployment}-{instance}.EXT` 1. `local.EXT` 1. `local-{instance}.EXT` 1. `local-{deployment}.EXT` 1. `local-{deployment}-{instance}.EXT` Where: * `EXT` can be any of `["json", "yaml", "js"]`. Confippet will load all of them, in that order. Each time it finds a config file, the values in that file will be loaded and merged into the config store. So `js` overrides `yaml`, which overrides `json`. You can add handlers for other file types and change their loading order—see [composeConfig] for further details. * `{instance}` is your app's instance string in multi-instance deployments (specified by the `NODE_APP_INSTANCE` environment variable). * `{short_hostname}` is your server name up to the first dot. * `{full_hostname}` is your whole server name. * `{deployment}` is your deployment environment (specified by the `NODE_ENV` environment variable). Overridden values are handled as follows: * Objects are merged. * Primitive values (string, boolean, number) are replaced. * **Arrays are replaced**, unless the key starts with `+` *and* both the source and the target are arrays. In that case, the two arrays are joined together using Lodash's `_.union` method. After Confippet loads all available configuration files, it will look for override JSON strings from the `NODE_CONFIG` and `CONFIPPET*` environment variables. See the next section for details. ### Environment Variables Confippet reads the following environment variables when composing a config store: * `AUTO_LOAD_CONFIG_OFF` - If this is set, then Confippet will **not** automatically load any configuration into the preset `config` store. `Confippet.config` will be an empty store. This enables you to customize the config structure before loading. * `NODE_CONFIG_DIR` - Set the directory to search for config files. By default, Confippet looks in the `config` directory for config files. * `NODE_ENV` - By default, Confippet loads `development` config files after loading `default`. Set this environment variable to change to a different deployment, such as `production`. * `NODE_APP_INSTANCE` - If your app is deployed to multiple instances, you can set this to load instance-specific configurations. * `AUTO_LOAD_CONFIG_PROCESS_OFF` - By default, after composing the config from all sources, Confippet will use [processConfig] to process [templates](#using-templates). You can set this environment variable to disable template processing. * `NODE_CONFIG` - You can set this to a valid JSON string and Confippet will parse it to override the configuration. * `CONFIPPET*` - Any environment variables that starts with `CONFIPPET` will be parsed as JSON strings to override the configuration. ### Using Templates Values in your config files can be templates, which will be resolved with a preset context. See [processConfig] for more information about how to use config value templates. ### Usage in Node Modules If you have a Node.js module that has its own configurations based on environment variables, like `NODE_ENV`, you can use Confippet to load config files for your module. The example below will use the [default compose options] to compose configurations from the directory `config` under the script's directory (`__dirname`). ```javascript const Confippet = require("electrode-confippet"); const options = { dirs: [Path.join(__dirname, "config")], warnMissing: false, context: { deployment: process.env.NODE_ENV } }; const defaults = Confippet.store(); defaults._$.compose(options); ``` ### Customization The [composeConfig] feature supports a fully customizable and extendable config structure. Even Confippet's own preset config structure can be extended, since it's composed using the same feature. If you want to use the preset config, but add an extension handler or insert a source, you can turn off auto loading, and load it yourself with your own options. > **NOTE:** This has to happen before any other file accesses > `Confippet.config`. You should do this in your startup `index.js` file. For example: ```javascript process.env.AUTO_LOAD_CONFIG_OFF = true; const JSON5 = require("json5"); const fs = require("fs"); const Confippet = require("electrode-confippet"); const config = Confippet.config; const extHandlers = Confippet.extHandlers; extHandlers.json5 = (fullF) => JSON5.parse(fs.readFileSync(fullF, "utf8")); Confippet.presetConfig.load(config, { extSearch: ["json", "json5", "yaml", "js"], extHandlers, providers: { customConfig: { name: "{{env.CUSTOM_CONFIG_SOURCE}}", order: 300, type: Confippet.providerTypes.required } } }); ``` The above compose option adds a new provider that looks for a file named by the environment variable `CUSTOM_CONFIG_SOURCE` and will be loaded after all default sources are loaded (controlled by `order`). It also adds a new extension handler, `json5`, to be loaded after `json`. To further understand the `_$` and the `compose` options, please see the documentation for [store], [composeConfig], and [processConfig] <file_sep>--- title: "Add Examples" permalink: docs/add_examples.html toplevel: "Getting Started: Intermediate" --- #### Add Examples to Your Demo Create a file named `<your-awesome-component>/demo/examples/render-friend.example`. Copy, paste and save the code below into this file: ```javascript <RenderFriend friend={ {name: "John", img: "//goo.gl/dL5MXT"} } /> ``` Create a file named `<your-awesome-component>/demo/examples/guest-list.example`. Copy, paste and save the code below into this file: ```javascript <GuestList invitees={[ {name: '<NAME>', invited: false}, {name: '<NAME>', invited: false}, {name: '<NAME>', invited: false} ]} toggleGuest={(invitee) => alert(invitee.name)} /> ``` Navigate to `<your-awesome-component>/demo/examples/your-awesome-component.example`. Add the code below. Don't forget to change the references from the literal `YourAwesomeComponent` to your actual component name: ```javascript <YourAwesomeComponent ourFriends={[ {name: "electrode", img: "//goo.gl/CZ4wAF", size: 12}, {name: "hapi", img: "//goo.gl/q9uIFW", size: 12}, {name: "React", img: "//goo.gl/dL5MXT", size: 12}, ]} invitees={[ {name: "electrode", invited: false}, {name: "hapi", invited: false}, {name: "React", invited: false} ]} toggleGuest={(invitee) => alert('Edit invitees array in playground to invite a guest!')} message={(c)=>( <div className={c}>Change key 'invited' to true in 'invitees' array in the playground above to invite guests!</div> )} /> ``` Now Navigate to `<your-awesome-component>/demo/demo.jsx`. Modify `const components` to include your demo examples: ```javascript const components = [ { title: "HouseParty", examples: [ { type: "playground", code: require("raw!./examples/guest-list.example"), noRender: true } ] }, { title: "RenderFriend", examples: [ { type: "playground", code: require("raw!./examples/render-friend.example"), noRender: true } ] }, { title: "YourAwesomeComponent", examples: [ { type: "playground", code: require("raw!./examples/your-awesome-component.example"), noRender: true } ] } ]; ``` <file_sep>--- title: "FAQs" permalink: docs/faq.html toplevel: "Resources" --- ###You Ask, We Answer: <br> #### 1. Is Electrode really being used to power walmart.com? In less than one year, [Walmart.com](http://walmart.com) has completed its migration to React/Node.js and we are proud of that accomplishment! The goal was to build a new application platform to help @WalmartLabs and its engineers scale for the future. As part of that migration [Electrode] served as the platform for enabling the fast paced transformation. Now we have open sourced release of [Electrode], the application platform powering Walmart.com. <br> #### 2. What are archetypes? Electrode archetypes are a way for every electrode module to share common scripts, dependencies and best practices that can be updated in real time, and have that update propagate to every module that inherits from that specific archetype. <br> Please refer to [what are archetypes?](what_are_archetypes.html) for a detailed description of archetypes. <br> #### 3. Why is my server throwing error "cannot find module ..." on start up? Most likely you are using npm@2. Upgrade to npm@3 by running command `npm i -g npm@3` and redo `npm i`. <br> #### 4. What is the difference between creating a new electrode app using yo electrode vs cloning/forking Electrode Boilerplate? [Electrode Boilerplate] was created using `yo electrode` command. `yo electrode` gives you a bare bones Electrode Isomorphic Universal React App with NodeJS backend. [Electrode Boilerplate] includes all the bells and whistles for the SSR optimizations using the following modules configured and integrated for your use: * [Electrode Confippet] * [Electrode CSRF JWT] * [Electrode React SSR Caching] * [Electrode Redux Router Engine] * [Above The Fold Only Server Render] Head over to this amazing [blog](https://medium.com/walmartlabs/using-electrode-to-improve-react-server-side-render-performance-by-up-to-70-e43f9494eb8b#.9qjftiinq) written by [<NAME>] about How Electrode improved Server Render performance by 70% using the [stand alone modules](stand_alone_modules.html) listed above. <br> #### 5. What do you mean by reusable electrode components? Electrode reusable components are for reusing across different apps, so they are made for being developed independently, consumed via electrode-explorer. These reusable components can take extra disk space to be able to develop & run independently in the browser, but when bundled/compiled the footprint is very small. *Note: If you just have one app, they probably shouldn't follow this model and embed the components in your app directly.* <br> #### 6. Why do we focus on Universal JavaScript? * SEO - Because [Walmart.com](www.walmart.com) is an eCommerce site, Search Engine Optimization is critical for our business model. To benefit from search indexing, SSR allows us to return an HTML string to search engines and our search analytics. * Reusability - At [Walmart.com](www.walmart.com) we handle highly complex user interactions at an unbelievable scale. [ReactJS](https://facebook.github.io/react/) is the chosen framework to deal with this so our developers can create reusable components that we can then run universally: on the client and the server. Creating modular and reusable components has helped us to share the same code across several different pages and even different brands. The shared components all have one single source of truth and are easy to read, debug and implement, so our engineers can focus on building great features to enrich user experience. * Maintainability - "[Code is a liability](https://medium.com/capital-one-developers/why-everyone-is-talking-about-isomorphic-universal-javascript-and-why-it-matters-38c07c87905#.y7cy5jki3)". Universal javascript allows developers to use modular components that are sharable, self-contained, and easy to reason about. We mentioned that we have thousands of components shared by thousand of developers at [WalmartLabs](www.walmartlabs.com). Creating strict best practices and tools like [Electrode-Explorer](electrode_explorer) help us to strengthen the increase in maintainability that Universal JS gives us. <br> #### 7. Any plan with Graphql and React Native in the future ? We have plans for GraphQL, but it’s a bit further out. Regarding React Native, we are currently investing in it as we speak. Our first RN open source piece will be released in a few weeks, sometime in mid Oct :). I’m super excited about it. <br> #### 8. Does electrode support hot reloading? hot-reloading of jsx is already built in electrode. `gulp hot` will enable hot-reloading. #### 9. Why does Electrode use Gulp? Initial versions of Electrode archetypes were certainly using *npm scripts* but we started running into a few problems and here are some of the brief benefits using gulp, we feel will help make it easy and simple for developers: ### Benefits - **Maintenance**: While npm scripts in package.json are simple, they are restrictive to shell commands, and can be messy to maintain since the shell commands have to go in the package.json files and separated from any extra work that requires JS code. - **tasks integrated in JS**: When we turn these scripts into JS files, we get the full benefits of writing any JS code as part of the build task. We no longer have to write JS scripts and then invoke them from npm scripts. - **Gulp features**: By using gulp, we get to use other gulp features, particularly the streaming feature, and if we could explore use cases that can benefit. - **Community**: npm scripts are generally for simple tasks, and for more complicate build tasks, the community is more a tune to a JS task runner such as grunt and gulp. Gulp being code centric vs grunt's config centric, has been gaining ground fast with a thriving supporting community. So going to gulp will be more familiar to the developer community. - **Compatibility**: At the moment our build tasks being shell scripts some are only compatible for Unix. If we go with tasks written in JS it's easier to make them compatible on other OS such as Windows. - **Resource**: With a large community behind gulp, there are a lot of plugins in the open source community for supporting various common build tasks and we can utilize them. gulp scripts can still be wrapped in **npm scripts** here is an example of using using npm scripts to execute JS tasks in the archetype: https://github.com/electrode-io/electrode/blob/d4142ee0c938cbf973a429ee8467052aa4e1c9be/samples/universal-react-node/package.json#L22-L29 [Electrode Boilerplate]: https://github.com/electrode-io/electrode#boilerplate-universal-react-node [Electrode Confippet]: https://github.com/electrode-io/electrode-confippet [Electrode Electrify]: https://github.com/electrode-io/electrify [Electrode CSRF JWT]: https://github.com/electrode-io/electrode-csrf-jwt [Electrode Redux Router Engine]: https://github.com/electrode-io/electrode-redux-router-engine [Electrode React SSR Caching]: https://github.com/electrode-io/electrode-react-ssr-caching [Above The Fold Only Server Render]: https://github.com/electrode-io/above-the-fold-only-server-render [<NAME>]: https://twitter.com/lexgrigoryan [Electrode]: http://www.electrode.io <file_sep>--- title: "Component Helpers" permalink: docs/component_helpers.html toplevel: "Getting Started: Intermediate" --- #### Develop helpers for the components Sometimes it makes sense to do the heavy lifting of your application in one or more separate modules that are imported. For example, let's make a helper module to handle different types of graphs. Remember that this helper was imported into the app in the last section via: ```javascript import style from "../helpers/graph-styles"; ``` In `src`, create a folder named `helpers` with a file named `graph-styles.js` inside (`<your-awesome-component>/src/helpers/graph-styles.js`). Copy the code from below into this file: ```javascript const PARENT = {divisor: 2}; const CHILD = {divisor: 4, rotateBack: -1}; const SINGLE = {marginDivisor: 8}; const CONTAINER = {paddingDivisor: .13, marginDivisor: .13}; export default (type, size, rotateVal) => { const nodeSize = type === "child" ? (size / CHILD.divisor) : (size / PARENT.divisor); const parentOrSingle = { width: `${nodeSize}em`, height: `${nodeSize}em`, margin: `-${nodeSize / PARENT.divisor}em`, display: `block`, position: `absolute`, top: `50%`, left: `50%`, transform: `translate(0em)` }; switch (type) { case "single": { const singleNode = { display: `inline-block`, position: `relative`, margin: `${nodeSize / SINGLE.marginDivisor}em` }; ["width", "height"].map((prop) => singleNode[prop] = parentOrSingle[prop]); return singleNode; } case "child": { const childNode = { transform: `rotate(${rotateVal * 1}deg) translate(${nodeSize * PARENT.divisor}em) rotate(${rotateVal * CHILD.rotateBack}deg)`, // eslint-disable-line max-len backgroundSize: `100%` }; return Object.assign(parentOrSingle, childNode); } case "container": { return { position: `relative`, width: `${size}em`, height: `${size}em`, padding: `${size * CONTAINER.paddingDivisor}em`, borderRadius: `50%`, display: `inline-block`, margin: `${size * CONTAINER.marginDivisor}em` }; } default: { return parentOrSingle; } } }; ``` <file_sep>--- title: "Docker" permalink: docs/docker.html toplevel: "Getting Started: Intermediate" --- ### Deploy with Docker Docker is a new container-based technology designed to make applications easier to create, deploy and run. It's an increasingly popular way to accelerate development and share content. To get started, sign up for [Docker], download [Docker for your machine] and read over the corresponding system requirements. Docker is available for all major operating systems. See the corresponding "Get Started Tutorial" for your OS version on the Docker product page. Let's check the versions of `Docker Engine`, `Compose` and `Machine` by running the commands below: ```bash $ docker --version $ docker-compose --version $ docker-machine --version ``` Verify your installation by running the Docker version of "Hello World": ```bash $ docker run hello-world ``` To show all the containers on the system, run the command below: ```bash $ docker ps -a ``` **Electrode has a [Dockerfile and Docker image] built in to expedite deployment. Simply:** ```bash $ docker pull electrode/electrode-io ``` Try the image in your docker container: ```bash $ docker run -d -p 3000:3000 electrode/electrode-io ``` You'll see your `<container_id>` in the terminal. Verify that the server is running by opening `localhost:3000` in your browser. Copy the code from the container to your local machine for development: ```bash $ docker cp <container_id>:/usr/src/app . ``` Go to the app folder, and use the following command to stop the container so you can start your development: ```bash $ docker stop <container_id> ``` Now let's build a new image by entering the following command: ```bash $ docker build -t docker-awesome-container . ``` Run the command below to see a list of the images you currently have: ```bash $ docker images ``` You'll see `node` listed. Find the corresponding `IMAGE ID` for your `node` image. We will now build a command to properly tag the image. It'll be using your `image id` + `account name/repo-name:latest` ```bash $ docker tag your-image-id-# your-account-name/docker-awesome-container:latest ``` Let's see it! Run the `images` command below to see a lit of the images you currently have: ```bash $ docker images ``` Run your image on your local container: ```bash $ docker run -d -p 3000:3000 docker-awesome-container ``` Open `localhost:3000` in your browser to see your app. Your container id will print in the terminal, or you can run the command below to see your containers: ```bash $ docker ps ``` Now you can stop the container: ```bash $ docker stop <container_id> ``` Log into Docker Hub from the command line. The format is below. Enter your password when prompted: ```bash $ docker login --username=yourhubusername --email=<EMAIL> ``` Run the `push` command below to push your image to your new repo: ```bash $ docker push your-username/docker-awesome-container ``` You have successfully pushed your new image to the Docker Cloud repository! From here, you can use the [User Guide] to run your own containers and build Docker images. [Docker]: https://cloud.docker.com [Docker for your machine]: https://www.docker.com/products/docker [virtualize the Docker Engine environment]: https://docs.docker.com/engine/installation/mac/#/docker-for-mac [Dockerfile and Docker image]: https://hub.docker.com/r/electrode/electrode-io/ [User Guide]: https://docs.docker.com/engine/userguide/intro/ <file_sep>var gitbookMobileLink; function changeIframeLink() { var native = "https://electrode.gitbooks.io/electrode-native/content", contribute = "https://electrode.gitbooks.io/electrode-native/overview/contributing.html", api = "https://electrode.gitbooks.io/electrode-native/platform-parts/apis.html", container = "https://electrode.gitbooks.io/electrode-native/platform-parts/container.html", cauldron = "https://electrode.gitbooks.io/electrode-native/platform-parts/cauldron.html", runner = "https://electrode.gitbooks.io/electrode-native/platform-parts/runner.html"; if (gitbookMobileLink == "contribute") { document.getElementById("gitbook-iframe").src = "https://electrode.gitbooks.io/electrode-native/overview/contributing.html"; } else if (gitbookMobileLink == "api") { document.getElementById("gitbook-iframe").src = api; } else if (gitbookMobileLink == "container") { document.getElementById("gitbook-iframe").src = container; } else if (gitbookMobileLink == "cauldron") { document.getElementById("gitbook-iframe").src = cauldron; } else if (gitbookMobileLink == "runner") { document.getElementById("gitbook-iframe").src = runner; } else { document.getElementById("gitbook-iframe").src = native; } } function changeIframeVariable(variable) { gitbookMobileLink = variable; } <file_sep>--- title: "Electrify" permalink: docs/electrify.html toplevel: "Stand Alone Modules" --- [![Build Status](https://travis-ci.org/electrode-io/electrode-electrify.svg?branch=master)](https://travis-ci.org/electrode-io/electrode-electrify) An Electrode Javascript bundle viewer aptly named [Electrify](https://github.com/electrode-io/electrify), this is a stunning visual tool for analyzing the module tree of [electrode-io + webpack](https://github.com/webpack/docs/wiki/node.js-api#stats) project bundles. It's especially handy for catching large and/or duplicate modules which might be either bloating your bundle or slowing down the build process. ![screencast](https://cloud.githubusercontent.com/assets/360041/18318796/ea0ddae4-74d7-11e6-89cb-08e02e4b1683.gif) ## Installation ## Electrify lives on [npm](https://www.npmjs.com/package/electrode-electrify), so if you haven't already, make sure you have [node](http://nodejs.org/) installed on your machine first. Installing should then be as easy as: ``` bash $ sudo npm install -g electrode-electrify ``` {% include module_usage.md moduleId="electrode-electrify" %} ## Command-Line Interface ## ``` bash electrify [stats-bundle(s)...] {options} Options: -h, --help Displays these instructions. -O, --open Opens viewer in a new browser window automatically -m, --mode the default file scale mode to display: should be either "count" or "size". Default: size ``` When you install Electrify globally, `electrify` command-line tool is made available as the quickest means of checking out your bundle. As of `electrode-electrify@v1.0.0`, the tool takes any [webpack-stats](https://github.com/webpack/docs/wiki/node.js-api#stats) object [example](https://github.com/webpack/analyse/blob/master/app/pages/upload/example.json) as input and spits out a standalone HTML page as output. You can easily chain the stats file into another command, or use the `--open` flag to open Electrify in your browser automatically: For example: ``` bash $ electrify build/stats.json --open ``` ## Palettes ## You can switch between multiple color palettes, most of which serve to highlight specific features of your bundle: ### Structure Highlights ### ![Structure Highlights](http://i.imgur.com/Ajp20Jxm.png) Highlights `node_modules` directories as green and `lib` directories as orange. This makes it easier to scan for "kitchen sink" modules or modules with lots of dependencies. ### File Types ### ![File Types](http://i.imgur.com/oY5euGAm.png) Highlights each file type (e.g. `.js`, `.css`, etc.) a different color. Helpful for tracking down code generated from a transform that's bloating your bundle more than expected. ### Original/Pastel ### ![Pastel](http://i.imgur.com/ajAoqePm.png) Nothing particularly special about these palettes – colored for legibility and aesthetics respectively. ### Other useful bundle/stats generators ### - [disc-browserify](https://github.com/hughsk/disc) (Helpful for analyzing **browserify** projects and a huge inspiration for electrify, used *disc* extensively in my past **browserify** based projects) - [webpack-bundle-size-analyzer](https://github.com/robertknight/webpack-bundle-size-analyzer) - [webpack-visualizer](https://github.com/chrisbateman/webpack-visualizer) - [webpack-chart](https://github.com/alexkuz/webpack-chart) - [stats-webpack-plugin](https://github.com/unindented/stats-webpack-plugin) <file_sep>--- title: "Requirements" permalink: docs/requirements.html toplevel: "Getting Started: Quick Guide" --- First, let's quickly check your development environment. You will need to have the following set up to generate and deploy your awesome Electrode app in under five minutes: ## For Development On Your Local machine 1. Install the latest [NodeJS LTS binary] in your machine. (at least v4.2 required). * Recommend a tool like [nvm] for managing NodeJS installations. 1. Install latest (v3) of [npm] with `npm install -g npm`. * Note: NodeJS v6.x already comes with npm@3 by default. * **Electrode requires npm version >= 3** 1. Install [Gulp] with `npm install -g gulp-cli`. 1. The text editor of your choice downloaded with CLI tools installed. > We write NodeJS code with ES6 features that NodeJS >= 4.2 supports. > Gulp is a Javascript build tool that lets us automate tasks. [NodeJS LTS binary]: https://nodejs.org [nvm]: https://github.com/creationix/nvm#install-script [npm]: https://www.npmjs.com/ [gulp]: https://github.com/gulpjs/gulp/blob/master/docs/getting-started.md ## For Online Deployments * A [Heroku](https://signup.heroku.com/dc) account + [CLI tools](https://devcenter.heroku.com/articles/heroku-command-line). * A [Github](https://github.com/) account. Ready? Let's [build](build_component.html). <file_sep>--- title: "Build and Demo" permalink: docs/build_and_demo.html toplevel: "Getting Started: Intermediate" --- ### Build and Demo the component Now run it and explore the live demo! ```bash $ cd your-awesome-component $ gulp build && gulp demo ``` Open `http://localhost:4000` in your browser to see your live demo. You will first see a Guest List header with a checkbox listing all of our resources, now referred to as Friends: ![party-false](/img/component-party-false.png) Have fun! Change the `invited` key to `true` in the `invitees` array. This live demo is completely interactive: ![component](/img/component-demo.png) The Electrode stack is now like an awesome party, where all of our favorite technologies get invited: ![party-true](/img/component-party-true.png) <file_sep>--- title: "Electrode Explorer" permalink: docs/electrode_explorer.html toplevel: "Stand Alone Modules" --- > An [electrode application] that allows you to view all the components in your organization, play with the components, read the component docs, view the different versions of the component, and more - All in your browser. [View The Live Demo](https://electrode-explorer.herokuapp.com/) ![electrode-explorer](/img/electrode-explorer.png) ## Source <a target="_blank" href="https://github.com/electrode-io/electrode-explorer">View source code on GitHub</a> ## Prerequisites * node: ">=4.2.0" * npm: ">=3.0.0" * Github access token ## Overview This is a central place where you can view * demos of all the components under the organizations you specified * documentation of your components * dependencies your components have (dependencies) * other components/applications that depend on your components (usages) There are two ways the components can update dynamically: 1. Add GitHub hooks to send POST requests to `/api/update/{org}/{repoName}` when a new tag is created 2. Enable `./server/poll` plugin to set up cron job that sends the POST requests every day It's recommended to use Method #1 to see updates in near real time. After the server receives the POST request, it will fetch the `package.json` file under `{yourGithubUrl}/{org}/{repoName}`, update [data/orgs.json] and `data/{org}/{repoName}.json` files. If there is a newer version, it will try to download the new component through npm ([scripts/install-module.sh]) after a waiting period, babel transpile, and webpack the demo module ([scripts/post-install-module.sh]). To make the server update immediately or force an update, add a url parameter to the POST request, `/api/update/{org}/{repoName}?updateNow=1`. This post processing script works well with all electrode components (meaning components using our [archetype]). If you have non-electrode components, you can modify your [scripts/post-install-module.sh] to babel transpile and bundle your demo files. ## Config ```js // config/default.json { "plugins": { "./server/poll": { "options": { "enable": true } } }, "githubApi": { "version": "3.0.0", "pathPrefix": "/api/v3", "protocol": "https", "host": "github.com" }, "ORGS": [ // org/user names under which components will be included in the explorer // for example, put ["xxx", "yyy"] to include every repo under github.com/xxx and github.com/yyy ], "REPOS_USAGE_INCLUDE": [ // consumers need to contain one of these substrings to be included in usages // for example, put ["react"] so consumers named /*react*/ will be included in usages ], "REPOS_USAGE_EXCLUDE": [ // consumers containing any of these substrings won't be included in usages // for example, put ["training"] so consumers named /*training*/ will be excluded in usages ], "MODULE_PREFIXES_INCLUDE": [ // only module names beginning with one of these strings will be included in dependencies // for example, put ["react"] so only modules with name starting with "react" will be included in dependencies ], "NPM_WAITING_TIME": 300000, // wait for 5 minutes before `npm install` "GHACCESS_TOKEN_NAME": "GHACCESS_TOKEN" // github token variable name, your token would be accessible via `process.env["GHACCESS_TOKEN"]`} ``` ## Start server First install dependencies ```bash npm i ``` Export github access token or set it as an environment variable ```bash export GHACCESS_TOKEN=YOUR_GITHUB_TOKEN ``` For development mode ```bash gulp dev ``` or ```bash GHACCESS_TOKEN=YOUR_GITHUB_TOKEN gulp dev ``` For production mode ```bash gulp build ``` and ```bash NODE_ENV=production node . ``` or ```bash GHACCESS_TOKEN=YOUR_GITHUB_TOKEN NODE_ENV=production node . ``` ## Deploy Since this is an Electrode application, it can be deployed the same way as any other Electrode app. You can use [Heroku](deploy.html) by following the steps in our Quick Start or use the [More Deployments](more_deployments.html) as a resource. *Just remember to set your GitHub token as an environment variable. ## Learn more Wish to learn more? Check our [wiki] page! [archetype]: https://github.com/electrode-io/electrode-archetype-react-component [data/orgs.json]: https://github.com/electrode-io/electrode-explorer/blob/master/data/orgs.json [electrode application]: https://github.com/electrode-io/electrode-explorer [scripts/install-module.sh]: https://github.com/electrode-io/electrode-explorer/blob/master/scripts/install-module.sh [scripts/post-install-module.sh]: https://github.com/electrode-io/electrode-explorer/blob/master/scripts/post-install-module.sh [wiki]: https://github.com/electrode-io/electrode-explorer/wiki <file_sep>--- title: "Add Routes" permalink: docs/add_routes.html toplevel: "Getting Started: Intermediate" --- From previous steps we have our open source friends, the ability to have a resource-list house party, and a working demo. It's time to build out our components to handle user interaction and send requests to our Hapi Plugin (for getting more friends to our party). We will use [React-Router] and create separate routes to serve different content to our views. Now we can integrate your published `<your-awesome-component>` as a node module and build out the app. Make sure you are inside of **Your Awesome App** and follow the steps below: ```bash $ npm i your-awesome-published-npm-module --save ``` Navigate to `<your-awesome-app>/src/client/routes.jsx`. Copy, paste and save the code below into this file. Change from the literal `YourAwesomeComponent` and `your-awesome-node-module` to your actual component name: ```javascript import React from "react"; import { Route, IndexRoute } from "react-router"; import { Home } from "./components/home"; import { YourAwesomeComponent } from "your-awesome-published-npm-module"; export const routes = ( <Route path="/" component={Home}> <IndexRoute component={YourAwesomeComponent}/> <Route path="/invite" component={YourAwesomeComponent}/> </Route> ); ``` Navigate to `<your-awesome-app>/src/client/components/home.jsx`. Override the existing code by copying, pasting and saving the code below: ```javascript import React, { Component, PropTypes } from "react"; import { Link } from "react-router"; export class Home extends Component { constructor(props) { super(props); this.state = { ourFriends: [], invitees: [] }; this.toggleGuest = this.toggleGuest.bind(this); } componentDidMount() { fetch("/friends", {method: "GET"}) .then((res) => res.json()) .then((json) => { const ourFriends = json.friends; const invitees = ourFriends.map(({name}) => { return { name, invited: false}; }); this.setState({ourFriends, invitees}); //eslint-disable-line }); } componentView({ location: { pathname } }) { return { intro: pathname === "/", invite: pathname === "/invite" }; } toggleGuest({name, invited}) { const invitees = this.state.invitees.map((invitee) => { if (invitee.name === name) { invitee.invited = !invited; } return invitee; }); this.setState({invitees}); } introMessage(className) { return ( <div className={className}> <p>We should have a house party and invite all of our friends!</p> <Link to="/invite">Click Here to Make it a Party!</Link> </div> ); } render() { const { ourFriends, invitees } = this.state; const toggleGuest = this.toggleGuest; const view = this.componentView(this.props); const message = this.introMessage; return ( <div> {React.cloneElement(this.props.children, { ourFriends, invitees, toggleGuest, view, message })} </div> ); } } Home.propTypes = { children: PropTypes.node }; ``` Navigate to [Intermediate: Server Config] to learn about [Confippet] and add our Hapi plugin to our server config. [Intermediate: Server Config]: server_config.html [Confippet]: confippet.html [React-Router]: https://github.com/ReactTraining/react-router <file_sep>// toggle function to toggle currently selected pillar in mobile view var pillarsArr = ["core", "modules", "tools"]; function togglePillars(pillarSelection) { pillarsArr.forEach(function(p){ if (pillarSelection === p){ document.getElementById("mobile-"+ p).setAttribute("class", "mobile-header-items selected"); document.getElementById("mobile-" + p + "-content").setAttribute("class", " show"); document.getElementById("mobile-" + p + "-footer").style.color = "#ff0076"; }else{ document.getElementById("mobile-"+ p).setAttribute("class", "mobile-header-items"); document.getElementById("mobile-" + p + "-content").setAttribute("class", "hide"); document.getElementById("mobile-" + p + "-footer").style.color = "#333"; } }); }; // Init call to set mobile-core pillar as default togglePillars("core"); <file_sep>--- title: "What are Archetypes?" permalink: docs/what_are_archetypes.html toplevel: "Getting Started: Quick Guide" --- > Archetypes are encapsulated boilerplates for centralizing your project configurations, workflows and dependencies. An archetype is an npm module template, which is a “superclass” of a module, think inheritance for npm modules but not one that is used to generate code files and then discarded. Archetypes provide something that is quite far off from what frameworks and app generators provide. Let’s say that you are developing many different modules and all those modules require you to have very similar configs, scripts and dependencies, you can use the same archetype for all of them. With a generator like Yeoman, you would run the generator once, and it would output your module’s boilerplate and all is fine. However, if you ever wanted to change dependencies, and have that change propagate through to each and every module, you would have to manually go through each module and update those dependencies by hand. > Archetypes help to solve the problem of updating module boilerplates, by providing a single source of truth, that all of your modules inherit from. If after developing hundreds of modules ( say, React components ), you decide to change your build script, and that build script requires a new dependency, you can change it once in the archetype. Once all of the other modules run `npm install`, they will get the updated build scripts as well as the updated dependencies. Electrode archetypes are a way for every electrode module to share common scripts, workflows, dependencies and best practices that can be updated in real time. That update will then propagate to every module that inherits from that specific archetype. > Electrode archetypes: > * [electrode-archetype-react-app] : Electrode Archetype for Apps. > * [electrode-archetype-react-component] : Electrode archetype for react components. > * [electrode-archetype-njs-module-dev] : Electrode archetype for server components. <br> #### Features Archetypes come loaded with the latest technologies for developing, bundling, testing and deployment workflows. * Generate/Build production bundles and assets. * Transpile your JavaScript using Babel. * Running eslint rules for client and server JavaScript and their tests. * Running unit tests for client and server (Karma/Mocha). * Running functional tests. * Generate code coverage results for client and server (Istanbul). * Run a webpack-dev-server for hot reloading of jsx changes. * Single source of truth for all dependencies. * Single source for all development, bundling, testing and deployment related workflows. <br> #### What configs exist inside archetypes? * Webpack * Babel * Eslint * Karma/Mocha/Istanbul <br> #### Webpack config setup Let's peek under the hood into the webpack setup workflow. *webpack.config.js* Webpack configuration entrypoint ```js var _ = require("lodash"); var mergeWebpackConfig = require("webpack-partial").default; var baseConfig = require("./base.js"); var defineConfig = require("./partial/define.js"); var optimizeConfig = require("./partial/optimize"); var localesConfig = require("./partial/locales"); var productionSourcemapsConfig = require("./partial/sourcemaps-remote"); module.exports = _.flow( mergeWebpackConfig.bind(null, {}, baseConfig), optimizeConfig(), localesConfig(), defineConfig(), productionSourcemapsConfig() )(); ``` *Webpack Base Config* ```js var baseConfig = { cache: true, context: context, plugins: [ new webpack.LoaderOptionsPlugin({ options: { debug: false } }) ], entry: appEntry(), output: { path: Path.resolve("dist", "js"), pathinfo: inspectpack, // Enable path information for inspectpack publicPath: "/js/", chunkFilename: "[hash].[name].js", filename: "[name].bundle.[hash].js" }, resolve: { modules: [ archetypeNodeModules, archetypeDevNodeModules, AppMode.isSrc && Path.resolve(AppMode.src.dir) || null ] .concat(archetype.webpack.modulesDirectories) .concat([process.cwd(), "node_modules"]) .filter(_.identity), extensions: [".js", ".jsx", ".json"] }, resolveLoader: { modules: [ archetypeNodeModules, archetypeDevNodeModules, Path.resolve("lib"), process.cwd(), "node_modules" ].filter(_.identity) } }; ``` <br> #### What workflows exist inside archetypes? Workflows are tasks exposed via npm scripts & gulp as part of the [electrode-archetype-react-app], type `gulp` on your command prompt to see the full list of workflow tasks. ``` $ gulp [16:56:36] Using gulpfile ~/walmart-oss/test-generator-electrode-app/test-app/gulpfile.js [16:56:36] Starting 'help'... Usage gulp [TASK] [OPTIONS...] Available tasks build ............................ Build your app's client bundle for production tasks: ["build-dist"] build-analyze -------------------- Build your app's client bundle for production and run bundle analyzer tasks: ["build-dist","optimize-stats"] deps: [".optimize-stats"] build-browser-coverage ........... Build browser coverage tasks: ["clean-dist",".build-browser-coverage-1","build-dist:flatten-l10n","build-dist:clean-tmp"] build-dev-static ----------------- Build static copy of your app's client bundle for development tasks: ["clean-dist","build-dist-dev-static"] build-dist ....................... tasks: ["clean-dist","build-dist-min","build-dist:flatten-l10n","generate-service-worker","build-dist:clean-tmp"] build-webpack-stats-with-fullpath Build static bundle with stats.json containing fullPaths to inspect the bundle on electrode-electrify etc ... ``` Let's dive a little deeper into an example workflow `gulp build` task that is provided by the archetype for a universal React application. #### gulp build This task produces a production ready js, css bundle. Running `gulp build` will run through a few other gulp tasks to help you build your application for a production environment generating a minified bundle ready to use. The following tasks will be run in order: * `clean-dist`: Delete the old `dist/` folder * `build-dist-min`: Run webpack.config.js This particular production webpack config will be merged with the base config that is located [here.](https://github.com/electrode-io/electrode-archetype-react-app/blob/master/config/webpack/base.js) Each of the archetypes webpack configs use lodash's [flow](https://lodash.com/docs/4.16.4#flow) and [webpack-partial](https://github.com/webpack-config/webpack-partial) to compose together functions that merge partial webpack configs together with the base config allowing for a modular configuration file. ```javascript // the production webpack config // _.flow is used to compose functions module.exports = _.flow( // use webpack-partial binding it to a the baseConfig mergeWebpackConfig.bind(null, {}, baseConfig), // optimize.js optimizeConfig(), // locals.js localesConfig(), // define.js defineConfig(), // sourcemaps-remote.js productionSourcemapsConfig() )(); ``` The production webpack config is merged together with the base config and the following partials: - [optimize.js](https://github.com/electrode-io/electrode-archetype-react-app/blob/master/config/webpack/partial/optimize.js): Apply webpack's dedupe plugin to deduplicate similar or equal files from the output bundle in addition to Uglifying the output using the UglifyJS plugin - [locales.js](https://github.com/electrode-io/electrode-archetype-react-app/blob/master/config/webpack/partial/locales.js): Handle possible dynamic requires within moment.js, so webpack does not include all of the language files - [define.js](https://github.com/electrode-io/electrode-archetype-react-app/blob/master/config/webpack/partial/define.js): Define a production environment for webpack so it can remove non production code. - [sourcemaps-remote.js](https://github.com/electrode-io/electrode-archetype-react-app/blob/master/config/webpack/partial/sourcemaps-remote.js): Create sourcemaps. * `build-dist:flatten-l10n`: Run a script to extract localized messages from a file located in a temporary folder generated by the build and write them to a json file in the dist folder. This script is located [here.](https://github.com/electrode-io/electrode-archetype-react-app/blob/master/scripts/l10n/flatten-messages.js) * `generate-service-worker`: Electrode's React application archetype has built in support for [service workers](https://developers.google.com/web/fundamentals/getting-started/primers/service-workers). This gulp task will take a service worker precache configuration file (if it exists, electrode does not provide it by default) and generate a new service worker file for caching of static assets with service workers. * `build-dist:clean-tmp`: Delete the .tmp folder generated by the build. The output of `gulp build` will look something like this: ```sh Hash: 095d27720d0a224d3f5a Version: webpack 1.13.2 Time: 6607ms Asset Size Chunks Chunk Names bundle.095d27720d0a224d3f5a.js 246 kB 0 [emitted] main style.095d27720d0a224d3f5a.css 182 bytes 0 [emitted] main ../map/bundle.095d27720d0a224d3f5a.js.map 2.42 MB 0 [emitted] main ../map/style.095d27720d0a224d3f5a.css.map 107 bytes 0 [emitted] main ../server/stats.json 233 bytes [emitted] ../isomorphic-assets.json 239 bytes [emitted] ``` [electrode-archetype-react-app]: https://github.com/electrode-io/electrode#app-archetype [electrode-archetype-react-component]: https://github.com/electrode-io/electrode-archetype-react-component [electrode-archetype-njs-module-dev]: https://github.com/electrode-io/electrode-archetype-njs-module-dev <file_sep>--- title: "Redux Router Engine" permalink: docs/redux_router_engine.html toplevel: "Stand Alone Modules" --- Electrode Redux Router Engine is a tool that handles async data for React Server Side Rendering using [react-router], Redux, and the [Redux Server Rendering] pattern. {% include module_usage.md moduleId="electrode-redux-router-engine" express_react_redux=true hapi_react_redux=true %} ## Configuration The [redux-router engine](#redux-router-engine) is initialized by passing a set of [options](#API) including both the [react-router](#react-router) routes and the initial [Redux Store](#redux-store). ####React-Router Therefore, to configure the engine, you will first need specify your app's routes according to [react-router]'s specs. For example, a typical `routes.jsx` file might look like this: ```js import { Route, IndexRoute, Redirect } from "react-router"; export default ( <Route path="/test" component={Page}> <IndexRoute component={Home}/> <Redirect from="source" to="target" /> </Route> ); ``` ####Redux Store Next, you'll want to configure the redux store using the [Redux Async Actions] pattern. The first step in this pattern is to handle any middleware you might be using in addition to the required [redux thunk](https://github.com/gaearon/redux-thunk#redux-thunk) middleware which [allows actions to return functions instead of objects](http://redux.js.org/docs/advanced/AsyncActions.html#async-action-creators), an important step that lets synchronous action creators work with networks requests. We're also using [redux logger](https://github.com/evgenyrodionov/redux-logger#logger-for-redux) in this example to show how other middlewares can be integrated: `configureStore.js` ```js import { createStore, applyMiddleware } from 'redux'; import rootReducer from './reducers'; import thunkMiddleware from 'redux-thunk'; import createLogger from 'redux-logger'; const loggerMiddleware = createLogger(); export default function configureStore(initialState) { return createStore(rootReducer, initialState, applyMiddleware( thunkMiddleware, loggerMiddleware )); } ``` Now let's create the redux store using the configure function from above. This pattern creates the store in a *server-side component* and initializes it with a promise library (the example below uses [bluebird](https://github.com/petkaantonov/bluebird/)): ```javascript import configureStore from "./configureStore"; const Promise = require("bluebird"); export default function createReduxStore(req) { const store = configureStore(); return Promise.all([ store.dispatch(yourAction()) // dispatch any other asynchronous actions here ]) .then(() => store); } ``` For more information about the pattern used here, you can read about [using Async Actions in Redux](http://redux.js.org/docs/advanced/AsyncActions.html). ####Redux Router Engine The `ReduxRouterEngine` is created using both the `Redux Store` and the `routes.jsx` component, each passed as key/value pairs to an options object. The module is stand-alone and can be used in **any** Redux application that runs on Express, Hapi or [WalmartLab's Electrode framework](http://www.electrode.io). Here's how to configure the engine depending on your framework: **Electrode** In an Electrode app, the engine configuration is straightforward: the route handling logic simply returns the output of the engine's `render` function in the `module.exports` clause: ```javascript import ReduxRouterEngine from "electrode-redux-router-engine"; import { routes } from "../../client/routes"; import CreateReduxStore from "./createReduxStore" module.exports = (req) => { if (!req.server.app.routesEngine) { req.server.app.routesEngine = new ReduxRouterEngine({ routes, createReduxStore }); } return req.server.app.routesEngine.render(req); }; ``` **Hapi / Express** To configure the Redux Router Engine in an Express or Hapi application, first initialize the engine and then use it within a route handler to return the HTML. An example usage follows: ```javascript const routes = require("./routes"); const engine = new ReduxRouterEngine({routes, createReduxStore}); // express or Hapi route handler: function handler(req, res) { engine.render(req) .then( (result) => { // TODO: send full HTML with result back using res }); } ``` Note the route handler configuration above is a stub in this case. In a real Hapi or Express application, the route handler would be more complex. You can refer to our [express](https://github.com/electrode-samples/express-react-redux-webpack/blob/8e6023af5d4c7f4ec8780cfeeb214efc04892b2c/src/server.js#L90-L94) and [Hapi](https://github.com/electrode-samples/hapi-react-redux/blob/685456d738997cfca5beda2ff3d9b655ad37e0e0/hapiApp/src/server.js#L123-L146) example applications for a more specific use case of the `engine.render` function. ## API ### [constructor(options)]() Where options could contain the following fields: - `routes` - **required** The react-router routes - `createReduxStore` - **required** async callback that returns a promise resolving to the Redux store. - It should take `(req, match)` arguments where match is react-router's match result. - If it's a `function` then its `this` references the engine instance. - `withIds` - **optional** boolean to indicate whether to render with react-dataids. - `stringifyPreloadedState` **optional** callback to return string for the preloaded state - `logError` - **optional** callback to log any error - It should take `(req, err)` arguments - If it's a `function` then its `this` references the engine instance - `renderToString` - **optional** callback to provide custom renderToString - It should take `(req, store, match, withIds)` arguments ### [engine.render(req, options)]() Method to render a route. - `req` - express/Hapi request object - `options` - override options passed to constructor - `withIds` - `stringifyPreloadedState` - `createReduxStore` If rendering the route is a success, then it returns a promise resolving to: ```js { status: 200, html: // string from React renderToString, prefetch: // string from stringifyPreloadedState } ``` If an error occured, then it returns a promise resolving to: ```js { status: react-router status or 500, message: err.message, path: // request path, _err: // original error object } ``` If no route matched, then it returns a promise resolving to: ```js { status: 404, message: `router-resolver: Path <path> not found` } ``` If react-router found a redirect route, then it returns a promise resolving to: ```js { status: 302, path: // redirect location } ``` [Redux Async Actions]: http://redux.js.org/docs/advanced/AsyncActions.html [Redux Server Rendering]: http://redux.js.org/docs/recipes/ServerRendering.html [react-router]: https://github.com/reactjs/react-router <file_sep>--- title: "Server Config" permalink: docs/server_config.html toplevel: "Getting Started: Intermediate" --- ### Server Config and Confippet Out of the box we're given [Confippet], a versatile utility for managing your NodeJS application configuration. Its goal is customization and extensibility, but it offers a preset config out of the box inside **Your Awesome (Electrode) App**: ``` config ├── default.json ├── development.json └── production.json ``` We'll need to extend our default.json to include our `friends` plugin and module `./src/server/plugins/friends`. Navigate to `<your-awesome-app>/config/development.json`. Copy, paste and save `friends` plugin: ```json { "plugins": { "friends": { "module": "./src/server/plugins/friends" } } } ``` You can learn more about Confippet and ways to extend your config in our Advanced Electrode App with the [Confippet] stand alone module. We should update our app test to reflect the changes we have made. Navigate to `<your-awesome-app>/test/client/components/home.spec.jsx`. Override the existing code by copying and pasting the code below: ```javascript require("isomorphic-fetch"); import React from "react"; import ReactDOM from "react-dom"; import { Home } from "client/components/home"; class ChildComponent extends React.Component { render() { return ( <div /> ); } } describe("Home", () => { let component; let container; let location; beforeEach(() => { container = document.createElement("div"); location = { pathname: "/" }; }); it("has expected content with deep render", () => { component = ReactDOM.render( <Home location={location}> <ChildComponent /> </Home>, container); expect(component).to.not.be.false; }); }); ``` Let's check it out! We'll run through our steps to test, run the app and view it in the browser. We'll need your GitHub API token as well: ```bash $ gulp check $ token='<PASSWORD>' gulp hot ``` Navigate to `localhost:3000`. Check it out! This is the `Index route` which renders our `Home component` using Server Side Rendering: ![app-home-view](/img/app-home-view.png) When you click the `Click Here to Make it a Party` link, Your Awesome App routes to the `/invite` route, which renders the guest list component. ![app-guest-list](/img/app-guest-list-view.png) By checking the guest list, you are setting the invitee object's key to `{invited: true}`, which tells `renderFriends` to render. When all of our guests are invited to the House Party, our CSS modules kick in and launch an Electrode House Party! ![app-party-view](/img/party-collabos.png) Feel free to add your own personal touch and build out your Resource List House Party. You can compare your work to our [Heroku deployed example app]. When you're ready, you can deploy Your Awesome App to [Heroku] by following the previous steps in our [Getting Started: Build More] section. If you choose this step, make sure you set all of the Heroku configurations, including the one for our [GitHub Api]. You can also navigate to [Intermediate: More Deployments] to learn how to deploy with [Docker] and [Kubernetes]. [Confippet]: https://github.com/electrode-io/electrode-confippet [Heroku deployed example app]: https://electrode-example-app.herokuapp.com/ [Heroku]: https://devcenter.heroku.com/categories/deployment [Getting Started: Build More]: build_component.html [GitHub Api]: build_server_plugin. [Intermediate: More Deployments]: more_deployments.html [Docker]: docker.html [Kubernetes]: kubernetes.html <file_sep>--- title: "Low-Level Components" permalink: docs/low_level_components.html toplevel: "Getting Started: Intermediate" --- #### Develop a couple of low-level components Create a file called `<your-awesome-component>/src/components/guest-list.jsx`. Copy the code from below into this file: ```javascript import React from "react"; import styles from "../../src/styles/guest-list.css"; const GuestList = ({invitees, toggleGuest}) => { const renderInvitees = (inviteesArr) => { return inviteesArr.map((invitee) => ( <div key={invitee.name} className={styles.guestName}> <input id={invitee.name} type="checkbox" checked={invitee.invited} onChange={() => toggleGuest(invitee)}/> <label htmlFor={invitee.name}> {invitee.name} </label> </div> )); }; return ( <div className={styles.guestList}> <h1>Guest List:</h1> {renderInvitees(invitees)} </div> ); }; GuestList.propTypes = { invitees: React.PropTypes.array, toggleGuest: React.PropTypes.func }; export default GuestList; ``` Create another file called `<your-awesome-component>/src/components/render-friend.jsx`. Copy the code from below into this file. Don't worry—we'll cover the helper and css modules in the next section. ```javascript import React from "react"; import styles from "../../src/styles/render-friend.css"; import style from "../helpers/graph-styles"; const DEFAULT_SIZE = 15; const DEGREES_OF_COOL = 360; const RenderFriend = ({friend, styleObj, className}) => { const { name, img, profile, friends } = friend; let { size } = friend; const parentFriend = { name, img, profile }; size = size ? size : DEFAULT_SIZE; const bgImg = {backgroundImage: `url(${img})`}; let applyStyle = styleObj ? Object.assign(bgImg, styleObj) : Object.assign(bgImg, style("single", size)); applyStyle = friends ? style("container", size) : applyStyle; let applyClass = friends ? styles.join : styles.friend; applyClass = styleObj ? applyClass : `${applyClass} ${styles.join} ${className || ""}`; const renderFriends = (friendsArr) => { const angleVal = (DEGREES_OF_COOL / friendsArr.length); let rotateVal = 0; return friendsArr.map((friendObj) => { rotateVal += angleVal; return ( <RenderFriend key={friendObj.name} friend={friendObj} styleObj={style("child", size, rotateVal)}/> ); }); }; return ( <div className={applyClass} style={applyStyle}> {!!friends && renderFriends(friends)} {!!friends && <RenderFriend friend={parentFriend} styleObj={style("parent", size)}/>} </div> ); }; RenderFriend.propTypes = { friend: React.PropTypes.object, styleObj: React.PropTypes.object }; export default RenderFriend; ``` <file_sep>--- title: "Further Reading" permalink: docs/further_reading.html toplevel: "Resources" --- <br> #### Universal Javascript * [Universal Javascript](https://medium.com/@mjackson/universal-javascript-4761051b7ae9#.vql04qjs4) - Defining things is hard: this articles outlines what Universal Javascript is and isn't. Naming things is hard: why developers are moving away from the term "Isomorphic". * [Why Everyone is Talking About Isomorphic / Universal JavaScript and Why it Matters](https://medium.com/capital-one-developers/why-everyone-is-talking-about-isomorphic-universal-javascript-and-why-it-matters-38c07c87905#.ut4ggn60w) - Short overview of the history of web development + why Universal Javascript is awesome. * [Isomorphic JavaScript: The Future of Web Apps](http://nerds.airbnb.com/isomorphic-javascript-future-web-apps) - An overview of airbnb's case for Isomorphic (Universal) Javascript. #### React * [React How To](https://github.com/petehunt/react-howto) - Info about the React ecosystem. * [Thinking in React](https://facebook.github.io/react/docs/thinking-in-react.html) + [Design Principles](https://facebook.github.io/react/contributing/design-principles.html) - Read the React docs. * [Building React.js at Enterprise Scale](https://medium.com/walmartlabs/building-react-js-at-enterprise-scale-17c17a36fd1f#.ewkzubo8i) - Why ReactJS + [WalmartLabs](http://www.walmartlabs.com) are a perfect match. * [Presentational and Container Components](https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0#.ma6icgu8p) A simple, but critical pattern for your React applications. #### Redux * [A Cartoon Intro to Redux](https://code-cartoons.com/a-cartoon-intro-to-redux-3afb775501a6#.cj6szcbtd) - Essential Redux content + cartoons = Awesome! * [Getting Started with Redux](https://egghead.io/courses/getting-started-with-redux) + [Building React Applications with Idiomatic Redux](https://egghead.io/courses/building-react-applications-with-idiomatic-redux) - This is a video series, but a great Redux introduction from the library's creator. * [Understanding Redux (Or, How I Fell in Love with a JavaScript State Container)](https://medium.com/@thejenniekim/understanding-redux-or-how-i-fell-in-love-with-a-javascript-state-container-5d940fcc10b3#.r2dui841u) - A high level synopsis of Redux with bonus links to other great resources. #### Universal Rendering * [ReactJS SSR Profiling + Caching](https://medium.com/walmartlabs/reactjs-ssr-profiling-and-caching-5d8e9e49240c#.yqnmwbp6t) - Outlines the [WalmartLabs](http://www.walmartlabs.com) Server Side Rendering challenges + ways to solve this. * [Server-Side Rendering With React, Node And Express](https://www.smashingmagazine.com/2016/03/server-side-rendering-react-node-express/) - A fast and clear explanation about the general advantages of SSR. #### Deployments * [How to Deploy Software](https://zachholman.com/posts/deploying-software) - Why the deployment process is complex, can be painful, and the solutions. * [Enterprise NodeJS On OneOps](https://medium.com/walmartlabs/enterprise-nodejs-on-oneops-f4bc7b1050cc#.sfsslnetq) - An overview of Node.js on WalmartLabs open-source deployment platform [OneOps](http://www.oneops.com/). #### Testing * [Approaches to testing React components - an overview](http://reactkungfu.com/2015/07/approaches-to-testing-react-components-an-overview/) - A general overview to React testing with pros + cons. * [Mocha.js: Simple, Flexible Fun](https://mochajs.org/) The Mocha docs, helping to make sense of asynchronous testing. * [Enzyme: JavaScript Testing utilities for React](https://medium.com/airbnb-engineering/enzyme-javascript-testing-utilities-for-react-a417e5e5090f#.eo79bodrj) - An overview of Enzyme with code examples. #### CSS Modules * [CSS Modules: Welcome to the Future](http://glenmaddern.com/articles/css-modules) - Overview of CSS modules + the problems they attempt to solve. * [Modular CSS with React](https://medium.com/@pioul/modular-css-with-react-61638ae9ea3e#.b5d00dcwp) - Blog about the business case for and implementation of CSS modules. * [Understanding the CSS Modules Methodology](https://www.sitepoint.com/understanding-css-modules-methodology/) - Outlines the 'what' and 'why' of CSS modules and shares a few important gotchas. #### Babel + ES6 * [Babel Docs](https://babeljs.io/docs/learn-es2015/) - The Babel docs, guides, and blog are very user friendly. * [A Quick Tour Of ES6 (Or, The Bits You’ll Actually Use)](http://jamesknelson.com/es6-the-bits-youll-actually-use/) - Highlights the commonly used parts of the ES6 syntax. <file_sep>--- title: "Electrode Boilerplate" permalink: docs/electrode_boilerplate.html toplevel: "Electrode Boilerplate" --- ###Maximum Performance Out of the Box In our [Getting Started](get_started.html) section, we introduced you to our Yeoman Electrode [Generator](https://github.com/electrode-io/electrode#yeoman-generator) and we constructed an impressive application with the built in technologies that the simple `yo electrode` command gave us (read our Getting Started: [What's Inside](whats_inside.html) to learn more): * [React](https://facebook.github.io/react/index.html) * [Redux](http://redux.js.org/docs/basics/UsageWithReact.html) * [React Router](https://github.com/ReactTraining/react-router/tree/master/docs) * [CSS Modules](https://github.com/css-modules/css-modules) * [Universal rendering](https://medium.com/@mjackson/universal-javascript-4761051b7ae9#.xjxr5yj5z) * [Webpack](https://webpack.github.io/docs/motivation.html) * [Webpack Isomorphic Loader](https://github.com/jchip/isomorphic-loader) * [Babel](https://babeljs.io/) * [ESLint](http://eslint.org/) * [Mocha](https://mochajs.org/) + [Enzyme](https://github.com/airbnb/enzyme) + [TravisCI](https://travis-ci.org/) * [Gulp](http://gulpjs.com/) * [Yeoman](http://yeoman.io/) * [History](https://www.npmjs.com/package/history) * [Bluebird](http://bluebirdjs.com/docs/why-promises.html) * [Electrode Confippet](https://github.com/electrode-io/electrode-confippet) * [Electrode-Server](https://github.com/electrode-io/electrode-server) * [Electrode-Docgen](https://github.com/electrode-io/electrode-docgen) This is the beginning foundation of the [Electrode Boilerplate]. You have learned in the [Stand Alone Modules](stand_alone_modules.html) section that each of the Electrode modules are agnostic and can be used individually to enhance one specific area of your application. However, integrated together, you have a supercharged application; one that is capable of handling the complex problems we face at [WalmartLabs](www.walmartlabs.com) and reach maximum efficiency and performance. This boilerplate includes the [Electrode Generator](whats_inside.html) and it also has the following stand alone modules and tools built in for peak optimization out-of-the-box: * [Above the Fold Rendering](above_fold_rendering.html) * [Server Side Render Cache + Profiling](server_side_render_cache.html) * [Stateless CSRF Validation](stateless_csrf_validation.html) * [Electrode Redux Router Engine](redux_router_engine.html) * [Electrode Bundle Analyzer](bundle_analyzer.html) * [Electrify](electrify.html) >Start creating a more complex application today with the [Electrode Boilerplate]. We can't wait to see what you build! [Electrode Boilerplate]: https://github.com/electrode-io/electrode#boilerplate-universal-react-node <file_sep>--- title: "React Native and Over the Air" permalink: docs/electrode_react_native_over_the_air_electron.html toplevel: "React Native: Over the Air" --- ## Electrode Over the Air Server Electrode Over the Air (OTA) is a Microsoft(tm) Code Push compatible server for allowing mobile applications to update with or without user intervention. ### Prerequisites * Node v6 or greater [here](https://nodejs.org/en/download/current/). * Apache Cassandra [here](http://cassandra.apache.org/) and getting started [here](http://cassandra.apache.org/doc/latest/getting_started/index.html) * Github Account (if using github as auth provider) [here](http://github.com) ### Running Cassandra Books have been written about running and configuring cassandra, this is just the most minimal way you can run it. Please read such books before running this server on a public network. ```sh $ curl http://apache.mirrors.hoobly.com/cassandra/3.9/apache-cassandra-3.9-bin.tar.gz | tar -xvzf - $ cd apache-cassandra-3.9/ $ ./bin/cassandra ``` ### Installation This covers a minimal way to install and run electrode-ota-server. For most scenarios this is not complete. Be sure to setup SSL, load balancing, and all the other requirements for your environment. ```sh $ mkdir your_ota $ cd your_ota $ npm init $ npm install electrode-ota-server --save $ mkdir config ``` In package.json add By default the server will start with production config. This can be overridden with NODE_ENV. ```json "scripts":{ "start":"NODE_ENV=production node node_modules/.bin/electrode-ota-server", "development":"NODE_ENV=development node node_modules/.bin/electrode-ota-server" } ``` ### Setting up OAuth To use github as an OAuth provider you need to login to github and add an OTA Application. Step 1 - Login to github and select Settings. ![OTA: Profile - Step 1]( ../img/electrode-ota/1-Profile.png) Step 2 - Go to "Developer Settings" and select "OAuth applications" ![OTA: Register OAuth - Step 2](../img/electrode-ota/2-Register-OAuth.png) Step 3 - Setup your application. Keep in mind protocols and urls are important. Also you can set up a key for development also (localhost.yourdomain.com). Make sure that resolves, for your machine, try adding it to your hosts file. If you do not have a public server running you can add a use http://localhost:9001/ for homepage and authorization callback url., for development only. ![OTA: Register OAuth - Step 3](../img/electrode-ota/3-Register-OAuth.png) Step 4 - Wild celebration, or double check that everthing is correct. This is your you get your clientId and clientSecret. Keep your clientSecret secret (avoid checking it into public github for example). ![OTA: Register OAuth - Step 4](../img/electrode-ota/4-Review-OAuth.png) ### Configure OTA Server Inside the config create a `config/production.json`. You must configure at one environment. You can create different settings for production,test and development, by creating seperate json files for each environment. In production please use TLS/HTTPS for the server.Setting TLS is outside the scope of this document. The configurations are loaded via electrode-confippet, more details [here](https://github.com/electrode-io/electrode-confippet). **The variables that should be configured is are in <%= variable %>.** **The comments must be removed if using JSON.** ```js { "plugins": { "electrode-ota-server-dao-cassandra": { "options": { //You can enter an array of cassandra "contactPoints" but you need at least one. // If you are running cassandra locally you can use "localhost". "contactPoints": [ "<%=cassandra.hosts%>" ], //Optional - If your cassandra server does not require a password "username": "<%=cassandra.username%>", //Optional - If your cassandra server does not require a password "password": "<%=<PASSWORD>%>" //Optional the keyspace you want to run the server with, by default the keyspace is "wm_ota". "keyspace":"<%=cassandra.keyspace%>" } }, //This allows for other fileservice mechanisms to be plugged in. Currently the files are stored // in the cassandra db, but the could be stored in anything really, including the filesystem. "electrode-ota-server-fileservice":{ "options": { //this needs to be the url of your acquistion server. It can be the same as your current // management server. "downloadUrl": "http://<%=your_ota_server%>/storagev2/" } }, "electrode-ota-server-auth": { "options": { "strategy": { //Authentication Strategy. The OTA uses [bell](http://https://github.com/hapijs/bell) for //OAuth. You can see the vendors and options there. We test with github oAuth. "github-oauth": { "options": { //A Cookie password otherwise a raondom one (Optional) "password":"<%= <PASSWORD>%>", //This is true by default if not running https change to false. You should run over https though "isSecure":true, //The callback hostname of your server. If you are running behind a proxy, //it may be different than what the server thinks it is. (Optional) "location":"<%= the address of your server %>", //Get the Oauth info from github. "clientId": "<%=github oauth clientId%>", "clientSecret": "<%=github oauth clientSecret%>" } }, "session": { "options": { //A Cookie password otherwise a raondom one (Optional) "password":"<%= <PASSWORD>%>", //This is true by default if not running https change to false. You should run over https though "isSecure":true } } } } } } } ``` OTA uses [bell](http://https://github.com/hapijs/bell) for oAuth you can look there for more configuration options. ### Running OTA You can run OTA many ways, the easiest is to just to run. ``` $ npm start ``` ## Logging into your OTA Server. To use the server you just set up you will need to make the following modifications to your client (iOS/Android(tm)) app, along with setting up Apps with the OTA Server. Your server can host multiple applications from multiple developers, to manage these you can use Microsoft's code-push cli. ### From the Command Line If want to manage your OTA Server via command line. You can follow these directions. Or you can use the Electrode OTA Desktop to do the same thing. #### Installing the code-push-cli ```sh $ npm install code-push-cli -g ``` #### Register You only need/can register once per github account. So the first time each user would need to: ```sh $ code-push register https://<%=your_ota_server%> ``` #### Login After you have registered if you've logged out you may need to log back in, or your acccess-key is lost or expired you can log back in. ```sh $ code-push login https://<%=your_ota_server%> ``` #### Server Token Your server token page should look like this. ![OTA: Server Token](../img/electrode-ota/NewToken.png) #### Creating a CodePushDeploymentKey ``` $ code-push app add <%=YourAppName%> ``` Should result in something like ```sh Successfully added the "YourAppName" app, along with the following default deployments: ┌────────────┬───────────────────────────────────────┐ │ Name │ Deployment Key │ ├────────────┼───────────────────────────────────────┤ │ Production │ 4ANCANCASDASDKASASDASDASDASDASDASDAS- │ ├────────────┼───────────────────────────────────────┤ │ Staging │ ASDASDASDASDASDASDASDASDASDASDASDASD- │ └────────────┴───────────────────────────────────────┘ ``` These are your deployment keys. You will need them in the next step. ## Changes to Your Application. If your app is already using code-push you just need to do the following. If you have not setup your app for code-push, please follow Microsoft&#8482;'s guide to setting up the client SDK for React&#8482; [here](https://microsoft.github.io/code-push/docs/react-native.html) or Cordova&#8482; [here](https://microsoft.github.io/code-push/docs/cordova.html). If you you need an Example application you can find one [here](https://github.com/Microsoft/react-native-code-push/tree/master/Examples/CodePushDemoApp). ### For IOS Then add the following to `ios/<%=your_app_name%>/Info.plist`. You can open this in ```sh open ios/<%=your_app_name%>.xcodeprog``` to edit. ![OTA: Edit Info.plist](../img/electrode-ota/Info-plist.png) Or using your favorite text editor. ```xml <key>CodePushDeploymentKey</key> <string><%=your_deployment_key%></string> <key>CodePushServerURL</key> <string>http://<%=your_ota_server%></string> ``` If your OTA server is not running over https you will need to add an exception to it in the `ios/<%=your_app_name%>/Info.plist`, or you use Xcode to update the file. ```xml <dict> <key>NSAllowsArbitraryLoads</key> <true/> <key>NSExceptionDomains</key> <dict> <key><%=your_ota_server%></key> <dict> <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key> <true/> </dict> </dict> </dict> ``` ### For Android Modify `android/app/src/main/java/com/<%=your_app_name%>/MainApplication.java` ```java /** * A list of packages used by the app. If the app uses additional views * or modules besides the default ones, add more packages here. **/ @Override protected List<ReactPackage> getPackages() { return Arrays.<ReactPackage>asList( new MainReactPackage(), new CodePush("<%=your_ota_deployment_key%>", this, BuildConfig.DEBUG, "<%=your_ota_server%>") ); } ``` ### Publishing (React) To update the app over the air run. See the Microsoft&#8482; code-push docs for more information. On how to add CodePush to your application. ```sh $ cd your_client_app_dir $ code-push release-react <%=YourAppName%> ios --deploymentName <%=Staging|Production|Etc.%> ``` ## Electrode Over the Air Desktop You can use either the microsoft code-push-cli or the Electrode OTA Desktop to manage your deployments. You can get the install [here](https://github.com/electrode-io/electrode-ota-desktop/releases). ### Installation Copy of the ElectrodeOTA icon to the Applications folder ![OTA: DMG](../img/electrode-ota/DMG.png) ###Logging in Use the token from the pretty screen with the trees on it here. The host would be your OTA Server. ![OTA: Login](../img/electrode-ota/Login.png) ###Creating a New App to Manage You will need an app to get the deployment keys. ![OTA: GettingStarted](../img/electrode-ota/GettingStarted.png) ![OTA: New App Success](../img/electrode-ota/NewAppSuccess.png) ###Creating a New Deployment You can use Staging and Development or create your own, for your workflow. ![OTA: New Deployment](../img/electrode-ota/NewDeployment.png) ![OTA: New Deployment Success](../img/electrode-ota/NewDeployment1.png) ###Adding a New Release To Upload a new release select the deployment and click release. ![OTA: Releases](../img/electrode-ota/Releases.png) ###Adding Collaborators If you need to share responsibility you can add collaborator. However they will need to register [see](#user-content-register) first to be able to add them to your App. ![OTA: Collaborate](../img/electrode-ota/Collaborate.png) ### New Key If you loose key, or want one for you CI server you can manage them here. ![OTA: Add Key](../img/electrode-ota/AddKey.png) ![OTA: New Key](../img/electrode-ota/NewKey.png) <file_sep>var mobileDropdownState = false; function changeMobileDropdown(section) { mobileDropdownState = !mobileDropdownState; if (mobileDropdownState) { if (section == 1) { document.getElementById("mob-section-1").style.opacity = "1"; document.getElementById("mob-section-1").style.height = "auto"; document.getElementById("dropdown-arrow-1").style.display = "none"; } else if (section == 2) { document.getElementById("mob-section-2").style.opacity = "1"; document.getElementById("mob-section-2").style.height = "auto"; document.getElementById("dropdown-arrow-2").style.display = "none"; } else { document.getElementById("mob-section-3").style.opacity = "1"; document.getElementById("mob-section-3").style.height = "auto"; document.getElementById("dropdown-arrow-3").style.display = "none"; } } else { if (section == 1) { document.getElementById("mob-section-1").style.opacity = "0"; document.getElementById("mob-section-1").style.height = "0"; document.getElementById("dropdown-arrow-1").style.display ="inline" document.getElementById("dropdown-arrow-1").src = "/img/mobile-page/arrow_down.svg"; } else if (section == 2) { document.getElementById("mob-section-2").style.opacity = "0"; document.getElementById("mob-section-2").style.height = "0"; document.getElementById("dropdown-arrow-2").style.display ="inline" document.getElementById("dropdown-arrow-2").src = "/img/mobile-page/arrow_down.svg"; } else { document.getElementById("mob-section-3").style.opacity = "0"; document.getElementById("mob-section-3").style.height = "0"; document.getElementById("dropdown-arrow-3").style.display ="inline" document.getElementById("dropdown-arrow-3").src = "/img/mobile-page/arrow_down.svg"; } } } <file_sep>--- id: introduction title: Introduction layout: tips permalink: tips/introduction.html next: inline-styles.html --- The Electrode tips section provides bite-sized information that can answer lots of questions you might have and warn you against common pitfalls. ## Contributing Submit a pull request to the [Electrode docs repository](https://github.com/electrode-io/electrode-io.github.io). <file_sep>--- title: "Powerful Electrode Tools" permalink: docs/electrode_tools.html toplevel: "Getting Started: Quick Guide" --- ###Using Powerful Electrode Tools We've created incredible tools for better leverage of your application's capabilities. We built them with flexibility and efficiency in mind, so you can focus on innovating: <br> #### [Electrify](electrify.html) is a sophisticated tool for analyzing the module tree of project bundles. ![screencast](https://cloud.githubusercontent.com/assets/360041/18318796/ea0ddae4-74d7-11e6-89cb-08e02e4b1683.gif) <br> #### [Electrode-Explorer](electrode_explorer.html) is a dynamic, real-time showcase of all your components. ![electrode-explorer](/img/electrode-explorer.png) <br> #### [Bundle Analyzer](bundle_analyzer.html) is a webpack tool that gives you a detail list of all the files that went into your deduped and minified bundle JS file. <iframe width="600" height="300" src="https://docs.google.com/spreadsheets/d/1IomT2fYCKEwVY0CO-0jImc7CBj_uAmgy70Egsm4CnVE/edit?usp=sharing&rm=minimal" frameborder="0" allowfullscreen></iframe> <file_sep>"use strict"; function GitIssues() { this.repos = new GitRepos(); this.issueHeaderId = "fix-issues"; this.issueListIdPrefix = "issue-list-"; } GitIssues.prototype.run = function() { var self = this; self.repos.getRepos().then(function(reposList) { var index; for(index = 0; index < reposList.length; index += 1) { self.render(reposList[index]); } }); }; GitIssues.prototype.render = function(repo) { var self = this; self.getData(repo).then(function(issues) { issues = issues.filter(bugFilter); if (issues.length === 0) { return; } self.appendIssueHeader(repo, issues); self.renderIssueList(repo, issues); function bugFilter(issue) { return issue.labels.find(findBug); } function findBug (label) { return label.name === "bug"; } }); }; GitIssues.prototype.appendIssueHeader = function(repo, issues) { var minIssues = 3; var headerElement = document.getElementById(this.issueHeaderId); headerElement.appendChild(this.createRepoName(repo)); headerElement.appendChild(this.createIssueList(repo)); if (issues.length > minIssues) { headerElement.appendChild(this.createIssuesSeeAll(repo)); } }; GitIssues.prototype.createRepoName = function(repo) { var repoName = document.createElement("a"); repoName.setAttribute("href", repo.html_url); repoName.setAttribute("class", "repo-name"); repoName.innerHTML = repo.name; return repoName; }; GitIssues.prototype.createIssuesSeeAll = function(repo) { var seeAll = document.createElement("a"); seeAll.setAttribute("href", this.repos.getIssuesUrl(repo)); seeAll.setAttribute("class", "repo-issues-see-all"); seeAll.innerHTML = "See All"; return seeAll; }; GitIssues.prototype.getData = function(repo) { return $.ajax({ url: this.repos.getIssuesApi(repo), method: "GET" }); }; GitIssues.prototype.renderIssueList = function(repo, issueList) { var index; var issue; var maxIssues = 3; var maxLength = (issueList.length > maxIssues) ? maxIssues : issueList.length; var repoIssueList = document.getElementById(this.issueListIdPrefix + repo.name); for (index = 0; index < maxLength; index += 1) { issue = issueList[index]; repoIssueList.appendChild(this.createIssueItem(issue)); } }; GitIssues.prototype.createIssueList = function(repo) { var issueList = document.createElement("ul"); issueList.setAttribute("id", this.issueListIdPrefix + repo.name); issueList.setAttribute("class", "issue-list"); return issueList; }; GitIssues.prototype.createIssueItem = function(issue) { var issueItem = document.createElement("li"); issueItem.setAttribute("class", "issue-item"); issueItem.appendChild(this.createIssueNumber(issue)); issueItem.appendChild(this.createIssueTitle(issue)); return issueItem; }; GitIssues.prototype.createIssueNumber = function(issue) { var issueNumber = document.createElement("a"); issueNumber.setAttribute("href", issue.html_url); issueNumber.setAttribute("class", "issue-number"); issueNumber.innerHTML = issue.number; return issueNumber; }; GitIssues.prototype.createIssueTitle = function(issue) { var issueTitle = document.createElement("p"); issueTitle.setAttribute("class", "issue-title"); issueTitle.innerHTML = issue.title; return issueTitle; }; var issues = new GitIssues(); issues.run(); <file_sep>--- title: "Develop Main Component" permalink: docs/high_level_component.html toplevel: "Getting Started: Intermediate" --- #### Develop main high-level component Replace the code in `<your-awesome-component>/src/components/your-awesome-component.jsx` with the code below. Change all references from the literal `your-awesome-component or YourAwesomeComponent` to your actual component name: ```javascript import React, { Component, PropTypes } from "react"; import styles from "../../src/styles/your-awesome-component.css"; import RenderFriend from "./render-friend"; import GuestList from "./guest-list"; export default class YourAwesomeComponent extends Component { constructor(props) { super(props); } renderFriends(friends, party) { const invitees = this.props.invitees; const partyTime = party ? styles.party : ""; return friends .filter((friend) => { return !!invitees.filter((invitee) => { return invitee.name === friend.name && invitee.invited; }).length; }) .map((friend) => ( <RenderFriend className={partyTime} key={friend.name} friend={friend}/> )); } viewState(view) { if (view) { return view; } return { intro: true, invite: true }; } houseParty(invitees, party) { return party ? `${styles.yourAwesomeComponent} ${styles.house}` : styles.house; } render() { const { ourFriends, invitees, view, message, toggleGuest } = this.props; const party = invitees.length === invitees.filter((invitee) => invitee.invited).length && invitees.length > 0; const { invite, intro } = this.viewState(view); const houseParty = this.houseParty(invitees, party); return ( <div> {invite && invitees.length > 0 && <GuestList invitees={invitees} toggleGuest={(invitee) => toggleGuest(invitee)}/>} <div className={styles.container}> {intro && !invitees.filter((invitee) => invitee.invited).length && message(styles.message)} <div className={houseParty}> <div className={styles.room}> {this.renderFriends(ourFriends, party)} </div> </div> </div> </div> ); } } YourAwesomeComponent.displayName = "YourAwesomeComponent"; YourAwesomeComponent.propTypes = { ourFriends: PropTypes.array, message: PropTypes.func, invitees: PropTypes.array, view: PropTypes.object, toggleGuest: PropTypes.func }; YourAwesomeComponent.defaultProps = { ourFriends: [], message: () => { return `<p>Let's party! Un-comment the all the commented-out lines in the playground then check the boxes on the GuestList to invite our friends to the party!</p>`; }, invitees: [] }; ``` Last edit! In `<your-awesome-component>/src/index.js` add the three lines below: ```javascript export { default as YourAwesomeComponent } from "./components/your-awesome-component"; export { default as RenderFriend } from "./components/render-friend"; export { default as GuestList } from "./components/guest-list"; ``` <file_sep>--- title: "Server Side Render Caching + Profiling" permalink: docs/server_side_render_cache.html toplevel: "Stand Alone Modules" --- Optimize React SSR with profiling and component caching. The [electrode-react-ssr-caching] module supports profiling React Server Side Rendering time to enable component caching to help you speed up Server Side Rendering of your components. [electrode-react-ssr-caching] module can be used as a *standalone* module and is *agnostic* to your web-server framework. In this tutorial we will demonstrate how to use this module in Electrode, Express.js and Hapi.js applications. {% include module_usage.md moduleId="electrode-react-ssr-caching" express_react_redux=true hapi_react_redux=true %} #### Profiling You can use this module to inspect the time each component took to render. ```js import SSRCaching from "electrode-react-ssr-caching"; import { renderToString } from "react-dom/server"; import MyComponent from "mycomponent"; // First you should render your component in // a loop to prime the JS engine (i.e: V8 for NodeJS) for( let i = 0; i < 10; i ++ ) { renderToString(<MyComponent />); } SSRCaching.clearProfileData(); SSRCaching.enableProfiling(); const html = renderToString(<MyComponent />); SSRCaching.enableProfiling(false); console.log(JSON.stringify(SSRCaching.profileData, null, 2)); ``` #### Caching Once you've determined the most expensive components with profiling, you can enable the component caching in this module to speed up SSR performance. The basic steps to enabling caching are: ```js import SSRCaching from "electrode-react-ssr-caching"; SSRCaching.enableCaching(); SSRCaching.setCachingConfig(cacheConfig); ``` Where `cacheConfig` contains information on what component to apply caching to. See below for details. ##### cacheConfig SSR component caching was first demonstrated in [Sasha Aickin's talk]. His demo requires each component to provide a function for generating the cache key. Here we implemented two cache key generation strategies: `simple` and `template`. You are required to pass in the `cacheConfig` to tell this module what component to apply caching to. For example: ```js const cacheConfig = { components: { "Component1": { strategy: "simple", enable: true }, "Component2": { strategy: "template", enable: true } } } SSRCaching.setCachingConfig(cacheConfig); ``` #### Caching Strategies ##### simple The `simple` caching strategy is basically doing a `JSON.stringify` on the component's props. You can also specify a callback in `cacheConfig` to return the key. For example: ```js const cacheConfig = { components: { Component1: { strategy: "simple", enable: true, genCacheKey: (props) => JSON.stringify(props) } } }; ``` This strategy is not very flexible. You need a cache entry for each component instance with different props. However it requires very little processing time. ##### template The `template` caching strategy is more complex but flexible. The idea is akin to generating logic-less handlebars templates from your React components and then use string replace to process the template with different props. If you have this component: ```js class Hello extends Component { render() { return <div>Hello, {this.props.name}. {this.props.message}</div> } } ``` And you render it with props: ```js const props = { name: "Bob", message: "How're you?" } ``` You get back HTML string: ```html <div>Hello, <span>Bob</span>. <span>How&#x27;re you?</span></div> ``` Now if you replace values in props with tokens, and you remember that `@0@` refers to `props.name` and `@1@` refers to `props.message`: ```js const tokenProps = { name: "@0@", message: "@1@" } ``` You get back HTML string that could be akin to a handlebars template: ```html <div>Hello, <span>@0@</span>. <span>@1@</span></div> ``` We cache this template html using the tokenized props as cache key. When we need to render the same component with a different props later, we can just lookup the template from cache and use string replace to apply the values: ```js cachedTemplateHtml.replace( /@0@/g, props.name ).replace( /@1@/g, props.message ); ``` That's the gist of the template strategy. Of course there are many small details such as handling the encoding of special characters, preserving props that can't be tokenized, avoiding tokenizing non-string props, or preserving `data-reactid` and `data-react-checksum`. To specify a component to be cached with the `template` strategy: ```js const cacheConfig = { components: { Hello: { strategy: "template", enable: true, preserveKeys: [ "key1", "key2" ], preserveEmptyKeys: [ "key3", "key4" ], ignoreKeys: [ "key5", "key6" ], whiteListNonStringKeys: [ "key7", "key8" ] } } }; ``` - `preserveKeys` - List of keys that should not be tokenized. - `preserveEmptyKeys` - List of keys that should not be tokenized if they are the empty string `""` - `ignoreKeys` - List of keys that should be completely ignored as part of the template cache key. - `whiteListNonStringKeys` - List of non-string keys that should be tokenized. # API ### [`enableProfiling(flag)`](#enableprofilingflag) Enable profiling according to flag - `undefined` or `true` - enable profiling - `false` - disable profiling ### [`enableCaching(flag)`](#enablecachingflag) Enable cache according to flag - `undefined` or `true` - enable caching - `false` - disable caching ### [`enableCachingDebug(flag)`](#enablecachingdebugflag) Enable cache debugging according to flag. > Caching must be enabled for this to have any effect. - `undefined` or `true` - enable cache debugging - `false` - disable cache debugging ### [`setCachingConfig(config)`](#setcachingconfigconfig) Set caching config to `config`. ### [`stripUrlProtocol(flag)`](#stripurlprotocolflag) Remove `http:` or `https:` from prop values that are URLs according to flag. > Caching must be enabled for this to have any effect. - `undefined` or `true` - strip URL protocol - `false` - don't strip ### [`shouldHashKeys(flag, [hashFn])`](#shouldhashkeysflaghashfn) Set whether the `template` strategy should hash the cache key and use that instead. > Caching must be enabled for this to have any effect. - `flag` - `undefined` or `true` - use a hash value of the cache key - `false` - don't use a hash valueo f the cache key - `hashFn` - optional, a custom callback to generate the hash from the cache key, which is passed in as a string - i.e. `function customHashFn(key) { return hash(key); }` If no `hashFn` is provided, then [farmhash] is used if it's available, otherwise hashing is turned off. ### [`clearProfileData()`](#clearprofiledata) Clear profiling data ### [`clearCache()`](#clearcache) Clear caching data ### [`cacheEntries()`](#cacheentries) Get total number of cache entries ### [`cacheHitReport()`](#cachehitreport) Print out cache entries and number of hits each one has. [Sasha Aickin's talk]: https://www.youtube.com/watch?v=PnpfGy7q96U [farmhash]: https://github.com/google/farmhash [electrode-react-ssr-caching]: https://github.com/electrode-io/electrode-react-ssr-caching <file_sep>--- title: "Build a Progressive Web App" permalink: docs/service_workers.html toplevel: "Getting Started: Intermediate" --- "A Progressive Web App (PWA) uses modern web capabilities to deliver an app-like user experience." – [Progressive Web Apps] PWAs are incredibly powerful and provide functionalities like offline first, push notifications, background sync, GPU rendering, 60FPS scrolling and add to home screen for a native-like app experience. PWAs are based on [Service Workers], which work independently in the background without interfering with your web app's life cycle. ## Benefits of using Electrode PWA ### Low friction of distribution If your progressive web app is online, it's already accessible for Chrome on Android (and other mobile). Your customers won't have to download an "app" from the App Store. 65.5% of US smartphone users don't download any new apps each month. PWAs eliminate the need to go to the app store, search for the app, click Install, wait for the download, then open the app. Each of these steps loses 20% of potential users. From a developer's point of view, you don't need to rely on the Play Store to publish your app! Push new changes to your web app, and the service worker will take care of updating the app shell. ### Frictionless shopping experience For example: for an e-commerce business, PWA offers our customers a more frictionless shopping experience that allows shoppers to search, buy, and checkout quickly without downloading the native app. Furthermore, it allows you to bring app-like experiences to mobile websites, including personalization and targeted offers. ### Faster mobile experience Web Apps built with Electrode + PWA will be significantly faster. Also, these websites enable an offline mode, allowing customers to continue browsing in areas with poor wireless reception (for example, on public transit). Given the fact that faster websites have higher conversion rates, websites built with PWA could result in increased revenue. ### Personalized push notifications Electrode Push notifications can be used to interact effectively with mobile customers, as these notifications are native to the mobile device and can be personal and timely. Similar notifications can be sent to desktop websites too. ## Getting Started In the first section, we are going to make your previously built Electrode app into a PWA with content caching, push notifications, and an option for the user to save your web app to their home screen. *If you are starting out with a new PWA, just answer "Y" to the following question* ```bash $ yo electrode # ... answer questions ... # Would you like to make a Progressive Web App? (Y/n) # ... answer rest of the questions and wait for app to be generated ... ``` *Follow Prerequisites and skip to [Push Notifications]* ### Prerequisites 1. We need certain API keys for push notifications. To generate these values, visit [Firebase] and create a new project. Click on the settings icon and open `Project settings`. Navigate to the `CLOUD MESSAGING` tab and note down your `Server key` and the `Sender ID`. 2. In the `client/images` directory, add the [logo 192x192] and [logo 72x72] icon images. We'll use these logos for the `Add to Homescreen` banner and push notifications. ### Generating a Service Worker Generating a service worker in an electrode app is as simple as adding a config file. Navigate to `<your-awesome-app>/config` and create a new `sw-config.js`: ```javascript module.exports = { cache: { cacheId: "<your-awesome-app>", runtimeCaching: [{ handler: "fastest", urlPattern: /\/$/ }], staticFileGlobs: ['dist/**/*'] }, manifest: { title: "<your-awesome-app>", logo: "./images/logo-192x192.png", short_name: "EPA", background: "#FFFFFF", theme_color: "#FFFFFF" } }; ``` This will generate a `sw.js` in the `dist` folder when you build the app. ### Registering the Service Worker We need to create a server plugin to access `dist/sw.js`. Create a file called `server/plugins/pwa/index.js`, and add the following code: ```javascript "use strict"; exports.register = function (server, options, next) { server.route({ method: "GET", path: "/sw.js", handler: { file: "dist/sw.js" } }); next(); }; exports.register.attributes = { name: "pwa", version: "0.0.1" }; ``` Also, add the following to `plugins` inside `config/default.json`: ```javascript "pwa": { "module": "./server/plugins/pwa" } ``` To register the service worker on the browser, create a file called `sw-registration.js` inside the `client` directory and add the following code: ```javascript module.exports = () => { // Exit early if the navigator isn't available if (typeof navigator === "undefined") { return; } // Feature check if service workers are supported. if ("serviceWorker" in navigator) { navigator.serviceWorker.register("sw.js", { scope: "./" }) // Service worker registration was successful .then((registration) => { // The updatefound event is dispatched when the installing // worker changes. This new worker will potentially become // the active worker if the install process completes. registration.onupdatefound = function () { const installingWorker = registration.installing; // Listen for state changes on the installing worker so // we know when it has completed. installingWorker.onstatechange = function () { switch (installingWorker.state) { case "installing": console.log("Installing a new service worker..."); break; case "installed": console.log(navigator.serviceWorker.controller); // We check the active controller which tells us if // new content is available, or the current service worker // is up to date (?) // TODO: Figure out why this is the case if (navigator.serviceWorker.controller) { console.log("New or updated content is available, refresh!"); } else { console.log("Content is now available offline!"); } break; case "activating": console.log("Activating a service worker..."); break; case "activated": console.log("Successfully activated service worker."); break; case "redundant": console.log("Service worker has become redundant"); break; } }; }; }) // Service worker registration failed .catch((err) => { console.log("Service worker registration failed: ", err); }); } }; ``` Import it in `client/app.jsx`: ```javascript require.ensure(["./sw-registration"], (require) => { require("./sw-registration")(); }, "sw-registration"); ``` We achieved a couple of things here: 1. "Offline First" with the cache property. Precache your static assets generated by webpack using the staticFileGlobs property. Or, use the runtimeCaching property to cache specific react routes in `routes.jsx`. 2. "Add to Home" with the manifest property. After visiting your website, users will get a prompt (if the user has visited your site at least twice, with at least five minutes between visits) to add your application to their homescreen. `manifest` gives you control over how your web app is installed on user's home screen with `short_name`, `title` and `logo` properties. Build your app and start the server with ```bash $ gulp pwa ``` **Note: Service worker currently does not work with webpack-dev-server. You need to build first and then run the server.** Navigate to `http://localhost:3000`, open `Developer tools`, and click on the `Application` tab. You should see your `Service Worker` activated and running! ![screenshot][screenshot] Go ahead and click on the `Offline` checkbox in the Developer tools. Terminate your server. Refresh your web page. **NOTE: The `Add to Homescreen` banner will pop up only on Android devices with Chrome 42+. To simulate the banner on your desktop Chrome, navigate to `Developer tools` -> `Applications` -> `Manifest` and click on `Add to homescreen`.** ### Push notifications The [Push API] requires a registered service worker so it can send notifications in the background when the web application isn't running. We already have our Service Worker generated with the help of `sw-config.js`. We only need to add a `Push` event to it. Create a new file `sw-events.js` inside the `client` directory and add the following to it: ```javascript /* eslint-env serviceworker */ import icon from "./images/logo-192x192.png"; import badge from "./images/logo-72x72.png"; self.addEventListener("push", (event) => { const title = "It worked!"; const options = { body: "Great job sending that push notification!", tag: "electrode-push-notification-test", icon, badge }; event.waitUntil( self.registration.showNotification(title, options) ); }); ``` Check out the [Adding Push Notifications to a Web App] Codelab provided by Google for an in-depth guide on how push notifications and service workers work together. Now we need to add this file to our Webpack bundle by referencing it in the `cache property` of `sw-config.js`: ```javascript module.exports = { cache: { importScripts: ['./sw-events.js'] } } ``` Now we have a registered service worker installed, activated and ready to accept `push` from the server. But before we can `push` we need to `request permissions` from the user and `subscribe` them to the notifications. Navigate to `client/components/home.jsx` and replace it with: ```javascript /* eslint-disable react/no-did-mount-set-state */ /* global navigator */ import React, {PropTypes} from "react"; import {connect} from "react-redux"; import {toggleCheck, incNumber, decNumber} from "../actions"; class Home extends React.Component { constructor() { super(); this.state = { // Whether ServiceWorkers are supported supported: false, // Did something fail? error: null, // Waiting on the service worker to be ready loading: true, // Whether we"ve got a push notification subscription subscribed: false, // The actual subscription itself subscription: null, title: "", body: "" }; this.sendNotification = this.sendNotification.bind(this); this.handleInputChange = this.handleInputChange.bind(this); this.subscribe = this.subscribe.bind(this); } componentDidMount() { if ("serviceWorker" in navigator) { navigator.serviceWorker.ready.then((registration) => { // Check for any existing subscriptions registration.pushManager.getSubscription().then((subscription) => { // No current subscription, let the user subscribe if (!subscription) { this.setState({ loading: false, subscribed: false, supported: true }); } else { this.setState({ subscription, subscribed: true, loading: false, supported: true }); } }) .catch((error) => { this.setState({loading: false, error}); }); }) .catch((error) => { this.setState({loading: false, error}); }); } else { // ServiceWorkers are not supported, let the user know. this.setState({loading: false, supported: false}); } } subscribe() { navigator.serviceWorker.ready.then((registration) => { registration.pushManager.subscribe({ userVisibleOnly: true }) .then((subscription) => { this.setState({subscription, subscribed: true}); }) .catch((error) => { this.setState({error}); }); }); } handleInputChange(event) { this.setState({ [event.target.name]: event.target.value }); } sendNotification() { const {title, body} = this.state; // you can add badge, icon images in the options. const options = {body}; navigator.serviceWorker.ready.then((registration) => { registration.showNotification(title, options); }); } render() { const props = this.props; const {checked, value} = props; const { error, loading, supported, subscribed, subscription } = this.state; if (!loading && !supported) { return ( <div>Sorry, service workers are not supported in this browser.</div> ); } if (error) { return ( <div>Woops! Looks like there was an error: <span style={{ fontFamily: "monospace", color: "red" }}> {error.name}: {error.message} </span> </div> ); } if (loading) { return (<div>Checking push notification subscription status...</div>); } if (!subscribed) { return ( <div>Click below to subscribe to push notifications <button onClick={this.subscribe}>Subscribe</button> </div> ); } const API_KEY = "<KEY>"; const GCM_ENDPOINT = "https://android.googleapis.com/gcm/send"; const endpointSections = subscription.endpoint.split("/"); const subscriptionId = endpointSections[endpointSections.length - 1]; const curlCommand = `curl --header "Authorization: key=${API_KEY}" --header Content-Type:"application/json" ${GCM_ENDPOINT} -d "{\\"registration_ids\\":[\\"${subscriptionId}\\"]}"`; return ( <div> <h1>Hello <a href={"https://github.com/electrode-io"}>{"Electrode"}</a></h1> <div> <h2>Managing States with Redux</h2> <label> <input onChange={props.onChangeCheck} type={"checkbox"} checked={checked}/> Checkbox </label> <div> <button type={"button"} onClick={props.onDecrease}>-</button> &nbsp;{value}&nbsp; <button type={"button"} onClick={props.onIncrease}>+</button> </div> </div> <br/> <h2>Push Notifications with Service Workers</h2> Fill the form below and click on send for a push notification. <label htmlFor="title">Title</label> <input onChange={this.handleInputChange} name="title"/> <label htmlFor="body">Body</label> <input onChange={this.handleInputChange} name="body"/> <br/> <button onClick={this.sendNotification}>Send</button> <h3>Subscription Endpoint</h3> <code>{this.state.subscription.endpoint}</code> <h3>Curl Command</h3> <code>{curlCommand}</code> </div> ); } } Home.propTypes = { checked: PropTypes.bool, value: PropTypes.number.isRequired }; const mapStateToProps = (state) => { return { checked: state.checkBox.checked, value: state.number.value }; }; const mapDispatchToProps = (dispatch) => { return { onChangeCheck: () => { dispatch(toggleCheck()); }, onIncrease: () => { dispatch(incNumber()); }, onDecrease: () => { dispatch(decNumber()); } }; }; export default connect(mapStateToProps, mapDispatchToProps)(Home); ``` Make sure you update the `API_KEY` with the one you previously generated in [Prerequisites]. `navigator.serviceWorker.ready` is a promise that will resolve once a service worker is registered, and it returns a reference to the active [ServiceWorkerRegistration]. The showNotification() method of the ServiceWorkerRegistration interface creates a notification and returns a Promise that resolves to a [NotificationEvent]. We also need to update `sw-config.js` with the `sender_id`, so the final `sw-config.js` should look like: ```javascript module.exports = { cache: { cacheId: "electrode", runtimeCaching: [{ handler: "fastest", urlPattern: "\/$" }], staticFileGlobs: ['dist/**/*'], importScripts: ['./sw-events.js'] }, manifest: { title: "Electrode Progressive App", short_name: "EPA", background: "#FFFFFF", theme_color: "#FFFFFF", gcm_sender_id: "YOUR SENDER ID" } }; ``` Rebuild your app and run the server with ```bash $ gulp pwa ``` With all the code in place, we are ready to see push notifications in action. Navigate to `http://localhost:3000`. Accept the permission for subscribing and you will see a curl command rendered on the page. You can either run the curl command from terminal to see the push notification or fill out the form and click on the `Send` button to trigger it! For more Electrode PWA code examples checkout [electrode-pwa-examples](https://github.com/electrode-samples/electrode-pwa-examples/tree/master/examples) repo. [screenshot]: https://cloud.githubusercontent.com/assets/4782871/20909807/b322e462-bb12-11e6-97af-797c808e11d9.png [Progressive Web Apps]: https://developers.google.com/web/progressive-web-apps/ [Service Workers]: https://developers.google.com/web/fundamentals/getting-started/primers/service-workers [Push Notifications]: service_workers.html#push-notifications [Firebase]: https://console.firebase.google.com [logo 192x192]: https://github.com/electrode-io/electrode/blob/d4142ee0c938cbf973a429ee8467052aa4e1c9be/samples/universal-react-node/client/images/logo-192x192.png [logo 72x72]: https://github.com/electrode-io/electrode/blob/d4142ee0c938cbf973a429ee8467052aa4e1c9be/samples/universal-react-node/client/images/logo-72x72.png [Push API]: https://developer.mozilla.org/en-US/docs/Web/API/Push_API [Adding Push Notifications to a Web App]: https://developers.google.com/web/fundamentals/getting-started/codelabs/push-notifications/ [Prerequisites]: #prerequisites [ServiceWorkerRegistration]: https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration [NotificationEvent]: https://developer.mozilla.org/en-US/docs/Web/API/NotificationEvent <file_sep>--- title: "Create a Reusable Component" permalink: docs/create_reusable_component.html toplevel: "Getting Started: Intermediate" --- First things first: let's make our thing…a Thing! In this guide, we’ll take some of the basics we explored in our [Quick Start] and go further. We will make our resource list a dynamic list that is styled, tested, published and capable of being deployed with other deployment software like Docker and Kubernetes. Building this application with React components will allow for greater modularity, which will enable reuse of code in later iterations. This greatly increases workflow efficiency by allowing developers to easily divide and conquer tasks during the production process. Furthermore, better separation of concerns allows for much easier debugging in general. Let's begin by using `cd ..` to exit the directory for Your-Awesome-App and create a new, separate directory for your reusable component: ```bash $ cd .. $ mkdir your-awesome-component $ cd your-awesome-component ``` Again, we'll use [Yeoman] to scaffold our first stand alone component. We will globally install the Electrode [generator-electrode-component]: ```bash $ npm install -g generator-electrode-component ``` Then generate your new component: ```bash $ yo electrode-component ``` Fill out the Electrode [Electrode component generator] with your information: ![component-form](/img/component-form.png) Open the application up with your favorite text editor. We'll start with a fast high level view of the most important files in your component: - `demo/` A live demo of your component. You can play with its integration in real time. This folder contains the .example files which you can customize to demonstrate the default state of your components when mounted in the playground. - `node_modules/` Other Javascript files contained in modules that we will use in this application, including Electrode modules that create your out-of-the-box Universal app. - `src/` Where all our component's source code lives. Non-universal apps might normally call this the `client` folder, but since our app code will run both on the client and server, via server-side rendering, we call this folder `src`. - `test/` Test driven development is the @WalmartLabs way, and it's critical for successful growth and scaling. All testing code lives in this folder, and we'll focus on unit testing with Mocha and Enzyme soon. - `src/components/.eslintrc` A configuration file that sets our custom linting rules and basic syntax validation. In this case, it's extended from the React component archetype. - `gulpfile.js` Gulp is a Javascript build tool that lets us automate tasks and `gulpfile.js` is where we define those tasks. We like its simple syntax and the increased productivity from using an intuitive task runner. Now that we understand the basic structure of the component, let's build out the component's functionality by following the below steps: 1. [Develop a couple of low-level components] 2. [Develop helpers for the components] 3. [Develop styles using CSS modules] 4. [Develop main high-level component] 5. [Develop tests for the above components] 6. [Add Examples to the Demo] 7. [Build and Demo the component] 8. [Generating documentation] Trust us, it will be worth it. [Electrode component generator]: https://github.com/electrode-io/generator-electrode-component [Develop a couple of low-level components]: low_level_components.html [Develop helpers for the components]: component_helpers.html [Develop styles using CSS modules]: develop_styles.html [Develop main high-level component]: high_level_component.html [Develop tests for the above components]: test_components.html [Add Examples to the Demo]: add_examples.html [Build and Demo the component]: build_and_demo.html [Generating documentation]: generate_docs.html [Quick Start]: get_started.html [Yeoman]: http://yeoman.io/ <file_sep>--- title: "Develop Styles" permalink: docs/develop_styles.html toplevel: "Getting Started: Intermediate" --- #### Develop styles using CSS modules Let's also add some style elements using [CSS modules] to create a dynamic application. Use the code below to replace what is in `<your-awesome-component>/src/styles/your-awesome-component.css`: ```css body { font-family: sans-serif; } p { padding: 15px; } @keyframes partyLights { 0%{background-position:0% 51%} 50%{background-position:100% 50%} 100%{background-position:0% 51%} } @keyframes shake { from { transform: scale3d(1, 1, 1); } 10%, 20% { transform: scale3d(.9, .9, .9) rotate3d(0, 0, 1, -3deg); } 30%, 50%, 70%, 90% { transform: scale3d(1.1, 1.1, 1.1) rotate3d(0, 0, 1, 3deg); } 40%, 60%, 80% { transform: scale3d(1.1, 1.1, 1.1) rotate3d(0, 0, 1, -3deg); } to { transform: scale3d(1, 1, 1); } } .party { animation-name: shake; animation-duration: 1s; animation-fill-mode: both; animation-iteration-count: infinite; } .houseParty { -webkit-clip-path: polygon(2% 97%, 98% 97%, 98% 44%, 51% 8%, 3% 45%); clip-path: polygon(2% 97%, 98% 97%, 98% 44%, 51% 8%, 3% 45%); background: linear-gradient(269deg, #ff90f1, #27ff8f, #6db0ff, #a398ff); background-size: 800% 800%; animation: partyLights 5s ease infinite; min-height: 12em; } .house { clip-path: polygon(2% 97%, 98% 97%, 98% 44%, 51% 8%, 3% 45%); background-color: #474747; padding: 10em 2em 2em 2em; border-radius: 10px; min-height: 35vh; } .container { width: 50vw; margin-left: auto; margin-right: auto; margin-top: 10%; position: relative; transition: filter .7s ease-in-out; } .container:before { content: ''; display: block; position: absolute; background-image: url(//goo.gl/8f5GrX); background-position: center; background-size: 95%; background-repeat: no-repeat; width: 45%; height: 45%; z-index: 999; left: 47%; top: -9%; } .room { position: absolute; bottom: 0; right: 0; padding: 2em; padding-right: 2.5em; } .message { display: block; position: absolute; width: 19em; height: 11em; z-index: 999; left: 4.5em; top: 7.5em; color: white; font-weight: 100; font-family: helvetica; font-size: 27px; } a, a:hover, a:active, a:visited { color: rgb(93, 245, 255); text-decoration: none; } ``` Create a file named: `<your-awesome-component>/src/styles/guest-list.css`. Copy the code from below into this file: ```css @import url(//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css); label { font-size: 2em; } input[type=checkbox] { display:none; } input[type=checkbox] + label:before { font-family: FontAwesome; display: inline-block; } input[type=checkbox] + label:before { content: "\f096"; } input[type=checkbox] + label:before { letter-spacing: 10px; } input[type=checkbox]:checked + label:before { content: "\f046"; } input[type=checkbox]:checked + label:before { letter-spacing: 5px; } .guestList { position: absolute; z-index: 999; background-color: rgba(255, 255, 255, 0.93); left: 10%; border: 2px solid whitesmoke; display: inline-block; padding-left: 4em; padding-right: 4em; padding-bottom: 3em; padding-top: 1.7em; border-radius: 3px; margin: 2em; } .guestList h1 { font-size: 2.5em; } .guestName { margin-bottom: .5em; } ``` Create a file named: `<your-awesome-component>/src/styles/render-friend.css`. Copy the code from below into this file: ```css @keyframes shake { from { transform: scale3d(1, 1, 1); } 10%, 20% { transform: scale3d(.9, .9, .9) rotate3d(0, 0, 1, -3deg); } 30%, 50%, 70%, 90% { transform: scale3d(1.1, 1.1, 1.1) rotate3d(0, 0, 1, 3deg); } 40%, 60%, 80% { transform: scale3d(1.1, 1.1, 1.1) rotate3d(0, 0, 1, -3deg); } to { transform: scale3d(1, 1, 1); } } .join { animation-name: shake; animation-duration: 1s; animation-fill-mode: both; } .friend { border-radius: 50%; background-color: #efefef; background-repeat: no-repeat; background-position: center; background-size: 60%; float: right; } ``` [CSS modules]: https://github.com/css-modules/css-modules <file_sep># electrode-io.github.io [![ci][1]][2] This repository contains the source for the Electrode documentation site, which is generated using [Jekyll](http://jekyllrb.com/). ## Contributing * Commit contributions to the `master` branch * Use [Markdown](https://daringfireball.net/projects/markdown/) when authoring new documentation ## Installation ### Prerequisites * [Ruby](https://www.ruby-lang.org/en/) * [Bundler](https://bundler.io/) ### Setup & Run Install the project dependencies using Bundler: ```sh bundle install ``` Run the server locally: ```sh bundle exec jekyll serve ``` You should be able to access the site at: [127.0.0.1:4000](http://127.0.0.1:4000/) ## Deploying to GitHub Pages Every push to `master` (i.e. every pull request merged) will automatically build and deploy the website to `gh-pages`. Explore the [Electrode.io](http://www.electrode.io/) Website. Built with :heart: by [Team Electrode](https://github.com/orgs/electrode-io/people) @WalmartLabs. [1]: https://github.com/electrode-io/electrode-io.github.io/workflows/ci/badge.svg [2]: https://github.com/electrode-io/electrode-io.github.io/actions <file_sep>--- title: "Server Side Data Hydration" permalink: docs/ss_data_hydration.html toplevel: "Getting Started: Intermediate" --- Server side rendering consists of two steps: creating the initial redux store data and calling `ReactDOM.renderToString` with that data. Server side data hydration refers the redux initial store data that was used for `ReactDom.renderToString` being passed to the browser so react can use the same data to bootstrap rendering on the client side. This helps the client side avoid making additional calls to the server to retrieve data for rendering. ### Server Side Rendering modes Although Electrode provides server side rendering by default, it provides modes where it can be turned off by passing an argument as a part of the URI. ####1. No Server Side Rendering(noss): This mode completely disables any rendering of html and server side data hydration. A typical use of this mode would be when the server load is high. ``` https://localhost:3000?__mode=noss ``` ####2. Server Side Data Only (datass): This mode provides server side data hydration only but does not provide any server rendered content. The benefit here would be that we are able to cut down on using server resources but are also able to provide data to the client. ``` https://localhost:3000?__mode=datass ``` ### Testing To verify that the mode is working correctly and server side rendering is turned off, once you open the app in your browser, view page source and check if the div ```(.js-content)``` is empty. If you used the ```datass``` mode, then you should still be able to see the initialized redux store. ### Auto Server Side Data Hydration As much as Electrode believes in the benefits of server side rendering, it is also aware of its side effects. Electrode is constantly monitoring the performance of your app and will turn of server side rendering if app performance is degrading. The following files in your server are responsible for this optimization and can be customized based on the needs of your application: {% raw %} ``` server/conditions/ ├── machine-info.js ├── machine-load.js ├── response-time.js └── server-load.js ``` {% endraw %} As indicated by the file names, we are monitoring the machine load, the server load and the response times of the app. In each file, we define default thresholds that we feel indicate a high load or long enough response time to make a decision that the server is overworked and server side rendering should now be disabled. ####machine-load.js We define two thresholds: ```DEFAULT_LOAD_THRESHOLD = 4 ``` and the ```DEFAULT_MEM_THRESHOLD = 0.8```. Electrode looks at the load averages for the last one minute and five minutes, the memory usage of the server and disables server side rendering if they are higher than the threshold. These default thresholds can be modified as per your needs or can be overridden if passed in the requests. More information on load averages and how a threshold can be calculated can be found <a target="_blank" href ="http://blog.scoutapp.com/articles/2009/07/31/understanding-load-averages">here</a>. ####response-time.js The important default thresholds for measuring response time are: ``` DEFAULT_LONG_RESPONSE_THRESHOLD_MS = 5000; DEFAULT_LONG_RESPONSE_AMOUNT = 6; DEFAULT_DISABLE_EXPIRY_MINS = 2; ``` The response time is monitored per request. A response that takes over 5seconds is considered a long response. The app then notes this and checks to see if we have hit the `DEFAULT_LONG_RESPONSE_AMOUNT`. If we have, then server side rendering is disabled for `DEFAULT_DISABLE_EXPIRY_MINS` minutes. Once the expiry time is reached, we check to see if we are no longer getting long responses and then enable server side rendering again. ####server-load.js We are simply measuring the event loop delay here compare it against the threshold `DEFAULT_EVENTLOOP_DELAY_MS = 40`. If found to be higher we disable server side rendering. [Here](http://2014.jsconf.eu/speakers/philip-roberts-what-the-heck-is-the-event-loop-anyway.html) is a good talk on learning about event loops. >NOTE: While generating an Electrode app using the Electrode generator via the `yo electrode` command, you will need to answer "Yes" to `Disable server side rendering based on high load?` in order to enable the above functionality. <file_sep>--- title: "Build a Server Plugin" permalink: docs/build_server_plugin.html toplevel: "Getting Started: Intermediate" --- #### Be Hapi and Build a server plugin At WalmartLabs, we use [Hapi] because of its flexible and robust plugin system. It allows us to modularize our application into isolated pieces of business logic and reusable utilities. Let's make a plugin! Plugins are way to extend our server's functionality. Building upon our open source theme, let's make a plugin that retrieves our tech friends for our "resource party." First, head back to Your Awesome App. We'll use the [GitHub API] to grab the latest 10 contributors of our open source friends, and display them in Your Awesome App. GitHub has [great documentation] and awesome libraries to help jumpstart our plugin. Let's begin there by installing a Node.js wrapper for the GitHub Api called [node-github] in Your Awesome App: ```bash $ npm install github ``` At their core, plugins are a simple `register object` that has the signature `function (server, options, next)`. Read more about building plugins from scratch in the [Hapi documentation]. Navigate to the `<your-awesome-app>/src/server/plugins` folder. Make a folder called `friends`, `cd` into your new `friends` folder, and create an empty `index.js` file: ```bash $ touch index.js ``` Your Server file pattern should now look like this: {% raw %} ``` server ├── index.js ├── plugins │ ├── friends │ │ └── index.js │   └── webapp │   ├── index.html │   └── index.js └── views └── index-view.jsx ``` {% endraw %} Navigate to `<your-awesome-app>/src/server/plugins/friends/index.js`. This is where we will make an external API call to Github and request the last ten contributors of our selected Open Source 'friend' using a URL `https://api.github.com/ + /repos/:user/:repo/contributors`. Our GitHub wrapper [library] will allow us to use a built in method, `github.repos.getContributors({})`, to streamline this process and return an array of Open Source contributors. We will also use [Bluebird], a Promise library that makes working with our async API calls much more manageable. Copy, paste and save the code below: ```javascript "use strict"; //a very simple plugin const Promise = require("bluebird"); const GitHubApi = require("github"); const github = new GitHubApi(); const AUTH_TOKEN = process.env.token; github.authenticate({ type: "oauth", token: AUTH_TOKEN }); const githubGetContributors = Promise.promisify(github.repos.getContributors); exports.register = (server, options, next) => { const friendsArr = [ /*eslint-disable max-len */ {name: "Electrode", img: "//goo.gl/I9utJF", size: 8, github: "https://github.com/electrode-io/electrode"}, {name: "React", img: "//goo.gl/xwbqlB", size: 8, github: "https://github.com/facebook/react"}, {name: "Redux", img: "//goo.gl/MGQ3lp", size: 8, github: "https://github.com/reactjs/redux"}, {name: "node", img: "//goo.gl/hxmCEE", size: 8, github: "https://github.com/nodejs/node"} ]; /*eslint-enable max-len */ const getContributorsPromises = friendsArr.map((friend) => { /*eslint-disable camelcase */ const githubUrl = friend.github.split("/"); const githubInfo = { repo: githubUrl.pop(), owner: githubUrl.pop(), anon: true, page: 1, per_page: 10 }; return githubGetContributors(githubInfo) .then((response) => { friend.friends = response.data.map(({ login, avatar_url, html_url }) => ( {name: login, img: avatar_url, profile: html_url} )); return friend; }); }); /*eslint-enable camelcase */ const getFriendsAndContributors = (reply) => { return Promise.all(getContributorsPromises) .then((response) => reply(null, JSON.stringify({friends: response}))) .catch((err) => reply(err)); }; server.route({ method: "GET", path: "/friends", handler: (request, reply) => getFriendsAndContributors(reply) }); next(); }; exports.register.attributes = { name: "getFriends", version: "1.0.0" }; ``` If you plan on building out Your Awesome App even further, you'll need to [generate a GitHub Api oAuth token] to remove the preset limit for API requests. We have already added the code to accept and use the token in our Hapi server plugin above `const AUTH_TOKEN = process.env.token`. Set a new [personal access token] (you may be prompted to login to your GitHub account if you haven't already), create your `token description` in the form given, and for `Select scopes` simply check `public repo`. Then hit the green `Generate token` button. You will be redirected to the next page to retrieve your token. Keep your token private and secure; do not copy and paste it directly into your app. Instead, we will set your token as a Node [environment variable]. Copy and save this token in a secure place; we will use it several times. Use this token in your command line as follows: Set the token locally: ```bash $ token='your-token-here' ``` Set your token for heroku deployment: ```bash heroku config:set token='your-token-here' ``` A great tool for testing your server requests is [Postman]. Its user interface for viewing response objects and errors is incredible. For now, you will have to trust us as we build out Your Awesome App. Navigate to [Intermediate: Add Routes], to add routing to the app and extend our UI to display our contributor array. [Hapi]: http://hapijs.com/ [GitHub API]: https://developer.github.com/v3/ [great documentation]: https://developer.github.com/v3/ [node-github]: https://github.com/mikedeboer/node-github [Hapi documentation]: http://hapijs.com/tutorials/plugins [library]: https://github.com/mikedeboer/node-github [Bluebird]: http://bluebirdjs.com/docs/getting-started.html [generate a GitHup Api oAuth token]: https://github.com/settings/tokens/new [personal access token]: https://github.com/settings/tokens/new [environment variable]: https://nodejs.org/api/process.html#process_process_env [Postman]: https://www.getpostman.com/ [Intermediate: Add Routes]: add_routes.html <file_sep>--- title: "What's Inside" permalink: docs/whats_inside.html toplevel: "Getting Started: Quick Guide" --- #### Explore More What does `generator-electrode` give you? Let's go through the most important files to understand the structure of your new app. > `<your-awesome-app>/src/client/components/home.jsx` This is the home React component for your app. [React](https://facebook.github.io/react/index.html) is a JavaScript library for building user interfaces. A simplified way to look at React is that it can be used as the _View_ in a _Model-View-Controller_ application. It was created by Facebook and is being actively developed. Building with React lets developers create a modular and reusable component architecture. We can then reuse the business logic in existing _models_ and _controllers_ because React components encapsulate only the _view_ layer. The components you write are self-contained, which aids developers in quickly determining what a component does directly by reading the source. Finally, it is ideally suited to Universal JavaScript (previously called Isomorphic JavaScript), the practice of sharing code between the server and the client. > `<your-awesome-app>/src/client/styles/base.css` We will use [CSS Modules](https://github.com/css-modules/css-modules): a CSS file in which all class names and animation names are scoped locally by default. At WalmartLabs, this helps us tackle large-scale styling requirements by mitigating the issues inherent in the global scope in CSS. > `<your-awesome-app>/src/client/app.jsx` To help you understand what `src/client/app.jsx` is doing, including the relationship between client and server, we've broken down each part of this file with a brief explanation below, including links to sources where you can learn even more: ```javascript import React from "react"; import { routes } from "./routes"; import { Router } from "react-router"; ``` Any real world web application needs to be able to handle different routes serving different content, so how do we handle the concept of routing in the Electrode platform? The library chosen to take care of this for us is [react-router](https://github.com/reactjs/react-router/tree/master/docs). Why react-router? The project is mature, well-documented, and integrates well within the Electrode tech stack. ```javascript import {createStore} from "redux"; import {Provider} from "react-redux"; ``` [Redux](http://redux.js.org/) is a state management library where your application data is in a store which contains a single object tree. This store is the single source of truth for your application and holds the state of your application. The store provides api's to access and update the state of your application. [React-Redux](https://github.com/reactjs/react-redux) is the official binding for Redux and React. The rest of the code in `src/client/app.jsx` sets up the React app to run when the page is loaded. The selector is based on the `<div>` in `electrode-react-webapp/lib/index.html` within your `node_modules`. ```javascript window.webappStart = () => { const initialState = window.__PRELOADED_STATE__; const store = createStore(rootReducer, initialState, enhancer); render( <Provider store={store}> <div> <Router history={browserHistory}>{routes}</Router> <DevTools /> </div> </Provider>, document.querySelector(".js-content") ); }; ``` If you have a universal application and server-side rendering, [electrode-redux-router-engine](https://github.com/electrode-io/electrode/tree/master/packages/electrode-redux-router-engine) handles async data for React Server Side Rendering using react-router, Redux, and the Redux Server Rendering pattern. > `<your-awesome-app>/src/client/routes.jsx` We will be sharing our routes between server and client, so obviously we only want to define them in one place. The `src/client/routes.jsx` encapsulates the routing logic accordingly. > `<your-awesome-app>/config` In this folder we are leveraging one of our most important stand alone modules: [Electrode-Confippet](confippet.html). Confippet is a versatile utility for managing your NodeJS application configuration. Its goal is customization and extensibility while offering a [preset configuration](https://github.com/electrode-io/electrode-confippet) out of the box. {% raw %} ``` config ├── default.json ├── development.json └── production.json ``` {% endraw %} We use this to keep environment-specific configurations manageable. Once you have your configuration files setup accordingly, you can simply pass the config object to electrode server. > `<your-awesome-app>/src/server` {% raw %} ``` server/ ├── conditions │   ├── machine-info.js │   ├── machine-load.js │   ├── response-time.js │   └── server-load.js ├── index.js ├── plugins │   ├── autossr.js │   ├── csrf.js │   ├── pwa.js │   └── updateStorage.js ├── storage.json └── views └── index-view.jsx ``` {% endraw %} You are now using [Electrode-Server](https://github.com/electrode-io/electrode-server), a NodeJS module that allows you to start up a Hapi server with a single function call, but gives you a lot of flexibility through configurations. This is the baseline functionality of a [Hapi](http://hapijs.com/) web server that you can extend via configuration. Before we move on, we should inspect a critical file, `electrode-react-webapp/lib/index.html` located within your `node_modules`. This is where the server-side rendering magic happens, implemented automatically via `generator-electrode`: {% raw %} ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{{PAGE_TITLE}}</title> {{WEBAPP_BUNDLES}} {{PREFETCH_BUNDLES}} </head> <body> <div class="js-content">{{SSR_CONTENT}}</div> <script>if (window.webappStart) webappStart();</script> </body> </html> ``` {% endraw %} All of your content will be served as an HTML string and placed in this unassuming piece of code: {% raw %} ```html <div class="js-content">{{SSR_CONTENT}}</div> ``` {% endraw %} This includes React components and Redux. To achieve this, the Electrode team has created another powerful module to optimize performance for an out-of-the-box Universal app: [Electrode-Redux-Router-Engine](https://github.com/electrode-io/electrode-redux-router-engine), which takes React routes and requests and returns HTML to be rendered by `electrode-react-webapp`. We have found this to be the [best tool](https://github.com/electrode-io/electrode-redux-router-engine) for dealing with asynchronous redux actions. > `<your-awesome-app>/src/client/.babelrc` This is where we extend our `electrode-archetype-react-app` [Babel](https://babeljs.io/docs/usage/babelrc/) configuration to use [the ES6 presets](https://babeljs.io/docs/plugins/preset-es2015/), as well as specifying any plugins or projects that need additional Babel settings. > `<your-awesome-app>/.isomorphic-loader-config.json` This [powerful tool](https://github.com/electrode-io/isomorphic-loader) makes NodeJS `require` work with files such as images for server-side rendering. It contains three pieces: a Webpack loader, Webpack plugin, and a library for your NodeJS app. --- With `generator-electrode`, we've created a dynamic and performant full stack Electrode app in under five minutes, using some of our favorite technologies, like [React](https://facebook.github.io/react/index.html) and [Hapi](http://hapijs.com/). Let's explore and personalize this web application in our next section, [Intermediate: Create a Resuable Component](create_reusable_component.html). <file_sep>--- title: "Test Components" permalink: docs/test_components.html toplevel: "Getting Started: Intermediate" --- #### Develop tests for the above components @WalmartLabs believes that testing is critical to writing great, high performance code. This includes unit testing at both the component and application level. For your component, we are using [Mocha], a Javascript testing framework that is perfect for running async tests, with [Enzyme], Airbnb's awesome testing utility for React, and [Chai] for assertions. #### How to run tests ```bash # Basic testing and linting $ gulp check # Continous Testing ## In one terminal $ gulp server-test ## In a different terminal $ gulp test-frontend-dev-watch ``` [Mocha]: https://mochajs.org/ [Enzyme]: http://airbnb.io/enzyme/docs/guides/mocha.html [Chai]: http://chaijs.com/ <file_sep>--- title: "Build Component" permalink: docs/build_component.html toplevel: "Getting Started: Quick Guide" --- #### Here at WalmartLabs we love to build! After you've generated your awesome electrode app, you are ready to focus on writing your React components. Navigate to `<your-awesome-app>/src/client/components/home.jsx`: ```javascript import React, {PropTypes} from "react"; import {connect} from "react-redux"; import {toggleCheck, incNumber, decNumber} from "../actions"; class Home extends React.Component { render() { const props = this.props; const {checked, value} = props; return ( <div> <h1>Hello <a href={"https://github.com/electrode-io"}>{"Electrode"}</a></h1> <div> <h2>Managing States with Redux</h2> <label> <input onChange={props.onChangeCheck} type={"checkbox"} checked={checked}/> Checkbox </label> <div> <button type={"button"} onClick={props.onDecrease}>-</button> &nbsp;{value}&nbsp; <button type={"button"} onClick={props.onIncrease}>+</button> </div> </div> </div> ); } } Home.propTypes = { checked: PropTypes.bool, value: PropTypes.number.isRequired }; const mapStateToProps = (state) => { return { checked: state.checkBox.checked, value: state.number.value }; }; const mapDispatchToProps = (dispatch) => { return { onChangeCheck: () => { dispatch(toggleCheck()); }, onIncrease: () => { dispatch(incNumber()); }, onDecrease: () => { dispatch(decNumber()); } }; }; export default connect(mapStateToProps, mapDispatchToProps)(Home); ``` We'll need a place to keep all of the resources we learned in the [Get Started](get_started.html) section. Let's make a visual library for our present stack and exciting technologies! Copy the code below and paste it into `<your-awesome-app>/src/client/components/home.jsx`: ```javascript import React, {PropTypes} from "react"; import {connect} from "react-redux"; import {toggleCheck, incNumber, decNumber} from "../actions"; export const imageUrls = [ 'http://daynin.github.io/clojurescript-presentation/img/react-logo.png', 'https://raw.githubusercontent.com/reactjs/redux/master/logo/logo.png', 'http://freevector.co/wp-content/uploads/2014/04/webpack.png', 'https://raw.github.com/hapijs/hapi/master/images/hapi.png', 'https://upload.wikimedia.org/wikipedia/commons/thumb/d/d0/Emoji_u26a1.svg/2000px-Emoji_u26a1.svg.png' ]; class Home extends React.Component { renderImage(imageUrl, key) { return ( <img key={key} src={imageUrl} width="10%" height="10%"/> ); } render() { const props = this.props; const {checked, value} = props; return ( <div> <h1>Hello <a href={"https://github.com/electrode-io"}>{"Electrode"}</a></h1> <div> <p>Our beloved friends</p></div> <div className="images"> {imageUrls.map((imageUrl, index) => this.renderImage(imageUrl, index))} </div> <div> <h2>Managing States with Redux</h2> <label> <input onChange={props.onChangeCheck} type={"checkbox"} checked={checked}/> Checkbox </label> <div> <button type={"button"} onClick={props.onDecrease}>-</button> &nbsp;{value}&nbsp; <button type={"button"} onClick={props.onIncrease}>+</button> </div> </div> </div> ); } } Home.propTypes = { checked: PropTypes.bool, value: PropTypes.number.isRequired }; const mapStateToProps = (state) => { return { checked: state.checkBox.checked, value: state.number.value }; }; const mapDispatchToProps = (dispatch) => { return { onChangeCheck: () => { dispatch(toggleCheck()); }, onIncrease: () => { dispatch(incNumber()); }, onDecrease: () => { dispatch(decNumber()); } }; }; export default connect(mapStateToProps, mapDispatchToProps)(Home); ``` Let's finish the UI by adding styles. Navigate to `<your-awesome-app>/src/client/styles/base.css` and add the code below: ```css h1 { font-size: 16px; color: red; } p { font-family: "Comic Sans MS", cursive, sans-serif; } a { font-size: 14px; color: red; } a:hover { color: blue; } .resource { margin-bottom: 10px; } .title { border-bottom: 2px solid blue; text-align: center; } ``` Run our new favorite command to see your tech list: ```bash gulp dev ``` Navigate to [https://localhost:3000](https://localhost:3000]). > If you are already running your app in dev mode, then your changes should've been updated automatically and you can just refresh your browser to see the changes. **The page should resemble the following screenshot:** ![Pastel](http://i.imgur.com/nwEl64l.png) Now let's jump to our next step, where we will deploy Your Awesome App to [Heroku](deploy_app.html). <file_sep>{% assign page_tokens = page.id | replace_first: '/docs/', '' | split: '-' %} {% assign page_ids = page_tokens.first | split: '.' %} {% assign before = true %} {% assign prev = "" %} {% assign next = "" %} {% for doc in site.docs %} {% assign filename = doc.id | replace_first: '/docs/', '' %} {% assign tokens = filename | split: '-' %} {% assign ids = tokens.first | split: '.' %} {% if ids.first == page_ids.first %} {% if page_tokens.first == tokens.first %} {% assign before = false %} {% elsif before == true %} {% assign prev = doc.permalink %} {% elsif next == "" %} {% assign next = doc.permalink %} {% endif %} {% endif %} {% endfor %} <div class="docs-prevnext"> {% if prev != "" %} <a class="docs-prev" href="{{ site.baseurl }}/{{ prev }}">&larr; Prev</a> {% endif %} {% if next != "" %} <a class="docs-next" href="{{ site.baseurl }}/{{ next }}">Next &rarr;</a> {% endif %} </div> <file_sep>--- title: "Above The Fold Rendering" permalink: docs/above_fold_rendering.html toplevel: "Stand Alone Modules" --- The [above-the-fold-only-server-render] is a React component for optionally skipping server side rendering of components outside above-the-fold (or inside of the viewport). This component helps render your components on the server that are above the fold and the remaining components on the client. [above-the-fold-only-server-render] is a *standalone* module. It is *agnostic* of your web-server framework. In this tutorial we will demonstrate how to use this module in Electrode, Express.js and Hapi.js applications. ### Why do we need this module? The table below outlines a clear performance increase in the example app by skipping server rendering of the `Footer` component and several other below the fold zones on [Walmart.com](http://www.walmart.com): ![above-the-fold-table](/img/above-the-fold-table.png) {% include module_usage.md moduleId="above-the-fold-only-server-render" express_react_redux=true hapi_react_redux=true %} The Above-the-fold component is used as a wrapper. After wrapping your react components in the AboveTheFoldOnlyServerRender wrapper, you can skip server side rendering on those components and save on CPU render time by passing a `skip={true}` prop to the wrapper component: ```js const SomeComponent = () => { return ( <AboveTheFoldOnlyServerRender skip={true}> <div>This will skip server side rendering.</div> </AboveTheFoldOnlyServerRender> ); }; ``` Alternatively, you can set up `aboveTheFoldOnlyServerRender` in your app context and pass the AboveTheFoldOnlyServerRender wrapper a `contextKey` prop: ```js const SomeComponent = () => { return ( <AboveTheFoldOnlyServerRender contextKey="aboveTheFoldOnlyServerRender.SomeComponent"> <div>This will not be server side rendered based on the context.</div> </AboveTheFoldOnlyServerRender> ); }; class SomeApp extends React.Component { getChildContext() { return { aboveTheFoldOnlyServerRender: { SomeComponent: true } }; } render() { return ( <SomeComponent /> ); } } SomeApp.childContextTypes = { aboveTheFoldOnlyServerRender: React.PropTypes.shape({ AnotherComponent: React.PropTypes.bool }) }; ``` By default, the [above-the-fold-only-server-render] component is an exercise in simplicity; at a high-level it returns the child component that it wraps around. ## Supported Platforms This module is web-server Platform agnostic can be used with your favorite node.js server framework [Electrode](https://github.com/electrode-io/electrode), [Express.js](https://github.com/electrode-samples/express-example-with-standalone-electrode-modules), or [Hapi.js](https://github.com/electrode-samples/hapijs-example-with-standalone-electrode-modules). [above-the-fold-only-server-render]: https://github.com/electrode-io/above-the-fold-only-server-render <file_sep>--- title: "What is Electrode?" permalink: docs/what_is_electrode.html toplevel: "Overview" --- > Electrode is a platform for building universal React/Node.js applications with a standardized structure that follows best practices and has modern technologies baked in. Electrode focuses on performance, component reusability and simple deployment to multiple cloud providers—so you can focus on what makes your app unique. ### Core: Quick + Easy Electrode Core allows you to build a flexible and universal React/Node.js application in minutes, with support for server-side rendering and easy deployment. Use Electrode to start new projects quickly with a simple, consistent structure that follows modern best practices. The heart of the Electrode platform is managed by the [Electrode Archetype System](what_are_archetypes.html), which allows for a standardized configuration, structure and workflow throughout the entire application. By enforcing a sensible structure and consistency for components, modules and the entire app, Electrode’s Archetype system helps you build scalable applications you can trust while ensuring streamlined development and deployment. **It only takes a few minutes to get your new Electrode application running and deployed to the cloud. See our [Getting Started:Quick Guide](get_started.html) to get started now.** <hr> ### Stand Alone Modules: Optimize Where You Want The Electrode platform uses several modules to help with a variety of common tasks from [server-side render caching](server_side_render_cache.html) to [flexible configuration management](confippet.html). These modules can be used independently of Electrode Core, which means you can [integrate them into your existing apps](stand_alone_modules.html). **Start using these modules in your existing application with our [guide](stand_alone_modules.html).** <hr> ### Tools: Power Up Your Existing Applications The Electrode Platform also has tools that can be consumed by existing applications built with other platforms (though with Electrode core, these tools are either bundled directly or require far less configuration). There are currently two powerful tools: * one which enables [discovery of reusable components](electrode_explorer.html) * another to help optimize your [JavaScript bundles](electrify.html) **Start using [Electrode Explorer](electrode_explorer.html) and [Electrify](electrify.html) in your existing applications.** ##Features [Electrode Boilerplate](https://github.com/electrode-io/electrode#boilerplate-universal-react-node) comes fully loaded with the best technologies available: * <a href="https://facebook.github.io/react/index.html" target="_blank">React</a> - an awesome JavaScript library for building user interfaces, created by Facebook. * <a href="http://redux.js.org/docs/basics/UsageWithReact.html" target="_blank">Redux</a> - a predictable state container for JavaScript apps. * <a href="https://reacttraining.com/react-router/" target="_blank">React Router</a> - a powerful routing library built on top of React. * <a href="https://github.com/css-modules/css-modules" target="_blank">CSS Modules</a> - a CSS file in which all class names and animation names are scoped locally by default. Fixes the problem of the global scope in CSS. * <a href="https://medium.com/@mjackson/universal-javascript-4761051b7ae9#.xjxr5yj5z" target="_blank">Universal rendering</a> * <a href="https://webpack.github.io/docs/motivation.html" target="_blank">Webpack</a> - a powerful module bundler. * <a href="https://github.com/jchip/isomorphic-loader" target="_blank">Webpack Isomorphic Loader</a> - a powerful tool that makes NodeJS `require` understand files such as images for SSR. * <a href="https://babeljs.io/" target="_blank">Babel</a> - a utility to transpile ES6 + 7. * <a href="http://eslint.org/" target="_blank">ESLint</a> - a pluggable linting utility for Javascript. * <a href="https://mochajs.org/" target="_blank">Mocha</a> - a feature-rich Javascript testing framework. * <a href="https://github.com/airbnb/enzyme" target="_blank">Enzyme</a> - a Javascript testing utility for React, created by airbnb. * <a href="https://travis-ci.org/" target="_blank">TravisCI</a> - a continuous integration service to build and test software projects. * <a href="http://gulpjs.com/" target="_blank">Gulp</a> - a Javascript build tool that lets us automate tasks. * <a href="http://yeoman.io/" target="_blank">Yeoman</a> - a Scaffolding tool for modern webapps. * <a href="https://www.npmjs.com/package/history" target="_blank">History</a> - a Javascript library for managing session history. * <a href="http://bluebirdjs.com/docs/why-promises.html" target="_blank">Bluebird</a> - a great Javascript promise library. * [Electrode Confippet](https://github.com/electrode-io/electrode-confippet) - a versatile and flexible utility for managing configurations of Node.js applications. * [Electrode JWT CSRF](https://github.com/electrode-io/electrode-csrf-jwt) - a module to enable stateless Cross-Site Request Forgery (CSRF) protection with JWT. * [Electrode-Redux-Router-Engine](https://github.com/electrode-io/electrode-redux-router-engine) - an Electrode routing and rendering engine using react-router and redux. * [Component Caching](https://github.com/electrode-io/electrode-react-ssr-caching) - an optimizer to improve React Server Side Rendering speed * [Electrode-Server](https://github.com/electrode-io/electrode-server) - a configurable web server using Hapi.js on top of Node.js. * [Electrify](https://github.com/electrode-io/electrify) - a tool for analyzing the module tree of webpack projects. * [Electrode-Docgen](https://github.com/electrode-io/electrode-docgen) - a custom metadata extractor for the Electrode framework, automates component documentation. <file_sep>--- title: "Why Use Electrode?" permalink: docs/why_use_electrode.html toplevel: "Overview" --- > If you're writing a universal React/Node.js application, then Electrode is for you! At [@WalmartLabs](http://www.walmartlabs.com/), we recently migrated [walmart.com](http://walmart.com) to a [Universal JavaScript](https://medium.com/@mjackson/universal-javascript-4761051b7ae9#.k3j9fruyn) stack using React/Node.js. Along the way, we hit a few stumbling blocks that might sound familiar if you've worked on a large, complex web app before. ### Universal JavaScript Universal JavaScript allows us to use the same view rendering code from the server and client. When a user requests a page, they immediately receive the fully rendered HTML on initial page load. They will not have to wait for the client side JavaScript code to load and render the page. Rich app like experiences are possible without requiring a full page load when navigating or responding to user actions within the same page. The client side code will handle all the rendering of the view changes within the page. Only the data changes will be sent between the client and the server. This approach provides for an optimized user experience resulting in fast page loads and even faster navigation experience. In the world of eCommerce where every millisecond counts, we believe this is the best way forward. ### Code/UI Reuse We reuse React components across all of our brands, which means our developers need to be able to search through thousands of components, view their documentation and see them rendered, and use another developer's component secure in the knowledge that its structure and implementation are consistent with our standards. We needed a way to ensure that all components were built according to modern best practices, without slowing our developers down with a lot of manual configuration. ### Server Side Rendering (SSR) Performance We serve millions of customers a day, so performance is critical to our business. React's SSR support is vital for SEO (Search Engine Optimization) and has the potential to improve performance, but it's intensive on the server CPUs. We needed a platform with SSR built-in with a default configuration that's optimized for performance. ### Fast Startup and Deployment We don't have time to create an application structure, configuration files, and Docker containers from scratch every time we start a project. We need to start fast and to deploy fast, with a consistent structure and optimal configuration every time. ### Three Pillars To solve these problems, we created the Electrode platform. Electrode consists of three pillars: Electrode Core, Electrode Modules, and Electrode Tools. ***Electrode Core*** provides a set of modules that get you started with a simple, consistent structure that follows modern best practices. When you're ready to take your app into production, Electrode automatically deploys to your favorite cloud provider. ***Electrode Modules*** improve performance, efficiency, and security by adding features like [above the fold rendering](above_fold_rendering.html), [configuration management](confippet.html), and [cross-site request forgery protection](stateless_csrf_validation.html). These modules can even be used with your existing React/Node.js application—so there's no need to migrate to Electrode Core. ***Electrode Tools*** help [organize](electrode_explorer.html) reusable components and [optimize large JavaScript bundles](electrify.html). Like the modules, our tools can be used with any React/Node.js app. ### Future Investment [Electrode](https://github.com/electrode-io) will continue to improve as we continue to solve problems like these at [@WalmartLabs](http://www.walmartlabs.com/). Future enhancements will include more [progressive web app features](https://developers.google.com/web/progressive-web-apps/) for web and mobile, bigger investments in performance, and much more. We're committed to open source, which means our investment is your investment. ### Take a Look So let's go! Check out the developer environment [requirements](requirements.html), dive into [Electrode's features in detail](https://electrode-io.github.io/docs/what_is_electrode.html#features), or use our [Getting Started: Quick Guide](get_started.html) to start building now. <file_sep>--- title: "Kubernetes" permalink: docs/kubernetes.html toplevel: "Getting Started: Intermediate" --- #### Deploy with Google's Kubernetes [Kubernetes] is an open-source system for automating deployment, scaling, and management of containerized applications. It was developed by Google to handle the ops demand for an organization of that scale and the flexibility to run an infrastructure at any size. To start, make sure you already have a [Google Account]. Sign in to the [Google Cloud Platform] and also sign up for a free trial on [Google Container Registry] and create a new project. Remember your project ID and use it on your command line: ```bash $ export PROJECT_ID="your-project-id" ``` Install the [Google Cloud SDK]. Next, run the following command to install [Kubernetes]: ```bash $ gcloud components install kubectl ``` We will use your [Docker image] from the "Deploy with Docker" section. Navigate to the docker `app` folder and update the Dockerfile to the following: ```bash FROM node:4.5 RUN npm i -g npm@3 EXPOSE 3000 RUN mkdir -p /usr/src/app WORKDIR /usr/src/app COPY . /usr/src/app RUN npm install RUN /usr/src/app/node_modules/.bin/gulp build CMD node server ``` Let's test out your image with Docker. Run the command below: ```bash $ docker run -d -p 3000:3000 docker-awesome-container ``` Visit your app in the browser at `http://localhost:3000`. You can stop running the container by using the command below: ```bash $ docker stop docker-awesome-container ``` We can now push the image to the [Google Container Registry]. Your Docker images will be stored in a private repo that is accessible from every Google Cloud project as well as from outside the Google Cloud Platform. ```bash $ gcloud docker push gcr.io/$PROJECT_ID/docker-awesome-container:v1 ``` You can explore other [Kubernetes capabilities] and dig deeper in the extensive [reference documentation]. [Kubernetes]: http://kubernetes.io/ [Google Account]: https://accounts.google.com/SignUp [Google Cloud Platform]: https://console.cloud.google.com/home/dashboard?project=gentle-waters-127300&pli=1 [Google Container Registry]: https://cloud.google.com/container-registry/ [Google Cloud SDK]: https://cloud.google.com/sdk/ [Kubernetes]: http://kubernetes.io/docs/user-guide/kubectl-overview/ [Docker image]: docker.html [Google Container Registry]: https://cloud.google.com/container-registry/ [Kubernetes capabilities]: http://kubernetes.io/docs/hellonode/ [reference documentation]: http://kubernetes.io/docs/reference/
fd1554771dfa9fa8ae969546d532214f9a7bb7d0
[ "Markdown", "JavaScript", "HTML" ]
53
Markdown
electrode-io/electrode-io.github.io
5685325991ee4ee391e275b1af0b8d652a5c66c0
e9f81d2e8bf98167170ed6efe84ee6d566288e25
refs/heads/master
<file_sep>#!/bin/bash # Install OpenSSH echo "==================INSTALLING OPEN-SSH====================" apt-get update && apt-get install -y make gcc net-tools openssh-server echo "==================OPEN-SSH INSTALLED SUCCESSFULLY====================" # Create ducc user & copy ssh credentials echo "==================ADDING DUCC USER WITH SSH CREDENTIALS====================" useradd -m ducc -s /bin/bash mkdir /home/ducc mkdir /home/ducc/.ssh wget https://raw.githubusercontent.com/Salmation/typhon-pre-reqs/master/id_rsa -P /home/ducc/.ssh/ wget https://raw.githubusercontent.com/Salmation/typhon-pre-reqs/master/id_rsa.pub -P /home/ducc/.ssh/ echo "==================ADDING DUCC USER: SUCCESSFULL====================" # Start SSH service service ssh start #Set Permissions chmod 700 /home/ducc/.ssh chmod 600 /home/ducc/.ssh/id_rsa chmod +r /home/ducc/.ssh/id_rsa.pub cp /home/ducc/.ssh/id_rsa.pub /home/ducc/.ssh/authorized_keys echo "StrictHostKeyChecking=no" > /home/ducc/.ssh/config # The same for root user cp -Rf /home/ducc/.ssh/ /root/ chown -Rf root.root /home/ducc/.ssh/ # UIMA DUCC installation mkdir /home/ducc/ducc_runtime # Install NFS-Client (Filesystem Sharing) apt-get update apt-get install nfs-common echo "============ !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ================" echo "============================== ADD WORKER NODE TO THE CLUSTER =============================" echo "============ !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ================" echo "Add HOST Node IP in Worker Node Hosts File: nano /etc/hosts" echo "Mount Shared folder: mount HOST-IP:/home/ducc/ducc_runtime /home/ducc/ducc_runtime" echo "Add Worker Node HOSTNAME to /home/ducc/ducc_runtime/resources/ducc.nodes on Shared Filesystem." echo "Re-Run DUCC from Head Node or Worker Node:" echo "(HEAD NODE): su - ducc -c '/home/ducc/ducc_runtime/admin/start_ducc'" echo "OR" echo "(WORKER NODE): su - ducc -c \"ssh HOST-IP-HERE '/home/ducc/ducc_runtime/admin/start_ducc'\"" echo "===========================================================================================================" echo "=========================================== SETUP COMPLETE ================================================" echo "===========================================================================================================" <file_sep>#!/bin/bash # Install OpenSSH echo "==================INSTALLING OPEN-SSH====================" apt-get update && apt-get install -y make gcc net-tools openssh-server echo "==================OPEN-SSH INSTALLED SUCCESSFULLY====================" # Create ducc user & copy ssh credentials echo "==================ADDING DUCC USER WITH SSH CREDENTIALS====================" useradd -m ducc -s /bin/bash mkdir /home/ducc mkdir /home/ducc/.ssh wget https://raw.githubusercontent.com/Salmation/typhon-pre-reqs/master/id_rsa -P /home/ducc/.ssh/ wget https://raw.githubusercontent.com/Salmation/typhon-pre-reqs/master/id_rsa.pub -P /home/ducc/.ssh/ echo "==================ADDING DUCC USER: SUCCESSFULL====================" # Download Uima-DUCC 3 wget http://ftp.halifax.rwth-aachen.de/apache//uima//uima-ducc-3.0.0/uima-ducc-3.0.0-bin.tar.gz -P /home/ducc # Start SSH service service ssh start #Set Permissions chmod 700 /home/ducc/.ssh chmod 600 /home/ducc/.ssh/id_rsa chmod +r /home/ducc/.ssh/id_rsa.pub cp /home/ducc/.ssh/id_rsa.pub /home/ducc/.ssh/authorized_keys echo "StrictHostKeyChecking=no" > /home/ducc/.ssh/config # The same for root user cp -Rf /home/ducc/.ssh/ /root/ chown -Rf root.root /home/ducc/.ssh/ # UIMA DUCC installation mkdir /home/ducc/ducc_runtime cd /home/ducc/ && tar xzf /home/ducc/uima-ducc-3.0.0-bin.tar.gz && mv apache-uima-ducc-3.0.0/* /home/ducc/ducc_runtime/ rm -Rf /home/ducc/apache-uima-ducc-3.0.0/ cd /home/ducc/ducc_runtime/admin/ && /home/ducc/ducc_runtime/admin/ducc_post_install #Sleep for 30 seconds sleep 30 chown ducc.ducc -Rf /home/ducc/ chmod 700 /home/ducc/ducc_runtime/admin/ # Create res folder to store the results mkdir /tmp/res chown ducc.ducc -Rf /tmp/res/ # Run check_ducc to check if UIMA is properly installed export LOGNAME="ducc" su - ducc -c "/home/ducc/ducc_runtime/admin/check_ducc" # Install NFS (Filesystem Sharing) apt-get update apt install nfs-kernel-server # Add Worker Node IP in hosts # nano /etc/hosts #Start DUCC su - ducc -c "/home/ducc/ducc_runtime/admin/start_ducc" echo "===========================================================================================================" echo "===================== TO ADD WORKER NODE TO CLUSTER PERFORM THE FOLLOWING STEPS ===========================" echo "===========================================================================================================" echo "nano /etc/exports" echo "/home/ducc/ducc_runtime (Insert-Worker-Node-IP-Here)(rw,sync,no_subtree_check)" echo "exportfs –a" echo "systemctl restart nfs-kernel-server" echo "ADD WORKER NODE IP TO HOST: nano /etc/hosts" echo "===========================================================================================================" echo "=========================================== SETUP COMPLETE ================================================" echo "==========================================================================================================="
82c40ff90762968358bdd07129f713964330c555
[ "Shell" ]
2
Shell
DrRaja/typhon-pre-reqs
00f246bd5f76e892d1be5cf3d897dda8090100d8
c9e87a1f83d2d4affddc23e7eafc32a2f4b72f99
refs/heads/master
<repo_name>Mebigi/material-ingreso<file_sep>/programacion/ingreso/3-InstruccionSwitch/jsInstruccionSwitch(5).js function Mostrar() { //tomo la hora var laHora = parseInt(document.getElementById('hora').value); // NOTA: con parseInt trnsformo un texto en umerico y evito usar las comillas en el swich //alert (laHora); switch(laHora){ case 7: case "8": case "9": case "10": case "11": alert('Es de mañana.'); break; } }//FIN DE LA FUNCIÓN<file_sep>/programacion/ingreso/5-InstruccionWhile/jsIteraciones (4).js function Mostrar() { var numero = parseInt(prompt("ingrese un número entre 0 y 10.")); //parseInt si no pongo numero devuelte NaN // isNaN pregunta si no es un numero, si es un numero da falso. while (numero > 10 || numero < 0 || isNaN(numero) ) //ojo no usar if porque este no se repite, la condicion no se repite. { numero = prompt("ingrese un número entre 0 y 10."); //chequerear de combiar el valor de la clave una vez que la valido } //alert("numero correcto!!") document.getElementById("Numero").value = numero; }//FIN DE LA FUNCIÓN<file_sep>/programacion/ingreso/5-InstruccionWhile/jsIteraciones (8).js function Mostrar() { var contador=0; var positivo=0; var negativo=1; // elemento neutro para multiplicacion el 1 var contadorNeg = 0 var respuesta='si'; do { //uso el contador como variable de control para que itere 5 veces numero = parseInt(prompt("Ingrese número")); //recordar hacer validaciones NaN if (numero >= 0) // considero 0 positivo { positivo = positivo + numero; } else { negativo = negativo * numero; contadorNeg ++; } respuesta = prompt("Desea continuar") } while(respuesta=='si') document.getElementById('suma').value=positivo; if(contadorNeg==0) { negativo = 0 } document.getElementById('producto').value=negativo; }//FIN DE LA FUNCIÓN<file_sep>/programacion/ingreso/6-InstruccionFor/jsIteracionesFor (5).js function Mostrar() { var numero = 0; for (i=0; ;i++) { numero = parseInt(prompt("ingrese numero")) if (numero == 9) { break; } } }//FIN DE LA FUNCIÓN<file_sep>/programacion/ingreso/5-InstruccionWhile/jsIteraciones (7).js function Mostrar() { var contador=0; var acumulador=0; var respuesta='si'; //while(respuesta=='si') //{ //uso el contador como variable de control para que itere 5 veces //numero = parseInt(prompt("Ingrese número")); //recordar hacer validaciones NaN //acumulador = acumulador + numero //parciales: diferencia ente acumulador y contador Recordar inicilizar porque si no sale NaN //contador += 1 //respuesta = prompt("Desea continuar") //} do //cuando se necita que se ejecute por lo menos una vez en este caso la variable respuesta no requiere ser inicalizada { //uso el contador como variable de control para que itere 5 veces numero = parseInt(prompt("Ingrese número")); //recordar hacer validaciones NaN acumulador = acumulador + numero //parciales: diferencia ente acumulador y contador Recordar inicilizar porque si no sale NaN contador += 1 respuesta = prompt("Desea continuar") } while(respuesta=='si'); document.getElementById('suma').value=acumulador; document.getElementById('promedio').value=acumulador/contador; }//FIN DE LA FUNCIÓN <file_sep>/programacion/ingreso/ExamenIngresoViejo/codigoFuenteParcial/2-entradaSalida.js //Debemos lograr mostrar un mensaje al presionar el botón 'MOSTRAR'. function Mostrar() { importe = parseInt(prompt('Ingrese un importe')); document.getElementById("importe").value = importe + (importe * 0.21) } <file_sep>/programacion/ingreso/ExamenIngresoViejo/codigoFuenteParcial/3-entradaSalida.js //Debemos lograr mostrar un mensaje al presionar el botón 'MOSTRAR'. function Mostrar() { var ancho = parseInt(document.getElementById("ancho").value); var largo = document.getElementById("largo").value; var hilos; hilos = (2* ancho + 2* largo) * 6; //no hace falta que ponga parentesis a la suma alert("Cantidad de hilos: " + hilos) } } <file_sep>/programacion/ingreso/5-InstruccionWhile/jsIteraciones (10).js function Mostrar() { //Al presionar el botón pedir números hasta que el usuario quiera, mostar: //1-Suma de los negativos. 2-Suma de los positivos. 3-Cantidad de positivos. //4-Cantidad de negativos. 5-Cantidad de ceros. 6-Cantidad de números pares. // 7-Promedio de positivos. 8-Promedios de negativos. //9-Diferencia entre positivos y negativos, (positvos-negativos). var numero; var sumaneg = 0; var sumapos = 0; var cantidadpos=0; var cantidadneg=0; var cantidadceros=0; var cantidadpares =0; var promediopos = 0; var promedioneg = 0; var sumapares = 0; //siempre inicializar un contador porque si no te da NaN; Ejemplo NaN + 1 = NaN // declarar variables var respuesta='si'; do { numero = parseInt(prompt("Ingrese número")); //recordar hacer validaciones NaN if(numero > 0)//beneficio una vez que se cumple la condicion ya no evalua el resto de las condiciones y ahorra codigo { cantidadpos ++; sumapos += numero; } else if (numero < 0) { cantidadneg ++; sumaneg += numero; } else { cantidadceros ++; } if (numero % 2 == 0) { sumapares += 1; } respuesta = prompt("Desea continuar"); } while(respuesta!='no'); //siempre que dividimos la varable tieen que ser distinto de cero if (cantidadpos != 0) { promediopos = sumapos/cantidadpos; } if (cantidadneg != 0) { promedioneg = sumaneg/cantidadneg; } document.write("suma positivos:" + sumapos); document.write("<Br/>"); document.write("suma negativos:" + sumaneg); document.write("<Br/>"); document.write("cantidad pos:" + cantidadpos); document.write("<Br/>"); document.write("cantidad neg:" + cantidadneg); document.write("<Br/>"); document.write("cantidad ceros:" + cantidadceros); document.write("<Br/>"); document.write("promedio pos:" + promediopos); document.write("<Br/>"); document.write("promedio neg:" + promedioneg); document.write("<Br/>"); document.write("diferencia:" + (cantidadpos - cantidadneg)); document.write("<Br/>"); document.write("suma positivos:" + sumapos); document.write("<Br/>"); document.write("suma pares:" + sumapares); document.write("<Br/>"); }//FIN DE LA FUNCIÓN<file_sep>/programacion/ingreso/ExamenIngresoViejo/codigoFuenteParcial/4-if.js //Debemos lograr mostrar un mensaje al presionar el botón 'MOSTRAR'. function Mostrar() { var numero1 = prompt('primer numero'); var numero2 = prompt('segunso numero'); if (numero1 == numero2) { alert("multiplica" + numero1 + numero2); } else { numero1 = parseInt(numero1); numero2 = parseInt(numero2); } if (numero1 > numero2) { alert("Resta" + (numero1-numero1)); } else { alert("Suma" + (numero1+numero2)); } } <file_sep>/programacion/ingreso/ExamenIngresoViejo/codigoFuenteParcial/6-iteraciones.js //Debemos lograr mostrar un mensaje al presionar el botón 'MOSTRAR'. function Mostrar() { var importe; var importemayor; var importemenor; var flag = 0; var diamayor; var diamenor; for (var dia=1; dia <= 7; dia++) { importe = parseInt(prompt("importe de la venta del día " + dia)); while (importe <= 0) { importe = parseInt(prompt("importe de la venta del día " + dia)); } if (importe > importemayor || flag == 0) { importemayor = importe; diamayor = dia; } if (importe < importemenor || flag == 0) { importemenor = importe; diamenor = dia; flag = 1; } document.write("importe " + dia + ": " + importe) } document.write("importe mayor " + importemayor + "<br />importe menor " + importemenor); } <file_sep>/programacion/ingreso/6-InstruccionFor/jsIteracionesFor (4).js function Mostrar() { for (var i=0; ;i++) { console.log(i); if (i == 15) { break;//te saca directameten al for //continue; puentea a la prox de interacion } } alert("listo"); }//FIN DE LA FUNCIÓN<file_sep>/programacion/ingreso/6-InstruccionFor/jsIteracionesFor (6).js function Mostrar() { var numero; var contadorpar= 0; numero =parseInt(prompt("ingrese numero")); for(var i=1; i<= numero; i++) { if (i%2 != 0) { continue; } contadorpar++; console.log(i) } console.log("cantidad numeros pares:" + contadorpar); }//FIN DE LA FUNCIÓN<file_sep>/programacion/ingreso/5-InstruccionWhile/jsIteraciones (5).js function Mostrar() { var sexo = prompt("ingrese f ó m ."); sexo = sexo.toLowerCase(); while ((sexo != "f") && (sexo != "m")) //ojo no usar if porque este no se repite, la condicion no se repite. { sexo = prompt("ingrese f ó m ."); //chequerear de combiar el valor de la clave una vez que la valido } document.getElementById('Sexo').value= sexo; }//FIN DE LA FUNCIÓN<file_sep>/programacion/ingreso/5-InstruccionWhile/jsIteraciones (9).js function Mostrar() { var contador=0; var maximo; var minimo; // var flag = 0; // declarar variables var respuesta='si'; do { numero = parseInt(prompt("Ingrese número")); //recordar hacer validaciones NaN if (contador!=0) // con flag saco contador { if(numero > maximo) // || flag == 0 { maximo = numero; } if (numero < minimo) // || flag == 0 { minimo = numero; //flag = 1; } } else { minimo = numero; maximo = numero; } respuesta = prompt("Desea continuar"); contador++; } while(respuesta!='no'); document.getElementById('maximo').value=maximo; document.getElementById('minimo').value=minimo; }//FIN DE LA FUNCIÓN
7a3fa853634369dec5f04c860ea4c1c4a88d536e
[ "JavaScript" ]
14
JavaScript
Mebigi/material-ingreso
6654d9a5c10867126cf649f42f28d60b4aa1d865
2efdb93fa0c566627430674519847142ea25d42f
refs/heads/master
<file_sep>import requests import time from plyer import notification notification.notify( title = "Belajar membuat notif menggunakan python", message = 'anjing lu', app_icon = "Paomedia-Small-N-Flat-Bell.ico", timeout = 10 ) """install module requests sebelum mencoba dengan command 'pip requests install'"""
86051103776bda6e042808861437551252cff6d7
[ "Python" ]
1
Python
siluthfi/desktopnotif
f9f2b2f207a9e120081642fc2d22889c29ca8199
23d9569d865f0442d7a448892ef2a1c84a3547c1
refs/heads/Old_Code
<file_sep>#include "TAxis.h" #include "TH2.h" #include "TStyle.h" #include "TCanvas.h" #include "TNtupleD.h" #include <stdio.h> #include <stdlib.h> #include <vector.h> #include "TGraph.h" #include <string> int getdata(int i, const char* dataname, TNtuple* ntuple) {//méthode très utile pour accéder à la donnée i d'une branche d'un arbre Float_t data; TBranch *dataBranch; ntuple->SetMakeClass(1); ntuple->SetBranchAddress(dataname, &data, &dataBranch);//fait pointer la branche dataBranch vers la branche dataname et data vers la case correspondante de dataBranch dataBranch->GetEntry(i); return data; } using namespace std; void collageuf(){ char premierFichier[256],secondFichier[256]; string text; cout<<"Enter the name of the first root file (xxx.root) : "<<endl; cin.getline(premierFichier,256); cout<<"Enter the name of the second root file (xxx.root) : "<<endl; cin.getline(secondFichier,256); cout<<"Enter the name of the output text file (yyy.txt) : "<<endl; cin>>text; char* textName=text.c_str(); TFile *fichier1=new TFile(premierFichier,"READ"); int N1=ntuple->GetEntries(); cout<<"going through first file..."<<endl; vector<float> I1v; vector<float> I2v; vector<float> I3v; vector<float> I4v; vector<float> tp1v; vector<float> tp2v; vector<float> pressurev; vector<float> humidityv; vector<float> dateabsv; vector<int> jour; vector<int> mois; vector<int> annee; vector <float> Ifinalv; //vector <float> I1nv; vector <float> E1v; vector <float> E2v; vector <float> E3v; vector <float> E4v; vector <float> I1nv; vector <float> I1nexpocv; vector <float> I2nv; vector <float> I2nexpocv; vector <float> I3nv; vector <float> I3nexpocv; vector <float> I4nv; vector <float> I4nexpocv; vector <float> chargev; vector <float> I1nerrorv; vector <float> I2nerrorv; vector <float> I3nerrorv; vector <float> I4nerrorv; vector <float> I1ncerrorv; vector <float> I2ncerrorv; vector <float> I3ncerrorv; vector <float> I4ncerrorv; for (int i=0;i<N1;i++){ I1v.push_back(getdata(i,"I1",ntuple)); I2v.push_back(getdata(i,"I2",ntuple)); I3v.push_back(getdata(i,"I3",ntuple)); I4v.push_back(getdata(i,"I4",ntuple)); tp1v.push_back(getdata(i,"tp1",ntuple)); tp2v.push_back(getdata(i,"tp2",ntuple)); pressurev.push_back(getdata(i,"pressure",ntuple)); humidityv.push_back(getdata(i,"humidity",ntuple)); dateabsv.push_back(getdata(i,"dateabs",ntuple)); jour.push_back(getdata(i,"jour",ntuple)); mois.push_back(getdata(i,"mois",ntuple)); annee.push_back(getdata(i,"annee",ntuple)); E1v.push_back(getdata(i,"I1error",ntuple)); E2v.push_back(getdata(i,"I2error",ntuple)); E3v.push_back(getdata(i,"I3error",ntuple)); E4v.push_back(getdata(i,"I4error",ntuple)); I1nv.push_back(getdata(i,"I1n",ntuple)); I2nv.push_back(getdata(i,"I2n",ntuple)); I3nv.push_back(getdata(i,"I3n",ntuple)); I4nv.push_back(getdata(i,"I4n",ntuple)); I1nexpocv.push_back(getdata(i,"I1nc",ntuple)); I2nexpocv.push_back(getdata(i,"I2nc",ntuple)); I3nexpocv.push_back(getdata(i,"I3nc",ntuple)); I4nexpocv.push_back(getdata(i,"I4nc",ntuple)); I1nerrorv.push_back(getdata(i,"I1nerror",ntuple)); I2nerrorv.push_back(getdata(i,"I2nerror",ntuple)); I3nerrorv.push_back(getdata(i,"I3nerror",ntuple)); I4nerrorv.push_back(getdata(i,"I4nerror",ntuple)); I1ncerrorv.push_back(getdata(i,"I1ncerror",ntuple)); I2ncerrorv.push_back(getdata(i,"I2ncerror",ntuple)); I3ncerrorv.push_back(getdata(i,"I3ncerror",ntuple)); I4ncerrorv.push_back(getdata(i,"I4ncerror",ntuple)); } fichier1->Close(); cout<<" going through second file..."<<endl; TFile *fichier2=new TFile(secondFichier,"READ"); int N2=ntuple->GetEntries(); for (int i=0;i<N2;i++){ I1v.push_back(getdata(i,"I1",ntuple)); I2v.push_back(getdata(i,"I2",ntuple)); I3v.push_back(getdata(i,"I3",ntuple)); I4v.push_back(getdata(i,"I4",ntuple)); tp1v.push_back(getdata(i,"tp1",ntuple)); tp2v.push_back(getdata(i,"tp2",ntuple)); pressurev.push_back(getdata(i,"pressure",ntuple)); humidityv.push_back(getdata(i,"humidity",ntuple)); dateabsv.push_back(getdata(i,"dateabs",ntuple)); jour.push_back(getdata(i,"jour",ntuple)); mois.push_back(getdata(i,"mois",ntuple)); annee.push_back(getdata(i,"annee",ntuple)); E1v.push_back(getdata(i,"I1error",ntuple)); E2v.push_back(getdata(i,"I2error",ntuple)); E3v.push_back(getdata(i,"I3error",ntuple)); E4v.push_back(getdata(i,"I4error",ntuple)); I1nv.push_back(getdata(i,"I1n",ntuple)); I2nv.push_back(getdata(i,"I2n",ntuple)); I3nv.push_back(getdata(i,"I3n",ntuple)); I4nv.push_back(getdata(i,"I4n",ntuple)); I1nexpocv.push_back(getdata(i,"I1nc",ntuple)); I2nexpocv.push_back(getdata(i,"I2nc",ntuple)); I3nexpocv.push_back(getdata(i,"I3nc",ntuple)); I4nexpocv.push_back(getdata(i,"I4nc",ntuple)); I1nerrorv.push_back(getdata(i,"I1nerror",ntuple)); I2nerrorv.push_back(getdata(i,"I2nerror",ntuple)); I3nerrorv.push_back(getdata(i,"I3nerror",ntuple)); I4nerrorv.push_back(getdata(i,"I4nerror",ntuple)); I1ncerrorv.push_back(getdata(i,"I1ncerror",ntuple)); I2ncerrorv.push_back(getdata(i,"I2ncerror",ntuple)); I3ncerrorv.push_back(getdata(i,"I3ncerror",ntuple)); I4ncerrorv.push_back(getdata(i,"I4ncerror",ntuple)); } fichier2->Close(); int taille=dateabsv.size(); cout<<"The resulting size is "<<taille<<endl; cout<<"Writing the file..."<<endl; ofstream fichier(textName, ios::out | ios::trunc); if(fichier) { int N=dateabsv.size(); for (Long64_t p = 0; p < taille; p++){ fichier << jour[p] << " " << mois[p] << " " << annee[p] << " " << dateabsv[p] << " " << I1v[p] << " " << I2v[p] << " " << I3v[p] << " " << I4v[p] << " " << E1v[p] << " " << E2v[p] << " " << E3v[p] << " " << E4v[p] << " " << tp1v[p] << " " << tp2v[p] << " " << humidityv[p] << " " << pressurev[p] << " " << I1nv[p] << " " << I2nv[p] << " " << I3nv[p] << " " << I4nv[p] << " " << I1nerrorv[p] << " " << I2nerrorv[p] << " " << I3nerrorv[p] << " " << I4nerrorv[p] << " " << I1nexpocv[p] << " " << I2nexpocv[p] << " " << I3nexpocv[p] << " " << I4nexpocv[p] << " " << I1ncerrorv[p]<< " " << I2ncerrorv[p]<< " " << I3ncerrorv[p]<< " " << I4ncerrorv[p] << endl; } fichier.close(); } else cerr << "Erreur à l'ouverture !" << endl; cout << "finished" << endl;} <file_sep>#include "TAxis.h" #include "TH2.h" #include "TStyle.h" #include "TCanvas.h" #include "TNtupleD.h" #include <stdio.h> #include <stdlib.h> #include <vector.h> #include "TGraph.h" int getdata(int i, const char* dataname, TNtuple* ntuple) //méthode très utile pour accéder à la donnée i d'une branche d'un arbre { Float_t data; TBranch *dataBranch; ntuple->SetMakeClass(1); ntuple->SetBranchAddress(dataname, &data, &dataBranch);//fait pointer la branche dataBranch vers la branche dataname et data vers la case correspondante de dataBranch dataBranch->GetEntry(i); return data; } using namespace std; void Addcharge() { char fileName[256]; float ChargeOffSet=0; cout<<"Enter the name of the input root file (xxx.root) : "<<endl; cin.getline(fileName,256); cout<<"Please, enter the inital charge (C/cm2) : "<<endl; cin>>ChargeOffSet; TFile *MyFile=new TFile(fileName,"UPDATE"); int N=ntuple->GetEntries(); vector<float> accCharge1(N); vector<float> accCharge2(N); vector<float> accCharge3(N); vector<float> accCharge4(N); float sommeCharge1=0,sommeCharge2=0,sommeCharge3=0,sommeCharge4=0; sommeCharge1=ChargeOffSet; sommeCharge2=ChargeOffSet; sommeCharge3=ChargeOffSet; sommeCharge4=ChargeOffSet/15; for (int i=0;i<N;i++) { sommeCharge1=sommeCharge1-getdata(i,"I1",ntuple)*300/95; accCharge1[i]=sommeCharge1; sommeCharge2=sommeCharge2-getdata(i,"I2",ntuple)*300/95; accCharge2[i]=sommeCharge2; sommeCharge3=sommeCharge3-getdata(i,"I3",ntuple)*300/95; accCharge3[i]=sommeCharge3; sommeCharge4=sommeCharge4-getdata(i,"I4",ntuple)*300/95; accCharge4[i]=sommeCharge4; } float charge1r,charge2r,charge3r,charge4r; TBranch *newbranch1=ntuple->Branch("charge1r",&charge1r); TBranch *newbranch2=ntuple->Branch("charge2r",&charge2r); TBranch *newbranch3=ntuple->Branch("charge3r",&charge3r); TBranch *newbranch4=ntuple->Branch("charge4r",&charge4r); for (int i=0;i<N;i++) { charge1r=accCharge1[i]; charge2r=accCharge2[i]; charge3r=accCharge3[i]; charge4r=accCharge4[i]; newbranch1->Fill(); newbranch2->Fill(); newbranch3->Fill(); newbranch4->Fill(); } ntuple->Write(); } <file_sep>The files stored in this specific folder have been originally used by <NAME> for the analysis purposes of the GIF++ data. The files are stored in the repository for the historiacal and reference issues. We intent to create the new framework, that would be holding all features distributed among those files, but would be much more user friendly. <file_sep>#include "TAxis.h" #include "TH2.h" #include "TStyle.h" #include "TCanvas.h" #include "TNtupleD.h" #include <stdio.h> #include <stdlib.h> #include <vector.h> #include "TGraph.h" #include "TH1.h" #include "math.h" #include "TMultiGraph.h" #include "TGraphErrors.h" #include "tdrstyle.C" #include <sstream> using namespace std; double getdata(int i, const char* dataname, TNtuple* ntuple) { Float_t data; TBranch *dataBranch; ntuple->SetMakeClass(1); ntuple->SetBranchAddress(dataname, &data, &dataBranch); dataBranch->GetEntry(i); return data;} void powercuf(){ char name[256], name3[256],name2[256]; std::cout << "Please, enter your root file's name (fileName.root) : "<<endl; std::cin.getline (name,256); std::cout<< "Enter the name of the branch containing the current normalised you want to study : "<<endl; std::cin.getline(name3,256); std::cout<< "Enter the name of the branch that will be created after the correction : "<<endl; std::cin.getline(name2,256); TFile *MyFile=new TFile(name,"READ"); int N = ntuple->GetEntries(); cout<<"There is "<<N<<" entries"<<endl; ostringstream error; error<<name3; string errorName=error.str(); char* branchName=(errorName+"error").c_str(); TCanvas *c1=new TCanvas("Canvas1","Canvas1"); TCanvas *c2=new TCanvas("Canvas2","Canvas2"); TCanvas *c3=new TCanvas("Canvas3","Canvas3"); TCanvas *c4=new TCanvas("Canvas4","Canvas4"); TCanvas *c5=new TCanvas("Canvas5","Canvas5"); c1->SetFillColor(0); c1->SetGrid(); c2->SetFillColor(0); c2->SetGrid(); c3->SetFillColor(0); c3->SetGrid(); c4->SetFillColor(0); c4->SetGrid(); c5->SetFillColor(0); c5->SetGrid(); float *I1n,*pressure,*tp1,*date,*lnI1n,*lnpressure,*lntp1,*Ierror; I1n=(float*) malloc(sizeof(float)*N); pressure=(float*) malloc(sizeof(float)*N); tp1=(float*) malloc(sizeof(float)*N); date=(float*) malloc(sizeof(float)*N); lnI1n=(float*) malloc(sizeof(float)*N); lnpressure=(float*) malloc(sizeof(float)*N); lntp1=(float*) malloc(sizeof(float)*N); Ierror=(float*) malloc(sizeof(float)*N); for (int i=0;i<N;i++){ I1n[i]=getdata(i,name3,ntuple); pressure[i]=getdata(i,"pressure",ntuple); tp1[i]=getdata(i,"tp1",ntuple); date[i]=getdata(i,"dateabs",ntuple); lnpressure[i]=log(pressure[i]); lntp1[i]=log(tp1[i]); lnI1n[i]=log(I1n[i]); Ierror[i]=getdata(i,branchName,ntuple);} c1->cd(); TGraph *I1pressure=new TGraph(N,lnpressure,lnI1n); I1pressure->SetMarkerColor(1); I1pressure->SetMarkerSize(0); I1pressure->SetTitle("log(I1n)=f(log(pressure))"); I1pressure->GetXaxis()->SetTitle("log(pressure)"); I1pressure->GetYaxis()->SetTitle("log(Intensity)"); TFitResultPtr res1 = I1pressure->Fit("pol1","SQ"); I1pressure->Draw("AP*"); //gStyle->SetOptFit(111); float a0=res1->Value(0); float b0=res1->Value(1); c2->cd(); float *I1cp,*lnI1cp; I1cp=(float*) malloc(sizeof(float)*N); lnI1cp=(float*) malloc(sizeof(float)*N); for (int i=0;i<N;i++){ float pressureFactor=exp(a0)*pow(pressure[i],b0); I1cp[i]=I1n[i]/pressureFactor; lnI1cp[i]=log(I1cp[i]);} TGraph *I1cpt=new TGraph(N,lntp1,lnI1cp); I1cpt->SetMarkerColor(1); I1cpt->SetMarkerSize(0); I1cpt->GetXaxis()->SetTitle("log(temperature)"); I1cpt->GetYaxis()->SetTitle("log(Intensity)"); I1cpt->SetTitle("log(I1n corrected by the pressure) =f(log(temp1))"); TFitResultPtr res2 = I1cpt->Fit("pol1","SQ"); I1cpt->Draw("AP*"); float a1=res2->Value(0); float b1=res2->Value(1); c3->cd(); float *I1c,*lnI1c,*I1cerror; I1c=(float*) malloc(sizeof(float)*N); I1cerror=(float*) malloc(sizeof(float)*N); lnI1c=(float*) malloc(sizeof(float)*N); for (int i=0;i<N;i++){ float tempFactor=exp(a1)*pow(tp1[i],b1); I1c[i]=I1cp[i]/tempFactor; I1cerror[i]=Ierror[i]/(exp(a0)*pow(pressure[i],b0)*tempFactor); lnI1c[i]=log(I1c[i]);} TGraph *I1corrected=new TGraph(N,lnpressure,lnI1c); I1corrected->SetMarkerColor(1); I1corrected->SetMarkerSize(0); I1corrected->GetXaxis()->SetTitle("log(pressure)"); I1corrected->GetYaxis()->SetTitle("log(Intensity)"); I1corrected->SetTitle("log(I1n already corrected once) =f(log(pressure))"); TFitResultPtr res3 = I1corrected->Fit("pol1","SQ"); I1corrected->Draw("AP*"); float a2=res3->Value(0); float b2=res3->Value(1); c4->cd(); float *I1cc,*lnI1cc,*I1ccerror;; I1cc=(float*) malloc (sizeof(float)*N); I1ccerror=(float*) malloc (sizeof(float)*N); lnI1cc=(float*) malloc (sizeof(float)*N); for (int i=0;i<N;i++){ I1cc[i]=I1c[i]/(exp(a2)*pow(pressure[i],b2)); lnI1cc[i]=log(I1cc[i]); I1ccerror[i]=I1cerror[i]/(exp(a2)*pow(pressure[i],b2));} TGraph *I1blue=new TGraph(N,lntp1,lnI1cc); I1blue->SetMarkerSize(0); I1blue->SetMarkerColor(1); I1blue->GetXaxis()->SetTitle("log(temperature)"); I1blue->GetYaxis()->SetTitle("log(intensity)"); I1blue->SetTitle("log(I1n after fine correction) =f(log(temp1))"); TFitResultPtr res4=I1blue->Fit("pol1","SQ"); I1blue->Draw("AP*"); float a3=res4->Value(0); float b3=res4->Value(1); float *I1ccc,*I1cccerror; I1ccc=(float*)malloc(sizeof(float)*N); I1cccerror=(float*)malloc(sizeof(float)*N); for (int i=0;i<N;i++){ I1ccc[i]=I1cc[i]/(exp(a3)*pow(tp1[i],b3)); I1cccerror[i]=I1ccerror[i]/(exp(a3)*pow(tp1[i],b3));} c5->cd(); //gStyle->SetOptStat(0); TMultiGraph *final=new TMultiGraph(); TGraphErrors *gr2=new TGraphErrors(N,date,I1n,0,0);//Remplacer le second zéro par Ierror gr2->SetMarkerColor(2); gr2->SetMarkerSize(0.3); gr2->SetMarkerStyle(20); gr2->SetLineColor(2); TGraphErrors *gr3=new TGraphErrors(N,date,I1c,0,0);//Remplacer le second zéro par I1cerror gr3->SetMarkerColor(1); gr3->SetMarkerSize(0.3); gr3->SetMarkerStyle(20); gr3->SetLineColor(1); //TGraphErrors *gr5=new TGraphErrors(N,date,I1ccc,0,0);//Remplacer le second zéro par I1cccerror //gr5->SetMarkerColor(1); //gr5->SetMarkerSize(0.5); //gr5->SetMarkerStyle(33); //gr5->SetLineColor(1); final->SetTitle("GE1/1 readout current I_{1} vs Time"); final->Add(gr2); final->Add(gr3); //final->Add(gr5); final->Draw("AP"); leg = new TLegend(0.1,0.7,0.48,0.9); //leg->SetHeader("Legends"); leg->AddEntry(gr2,"I_{1} without correction","p"); leg->AddEntry(gr3,"I_{1} corrected","p"); //leg->AddEntry(gr5,"I_{1} corrected twice","p"); final->GetXaxis()->SetTitle("Time [min]"); final->GetYaxis()->SetTitle("Intensity [a.u]"); leg->Draw("P"); ostringstream ss3; ss3<<name3; string nameImage=ss3.str(); char* image=("./"+nameImage+"powercorrectedpt.jpg").c_str(); //c5->SaveAs(image); MyFile->Close(); ostringstream o; o<<name2; char* namebranch2=(o.str()+"error").c_str(); TFile *MyFile2=new TFile(name,"UPDATE"); float Ifinale,errorFinale; cout << "mane is :" << name2 << endl; TBranch *newbranch=ntuple->Branch(name2,&Ifinale); TBranch *newbranch2=ntuple->Branch(namebranch2,&errorFinale); for (int i=0;i<N;i++){ errorFinale=I1cccerror[i]; newbranch2->Fill(); Ifinale=I1ccc[i]; newbranch->Fill(); } ntuple->Write(); free(date); free(pressure); free(tp1); free(I1n); free(I1cp); free(I1c); free(I1cc); free(I1ccc); free(lnI1n); free(lnpressure); free(lntp1); free(lnI1cp); free(lnI1c); free(lnI1cc); free(Ierror); free(I1cerror); free(I1ccerror); free(I1cccerror); } <file_sep>#include "TAxis.h" #include "TH2.h" #include "TStyle.h" #include "TCanvas.h" #include "TNtupleD.h" #include <stdio.h> #include <stdlib.h> #include <vector.h> #include <string> int getdata(int i, const char* dataname, TNtuple* ntuple) { Float_t data; TBranch *dataBranch; ntuple->SetMakeClass(1); ntuple->SetBranchAddress(dataname, &data, &dataBranch);//fait pointer la branche dataBranch vers la branche dataname et data vers la case correspondante de dataBranch dataBranch->GetEntry(i); return data; } using namespace std; void gifuf(){ int ncols; int nlines=0; int j, mois, a, h, m; float I1,E1,I2,E2,I3,E4,I4,E4; char fileName[256],rfileName[256]; cout << "Please, enter your input file's name (xxx.txt) : "<<endl; cin.getline (fileName,256); cout << "Enter the name you want for the output (yyy.root) : "; cin.getline (rfileName,256); TFile *MyFile = new TFile(rfileName,"RECREATE"); TNtuple *ntuple = new TNtuple("ntuple","data from ascii file","j:mois:a:h:m:I1:E1:I2:E2:I3:E3:I4:E4"); ntuple->ReadFile(fileName);//attention ce fichier doit etre obtenu après avoir supprimés les / et les : avec la fonction find and replace d'un éditeur de texte (gedit par exemple) ntuple->Write(); int N=ntuple->GetEntries(); cout<<"This file contains "<<N<<" entries"<<endl; vector<int> dates(N); vector<int> month(12); int nbjfev; month[0]=31; month[2]=31; month[3]=30; month[4]=31; month[5]=30; month[6]=31; month[7]=31; month[8]=30; month[9]=31; month[10]=30; month[11]=31; for (int i=0;i<N;i++){ int anneeactuelle=getdata(i,"a",ntuple); if (anneeactuelle==2008||anneeactuelle==2012||anneeactuelle==2016||anneeactuelle==2020||anneeactuelle==2024){nbjfev=29;} else {nbjfev=28;} month[1]=nbjfev; int somme=0; int moisactuel=getdata(i,"mois",ntuple); for (int k=2013;k<anneeactuelle;k++){somme=somme+365*24*60;} for (int j=0;j<moisactuel-1;j++){somme=somme+month[j]*24*60;} dates[i]=somme+getdata(i,"h",ntuple)*60+getdata(i,"m",ntuple)+getdata(i,"j",ntuple)*24*60; } cout<<"The beginning date of this file is : "<<dates[0]<<endl; cout<<"The end date of this file is : " <<dates[N-1]<<endl;//On vient de créer le vecteur des dates absolues en prenant la référence le 1er janvier 2013 à 00:00 on compte en minute à partir de cette date Float_t date; TBranch *newbranch =ntuple->Branch("dateabs", &date); for (Long64_t p = 0; p < N; p++){ date= dates[p]; newbranch->Fill(); }//Après avoir créé une nouvelle branche on la remplit avec les valeurs du vecteur de date ntuple->Write(); MyFile->Close();//On oublie pas de fermer le fichier } <file_sep>#include "TAxis.h" #include "TH2.h" #include "TStyle.h" #include "TCanvas.h" #include "TNtupleD.h" #include <stdio.h> #include <stdlib.h> #include <vector.h> #include "TGraph.h" int getdata(int i, const char* dataname, TNtuple* ntuple) {//méthode très utile pour accéder à la donnée i d'une branche d'un arbre Float_t data; TBranch *dataBranch; ntuple->SetMakeClass(1); ntuple->SetBranchAddress(dataname, &data, &dataBranch);//fait pointer la branche dataBranch vers la branche dataname et data vers la case correspondante de dataBranch dataBranch->GetEntry(i); return data; } using namespace std; void tempuf(){ int ncols; int nlines=0; int j, mois, a, h, m; float m1,m2,tp1,tp2,m3,m4,m5,m6,pressure,humidity,m7,m8,m9; char fileName[256],rfileName[256]; cout << "Please, enter your input file's name (xxx.txt) : "; cin.getline (fileName,256); cout << "Enter the name you want for the output (yyy.root) : "; cin.getline (rfileName,256); TFile *MyFile = new TFile(rfileName,"RECREATE");//Création d'un nouveau fichier temp.root à chaque execution du programme TNtuple *ntuple = new TNtuple("ntuple","data from ascii file","j:mois:a:h:m:m1:m2:tp1:tp2:m3:m4:m5:m6:pressure:humidity:m7:m8:m9"); ntuple->ReadFile(fileName);//lis le flux du fichier en identifiant les entiers et flottants dans l'ordre voulu dans les variables j,mois,année etc. ntuple->Write();//Les écrit dans le fichier temp.root int N=ntuple->GetEntries();//Nombre de lignes du fichiers (pas de boucle inutile) cout<<" This file contains "<<N<<" entries"<<endl; vector<int> dates(N);//initialisation d'un vecteur de dates qui va utiliser les variables j,mois,a,h,m. vector<float> press(N); vector<int> month(12); int nbjfev; month[0]=31; month[2]=31; month[3]=30; month[4]=31; month[5]=30; month[6]=31; month[7]=31; month[8]=30; month[9]=31; month[10]=30; month[11]=31; for (int i=0;i<N;i++){ int anneeactuelle=getdata(i,"a",ntuple); if (anneeactuelle==2008||anneeactuelle==2012||anneeactuelle==2016||anneeactuelle==2020||anneeactuelle==2024){nbjfev=29;} else {nbjfev=28;} month[1]=nbjfev;//Prise en compte de l'année bissextile ou pas en cours if (anneeactuelle==2013){ int moisactuel=getdata(i,"mois",ntuple); int somme=0; for (int j=0;j<moisactuel;j++){somme+=month[j]*24*60;} dates[i]=somme+getdata(i,"h",ntuple)*60+getdata(i,"m",ntuple);} else { int somme=0; int moisactuel=getdata(i,"mois",ntuple); for (int k=2013;k<anneeactuelle;k++){somme=somme+365*24*60;} for (int j=0;j<moisactuel-1;j++){somme=somme+month[j]*24*60;} dates[i]=somme+getdata(i,"h",ntuple)*60+getdata(i,"m",ntuple)+getdata(i,"j",ntuple)*24*60; }//dates absolues référence 1er janvier 2013 00:00 comptée en minute } cout<<"The beginning date of this file is : "<<dates[0]<<endl; cout<<"The end date of this file is : "<<dates[N-1]<<endl; Float_t date; TBranch *newbranch = ntuple->Branch("dateabs", &date); for (Long64_t p = 0; p < N; p++){ date= dates[p]; newbranch->Fill(); }//Après avoir créé une nouvelle branche on la remplit avec les valeurs du vecteur de date ntuple->Write();//necessaire pour la sauvegarde de la nouvelle branche MyFile->Close(); } <file_sep>#include "TAxis.h" #include "TH2.h" #include "TStyle.h" #include "TCanvas.h" #include "TNtupleD.h" #include <stdio.h> #include <stdlib.h> #include <vector.h> #include <algorithm> #include <iostream> #include "math.h" #include <string> using namespace std; float getdata(int i, const char* dataname, TNtuple* ntuple) { Float_t data; TBranch *dataBranch; ntuple->SetMakeClass(1); ntuple->SetBranchAddress(dataname, &data, &dataBranch); dataBranch->GetEntry(i); return data;} void normalisationuf (){ char fileName[256]; string current; int N1; float Ref=1; cout << "Please, enter your root file's name (fileName.root) : "; cin.getline (fileName,256); cout<<"This program will calculate the mean of the first N measurements and use it to normalise the current, please enter the integer N :"<<endl; cin>>N1; cout<<"Please, enter the reference number for normalization :"<<endl; cin>>Ref; TFile *MyFile=new TFile(fileName,"UPDATE"); int N=ntuple->GetEntries(); float sommeI1=0,sommeI2=0,sommeI3=0,sommeI4=0; float meanI1,meanI2,meanI3,meanI4; for (int i=0;i<N1;i++){ sommeI1=sommeI1+getdata(i,"I1",ntuple); sommeI2=sommeI2+getdata(i,"I2",ntuple); sommeI3=sommeI3+getdata(i,"I3",ntuple); sommeI4=sommeI4+getdata(i,"I4",ntuple); } meanI1=sommeI1/(N1*Ref); meanI2=sommeI2/(N1*Ref); meanI3=sommeI3/(N1*Ref); meanI4=sommeI4/(N1*Ref); float I1n,I2n,I3n,I4n; float I1nerror,I2nerror,I3nerror,I4nerror; TBranch *newbranch1=ntuple->Branch("I1n",&I1n); TBranch *newbranch2=ntuple->Branch("I2n",&I2n); TBranch *newbranch3=ntuple->Branch("I3n",&I3n); TBranch *newbranch4=ntuple->Branch("I4n",&I4n); TBranch *newbranch5=ntuple->Branch("I1nerror",&I1nerror); TBranch *newbranch6=ntuple->Branch("I2nerror",&I1nerror); TBranch *newbranch7=ntuple->Branch("I3nerror",&I1nerror); TBranch *newbranch8=ntuple->Branch("I4nerror",&I1nerror); for (Long64_t p = 0; p < N; p++){ I1n=getdata(p,"I1",ntuple)/meanI1; I1nerror=getdata(p,"I1error",ntuple)/(-meanI1); I2n=getdata(p,"I2",ntuple)/meanI2; I2nerror=getdata(p,"I2error",ntuple)/(-meanI2); I3n=getdata(p,"I3",ntuple)/meanI3; I3nerror=getdata(p,"I3error",ntuple)/(-meanI3); I4n=getdata(p,"I4",ntuple)/meanI4; I4nerror=getdata(p,"I4error",ntuple)/(-meanI4); newbranch1->Fill(); newbranch2->Fill(); newbranch3->Fill(); newbranch4->Fill(); newbranch5->Fill(); newbranch6->Fill(); newbranch7->Fill(); newbranch8->Fill(); } ntuple->Write(); MyFile->Close();} <file_sep>#include "TAxis.h" #include "TH2.h" #include "TStyle.h" #include "TCanvas.h" #include "TNtupleD.h" #include <stdio.h> #include <stdlib.h> #include <vector.h> #include <algorithm> #include <iostream> #include "math.h" using namespace std; float getdata(int i, const char* dataname, TNtuple* ntuple) { Float_t data; TBranch *dataBranch; ntuple->SetMakeClass(1); ntuple->SetBranchAddress(dataname, &data, &dataBranch); dataBranch->GetEntry(i); return data;} void zerosuppressionuf (){ char fileName1[256],fileName2[256]; string fileName3; float N1; cout <<" Enter the name of the root file you want to modify (xxx.root) : "<<endl; cin.getline(fileName1,256); cout <<" Enter the name of the current you want to change : "<<endl; cin.getline(fileName2,256); cout <<" Enter the value of the threshold that you want in the form of a power of ten (for exemple -6 for 10^(-6)) : "<<endl; cin>>N1; cout <<" Enter the text file you want to create (yyy.txt) : "<<endl; cin>>fileName3; char* textName=fileName3.c_str(); TFile *MyFile=new TFile(fileName1,"READ"); int N=ntuple->GetEntries(); vector<float> I1v; vector<float> I2v; vector<float> I3v; vector<float> I4v; vector<float> tp1v; vector<float> tp2v; vector<float> pressurev; vector<float> humidityv; vector<float> dateabsv; vector<int> jour;//* vector<int> mois;//* vector<int> annee;//* vector<float> chargev; vector<float> I1errorv; vector<float> I2errorv; vector<float> I3errorv; vector<float> I4errorv; cout<<"The previous size was "<<N<<endl; for (int i=0;i<N;i++){ Float_t currentI=getdata(i,fileName2,ntuple); bool b=false; if (currentI>N1){b=true;} if (b==false){ I1v.push_back(getdata(i,"I1",ntuple)); tp1v.push_back(getdata(i,"tp1",ntuple)); tp2v.push_back(getdata(i,"tp2",ntuple)); pressurev.push_back(getdata(i,"pressure",ntuple)); I2v.push_back(getdata(i,"I2",ntuple)); I3v.push_back(getdata(i,"I3",ntuple)); I4v.push_back(getdata(i,"I4",ntuple)); humidityv.push_back(getdata(i,"humidity",ntuple)); dateabsv.push_back(getdata(i,"dateabs",ntuple)); jour.push_back(getdata(i,"jour",ntuple)); mois.push_back(getdata(i,"mois",ntuple)); annee.push_back(getdata(i,"annee",ntuple)); I1errorv.push_back(getdata(i,"I1error",ntuple)); I2errorv.push_back(getdata(i,"I2error",ntuple)); I3errorv.push_back(getdata(i,"I3error",ntuple)); I4errorv.push_back(getdata(i,"I4error",ntuple)); //chargev.push_back(getdata(i,"charge",ntuple)); }} MyFile->Close(); int taille=I1v.size(); cout<<"The size of the new vector Izero is "<<taille<<endl; ofstream fichier(textName, ios::out | ios::trunc); if(fichier) { int N=dateabsv.size(); for (Long64_t p = 0; p < N; p++){ fichier << jour[p] << " " << mois[p] << " " << annee[p] << " " << dateabsv[p] << " " << I1v[p] << " " << I2v[p] << " " << I3v[p] << " " << I4v[p] << " " << I1errorv[p] << " " << I2errorv[p] << " " << I3errorv[p] << " " << I4errorv[p] << " " << tp1v[p] << " " << tp2v[p] << " " << humidityv[p] << " " << pressurev[p] // << chargev[p] << " " << endl; } fichier.close(); } else cerr << "Error !" << endl; cout << "Finished !" << endl; } <file_sep>#include "TAxis.h" #include "TH2.h" #include "TStyle.h" #include "TCanvas.h" #include "TNtupleD.h" #include <stdio.h> #include <stdlib.h> #include <vector.h> using namespace std; void txtfusionuf(){ int dateabs,jour,mois,annee; float I1,I2,I3,I4,pressure,humidity,tp1,tp2,Ifinal,I1n,I1error,I2error,I3error,I4error,I1n,I2n,I3n,I4n,I1nexpoc,I2nexpoc,I3nexpoc,I4nexpoc; char fileName1[256], fileName2[256]; cout<<"First of all please check the syntaxe of your text file it must not contain any not float symbol and the measurements must be in order"<<endl; cout<<"Enter the name of the input text file (xxx.txt) : "<<endl; cin.getline(fileName1,256); cout<<"Enter the name of the output root file you want to create (yyy.root) : "<<endl; cin.getline(fileName2,256); TFile *MyFile = new TFile(fileName2,"RECREATE"); TNtuple *ntuple = new TNtuple("ntuple","data from two files","jour:mois:annee:dateabs:I1:I2:I3:I4:I1error:I2error:I3error:I4error:tp1:tp2:humidity:pressure"); ntuple->ReadFile(fileName1); ntuple->Write(); int N=ntuple->GetEntries(); cout<<"This file contains "<<N<<" entries"<<endl; MyFile->Close(); } <file_sep>#include "TAxis.h" #include "TH2.h" #include "TStyle.h" #include "TCanvas.h" #include "TNtupleD.h" #include <stdio.h> #include <stdlib.h> #include <vector.h> #include <algorithm> #include <iostream> #include "math.h" #include <string> #include <iostream> #include "Riostream.h" #include <string> #include <cstdio> #include <cstdlib> #include <fstream> #include "TTree.h" #include "TBranch.h" #include "TFrame.h" #include "TCanvas.h" #include "TPaveLabel.h" #include "TPaveText.h" #include "TFile.h" #include "TString.h" #include "TStyle.h" #include "TH1F.h" #include "TH2F.h" #include "TH1.h" #include "TF1.h" #include "TLorentzVector.h" #include "math.h" #include "time.h" #include "TRandom.h" #include "TSpectrum.h" #include "TGraph.h" #include "TMultiGraph.h" #include <algorithm> #include "tdrstyle.C" using namespace std; float getdata(int i, const char* dataname, TNtuple* ntuple) { Float_t data; TBranch *dataBranch; ntuple->SetMakeClass(1); ntuple->SetBranchAddress(dataname, &data, &dataBranch); dataBranch->GetEntry(i); return data; } void ReadDataGIF(void) { char fileName[256]; string current; float Ref=1; cout << "Please, enter your root file's name (fileName.root) : "; cin.getline (fileName,256); double *Charge1=NULL, *Charge2=NULL, *Charge3=NULL, *Charge4=NULL, *Time=NULL; double *I1n=NULL, *I2n=NULL, *I3n=NULL, *I4n=NULL, *I1nc=NULL, *I2nc=NULL, *I3nc=NULL, *I4nc=NULL; double *I1nerror=NULL, *I2nerror=NULL, *I3nerror=NULL, *I4nerror=NULL, *I1ncerror=NULL, *I2ncerror=NULL, *I3ncerror=NULL, *I4ncerror=NULL; TFile *MyFile=new TFile(fileName,"READ"); int N=ntuple->GetEntries(); Charge1 = malloc(N*sizeof(double)); Charge2 = malloc(N*sizeof(double)); Charge3 = malloc(N*sizeof(double)); Charge4 = malloc(N*sizeof(double)); Time = malloc(N*sizeof(double)); I1n = malloc(N*sizeof(double)); I2n = malloc(N*sizeof(double)); I3n = malloc(N*sizeof(double)); I4n = malloc(N*sizeof(double)); I1nc = malloc(N*sizeof(double)); I2nc = malloc(N*sizeof(double)); I3nc = malloc(N*sizeof(double)); I4nc = malloc(N*sizeof(double)); I1nerror = malloc(N*sizeof(double)); I2nerror = malloc(N*sizeof(double)); I3nerror = malloc(N*sizeof(double)); I4nerror = malloc(N*sizeof(double)); I1ncerror = malloc(N*sizeof(double)); I2ncerror = malloc(N*sizeof(double)); I3ncerror = malloc(N*sizeof(double)); I4ncerror = malloc(N*sizeof(double)); for (int i=0;i<N;i++) { Charge1[i]=getdata(i,"charge1r",ntuple); Charge2[i]=getdata(i,"charge2r",ntuple); Charge3[i]=getdata(i,"charge3r",ntuple); Charge4[i]=getdata(i,"charge4r",ntuple); Time[i]=getdata(i,"dateabs",ntuple); I1n[i]=getdata(i,"I1n",ntuple); I2n[i]=getdata(i,"I2n",ntuple); I3n[i]=getdata(i,"I3n",ntuple); I4n[i]=getdata(i,"I4n",ntuple); I1nerror[i]=getdata(i,"I1nerror",ntuple)*1E-6; I2nerror[i]=getdata(i,"I2nerror",ntuple)*1E-6; I3nerror[i]=getdata(i,"I3nerror",ntuple)*1E-6; I4nerror[i]=getdata(i,"I4nerror",ntuple)*1E-6; I1nc[i]=getdata(i,"I1nc",ntuple); I2nc[i]=getdata(i,"I2nc",ntuple); I3nc[i]=getdata(i,"I3nc",ntuple); I4nc[i]=getdata(i,"I4nc",ntuple); I1ncerror[i]=getdata(i,"I1ncerror",ntuple)*1E-6; I2ncerror[i]=getdata(i,"I2ncerror",ntuple)*1E-6; I3ncerror[i]=getdata(i,"I3ncerror",ntuple)*1E-6; I4ncerror[i]=getdata(i,"I4ncerror",ntuple)*1E-6; } MyFile->Close(); TCanvas *C1 = new TCanvas("C1","Sector 1",700,400); TCanvas *C2 = new TCanvas("C2","Sector 2",700,400); TCanvas *C3 = new TCanvas("C3","Sector 3",700,400); TCanvas *C4 = new TCanvas("C4","Sector 4",700,400); TMultiGraph *gI1=new TMultiGraph(); TGraphErrors *gI1n=new TGraphErrors(N,Charge1,I1n,0,I1nerror); TGraphErrors *gI1nc=new TGraphErrors(N,Charge1,I1nc,0,I1ncerror); TMultiGraph *gI2=new TMultiGraph(); TGraphErrors *gI2n=new TGraphErrors(N,Charge2,I2n,0,I2nerror); TGraphErrors *gI2nc=new TGraphErrors(N,Charge2,I2nc,0,I2ncerror); TMultiGraph *gI3=new TMultiGraph(); TGraphErrors *gI3n=new TGraphErrors(N,Charge3,I3n,0,I3nerror); TGraphErrors *gI3nc=new TGraphErrors(N,Charge3,I3nc,0,I3ncerror); TMultiGraph *gI4=new TMultiGraph(); TGraphErrors *gI4n=new TGraphErrors(N,Charge4,I4n,0,I4nerror); TGraphErrors *gI4nc=new TGraphErrors(N,Charge4,I4nc,0,I4ncerror); C1->cd()->SetLogy(0); C1->SetGrid(); C1->cd(); gI1n->SetMarkerStyle(20); gI1n->SetMarkerColor(2); gI1n->SetMarkerSize(0.3); gI1n->SetLineColor(46); gI1n->SetFillColor(2); gI1n->GetYaxis()->SetRangeUser(0,2); gI1nc->SetMarkerStyle(20); gI1nc->SetMarkerColor(1); gI1nc->SetMarkerSize(0.3); gI1nc->SetLineColor(15); gI1nc->SetFillColor(1); gI1nc->GetYaxis()->SetRangeUser(0,2); gI1->Add(gI1n); gI1->Add(gI1nc); gI1->SetTitle("Sector 1 : Normalized and Corrected Gain;Accumulated Charge [C/cm^{2}];Normalized Gain [a.u];"); gI1->Draw("A3"); gI1->Draw("PX"); TLegend *legendI1 = new TLegend(0.1,0.7,0.48,0.9); legendI1->AddEntry(gI1n,"Norm. only","f"); legendI1->AddEntry(gI1nc," Norm. and Corrected","f"); legendI1->Draw(); C2->cd()->SetLogy(0); C2->SetGrid(); C2->cd(); gI2n->SetMarkerStyle(20); gI2n->SetMarkerColor(2); gI2n->SetMarkerSize(0.3); gI2n->SetLineColor(46); gI2n->SetFillColor(2); gI2n->GetYaxis()->SetRangeUser(0,2); gI2nc->SetMarkerStyle(20); gI2nc->SetMarkerColor(1); gI2nc->SetMarkerSize(0.3); gI2nc->SetLineColor(15); gI2nc->SetFillColor(1); gI2nc->GetYaxis()->SetRangeUser(0,2); gI2->Add(gI2n); gI2->Add(gI2nc); gI2->SetTitle("Sector 2 : Normalized and Corrected Gain;Accumulated Charge [C/cm^{2}];Normalized Gain [a.u];"); gI2->Draw("A3"); gI2->Draw("PX"); TLegend *legendI2 = new TLegend(0.1,0.7,0.48,0.9); legendI2->AddEntry(gI2n,"Norm. only","f"); legendI2->AddEntry(gI2nc," Norm. and Corrected","f"); legendI2->Draw(); C3->cd()->SetLogy(0); C3->SetGrid(); C3->cd(); gI3n->SetMarkerStyle(20); gI3n->SetMarkerColor(2); gI3n->SetMarkerSize(0.3); gI3n->SetLineColor(46); gI3n->SetFillColor(2); gI3n->GetYaxis()->SetRangeUser(0,2); gI3nc->SetMarkerStyle(20); gI3nc->SetMarkerColor(1); gI3nc->SetMarkerSize(0.3); gI3nc->SetLineColor(15); gI3nc->SetFillColor(1); gI3nc->GetYaxis()->SetRangeUser(0,2); gI3->Add(gI3n); gI3->Add(gI3nc); gI3->SetTitle("Sector 3 : Normalized and Corrected Gain;Accumulated Charge [C/cm^{2}];Normalized Gain [a.u];"); gI3->Draw("A3"); gI3->Draw("PX"); TLegend *legendI3 = new TLegend(0.1,0.7,0.48,0.9); legendI3->AddEntry(gI3n,"Norm. only","f"); legendI3->AddEntry(gI3nc," Norm. and Corrected","f"); legendI3->Draw(); C4->cd()->SetLogy(0); C4->SetGrid(); C4->cd(); gI4n->SetMarkerStyle(20); gI4n->SetMarkerColor(2); gI4n->SetMarkerSize(0.3); gI4n->SetLineColor(46); gI4n->SetFillColor(2); gI4n->GetYaxis()->SetRangeUser(0,2); gI4nc->SetMarkerStyle(20); gI4nc->SetMarkerColor(1); gI4nc->SetMarkerSize(0.3); gI4nc->SetLineColor(15); gI4nc->SetFillColor(1); gI4nc->GetYaxis()->SetRangeUser(0,2); gI4->Add(gI4n); gI4->Add(gI4nc); gI4->SetTitle("Sector 4 : Normalized and Corrected Gain;Accumulated Charge [C/cm^{2}];Normalized Gain [a.u];"); gI4->Draw("A3"); gI4->Draw("PX"); TLegend *legendI4 = new TLegend(0.1,0.7,0.48,0.9); legendI4->AddEntry(gI4n,"Norm. only","f"); legendI4->AddEntry(gI4nc," Norm. and Corrected","f"); legendI4->Draw(); free(Charge1); free(Charge2); free(Charge3); free(Charge4); free(Time); free(I1n); free(I2n); free(I3n); free(I4n); free(I1nc); free(I2nc); free(I3nc); free(I4nc); free(I1nerror); free(I2nerror); free(I3nerror); free(I4nerror); free(I1ncerror); free(I2ncerror); free(I3ncerror); free(I4ncerror); return(0); } <file_sep>#include "TAxis.h" #include "TH2.h" #include "TStyle.h" #include "TCanvas.h" #include "TNtupleD.h" #include <stdio.h> #include <stdlib.h> #include <vector.h> #include <algorithm> #include <iostream> #include<string> using namespace std; float getdata(int i, const char* dataname, TNtuple* ntuple) { Float_t data; TBranch *dataBranch; ntuple->SetMakeClass(1); ntuple->SetBranchAddress(dataname, &data, &dataBranch); dataBranch->GetEntry(i); return data; } void fusionuf(){ char fileName1[256],fileName2[256]; string fileName3; cout << "Please, enter the TEMPERATURE file's name (x1x1x1.root) : "; cin.getline (fileName1,256); cout << "Please, enter the GIF file's name (x2x2x2.root) : "; cin.getline (fileName2,256); cout << "Enter the name of the output text file you want to create (yyy.txt) : "; cin>>fileName3; char* textName=fileName3.c_str(); cout << "Reading of the number of entries and the start/end dates of the first file.. " << endl; // On récupère les données de temps.root pour comparaison // Pour s'en servir plus tard TFile *fTemp = new TFile(fileName1,"READ"); int N1 = ntuple->GetEntries(); int dateTempBegin = getdata(0, "dateabs", ntuple); int dateTempEnd = getdata(N1-1, "dateabs", ntuple); fTemp->Close(); cout <<"Reading of the number of entries and the start/end dates of the second file.. " << endl; // On récupère les données de gif2.root pour comparaison TFile *fGif= new TFile(fileName2,"READ"); int N2 = ntuple->GetEntries(); int dateGifBegin = getdata(0, "dateabs",ntuple); int dateGifEnd = getdata(N2-1,"dateabs",ntuple); // A présent on compare les dates de données de Gif2 int indexStartOfGif = 0; // Cas d'arrêt du programme if(dateGifEnd < dateTempBegin) { cout << "Impossible fusion.." << endl; return; } // Intersection : recupérer les limites du tableau final int tailleMaxFinal = min(N1,N2); for (int i = 0; i < tailleMaxFinal; i++){ int currentDateOfGif = getdata(i,"dateabs",ntuple); if (currentDateOfGif <= dateTempBegin) indexStartOfGif = i; else break; } fGif->Close(); // A présent on stocke tout le fichier temps pour fusionner les intersections TFile *fTemp =new TFile(fileName1,"READ"); vector<float> tp1vi; vector<float> tp2vi; vector<float> pressurevi; vector<float> humidityvi; vector<int> dateabsvi; cout << "Storage of temp.root file.." << endl; for(int i = 0; i < N1; i++){ dateabsvi.push_back(getdata(i,"dateabs",ntuple)); pressurevi.push_back(getdata(i,"pressure",ntuple)); humidityvi.push_back(getdata(i,"humidity",ntuple)); tp1vi.push_back(getdata(i,"tp1",ntuple)); tp2vi.push_back(getdata(i,"tp2",ntuple)); } fTemp->Close(); cout << "Comparison of the two files (this may take a while).." << endl; // On stocke le premier fichier temp dans la mémoire à partir de la première ligne // de la coincidence car on ne peut pas ouvrir deux fichiers root en même temps TFile *fGif = new TFile(fileName2,"READ"); vector<float> I1v; vector<float> I2v; vector<float> I3v; vector<float> I4v; vector<float> tp1v; vector<float> tp2v; vector<float> pressurev; vector<float> humidityv; vector<int> dateabsv; vector<int> jour;//* vector<int> mois;//* vector<int> annee;//* vector<float> E1v; vector<float> E2v; vector<float> E3v; vector<float> E4v; int nbTotalOccurence = 0; for (int k = indexStartOfGif, u = 0; k < tailleMaxFinal; k++){ if(currentDateOfGif > dateabsvi[N1-1]) break; int currentDateOfGif = getdata(k,"dateabs",ntuple); float I1vi = getdata(k,"I1",ntuple); float I2vi = getdata(k,"I2",ntuple); float I3vi = getdata(k,"I3",ntuple); float I4vi = getdata(k,"I4",ntuple); float E1vi=getdata(k,"E1",ntuple); float E2vi=getdata(k,"E2",ntuple); float E3vi=getdata(k,"E3",ntuple); float E4vi=getdata(k,"E4",ntuple); while(currentDateOfGif >= dateabsvi[u]) { if (currentDateOfGif == dateabsvi[u]){ dateabsv.push_back(dateabsvi[u]); pressurev.push_back(pressurevi[u]); humidityv.push_back(humidityvi[u]); tp1v.push_back(tp1vi[u]); tp2v.push_back(tp2vi[u]); I1v.push_back(I1vi); I2v.push_back(I2vi); I3v.push_back(I3vi); I4v.push_back(I4vi); E1v.push_back(E1vi); E2v.push_back(E2vi); E3v.push_back(E3vi); E4v.push_back(E4vi); jour.push_back(getdata(k,"j",ntuple));//* mois.push_back(getdata(k,"mois",ntuple));//* annee.push_back(getdata(k,"a",ntuple));//* nbTotalOccurence++; break; } u++; } } cout << "I found " << nbTotalOccurence << " coincidences" << endl; fGif->Close(); cout << "Creation of the output text file.." << endl; // On sauvegarde les resultats dans un fichier txt ofstream fichier(textName, ios::out | ios::trunc); if(fichier) { int N=dateabsv.size(); for (Long64_t p = 0; p < N; p++){ fichier << jour[p] << " "//J'ai décidé de garder jour mois et année car la reconversion dateabs vers jour/mois/anne est << mois[p] << " "//non triviale et prendrait beaucoup de temps inutilement (dans moy.cpp par exemple on a << annee[p] << " "//besoin du jour courant)mais cela dépend de l'utilisateur (cela ralentit un peu le programme) << dateabsv[p] << " "//si besoin est supprimez toutes les lignes marquées * plus celles là << I1v[p] << " " << I2v[p] << " " << I3v[p] << " " << I4v[p] << " " << E1v[p] << " " << E2v[p] << " " << E3v[p] << " " << E4v[p] << " " << tp1v[p] << " " << tp2v[p] << " " << humidityv[p] << " " << pressurev[p] << endl; } fichier.close(); } else cerr << "Error " << endl; cout << "finished" << endl; } <file_sep>#include "TAxis.h" #include "TH2.h" #include "TStyle.h" #include "TCanvas.h" #include "TNtupleD.h" #include <stdio.h> #include <stdlib.h> #include <vector.h> #include "TGraph.h" #include "math.h" #include <string> int getdata(int i, const char* dataname, TNtuple* ntuple) {//méthode très utile pour accéder à la donnée i d'une branche d'un arbre Float_t data; TBranch *dataBranch; ntuple->SetMakeClass(1); ntuple->SetBranchAddress(dataname, &data, &dataBranch);//fait pointer la branche dataBranch vers la branche dataname et data vers la case correspondante de dataBranch dataBranch->GetEntry(i); return data; } using namespace std; void moyuf(){ char fileName1[256]; string fileName2; int N1; cout<<"Enter the name of the input root file (xxx.root) : "; cin.getline(fileName1,256); cout<<"Enter the number of measurements you want to take the mean from: "; cin>>N1; cout<<"Enter the name of the output text file (yyy.txt) : "; cin>>fileName2; char* textName=fileName2.c_str(); TFile *MyFile=new TFile(fileName1,"READ"); int N=ntuple->GetEntries(); cout<<"There were "<<N<<" entries"<<endl; vector<float> I1v; vector<float> I2v; vector<float> I3v; vector<float> I4v; vector<float> tp1v; vector<float> tp2v; vector<float> pressurev; vector<float> humidityv; vector<float> dateabsv; vector<int> days; int u=1; float sommeerror1=0; float sommeerror2=0; float sommeerror3=0; float sommeerror4=0; float sommetp1=0; float sommetp2=0; float sommeI1=0; float sommeI2=0; float sommeI3=0; float sommeI4=0; float sommepressure=0; float sommehumidity=0; int sommedateabs=0; vector<float> E1v; vector<float> E2v; vector<float> E3v; vector<float> E4v; /*vector<float> I1errorv; vector<float> I2errorv; vector<float> I3errorv; vector<float> I4errorv; vector<float> humidityerrorv; vector<float> pressureerrorv; vector<float> tp1errorv; vector<float> tp2errorv; float I1error=0; float I2error=0; float I3error=0; float I4error=0; float pressureerror=0; float humidityerror=0; float tp1error=0; float tp2error=0; int pday=0;*/ for (int i=0;i<N;i++){ if (u<N1){ sommeI1=sommeI1+getdata(i,"I1",ntuple); sommeI2=sommeI2+getdata(i,"I2",ntuple); sommeI3=sommeI3+getdata(i,"I3",ntuple); sommeI4=sommeI4+getdata(i,"I4",ntuple); sommepressure=sommepressure+getdata(i,"pressure",ntuple); sommehumidity=sommehumidity+getdata(i,"humidity",ntuple); sommetp1=sommetp1+getdata(i,"tp1",ntuple); sommetp2=sommetp2+getdata(i,"tp2",ntuple); sommedateabs=sommedateabs+getdata(i,"dateabs",ntuple); sommeerror1=sommeerror1+getdata(i,"I1error",ntuple); sommeerror2=sommeerror2+getdata(i,"I2error",ntuple); sommeerror3=sommeerror3+getdata(i,"I3error",ntuple); sommeerror4=sommeerror4+getdata(i,"I4error",ntuple); u++;} else if (i==N1-1){ I1v.push_back(sommeI1/u); I2v.push_back(sommeI2/u); I3v.push_back(sommeI3/u); I4v.push_back(sommeI4/u); tp1v.push_back(sommetp1/u); tp2v.push_back(sommetp2/u); pressurev.push_back(sommepressure/u); humidityv.push_back(sommehumidity/u); dateabsv.push_back(sommedateabs/u); E1v.push_back(sommeerror1/u); E2v.push_back(sommeerror2/u); E3v.push_back(sommeerror3/u); E4v.push_back(sommeerror4/u);} else { I1v.push_back(sommeI1/N1); I2v.push_back(sommeI2/N1); I3v.push_back(sommeI3/N1); I4v.push_back(sommeI4/N1); tp1v.push_back(sommetp1/N1); tp2v.push_back(sommetp2/N1); pressurev.push_back(sommepressure/N1); humidityv.push_back(sommehumidity/N1); dateabsv.push_back(sommedateabs/N1); E1v.push_back(sommeerror1/N1); E2v.push_back(sommeerror2/N1); E3v.push_back(sommeerror3/N1); E4v.push_back(sommeerror4/N1); u=1; sommeI1=getdata(i,"I1",ntuple); sommeI2=getdata(i,"I2",ntuple); sommeI3=getdata(i,"I3",ntuple); sommeI4=getdata(i,"I4",ntuple); sommepressure=getdata(i,"pressure",ntuple); sommehumidity=getdata(i,"humidity",ntuple); sommetp1=getdata(i,"tp1",ntuple); sommetp2=getdata(i,"tp2",ntuple); sommedateabs=getdata(i,"dateabs",ntuple); sommeerror1=getdata(i,"I1error",ntuple); sommeerror2=getdata(i,"I2error",ntuple); sommeerror3=getdata(i,"I3error",ntuple); sommeerror4=getdata(i,"I4error",ntuple);}} int taille=dateabsv.size(); cout<<"the new size is "<<taille<<endl; ofstream fichier(textName, ios::out | ios::trunc); if(fichier) { int N=dateabsv.size(); for (Long64_t p = 0; p < taille; p++){ fichier << dateabsv[p] << " " << I1v[p] << " " //<< I1errorv[p] << " " << I2v[p] << " " //<< I2errorv[p] << " " << I3v[p] << " " //<< I3errorv[p] << " " << I4v[p] << " " //<< I4errorv[p] << " " << E1v[p] << " " << E2v[p] << " " << E3v[p] << " " << E4v[p] << " " << tp1v[p] << " " //<< tp1errorv[p] << " " << tp2v[p] << " " //<< tp2errorv[p] << " " << humidityv[p] << " " //<< humidityerrorv[p] << " " << pressurev[p] //<< pressureerrorv[p] << " " << endl; } fichier.close(); } else cerr << "Error" << endl; cout << "finished" << endl;}
66ca8bc1a1c01022b578330236b9a6dd9a5da87c
[ "Text", "C++" ]
12
C++
mgruchala/CMS_GEM_GIF-_Analysis_Framework
3c4357c7c4390a972a45f45be49a5d2a22b26032
7da0bd06d2da8a10dd94a44e0820bbbcb515d6d5
refs/heads/master
<file_sep># Galancar Galancar es una aplicación de escritorio escrita en Java, que tiene cómo finalidad el facilitar los desplazamientos a través de la provincia de Ciudad Real. <file_sep>package galancar; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.io.*; import java.util.*; import javax.swing.JOptionPane; import java.sql.*; public class fichero { public Statement stmt = null; public ResultSet rs = null; public Connection conect; public fichero() { try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection conect = DriverManager.getConnection("jdbc:mysql://localhost:3307/galancar?user=root&password=" + "&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC"); String ruta = JOptionPane.showInputDialog("Introduce la ruta donde tienes el fichero a ejecutar: "); FileReader fr = new FileReader(ruta); BufferedReader br = new BufferedReader(fr); String linea; while ((linea = br.readLine()) != null) { System.out.println(linea); String sql = (linea); stmt = conect.createStatement(); stmt.executeUpdate(sql); } } catch (Exception ex) { ex.printStackTrace(); System.out.println(ex.getMessage()); } } public static void main(String[] args) { fichero iniciador = new fichero(); } } <file_sep>-- Creación base de datos create database galancar; use galancar; -- Creación de tablas -- Tabla usuario CREATE TABLE usuario ( dni_usuario VARCHAR(30) PRIMARY KEY NOT NULL, nombre VARCHAR(50) NOT NULL, apellidos VARCHAR(50) NOT NULL, contrasena varchar(50) NOT NULL, fecha_nacimiento DATE, provincia VARCHAR(50) NOT NULL, localidad VARCHAR(50) NOT NULL, movil INT(9) NOT NULL, email VARCHAR(50) NOT NULL ); CREATE TABLE localidad ( id_localidad INT PRIMARY KEY NOT NULL, nombre_localidad VARCHAR(20) NOT NULL ); CREATE TABLE viajes ( id_viaje INT PRIMARY KEY NOT NULL AUTO_INCREMENT, dni_conductor VARCHAR(30) NOT NULL, id_origen INT NOT NULL, id_destino INT NOT NULL, plazas_disponibles INT(1) NOT NULL, FOREIGN KEY (dni_conductor) REFERENCES usuario (dni_usuario) ON DELETE CASCADE ON UPDATE CASCADE, FOREIGN KEY (id_origen) REFERENCES localidad (id_localidad) ON DELETE CASCADE ON UPDATE CASCADE, FOREIGN KEY (id_destino) REFERENCES localidad (id_localidad) ON DELETE CASCADE ON UPDATE CASCADE ); CREATE TABLE pasajero_viaje ( id_viaje INT(11) NOT NULL, dni_pasajero VARCHAR(30) NOT NULL, PRIMARY KEY(id_viaje, dni_pasajero), FOREIGN KEY (id_viaje) REFERENCES viajes (id_viaje) ON DELETE CASCADE ON UPDATE CASCADE, FOREIGN KEY (dni_pasajero) REFERENCES usuario (dni_usuario) ON DELETE CASCADE ON UPDATE CASCADE ); insert into localidad values (1, 'Ciudad Real'); insert into localidad values (2, 'Puertollano'); insert into localidad values (3, 'Tomelloso'); insert into localidad values (4, 'Alcázar De San Juan'); insert into localidad values (5, 'Valdepeñas'); insert into localidad values (6, 'La Solana'); insert into localidad values (7, 'Membrilla'); insert into localidad values (8, 'San Carlos Del Valle'); insert into localidad values (9, 'Daimiel'); insert into localidad values (10, 'Miguelturra'); insert into localidad values (11, 'Herencia'); insert into localidad values (12, 'Alhambra'); insert into localidad values (13, 'Almagro'); insert into localidad values (14, 'Sotuélamos'); insert into localidad values (15, 'Malagon'); insert into localidad values (16, '<NAME>'); insert into localidad values (17, 'Campo de Criptana'); insert into localidad values (18, 'Almadén'); insert into localidad values (19, 'Pozo De La Serna'); insert into localidad values (20, 'Argamasilla De Alba'); -- Triggers CREATE DEFINER=`root`@`localhost` TRIGGER `pasajero_viaje_AFTER_INSERT` AFTER INSERT ON `pasajero_viaje` FOR EACH ROW BEGIN update viajes set plazas_disponibles = plazas_disponibles - 1 where id_viaje=new.id_viaje; END CREATE DEFINER=`root`@`localhost` TRIGGER `pasajero_viaje_AFTER_DELETE` AFTER DELETE ON `pasajero_viaje` FOR EACH ROW BEGIN update viajes set plazas_disponibles = plazas_disponibles + 1 where id_viaje=old.id_viaje; END
f7fce45ee372d047dd0d11407ce596b172635829
[ "Markdown", "Java", "SQL" ]
3
Markdown
ttomasperez/galancar
8695d885c09e3b354aca7b9a0e8d433a8581de39
24914be1012f881abf9e7c335f9f71c93f0f7299
refs/heads/master
<repo_name>BeamzDream/Instagram<file_sep>/app/src/main/java/flicks/codepath/instagram/fragment/ProfileFragment.java package flicks.codepath.instagram.fragment; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.content.FileProvider; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.parse.FindCallback; import com.parse.ParseException; import com.parse.ParseFile; import com.parse.ParseUser; import java.io.File; import java.util.ArrayList; import java.util.List; import flicks.codepath.instagram.MainActivity; import flicks.codepath.instagram.ProfileAdapter; import flicks.codepath.instagram.R; import flicks.codepath.instagram.model.Post; import jp.wasabeef.glide.transformations.RoundedCornersTransformation; import static android.app.Activity.RESULT_OK; import static flicks.codepath.instagram.fragment.ComposeFragment.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE; //import java.io.File; public class ProfileFragment extends Fragment { private ImageView ivProfilePicture; private Button btnLogOut; private Button btnViewPosts; private TextView tvBio; private TextView tvUserName; public String photoFileName = "photo.jpg"; private File photoFile; public final String APP_TAG = "ProfileTag"; ParseUser currentUser; RecyclerView rvPost; ArrayList<Post> tPosts; ProfileAdapter tAdapter; boolean mFirstLoad; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { currentUser = ParseUser.getCurrentUser(); return inflater.inflate(R.layout.activity_profile_fragment, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ivProfilePicture = view.findViewById(R.id.ivProfilePicture); btnLogOut = view.findViewById(R.id.btnLogOut); tvBio = view.findViewById(R.id.tvBio); tvUserName = view.findViewById(R.id.tvUsername); btnViewPosts = view.findViewById(R.id.btnViewPosts); /* btnViewPosts.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getContext(), UserPost.class); startActivity(intent); } });*/ Log.d("Profile", currentUser.toString()); tvUserName.setText(currentUser.getUsername()); tvBio.setText(currentUser.getString("bio")); Glide.with(getContext()) .load(currentUser.getParseFile("profilepic").getUrl()) .bitmapTransform(new RoundedCornersTransformation(getContext(), 10, 10)) .into(ivProfilePicture); tPosts = new ArrayList<>(); // find the recycler view rvPost = (RecyclerView) view.findViewById(R.id.rvProfile); tAdapter = new ProfileAdapter(getContext(), tPosts); rvPost.setAdapter(tAdapter); // associate the LayoutManager with the RecylcerView final GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 3); rvPost.setLayoutManager(gridLayoutManager); populateTimeline(); btnLogOut.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ParseUser.logOut(); ParseUser currentUser = ParseUser.getCurrentUser(); final Intent intent = new Intent(getContext(), MainActivity.class); startActivity(intent); } }); ivProfilePicture.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { LaunchCamera(); } }); } public void LaunchCamera() { // create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // Create a File reference to access to future access photoFile = getPhotoFileUri(photoFileName); // wrap File object into a content provider // required for API >= 24 // See https://guides.codepath.com/android/Sharing-Content-with-Intents#sharing-files-with-api-24-or-higher Uri fileProvider = FileProvider.getUriForFile(getContext(), "com.codepath.fileprovider", photoFile); intent.putExtra(MediaStore.EXTRA_OUTPUT, fileProvider); // If you call startActivityForResult() using an intent that no app can handle, your app will crash. // So as long as the result is not null, it's safe to use the intent. if (intent.resolveActivity(getContext().getPackageManager()) != null) { // Start the image capture intent to take photo startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE); } } // Returns the File for a photo stored on disk given the fileName public File getPhotoFileUri(String fileName) { // Get safe storage directory for photos // Use `getExternalFilesDir` on Context to access package-specific directories. // This way, we don't need to request external read/write runtime permissions. File mediaStorageDir = new File(getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES), APP_TAG); // Create the storage directory if it does not exist if (!mediaStorageDir.exists() && !mediaStorageDir.mkdirs()){ Log.d(APP_TAG, "failed to create directory"); } // Return the file target for the photo based on filename File file = new File(mediaStorageDir.getPath() + File.separator + fileName); return file; } @Override public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) { if (resultCode == RESULT_OK) { // by this point we have the camera photo on disk Bitmap takenImage = BitmapFactory.decodeFile(photoFile.getAbsolutePath()); // RESIZE BITMAP, see section below // Load the taken image into a preview ivProfilePicture.setImageBitmap(takenImage); currentUser.put("profilepic", new ParseFile(photoFile)); currentUser.saveInBackground(); } else { // Result was a failure Toast.makeText(getContext(), "Picture wasn't taken!", Toast.LENGTH_SHORT).show(); } } } protected void populateTimeline() { final Post.Query postQuery = new Post.Query(); postQuery.getTop().withUser(); postQuery.orderByDescending("createdAt"); postQuery.whereEqualTo(Post.KEY_USER, ParseUser.getCurrentUser()); postQuery.findInBackground(new FindCallback<Post>() { @Override public void done(List<Post> object, ParseException e) { if (e == null) { for (int i = 0; i < object.size(); i++) { Log.d("HomeActivity", "Post [" + i + "] = " + object.get(i).getDescription() + "\nusername = " + object.get(i).getUser().getUsername() + "\nimageurl = " + object.get(i).getImage()); } tPosts.clear(); tPosts.addAll(object); tAdapter.notifyDataSetChanged(); if (mFirstLoad) { rvPost.scrollToPosition(0); mFirstLoad = false; } Log.d("Timeline Activity", "Successfully loaded posts!"); } else { e.printStackTrace(); } } }); } } <file_sep>/app/src/main/java/flicks/codepath/instagram/fragment/TimelineFragment.java package flicks.codepath.instagram.fragment; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.parse.FindCallback; import com.parse.ParseException; import com.parse.ParseUser; import java.util.ArrayList; import java.util.List; import flicks.codepath.instagram.InstaAdapter; import flicks.codepath.instagram.R; import flicks.codepath.instagram.model.Post; public class TimelineFragment extends Fragment { RecyclerView rvPost; ArrayList<Post> mPosts; InstaAdapter mAdapter; boolean mFirstLoad; private SwipeRefreshLayout swipeContainer; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.activity_timeline_fragment, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); swipeContainer = (SwipeRefreshLayout) view.findViewById(R.id.swipeContainer); swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { // Your code to refresh the list here. // Make sure you call swipeContainer.setRefreshing(false) // once the network request has completed successfully. fetchTimelineAsync(); } }); swipeContainer.setColorSchemeResources(android.R.color.holo_red_light); ParseUser currentUser = ParseUser.getCurrentUser(); // Find the toolbar view inside the activity layout /*Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // Sets the Toolbar to act as the ActionBar for this Activity window. // Make sure the toolbar exists in the activity and is not null setSupportActionBar(toolbar);*/ mPosts = new ArrayList<>(); // find the recycler view rvPost = (RecyclerView) view.findViewById(R.id.rvPost); mAdapter = new InstaAdapter(getContext(), mPosts); rvPost.setAdapter(mAdapter); // associate the LayoutManager with the RecylcerView final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext()); rvPost.setLayoutManager(linearLayoutManager); populateTimeline(); } public void fetchTimelineAsync() { // Remember to CLEAR OUT old items before appending in the new ones mAdapter.clear(); // ...the data has come back, add new items to your adapter... populateTimeline(); // Now we call setRefreshing(false) to signal refresh has finished swipeContainer.setRefreshing(false); } protected void populateTimeline() { final Post.Query postQuery = new Post.Query(); postQuery.getTop().withUser(); postQuery.orderByDescending("createdAt"); postQuery.findInBackground(new FindCallback<Post>() { @Override public void done(List<Post> object, ParseException e) { if (e == null) { for (int i = 0; i < object.size(); i++) { Log.d("HomeActivity", "Post [" + i + "] = " + object.get(i).getDescription() + "\nusername = " + object.get(i).getUser().getUsername() + "\nimageurl = " + object.get(i).getImage()); } mPosts.clear(); mPosts.addAll(object); mAdapter.notifyDataSetChanged(); if (mFirstLoad) { rvPost.scrollToPosition(0); mFirstLoad = false; } Log.d("Timeline Activity", "Successfully loaded posts!"); } else { e.printStackTrace(); } } }); } } <file_sep>/app/src/main/java/flicks/codepath/instagram/InstaAdapter.java package flicks.codepath.instagram; import android.content.Context; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.text.Html; import android.text.format.DateUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.parse.SaveCallback; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.List; import java.util.Locale; import flicks.codepath.instagram.model.Post; import jp.wasabeef.glide.transformations.RoundedCornersTransformation; public class InstaAdapter extends RecyclerView.Adapter<InstaAdapter.ViewHolder> { private List<Post> mPosts; private Context mContext; public InstaAdapter(Context context, List<Post> posts) { mPosts = posts; mContext = context; } RecyclerView rvPost; private boolean click; Post post; @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { Context context = parent.getContext(); LayoutInflater inflater = LayoutInflater.from(context); View postView = inflater.inflate(R.layout.item_post, parent, false); ViewHolder viewHolder = new ViewHolder(postView); return viewHolder; } @Override public void onBindViewHolder(@NonNull final ViewHolder holder, int position) { // get data according to position post = mPosts.get(position); // populate the views according to this data holder.tvUsername.setText(post.getUser().getUsername()); String description = "<b>" + post.getUser().getUsername() + "</b> " + post.getDescription(); holder.tvBody.setText(Html.fromHtml(description)); String date = getRelativeTimeAgo(post.getCreatedAt().toString()); holder.tvDate.setText(date); holder.tvLikes.setText("Liked by Beamy and "+ post.getLikes()+" others"); Glide.with(mContext) .load(post.getUser().getParseFile("profilepic").getUrl()) .bitmapTransform(new RoundedCornersTransformation(mContext, 10, 10)) .into(holder.ivProfilePicture); /* holder.tvRetweetCount.setText(tweet.retweetCount+""); holder.tvFavCount.setText(tweet.favoriteCount+""); holder.tvScreenName.setText("@"+tweet.user.screenName); holder.tvDate.setText(tweet.createdAt);*/ /* if (tweet.imageUrl == null) { holder.ivTweetImage.setVisibility(View.GONE); } else {*/ Log.d("Adapter", post.getImage().getUrl()); Glide.with(mContext) .load(post.getImage().getUrl()) .into(holder.ivImagePost); /*Bitmap takenImage = null; Log.d("Images", "Successfully loaded" + post.getImage().toString()); try { takenImage = BitmapFactory.decodeFile(post.getImage().getFile().getPath()); System.out.println(takenImage); } catch (ParseException e) { e.printStackTrace(); } holder.ivImagePost.setImageBitmap(takenImage);*/ // RESIZE BITMAP, see section below // Load the taken image into a preview /*holder.ivTweetImage.setVisibility(View.VISIBLE);*/ /* Glide.with(context) .load(tweet.user.profileImageUrl) .bitmapTransform(new RoundedCornersTransformation(context, 60, 0)) .into(holder.ivProfileImage);*/ } // getRelativeTimeAgo("Mon Apr 01 21:16:23 +0000 2014"); public static String getRelativeTimeAgo(String rawJsonDate) { String twitterFormat = "EEE MMM dd HH:mm:ss ZZZZZ yyyy"; SimpleDateFormat sf = new SimpleDateFormat(twitterFormat, Locale.ENGLISH); sf.setLenient(true); String relativeDate = ""; try { long dateMillis = sf.parse(rawJsonDate).getTime(); relativeDate = DateUtils.getRelativeTimeSpanString(dateMillis, System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS).toString(); } catch (ParseException e) { e.printStackTrace(); } return relativeDate; } @Override public int getItemCount() { return mPosts.size(); } // for each row, inflate the alyout and cache references intop view public void clear() { mPosts.clear(); notifyDataSetChanged(); } // Add a list of items -- change to type used public void addAll(List<Post> list) { mPosts.addAll(list); notifyDataSetChanged(); } // create the viewholder class public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{ public TextView tvUsername; public TextView tvBody; public TextView tvDate; public ImageView ivImagePost; public ImageView ivLike; public TextView tvLikes; public TextView tvComments; public ImageView ivProfilePicture; public ImageView ivSave; public ImageView ivComment; public boolean clickSave; public boolean clickLike; public ViewHolder(View itemView) { super(itemView); // perform findview /*ivProfileImage = (ImageView) itemView.findViewById(R.id.ivProfileImage);*/ tvUsername = (TextView) itemView.findViewById(R.id.tvUsername); tvBody = (TextView) itemView.findViewById(R.id.tvDescription); ivImagePost = itemView.findViewById(R.id.ivImagePost); ivLike = itemView.findViewById(R.id.ivHeart); ivProfilePicture = itemView.findViewById(R.id.ivProfilePicture); ivSave = itemView.findViewById(R.id.ivSave); tvDate = itemView.findViewById(R.id.tvTime); ivComment = itemView.findViewById(R.id.ivComment); tvLikes = itemView.findViewById(R.id.tvLikes); tvComments = itemView.findViewById(R.id.tvComments); clickSave = false; clickLike = false; ivSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!clickSave){ ivSave.setImageResource(R.drawable.ic_insta_save_true); } else { ivSave.setImageResource(R.drawable.ic_insta_save); } clickSave = !clickSave; } }); ivLike.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!clickLike){ ivLike.setImageResource(R.drawable.ic_insta_heart_true);; tvLikes.setText("Liked by Beamy and " + (post.getLikes()+1)+ " others"); post.setLikes(post.getLikes()+1); post.saveInBackground(new SaveCallback() { @Override public void done(com.parse.ParseException e) { if (e == null) { Log.d("Home Activity", "Create a new post success!"); } else { Log.d("Home Activity", "Failed in creating a post!"); e.printStackTrace(); } } }); } else { ivLike.setImageResource(R.drawable.ic_insta_heart); tvLikes.setText("Liked by Beamy and " + (post.getLikes()-1)+ " others"); post.setLikes(post.getLikes()-1); post.saveInBackground(new SaveCallback() { @Override public void done(com.parse.ParseException e) { if (e == null) { Log.d("Home Activity", "Liked!"); } else { Log.d("Home Activity", "Not liked!"); e.printStackTrace(); } } }); } clickLike = !clickLike; } }); ivImagePost.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int position = getAdapterPosition(); // make sure the position is valid, i.e. actually exists in the view if (position != RecyclerView.NO_POSITION) { // get the movie at the position, this won't work if the class is static Post post = mPosts.get(position); // create intent for the new activity Intent details = new Intent(mContext, PostDetails.class); // serialize the movie using parceler, use its short name as a key details.putExtra("POST", post); Toast.makeText(mContext.getApplicationContext(), "Detail of post by "+post.getUser().getUsername(), Toast.LENGTH_SHORT).show(); mContext.startActivity(details); } } }); ivComment.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int position = getAdapterPosition(); // make sure the position is valid, i.e. actually exists in the view if (position != RecyclerView.NO_POSITION) { // get the movie at the position, this won't work if the class is static Post post = mPosts.get(position); // create intent for the new activity Intent details = new Intent(mContext, CommentDetails.class); // serialize the movie using parceler, use its short name as a key details.putExtra("POST", post); Toast.makeText(mContext.getApplicationContext(), "Detail of post by "+post.getUser().getUsername(), Toast.LENGTH_SHORT).show(); mContext.startActivity(details); } } }); } /* @Override public void onClick(View v) { Intent intent = new Intent(mContext, SignUp.class); mContext.startActivity(intent); }*/ @Override public void onClick(View v) { // gets item position int position = getAdapterPosition(); // make sure the position is valid, i.e. actually exists in the view if (position != RecyclerView.NO_POSITION) { // get the movie at the position, this won't work if the class is static Post post = mPosts.get(position); // create intent for the new activity Intent details = new Intent(mContext, PostDetails.class); // serialize the movie using parceler, use its short name as a key details.putExtra("POST", post); Toast.makeText(mContext.getApplicationContext(), "Detail of post by "+post.getUser().getUsername(), Toast.LENGTH_SHORT).show(); mContext.startActivity(details); } } } }<file_sep>/app/src/main/java/flicks/codepath/instagram/SignUp.java package flicks.codepath.instagram; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.support.v4.content.FileProvider; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.parse.ParseException; import com.parse.ParseFile; import com.parse.ParseUser; import com.parse.SignUpCallback; import java.io.File; import static flicks.codepath.instagram.fragment.ComposeFragment.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE; public class SignUp extends AppCompatActivity { private EditText etUsername; private EditText etPassword; private EditText etEmail; private Button btnSignUp; private Button btnTakePic; public String photoFileName = "photo.jpg"; private File photoProfile; public final String APP_TAG = "SignUp"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign_up); etUsername = findViewById(R.id.etUsername); etPassword = findViewById(R.id.etPassword); etEmail = findViewById(R.id.etPassword); btnSignUp = findViewById(R.id.btnSignUp); btnTakePic = findViewById(R.id.btnTakePicture); btnTakePic.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { LaunchCamera(); } }); btnSignUp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final String username = etUsername.getText().toString(); final String password = etPassword.getText().toString(); final String email= etEmail.getText().toString(); signup(username, password, email, photoProfile); } }); } private void signup(final String username, String password, String email, File photo) { ParseUser user = new ParseUser(); // Set core properties user.setUsername(username); user.setPassword(<PASSWORD>); user.put("profilepic", new ParseFile(photo)); user.setEmail(email); user.put("handle", "fake_"+username); /*user.setEmail("<EMAIL>"); // Set custom properties user.put("phone", "650-253-0000");*/ // Invoke signUpInBackground user.signUpInBackground(new SignUpCallback() { public void done(ParseException e) { if (e == null) { // Hooray! Let them use the app now. Log.d("LogInActivity", username+"has successfully signed up!"); final Intent intent = new Intent(SignUp.this, HomeActivity.class); startActivity(intent); finish(); } else { // Sign up didn't succeed. Look at the ParseException // to figure out what went wrong Log.d("SignUpActivity", "Signup Failed!"); e.printStackTrace(); } } }); } public void LaunchCamera() { // create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // Create a File reference to access to future access photoProfile = getPhotoFileUri(photoFileName); // wrap File object into a content provider // required for API >= 24 // See https://guides.codepath.com/android/Sharing-Content-with-Intents#sharing-files-with-api-24-or-higher Uri fileProvider = FileProvider.getUriForFile(SignUp.this, "com.codepath.fileprovider", photoProfile); intent.putExtra(MediaStore.EXTRA_OUTPUT, fileProvider); // If you call startActivityForResult() using an intent that no app can handle, your app will crash. // So as long as the result is not null, it's safe to use the intent. if (intent.resolveActivity(getPackageManager()) != null) { // Start the image capture intent to take photo startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE); } } // Returns the File for a photo stored on disk given the fileName public File getPhotoFileUri(String fileName) { // Get safe storage directory for photos // Use `getExternalFilesDir` on Context to access package-specific directories. // This way, we don't need to request external read/write runtime permissions. File mediaStorageDir = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), APP_TAG); // Create the storage directory if it does not exist if (!mediaStorageDir.exists() && !mediaStorageDir.mkdirs()){ Log.d(APP_TAG, "failed to create directory"); } // Return the file target for the photo based on filename File file = new File(mediaStorageDir.getPath() + File.separator + fileName); return file; } }
ce2cac38e7eb45bae024207a77deefb857e12603
[ "Java" ]
4
Java
BeamzDream/Instagram
251439580f2853b772f4f7f52e87bb948f3918a3
dcbca6a6d905d9ec422383301226caff1712b0aa
refs/heads/main
<repo_name>juanprq/challenges<file_sep>/src/str-str/index.test.js const strStr = require('./index'); describe('strStr', () => { it('should be a function', () => { expect(strStr).toBeInstanceOf(Function); }); it('should return 2', () => { expect(strStr('hello', 'll')).toEqual(2); }); it('should return -1', () => { expect(strStr('aaaa', 'bba')).toEqual(-1); }); it('should return 0', () => { expect(strStr('', '')).toEqual(0); }); it('should return 0', () => { expect(strStr('a', 'a')).toEqual(0); }); it('should return -1', () => { expect(strStr('aaa', 'aaaa')).toEqual(-1); }); }); <file_sep>/src/rotate-string/index.js // This is a solution of O(n) const rotateString = (s, goal) => { if (s.length !== goal.length) return false; if (s.length === 0) return true; // find the index of the first letter of goal const firstLetter = goal.charAt(0); const indexes = []; for (let i = 0; i < goal.length; i++) { if (s.charAt(i) === firstLetter) { indexes.push(i); } } for (let i = 0; i < indexes.length; i++) { // one doubt that i have is the time complexity of the slice const a = s.slice(0, indexes[i]); const b = s.slice(indexes[i]); if ( b + a === goal ) return true; } return false; }; module.exports = rotateString; <file_sep>/src/queue/index.test.js const Queue = require('./index'); describe('Queue', () => { let queue; beforeEach(() => { queue = new Queue(); }); it('should be an instance of Queue', () => { expect(queue).toBeInstanceOf(Queue); }); it('should have a enqueue method', () => { expect(queue.enqueue).toBeInstanceOf(Function); }); it('should have a dequeue method', () => { expect(queue.dequeue).toBeInstanceOf(Function); }); it('should have a front method', () => { expect(queue.front).toBeInstanceOf(Function); }); it('should have a size method', () => { expect(queue.size).toBeInstanceOf(Function); }); it('should have an isEmpty method', () => { expect(queue.isEmpty).toBeInstanceOf(Function); }); it('should dequeue', () => { queue.enqueue(1); queue.enqueue(2); expect(queue.dequeue()).toEqual(1); expect(queue.dequeue()).toEqual(2); }); it('should return front element', () => { queue.enqueue(1); expect(queue.front()).toEqual(1); expect(queue.front()).toEqual(1); queue.enqueue(2); expect(queue.front()).toEqual(1); queue.dequeue(); expect(queue.front()).toEqual(2); }); it('should return size', () => { queue.enqueue(1); queue.enqueue(2); queue.enqueue(3); expect(queue.size()).toEqual(3); queue.enqueue(4); expect(queue.size()).toEqual(4); queue.dequeue(); queue.dequeue(); expect(queue.size()).toEqual(2); }); it("should return if it's empty", () => { expect(queue.isEmpty()).toBe(true); queue.enqueue(1); expect(queue.isEmpty()).toBe(false); queue.dequeue(); expect(queue.isEmpty()).toBe(true); }); }); <file_sep>/src/trapping-rain-water/index.js const trap = (height) => { let i = 0; let result = 0; while (i < height.length) { // rule 1 let nextIndex = i + 1; let maxValue = -Infinity; let maxIndex = -1; while (height[nextIndex] < height[i]) { if (height[nextIndex] > maxValue) { maxValue = height[nextIndex]; maxIndex = nextIndex; } // increment until a taller column appears nextIndex++; } if (nextIndex === height.length && maxValue === -Infinity) { i++; continue; } const target = nextIndex < height.length ? nextIndex : maxIndex; const min = Math.min(height[i], height[target]); let accum = 0; for (let j = i + 1; j < target; j++) { accum += min - height[j]; } i = target; result += accum; } return result; }; module.exports = trap; <file_sep>/src/group-anagrams/index.test.js const groupAnagrams = require('./index'); describe('groupAnagrams', () => { it('should be a function', () => { expect(groupAnagrams).toBeInstanceOf(Function); }); it('should return 3 groups', () => { const input = ['eat', 'tea', 'tan', 'ate', 'nat', 'bat']; const result = [[ 'eat', 'tea', 'ate' ], [ 'tan', 'nat' ], [ 'bat' ]]; expect(groupAnagrams(input)).toEqual(result); }); it('should return 1 empty group', () => { const input = ['']; const result = [['']]; expect(groupAnagrams(input)).toEqual(result); }); it('should return 1 group', () => { const input = ['a']; const result = [['a']]; expect(groupAnagrams(input)).toEqual(result); }); }) <file_sep>/src/binary-search/index.js const binarySearch = (nums, target) => { let l = 0; let r = nums.length - 1; while(l <= r) { let mid = Math.floor((l + r) / 2); if (nums[mid] === target) return mid; if (target < nums[mid]) { r = mid - 1; } else { l = mid + 1; } } return -1; }; module.exports = binarySearch; <file_sep>/src/valid-parentheses/index.test.js const isValid = require('./index'); describe('isValid', () => { it('should be a function', () => { expect(isValid).toBeInstanceOf(Function); }); it('should return true', () => { expect(isValid('()')).toBe(true); }); it('should return true', () => { expect(isValid('()[]{}')).toBe(true); }); it('should return false', () => { expect(isValid('(]')).toBe(false); }); it('should return false', () => { expect(isValid('([)]')).toBe(false); }); it('shoul return true', () => { expect(isValid('{[]}')).toBe(true); }); }); <file_sep>/src/binary-search/index.test.js const binarySearch = require('./index'); describe('binarySearch', () => { it('should be a function', () => { expect(binarySearch).toBeInstanceOf(Function); }); it('should return 3', () => { const nums = [1, 2, 3, 4, 5, 6]; const target = 4; expect(binarySearch(nums, target)).toEqual(3); }); it('should return 1', () => { const nums = [1, 2]; const target = 2; expect(binarySearch(nums, target)).toEqual(1); }); it('should return -1', () => { const nums = [1, 2]; const target = 3; expect(binarySearch(nums, target)).toEqual(-1); }); }); <file_sep>/src/first-missing-positive/index.js const firstMissingPositive = (nums) => { let i = 0; let max = -Infinity; while (i < nums.length) { max = Math.max(max, nums[i]); if (nums[i] < 0) { i++; continue; } const currentIndex = nums[i] - 1; if (currentIndex > nums.length) { nums[i] = 0; } else if (nums[currentIndex] > 0) { nums[i] = nums[currentIndex] } else { nums[i] = 0; i++; } nums[currentIndex] = -1; } for (let i = 0; i < nums.length; i++) { if (nums[i] === 0) { return i + 1; } } return Math.max(max + 1, 1); }; module.exports = firstMissingPositive; <file_sep>/src/candy-bars/index.test.js const balanceCandyBars = require('./index'); describe('balanceCandyBars', () => { it('should be a function', () => { expect(balanceCandyBars).toBeInstanceOf(Function); }); it('should return [[7, 5], [3, 1]]', () => { const alice = [7, 3, 2, 4]; const bob = [6, 1, 5]; expect(balanceCandyBars(alice, bob)).toEqual([[7, 5], [3, 1]]); }); }); <file_sep>/src/binary-search-tree/index.test.js const BinarySearchTree = require('./index'); describe('BinarySearchTree', () => { let binarySearchTree; beforeEach(() => { binarySearchTree = new BinarySearchTree(); }); it('should be a BinarySearchTree', () => { expect(binarySearchTree).toBeInstanceOf(BinarySearchTree); }); it('should have the add method', () => { expect(binarySearchTree.add).toBeInstanceOf(Function); }); it('should add an element in a sorted way', () => { binarySearchTree.add(2); binarySearchTree.add(1); binarySearchTree.add(3); expect(binarySearchTree.root.value).toEqual(2); expect(binarySearchTree.root.left.value).toEqual(1); expect(binarySearchTree.root.right.value).toEqual(3); }); it('should not add an element that already exists', () => { binarySearchTree.add(1); binarySearchTree.add(2); expect(binarySearchTree.add(2)).toBe(null); expect(binarySearchTree.root.value).toEqual(1); expect(binarySearchTree.root.right.value).toEqual(2); expect(binarySearchTree.root.right.left).toBe(null); expect(binarySearchTree.root.right.right).toBe(null); }); it('should have a findMin method', () => { expect(binarySearchTree.findMin).toBeInstanceOf(Function); }); it('should have a findMax method', () => { expect(binarySearchTree.findMax).toBeInstanceOf(Function); }); it('should return the minium value of the tree', () => { binarySearchTree.add(1); binarySearchTree.add(1); binarySearchTree.add(3); binarySearchTree.add(4); binarySearchTree.add(5); expect(binarySearchTree.findMin()).toEqual(1); }); it('should return the maximum value of the tree', () => { binarySearchTree.add(1); binarySearchTree.add(2); binarySearchTree.add(3); binarySearchTree.add(4); binarySearchTree.add(5); expect(binarySearchTree.findMax()).toEqual(5); }); it('should return null if an empty tree', () => { expect(binarySearchTree.findMin()).toBe(null); expect(binarySearchTree.findMax()).toBe(null); }); it('should have an isPresent method', () => { expect(binarySearchTree.isPresent).toBeInstanceOf(Function); }); it('should return true if an element isPresent', () => { binarySearchTree.add(1); binarySearchTree.add(2); binarySearchTree.add(3); expect(binarySearchTree.isPresent(2)).toBe(true); }); it('should return false with an empty tree', () => { expect(binarySearchTree.isPresent(5)).toBe(false); }); it('should have the findMinHeight method', () => { expect(binarySearchTree.findMinHeight).toBeInstanceOf(Function); }); it('should have the findMaxHeight method', () => { expect(binarySearchTree.findMaxHeight).toBeInstanceOf(Function); }); it('should have the isBalancedTree', () => { expect(binarySearchTree.isBalanced).toBeInstanceOf(Function); }); it('should return the minimum height of the tree', () => { binarySearchTree.add(2); binarySearchTree.add(1); binarySearchTree.add(3); binarySearchTree.add(4); binarySearchTree.add(5); binarySearchTree.add(6); expect(binarySearchTree.findMinHeight()).toEqual(1); }); it('should return the maximum height of the tree', () => { binarySearchTree.add(2); binarySearchTree.add(1); binarySearchTree.add(3); binarySearchTree.add(4); binarySearchTree.add(5); binarySearchTree.add(6); expect(binarySearchTree.findMaxHeight()).toEqual(4); }); it('should return -1 if is an empty tree', () => { expect(binarySearchTree.findMaxHeight()).toEqual(-1); expect(binarySearchTree.findMinHeight()).toEqual(-1); }); it('should return false if the tree is unbalanced', () => { binarySearchTree.add(2); binarySearchTree.add(1); binarySearchTree.add(3); binarySearchTree.add(4); binarySearchTree.add(5); binarySearchTree.add(6); expect(binarySearchTree.isBalanced()).toBe(false); }); it('should return true if the tree is balanced', () => { binarySearchTree.add(2); binarySearchTree.add(1); binarySearchTree.add(3); expect(binarySearchTree.isBalanced()).toBe(true); }); it('should have the inorder method', () => { expect(binarySearchTree.inorder).toBeInstanceOf(Function); }); it('should have the preorder method', () => { expect(binarySearchTree.preorder).toBeInstanceOf(Function); }); it('should have the postorder method', () => { expect(binarySearchTree.postorder).toBeInstanceOf(Function); }); it('should return an array for inorder traversal', () => { binarySearchTree.add(2); binarySearchTree.add(1); binarySearchTree.add(3); binarySearchTree.add(4); binarySearchTree.add(5); binarySearchTree.add(6); const result = [1, 2, 3, 4, 5, 6]; expect(binarySearchTree.inorder()).toEqual(result); }); it('should return an array for preorder traversal', () => { binarySearchTree.add(2); binarySearchTree.add(1); binarySearchTree.add(3); binarySearchTree.add(4); binarySearchTree.add(5); binarySearchTree.add(6); const result = [2, 1, 3, 4, 5, 6]; expect(binarySearchTree.preorder()).toEqual(result); }); it('should return an array for postorder traversal', () => { binarySearchTree.add(2); binarySearchTree.add(1); binarySearchTree.add(3); binarySearchTree.add(4); binarySearchTree.add(5); binarySearchTree.add(6); const result = [1, 6, 5, 4, 3, 2]; expect(binarySearchTree.postorder()).toEqual(result); }); it('should return null on empty tree', () => { expect(binarySearchTree.inorder()).toBe(null); expect(binarySearchTree.preorder()).toBe(null); expect(binarySearchTree.postorder()).toBe(null); }); it('should have a method called levelOrder', () => { expect(binarySearchTree.levelOrder).toBeInstanceOf(Function); }); it('should have a method called reverseLevelOrder', () => { expect(binarySearchTree.reverseLevelOrder).toBeInstanceOf(Function); }); it('should return an array of values explored in level order', () => { binarySearchTree.add(4); binarySearchTree.add(2); binarySearchTree.add(6); binarySearchTree.add(1); binarySearchTree.add(3); binarySearchTree.add(5); binarySearchTree.add(7); const result = [4, 2, 6, 1, 3, 5, 7]; expect(binarySearchTree.levelOrder()).toEqual(result); }); it('should return an array of values explored in reverse level order', () => { binarySearchTree.add(4); binarySearchTree.add(2); binarySearchTree.add(6); binarySearchTree.add(1); binarySearchTree.add(3); binarySearchTree.add(5); binarySearchTree.add(7); const result = [4, 6, 2, 7, 5, 3, 1]; expect(binarySearchTree.reverseLevelOrder()).toEqual(result); }); it('should levelOrder return null if an empty tree', () => { expect(binarySearchTree.levelOrder()).toBe(null); }); it('should reverseLevelOrder return null if an empty tree', () => { expect(binarySearchTree.reverseLevelOrder()).toBe(null); }); it('should have the remove method', () => { expect(binarySearchTree.remove).toBeInstanceOf(Function); }); it(`should return true if the element doesn't exits`, () => { binarySearchTree.add(2); binarySearchTree.add(1); binarySearchTree.add(3); expect(binarySearchTree.remove(4)).toBe(null); }); it('should set root to null if no children', () => { binarySearchTree.add(2); binarySearchTree.remove(2); expect(binarySearchTree.root).toBe(null); }); it('should remove leaf nodes from the tree', () => { binarySearchTree.add(2); binarySearchTree.add(1); binarySearchTree.add(3); binarySearchTree.remove(1); expect(binarySearchTree.root.left).toBe(null); }); it('should remove a node with one child', () => { binarySearchTree.add(1); binarySearchTree.add(2); binarySearchTree.add(3); binarySearchTree.remove(2); expect(binarySearchTree.root.right.value).toEqual(3); }); it('should remove the root node and set the child as root', () => { binarySearchTree.add(1); binarySearchTree.add(2); binarySearchTree.remove(1); expect(binarySearchTree.root.value).toEqual(2); }); it('should remove the root in a tree with two nodes and set the second to be the root', () => { binarySearchTree.add(2); binarySearchTree.add(1); binarySearchTree.add(3); binarySearchTree.remove(2); expect(binarySearchTree.root.value).toEqual(3); expect(binarySearchTree.root.left.value).toEqual(1); }); it('should remove the node with two children while remaining a binary search tree structure', () => { binarySearchTree.add(5); binarySearchTree.add(10); binarySearchTree.add(8); binarySearchTree.add(12); binarySearchTree.add(6); binarySearchTree.add(9); binarySearchTree.add(11); binarySearchTree.add(13); binarySearchTree.remove(10); expect(binarySearchTree.root.right.value).toEqual(12); expect(binarySearchTree.root.right.left.value).toEqual(11); expect(binarySearchTree.root.right.left.left.value).toEqual(8); }); it('should have a method called invert', () => { expect(binarySearchTree.invert).toBeInstanceOf(Function); }); it('should invert correctly the tree structure', () => { binarySearchTree.add(2); binarySearchTree.add(1); binarySearchTree.add(3); binarySearchTree.invert(); expect(binarySearchTree.root.value).toEqual(2); expect(binarySearchTree.root.left.value).toEqual(3); expect(binarySearchTree.root.right.value).toEqual(1); }); it('should invert return null if the tree is empty', () => { expect(binarySearchTree.invert()).toBe(null); }); }); <file_sep>/src/k-diff/index.test.js const kDiff = require('./index'); describe('kDiff', () => { it('should be a function', () => { expect(kDiff).toBeInstanceOf(Function); }); it('should return 2 pairs', () => { const nums = [3, 1, 4, 1, 5]; const k = 2; expect(kDiff(nums, k)).toEqual(2); }); it('should return 4', () => { const nums = [1, 2 ,3 ,4, 5]; const k = 1; expect(kDiff(nums, k)).toEqual(4); }); it('should return 1', () => { const nums = [1, 3, 1, 5, 4]; const k = 0; expect(kDiff(nums, k)).toEqual(1); }); it('should return 2', () => { const nums = [1, 2, 4, 4, 3, 3, 0, 9, 2, 3]; const k = 3; expect(kDiff(nums, k)).toEqual(2); }); it('should return 2', () => { const nums = [-1, -2, -3]; const k = 1; expect(kDiff(nums, k)).toEqual(2); }); }); <file_sep>/src/generate-parenthesis/index.test.js const generateParenthesis = require('./index'); describe('generateParenthesis', () => { it('should be a function', () => { expect(generateParenthesis).toBeInstanceOf(Function); }); it('should return 5 combinations', () => { expect(generateParenthesis(3)).toEqual( ['((()))', '(()())', '(())()', '()(())', '()()()'], ); }); it('should return 1 combination', () => { expect(generateParenthesis(1)).toEqual( ['()'], ); }); }); <file_sep>/src/count-and-say/index.js const countAndSay = (n) => { let currentResult = '1'; for (let i = 1; i < n; i++) { let iterationResult = ''; let j = 0; while (j < currentResult.length) { let count = 1; const currentChar = currentResult.charAt(j); while (currentChar === currentResult.charAt(j + 1)) { count++; j++; } iterationResult += `${count}${currentChar}`; j++; } currentResult = iterationResult; } return currentResult; }; module.exports = countAndSay; <file_sep>/src/largest-prime-factor/index.js const n = 10000; const generatePrimes = () => { const primes = []; for (let i = 1; i < n; i++) { let prime = true; for (let j = 2; j <= i / 2; j++) { if (i % j === 0) { prime = false; break; } } if (prime) primes.push(i); } return primes; }; const largestPrimeFactor = (n) => { const primes = generatePrimes(); return primes .reduce((maxPrime, prime) => { if (n % prime === 0) return prime; return maxPrime; }, 1); }; module.exports = largestPrimeFactor; <file_sep>/src/longest-common-prefix/index.test.js const longestCommonPrefix = require('./index'); describe('longestCommonPrefix', () => { it('should be a function', () => { expect(longestCommonPrefix).toBeInstanceOf(Function); }); it('should return "fl"', () => { const input = ['flower', 'flow', 'flight']; expect(longestCommonPrefix(input)).toEqual('fl'); }); it('should return ""', () => { const input = ['dog', 'racecar', 'car']; expect(longestCommonPrefix(input)).toEqual(''); }); it('should return ""', () => { const input = []; expect(longestCommonPrefix(input)).toEqual(''); }); it('should return "a"', () => { const input = ['a']; expect(longestCommonPrefix(input)).toEqual('a'); }); }); <file_sep>/src/longest-palindrome-substring/index.test.js const longestPalindrome = require('./index'); describe('longestPalindrome', () => { it('should be a function', () => { expect(longestPalindrome).toBeInstanceOf(Function); }); it('should return "bab"', () => { expect(longestPalindrome('babad')).toEqual('aba'); }); it('should return "bb"', () => { expect(longestPalindrome('cbbd')).toEqual('bb'); }); it('should return "a"', () => { expect(longestPalindrome('a')).toEqual('a'); }); it('should return "a"', () => { expect(longestPalindrome('ac')).toEqual('c'); }); }); <file_sep>/src/count-and-say/index.test.js const countAndSay = require('./index'); describe('countAndSay', () => { it('should be a function', () => { expect(countAndSay).toBeInstanceOf(Function); }); it('should return "1"', () => { expect(countAndSay(1)).toEqual('1'); }); it('should return "11"', () => { expect(countAndSay(2)).toEqual('11'); }); it('should return "21"', () => { expect(countAndSay(3)).toEqual('21'); }); it('should return "1211"', () => { expect(countAndSay(4)).toEqual('1211'); }); }); <file_sep>/src/breath-first-search/index.test.js const bfs = require('./index'); describe('bfs', () => { it('should return the correct length', () => { const input = [ [0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0], ]; expect(bfs(input, 1)) .toEqual({ 0: 1, 1: 0, 2: 1, 3: 2, }); }); it('should return the correct length', () => { const input = [ [0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0], ]; expect(bfs(input, 1)) .toEqual({ 0: 1, 1: 0, 2: 1, 3: Infinity, }); }); it('should return the correct length', () => { const input = [ [0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0], ]; expect(bfs(input, 0)) .toEqual({ 0: 0, 1: 1, 2: 2, 3: 3, }); }); it('should return the correct length', () => { const input = [ [0, 1], [1, 0], ]; expect(bfs(input, 0)) .toEqual({ 0: 0, 1: 1, }); }); }); <file_sep>/src/no-repeats-please/index.test.js const permAlone = require('./index'); describe('permAlone', () => { it('should be a function', () => { expect(permAlone).toBeInstanceOf(Function); }); it('should return 2', () => { expect(permAlone('aab')).toEqual(2); }); it('should return 0', () => { expect(permAlone('aaa')).toEqual(0); }); it('should return 8', () => { expect(permAlone('aabb')).toEqual(8); }); it('should return 3600', () => { expect(permAlone('abcdefa')).toEqual(3600); }); it('should return 2640', () => { expect(permAlone('abfdefa')).toEqual(2640); }); it('should return 0', () => { expect(permAlone('zzzzzzzz')).toEqual(0); }); it('should return 1', () => { expect(permAlone('a')).toEqual(1); }); it('should return 0', () => { expect(permAlone('aaab')).toEqual(0); }); it('should return 12', () => { expect(permAlone('aaabb')).toEqual(12); }); }); <file_sep>/src/regular-expression-matching/index.js const isMatch = (string, pattern) => { const memo = []; for (let i = 0; i <= string.length; i++) { for (let j = 0; j <= pattern.length; j++) { if (memo[i]) { memo[i][j] = undefined; } else { memo[i] = [undefined]; } } } const iterate = (stringIndex = 0, patternIndex = 0) => { if (memo[stringIndex] && memo[stringIndex][patternIndex] !== undefined) return memo[stringIndex][patternIndex]; if (patternIndex === pattern.length) { // check if we consumed all the string or not return stringIndex === string.length; } let result; const currentPattern = pattern.charAt(patternIndex); const firstMatch = stringIndex < string.length && (string.charAt(stringIndex) === currentPattern || currentPattern === '.'); if (pattern.charAt(patternIndex + 1) === '*') { result = iterate(stringIndex, patternIndex + 2) // this is for ignoring the current char || firstMatch && iterate(stringIndex + 1, patternIndex); // or consume the char without going to the next pattern } else { result = firstMatch && iterate(stringIndex + 1, patternIndex + 1); } memo[stringIndex][patternIndex] = result; return result; }; return iterate(); }; module.exports = isMatch; <file_sep>/src/remove-covered-intervals/index.js const removeCoveredIntervals = (intervals) => { const result = []; let currentIntervals = intervals; while (currentIntervals.length > 0) { const [head, ...rest] = currentIntervals; let handled = false; for (let i = 0; i < result.length; i++) { const [leftMin, leftMax] = result[i]; const [rightMin, rightMax] = head; if (leftMin <= rightMin && leftMax >= rightMax) { handled = true; break; } else if (rightMin <= leftMin && rightMax >= leftMax ) { handled = true; result[i] = head; break; } } currentIntervals = rest; if (!handled) { result.push(head); } } return result.length; }; module.exports = removeCoveredIntervals; <file_sep>/src/median-of-two-sorted-arrays/index.js const findMedianSortedArrays = (a1, a2) => { // first lets implement this in a regular linear way // I'm going to merge the arrays into a new one const result = []; let i = 0; let j = 0; while (i < a1.length || j < a2.length) { const a = a1[i] !== undefined ? a1[i] : Infinity; const b = a2[j] !== undefined ? a2[j] : Infinity; if (j === 2) throw new Error('dry'); if (a !== undefined && a < b) { result.push(a); i++; } else { result.push(b); j++; } } if (result.length % 2 === 0) { return (result[result.length / 2 - 1] + result[result.length / 2]) / 2; } else { return result[Math.floor(result.length / 2)]; } }; module.exports = findMedianSortedArrays; <file_sep>/src/next-round/index.js const nextRound = (k, input) => { const targetScore = input[k - 1]; const toNextRound = input .filter(value => value >= targetScore && value > 0); return toNextRound.length; }; module.exports = nextRound; <file_sep>/src/move-zeroes/index.test.js const moveZeroes = require('./index'); describe('moveZeroes', () => { it('should be a function', () => { expect(moveZeroes).toBeInstanceOf(Function); }); it('should move the zeroes to the right', () => { const input = [0,2,0,3,8]; expect(moveZeroes(input)).toEqual([2,3,8,0,0]); }); }); <file_sep>/src/merge-k-sorted-list/index.js class ListNode { constructor(val, next) { this.val = (val===undefined ? 0 : val); this.next = (next===undefined ? null : next); } } const mergeKLists = (lists) => { const head = new ListNode(-1); let currentNode = head; while (true) { const minIdx = lists .reduce((accum, node, idx) => { const currentMin = lists[accum] ? lists[accum].val : Infinity; const nextMin = node ? node.val : Infinity; if (nextMin < currentMin) { return idx; } return accum; }, -1); if (minIdx === -1) break; currentNode.next = new ListNode(lists[minIdx].val); currentNode = currentNode.next; lists[minIdx] = lists[minIdx].next; } currentNode = head; while (currentNode) { currentNode = currentNode.next; } return head.next; }; module.exports = mergeKLists; module.exports.ListNode = ListNode; <file_sep>/src/class-stack/index.test.js const Stack = require('./index'); describe('stack', () => { let stack; beforeEach(() => { stack = new Stack(); }); it('should be an instance of Stack', () => { expect(stack).toBeInstanceOf(Stack); }); it('should have a push method', () => { expect(stack.push).toBeInstanceOf(Function); }); it('should have a pop method', () => { expect(stack.pop).toBeInstanceOf(Function); }); it('should have a peek method', () => { expect(stack.peek).toBeInstanceOf(Function); }); it('should have a isEmpty method', () => { expect(stack.isEmpty).toBeInstanceOf(Function); }); it('should have a clear method', () => { expect(stack.clear).toBeInstanceOf(Function); }); it('should return the top element #peek', () => { stack.push(1); stack.push(2); expect(stack.peek()).toEqual(2); expect(stack.peek()).toEqual(2); stack.pop(); expect(stack.peek()).toEqual(1); }); it('should return the top element #pop', () => { stack.push(1); stack.push(2); expect(stack.pop()).toEqual(2); expect(stack.pop()).toEqual(1); expect(stack.isEmpty()).toBe(true); }); it('should return true if stack is empty', () => { expect(stack.isEmpty()).toBe(true); stack.push(1); expect(stack.isEmpty()).toBe(false); }); it('should clear all elements in stack', () => { stack.push(1); stack.push(2); expect(stack.isEmpty()).toBe(false); stack.clear(); expect(stack.isEmpty()).toBe(true); }); }); <file_sep>/src/linked-list/index.js class Node { constructor(element) { this.element = element; this.next = null; } }; class LinkedList { length = 0; cHead = null; head() { return this.cHead; } size() { return this.length; } add(element) { this.length++; const newNode = new Node(element); if (!this.cHead) { this.cHead = newNode; } else { let currentNode = this.cHead; while (currentNode.next) { currentNode = currentNode.next; } currentNode.next = newNode; } } remove(element) { if (element === this.head().element) { this.cHead = this.head().next; this.length--; } else { let prev = this.head(); let current = prev.next; while(current !== null && current.element !== element) { prev = current; current = current.next; } if (current) { this.length--; prev.next = current.next; } } } isEmpty() { return this.length === 0; } indexOf(element) { let current = this.head(); let index = 0; while(current !== null && current.element !== element) { current = current.next index++; } return current ? index : -1; } elementAt(index) { let current = this.head(); let currentIndex = 0; while (current !== null && currentIndex < index) { current = current.next; currentIndex++; } return current ? current.element : undefined; } removeAt(index) { if (index < 0 || index >= this.size()) return null; this.length--; let currentIndex = 0; let current = this.head(); let prev; while (currentIndex < index) { prev = current; current = current.next; currentIndex++; } const { element } = current; if (current === this.head()) { this.cHead = current.next; } else { prev.next = current.next; } return element; } addAt(index, element) { if (index < 0 || index >= this.size()) return false; this.length++; let currentIndex = 0; let current = this.head(); let prev; while (currentIndex < index) { prev = current; current = current.next; currentIndex++; } const newElement = new Node(element); if (prev) { prev.next = newElement; newElement.next = current; } else { newElement.next = this.head(); this.cHead = newElement; } return true; } } module.exports = LinkedList; <file_sep>/src/min-heap/index.js class MinHeap { heap = [null]; insert(value) { let index = this.heap.length; let parentIndex = Math.floor(index / 2); this.heap.push(value); while (index > 1 && this.heap[parentIndex] > this.heap[index]) { const aux = this.heap[index]; this.heap[index] = this.heap[parentIndex]; this.heap[parentIndex] = aux; index = parentIndex; parentIndex = Math.floor(index / 2); } } remove() { if (this.heap.length === 1) return null; const result = this.heap[1]; this.heap[1] = this.heap[this.heap.length - 1]; this.heap.pop(); let index = 1; let test = 1; while ( index * 2 < this.heap.length && ( this.heap[index * 2] < this.heap[index] || this.heap[index * 2 + 1] < this.heap[index] ) ) { const childIndex = this.heap[index * 2] < (this.heap[index * 2 + 1] || Infinity) ? index * 2 : index * 2 + 1; const aux = this.heap[index]; this.heap[index] = this.heap[childIndex]; this.heap[childIndex] = aux; index = childIndex; test++; if (test > 10) throw new Error('dry!'); } return result; } sort() { const result = []; while (this.heap.length > 1) { result.push(this.remove()); } return result; } } module.exports = MinHeap; <file_sep>/src/longest-substring/index.js const lengthOfLongestSubstring = (s) => { let result = 0; const memo = {}; let i = 0; for (let j = 0; j < s.length; j++) { const char = s[j]; if (memo[char]) { i = Math.max(memo[char], i); } result = Math.max(result, j - i + 1); memo[char] = j + 1; } return result; }; module.exports = lengthOfLongestSubstring; <file_sep>/src/search-in-rotated-sorted-array/index.test.js const search = require('./index'); describe('search', () => { it('should be a function', () => { expect(search).toBeInstanceOf(Function); }); it('should return 4', () => { expect(search([4, 5, 6, 7, 0, 1, 2], 0)).toEqual(4); }); it('should return -1', () => { expect(search([4, 5, 6, 7, 0, 1, 2], 3)).toEqual(-1); }); it('should return -1', () => { expect(search([1], 0)).toEqual(-1); }); }); <file_sep>/src/median-of-two-sorted-arrays/index.test.js const findMedianSortedArrays = require('./index'); describe('medianOfTwoSortedArrays', () => { test('it should be a function', () => { expect(findMedianSortedArrays).toBeInstanceOf(Function); }); test('it should return 2', () => { const a1 = [1, 3]; const a2 = [2]; expect(findMedianSortedArrays(a1, a2)).toEqual(2); }); test('it should return 2.5', () => { const a1 = [1, 2]; const a2 = [3, 4]; expect(findMedianSortedArrays(a1, a2)).toEqual(2.5); }); test('it should return 0', () => { const a1 = [0]; const a2 = [0]; expect(findMedianSortedArrays(a1, a2)).toEqual(0); }); test('it should return 1', () => { const a1 = []; const a2 = [1]; expect(findMedianSortedArrays(a1, a2)).toEqual(1); }); test('it should return 2', () => { const a1 = [2]; const a2 = []; expect(findMedianSortedArrays(a1, a2)).toEqual(2); }); }); <file_sep>/src/garden-problem/index.test.js const canPlant = require('./index'); describe('canPlant', () => { it('should be a function', () => { expect(canPlant).toBeInstanceOf(Function); }); it('should return true', () => { const garden = [1, 0, 0, 0, 1]; expect(canPlant(garden, 1)).toBe(true); }); it('should return false', () => { const garden = [1, 0, 0, 0, 1]; expect(canPlant(garden, 4)).toBe(false); }); }); <file_sep>/src/combination-sum/index.js const combinationSum = (candidates, target, currentIndex = 0, currentCandidates = []) => { if (target === 0) return [currentCandidates]; if (target < 0 || currentIndex >= candidates.length) return []; const current = candidates[currentIndex]; return [ ...combinationSum(candidates, target - current, currentIndex, [...currentCandidates, current]), ...combinationSum(candidates, target, currentIndex + 1, currentCandidates), ]; }; module.exports = combinationSum; <file_sep>/src/multiples-of-3-and-5/index.js const multiplesOf3And5 = (n) => { let result = 0; for (let i = 0; i < n; i++) { if (i % 3 === 0 || i % 5 === 0) { result += i; } } return result; }; module.exports = multiplesOf3And5; <file_sep>/src/longest-palindrome-substring/index.js const longestPalindrome = (string) => { if ((string || '').length === 0) return ''; const expandAroundCenter = (i, j) => { let left = i; let right = j; while (left >= 0 && right < string.length && string.charAt(left) === string.charAt(right)) { left--; right++; } return right - left - 1; }; let start = 0; let end = 0; for (let i = 0; i < string.length; i++) { const l1 = expandAroundCenter(i, i); const l2 = expandAroundCenter(i, i + 1); const length = Math.max(l1, l2); if (length > (end - start)) { start = i - Math.floor((length - 1) / 2); end = i + Math.floor(length / 2); } } return string.slice(start, end + 1); }; module.exports = longestPalindrome; <file_sep>/src/100-doors/index.js const getFinalOpenedDoors = (numDoors) => { let i = 1; let ii = i * i; let result = []; while (ii <= numDoors) { result.push(ii); i++; ii = i * i; } return result; }; module.exports = getFinalOpenedDoors; <file_sep>/src/roman-to-int/index.test.js const romanToInt = require('./index'); describe('romanToInt', () => { it('should be a function', () => { expect(romanToInt).toBeInstanceOf(Function); }); it('should return 3', () => { expect(romanToInt('III')).toEqual(3); }); it('should return 4', () => { expect(romanToInt('IV')).toEqual(4); }); it('should return 9', () => { expect(romanToInt('IX')).toEqual(9); }); it('should return 58', () => { expect(romanToInt('LVIII')).toEqual(58); }); it('should return 1994', () => { expect(romanToInt('MCMXCIV')).toEqual(1994); }); }); <file_sep>/src/add-two-numbers/index.js class ListNode { constructor(val, next) { this.val = (val===undefined ? 0 : val) this.next = (next===undefined ? null : next) } } const addTwoNumbers = (l1, l2) => { let result; let prev; let carry = 0; let x = l1; let y = l2; while (x || y || carry !== 0) { let sum = carry; if (x) { sum += x.val; x = x.next; } if (y) { sum += y.val; y = y.next; } const currentNode = new ListNode(sum % 10); if (prev) { prev.next = currentNode; } else { result = currentNode; } prev = currentNode; carry = Math.floor(sum / 10); } return result; }; module.exports = addTwoNumbers; module.exports.ListNode = ListNode; <file_sep>/src/max-area/index.js const maxArea = (numbers) => { let lowerPointer = 0; let upperPointer = numbers.length - 1; let max = 0; while (lowerPointer < upperPointer) { const area = Math.min(numbers[lowerPointer], numbers[upperPointer]) * (upperPointer - lowerPointer); max = Math.max(max, area); if (numbers[lowerPointer] > numbers[upperPointer]) { upperPointer--; } else { lowerPointer++; } } return max; }; module.exports = maxArea; <file_sep>/src/valid-sudoku/index.js const isValidArray = (array) => { const set = new Set(array); return set.size === array.length; }; const isValidSudoku = (sudoku) => { // rows for (let i = 0; i < sudoku.length; i++) { const numbers = sudoku[i].filter(v => v !== '.'); if (!isValidArray(numbers)) return false; } // cols for (let i = 0; i < sudoku.length; i++) { const numbers = []; for (let j = 0; j < sudoku.length; j++) { if (sudoku[j][i] !== '.') numbers.push(sudoku[j][i]); } if(!isValidArray(numbers)) return false; } // cubes for (let i = 0; i < sudoku.length / 3; i++) { for (let j = 0; j < sudoku.length / 3; j++) { let cube = []; for (let r = 0; r < sudoku.length / 3; r++) { for (let c = 0; c < sudoku.length / 3; c++) { const value = sudoku[i * 3 + r][j * 3 + c]; if (value !== '.') { cube.push(value); } } } if (!isValidArray(cube)) return false; } } return true; }; module.exports = isValidSudoku; <file_sep>/src/divide-two-integers/index.test.js const divide = require('./index'); describe('divide', () => { it('should be a function', () => { expect(divide).toBeInstanceOf(Function); }); it('should return 3', () => { expect(divide(10, 3)).toEqual(3); }); it('should return -2', () => { expect(divide(7, -3)).toEqual(-2); }); it('should return 0', () => { expect(divide(0, 1)).toEqual(0); }); it('should return 1', () => { expect(divide(1, 1)).toEqual(1); }); }); <file_sep>/src/trie/index.test.js const Trie = require('./index'); describe('Trie', () => { let trie; beforeEach(() => { trie = new Trie(); }); it('should be a Trie instance', () => { expect(trie).toBeInstanceOf(Trie); }); it('should have an add method', () => { expect(trie.add).toBeInstanceOf(Function); }); it('should have a print method', () => { expect(trie.print).toBeInstanceOf(Function); }); it('should have a isWord method', () => { expect(trie.isWord).toBeInstanceOf(Function); }); it('should return all items added as strings in an array', () => { trie.add('hello'); trie.add('world'); trie.add('juan'); trie.add('helling'); const result = ['hello', 'world', 'juan', 'helling'].sort(); expect(trie.print().sort()).toEqual(result); }); it('should return true for only words added to the trie, false otherwise', () => { trie.add('hello'); trie.add('world'); expect(trie.isWord('hello')).toBe(true); expect(trie.isWord('test')).toBe(false); expect(trie.isWord('world')).toBe(true); }); }); <file_sep>/src/add-two-numbers/index.test.js const addTwoNumbers = require('./index'); const { ListNode } = require('./index'); const fromArrayToList = (array) => { let head; let prev; array.forEach((item) => { const currentNode = new ListNode(item); if (prev) { prev.next = currentNode; } else { head = currentNode; } prev = currentNode; }); return head; }; const fromListToArray = (head) => { const array = []; let currentNode = head; while (currentNode) { array.push(currentNode.val); currentNode = currentNode.next; } return array; } describe('addTwoNumbers', () => { test('it should be a function', () => { expect(addTwoNumbers).toBeInstanceOf(Function); }); test('it should return 708', () => { const l1 = fromArrayToList([2, 4, 3]); const l2 = fromArrayToList([5, 6, 4]); const result = addTwoNumbers(l1, l2); expect(fromListToArray(result)).toEqual([7, 0, 8]); }); test('it should return 0', () => { const l1 = fromArrayToList([0]); const l2 = fromArrayToList([0]); const result = addTwoNumbers(l1, l2); expect(fromListToArray(result)).toEqual([0]); }); test('it should return 89990001', () => { const l1 = fromArrayToList([9, 9, 9, 9, 9, 9, 9]); const l2 = fromArrayToList([9, 9, 9, 9]); const result = addTwoNumbers(l1, l2); expect(fromListToArray(result)).toEqual([8, 9, 9, 9, 0, 0, 0, 1]); }); test('it should return 6640000000000000000000000000001', () => { const l1 = fromArrayToList([1,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,1]); const l2 = fromArrayToList([5,6,4]); const result = addTwoNumbers(l1, l2); expect(fromListToArray(result)).toEqual([6,6,4,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,1]); }); }); <file_sep>/src/max-heap/index.js class MaxHeap { heap = [null]; insert(value) { let index = this.heap.length; let parentIndex = Math.floor(index / 2); this.heap.push(value); while (parentIndex > 0 && this.heap[parentIndex] < value) { const aux = this.heap[index]; this.heap[index] = this.heap[parentIndex]; this.heap[parentIndex] = aux; index = parentIndex; parentIndex = Math.floor(index / 2); } } remove() { const result = this.heap[1]; this.heap[1] = this.heap[this.heap.length - 1]; this.heap.pop(); let index = 1; while ( index < this.heap.length - 1 && ( this.heap[index * 2] > this.heap[index] || this.heap[index * 2 + 1] > this.heap[index] ) ) { const aux = this.heap[index]; let childIndex = index * 2; if (this.heap[childIndex] < this.heap[childIndex + 1]) childIndex++; this.heap[index] = this.heap[childIndex]; this.heap[childIndex] = aux; index = childIndex; } return result; } print() { return this.heap.slice(1); } } module.exports = MaxHeap; <file_sep>/src/priority-queue/index.test.js const PriorityQueue = require('./index'); describe('PriorityQueue', () => { let priorityQueue; beforeEach(() => { priorityQueue = new PriorityQueue(); }); it('should be of type PriorityQueue', () => { expect(priorityQueue).toBeInstanceOf(PriorityQueue); }); it('should have an enqueue method', () => { expect(priorityQueue.enqueue).toBeInstanceOf(Function); }); it('should have a dequeue method', () => { expect(priorityQueue.dequeue).toBeInstanceOf(Function); }); it('should have a size method', () => { expect(priorityQueue.size).toBeInstanceOf(Function); }); it('should have a front method', () => { expect(priorityQueue.front).toBeInstanceOf(Function); }); it('should have an isEmpty method', () => { expect(priorityQueue.isEmpty).toBeInstanceOf(Function); }); it('should keep track of the current number of items enqueued', () => { priorityQueue.enqueue(['coin', 1]); priorityQueue.enqueue(['stick', 2]); priorityQueue.enqueue(['pencil', 1]); expect(priorityQueue.size()).toEqual(3); priorityQueue.dequeue(); expect(priorityQueue.size()).toEqual(2); priorityQueue.dequeue(); expect(priorityQueue.size()).toEqual(1); }); it('should return correct item in the front method', () => { priorityQueue.enqueue(['coin', 1]); priorityQueue.enqueue(['stick', 2]); priorityQueue.enqueue(['pencil', 1]); expect(priorityQueue.front()).toEqual('coin'); priorityQueue.dequeue(); expect(priorityQueue.front()).toEqual('pencil'); }); it('should return true if the queue is empty', () => { expect(priorityQueue.isEmpty()).toBe(true); priorityQueue.enqueue(['test', 1]); expect(priorityQueue.isEmpty()).toBe(false); }); it('should return items with a higher priority before items with lower priority and return items in fifo', () => { priorityQueue.enqueue(['coin', 1]); priorityQueue.enqueue(['stick', 2]); priorityQueue.enqueue(['pencil', 1]); expect(priorityQueue.dequeue()).toEqual('coin'); expect(priorityQueue.dequeue()).toEqual('pencil'); expect(priorityQueue.dequeue()).toEqual('stick'); }); }); <file_sep>/src/spiral-matrix/index.test.js const spiralOrder = require('./index'); describe('spiralOrder', () => { it('should be a function', () => { expect(spiralOrder).toBeInstanceOf(Function); }); it('should return spiral order', () => { const input = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ]; const output = [1, 2, 3, 6, 9, 8, 7, 4, 5]; expect(spiralOrder(input)).toEqual(output); }); it('should return spiral order', () => { const input = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], ]; const output = [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]; expect(spiralOrder(input)).toEqual(output); }); it('should return spiral order', () => { const input = [ [3], [2], ]; const output = [3, 2]; expect(spiralOrder(input)).toEqual(output); }); it('should return spiral order', () => { const input = [ [1, 2], ]; const output = [1, 2]; expect(spiralOrder(input)).toEqual(output); }); }); <file_sep>/src/100-doors/index.test.js const getFinalOpenedDoors = require('./index'); describe('getFinalOpenedDoors', () => { it('should be a function', () => { expect(getFinalOpenedDoors).toBeInstanceOf(Function); }); it('should return an array', () => { expect(getFinalOpenedDoors(100)).toBeInstanceOf(Array); }); it('should return the correct toggled doors', () => { const result = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]; expect(getFinalOpenedDoors(100)).toEqual(result); }); }); <file_sep>/src/incidence-matrix/index.test.js const incidenceMatrix = [ [1, 0, 0, 0], [1, 1, 0, 1], [0, 1, 1, 0], [0, 0, 0, 1], [0, 0, 1, 0], ]; describe('incidenceMatrix', () => { it('should have 5 nodes', () => { expect(incidenceMatrix).toHaveLength(5); }); it('should have the first edge between first and second node', () => { expect(incidenceMatrix[0][0]).toEqual(1); expect(incidenceMatrix[1][0]).toEqual(1); expect(incidenceMatrix[2][0]).toEqual(0); expect(incidenceMatrix[3][0]).toEqual(0); expect(incidenceMatrix[4][0]).toEqual(0); }); it('should have an edge between the second and third node', () => { expect(incidenceMatrix[0][1]).toEqual(0); expect(incidenceMatrix[1][1]).toEqual(1); expect(incidenceMatrix[2][1]).toEqual(1); expect(incidenceMatrix[3][1]).toEqual(0); expect(incidenceMatrix[4][1]).toEqual(0); }); it('should have an edge between the third and fifth node', () => { expect(incidenceMatrix[0][2]).toEqual(0); expect(incidenceMatrix[1][2]).toEqual(0); expect(incidenceMatrix[2][2]).toEqual(1); expect(incidenceMatrix[3][2]).toEqual(0); expect(incidenceMatrix[4][2]).toEqual(1); }); it('should have an edge between the fourth and the second node', () => { expect(incidenceMatrix[0][3]).toEqual(0); expect(incidenceMatrix[1][3]).toEqual(1); expect(incidenceMatrix[2][3]).toEqual(0); expect(incidenceMatrix[3][3]).toEqual(1); expect(incidenceMatrix[4][3]).toEqual(0); }); }); <file_sep>/src/move-zeroes/index.js const moveZeroes = (input) => { for (let i = 0; i < input.length; i++) { if (input[i] === 0) { for (let j = i; j < input.length - 1; j++) { input[j] = input[j + 1]; input[j + 1] = 0 } } } return input; }; module.exports = moveZeroes; <file_sep>/src/best-time-to-buy-stock/index.test.js const maxProfit = require('./index'); const tests = [ { input: [7, 1, 5, 3, 6, 4], result: 5, }, { input: [7, 6, 4, 3, 1], result: 0, }, ]; describe('maxProfit', () => { it('should be a function', () => { expect(maxProfit).toBeInstanceOf(Function); }); tests.forEach(({ input, result }) => { it(`input: ${JSON.stringify(input)} should return: ${result}`, () => { expect(maxProfit(input)).toEqual(result); }); }); }); <file_sep>/src/min-heap/index.test.js const MinHeap = require('./index'); describe('MinHeap', () => { let minHeap; beforeEach(() => { minHeap = new MinHeap(); }); it('should the structure exists', () => { expect(minHeap).toBeInstanceOf(MinHeap); }); it('should have the method called insert', () => { expect(minHeap.insert).toBeInstanceOf(Function); }); it('should have the method called remove', () => { expect(minHeap.remove).toBeInstanceOf(Function); }); it('should have the method called sort', () => { expect(minHeap.sort).toBeInstanceOf(Function); }); it('should #sort return the array containing the items in a sorted way', () => { minHeap.insert(7); minHeap.insert(13); minHeap.insert(2); minHeap.insert(9); minHeap.insert(22); minHeap.insert(6); expect(minHeap.sort()).toEqual([2, 6, 7, 9, 13, 22]); }); }); <file_sep>/src/reverse-integer/index.js const MAX = Math.pow(2, 31) - 1; const MIN = -1 * Math.pow(2, 31); const reverseInteger = (number) => { let negative = number < 0 ? -1 : 1; let reminder = number * negative; let result = 0; while (reminder > 0) { const digit = reminder % 10; if (result > MAX / 10 || (result === MAX / 10 && digit > 7)) return 0; if (result < MIN / 10 || (result === MIN / 10) && digit < -8) return 0; result = result * 10 + digit; reminder = Math.floor(reminder / 10); } return result * negative; }; module.exports = reverseInteger; <file_sep>/src/pow/index.js const myPow = (base, exponent) => { if (exponent === 0) return 1; if (exponent < 0) return 1 / myPow(base, exponent * -1); return base * myPow(base, exponent - 1); }; module.exports = myPow; <file_sep>/src/three-sum/index.js const threeSum = (numbers) => { if (numbers.length < 3) return []; if (numbers.length === 3) { const sum = numbers.reduce((a, b) => a + b); if (sum === 0) { return [numbers]; } else { return []; } } numbers.sort((a, b) => a - b); const results = []; for(let i = 0; i < numbers.length - 3; i++) { if (i > 0 && numbers[i] === numbers[i - 1]) continue; let lower = i + 1; let upper = numbers.length - 1; while (lower < upper) { const result = numbers[i] + numbers[lower] + numbers[upper]; if (result < 0) { lower++; } else if (result > 0) { upper--; } else { results.push([numbers[i], numbers[lower], numbers[upper]]); while (lower < upper && numbers[lower] === numbers[lower + 1]) lower++; while (lower < upper && numbers[upper] === numbers[upper - 1]) upper--; lower++; upper--; } } } return results; }; module.exports = threeSum; <file_sep>/src/valid-numbers/index.js const isValidNumber = (number) => { return /^(\+|-)?\d*\.?\d*$/.test(number); }; module.exports = isValidNumber; <file_sep>/src/letter-combination-of-phone/index.js const mapping = [ ['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['j', 'k', 'l'], ['m', 'n', 'o'], ['p', 'q', 'r', 's'], ['t', 'u', 'v'], ['w', 'x', 'y', 'z'], ]; const letterCombinations = (input) => { let result = []; for (let i = 0; i < input.length; i++) { const letters = mapping[parseInt(input.charAt(i), 10) - 2]; if (result.length === 0) { result = letters; } else { result = letters.reduce((accum, letter) => { const subArray = result.map(accumLetter => { return accumLetter + letter; }); return [...accum, ...subArray]; }, []); } } return result; }; module.exports = letterCombinations; <file_sep>/src/pascale-triangle/index.js const getRowPascaleTriangle = (n) => { if (n === 1) return [1]; if (n === 2) return [1, 1]; const prev = getRowPascaleTriangle(n - 1); const sum = []; for (let i = 0; i < prev.length - 1; i++) { sum.push(prev[i] + prev[i + 1]); } return [1, ...sum, 1]; }; module.exports = getRowPascaleTriangle; <file_sep>/src/hash-table/index.test.js const HashTable = require('./index'); describe('HashTable', () => { let hashTable; beforeEach(() => { hashTable = new HashTable(); }); it('should be a HashTable', () => { expect(hashTable).toBeInstanceOf(HashTable); }); it('should have a add method', () => { expect(hashTable.add).toBeInstanceOf(Function); }); it('should have a remove method', () => { expect(hashTable.remove).toBeInstanceOf(Function); }); it('should have a lookup method', () => { expect(hashTable.lookup).toBeInstanceOf(Function); }); it('it should add items and lookup values', () => { hashTable.add('a', 1); hashTable.add('b', 2); hashTable.add('c', 3); expect(hashTable.lookup('a')).toEqual(1); expect(hashTable.lookup('b')).toEqual(2); expect(hashTable.lookup('c')).toEqual(3); }); it('should remove items', () => { hashTable.add('a', 1); expect(hashTable.lookup('a')).toEqual(1); hashTable.remove('a'); expect(hashTable.lookup('a')).toBe(null); }); }); <file_sep>/src/no-repeats-please/index.js const noRepeatingChars = (string) => { for (let i = 1; i < string.length; i++) { if (string.charAt(i) === string.charAt(i - 1)) return false; } return true; }; const generatePermutations = (string) => { if (string.length < 2) { return [string]; }; const results = []; for (let i = 0; i < string.length; i++) { const char = string.charAt(i); const remaining = string.slice(0, i).concat(string.slice(i + 1)); generatePermutations(remaining) .map(permutation => char + permutation) .filter(noRepeatingChars) .forEach(permutation => results.push(permutation)); } return results; }; const permAlone = (string) => generatePermutations(string).length; module.exports = permAlone; <file_sep>/src/remove-covered-intervals/index.test.js const removeCoveredIntervals = require('./index'); describe('removeCoveredIntervals', () => { it('should be a function', () => { expect(removeCoveredIntervals).toBeInstanceOf(Function); }); it('should return 2 intervals', () => { const intervals = [[1, 4], [3, 6], [2,8]]; expect(removeCoveredIntervals(intervals)).toEqual(2); }); it('should return 1 interval', () => { const intervals = [[1, 4], [2, 3]]; expect(removeCoveredIntervals(intervals)).toEqual(1); }); it('should return 2 intervals', () => { const intervals = [[0, 10], [5, 12]]; expect(removeCoveredIntervals(intervals)).toEqual(2); }); it('should return 2 intervals', () => { const intervals = [[3, 10], [4, 10], [5, 11]]; expect(removeCoveredIntervals(intervals)).toEqual(2); }); it('should return 1 interval', () => { const intervals = [[1, 2], [1, 4], [3, 4]]; expect(removeCoveredIntervals(intervals)).toEqual(1); }); }); <file_sep>/src/chat-order/index.js const chatOrder = (input) => { input.reverse(); const set = new Set(input); return [...set]; }; module.exports = chatOrder; <file_sep>/src/smallest-mult/index.js const lcm = (a, b) => (a * b) / gcd(a, b); const gcd = (a, b) => { if (b === 0) return a; return gcd(b, a % b); } const smallestMult = (n) => { let maxLCM = 1; for (let i = 2; i <= n; i++) { console.log(maxLCM); maxLCM = lcm(maxLCM, i); } return maxLCM; } module.exports = smallestMult; <file_sep>/src/rotate-image/index.js const rotate = (matrix) => { const n = matrix.length; for (let i = 0; i < n - i; i++) { for (let j = i; j < n - i - 1; j++) { let aux; let aux2; let source = [i, j]; let target = [j, n - 1 - i]; aux = matrix[target[0]][target[1]]; matrix[target[0]][target[1]] = matrix[source[0]][source[1]]; target = [n - 1 - i, n - 1 - j]; aux2 = aux; aux = matrix[target[0]][target[1]]; matrix[target[0]][target[1]] = aux2; target = [n - 1 - j, i]; aux2 = aux; aux = matrix[target[0]][target[1]]; matrix[target[0]][target[1]] = aux2; target = [i, j]; aux2 = aux; aux = matrix[target[0]][target[1]]; matrix[target[0]][target[1]] = aux2; } } return matrix; }; module.exports = rotate; <file_sep>/src/sliding-window/index.js const maxSumOfK = (input, k) => { let max = 0; for (let i = 0; i < k; i++) { max += input[i]; } let current = max; for (let i = k; i < input.length; i++) { current = current - input[i - k] + input[i]; max = Math.max(max, current); } return max; }; module.exports = maxSumOfK; <file_sep>/src/recent-counter/index.test.js const RecentCounter = require('./index'); describe('RecentCounter', () => { let recentCounter; beforeEach(() => { recentCounter = new RecentCounter(); }); it('should be a RecentCounter instance', () => { expect(recentCounter).toBeInstanceOf(RecentCounter); }); it('should have the ping method', () => { expect(recentCounter.ping).toBeInstanceOf(Function); }); it('should return the correct count', () => { expect(recentCounter.ping(1)).toEqual(1); expect(recentCounter.ping(100)).toEqual(2); expect(recentCounter.ping(3001)).toEqual(3); expect(recentCounter.ping(3002)).toEqual(3); }); }); <file_sep>/src/regular-expression-matching/index.test.js const isMatch = require('./index'); describe('isMatch', () => { it('should be a function', () => { expect(isMatch).toBeInstanceOf(Function); }); it('should return false', () => { expect(isMatch('aa', 'a')).toBe(false); }); it('should return true', () => { expect(isMatch('aa', 'aa')).toBe(true); }); it('should return true', () => { expect(isMatch('ab', 'a.')).toBe(true); }); it('should return true', () => { expect(isMatch('aa', 'a*')).toBe(true); }); it('should return true', () => { expect(isMatch('ab', '.*')).toBe(true); }); it('should return true', () => { expect(isMatch('aab', 'c*a*b*')).toBe(true); }); it('should return false', () => { expect(isMatch('mississippi', 'mis*is*p*.')).toBe(false); }); it('should return false', () => { expect(isMatch('ab', '.*c')).toBe(false); }); it('should return true', () => { expect(isMatch('aaa', 'a*a')).toBe(true); }); }); <file_sep>/src/largest-palindrome-product/index.js const isPalindrome = (string) => { for (let i = 0; i < Math.floor(string.length / 2); i++) { const counterIndex = string.length - i - 1; if (string.charAt(i) !== string.charAt(counterIndex)) return false; } return true; }; const largestPalindromeProduct = (n) => { const max = Math.pow(10, n) - 1; const min = Math.floor(max / 10 + 1) + 1; for (let i = max * max; i >= min; i--) { if (isPalindrome(`${i}`)) { for (let j = max; j > min; j--) { const div = i / j; if (i % j === 0 && div <= max && div >= min) return i; } } } return 9; }; module.exports = largestPalindromeProduct; <file_sep>/src/first-missing-positive/index.test.js const firstMissingPositive = require('./index'); describe('firstMissingPositive', () => { it('should be a function', () => { expect(firstMissingPositive).toBeInstanceOf(Function); }); it('should return 3', () => { const nums = [1, 2, 0]; expect(firstMissingPositive(nums)).toEqual(3); }); it('should return 2', () => { const nums = [3, 4, -1, 1]; expect(firstMissingPositive(nums)).toEqual(2); }); it('should return 1', () => { const nums = [7, 8, 9, 11, 12]; expect(firstMissingPositive(nums)).toEqual(1); }); it('should return 1', () => { const nums = []; expect(firstMissingPositive(nums)).toEqual(1); }); it('should return 1', () => { const nums = [-5]; expect(firstMissingPositive(nums)).toEqual(1); }); it('should return 2', () => { const nums = [1]; expect(firstMissingPositive(nums)).toEqual(2); }); }); <file_sep>/src/registration-system/index.js const registrationSystem = (input) => { const memo = {}; return input.map(value => { const current = memo[value]; if (current) { memo[value] = current + 1; return `${value}${current}`; } else { memo[value] = 1; return 'OK'; } }); }; module.exports = registrationSystem; <file_sep>/src/breath-first-search/index.js const bfs = (matrix, initialNode) => { const result = {}; const visited = []; const queue = []; for (let i = 0; i < matrix.length; i++) { result[i] = Infinity; visited[i] = false; } // init the node result[initialNode] = 0; visited[initialNode] = true; matrix[initialNode].forEach((value, index) => { if (value > 0) { queue.push({ node: index, parent: initialNode }); } }); while(queue.length > 0) { const { node, parent } = queue.shift(); visited[node] = true; result[node] = matrix[parent][node] + result[parent]; matrix[node].forEach((value, index) => { if (value > 0 && !visited[index]) { queue.push({ node: index, parent: node }); } }); } return result; }; module.exports = bfs; <file_sep>/src/remove-nth-from-end/index.test.js const removeNthFromEnd = require('./index'); const { ListNode } = require('./index'); const arrayToList = (array) => { let head; let current; array.forEach(element => { if (head) { current.next = new ListNode(element); current = current.next; } else { head = new ListNode(element); current = head; } }); return head; }; const listToArray = (head) => { let current = head; const result = []; while(current) { result.push(current.val); current = current.next; } return result; }; describe('removeNthFromEnd', () => { it('should be a function', () => { expect(removeNthFromEnd).toBeInstanceOf(Function); }); it('should return [1, 2, 3, 5]', () => { const input = arrayToList([1, 2, 3, 4, 5]); const result = listToArray(removeNthFromEnd(input, 2)); expect(result).toEqual([1, 2, 3, 5]); }); it('should return []', () => { const input = arrayToList([1]); const result = listToArray(removeNthFromEnd(input, 1)); expect(result).toEqual([]); }); it('should return [1]', () => { const input = arrayToList([1, 2]); const result = listToArray(removeNthFromEnd(input, 1)); expect(result).toEqual([1]); }); it('should return [2]', () => { const input = arrayToList([1, 2]); const result = listToArray(removeNthFromEnd(input, 2)); expect(result).toEqual([2]); }); }); <file_sep>/src/wildcard-matching/index.test.js const isMatch = require('./index'); describe('isMatch', () => { it('should be a function', () => { expect(isMatch).toBeInstanceOf(Function); }); it('should return false', () => { const s = 'aa'; const p = 'a'; expect(isMatch(s, p)).toBe(false); }); it('should return true', () => { const s = 'aa'; const p = '*'; expect(isMatch(s, p)).toBe(true); }); it('should return false', () => { const s = 'cb'; const p = '?a'; expect(isMatch(s, p)).toBe(false); }); it('should return true', () => { const s = 'adceb'; const p = '*a*b'; expect(isMatch(s, p)).toBe(true); }); it('should return false', () => { const s = 'acdcb'; const p = 'a*c?b'; expect(isMatch(s, p)).toBe(false); }); it('should return false', () => { const s = ''; const p = '******'; expect(isMatch(s, p)).toBe(true); }); it('should return true', () => { const s = 'aaabababaaabaababbbaaaabbbbbbabbbbabbbabbaabbababab'; const p = '*ab***ba**b*b*aaab*b'; expect(isMatch(s, p)).toBe(true); }); }); <file_sep>/src/maximum-sub-array/index.js const maxSubArray = (nums) => { if (nums.length === 1) return nums[0]; const half = Math.floor(nums.length / 2); const left = nums.slice(0, half); const right = nums.slice(half); console.log({ nums, left, right }); const best = Math.max(maxSubArray(left), maxSubArray(right)); let bestSumLeft = left[left.length - 1]; let sumLeft = left[left.length - 1]; for (let i = left.length - 2; i >= 0; i--) { sumLeft += left[i]; Math.max(bestSumLeft, sumLeft); } let bestSumRight = right[0]; let sumRight = right[0]; for (let i = 1; i < right.length; i++) { sumRight += right[i]; Math.max(bestSumRight, sumRight); } return Math.max(best, bestSumLeft + bestSumRight); }; module.exports = maxSubArray; <file_sep>/src/find-first-last-position-sorted-array/index.test.js const searchRange = require('./index'); describe('searchRange', () => { it('should be a function', () => { expect(searchRange).toBeInstanceOf(Function); }); it('should return [3, 4]', () => { const nums = [5, 7, 7, 8, 8, 10]; const target = 8; expect(searchRange(nums, target)).toEqual([3, 4]); }); it('should return [3, 4]', () => { const nums = [5, 7, 7, 8, 8, 10]; const target = 6; expect(searchRange(nums, target)).toEqual([-1, -1]); }); it('should return [3, 4]', () => { const nums = []; const target = 0; expect(searchRange(nums, target)).toEqual([-1, -1]); }); }); <file_sep>/src/jump-game/index.js const canJump = (nums, currentIndex = 0) => { if (currentIndex === nums.length - 1) return true; if (currentIndex >= nums.length) return false; const maxLengthJump = nums[currentIndex]; let results = [false]; for (let i = 1; i <= maxLengthJump; i++) { results.push(canJump(nums, currentIndex + i)); } return results.some(a => a); }; module.exports = canJump; <file_sep>/src/binary-search-tree/index.js const displayTree = tree => console.log(JSON.stringify(tree, null, 2)); class Node { left = null; right = null; constructor(value) { this.value = value; } } class BinarySearchTree { root = null; add(value, currentNode = this.root) { const newNode = new Node(value); if (currentNode === null) { this.root = newNode; return; } if (currentNode.value === value) { return null; } let nextNodeKey = value <= currentNode.value ? 'left' : 'right'; if (currentNode[nextNodeKey]) return this.add(value, currentNode[nextNodeKey]); currentNode[nextNodeKey] = newNode; } findMin() { if (!this.root) return null; let current = this.root; while (current.left) { current = current.left; } return current.value; } findMax() { if (!this.root) return null; let current = this.root; while (current.right) { current = current.right; } return current.value; } isPresent(value) { let current = this.root; while (current && current.value !== value) { current = value <= current.value ? current.left : current.right; } return !!current; } findMinHeight() { const fn = (currentNode = this.root) => { if (currentNode === null) return 0; return 1 + Math.min( fn(currentNode.left), fn(currentNode.right), ); }; return fn() - 1; } findMaxHeight() { const fn = (currentNode = this.root) => { if (currentNode === null) return 0; return 1 + Math.max( fn(currentNode.left), fn(currentNode.right), ); }; return fn() - 1; } isBalanced() { const min = this.findMinHeight(); const max = this.findMaxHeight(); return max - min <= 1; } inorder() { if (!this.root) return null; const fn = (current = this.root) => { if (!current) return []; return [ ...fn(current.left), current.value, ...fn(current.right), ]; } return fn(); } preorder() { if (!this.root) return null; const fn = (current = this.root) => { if (!current) return []; return [ current.value, ...fn(current.left), ...fn(current.right), ]; } return fn(); } postorder() { if (!this.root) return null; const fn = (current = this.root) => { if (!current) return []; return [ ...fn(current.left), ...fn(current.right), current.value, ]; } return fn(); } levelOrder() { if (!this.root) return null; const queue = [this.root]; const result = []; while (queue.length) { const node = queue.shift(); result.push(node.value); if (node.left) queue.push(node.left); if (node.right) queue.push(node.right); } return result; } reverseLevelOrder() { if (!this.root) return null; const queue = [this.root]; const result = []; while (queue.length) { const node = queue.shift(); result.push(node.value); if (node.right) queue.push(node.right); if (node.left) queue.push(node.left); } return result; } remove(value) { let current = this.root; let parent; while (current && current.value !== value) { parent = current; const key = value < current.value ? 'left' : 'right'; current = current[key]; } if (!current) return null; const children = (current.left ? 1 : 0) + (current.right ? 1 : 0); if (current === this.root) { if (children > 1) { current.right.left = current.left; this.root = current.right; } else { this.root = current.left || current.right; } } else { if (children > 1) { parent.right = current.right let leftPosition = current.right.left; while (leftPosition.left) { leftPosition = leftPosition.left; } leftPosition.left = current.left; } else { const key = value < parent.value ? 'left' : 'right'; parent[key] = current.left || current.right; } } current.left = null; current.right = null; return current; } invert() { if (!this.root) return null; const traverse = (current = this.root) => { if (!current) return; const { left, right } = current; current.left = right; current.right = left; traverse(left); traverse(right); } return traverse(); } } module.exports = BinarySearchTree; module.exports.Node = Node; module.exports.displayTree = displayTree; <file_sep>/src/garden-problem/index.js const noPlant = (garden, index) => { return garden[index] !== 1; } const canPlant = (garden, n) => { const newGarden = [...garden]; let newPlants = 0; for (let i = 0; i < newGarden.length; i++) { if (noPlant(garden, i - 1) && noPlant(garden, i) && noPlant(garden, i + 1)) { newGarden[i] = 1; newPlants++; } } return newPlants >= n; }; module.exports = canPlant; <file_sep>/src/set/index.js class Set { constructor() { this.dictionary = {}; } has(item) { return this.dictionary[item] !== undefined; } values() { return Object.values(this.dictionary); } add(item) { if (this.has(item)) { return false; } else { this.dictionary[item] = item; return true; } } remove(item) { if (this.has(item)) { delete this.dictionary[item]; return true; } else { return false; } } size() { return this.values().length; } union(set) { const resultSet = new Set(); const add = (item) => resultSet.add(item); this.values().forEach(add); set.values().forEach(add); return resultSet; } intersection(set) { const resultSet = new Set(); this.values().forEach(value => { if (set.has(value)) { resultSet.add(value); } }); return resultSet; } difference(set) { const resultSet = new Set(); this.values().forEach(value => { if (!set.has(value)) { resultSet.add(value); } }); return resultSet; } isSubsetOf(set) { return this .values() .every(value => set.has(value)); } } module.exports = Set; <file_sep>/src/permutations/index.test.js const permute = require('./index'); describe('permute', () => { it('should be a function', () => { expect(permute).toBeInstanceOf(Function); }); it('should return 1 permutation', () => { expect(permute([1])).toEqual([[1]]); }); it('should return 2 permutations', () => { expect(permute([0, 1])).toEqual([[0, 1], [1, 0]]); }); it('should return 6', () => { expect(permute([1, 2, 3])).toEqual([ [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1], ]); }); }); <file_sep>/src/contains-duplicate/index.js // this solution is order of N const containsDuplicate = (array) => { return array.length !== new Set(array).size; }; module.exports = containsDuplicate; <file_sep>/src/is-binary-search-tree/index.test.js const BinarySearchTree = require('../binary-search-tree'); const { Node } = require('../binary-search-tree'); const isBinarySearchTree = require('./index'); describe('isBinarySearchTree', () => { it('should be a function', () => { expect(isBinarySearchTree).toBeInstanceOf(Function); }); it('should return true if the tree is a binary search tree', () => { const node1 = new Node(1); const node2 = new Node(2); const node3 = new Node(3); const node4 = new Node(4); const node5 = new Node(5); node3.left = node2; node2.left = node1; node3.right = node4; node4.right = node5; const tree = new BinarySearchTree(); tree.root = node3; expect(isBinarySearchTree(tree)).toBe(true); }); it('should return false if the tree is not a binary search tree', () => { const node1 = new Node(1); const node2 = new Node(2); const node3 = new Node(3); const node4 = new Node(4); const node5 = new Node(5); node1.left = node5; node1.right = node2; node5.left = node4 node5.right = node3; const tree = new BinarySearchTree(); tree.root = node1; expect(isBinarySearchTree(tree)).toBe(false); }); }); <file_sep>/src/map/index.js class Map { collection = {} add(key, value) { this.collection[key] = value; } remove(key) { delete this.collection[key]; } get(key) { return this.collection[key]; } has(key) { return !!this.collection[key]; } values() { return Object.values(this.collection); } clear() { this.collection = {}; } size() { return Object.values(this.collection).length; } }; module.exports = Map; <file_sep>/src/remove-nth-from-end/index.js class ListNode { constructor(val, next) { this.val = (val === undefined ? 0 : val); this.next = (next === undefined ? null : next) } } const removeNthFromEnd = (head, n) => { let i = 0; let current = head; let prev = head; while(current) { current = current.next; if (i > n) { prev = prev.next; } i++; } if (i === n) { head = head.next; } else if (prev.next) { prev.next = prev.next.next; } return head; }; module.exports = removeNthFromEnd; module.exports.ListNode = ListNode; <file_sep>/src/pow/index.test.js const myPow = require('./index'); describe('myPow', () => { it('should be a function', () => { expect(myPow).toBeInstanceOf(Function); }); it('should return 1024.00000', () => { expect(myPow(2.0, 10)).toEqual(1024.0); }); it('should return 9.26100', () => { expect(myPow(2.1, 3)).toEqual(9.26100); }); it('should return 0.25', () => { expect(myPow(2.0, -2)).toEqual(0.25); }); }); <file_sep>/src/linked-list-cycle/index.test.js const hasCycle = require('./index'); class ListNode { constructor(val) { this.val = val; this.next = null; } } describe('hasCycle', () => { it('should be a function', () => { expect(hasCycle).toBeInstanceOf(Function); }); it('should return true', () => { const head = new ListNode(3); const n2 = new ListNode(2); const n3 = new ListNode(0); const n4 = new ListNode(-4); head.next = n2; n2.next = n3; n3.next = n4; n4.next = n2; // the cycle is in here expect(hasCycle(head)).toBe(true); }); it('should return true', () => { const head = new ListNode(1); const n2 = new ListNode(2); head.next = n2; n2.next = head; // the cycle is in here expect(hasCycle(head)).toBe(true); }); it('should return false', () => { const head = new ListNode(1); expect(hasCycle(head)).toBe(false); }); }); <file_sep>/src/even-fibonacci-numbers/index.js const fiboEvenSum = (n) => { let result = 0; const fibonacci = [0, 1]; while (fibonacci[fibonacci.length - 1] <= n) { const newNumber = fibonacci[1] + fibonacci[0]; if (newNumber % 2 === 0) { result += newNumber; } fibonacci[0] = fibonacci[1]; fibonacci[1] = newNumber; } return result; }; module.exports = fiboEvenSum; <file_sep>/src/pairwise/index.js const pairwise = (array, n) => { const usedIndexes = {}; const indexes = array .reduce((accum, value, index) => { return { ...accum, [value]: accum[value] ? [...accum[value], index] : [index] }; }, {}); const result = []; for (let i = 0; i < array.length; i++) { const target = n - array[i]; if (indexes[target] && indexes[target].length > 0 && usedIndexes[i] === undefined) { let targetIndex = indexes[target].shift(); if (targetIndex === i && indexes[target].length > 0) { const aux = targetIndex; targetIndex = indexes[target][0]; indexes[target][0] = aux; } if (usedIndexes[targetIndex] === undefined && targetIndex !== i) { usedIndexes[i] = true; usedIndexes[targetIndex] = true; result.push([array[i], target]); } } } return Object .keys(usedIndexes) .map(value => parseInt(value, 10)) .reduce((a, b) => a + b, 0); }; module.exports = pairwise; <file_sep>/src/product-of-arrays-except-self/index.test.js const productExceptSelf = require('./index'); const tests = [ { input: [1, 2, 3, 4], result: [24, 12, 8, 6], }, { input: [-1, 1, 0, -3, 3], result: [0, 0, 9, 0, 0], }, ]; describe('productExceptSelf', () => { it('should be a function', () => { expect(productExceptSelf).toBeInstanceOf(Function); }); tests.forEach(({ input, result }) => { it(`input ${JSON.stringify(input)} should return: ${result}`, () => { expect(productExceptSelf(input)).toEqual(result); }); }); }); <file_sep>/src/merge-sort/index.js const merge = (left, right) => { const [leftHead, ...leftRest] = left; const [rightHead, ...rightRest] = right; if (!leftHead) return right; if (!rightHead) return left; if (leftHead < rightHead) { return [leftHead, ...merge(leftRest, right)]; } else { return [rightHead, ...merge(left, rightRest)]; } }; const mergeSort = (array) => { if (array.length <= 1) return array; const mid = Math.floor(array.length / 2); const left = mergeSort(array.slice(0, mid)); const right = mergeSort(array.slice(mid)); return merge(left, right); }; module.exports = mergeSort; <file_sep>/src/hash-table/index.js let called = 0; const hash = string => { called++; let hashed = 0; for (var i = 0; i < string.length; i++) { hashed += string.charCodeAt(i); } return hashed; }; class HashTable { collection = {} add(key, value) { const hashedKey = hash(key); if (!this.collection[hashedKey]) { this.collection[hashedKey] = {}; } this.collection[hashedKey][key] = value; } remove(key) { const hashedKey = hash(key); if (this.collection[hashedKey]) { delete this.collection[hashedKey][key]; if (Object.keys(this.collection[hashedKey]).length === 0) { delete this.collection[hashedKey]; } } } lookup(key) { const hashedKey = hash(key); if (this.collection[hashedKey]) { return this.collection[hashedKey][key] || null; } return null; } } module.exports = HashTable; <file_sep>/src/even-fibonacci-numbers/index.test.js const fiboEvenSum = require('./index'); describe(fiboEvenSum, () => { it('should be a function', () => { expect(fiboEvenSum).toBeInstanceOf(Function); }); it('should return a number', () => { expect(typeof fiboEvenSum(10)).toBe('number'); }); it('should return an even value', () => { expect(fiboEvenSum(10) % 2).toEqual(0); }); it('should return 10', () => { expect(fiboEvenSum(8)).toEqual(10); }); it('should return 10', () => { expect(fiboEvenSum(10)).toEqual(10); }); it('should return 44', () => { expect(fiboEvenSum(34)).toEqual(44) }); it('should return 44', () => { expect(fiboEvenSum(60)).toEqual(44) }); it('should return 798', () => { expect(fiboEvenSum(1000)).toEqual(798); }); it('should return 60696', () => { expect(fiboEvenSum(100000)).toEqual(60696); }); it('should return 4613732', () => { expect(fiboEvenSum(4000000)).toEqual(4613732); }); }); <file_sep>/src/candy-bars/index.js const balanceCandyBars = (candiesA, candiesB) => { const sum = (a, b) => a + b; const sumA = candiesA.reduce(sum); const sumB = candiesB.reduce(sum); const target = (sumA - sumB) / 2; let result = []; candiesA.forEach(candyA => { candiesB.forEach(candyB => { if (candyA - candyB === target) { result.push([candyA, candyB]); } }); }); return result; }; module.exports = balanceCandyBars; <file_sep>/src/permutations/index.js const permute = (nums) => { if (nums.length === 1) return [nums]; let result = []; for (let i = 0; i < nums.length; i++) { const currentItem = nums[i]; const rest = nums.slice(0, i).concat(nums.slice(i + 1)); const permutations = permute(rest).map(permutation => [currentItem, ...permutation]); result = [...result, ...permutations]; } return result; }; module.exports = permute; <file_sep>/src/three-sum/index.test.js const threeSum = require('./index'); describe('threeSum', () => { it('should be a function', () => { expect(threeSum).toBeInstanceOf(Function); }); it('should return [[-1, -1, 2], [-1, 0, 1]]', () => { const input = [-1, 0, 1, 2, -1, -4]; expect(threeSum(input)).toEqual([[-1, -1, 2], [-1, 0, 1]]); }); it('should return []', () => { expect(threeSum([])).toEqual([]); }); it('should return []', () => { expect(threeSum([0])).toEqual([]); }); it('should return [[0, 0, 0]]', () => { expect(threeSum([0, 0, 0])).toEqual([[0, 0, 0]]); }); }); <file_sep>/src/valid-numbers/index.test.js const isValidNumber = require('./index'); describe('isValidNumber', () => { it('should be a function', () => { expect(isValidNumber).toBeInstanceOf(Function); }); it('should return true', () => { expect(isValidNumber('7')).toBe(true); }); it('should return true', () => { expect(isValidNumber('0011')).toBe(true); }); it('should return true', () => { expect(isValidNumber('+3.14')).toBe(true); }); it('should return true', () => { expect(isValidNumber('4.')).toBe(true); }); it('should return true', () => { expect(isValidNumber('-.9')).toBe(true); }); it('should return true', () => { expect(isValidNumber('-123.456')).toBe(true); }); it('should return true', () => { expect(isValidNumber('-0.1')).toBe(true); }); it('should return false', () => { expect(isValidNumber('abc')).toBe(false); }); it('should return false', () => { expect(isValidNumber('1a')).toBe(false); }); it('should return false', () => { expect(isValidNumber('e8')).toBe(false); }); it('should return false', () => { expect(isValidNumber('–6')).toBe(false); }); it('should return false', () => { expect(isValidNumber('-+3')).toBe(false); }); it('should return false', () => { expect(isValidNumber('95x54e53.')).toBe(false); }); }); <file_sep>/src/circular-queue/index.test.js const CircularQueue = require('./index'); describe('CircularQueue', () => { let circularQueue; beforeEach(() => { circularQueue = new CircularQueue(5); }); it('should be instance of CircularQueue', () => { expect(circularQueue).toBeInstanceOf(CircularQueue); }); it('should have an enqueue method', () => { expect(circularQueue.enqueue).toBeInstanceOf(Function); }); it('should have a dequeue method', () => { expect(circularQueue.dequeue).toBeInstanceOf(Function); }); it('should add items to the circular queue', () => { circularQueue.enqueue(1); circularQueue.enqueue(2); circularQueue.enqueue(3); expect(circularQueue.print()).toEqual([1, 2, 3, null, null]); }); it('should add items to the circular queue', () => { circularQueue.enqueue(1); circularQueue.enqueue(2); circularQueue.enqueue(3); circularQueue.enqueue(4); circularQueue.enqueue(5); circularQueue.enqueue(6); circularQueue.enqueue(7); expect(circularQueue.print()).toEqual([1, 2, 3, 4, 5]); }); it('should dequeue items from the queue', () => { circularQueue.enqueue(1); circularQueue.enqueue(2); circularQueue.enqueue(3); circularQueue.enqueue(4); expect(circularQueue.dequeue()).toEqual(1); expect(circularQueue.dequeue()).toEqual(2); expect(circularQueue.dequeue()).toEqual(3); }); it('should set items to null when dequeued', () => { circularQueue.enqueue(1); circularQueue.enqueue(2); circularQueue.enqueue(3); expect(circularQueue.dequeue()).toEqual(1); expect(circularQueue.print()).toEqual([null, 2, 3, null, null]); }); it('should not dequeue items past the writer poiner', () => { circularQueue.enqueue(1); circularQueue.enqueue(2); circularQueue.dequeue(); circularQueue.dequeue(); expect(circularQueue.dequeue()).toBe(null); expect(circularQueue.print()).toEqual([null, null, null, null, null]); }); }); <file_sep>/src/doubly-linked-list/index.test.js const DoublyLinkedList = require('./index'); describe('DoublyLinkedList', () => { let doublyLinkedList; beforeEach(() => { doublyLinkedList = new DoublyLinkedList(); }); it('should be of DoublyLinkedList instance', () => { expect(doublyLinkedList).toBeInstanceOf(DoublyLinkedList); }); it('should have the add method', () => { expect(doublyLinkedList.add).toBeInstanceOf(Function); }); it('should have the remove method', () => { expect(doublyLinkedList.remove).toBeInstanceOf(Function); }); it('should remove an item from an empty list return null', () => { expect(doublyLinkedList.remove(2)).toBe(null); }); it('should add items to the list', () => { doublyLinkedList.add(1); doublyLinkedList.add(2); doublyLinkedList.add(3); expect(doublyLinkedList.head.data).toEqual(1); expect(doublyLinkedList.head.next.data).toEqual(2); expect(doublyLinkedList.head.next.next.data).toEqual(3); }); it('should track of the previous node', () => { doublyLinkedList.add(1); doublyLinkedList.add(2); doublyLinkedList.add(3); expect(doublyLinkedList.head.prev).toBe(null); expect(doublyLinkedList.head.next.prev.data).toEqual(1); expect(doublyLinkedList.head.next.next.prev.data).toEqual(2); }); it('should remove the first item of the list', () => { doublyLinkedList.add(1); doublyLinkedList.add(2); doublyLinkedList.remove(1); expect(doublyLinkedList.head.data).toEqual(2); }); it('should remove the first item of the list', () => { doublyLinkedList.add(1); doublyLinkedList.add(2); doublyLinkedList.remove(2); expect(doublyLinkedList.head.next).toBe(null); }); it('should have a reverse method', () => { expect(doublyLinkedList.reverse).toBeInstanceOf(Function); }); it('should return null reversing an empty linked list', () => { expect(doublyLinkedList.reverse()).toEqual(null); }); it('should reverse the list', () => { doublyLinkedList.add(1); doublyLinkedList.add(2); doublyLinkedList.add(3); doublyLinkedList.reverse(); expect(doublyLinkedList.head.data).toEqual(3); expect(doublyLinkedList.head.next.data).toEqual(2); expect(doublyLinkedList.head.next.next.data).toEqual(1); }); it('should maintain the correct references to next and prev', () => { doublyLinkedList.add(1); doublyLinkedList.add(2); doublyLinkedList.add(3); doublyLinkedList.reverse(); expect(doublyLinkedList.head.prev).toBe(null); expect(doublyLinkedList.head.next.prev.data).toEqual(3); expect(doublyLinkedList.head.next.next.prev.data).toEqual(2); }); }); <file_sep>/src/reverse-list/index.test.js const reverseList = require('./index'); class ListNode { constructor(val, next) { this.val = (val === undefined ? 0 : val); this.next = (next === undefined ? null : next); } } describe('reverseList', () => { it('should be a function', () => { expect(reverseList).toBeInstanceOf(Function); }); it('should return the reverse list', () => { const node5 = new ListNode(5); const node4 = new ListNode(4, node5); const node3 = new ListNode(3, node4); const node2 = new ListNode(2, node3); const head = new ListNode(1, node2); const newHead = reverseList(head); expect(newHead.val).toBe(5); expect(newHead.next.val).toBe(4); expect(newHead.next.next.val).toBe(3); expect(newHead.next.next.next.val).toBe(2); expect(newHead.next.next.next.next.val).toBe(1); expect(newHead.next.next.next.next.next).toBeNull(); }); it('should return the reverse list', () => { const node2 = new ListNode(2); const head = new ListNode(1, node2); const newHead = reverseList(head); expect(newHead.val).toBe(2); expect(newHead.next.val).toBe(1); expect(newHead.next.next).toBeNull(); }); it('should return the reverse list', () => { const newHead = reverseList(null); expect(newHead).toBeNull(); }); }); <file_sep>/src/chat-order/index.test.js const chatOrder = require('./index'); describe('chatOrder', () => { it('should be a function', () => { expect(chatOrder).toBeInstanceOf(Function); }); it('should return the list', () => { const input = [ 'alina', 'maria', 'ekaterina', 'darya', 'darya', 'ekaterina', 'maria', 'alina', ]; const response = [ 'alina', 'maria', 'ekaterina', 'darya', ]; expect(chatOrder(input)).toEqual(response); }); it('should return the list', () => { const input = ['alex', 'ivan', 'roman', 'ivan']; const response = ['ivan', 'roman', 'alex']; expect(chatOrder(input)).toEqual(response); }); }); <file_sep>/src/set/index.test.js const Set = require('./index'); describe('Set', () => { let set; beforeEach(() => { set = new Set(); }); it('should be a Set', () => { expect(set).toBeInstanceOf(Set); }); it('should have the add method', () => { expect(set.add).toBeInstanceOf(Function); }); it('should have values method', () => { expect(set.values).toBeInstanceOf(Function); }); it('should have the remove method', () => { expect(set.remove).toBeInstanceOf(Function); }); it('should have a size method', () => { expect(set.size).toBeInstanceOf(Function); }); it('should have a has method', () => { expect(set.has).toBeInstanceOf(Function); }); it('should have the union method', () => { expect(set.union).toBeInstanceOf(Function); }); it('should have the intersection method', () => { expect(set.intersection).toBeInstanceOf(Function); }); it('should have the difference method', () => { expect(set.difference).toBeInstanceOf(Function); }); it('should have the isSubsetOf method', () => { expect(set.isSubsetOf).toBeInstanceOf(Function); }); it('should not add duplicate values', () => { set.add(1); set.add(1); expect(set.values()).toEqual([1]); }); it('should return true when an item is successfully added', () => { expect(set.add(1)).toBe(true); }); it('should return false when an item is duplicated', () => { set.add(1); expect(set.add(1)).toBe(false); }); it('should remove only items present', () => { set.add(1); set.add(2); expect(set.remove(1)).toBe(true); expect(set.remove(3)).toBe(false); }); it('should remove the item from the set', () => { set.add(1); set.add(2) set.remove(1); expect(set.values()).toEqual([2]); }); it('should return the correct size of the set', () => { set.add(1); set.add(1); set.add(2); set.add(3); expect(set.size()).toEqual(3); }); it('should make a union of two sets', () => { set.add('a'); set.add('b'); set.add('c'); const set2 = new Set(); set2.add('c'); set2.add('d'); expect(set.union(set2).values()).toEqual(['a', 'b', 'c', 'd']); }); it('should make an intersection of two sets', () => { set.add('a'); set.add('b'); set.add('c'); const set2 = new Set(); set2.add('a'); set2.add('b'); set2.add('d'); set2.add('e'); expect(set.intersection(set2).values()).toEqual(['a', 'b']); }); it('should make the difference of two sets', () => { set.add('a'); set.add('b'); set.add('c'); const set2 = new Set(); set2.add('a'); set2.add('b'); set2.add('d'); set2.add('e'); expect(set.difference(set2).values()).toEqual(['c']); }); it('should return true if a is subset of b', () => { set.add('a'); set.add('b'); const set2 = new Set(); set2.add('a'); set2.add('b'); set2.add('c'); set2.add('d'); expect(set.isSubsetOf(set2)).toBe(true); }); it('should return if a is not a subset of b', () => { set.add('a'); set.add('b'); set.add('c'); const set2 = new Set(); set2.add('a'); set2.add('b'); expect(set.isSubsetOf(set2)).toBe(false); }); it('should return true on a subset of an empty set', () => { expect(set.isSubsetOf(new Set())).toBe(true); }); }); <file_sep>/src/letter-combination-of-phone/index.test.js const letterCombinations = require('./index'); describe('letterCombinations', () => { it('should be a function', () => { expect(letterCombinations).toBeInstanceOf(Function); }); it('should return ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]', () => { const result = [ 'ad', 'bd', 'cd', 'ae', 'be', 'ce', 'af', 'bf', 'cf' ]; expect(letterCombinations('23')).toEqual(result); }); it('should return []', () => { const result = []; expect(letterCombinations('')).toEqual(result); }); it('should return ["a", "b", "c"]', () => { const result = ['a', 'b', 'c']; expect(letterCombinations('2')).toEqual(result); }); }); <file_sep>/src/maximum-sub-array/index.test.js const maxSubArray = require('./index'); describe('maxSubArray', () => { it('should be a function', () => { expect(maxSubArray).toBeInstanceOf(Function); }); it('should return 6', () => { const nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]; expect(maxSubArray(nums)).toEqual(6); }); it('should return 1', () => { const nums = [1]; expect(maxSubArray(nums)).toEqual(1); }); it('should return 23', () => { const nums = [5, 4, -1, 7, 8]; expect(maxSubArray(nums)).toEqual(23); }); }); <file_sep>/src/recent-counter/index.js class RequestCounter { pings = []; ping(time) { this.pings.push(time); const lowerBound = time - 3000; this.pings = this.pings.filter(p => p >= lowerBound); return this.pings.length; } } module.exports = RequestCounter; <file_sep>/src/symetric-difference/index.js const sym = (...args) => { if (args.length === 1) return args[0]; const [first, second, ...rest] = args; const count = [...new Set(first), ...new Set(second)] .reduce((accum, value) => ({ ...accum, [value]: accum[value] ? accum[value] + 1 : 1, }), {}); const result = Object .entries(count) .filter(([, value]) => value === 1) .map(([key]) => parseInt(key, 10)) return sym(result, ...rest); }; module.exports = sym; <file_sep>/src/circular-queue/index.js class CircularQueue { constructor(size) { this.read = 0; this.write = 0; this.max = size - 1; this.queue = new Array(size).fill(null); } enqueue(item) { if (this.queue[this.write] === null) { this.queue[this.write] = item; this.write = (this.write + 1) % (this.max + 1); return item; } return null; } dequeue() { if (this.queue[this.read] !== null) { const item = this.queue[this.read]; this.queue[this.read] = null; this.read = (this.read + 1) % (this.max + 1); return item; } return null; } print() { return this.queue; } } module.exports = CircularQueue; <file_sep>/src/product-of-arrays-except-self/index.js const productExceptSelf = (input) => { const result = [] let left = 1; let right = 1; for (let i = 0; i < input.length; i++) { result[i] = left; left = left * input[i]; } for (let i = input.length - 1; i >= 0; i--) { result[i] = result[i] * right; right = right * input[i]; } return result; }; module.exports = productExceptSelf; <file_sep>/src/str-str/index.js const strStr = (haystack, needle) => { if (needle.length === 0) return 0; for (let i = 0; i < haystack.length; i++) { let match = true; for (let j = 0; j < needle.length; j++) { if (haystack.charAt(i + j) !== needle.charAt(j)) { match = false; break; } } if (match) return i; } return -1; }; module.exports = strStr; <file_sep>/src/linked-list/index.test.js const LinkedList = require('./index'); describe(LinkedList, () => { let linkedList; beforeEach(() => { linkedList = new LinkedList(); }); it('should be a LinkedList', () => { expect(linkedList).toBeInstanceOf(LinkedList); }); it('should have an add method', () => { expect(linkedList.add).toBeInstanceOf(Function); }); it('should have a head method', () => { expect(linkedList.head).toBeInstanceOf(Function); }); it('should have a size method', () => { expect(linkedList.size).toBeInstanceOf(Function); }); it('should assign head to the first node added', () => { linkedList.add(1); linkedList.add(2); expect(linkedList.head().element).toEqual(1); }); it('should count the correct ammount of nodes', () => { linkedList.add(1); expect(linkedList.size()).toEqual(1); linkedList.add(2); linkedList.add(3); expect(linkedList.size()).toEqual(3); }); it('should have a remove method', () => { expect(linkedList.remove).toBeInstanceOf(Function); }); it('should remove the head of the linked list', () => { linkedList.add(1); linkedList.add(2); expect(linkedList.head().element).toEqual(1); linkedList.remove(1); expect(linkedList.head().element).toEqual(2); }); it('should remoce and decrease the length of the linkedList', () => { linkedList.add(1); linkedList.add(2); linkedList.add(3); expect(linkedList.size()).toEqual(3); linkedList.remove(2); expect(linkedList.size()).toEqual(2); }); it('should remove and reassign the reference to the previous node', () => { linkedList.add(1); linkedList.add(2); linkedList.add(3); linkedList.remove(2); expect(linkedList.head().next.element).toEqual(3); }); it('should not change the list if the element is not present on the list', () => { linkedList.add(1); linkedList.add(2); linkedList.add(3); linkedList.remove(4); expect(linkedList.head().element).toEqual(1); expect(linkedList.head().next.element).toEqual(2); expect(linkedList.head().next.next.element).toEqual(3); expect(linkedList.head().next.next.next).toBe(null); }); it('should have an isEmpty method', () => { expect(linkedList.isEmpty).toBeInstanceOf(Function); }); it('should have an indexOf method', () => { expect(linkedList.indexOf).toBeInstanceOf(Function); }); it('should have elementAt method', () => { expect(linkedList.elementAt).toBeInstanceOf(Function); }); it('should return false when there are elements in the list', () => { linkedList.add(1); linkedList.add(2); linkedList.add(3); expect(linkedList.isEmpty()).toBe(false); }); it('should return true when there are no elements in the list', () => { expect(linkedList.isEmpty()).toBe(true); }); it('should return the index of a given element', () => { linkedList.add(1); linkedList.add(2); linkedList.add(3); expect(linkedList.indexOf(2)).toEqual(1); }); it('should return -1 if the element is not found', () => { linkedList.add(1); linkedList.add(2); linkedList.add(3); expect(linkedList.indexOf(7)).toEqual(-1); }); it('should return the element at given index', () => { linkedList.add(1); linkedList.add(2); linkedList.add(3); expect(linkedList.elementAt(2)).toEqual(3); }); it('should return undefined if the item is not found', () => { linkedList.add(1); linkedList.add(2); linkedList.add(3); expect(linkedList.elementAt(3)).toBeUndefined(); }); it('should have a removeAt method', () => { expect(linkedList.removeAt).toBeInstanceOf(Function); }); it('should reduce the length of the linked list by one', () => { linkedList.add(1); linkedList.add(2); linkedList.add(3); linkedList.removeAt(1); expect(linkedList.size()).toEqual(2); }); it('should remove the elemnt at the specified index', () => { linkedList.add(1); linkedList.add(2); linkedList.add(3); linkedList.removeAt(1); expect(linkedList.head().element).toEqual(1); expect(linkedList.head().next.element).toEqual(3); }); it('it should remove when only one element', () => { linkedList.add(1); expect(linkedList.removeAt(0)).toEqual(1); expect(linkedList.size()).toEqual(0); }); it('should return the element removed by the method', () => { linkedList.add(1); linkedList.add(2); linkedList.add(3); expect(linkedList.removeAt(1)).toEqual(2); }); it('should return null if the index is less than 0', () => { linkedList.add(1); linkedList.add(2); linkedList.add(3); expect(linkedList.removeAt(-2)).toEqual(null); }); it('should return null if the index is greater than last index', () => { linkedList.add(1); linkedList.add(2); linkedList.add(3); expect(linkedList.removeAt(4)).toEqual(null); expect(linkedList.size()).toEqual(3); }); it('should have an addAt method', () => { expect(linkedList.addAt).toBeInstanceOf(Function); }); it('should #addAt increase the length of the list', () => { linkedList.add(1); linkedList.add(2); linkedList.add(3); linkedList.addAt(1, 5); expect(linkedList.size()).toEqual(4); }); it('should #addAt return false if was unable to add the element', () => { linkedList.add(1); linkedList.add(2); linkedList.add(3); expect(linkedList.addAt(4)).toBe(false); }); }); <file_sep>/src/trie/index.js class Node { keys = new Map(); end = false; setEnd() { this.end = true; } isEnd() { return this.end; } } class Trie { root = new Node(); add(word) { const letters = word.split(''); let current = this.root; letters.forEach((letter, i) => { let node = current.keys.get(letter); if (!node) { node = new Node(); current.keys.set(letter, node); } if (i === letters.length - 1) node.setEnd(); current = node; }); } print() { const result = []; const fn = (currentNode = this.root, accum = '') => { if (!currentNode) return; if (currentNode.isEnd()) result.push(accum); currentNode.keys.forEach((value, key) => { fn(value, accum + key); }); }; fn(); return result; } isWord(word) { const letters = word.split(''); let current = this.root; for (let i = 0; i < letters.length; i++) { if (!current) return false; current = current.keys.get(letters[i]); } return current.isEnd(); } } module.exports = Trie; <file_sep>/src/merge-sort/index.test.js const mergeSort = require('./index'); describe('mergeSort', () => { it('should be a function', () => { expect(mergeSort).toBeInstanceOf(Function); }); it('should sort an empty array', () => { expect(mergeSort([])).toEqual([]); }); it('should sort a one element array', () => { expect(mergeSort([1])).toEqual([1]); }); it('should sort a two element array', () => { expect(mergeSort([19, 3])).toEqual([3, 19]); }); it('should sort an array', () => { expect(mergeSort([3, 42, 2, 1, 39])).toEqual([1, 2, 3, 39, 42]); }); it('should sort a long array', () => { expect( mergeSort([ 1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92, ]) ).toEqual([ 1, 1, 2, 2, 4, 8, 32, 43, 43, 55, 63, 92, 123, 123, 234, 345, 5643, ]); }); }); <file_sep>/src/registration-system/index.test.js const registrationSystem = require('./index'); describe('registrationSystem', () => { it('should be a function', () => { }); it('should return the log', () => { const input = [ 'abacaba', 'acaba', 'abacaba', 'acab', ]; const response = [ 'OK', 'OK', 'abacaba1', 'OK', ]; expect(registrationSystem(input)).toEqual(response); }); it('should return the log', () => { const input = [ 'first', 'first', 'second', 'second', 'third', 'third', ]; const response = [ 'OK', 'first1', 'OK', 'second1', 'OK', 'third1', ]; expect(registrationSystem(input)).toEqual(response); }); }); <file_sep>/src/show-local-weather/index.js const showPosition = async (position) => { let isCelsius = true; const { latitude, longitude } = position.coords; const url = `https://weather-proxy.freecodecamp.rocks/api/current?lat=${latitude}&lon=${longitude}` const { data } = await axios.get(url); const { weather: [{ icon }], sys: { country }, main: { temp }, name, } = data; document .getElementById('loading') .remove(); const cardEl = document.getElementById('card'); const cityEl = document.createElement('div'); cityEl.appendChild(document.createTextNode(`${name}, ${country}`)); cardEl.appendChild(cityEl); const temperatureEl = document.createElement('div'); temperatureEl.setAttribute('id', 'temperature'); temperatureEl.appendChild(document.createTextNode(`${temp} °C`)); cardEl.appendChild(temperatureEl); const imageEl = document.createElement('img'); imageEl.setAttribute('src', icon); cardEl.appendChild(imageEl); const button = document.getElementById('toggle'); button.onclick = () => { isCelsius = !isCelsius; const text = isCelsius ? `${temp} °C` : `${temp * 1.8 + 32} °F`; temperatureEl.firstChild.nodeValue = text; }; } navigator .geolocation .getCurrentPosition(showPosition); <file_sep>/src/max-area/index.test.js const maxArea = require('./index'); describe('maxArea', () => { it('should be a function', () => { expect(maxArea).toBeInstanceOf(Function); }); it('should return 49', () => { const input = [1, 8, 6, 2, 5, 4, 8, 3, 7]; const result = 49; expect(maxArea(input)).toEqual(result); }); it('should return 1', () => { const input = [1, 1]; const result = 1; expect(maxArea(input)).toEqual(result); }); it('should return 16', () => { const input = [4, 3, 2, 1, 4]; const result = 16; expect(maxArea(input)).toEqual(result); }); it('should return 2', () => { const input = [1, 2, 1]; const result = 2; expect(maxArea(input)).toEqual(result); }); }); <file_sep>/src/max-heap/index.test.js const MaxHeap = require('./index'); describe('MaxHeap', () => { let maxHeap; beforeEach(() => { maxHeap = new MaxHeap(); }); it('should exist', () => { expect(maxHeap).toBeInstanceOf(MaxHeap); }); it('should have a method called insert', () => { expect(maxHeap.insert).toBeInstanceOf(Function); }); it('should have a method called print', () => { expect(maxHeap.print).toBeInstanceOf(Function); }); it('should insert according to max heap property', () => { maxHeap.insert(30); maxHeap.insert(20); maxHeap.insert(28); maxHeap.insert(31); const result = [31, 30, 28, 20]; expect(maxHeap.print()).toEqual(result); }); it('should have a method called remove', () => { expect(maxHeap.remove).toBeInstanceOf(Function); }); it('should remove the gratest element of the heap while maintaining the max heap property', () => { maxHeap.insert(30); maxHeap.insert(20); maxHeap.insert(28); maxHeap.insert(31); expect(maxHeap.remove()).toEqual(31); expect(maxHeap.remove()).toEqual(30); expect(maxHeap.print()).toEqual([28, 20]); }); it('should remove and re-arrange the heap maintaining the max heap property', () => { maxHeap.insert(10); maxHeap.insert(9); maxHeap.insert(8); maxHeap.insert(7); maxHeap.insert(6); maxHeap.insert(5); maxHeap.insert(4); maxHeap.insert(3); maxHeap.insert(2); maxHeap.insert(1); expect(maxHeap.remove()).toEqual(10); expect(maxHeap.print()).toEqual([9, 7, 8, 3, 6, 5, 4, 1, 2]); }); });
55bb88139468beaadf05aeb74320ffde24883084
[ "JavaScript" ]
115
JavaScript
juanprq/challenges
8a5658c35f25c68593a4b73c3bd6775a657b4b11
8627c8133ace59c0c999824f871dd8e7d988e78e
refs/heads/master
<repo_name>freeuni-sdp/iot-camera-object-recognizer<file_sep>/src/main/java/ge/edu/freeuni/sdp/iot/service/camera_object_recognizer/model/ServiceState.java package ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.model; public enum ServiceState { DEV, REAL } <file_sep>/src/main/java/ge/edu/freeuni/sdp/iot/service/camera_object_recognizer/data/RepositoryFactory.java package ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.data; import com.microsoft.azure.storage.CloudStorageAccount; import com.microsoft.azure.storage.StorageException; import com.microsoft.azure.storage.table.CloudTable; import com.microsoft.azure.storage.table.CloudTableClient; import java.net.URISyntaxException; import java.security.InvalidKeyException; public class RepositoryFactory { private static final String ACCOUNT_KEY = <KEY>; private static final String ACCOUNT_NAME = "freeunisdptodo"; private static final String TABLE_NAME = "iotcamerarecognizer"; public static Repository create() throws StorageException { return new CloudRepository(getTable()); } private static CloudTable getTable() throws StorageException { final String storageConnectionString = String.format("DefaultEndpointsProtocol=http;AccountName=%s;AccountKey=%s", ACCOUNT_NAME, ACCOUNT_KEY); CloudStorageAccount storageAccount; try { storageAccount = CloudStorageAccount.parse(storageConnectionString); } catch (InvalidKeyException | URISyntaxException e) { e.printStackTrace(); return null; } CloudTableClient tableClient = storageAccount.createCloudTableClient(); CloudTable cloudTable; try { cloudTable = tableClient.getTableReference(TABLE_NAME); } catch (URISyntaxException e) { e.printStackTrace(); return null; } cloudTable.createIfNotExists(); return cloudTable; } } <file_sep>/src/main/java/ge/edu/freeuni/sdp/iot/service/camera_object_recognizer/proxy/CameraProxy.java package ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.proxy; import ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.model.ServiceState; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.jackson.JacksonFeature; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; public class CameraProxy { private final Client client; private final ServiceState state; public CameraProxy(ServiceState state) { this.state = state; ClientConfig config = new ClientConfig().register(JacksonFeature.class); this.client = ClientBuilder.newClient(config); } public byte[] get(String cameraUrl) { Response response = client .target(cameraUrl) .request(MediaType.APPLICATION_OCTET_STREAM) .get(); byte[] ret = null; if (ResponseUtils.is200(response)) ret = response.readEntity(byte[].class); return ret; } } <file_sep>/src/main/java/ge/edu/freeuni/sdp/iot/service/camera_object_recognizer/service/CheckService.java package ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.service; import com.microsoft.azure.storage.StorageException; import ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.model.ObjectEntity; import ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.proxy.ProxyFactory; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @Path("/houses/{house_id}/check") @Produces(MediaType.APPLICATION_JSON) public class CheckService extends Services { private static final int DEFAULT_MAX_RESULTS = 50; @GET public CheckDo checkForUnknownObjects(@PathParam("house_id") String houseId) throws StorageException, IOException, GeneralSecurityException { if (!houseExists(houseId)) throw new NotFoundException(); Map<String, Integer> knowns = new HashMap<>(); for (ObjectEntity obj : getRepository ().getAll(houseId)) { String type = obj.toDo().getType(); int quantity = 1; if (knowns.containsKey(type)) quantity = knowns.get(type) + 1; knowns.put(type, quantity); } List<String> unkowns = new ArrayList<>(); ProxyFactory factory = getProxyFactory(); String cameraUrl = factory.getHouseRegistryService().getCameraUrl(houseId); if (cameraUrl == null) throw new NotFoundException(); List<String> found = factory.getGoogleApiProxy().getObjectList( factory.getCamera().get(cameraUrl), DEFAULT_MAX_RESULTS); for (String type : found) { if (knowns.containsKey(type)) { int count = knowns.get(type) - 1; if (count == 0) knowns.remove(type); else knowns.put(type, count); } else { unkowns.add(type); } } return new CheckDo(unkowns.size() == 0, unkowns); } } <file_sep>/src/test/ge/edu/freeuni/sdp/iot/service/camera_object_recognizer/proxy/FakeProxyFactory.java package ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.proxy; import ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.model.ServiceState; /** * Created by misho on 7/11/16. */ public class FakeProxyFactory extends ProxyFactory { private static FakeProxyFactory proxyFactory; public static FakeProxyFactory getFakeFactory() { if (proxyFactory == null) proxyFactory = new FakeProxyFactory(); return proxyFactory; } private CameraProxy camera; private GoogleApiServiceProxy googleApiService; private HouseRegistryServiceProxy houseRegistryService; public void setHouseRegistryService(HouseRegistryServiceProxy houseRegistryService) { this.houseRegistryService = houseRegistryService; } public void setGoogleApiService(GoogleApiServiceProxy googleApiService) { this.googleApiService = googleApiService; } public void setCamera(CameraProxy camera) { this.camera = camera; } @Override public CameraProxy getCamera() { return this.camera; } @Override public GoogleApiServiceProxy getGoogleApiProxy() { return this.googleApiService; } @Override public HouseRegistryServiceProxy getHouseRegistryService() { return this.houseRegistryService; } } <file_sep>/README.md # iot-camera-object-recognizer [![Build Status](https://travis-ci.org/freeuni-sdp/iot-camera-object-recognizer.svg?branch=master)](https://travis-ci.org/freeuni-sdp/iot-camera-object-recognizer) | | | |--------------------|---------------------------------| | API Documentation | http://docs.iotcameraobjectrecognizer.apiary.io/ | | Deployment | https://iot-camera-object-recognizer.herokuapp.com/ | მოიპოვებს სურათს კამერიდან. აწარმოებს სურათზე ობიექტების ამოცნობას გარე სერვისის საშუალებით <file_sep>/src/test/ge/edu/freeuni/sdp/iot/service/camera_object_recognizer/data/FakeRepository.java package ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.data; import com.microsoft.azure.storage.StorageException; import ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.model.ObjectEntity; import java.util.Collections; import java.util.HashMap; public class FakeRepository implements Repository { private static FakeRepository instance; private final HashMap<String, HashMap<String, ObjectEntity>> memo; public FakeRepository(HashMap<String, HashMap<String, ObjectEntity>> memo) { this.memo = memo; } public static FakeRepository instance() { if (instance==null) { instance = new FakeRepository(new HashMap<String, HashMap<String, ObjectEntity>>()); } return instance; } @Override public void insertOrUpdate(ObjectEntity object) throws StorageException { HashMap<String, ObjectEntity> partition = new HashMap<>(); if (memo.containsKey(object.getPartitionKey())) partition = memo.get(object.getPartitionKey()); partition.put(object.getRowKey(), object); memo.put(object.getPartitionKey(), partition); } @Override public ObjectEntity delete(String houseId, String id) throws StorageException { ObjectEntity object = null; if (memo.containsKey(houseId)) { HashMap<String, ObjectEntity> partition = memo.get(houseId); if (partition.containsKey(id)) object = partition.remove(id); } return object; } @Override public ObjectEntity find(String houseId, String id) throws StorageException { ObjectEntity object = null; if (memo.containsKey(houseId)) { HashMap<String, ObjectEntity> partition = memo.get(houseId); if (partition.containsKey(id)) object = partition.get(id); } return object; } @Override public Iterable<ObjectEntity> getAll(String houseId) { Iterable<ObjectEntity> objects = Collections.emptyList(); if (memo.containsKey(houseId)) objects = memo.get(houseId).values(); return objects; } public void clear() { memo.clear(); } public boolean contains(String houseId, String id) { return memo.containsKey(houseId) && memo.get(houseId).containsKey(id); } } <file_sep>/src/main/java/ge/edu/freeuni/sdp/iot/service/camera_object_recognizer/model/ObjectEntity.java package ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.model; import com.microsoft.azure.storage.table.TableServiceEntity; import ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.service.ObjectDo; public class ObjectEntity extends TableServiceEntity { private String type; public ObjectEntity() { } private ObjectEntity(String houseId, ObjectDo objectDo) { this.partitionKey = houseId; this.rowKey = objectDo.getId(); this.type = objectDo.getType(); } public String getType() { return type; } public void setType(String type) { this.type = type; } public ObjectDo toDo() { return new ObjectDo(getRowKey(), type); } public static ObjectEntity fromDo(String houseId, ObjectDo objectDo) { return new ObjectEntity(houseId, objectDo); } } <file_sep>/src/main/java/ge/edu/freeuni/sdp/iot/service/camera_object_recognizer/service/Services.java package ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.service; import com.microsoft.azure.storage.StorageException; import ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.data.Repository; import ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.data.RepositoryFactory; import ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.proxy.ProxyFactory; public class Services { public Repository getRepository() throws StorageException { return RepositoryFactory.create(); } public ProxyFactory getProxyFactory() { return ProxyFactory.getProxyFactory(); } protected boolean houseExists(String id) { return getProxyFactory() .getHouseRegistryService() .get(id); } } <file_sep>/src/main/java/ge/edu/freeuni/sdp/iot/service/camera_object_recognizer/data/Repository.java package ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.data; import com.microsoft.azure.storage.StorageException; import ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.model.ObjectEntity; public interface Repository { void insertOrUpdate(ObjectEntity object) throws StorageException; ObjectEntity delete(String houseId, String id) throws StorageException; ObjectEntity find(String houseId, String id) throws StorageException; Iterable<ObjectEntity> getAll(String houseId); } <file_sep>/src/test/ge/edu/freeuni/sdp/iot/service/camera_object_recognizer/service/FakeCheckService.java package ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.service; import com.microsoft.azure.storage.StorageException; import ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.data.FakeRepository; import ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.data.Repository; import ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.proxy.FakeProxyFactory; import ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.proxy.ProxyFactory; /** * Created by misho on 7/11/16. */ public class FakeCheckService extends CheckService { @Override public Repository getRepository() throws StorageException { return FakeRepository.instance(); } @Override public ProxyFactory getProxyFactory() { return FakeProxyFactory.getFakeFactory(); } } <file_sep>/src/main/java/ge/edu/freeuni/sdp/iot/service/camera_object_recognizer/data/CloudRepository.java package ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.data; import com.microsoft.azure.storage.StorageException; import com.microsoft.azure.storage.table.CloudTable; import com.microsoft.azure.storage.table.TableOperation; import com.microsoft.azure.storage.table.TableQuery; import ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.model.ObjectEntity; public class CloudRepository implements Repository { private static final String PARTITION_KEY = "PartitionKey"; private CloudTable table; public CloudRepository(CloudTable table) { this.table = table; } @Override public void insertOrUpdate(ObjectEntity object) throws StorageException { table.execute(TableOperation.insertOrReplace(object)); } @Override public ObjectEntity delete(String houseId, String objectId) throws StorageException { ObjectEntity object = find(houseId, objectId); if (object != null) { TableOperation operation = TableOperation.delete(object); table.execute(operation); } return object; } @Override public ObjectEntity find(String houseId, String objectId) throws StorageException { TableOperation operation = TableOperation.retrieve(houseId, objectId, ObjectEntity.class); return table.execute(operation).getResultAsType(); } @Override public Iterable<ObjectEntity> getAll(String houseId) { String partitionFilter = TableQuery.generateFilterCondition(PARTITION_KEY, TableQuery.QueryComparisons.EQUAL, houseId); return table.execute(TableQuery.from(ObjectEntity.class).where(partitionFilter)); } } <file_sep>/src/test/ge/edu/freeuni/sdp/iot/service/camera_object_recognizer/service/ObjectServiceTest.java package ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.service; import com.microsoft.azure.storage.StorageException; import ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.data.FakeRepository; import ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.model.ObjectEntity; import ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.proxy.CameraProxy; import ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.proxy.FakeProxyFactory; import ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.proxy.GoogleApiServiceProxy; import ge.edu.freeuni.sdp.iot.service.camera_object_recognizer.proxy.HouseRegistryServiceProxy; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Application; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.Random; import java.util.UUID; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsEqual.equalTo; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class ObjectServiceTest extends JerseyTest { private static final String[] OBJECTS = {"person", "dog", "cat", "table"}; @Mock private CameraProxy cameraProxy; @Mock private GoogleApiServiceProxy googleApiServiceProxy; @Mock private HouseRegistryServiceProxy houseRegistryServiceProxy; @Override protected Application configure() { return new ResourceConfig(FakeObjectService.class); } @Before public void setUpChild() throws Exception { MockitoAnnotations.initMocks(this); FakeProxyFactory.getFakeFactory().setCamera(cameraProxy); FakeProxyFactory.getFakeFactory().setGoogleApiService(googleApiServiceProxy); FakeProxyFactory.getFakeFactory().setHouseRegistryService(houseRegistryServiceProxy); } @Test public void testGetList_except200emptyList() { FakeRepository.instance().clear(); when(houseRegistryServiceProxy.get("1")).thenReturn(true); Response actual = getTarget("1") .request(MediaType.APPLICATION_JSON_TYPE) .get(); ObjectDo[] actualDo = actual.readEntity(ObjectDo[].class); assertThat(actual.getStatus(), is(Response.Status.OK.getStatusCode())); assertNotNull(actualDo); assertThat(actualDo.length, is(0)); } @Test public void testGetList_except200nonemptyList() throws StorageException { FakeRepository.instance().clear(); String houseId = "1"; ObjectEntity expected = getRandomObjectEntity(houseId); FakeRepository.instance().insertOrUpdate(expected); when(houseRegistryServiceProxy.get(houseId)).thenReturn(true); Response actual = getTarget("1") .request(MediaType.APPLICATION_JSON_TYPE) .get(); ObjectDo[] actualDo = actual.readEntity(ObjectDo[].class); assertThat(actual.getStatus(), is(Response.Status.OK.getStatusCode())); assertThat(actualDo.length, is(1)); assertThat(actualDo[0], is(equalTo(expected.toDo()))); } @Test public void testGetList_except404wrongHouseId() { FakeRepository.instance().clear(); String houseId = "1"; when(houseRegistryServiceProxy.get(houseId)).thenReturn(false); Response actual = getTarget(houseId) .request(MediaType.APPLICATION_JSON_TYPE) .get(); assertThat(actual.getStatus(), is(Response.Status.NOT_FOUND.getStatusCode())); } @Test public void testGetObjectById_except200ObjectDo() throws StorageException { FakeRepository.instance().clear(); String houseId = "1"; ObjectEntity expected = getRandomObjectEntity(houseId); FakeRepository.instance().insertOrUpdate(expected); when(houseRegistryServiceProxy.get(houseId)).thenReturn(true); Response actual = getTarget(houseId, expected.getRowKey()) .request(MediaType.APPLICATION_JSON_TYPE) .get(); ObjectDo actualDo = actual.readEntity(ObjectDo.class); assertThat(actual.getStatus(), is(Response.Status.OK.getStatusCode())); assertThat(actualDo, is(equalTo(expected.toDo()))); } @Test public void testGetObjectById_except404WrongHouseId() throws StorageException { FakeRepository.instance().clear(); String houseId = "1"; ObjectEntity expected = getRandomObjectEntity(houseId); FakeRepository.instance().insertOrUpdate(expected); when(houseRegistryServiceProxy.get(houseId)).thenReturn(false); Response actual = getTarget(houseId, expected.getRowKey()) .request(MediaType.APPLICATION_JSON_TYPE) .get(); assertThat(actual.getStatus(), is(Response.Status.NOT_FOUND.getStatusCode())); } @Test public void testGetObjectById_except404WrongObjectId() throws StorageException { FakeRepository.instance().clear(); String houseId = "1"; ObjectEntity expected = getRandomObjectEntity(houseId); FakeRepository.instance().insertOrUpdate(expected); when(houseRegistryServiceProxy.get(houseId)).thenReturn(true); Response actual = getTarget(houseId, "zoro") .request(MediaType.APPLICATION_JSON_TYPE) .get(); assertThat(actual.getStatus(), is(Response.Status.NOT_FOUND.getStatusCode())); } @Test public void testAddObject_except200() { FakeRepository.instance().clear(); String houseId = "1"; ObjectDo expected = getRandomObjectDo(); when(houseRegistryServiceProxy.get(houseId)).thenReturn(true); Response actual = getTarget(houseId) .request() .post(Entity.entity(expected, MediaType.APPLICATION_JSON_TYPE)); ObjectDo actualDo = actual.readEntity(ObjectDo.class); assertThat(actual.getStatus(), is(Response.Status.OK.getStatusCode())); assertThat(actualDo.getType(), is(equalTo(expected.getType()))); assertThat(FakeRepository.instance().contains(houseId, actualDo.getId()), is(true)); } @Test public void testAddObject_except404WrongHouseId() { FakeRepository.instance().clear(); String houseId = "1"; ObjectDo expected = getRandomObjectDo(); when(houseRegistryServiceProxy.get(houseId)).thenReturn(false); Response actual = getTarget(houseId) .request() .post(Entity.entity(expected, MediaType.APPLICATION_JSON_TYPE)); assertThat(actual.getStatus(), is(Response.Status.NOT_FOUND.getStatusCode())); } @Test public void testUpdateObjectById_except200UpdatedObjectDo() throws StorageException { FakeRepository.instance().clear(); String houseId = "1"; ObjectEntity randomObjectEntity = getRandomObjectEntity(houseId); FakeRepository.instance().insertOrUpdate(randomObjectEntity); ObjectDo expected = randomObjectEntity.toDo(); expected.setType(getRandomType()); when(houseRegistryServiceProxy.get(houseId)).thenReturn(true); Response actual = getTarget(houseId, expected.getId()) .request() .put(Entity.entity(expected, MediaType.APPLICATION_JSON_TYPE)); ObjectDo actualDo = actual.readEntity(ObjectDo.class); assertThat(actual.getStatus(), is(Response.Status.OK.getStatusCode())); assertThat(actualDo, is(equalTo(expected))); assertThat(FakeRepository.instance().contains(houseId, actualDo.getId()), is(true)); } @Test public void testUpdateObjectById_except404WrongHouseId() throws StorageException { FakeRepository.instance().clear(); String houseId = "1"; ObjectEntity randomObjectEntity = getRandomObjectEntity(houseId); FakeRepository.instance().insertOrUpdate(randomObjectEntity); ObjectDo expected = randomObjectEntity.toDo(); expected.setType(getRandomType()); when(houseRegistryServiceProxy.get(houseId)).thenReturn(false); Response actual = getTarget(houseId, expected.getId()) .request() .put(Entity.entity(expected, MediaType.APPLICATION_JSON_TYPE)); assertThat(actual.getStatus(), is(Response.Status.NOT_FOUND.getStatusCode())); } @Test public void testUpdateObjectById_except404WrongObjectId() throws StorageException { FakeRepository.instance().clear(); String houseId = "1"; ObjectEntity randomObjectEntity = getRandomObjectEntity(houseId); FakeRepository.instance().insertOrUpdate(randomObjectEntity); ObjectDo expected = randomObjectEntity.toDo(); expected.setType(getRandomType()); when(houseRegistryServiceProxy.get(houseId)).thenReturn(true); Response actual = getTarget(houseId, "zoro") .request() .put(Entity.entity(expected, MediaType.APPLICATION_JSON_TYPE)); assertThat(actual.getStatus(), is(Response.Status.NOT_FOUND.getStatusCode())); } @Test public void testDeleteObjectById_except200() throws StorageException { FakeRepository.instance().clear(); String houseId = "1"; ObjectEntity expected = getRandomObjectEntity(houseId); FakeRepository.instance().insertOrUpdate(expected); when(houseRegistryServiceProxy.get(houseId)).thenReturn(true); Response actual = getTarget(houseId, expected.getRowKey()) .request(MediaType.APPLICATION_JSON_TYPE) .delete(); assertThat(actual.getStatus(), is(Response.Status.OK.getStatusCode())); assertThat(FakeRepository.instance().contains(houseId, expected.getRowKey()), is(false)); } @Test public void testDeleteObjectById_except404WrongHouseId() throws StorageException { FakeRepository.instance().clear(); String houseId = "1"; ObjectEntity randomObjectEntity = getRandomObjectEntity(houseId); FakeRepository.instance().insertOrUpdate(randomObjectEntity); ObjectDo expected = randomObjectEntity.toDo(); expected.setType(getRandomType()); when(houseRegistryServiceProxy.get(houseId)).thenReturn(false); Response actual = getTarget(houseId, expected.getId()) .request(MediaType.APPLICATION_JSON_TYPE) .delete(); assertThat(actual.getStatus(), is(Response.Status.NOT_FOUND.getStatusCode())); } @Test public void testDeleteObjectById_except404WrongObjectId() throws StorageException { FakeRepository.instance().clear(); String houseId = "1"; ObjectEntity randomObjectEntity = getRandomObjectEntity(houseId); FakeRepository.instance().insertOrUpdate(randomObjectEntity); ObjectDo expected = randomObjectEntity.toDo(); expected.setType(getRandomType()); when(houseRegistryServiceProxy.get(houseId)).thenReturn(true); Response actual = getTarget(houseId, "zoro") .request(MediaType.APPLICATION_JSON_TYPE) .delete(); assertThat(actual.getStatus(), is(Response.Status.NOT_FOUND.getStatusCode())); } private WebTarget getTarget(String houseId) { String path = String.format("/houses/%s/objects", houseId); return target(path); } private WebTarget getTarget(String houseId, String objectId) { String path = String.format("/houses/%s/objects/%s", houseId, objectId); return target(path); } private ObjectEntity getRandomObjectEntity(String houseId) { return ObjectEntity.fromDo(houseId, getRandomObjectDo()); } private ObjectDo getRandomObjectDo() { return new ObjectDo(UUID.randomUUID().toString(), getRandomType()); } private String getRandomType() { int index = new Random().nextInt(OBJECTS.length); return OBJECTS[index]; } }
1b48b5543405c35c7a27aea22673b4341788c68d
[ "Markdown", "Java" ]
13
Java
freeuni-sdp/iot-camera-object-recognizer
3dbd5aaeb95d779e047392f66b1ab3eeff521942
13233b195ea5b47b3c8be9ef12728777909bc803
refs/heads/master
<file_sep> package com.parse.starter; import java.util.*; import com.parse.*; import android.app.AlertDialog; import android.app.ListActivity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.view.LayoutInflater; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; public class ParseStarterProjectActivity extends ListActivity { boolean remove = false; final Context context = this; private EditText editTextMainScreen; static final List<String> listItems = new ArrayList<String>(); static String parentMenu = ""; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); listItems.add("Add Button"); listItems.add("Remove Button"); ParseQuery<ParseObject> query = ParseQuery.getQuery("Primary"); if(!parentMenu.equals("")){ listItems.add("Back"); listItems.add("Set Price"); } try { List<ParseObject> list = query.find(); for(ParseObject p: list){ if(!parentMenu.equals("")){ List<ParseObject> l = new ArrayList<ParseObject>(); l = p.getRelation("Parent4").getQuery().find(); for(ParseObject x: l){ if(x.getString("Title").equals(parentMenu)){ //System.out.println("X:"+x.getString("Title")); //System.out.println("ParentMenu:" + parentMenu); listItems.add((String)p.get("Title")); x.get("Title"); } } //System.out.println("thing: " + p.getString("Title") + " : " + p.getRelation(parentMenu).equals(parentMenu)); //System.out.println("Count:"+p.getRelation("Parent4").getQuery().count()); } else { if(p.getRelation("Parent4").getQuery().count()==0) { listItems.add((String)p.get("Title")); } } } } catch (ParseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } String[] strA = Arrays.asList(listItems.toArray()).toArray(new String[listItems.size()]); setListAdapter(new ArrayAdapter<String>(this, R.layout.main,strA)); ListView listView = getListView(); listView.setTextFilterEnabled(true); listView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view,int position, long id) { if(remove){ String toRemove = getListAdapter().getItem(position).toString(); for(int i=0;i<listItems.size();i++){ System.out.println("To Remove:"+toRemove); if(!toRemove.equals("Remove Button") && !toRemove.equals("Add Button")){ listItems.remove(toRemove); remove=false; ParseQuery<ParseObject> query = ParseQuery.getQuery("Primary"); query.whereEqualTo("Title", toRemove); try { ParseObject po = query.getFirst(); po.delete(); po.save(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } listItems.clear(); finish(); startActivity(getIntent()); } } } String selectedValue = (String) getListAdapter().getItem(position); if(selectedValue.equals("Remove Button")){ remove=true; } else if(selectedValue.equals("Add Button")){ LayoutInflater layoutInflater = LayoutInflater.from(context); View promptView = layoutInflater.inflate(R.layout.dialog, null); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); alertDialogBuilder.setView(promptView); final EditText input = (EditText) promptView.findViewById(R.id.userInput); alertDialogBuilder .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Editable e = input.getText(); String s = e.toString(); ParseObject po = new ParseObject("Primary"); try { if(!parentMenu.equals("")){ ; ParseQuery<ParseObject> query = ParseQuery.getQuery("Primary"); query.whereEqualTo("Title", parentMenu); ParseObject parentObject = query.getFirst(); ParseRelation<ParseObject> relation = po.getRelation("Parent4"); relation.add(parentObject); } po.put("Title", s); po.save(); } catch (ParseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } listItems.clear(); finish(); startActivity(getIntent()); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alertD = alertDialogBuilder.create(); alertD.show(); } else if(selectedValue.equals("Back")){ parentMenu = ""; listItems.clear(); finish(); startActivity(getIntent()); } else if(selectedValue.equals("Set Price")){ } else { parentMenu = selectedValue.toString(); listItems.clear(); finish(); startActivity(getIntent()); } } }); } }
265961161717d498f3fee91ccd78ab91bd1faf32
[ "Java" ]
1
Java
apbertram/CS330-Parse
0d56e8811a8d157ff1abc977bff9a8a481d7b58e
7126dcf32ba20f1794be15d5a0f4540cf3a1367c
refs/heads/master
<file_sep>export default [{ name: '正常开启', icon: '', value: '', showTabHeader: false, defaultIcon: '', selectIcon: '', selectIndex: 0, tabs: [{ icon: '', name: '', selectIndex: 0, detailList: [{ name: '正常开启', icon: '', value: '1', selectIndex: 0 }, { name: '非法开启', icon: '', value: '6', selectIndex: 1 }, { name: '关闭', icon: '', value: '2', selectIndex: 2 }] }] }, { name: '使用时间', icon: '', value: '', showTabHeader: false, defaultIcon: '', selectIcon: '', selectIndex: 0, tabs: [{ icon: '', name: '', selectIndex: 0, detailList: [{ name: '0~3小时', icon: '', value: '0-3', selectIndex: 3 }, { name: '3~6小时', icon: '', value: '3-6', selectIndex: 4 }, { name: '6~9小时', icon: '', value: '6-9', selectIndex: 5 }, { name: '9~12小时', icon: '', value: '9-12', selectIndex: 6 }, { name: '12小时以上', icon: '', value: '12', selectIndex: 7 }] }] }, { name: '电池电量', icon: '', value: '', showTabHeader: false, defaultIcon: '', selectIcon: '', selectIndex: 0, tabs: [{ icon: '', name: '', selectIndex: 0, detailList: [{ name: '20%以下', icon: '', value: '20', selectIndex: 8 }, { name: '50%以下', icon: '', value: '50', selectIndex: 9 }, { name: '50%以上', icon: '', value: '50', selectIndex: 10 }] }] }, { name: '流量', icon: '', value: '', showTabHeader: false, defaultIcon: '', selectIcon: '', selectIndex: 0, tabs: [{ icon: '', name: '', selectIndex: 0, detailList: [{ name: '100b', icon: '', value: '100', selectIndex: 11 }, { name: '100kb', icon: '', value: '100', selectIndex: 12 }, { name: '100mb', icon: '', value: '100', selectIndex: 13 }] }] }, ] <file_sep>import { commonParams, options } from "./config"; import axios from "axios"; // 用户端 // 1.扫码或输入编号开锁接口(写好待测) export function handSerial() { const url = "/user/openLock"; const data = Object.assign({}, { user_id: "8be665d43fa838010e8ba95ba20d5a8f", chaperonage_bed_code: 1800100 // chaperonage_bed_code: serial }); return axios .get(url, { params: data }) .then(res => { return Promise.resolve(res.data); }); } // 4.用户进入缴纳押金界面或查看押金接口(写好待测) export function deposit() { const url = "/user/pay_deposit"; const data = Object.assign({}, { user_id: "a<PASSWORD>" }); return axios .get(url, { params: data }) .then(res => { return Promise.resolve(res.data); }); } // 9.我的订单接口(写好待测) export function order() { const url = "/user/my_order"; const data = Object.assign({}, { user_id: "a<PASSWORD>", pay_state: "-1" }); return axios .get(url, { params: data }) .then(res => { return Promise.resolve(res.data); }); } // 10.详情订单接口(写好待测) export function orderDetail(order_id) { const url = "/user/order_form"; const data = Object.assign({}, { user_id: "a<PASSWORD>", order_id: order_id }); return axios .get(url, { params: data }) .then(res => { return Promise.resolve(res.data); }); } // 微信支付 export function pay(order_id) { const url = "/E2306_service/app/rescheduAppletPay"; const data = Object.assign({}, { user_id: "a8dc75be56fe5f7833eed2f88d7d701e", order_id: order_id }); return axios .get(url, { params: data }) .then(res => { return Promise.resolve(res.data); }); } // 搜索条件接口 // export function bedSearch(serial) { // const url = 'admin/hospitalUser/QueryList' // const data = Object.assign({}, { // currentPage: 1, // pageSize: '10', // hospitalId: '030b7bef56fe5f783357075d6264fe22', // subName: '儿童保健科', // chaperonageBedCode: serial // }) // return axios.get(url, { // params: data // }).then((res) => { // return Promise.resolve(res.data) // }) // } //微信支付方法(点击按键调用) let wx = require('weixin-js-sdk'); /* 微信支付方法 获取微信加签信息 @param{data}:获取的微信加签 @param{cb}:成功回调 */ export function wexinPay(data, cb, errorCb) { let appId = data.appId; let timestamp = data.timeStamp; let nonceStr = data.nonceStr; let signature = data.signature; let packages = data.package; let paySign = data.paySign; wx.config({ debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 appId: appId, // 必填,公众号的唯一标识 timestamp: timestamp, // 必填,生成签名的时间戳 nonceStr: nonceStr, // 必填,生成签名的随机串 signature: signature, // 必填,签名,见附录1 jsApiList: ['chooseWXPay'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2 }); wx.ready(function () { wx.chooseWXPay({ timestamp: timestamp, // 支付签名时间戳,注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符 nonceStr: nonceStr, // 支付签名随机串,不长于 32 位 package: packages, // 统一支付接口返回的prepay_id参数值,提交格式如:prepay_id=***) signType: 'MD5', // 签名方式,默认为'SHA1',使用新版支付需传入'MD5' paySign: paySign, // 支付签名 success: function (res) { // 支付成功后的回调函数 cb(res); }, fail: function (res) { errorCb(res); } }); }); wx.error(function (res) { // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。 /*alert("config信息验证失败");*/ }); } <file_sep>import { commonParams } from './config' import axios from 'axios' // 获取验证码 export function getcode(phone) { const url = 'EDoctor_service/app/manager/account/user/userCodeLogin' const data = Object.assign({}, { sid: '123', mobileNo: phone }) return axios.get(url, { params: data }).then((res) => { return Promise.resolve(res.data) }) } // 校验账户密码 export function checkcode(phone, sms) { const url = 'admin/hospitalUser/login' const data = Object.assign({}, { username: phone, password: sms }) return axios.get(url, { params: data }).then((res) => { return Promise.resolve(res.data) }) } <file_sep>// 是否登录 export const SET_ISLOGIN = 'SET_ISLOGIN' // 信息管理 export const SET_BEDMANAGER = 'SET_BEDMANAGER' // 押金管理 export const SET_DEPOSIT_TYPE = 'SET_DEPOSIT_TYPE' // 订单管理 export const SET_ORDER_STATE = 'SET_ORDER_STATE' // 订单 export const SET_ORDER = 'SET_ORDER' // 使用说明 export const SET_DIRECTIONS = 'SET_DIRECTIONS' // 选择医院 export const SET_HOSPITAL = 'SET_HOSPITAL' // 选择日期 export const SET_DATE_TIME = 'SET_DATE_TIME' // 结果 export const SET_RESULT_TYPE = 'SET_RESULT_TYPE'
bbd35118eaaac870e3891be2bb1da7bb6590b69a
[ "JavaScript" ]
4
JavaScript
zlaccount/nurse
dcfcae33a886c37d28c6d44e8c6e40d87b49b0ec
e6fa2e4225b8f0ca02b79488043c5aaac21e4b67
refs/heads/trunk
<file_sep>/** * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE * file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package org.apache.kafka.common.config; import java.util.Collections; import java.util.List; public class SaslConfigs { /* * NOTE: DO NOT CHANGE EITHER CONFIG NAMES AS THESE ARE PART OF THE PUBLIC API AND CHANGE WILL BREAK USER CODE. */ public static final String SASL_KAFKA_SERVER_REALM = "sasl.kafka.server.realm"; public static final String SASL_KAFKA_SERVER_DOC = "The sasl kafka server realm. " + "Default will be from kafka jaas config"; public static final String SASL_KERBEROS_SERVICE_NAME = "sasl.kerberos.service.name"; public static final String SASL_KERBEROS_SERVICE_NAME_DOC = "The Kerberos principal name that Kafka runs as. " + "This can be defined either in the JAAS config or in the Kakfa config."; public static final String SASL_KERBEROS_KINIT_CMD = "sasl.kerberos.kinit.cmd"; public static final String SASL_KERBEROS_KINIT_CMD_DOC = "Kerberos kinit command path. " + "Default will be /usr/bin/kinit"; public static final String DEFAULT_KERBEROS_KINIT_CMD = "/usr/bin/kinit"; public static final String SASL_KERBEROS_TICKET_RENEW_WINDOW_FACTOR = "sasl.kerberos.ticket.renew.window.factor"; public static final String SASL_KERBEROS_TICKET_RENEW_WINDOW_FACTOR_DOC = "LoginThread will sleep until specified window factor of time from last refresh" + " to ticket's expiry has been reached, at which time it will wake and try to renew the ticket."; public static final double DEFAULT_KERBEROS_TICKET_RENEW_WINDOW_FACTOR = 0.80; public static final String SASL_KERBEROS_TICKET_RENEW_JITTER = "sasl.kerberos.ticket.renew.jitter"; public static final String SASL_KERBEROS_TICKET_RENEW_JITTER_DOC = "Percentage of random jitter added to the renewal time"; public static final double DEFAULT_KERBEROS_TICKET_RENEW_JITTER = 0.05; public static final String SASL_KERBEROS_MIN_TIME_BEFORE_RELOGIN = "sasl.kerberos.min.time.before.relogin"; public static final String SASL_KERBEROS_MIN_TIME_BEFORE_RELOGIN_DOC = "LoginThread sleep time between refresh attempts"; public static final long DEFAULT_KERBEROS_MIN_TIME_BEFORE_RELOGIN = 1 * 60 * 1000L; public static final String AUTH_TO_LOCAL = "kafka.security.auth.to.local"; public static final String AUTH_TO_LOCAL_DOC = "Rules for the mapping between principal names and operating system user names"; public static final List<String> DEFAULT_AUTH_TO_LOCAL = Collections.singletonList("DEFAULT"); }
fa484db6ac49d492f48ed09a8d31ad25630cc6d1
[ "Java" ]
1
Java
xgqfrms/kafka
16f194b20ad9795188f1d7781e7cbca1cd2a6a2d
3c5f53c8051242b61fdf448d5aa7743bc812bba6
refs/heads/master
<repo_name>josmel/solar<file_sep>/source/library/ZExtraLib/PaginatorCustom.php <?php class ZExtraLib_PaginatorCustom extends Zend_Paginator{ public function __construct($adapter) { parent::__construct($adapter); } public function setearPagina($param) { $this->_pageCount = $param; } public function setCurren($param){ $this->current = $param; } } ?><file_sep>/source/library/ZExtraLib/View/Helper/Dax.php <?php class ZExtraLib_View_Helper_Dax extends Zend_View_Helper_Abstract { function dax() { $result = '<!-- Certifica.com --> <script language="JavaScript1.3" src="http://b.scorecardresearch.com/c2/6906602/ct.js"></script>'; return $result; } function googleAnalitysc(){ $result = "<script type='text/javascript'> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-28124903-1']); _gaq.push(['_setDomainName', 'clasificados.pe']); _gaq.push(['_trackPageview']); _gaq.push(['_trackPageLoadTime']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script>"; return $result ; } }<file_sep>/source/application/models/User.php <?php class Application_Model_User extends Core_Model { protected $_tableUser; public function __construct() { $this->_tableUser= new Application_Model_DbTable_User(); } public function getOneUser($idFacebook) { $smt=$this->_tableUser->getAdapter()->query(" SELECT * FROM User WHERE idFacebook='".$idFacebook."' "); $result=$smt->fetch(); $smt->closeCursor(); return $result; } } <file_sep>/source/library/ZExtraLib/View/Helper/Facebookmeta.php <?php class ZExtraLib_View_Helper_Facebookmeta extends Zend_View_Helper_Abstract { /** * $dataAviso * @var array */ protected $_dataAviso = array(); public function facebookmeta() { //Zend_Debug::dump($this->view->mostrarDetalleAutoUsado['TituloAviso']); if(!empty($this->view->mostrarDetalleAutoUsado) && isset($this->view->mostrarDetalleAutoUsado)){ $dataAviso = $this->view->mostrarDetalleAutoUsado; $dataAviso['DescripcionAviso'] = !empty($dataAviso['DescripcionAviso'])? $dataAviso['DescripcionAviso'] : $dataAviso['TituloAviso']; $metafacebook = ' <meta property="og:site_name" content="Neo Auto" /> <meta property="og:title" content="'. $dataAviso['TituloAviso'].'" /> <meta property="og:description" content="'. $dataAviso['DescripcionAviso'].'" /> <meta property="og:type" content="website" /> <meta property="og:url" content="'. $this->view->hostContent.'/autos-usados/' .$dataAviso['SlugUrl'].'-'. $dataAviso['UrlId'].'" />'; $colFotos = ''; foreach($this->view->mostrarFotos as $value){ $colFotos .= '<meta property="og:image" content="'. $this->view->hostImg.$this->view->configImg['autosUsados']['rutaBase']. $this->view->configImg['autosUsados']['rutaExtraSmallx'].'/'. $dataAviso['IdUsuarioAnunciante'].'/'.$value['NombreFoto'].'" />'; } return $metafacebook.$colFotos ; }elseif(!empty($this->view->listaAuto) && isset($this->view->listaAuto)){ $dataAviso = $this->view->listaAuto; $metafacebook = ' <meta property="og:site_name" content="Neo Auto" /> <meta property="og:title" content="'. $dataAviso['TituloAviso'].'" /> <meta property="og:description" content="'. $dataAviso['TituloAviso'].'" /> <meta property="og:type" content="website" /> <meta property="og:url" content="'. $this->view->hostContent.'/0km/'.$this->view->slugEnte.'/' .$dataAviso['SlugUrl'].'-'. $dataAviso['UrlId'].'" />'; $colFotos = ''; foreach(explode(',',$dataAviso['Fotos']) as $value){ $colFotos .= '<meta property="og:image" content="'. $this->view->hostImg.$this->view->configImg['concesionario']['rutaBase']. $this->view->configImg['concesionario']['rutaExtraSmallx'].'/'. $dataAviso['IdUsuarioAnunciante'].'/'.$value.'" />'; } return $metafacebook.$colFotos; }else{ return '' ; } } }<file_sep>/source/library/ZExtraLib/Paquete/ValidarNuevoAvisoConcesionario.php <?php class ZExtraLib_Paquete_ValidarNuevoAvisoConcesionario { protected $_tipoAnunciante; protected $_paqueteEnte; protected $_aviso; protected $_getPaqueteEnte; protected $_idPaqueteEnte; protected $_numAvisosDisponiblePorSemana; public $idusuario; /*$tipoAnunciante Revendedor/Concesionario * $isWeb TRUE (Valida para avisos web) / false (valida para avisos impresos) * $noActivar null (solo valida no activa) */ public function __construct($idConcesionario, $idTipoVendedor) { $this->_paqueteEnte = new Application_Model_PaqueteEnte(); $this->_aviso = new Application_Model_Aviso(); $this->paqueteWebDisponible=''; $this->paqueteImpresoDisponible = ''; $paquetesListos = $this->_paqueteEnte->getPaquetesListosConcesionario($idConcesionario, $idTipoVendedor); if (count($paquetesListos) > 0) { foreach ($paquetesListos as $getPaqueteEnte) { if(!empty($getPaqueteEnte['AvisoWebDisponible']) && empty($this->paqueteWebDisponible)) { $this->paqueteWebDisponible=$getPaqueteEnte; } if(!empty($getPaqueteEnte['AvisoPapelFotoDisponible']) && empty($this->paqueteImpresoDisponible)){ $this->paqueteImpresoDisponible=$getPaqueteEnte; } if(!empty($this->paqueteWebDisponible) && !empty($this->paqueteImpresoDisponible)){ break; } } } } public function getPaqueteWebDisponible() { return $this->paqueteWebDisponible; } public function getPaqueteImpresoDisponible() { return $this->paqueteImpresoDisponible; } public function activarWebPaqueteEnte(){ if($this->paqueteWebDisponible['ActivoPaqueteEnte']!=1){ $weeks = $this->paqueteWebDisponible['SemanaDuracionPaqueteEnte']; $data['ActivoPaqueteEnte'] = 1; $data['FechaInicioPaqueteEnte'] = date('Y-m-d H:i:s'); $data['FechaFinPaqueteEnte'] = date("Y-m-d ", strtotime(date("m/d/Y")." +".$weeks ." week")); $this->_paqueteEnte->actualizarPaqueteEnte($this->paqueteWebDisponible['IdPaqueteEnte'], $data); } } public function activarImpresoPaqueteEnte(){ if($this->paqueteImpresoDisponible['ActivoPaqueteEnte']!=1){ $weeks = $this->paqueteImpresoDisponible['SemanaDuracionPaqueteEnte']; $data['ActivoPaqueteEnte'] = 1; $data['FechaInicioPaqueteEnte'] = date('Y-m-d H:i:s'); $data['FechaFinPaqueteEnte'] = date("Y-m-d ", strtotime(date("m/d/Y")." +".$weeks ." week")); $this->_paqueteEnte->actualizarPaqueteEnte($this->paqueteImpresoDisponible['IdPaqueteEnte'], $data); } } } <file_sep>/source/application/models/DbTable/Hobby.php <?php /** * Table Activities * * @author marrselo */ class Application_Model_DbTable_Hobby extends Core_Db_Table { protected $_name = "hobby"; protected $_primary = "idHobby"; const NAMETABLE = 'hobby'; static function populate($params) { $data = array( 'name' => isset($params['name']) ? $params['name'] : '', ); $data = array_filter($data); return $data; } /** * * @param obj DB $resulQuery */ public function getPrimaryKey() { return $this->_primary; } public function insertIdUser($hobby,$user) { $this->getAdapter()->insert(array('idHobby' => $hobby, 'idUser' => $user)); //return $result; } } <file_sep>/source/library/ZExtraLib/Application/Resource/Testing.php <?php class ZExtraLib_Application_Resource_Testing extends Zend_Application_Resource_ResourceAbstract { function init () { // die('init'); } }<file_sep>/source/library/ZExtraLib/Db/Table.php <?php class ZExtraLib_Db_Table extends Zend_Db_Table { function __construct($config = array(), $definition = null) { $this->_db = ZExtraLib_Server::getDb('query'); parent::__construct($config, $definition); } function insert(array $data) { $this->_db = ZExtraLib_Server::getDb('process'); parent::insert($data); } function update(array $data, $where) { $this->_db = ZExtraLib_Server::getDb('process'); return parent::update($data, $where); } function delete($where) { $this->_db = ZExtraLib_Server::getDb('process'); parent::delete($where); } public function getName() { return $this->_name; } public function getCols(){ return $this->_getCols(); } } <file_sep>/source/library/ZExtraLib/Filter/ExtraTag.php <?php /** * shortDescription * * longDescription * * @category category * @package package * @subpackage subpackage * @copyright Leer archivo COPYRIGHT * @license Leer archivo LICENSE * @version Release: @package_version@ */ class ZExtraLib_Filter_ExtraTag extends Zend_Filter_Alnum { public function __construct($allowWhiteSpace = false) { parent::__construct(); } public function filter($words) { return implode(' ',ZExtraLib_Utils::extractTag($words)); } } <file_sep>/source/library/ZExtraLib/Filter/ExtracString.php <?php class ZExtraLib_Filter_ExtracString { /** * Extrae una porcion de una cadena * @param string $string texto total * @param string $strIni texto inicial * @param strgng $strFin texto final * @return string */ static public function extrac($string,$strIni,$strFin) { $cadena = str_replace($strIni,'',trim($string)); $total = strpos($cadena,$strFin); return substr($cadena,0,($total)); } static public function extractImg($string) { $img=substr($string,strpos($string, 'src="')) ; $tot=strpos($img,'alt'); $imagen=str_replace('src="','',substr($img,0,-(strlen($img)-$tot))); return substr($imagen,0,-(strlen($imagen)-strpos($imagen,'"'))); } }<file_sep>/source/library/ZExtraLib/Filter/RangoAnos.php <?php class ZExtraLib_Filter_RangoAnos extends Zend_Filter { public function filter($rangos) { $valid = array(); $v = new ZExtraLib_Validate_RangoAnos(); foreach($rangos as $rango){ if($v->isValid($rango)){ $valid[] = $rango; } } return $valid; } } <file_sep>/source/library/ZExtraLib/PageCache.php <?php require_once 'Zend/Cache.php'; require_once 'Zend/Registry.php'; class ZExtraLib_PageCache { const CACHE_NAME = 'PageCache'; public static function getCache() { return Zend_Cache::factory( 'Page', 'File', array( 'lifetime' => 30, //30 segundos 'automatic_serialization' => true, 'debug_header' => false, 'default_options' => array( 'make_id_with_get_variables' => true, //true 'cache_with_cookie_variables' => true, 'cache_with_post_variables' => true, 'cache_with_get_variables' => true, 'cache_with_session_variables' => false, 'cache_with_files_variables' => false ), 'regexps' => array( '^/*' => array('cache' => true), '^/anunciante/' => array('cache' => true), '^/default/' => array('cache' => true), '^/admin/' => array('cache' => true), '^/test/' => array('cache' => true), '^/auth/' => array('cache' => true) ) ), array( 'cache_dir' => APPLICATION_PATH . '/../var/cache' ) ); } }<file_sep>/source/library/ZExtraLib/IpLocation.php <?php //require_once _PS_ROOT_DIR_.'/library/Zend/Http/Client.php'; //require_once _PS_ROOT_DIR_.'/library/Zend/XmlRpc/Client.php'; //require_once _PS_ROOT_DIR_.'/library/Zend/Json.php'; //require_once 'XmlRpc/Client.php'; //require_once 'Json/'; class ZExtraLib_IpLocation { protected $ip; protected $key='8522614bf1f82125ccc068276a07ad1b344ef2f10f41c1d45a8599de322aad1b'; public $country; public $region; public $city; private $client="http://api.ipinfodb.com/v3/ip-city/"; public function __construct($ip, $key='8522614bf1f82125ccc068276a07ad1b344ef2f10f41c1d45a8599de322aad1b') { $this->ip=$ip; $this->key=$key; } /** * Geolocation API access * * @param string $ip IP address to query * @param string $format output format of response * * @return string XML, JSON or CSV string */ function get_ip_location() { /* Set allowed output formats */ $client = new Zend_Http_Client($this->client); $client->setParameterGet(array( 'key' => $this->key, 'ip' => $this->ip, )); $response = $client->request(); if ($response->isSuccessful() ) {//Zend_Json::decode( $phpNative = $response->getBody(); $phpNative =explode(";",$phpNative); if ($phpNative[0]=='OK') { $this->abrv = $phpNative[3]; $this->country= $phpNative[4]; $this->region=$phpNative[5]; return 1; } } return 0; } } <file_sep>/source/library/ZExtraLib/Validate/RangoAnos.php <?php class ZExtraLib_Validate_RangoAnos extends Zend_Validate_Abstract{ const INVALID1 = 'invalid1'; const INVALID2 = 'invalid2'; const INVALID3 = 'invalid3'; const INVALID4 = 'invalid4'; protected $_messageTemplates = array( self::INVALID1 => "Rango inválido 1", self::INVALID2 => "Rango inválido 2", self::INVALID3 => "Rango inválido 3", self::INVALID4 => "Rango inválido 4" ); function isValid($value) { $this->_setValue($value); $parts = explode('-', $value); if(count($parts)!=2){ $this->_error(self::INVALID1); return false; } foreach($parts as $anyo){ $anyo = trim($anyo); if( !is_numeric($anyo) || $anyo < 1800 || $anyo > date('Y')+1 ){ $this->_error(self::INVALID2); return false; } } if(trim($parts[1])>=trim($parts[0])){ $this->_error(self::INVALID3); return false; } return true; } }<file_sep>/source/library/ZExtraLib/Auth.php <?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * Description of ZExtraLib_Auth * * @author nazart */ class ZExtraLib_Auth extends Zend_Auth { /** * Singleton instance * * @var Zend_Auth */ protected static $_instance = null; public static function getInstance() { if (null === self::$_instance) { self::$_instance = new self(); } return self::$_instance; } public function authenticates(Zend_Auth_Adapter_Interface $adapter,$noauth=null) { $result = $adapter->authenticate(); /** * ZF-7546 - prevent multiple succesive calls from storing inconsistent results * Ensure storage has clean state */ if ($this->hasIdentity()) { if($noauth!=1){ $this->clearIdentity(); } } if ($result->isValid()) { if($noauth!=1){ $this->getStorage()->write($result->getIdentity()); } } return $result; } } ?> <file_sep>/source/library/ZExtraLib/View/Helper/ImgSinFoto.php <?php class ZExtraLib_View_Helper_ImgSinFoto extends Zend_View_Helper_Abstract { function ImgSinFoto($img) { $fp = @fopen($img, "rb"); if ($fp) { fclose($fp); $result = true; } else { $result = false ; } @fclose($fp); //return $img; return $result; } }<file_sep>/source/library/ZExtraLib/Controller/Plugin/Ids.php <?php class ZExtraLib_Controller_Plugin_Ids extends Zend_Controller_Plugin_Abstract { public function preDispatch(Zend_Controller_Request_Abstract $request) { require_once 'IDS/Init.php'; $request = array('REQUEST' => $_REQUEST, 'GET' => $_GET, 'POST' => $_POST, 'COOKIE' => $_COOKIE); $config= new Zend_Config_Ini(APPLICATION_PATH.'/configs/ids.ini'); //$init = IDS_Init::init(APPLICATION_PATH . '/../library/IDS/Config/Config.ini.php'); $init = IDS_Init::init(APPLICATION_PATH.'/configs/ids.ini'); $ids = new IDS_Monitor($request, $init); $result = $ids->run(); if (!$result->isEmpty()) { // This is where you should put some code that // deals with potential attacks, e.g. throwing // an exception, logging the attack, etc. echo $result; } return $request; } } <file_sep>/source/application/modules/default/controllers/IndexController.php <?php require_once('../library/SolrPhpClient/Apache/Solr/Service.php'); class Default_IndexController extends Core_Controller_ActionDefault { public function init() { parent::init(); } public function indexAction() { $this->view->hola = "Prueba Apache Solr"; } public function insertAction() { if ($this->_request->isPost()) { $params = $this->_getAllParams(); $obj = new Application_Entity_RunSql('User'); $objTwo = new Application_Entity_HobbyUser(); if (empty($params['idUser'])) { $obj->save = $params; $id = $obj->save; for ($i = 0; $i < count($params['hobby']); $i++) { $objTwo->insertUserHobby($params['hobby'][$i], $id); } $this->indexarSolr($params, $id); } else { $objTwo->deleteUserHobby($params['idUser']); $obj->edit = $params; for ($i = 0; $i < count($params['hobby']); $i++) { $objTwo->insertUserHobby($params['hobby'][$i], $params['idUser']); } $this->indexarSolr($params, $params['idUser']); } $this->_redirect('/default/index/list'); } $form = new Application_Entity_UserForm(); $this->view->form = $form; $this->view->hola = "Prueba Apache Solr"; } public function editAction() { $id = $this->_getParam('id', 0); $form = new Application_Entity_UserForm($id); if (!empty($id)) { $obj = new Application_Entity_RunSql('User'); $obj->getone = $id; $dataObj = $obj->getone; $form->populate($dataObj); } $this->view->form = $form; } public function listAction() { $obj = new Application_Entity_User(); $dataObj = $obj->listAll(); $this->view->data = $dataObj; $this->view->submit = "Guardar Blog"; $this->view->action = "/blog/new"; } public function indexarSolr($params, $id) { $solr = new Apache_Solr_Service('localhost', 8983, '/solr/'); $hobby = new Application_Entity_User(); $totalHobby = $hobby->findAll($id); if ($solr->ping()) { $solr->deleteByQuery('id:' . $id); // $solr->deleteByQuery('*:*'); $document = new \Apache_Solr_Document ( ); $document->addField('id', $id); $document->addField('url', $params['flagAct']); $document->addField('category', $params['firstName']); $document->addField('keywords', $params['lastName']); if (count($totalHobby) > 0) { foreach ($totalHobby as $resultado) { $document->setMultiValue('title', $resultado['name']); } } $document->addField('author', $params['name']); $solr->addDocument($document); //$solr->commit(); //$solr->optimize(); return; } echo 'error de conexion con Solr'; exit; } public function buscarAction() { if ($this->_request->isGet()) { $idParametro = $this->_getParam('q', 0); if (!empty($idParametro)) { $limit = 10; $query = isset($idParametro) ? $idParametro : false; $results = false; if ($query) { $solr = new Apache_Solr_Service('localhost', 8983, '/solr/'); if (get_magic_quotes_gpc() == 1) { $query = stripslashes($query); } try { $results = $solr->search($query, 0, $limit); if ($results) { $total = (int) $results->response->numFound; $start = min(1, $total); $end = min($limit, $total); } } catch (Exception $e) { return; } } $this->view->hola = "Prueba Apache Solr"; $this->view->total = $total; $this->view->start = $start; $this->view->end = $end; $this->view->resultado = $results->response->docs; } } } } /*public function indexarSolr() { $solr = new Apache_Solr_Service('localhost', 8080, '/solr/'); if ($solr->ping()) { // $solr->deleteByQuery('id:' . $id); // $solr->deleteByQuery('*:*'); $document = new \Apache_Solr_Document ( ); $document->addField('id', rand(20, 100) . 'id'); $document->addField('url', 'http//ww.facebook3.com'); $document->addField('category', 'futbol'); $document->addField('keywords', '245745474'); $document->setMultiValue('title', 'futbol total'); $document->setMultiValue('title', 'voley'); $document->addField('author', '<NAME>'); $solr->addDocument($document); //$solr->commit(); //$solr->optimize(); echo 'se indexo correctamente'; exit; } else { $this->_redirect('/default/index/indexar'); } ; $this->_redirect('/default/index/indexar'); } /* $document->id = rand(4, 10); $document->title = 'prueba.solr'; $document->_version_ = '45454545454'; // $document->_root_ = 'root'; */ // $document->addField('price', 12.4554); // $document->addField('title','prueba de titulo'); // $document->addField('_version_', 14673725); // $document->addField('_root_', ); /* $document->links = 'httt'; $document->last_modified = '2014-11-15'; $document->content_type = 'prueba.solr'; $document->url = 'prueba.solr'; $document->resourcename = 'prueba.solr'; $document->comments = 'prueba.solr'; $document->description = 'prueba.solr'; $document->subject = 'prueba.solr'; $document->title = 'prueba.solr'; $document->store = 'prueba.solr'; $document->inStock = true; $document->popularity = 14545; $document->price = 155.255; $document->weight = true; $document->includes = 'prueba.solr'; $document->features = 'prueba.solr'; $document->cat = 'prueba.solr'; $document->manu = 'prueba.solr'; $document->name = 'prueba.solr'; $document->sku = 'prueba.solr'; $document->content = 'prueba.solr'; $document->text = 'prueba.solr'; $document->text_rev = 'prueba.solr'; $document->manu_exact = 'prueba.solr'; $document->payloads = 'prueba.solr'; */ // var_dump($document);exit;<file_sep>/source/library/ZExtraLib/Controller/ActionConcesionario.php <?php class ZExtraLib_Controller_ActionConcesionario extends ZExtraLib_Controller_Action { protected $_layout; protected $_hostFileStatic; protected $_arrayAclAnunciante; protected $_identity; protected $_identityTemp; protected $_sessionAdmin; /** * * @var Zend_Session_Namespace */ public $session; public function init() { parent::init(); if (!Zend_Session::isStarted()) { Zend_Session::start(); } $this->session = new Zend_Session_Namespace('Neoauto'); if (!isset($this->session->initialized)) { Zend_Session::regenerateId(); $this->session->initialized = true; } $this->_sessionAdmin = new Zend_Session_Namespace('sessionAdmin'); if (isset($this->_sessionAdmin->identity)){ $this->view->identityAdmin = $this->_sessionAdmin->identity; } $this->_identity = Zend_Auth::getInstance()->getIdentity(); $this->initValidacionUsuario(); if (isset($this->_identity)) { $concesionario = new Application_Model_Concesionario(); $this->view->getConcesionario = $concesionario ->concesionarioMisDatos( $this->_identity->IdEnte,$this->_identity->IdUsuarioAnunciante); $nombretipoconcesionario = $this->_request->getParam('tipo'); if(empty($this->_identity->TipoVendedorConcesionario)){ $this->_helper->getHelper('FlashMessenger') ->addMessage('No cuenta con un perfil activo.'); $this->_redirect('/'); } /***/ $this->_arrayAclAnunciante = $arrayAcl = array("miperfil" => array("nombre" => "Concesionario", "ruta" => '/concesionario/admin/inicio/'.$nombretipoconcesionario, "arbol" => array( "inicio" => array("nombre" => "Inicio", "class" => "inicio-".$nombretipoconcesionario, "ruta" => '/concesionario/admin/inicio/'.$nombretipoconcesionario, "arbol" => ''), "mis-datos" => array("nombre" => "Mis Datos", "class" => "mis-datos-".$nombretipoconcesionario, "ruta" => '/concesionario/admin/mis-datos/'.$nombretipoconcesionario, "arbol" => ''), "avisos" => array("nombre" => "Mis Avisos", "class" => "anadir-avisos-".$nombretipoconcesionario, "ruta" => '/concesionario/avisos/anadir-avisos/'.$nombretipoconcesionario, "arbol" => array("anadir-avisos" => array("nombre" => "Añadir Avisos", "action" => "anadir-avisos", "ruta" => '/concesionario/avisos/anadir-avisos/'.$nombretipoconcesionario), "avisos-activos" => array("nombre" => "Avisos Activos", "action" => "avisos-activos", "ruta" => '/concesionario/avisos/avisos-activos/'.$nombretipoconcesionario), "avisos-baja" => array("nombre" => "De baja", "action" => "avisos-baja", "ruta" => '/concesionario/avisos/avisos-baja/'.$nombretipoconcesionario) ) ), "tienda" => array("nombre" => "Mi Tienda", "class" => "destacados-".$nombretipoconcesionario, "ruta" => '/concesionario/tienda/destacados/'.$nombretipoconcesionario, "arbol" => array("destacados" => array("nombre" => "Adm. destacados", "action" => "destacados", "ruta" => '/concesionario/tienda/destacados/'.$nombretipoconcesionario), "nota-informativa" => array("nombre" => "Nota Informativa", "action" => "nota-informativa", "ruta" => '/concesionario/tienda/nota-informativa/'.$nombretipoconcesionario) //, // "promociones" => // array("nombre" => "Promociones", // "action" => 'promociones', // "ruta" => '/concesionario/tienda/promociones') ) ), "Mis Paquetes" => array("nombre" => "Mis Paquetes", "class" => "mis-paquetes-".$nombretipoconcesionario, "ruta" => '/concesionario/admin/mis-paquetes/'.$nombretipoconcesionario, "arbol" => '' ), "utilidades" => array("nombre" => "Utilidades", "class" => "utilidades-".$nombretipoconcesionario, "ruta" => '/concesionario/admin/utilidades/'.$nombretipoconcesionario, "arbol" => '') ) ) ); } $frontController = Zend_Controller_Front::getInstance(); $fechaCierre = date("Y-m-d",strtotime($frontController->getParam('bootstrap')->getOption('MessageClose') )); $fechaActual = date("Y-m-d"); $this->view->fechaCierre = ($fechaActual < $fechaCierre )? $fechaCierre: null; $this->view->mensajeFechaCierre = (!empty($this->view->fechaCierre))? 'Estimados anunciantes, el cierre de publicaciones para la edición impresa del domingo 04 de Noviembre será adelantada al día miércoles 31 de Octubre hasta las 6:00 p.m., aplica para todos nuestros canales de venta, incluyendo fonoavisos y agencias concesionarias, toda publicidad ingresada después de esta fecha y hora, pasará a publicarse en la siguiente edición impresa del domingo 11 de Noviembre.' : ''; $this->view->rutaBlog = $this->_rutaBlog = $frontController->getParam('bootstrap')->getOption('BlogNeoautoHome'); $this->_hostFileStatic = ZExtraLib_Server::getStatic()->host; $this->_hostFileContent = ZExtraLib_Server::getContent()->host; $this->_layout = Zend_Layout::getMvcInstance(); $this->initMenuAnunciante(); $this->initPublicacion(); $this->session->_identityTemp = isset($this->session->_identityTemp) ? $this->session->_identityTemp : $this->_identity; $this->view->identity = $this->_identity; $this->view->hostFileStatic = $this->_hostFileStatic; $this->view->cantidadPalabrasImpresoTipoPUblicacion = ''; $this->_configImg = ZExtraLib_Server::getFile(0)->upload; $this->view->configImg = $this->_configImg; $this->_versionJs = ZExtraLib_Server::getStatic()->versionJs; $this->view->versionJs = $this->_versionJs; $this->_hostImg = ZExtraLib_Server::getFile(0)->host; $this->view->hostImg = $this->_hostImg; $this->view->hostContent = $this->_hostFileContent; $detalleBusqueda = new Application_Model_DetalleBusqueda(); $this->view->contarAvisosMarcaFooter = $detalleBusqueda->contarAvisosMarca(); $this->view->contarModelos = $detalleBusqueda->contarModelo(); $this->view->contarUltimosAvisosFooter = $detalleBusqueda->ultimosAvisosUsados(6); $this->view->AclAnunciante = $this->_arrayAclAnunciante; $this->view->filterHtml = new Zend_Filter_StripTags(); $this->verficarPermisos(); $this->view->messages = $this->_helper->getHelper('FlashMessenger')->getMessages(); $this->initView(); } function initValidacionUsuario() { if($this->_request->getModuleName() != "default" || $this->_request->getControllerName() != "index" || $this->_request->getActionName() != "login"){ if(!$this->_identity){ $this->_redirect("/cuenta/login"); } } } public function initPublicacion() { if($this->_getParam('reset')==1){ } if($this->_request->getModuleName() == 'anunciante') { if ($this->_request->getControllerName() == 'publicacion') { $this->_layout->setLayout('layout-anunciante-publicacion'); } else { if (isset($this->session->AvisoRegistrado)) { $this->session->AvisoRegistrado = null; unset($this->session->AvisoRegistrado); $this->session->flagAvisoImportado = null; unset($this->session->flagAvisoImportado); } } }elseif ($this->_request->getModuleName() == 'concesionario') { $this->_layout->setLayout('layout-concesionario'); $this->session->AvisoRegistrado = null; unset($this->session->AvisoRegistrado); $this->session->flagAvisoImportado = null; unset($this->session->flagAvisoImportado); } if( $this->_request->getModuleName() == 'default' && $this->_request->getControllerName() == 'index' ) { $this->session->AvisoRegistrado = null; unset($this->session->AvisoRegistrado); $this->session->flagAvisoImportado = null; unset($this->session->flagAvisoImportado); } } public function initMenuAnunciante() { if ($this->_request->getModuleName() == 'anunciante') { if (!$this->_identity && (!($this->_request->getControllerName() == 'publicacion' && $this->_request->getActionName() == 'index') && !($this->_request->getControllerName() == 'pagoefectivo' && $this->_request->getActionName() == 'pago-efectivo-urlok')) ) { $this->_redirect(ZExtraLib_Server::getContent()->host); } $this->_layout->setLayout('layout-anunciante'); switch ($this->_request->getControllerName()) { case 'miperfil':$this->view->menuAdminSelectd_1 = 'selected'; break; case 'micuenta':$this->view->menuAdminSelectd_2 = 'selected'; break; case 'vendedor':$this->view->menuAdminSelectd_3 = 'selected'; break; } } elseif ($this->_request->getModuleName() == 'concesionario') { $this->_layout->setLayout('layout-concesionario'); if (!$this->_identity){ $this->_redirect(ZExtraLib_Server::getContent()->host); } }elseif($this->_request->getModuleName() == 'cerokm'){ if (!$this->_identity){ $this->_redirect(ZExtraLib_Server::getContent()->host); } }elseif($this->_request->getModuleName() == 'callCenter'){ if (!$this->_identity){ $this->_redirect(ZExtraLib_Server::getContent()->host); } }elseif($this->_request->getModuleName() == 'anunciante'){ if (!$this->_identity){ $this->_redirect(ZExtraLib_Server::getContent()->host); } } } }<file_sep>/source/library/ZExtraLib/View/Helper/Cx.php <?php class ZExtraLib_View_Helper_Cx extends Zend_View_Helper_Abstract { /** * * @var Zend_Controller_Front */ protected $_nameAction = null; public function __construct() { $this->_nameAction = Zend_Controller_Front::getInstance()->getRequest() ->getActionName(); } public function cx() { switch($this->_nameAction){ case 'verdetalle' : case 'registro' : $return = ''; break; default : $return = $this->view->layout()->render('_cxense'); } return $return; } }<file_sep>/source/library/ZExtraLib/Validate/LimpiarTexto.php <?php class ZExtraLib_Validate_LimpiarTexto { protected $_texto = ''; protected $_numero = ''; protected $_separador = ''; function __construct($texto,$separador,$number=true) { $this->_texto = $texto; $this->_numero = $number; $this->_separador = $separador; $exclude = array('el', 'la', 'los', 'las', 'esto', 'esto', 'es', 'de', 'asi', 'select', 'delete', 'from', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a%C3%B1o', 'tipo', 'texto', 'precio-min', 'precio-max'); $texto = str_replace(array("á", "é", "í", "ó", "ú", "ñ"), array("a", "e", "i", "o", "u", "n"), $texto); $filter = ($number) ? "/[^0-9a-zA-Z ]/i" : "/[^a-zA-Z ]/i"; $texto = strtolower(preg_replace($filter, '-', $texto)); $this->arrayTexto = array_filter(array_diff(array_unique(explode($separador, $texto)), $exclude)); } function stringTokenBusqueda() { return "'".implode("','",$this->arrayTexto)."'"; } } <file_sep>/source/library/ZExtraLib/Model.php <?php class ZExtraLib_Model{ function fetchPairs($array){ $data=array(); foreach ($array as $index){ $arrayKey=array_keys($index); $data[$index[$arrayKey[0]]] = $index[$arrayKey[1]]; } return $data; } function clearDataTable($objTable,$datos){ $colum=$objTable->getCols(); $arrayLista = array(); foreach($datos as $index=>$value){ if(in_array($index, $colum)) $arrayLista[$index]=$value; } return $arrayLista; } function getArrayFirstValue($array){ $data=array(); foreach ($array as $index){ $arrayKey=array_keys($index); $data[] = $index[$arrayKey[0]]; } return $data; } function arrayAsoccForFirstItem($array){ $arrayResponse = array(); foreach($array as $index => $data){ $arrayResponse[$data[key($data)]][]=$data; } return $arrayResponse; } }<file_sep>/source/library/ZExtraLib/RegistroEmpresaUsuarioAnunciante.php <?php class ZExtraLib_RegistroEmpresaUsuarioAnunciante { protected $_mensaje; protected $_conEnte; protected $_idEnte; protected $_nombreEnte; protected $_nroDocumento; public function __construct($idUsuario,$nombreEmpresa,$direccion,$ruc,$tipoDocumento= NULL,$arrayDatos = NULL) { $Numero_Documento = $ruc; $Ape_Paterno = $arrayDatos==null?$arrayDatos['apellidoPaterno']:''; $Ape_Materno = $arrayDatos==null?$arrayDatos['apellidoMaterno']:''; $PreNombre = $arrayDatos==null?$arrayDatos['nombre']:''; $Nombre_RznComc = $nombreEmpresa; $NombreCalle = $direccion; $tipDoc = $tipoDocumento!=''? '2' :'1'; // Buscar empresa en adecsys $strTipoDoc = $tipDoc==1? 'DNI':'RUC'; $EnteWs = $this->buscarEmpresaWS($strTipoDoc, $Numero_Documento); if ($EnteWs =='') { // Ente no registrado en adecsys, debe registrarse $arrayNuevoEnte = array( 'Tipo_Documento' => $strTipoDoc, 'Numero_Documento'=>$Numero_Documento, 'Ape_Paterno' => $Ape_Paterno, 'Ape_Materno' => $Ape_Materno, 'Nombres_RznSocial' => $Nombre_RznComc, 'Nombre_RznComc' => $Nombre_RznComc, 'Nombre_Calle' => $NombreCalle ); $CodEnteWs = $this->registrarEmpresaWS($arrayNuevoEnte); // Enviar mensaje de registro de ente $dataCorreo = array('[NroDocumento]'=>$ruc, '[RzSocial]'=>$nombreEmpresa, '[Direccion]'=>$direccion, '[FechaRegistro]'=>date('d-m-Y'), '[codAdecsys]'=>$CodEnteWs, '[fecha]'=>date('Y') ); $this->enviarCorreo($dataCorreo); $EnteWs = $this->buscarEmpresaWS($strTipoDoc, $Numero_Documento); // Recuperar toda la data } // Buscamos ente en neoauto $modelEnte = new Application_Model_Ente(); $EnteDb = $modelEnte->getEntexDoc($tipDoc, $ruc); try { $db = ZExtraLib_Server::getDb('process'); $db->beginTransaction(); if($EnteDb == ''){ // Si no existe el ente en neoauto, se registra $filter = new ZExtraLib_Filter_SeoUrl(); $arrayNuevoEnteDb = array( 'NombreEnte' => $EnteWs->RznSoc_Nombre, 'DireccionEnte' => $EnteWs->Nom_Calle, 'IdTipoDocumento' => $tipDoc, 'NroDocumento' => $EnteWs->Num_Doc, 'IdUsuarioAnunciante' => $idUsuario, 'FechaEnte' => date("Y-m-d"), 'ApellidoPaterno' => $EnteWs->Ape_Pat, 'ApellidoMaterno' => $EnteWs->Ape_Mat, 'PreNombre' => $EnteWs->Pre_Nom, 'RazonSocialComercial' => $EnteWs->RznSoc_Nombre, 'TipoPersona' => $EnteWs->Tip_Per, 'Email' => $EnteWs->Email, 'Telefono' => $EnteWs->Telf, 'Ciudad' => $EnteWs->Ciudad, 'TipoCentroPoblado' => $EnteWs->Tip_Cen_Pob, 'TipoCalle' => $EnteWs->Tip_Calle, 'NombreCalle' => $EnteWs->Nom_Calle, 'NumeroPuerta' => $EnteWs->Num_Pta, 'EstadoActual' => $EnteWs->Est_Act, 'CodDireccion' => $EnteWs->Cod_Direccion, 'SlugEnte' => $filter->urlFriendly($EnteWs->RznSoc_Nombre, '-', 0), 'IdAdecsys' => $EnteWs->Id, 'NombreComercial' => $EnteWs->RznCom ); $EnteDbId = $modelEnte->registrarEnte($arrayNuevoEnteDb); $this->_mensaje = 'El perfil ha sido guardado.'; } else{// Actualizar ente en neoauto $arrayEnte = array( 'ApellidoPaterno' => $EnteWs->Ape_Pat, 'ApellidoMaterno' => $EnteWs->Ape_Mat, 'PreNombre' => $EnteWs->Pre_Nom, 'RazonSocialComercial' => $EnteWs->RznSoc_Nombre, 'TipoPersona' => $EnteWs->Tip_Per, 'Telefono' => $EnteWs->Telf, 'Ciudad' => $EnteWs->Ciudad, 'TipoCentroPoblado' => $EnteWs->Tip_Cen_Pob, 'TipoCalle' => $EnteWs->Tip_Calle, 'NombreCalle' => $EnteWs->Nom_Calle, 'NumeroPuerta' => $EnteWs->Num_Pta, 'EstadoActual' => $EnteWs->Est_Act, 'CodDireccion' => $EnteWs->Cod_Direccion, 'IdAdecsys' => $EnteWs->Id ); $EnteDbId = $EnteDb['IdEnte']; $modelEnte->actualizarEnte($EnteDbId,$arrayEnte); } // Buscamos la asociacion del usuario con la empresa // Si la empresa ya está asociada al usuario, retorna // Si la empresa no está asociada al usuario, se asocia $this->_codEnte = $EnteWs->Id; $this->_nombreEnte = $EnteWs->Pre_Nom; $this->_nroDocumento = $EnteWs->Num_Doc; $this->_idEnte = $EnteDbId; $modelEmpresa = new Application_Model_Empresa(); if($modelEmpresa->registrarIntermediaria($idUsuario, $EnteDbId)){ $this->_mensaje = 'El perfil ha sido guardado.'; } else { $this->_mensaje = 'Ya se encuentra asociado a esta empresa.'; } $db->commit(); } catch (Exception $e) { $db->rollBack(); ZExtraLib_Log::err($e->getMessage(). '__________ Error al Insertar una Empresa:'.print_r(func_get_args(), true)); $this->_mensaje = 'Error al registrar la Empresa.'; } } function buscarEmpresaWS($tipoDoc, $numDoc) { try { $frontController = Zend_Controller_Front::getInstance(); $uriEnc = $frontController->getParam('bootstrap')->getOption('Adecsys'); $client = new Zend_Soap_Client($uriEnc['empresa']['wsEmpresa']); $array=array('Tipo_Documento' => $tipoDoc,'Numero_Documento' => $numDoc); $response=$client->Validar_Cliente($array); if(isset($response->Validar_ClienteResult)) return $response->Validar_ClienteResult; else return ''; } catch (Exception $e) { return ''; } } function registrarEmpresaWS($arrayDatosNuevoEnte) { try { $frontController = Zend_Controller_Front::getInstance(); $uriEnc = $frontController->getParam('bootstrap')->getOption('Adecsys'); $client = new Zend_Soap_Client($uriEnc['empresa']['wsEmpresa']); $arrayRegistroEnte=array( 'Tipo_Documento'=> $arrayDatosNuevoEnte['Tipo_Documento'], 'Numero_Documento' => $arrayDatosNuevoEnte['Numero_Documento'], 'Ape_Paterno' => strtoupper($arrayDatosNuevoEnte['Ape_Paterno']), 'Ape_Materno' => strtoupper($arrayDatosNuevoEnte['Ape_Materno']), 'Nombres_RznSocial' => strtoupper($arrayDatosNuevoEnte['Nombres_RznSocial']), 'Email' => '', 'Telefono' => '', 'Tipo_Cen_Poblado' => '', 'Nombre_Cen_Poblado' => '', 'Tipo_Calle' => 'CA', 'Nombre_Calle' => $arrayDatosNuevoEnte['Nombre_Calle'], 'Numero_Puerta' => '', 'CodCiudad' => '1', 'Nombre_RznComc' => strtoupper($arrayDatosNuevoEnte['Nombre_RznComc'])); $response=$client->Registrar_Cliente($arrayRegistroEnte); if($response->Registrar_ClienteResult!=''){ return $response->Registrar_ClienteResult; }else{ return ''; } } catch (Exception $e) { ZExtraLib_Log::err($e->getMessage(). '__________ Error al Insertar en el web service :'.print_r($e, true)); } } function getMessage() { return $this->_mensaje; } function getConEnte() { return $this->_codEnte; } function getIdEnte() { return $this->_idEnte; } function getNombreEnte() { return $this->_nombreEnte; } function getNroDocumento() { return $this->_nroDocumento; } function enviarCorreo($dataCorreo) { $template = new ZExtraLib_Template(); try { $textoCorreo = $template->load('RegistrarEnte',$dataCorreo); $correo = Zend_Registry::get('mail'); $correoUsuario = new Application_Model_UsuarioCorreo(); $usuarioCorreo = $correoUsuario->listarUsuarioCorreo(7); foreach ($usuarioCorreo as $index): $correoAdmin[] = $index['CorreoUsuarioAdmin']; endforeach; $correo->addTo($correoAdmin) ->clearSubject() ->setSubject('Registro de nuevo Ente - Neoauto') ->setBodyHtml($textoCorreo); $correo->send(); } catch (Exception $exc) { ZExtraLib_Log::err('Registrar nuevo Ente Adecsys'. $exc->__toString(),' --- ' . print_r($correoAdmin)); } } }<file_sep>/source/library/ZExtraLib/Paquete/ValidarNuevoAviso.php <?php class ZExtraLib_Paquete_ValidarNuevoAviso { protected $_tipoAnunciante; protected $_paqueteEnte; protected $_aviso; protected $_getPaqueteEnte; protected $_idPaqueteEnte; protected $_numAvisosDisponiblePorSemana; public $idusuario; /*$tipoAnunciante Revendedor/Concesionario * $isWeb TRUE (Valida para avisos web) / false (valida para avisos impresos) * $noActivar null (solo valida no activa) */ public function __construct($tipoAnunciante, $idEnte, $isWeb = TRUE,$noActivar = null,$idusuario=null) { $this->_paqueteEnte = new Application_Model_PaqueteEnte(); $this->_aviso = new Application_Model_Aviso(); $this->_idEnte = $idEnte; $this->_numAvisosDisponiblePorSemana = ''; if ($tipoAnunciante == 2 || $tipoAnunciante == 4) { $idUser= !empty($idusuario)? $idusuario : ''; $existenPaquetesPagados = $this->_paqueteEnte->buscarPaqueteListo($idEnte,$idUser); if (count($existenPaquetesPagados) > 0) { foreach ($existenPaquetesPagados as $getPaqueteEnte) { $idPaqueteEnte = $getPaqueteEnte['IdPaqueteEnte']; $numeroAvisosWebPermitidos = $getPaqueteEnte['AvisoWebPaqueteEnte']; $numeroAvisosImpresosPermitidos = $getPaqueteEnte['AvisoPapelFotoPaqueteEnte']; $numeroAvisosImpresosUsados = $getPaqueteEnte['AvisoPapelFotoPaqueteEnte'] - $getPaqueteEnte['AvisoPapelFotoDisponible']; //$arrAvisosImpresosUsados['numeroAvisosImpresos']; $this->numeroAvisosImpresosUsados = $numeroAvisosImpresosUsados; $numeroAvisosWebUsados = $numeroAvisosWebPermitidos - $getPaqueteEnte['AvisoWebDisponible']; //$arrAvisosWebUsados['numeroAvisosPaqueteEnte']; $this->_numeroAvisosWebUsados = $numeroAvisosWebUsados; $diasDuracion = $getPaqueteEnte['SemanaDuracionPaqueteEnte'] * 7; $this->_getPaqueteEnte = $getPaqueteEnte; if ($getPaqueteEnte['ActivoPaqueteEnte'] == 1) { //* verificar asignar aviso a paquete if ($isWeb) { if ($getPaqueteEnte['FlagNumAvisoWeb'] != 1) { if (($numeroAvisosWebPermitidos - $numeroAvisosWebUsados) > 0) { break; } else { $this->_getPaqueteEnte = 0; } } else { break; } } else { if ($getPaqueteEnte['FlagAvisoPapelFoto'] != 1) { if (($numeroAvisosImpresosPermitidos - $numeroAvisosImpresosUsados) > 0) { break; } else { $this->_getPaqueteEnte = 0; } // if($tipoAnunciante==2){ // Revendedor // if(($numeroAvisosImpresosPermitidos - $numeroAvisosImpresosUsados) > 0 ){ // break; // }else{ // $this->_getPaqueteEnte = 0; // } // }else{ //Concesionario // $promedioImpresoSemanal = $getPaqueteEnte['PromedioSemanalAvisoImpreso']; // // $avisoImpreso = new Application_Model_AvisoImpreso(); // $numAvisosUsadosSemana = $avisoImpreso->validarNumeroAvisoSemanal($this->_idEnte); // if(($promedioImpresoSemanal - $numAvisosUsadosSemana)>0){ // $this->_numAvisosDisponiblePorSemana = ($promedioImpresoSemanal - $numAvisosUsadosSemana); // break; // }else{ // $this->_numAvisosDisponiblePorSemana = 0 ; // $this->_getPaqueteEnte = 0; // break; // } // } } else { break; } } } else { if(empty($noActivar)){ $this->_getPaqueteEnte = $this->activarPaqueteEnte($idPaqueteEnte, $diasDuracion); } break; } } } else { $this->_getPaqueteEnte = 0; } } else { $this->_getPaqueteEnte = 0; } } public function getPaqueteEnte() { return $this->_getPaqueteEnte; } public function getNumeroAvisosWebUsados() { return $this->_numeroAvisosWebUsados; } public function getNumeroAvisosImpresosUsados() { return $this->numeroAvisosImpresosUsados; } function activarPaqueteEnte($idPaqueteEnte, $dias) { if (!empty($idPaqueteEnte) && !empty($dias)) { $date = new Zend_Date(); $horas = $dias * 24; $date->add($horas . ':00:00', Zend_Date::TIMES); $fechaFin = explode(' ', $date); $fechaFin2 = explode('/', $fechaFin[0]); $data = array(); $data['ActivoPaqueteEnte'] = 1; $data['FechaInicioPaqueteEnte'] = date('Y-m-d H:i:s'); $data['FechaFinPaqueteEnte'] = $fechaFin2[2] . '-' . $fechaFin2[1] . '-' . $fechaFin2[0] . ' ' . $fechaFin[1]; $this->_paqueteEnte->actualizarPaqueteEnte($idPaqueteEnte, $data); } return $this->_paqueteEnte->getPaqueteEnte($idPaqueteEnte); } function getNumeroAvisosDisponiblePorSemana() { return $this->_numAvisosDisponiblePorSemana; } } <file_sep>/source/library/ZExtraLib/Log.php <?php class ZExtraLib_Log { /** * * @var Zend_Log */ protected $logger; static $fileLogger = null; public static function getInstance() { if (self::$fileLogger === null) { self::$fileLogger = new self(); } return self::$fileLogger; } /** * * @return Zend_Log */ public function getLog() { return $this->logger; } protected function __construct() { $this->logger = Zend_Registry::get('Log'); } /** * log a message * @param string $message */ public static function info($message) { self::getInstance()->getLog()->info(self::getMessage($message)); } /** * log a message * @param string $message */ public static function err($message,$datos=null) { /* $correo = Zend_Registry::get('mail'); $correo->addTo('<EMAIL>') ->clearSubject() ->setSubject('Confirma tu Registro') ->setBodyHtml($textoCorreo); $correo->send();*/ self::getInstance()->getLog()->err(self::getMessage($message)); } /** * log a message * @param string $message */ public static function warn($message) { self::getInstance()->getLog()->warn(self::getMessage($message)); } public static function crit($message) { self::getInstance()->getLog()->crit(self::getMessage($message)); } public static function getMessage($message) { return $message; } }<file_sep>/source/library/ZExtraLib/TextTime.php <?php class ZExtraLib_TextTime { protected $_time; protected $_textElapsedTime; public function __construct($date=Null) { if(empty ($date)){ $this->_time = date('YYYY-MM-DD'); } else{ $this->_time = date($date); } } public function ElapsedTime() { $intervalos = array("segundo", "minuto", "hora", "día", "semana", "mes", "año"); $duraciones = array("60", "60","60", "24", "7", "4.35", "12"); $ahora = time(); $Fecha_Unix = strtotime($this->_time); if (empty($Fecha_Unix)) { return "Fecha incorrecta"; } if ($ahora > $Fecha_Unix) { $diferencia = $ahora - $Fecha_Unix; $tiempo = "Hace"; } else { $diferencia = $Fecha_Unix - $ahora; $tiempo = "Dentro de"; } for ($j = 0; $diferencia >= $duraciones[$j] && $j < count($duraciones) - 1; $j++) { $diferencia /= $duraciones[$j]; } $diferencia = round($diferencia); if ($diferencia != 1) { $intervalos[5].="e"; //MESES $intervalos[$j].= "s"; } $this->_textElapsedTime = "$tiempo $diferencia $intervalos[$j]"; } public function setTime($time) { $this->_time = date($time); } public function getTextElapsedTime() { return $this->_textElapsedTime; } } // Ejemplos de uso // fecha en formato yyyy-mm-dd // echo tiempo_transcurrido('2010/02/05'); // fecha y hora // echo tiempo_transcurrido('2010/02/10 08:30:00');<file_sep>/source/application/entitys/UserForm.php <?php class Application_Entity_UserForm extends Core_Form_Form { protected $_idUser = ''; public function __construct($id = null, $options = null) { $this->_idUser = $id; parent::__construct($options); } public function init() { $obj = new Application_Model_DbTable_User(); $primaryKey = $obj->getPrimaryKey(); $this->setMethod('post'); $this->setEnctype('multipart/form-data'); $this->setAttrib('idfile', $primaryKey); $this->setAction('/default/index/insert'); $e = new Zend_Form_Element_Hidden($primaryKey); $this->addElement($e); $hob = new Application_Entity_Hobby(); $hobtw = new Application_Entity_HobbyUser(); $hobbys= $hob->listAll(); $e = new Zend_Form_Element_MultiCheckbox('hobby'); $e->addMultiOptions($hobbys); if ($this->_idUser !== null) { $ma = $hobtw->getFeaturedTwo($this->_idUser); $idsgreat = array(); foreach ($ma as $resulta) { $idsgreat[] = $resulta['idHobby']; } $e->setValue($idsgreat); } $this->addElement($e); $e = new Zend_Form_Element_Text('name'); $this->addElement($e); $e = new Zend_Form_Element_Text('lastName'); $this->addElement($e); $e = new Zend_Form_Element_Text('firstName'); $this->addElement($e); $e = new Zend_Form_Element_Text('mail'); $this->addElement($e); $e = new Zend_Form_Element_Text('age'); $this->addElement($e); $e = new Zend_Form_Element_Submit('enviar'); $this->addElement($e); $e = new Zend_Form_Element_Checkbox('flagAct'); $e->setValue(true); $this->addElement($e); foreach ($this->getElements() as $element) { $element->removeDecorator('Label'); $element->removeDecorator('DtDdWrapper'); $element->removeDecorator('HtmlTag'); } } public function populate(array $values) { parent::populate($values); } } <file_sep>/source/application/models/DbTable/Level.php <?php /** * Table Activities * * @author marrselo */ class Application_Model_DbTable_Level extends Core_Db_Table { protected $_name = "Level"; protected $_primary = "idLevel"; const NAMETABLE='Level'; static function populate($params) { $data= array( 'idUser'=>isset($params['idUser'])?$params['idUser']:'', 'category'=>isset($params['category'])?$params['category']:'', 'level'=>isset($params['level'])?$params['level']:'', 'lastUpdate'=>date('Y-m-d H:i:s') ); $data= array_filter($data); $data['flagAct']=isset($params['flagAct'])?$params['flagAct']:1; return $data; } /** * * @param obj DB $resulQuery */ public function columnDisplay() { return array('name','imageIcon','imageMedium','imageLarge'); } public function getPrimaryKey() { return $this->_primary; } public function getWhereActive() { return " AND flagAct= 1"; } public function getIdUser($idFacebook) { $smt = $this->getAdapter()->select() ->from(array('u' => 'User'), array('*')) ->where('u.idFacebook = ?', $idFacebook) ->where('u.flagAct = ?', 1) ->query() ; $result = $smt->fetch(); $smt->closeCursor(); return $result; } } <file_sep>/source/application/entitys/User.php <?php class Application_Entity_User extends Core_Model { protected $_tableUser; public function __construct() { $this->_tableUser = new Application_Model_DbTable_User(); } public function findAll($idUser) { $select = $this->_tableUser->getAdapter()->select() ->from(array('f' => $this->_tableUser->getName()), array('f.idUser') )->join(array('tf' => 'hobbyuser'), "f.idUser = tf.idUser" )->join(array('tr' => 'hobby'), "tr.idHobby = tf.idHobby", array('name' => 'tr.name') ) ->where("f.idUser = ?", $idUser); $select = $select->query(); $result = $select->fetchAll(); $select->closeCursor(); return $result; } public function listAll() { $smt = $this->_tableUser->getAdapter()->select()->distinct() ->from($this->_tableUser->getName()) ->query(); $result = $smt->fetchAll(); $smt->closeCursor(); return $result; } } <file_sep>/source/library/ZExtraLib/Validate/UrlYoutube.php <?php class ZExtraLib_Validate_UrlYoutube extends Zend_Validate_Abstract{ const MessageUrlYoutubeValidator = ''; protected $_messageTemplates = array( self::MessageUrlYoutubeValidator => "La Url '%value%' No es Valida" ); function isValid($value) { $this->_setValue($value); $arrayData = ZExtraLib_Utils::validateUrlYoutube($value); $value = trim($value); if($value != '' && !$arrayData['validate']){ $this->_error(self::MessageUrlYoutubeValidator); return false; } return true; } }<file_sep>/source/application/configs/application.ini [production] ;; Manejo de errores phpSettings.display_startup_errors = 0 phpSettings.display_errors = 0 includePaths.library = APPLICATION_PATH "/../library" bootstrap.path = APPLICATION_PATH "/Bootstrap.php" bootstrap.class = "Bootstrap" appnamespace = "Application" resources.frontController.params.displayExceptions = 0 ; autoloader autoloaderNamespaces[] = "Core" autoloaderNamespaces[] = "QueryTable" autoloaderNamespaces[] = "Store" autoloaderNamespaces[] = "Application" ;; RESOURCES resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers" resources.frontController.moduleDirectory = APPLICATION_PATH "/modules" resources.frontController.params.prefixDefaultModule = "1" resources.frontController.actionhelperpaths.Mailing_Action_Helper = APPLICATION_PATH "/entitys/mailing/helpers" ;resources.frontController.plugins.acl = "Core_Controller_Plugin_Acl" resources.view.charset = "UTF-8" resources.view.title = 'ifuxion.com' resources.view.encoding = "UTF-8" resources.view.doctype = "HTML5" ;doesn't work resources.view.contentType = "text/html; charset=UTF-8" resources.view.helperPath.Core_View_Helper = APPLICATION_PATH "/../library/Core/View/Helper" ;resources.view.helperPath.App_View_Helper = APPLICATION_PATH "/../library/core/View/Helper" ;;Cache por defecto resources.cachemanager.default.frontend.name = Core resources.cachemanager.default.frontend.customFrontendNaming = false resources.cachemanager.default.frontend.options.lifetime = 120 resources.cachemanager.default.frontend.options.automatic_serialization = true resources.cachemanager.default.backend.name = File resources.cachemanager.default.backend.customBackendNaming = false resources.cachemanager.default.backend.options.cache_dir = APPLICATION_PATH "/../var/cache/default" resources.cachemanager.default.frontendBackendAutoload = false ;; layout resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts/" ;;captcha captcha.font = APPLICATION_PATH "/../public/landing/font/arial.ttf" captcha.img = APPLICATION_PATH "/../public/captcha" ;; Languaje language.default = 'en' language.PE = 'es' app.elementTemp = APPLICATION_PATH "/../public/tmp"; app.rootImgDinamic = APPLICATION_PATH "/../public/dinamic"; app.logPath = APPLICATION_PATH "/../var/log"; app.cache = mem ;[!!!] ;; Base de datos ;; resources.multidb.db.adapter="Mysqli" resources.multidb.db.host = "localhost" resources.multidb.db.username = "root" resources.multidb.db.password = "<PASSWORD>" resources.multidb.db.dbname = "osp_betaflight" resources.multidb.db.charset = "utf8" resources.multidb.db.isDefaultTableAdapter = true resources.multidb.db.defaultMetadataCache = "default" app.siteUrl = http://betaflight.onlinestudioproductions.com/ ;[!!!] app.staticUrl = http://betaflight.onlinestudioproductions.com/static/;[!!!] app.dinamicUrl = http://betaflight.onlinestudioproductions.com/dinamic/;[!!!] [staging : production] [testing : production] phpSettings.display_startup_errors = 1 phpSettings.display_errors = 1 [development : production] phpSettings.display_startup_errors = 1 phpSettings.display_errors = 1 resources.frontController.params.displayExceptions = 1 resources.multidb.db.adapter='Mysqli' resources.multidb.db.host = "localhost" resources.multidb.db.username = "root" resources.multidb.db.password = "<PASSWORD>" resources.multidb.db.dbname = "solar" resources.multidb.db.charset = "utf8" resources.multidb.db.isDefaultTableAdapter = true resources.multidb.db.defaultMetadataCache = "default" app.siteUrl = http://betaflight.onlinestudioproductions.com/ ;[!!!] app.staticUrl = http://betaflight.onlinestudioproductions.com/static/;[!!!] app.dinamicUrl = http://betaflight.onlinestudioproductions.com/dinamic/;[!!!] [local : development] resources.multidb.db.adapter='Mysqli' resources.multidb.db.host = "localhost" resources.multidb.db.username = "root" resources.multidb.db.password = "<PASSWORD>" app.siteUrl = http://local.solar:98/ ;[!!!] app.staticUrl = http://local.solar:98/static/;[!!!] app.dinamicUrl = http://local.solar:98/dinamic/;[!!!] app.imgUrl = http://local.solar:98/element/; [!!!] app.elementTemp = APPLICATION_PATH "/../public/tmp";[!!!] app.cache = mem ;[!!!] app.imgAdmin = http://local.solar:98/static/img/; app.rootImgDinamic = APPLICATION_PATH "/../public/dinamic";<file_sep>/source/library/ZExtraLib/Utils.php <?php /** * shortDescription * * longDescription * * @category category * @package package * @subpackage subpackage * @copyright Leer archivo COPYRIGHT * @license Leer archivo LICENSE * @version Release: @package_version@ */ class ZExtraLib_Utils { const key='feRr=sp5vuda8ePrubudra2reBequrRr'; protected $_filterSEO; /** * description * @param paramType paramName paramDescription * @uses class::name() * @return returnType returnDescription */ static function arrayToObject($array) { if (is_array($array)) { return (object) array_map(array('ZExtraLib_Utils', 'arrayToObject'), $array); } else { return $array; } } /** * description * @param paramType paramName paramDescription * @uses class::name() * @return returnType returnDescription */ static function toSEO($url) { if (!isset($this->_filterSEO)) { $this->_filterSEO = new ZExtraLib_Filter_Alnum(); } return $this->_filterSEO->filter(trim($url), '-'); } /** * Funcón para encritar una cadena * @param string $msg Cadena a encriptar * @uses ZExtraLib_Utils::encrypt() * @return string Cadena encriptada */ static function encrypt($rawPassword,$algo='sha1') { # return iv+ciphertext+mac /*return hash('sha256', $rawPassword, false);*/ $salt = substr(md5(rand(0, 999999) + time()), 6, 5); $passw = ''; if ($algo == 'sha1') { $passw = $algo . '$' . $salt . '$' . sha1($salt . $rawPassword); } else { $passw = $algo . '$' . $salt . '$' . md5($salt . $rawPassword); } // ZExtraLib_Log::err('password : ->'.$passw); return $passw; } /** * Genera un código Hash * @param boolean $returnLast Indica si desea capturar el ultimo hash generado * @return string Codigo Hash */ static function hashCode($returnLast=false) { $session = new Zend_Session_Namespace('HashCode'); if (!$returnLast) { $session->hashCode = md5(time()); } return $session->hashCode; } static function to32($cant) { $q = 10000000 + $cant; $alfabet = '4agf2hkve3prq7stu9jmnyzwx5b6d8c'; $l = strlen($alfabet); $splitAlfabet = str_split($alfabet); $dataResult = array(); while ($q != 0) { $r = $q % $l; $q = intval($q / $l); $dataResult[] = $splitAlfabet[$r]; } $dataResultString = ""; krsort($dataResult); foreach ($dataResult as $index) $dataResultString = $dataResultString . $index; return $dataResultString; } static function createFileImagenPersonaNatural($idUsr) { $file = ZExtraLib_Server::getFile(); //print_r($file); $ftp = new ZExtraLib_UploadFtpImgServer(); $ftp->connect(); //print_r($file); $rutasExtras = $file->upload['autosUsados']['rutaExtra']; $rutaRemota = $file->upload['fileBase'] . $file->upload['autosUsados']['rutaBase'] . $file->upload['autosUsados']['rutaOrigin']; $ftp->newDirectory($rutaRemota, $idUsr); $rutasExtras = explode(',', $rutasExtras); foreach ($rutasExtras as $index) { $index2 = explode('-', $index); $rutaFile = $index2[0]; $rutaRemota = $file->upload['fileBase'] . $file->upload['autosUsados']['rutaBase'] . '/' . $rutaFile; $ftp->newDirectory($rutaRemota, $idUsr); } } static function extractTag($words, $number=true) { $_exclude = array('el', 'la', 'los', 'las', 'esto', 'esto', 'es', 'de', 'asi', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'tipo', 'marca', 'modelo','select','update','delete'); $words = str_replace(array("á", "é", "í", "ó", "ú", "ñ"), array("a", "e", "i", "o", "u", "n"), $words); $filter = ($number) ? "/[^0-9a-zA-Z ]/i" : "/[^a-zA-Z ]/i"; $words = strtolower(preg_replace($filter, '', $words)); return array_diff(array_unique(explode(' ', $words)), $_exclude); } static function redondear_dos_decimal($valor) { $float_redondeado = round($valor * 100) / 100; return $float_redondeado; } static function getLocate() { $locale = new Zend_Locale('es_PE'); return $locale; } static function convertUrlQuery($query) { if($query!=''){ $queryParts = explode('&', $query); $params = array(); foreach ($queryParts as $param) { $item = explode('=', $param); $params[$item[0]] = $item[1]; } return $params;} } static function validateUrlYoutube($uri='') { $arrayReturn = array(); if($uri==''){ $arrayReturn['validate']=false; return $arrayReturn; } $array = parse_url($uri); if(isset($array['query'])) $array = self::convertUrlQuery($array['query']); $yt = new Zend_Gdata_YouTube(); $objUri = Zend_Uri::factory($uri); $arrayReturn['validate'] = TRUE; if ($objUri->valid() && strpos($uri,"http://www.youtube.com/watch?v=")===0) { try { $videoEntry = $yt->getVideoEntry($array['v']); $arrayReturn['Video'] = $videoEntry->getVideoTitle(); $arrayReturn['Video_ID'] = $videoEntry->getVideoId(); $arrayReturn['Updated'] = $videoEntry->getUpdated(); $arrayReturn['Description'] = $videoEntry->getVideoDescription(); $arrayReturn['Category'] = $videoEntry->getVideoCategory(); $arrayReturn['Tags'] = implode(", ", $videoEntry->getVideoTags()); $arrayReturn['Watch_page'] = $videoEntry->getVideoWatchPageUrl(); $arrayReturn['Flash_Player_Url'] = $videoEntry->getFlashPlayerUrl(); $arrayReturn['Duration'] = $videoEntry->getVideoDuration(); $arrayReturn['View_count'] = $videoEntry->getVideoViewCount(); $arrayReturn['message'] = $videoEntry->getVideoViewCount(); } catch (Exception $e) { $arrayReturn['validate'] = FALSE; $arrayReturn['message'] = $e->getMessage(); } } else { $arrayReturn['validate'] = FALSE; $arrayReturn['message'] = 'La ruta no es valida'; } return $arrayReturn; } static function generaClave($lengCadena) { $minuscula = 'abcdefghijklnmopqrstuvwxyz'; $mayuscula = strtoupper($minuscula); $numero = '1234567890'; $arrayLetras = array(str_split($minuscula),str_split($mayuscula),str_split($numero)); $letra =''; for($i=0; $i<=$lengCadena;$i++){ $index = rand(0,2); $index2 = rand(0,count($arrayLetras[$index])); $letra = $letra.$arrayLetras[$index][$index2]; } return $letra; } static function getIdentityTemp () { //ZExtraLib_Utils::consoleLog('getIdentityTemp'); $space = new Zend_Session_Namespace('Neoauto'); if (!isset($space->_identityTemp)){ $space->_identityTemp = Zend_Auth::getInstance()->getIdentity(); // ZExtraLib_Utils::consoleLog('Asignar : ' . json_encode($space->_identityTemp)); } //ZExtraLib_Utils::consoleLog('getIdentityTemp'); return $space->_identityTemp; } //end function setIdentityTemp static function consoleLog ($string) { echo "<script>console.log('" . $string . "');</script>"; } //end function consoleLog /** * Consider the following production envs: * pre, preproduction, production * @return boolean */ static public function isDevEnv() { if (APPLICATION_ENV == 'pre' || APPLICATION_ENV == 'preproduction' || APPLICATION_ENV == 'production' ) { return false; } return true; } }<file_sep>/source/library/ZExtraLib/Controller/Plugin/Acl.php <?php class ZExtraLib_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract { private $_noauth = array('module' => 'default', 'controller' => 'cuenta', 'action' => 'login'); private $_noacl = array('module' => 'default', 'controller' => 'error', 'action' => 'error'); protected $_acl; protected $_role; public function preDispatch(Zend_Controller_Request_Abstract $request) { $this->setAcl(Zend_Registry::get('Acl')); $auth = Zend_Auth::getInstance(); if ($auth->hasIdentity()) { $user = $auth->getStorage()->read(); $roleName = $user->IdRolUsuarioAnunciante; } else { $roleName = 1; //Visitante } $this->setRole($roleName); if (!$this->isValidUrl($request)) { $request->setModuleName($this->_noacl['module']); $request->setControllerName($this->_noacl['controller']); $request->setActionName($this->_noacl['action']); } } function isValidUrl(Zend_Controller_Request_Abstract $request) { $acl = $this->getAcl(); $url1 = 'mvc:' . $request->getModuleName() . '/*'; $url2 = 'mvc:' . $request->getModuleName() . '/' . $request->getControllerName() . '/*'; $url3 = 'mvc:' . $request->getModuleName() . '/' . $request->getControllerName() . '/' . $request->getActionName(); return ($acl->has($url1) && $acl->isAllowed($this->getRole(), $url1)) || $acl->has($url2) && $acl->isAllowed($this->getRole(), $url2) || $acl->has($url3) && $acl->isAllowed($this->getRole(), $url3); } function getAcl() { return $this->_acl; } function getRole() { return $this->_role; } function setRole($role) { $this->_role = $role; } function setAcl($acl) { $this->_acl = $acl; } } <file_sep>/source/library/ZExtraLib/View/Helper/Certifica.php <?php class ZExtraLib_View_Helper_Certifica extends Zend_View_Helper_Abstract { function certifica($codigo,$url) { $result = '<!-- Certifica.com --> <script type="text/javascript" src="http://c.scorecardresearch.com/certifica-js14.js"></script> <script type="text/javascript" src="http://c.scorecardresearch.com/certifica.js"></script> <script type="text/javascript"> <!-- tagCertifica('.$codigo.',"'.$url.'"); // --> </script> '; return $result; } }<file_sep>/source/library/ZExtraLib/View/Helper/ImageDefault.php <?php class ZExtraLib_View_Helper_ImageDefault extends Zend_View_Helper_Abstract { function ImageDefault($img,$dimension='',$varIndex = null) { $arrayDimension = array( '86x85', '640x1000', '188x142', '110x60', '434x195', '138x98', '400x300', '800x600', '60x70', '86x61', '100x100', '170x126', '371x280', '288x216', '30x18', '120x50', '140x70', '144x108', '176x132', '168x126', '465x320'); $fp = @fopen($img, "rb"); if ($fp) { fclose($fp); $result = $img; } else { if (!in_array($dimension, $arrayDimension)) { $dimension = $arrayDimension[2]; } if(!isset($varIndex) and empty($varIndex)){ $result = ZExtraLib_Server::getFile(0) ->host . '/defaultImg/' . $dimension . '.jpg'; }else{ $result = ZExtraLib_Server::getFile(0) ->host . '/defaultImg/default.gif'; } } @fclose($fp); //return $img; return $result; } }<file_sep>/source/library/ZExtraLib/View/Helper/Eplanning.php <?php class ZExtraLib_View_Helper_Eplanning extends Zend_View_Helper_Abstract { public function eplanning($seccion = '', $eplanningEis = '') { if (APPLICATION_ENV == 'local' || APPLICATION_ENV == 'development') { return ""; } if ($seccion == '') { $fc = Zend_Controller_Front::getInstance(); $rqs = $fc->getRequest(); $controllerName = $rqs->getControllerName(); $actionName = $rqs->getActionName(); $moduleName = $rqs->getModuleName(); $ruta = $moduleName . '/' . $controllerName . '/' . $actionName; if ('default/index/index' != $ruta) { $seccion = 'Internas'; } else { $seccion = 'Portada'; } } if($eplanningEis == ''){ $eplanningEis = '["Top","Right1","Logo","Expandible","Right2"]'; } $var = 'var eS1 = \'us.img.e-planning.net\';var eplArgs = { iIF:1,sV:"http://ads.us.e-planning.net/",vV:"4",sI:"8aeb",sec:"' . $seccion . '",eIs:' . $eplanningEis . '};'; $result = ' <script type="text/javascript" src="' . ZExtraLib_Server::getStatic()->host . '/f/js/peruredfcustom.js"></script> <!-- e-planning SETUP begin --> <script language="JavaScript" type="text/javascript"> var eplDoc = document; var eplLL = false;' . $var . ' function eplCheckStart() { if (document.epl) { var e = document.epl; if (e.eplReady()) { return true; } else { e.eplInit(eplArgs); if (eplArgs.custom) { for (var s in eplArgs.custom) { document.epl.setCustomAdShow(s, eplArgs.custom[s]); } } return e.eplReady(); } } else { if (eplLL) return false; if (!document.body) return false; var eS2; var dc = document.cookie; var ci = dc.indexOf("EPLSERVER="); if (ci != -1) { ci += 10; var ce = dc.indexOf(\';\', ci); if (ce == -1) ce = dc.length; eS2 = dc.substring(ci, ce); } var eIF = document.createElement(\'IFRAME\'); eIF.src = \'about:blank\'; eIF.id = \'epl4iframe\'; eIF.name = \'epl4iframe\'; eIF.width=0; eIF.height=0; eIF.style.width=\'0px\'; eIF.style.height=\'0px\'; eIF.style.display=\'none\'; document.body.appendChild(eIF); var eIFD = eIF.contentDocument ? eIF.contentDocument : eIF.document; eIFD.open();eIFD.write(\'<html><head><title>e-planning</title></head><bo\'+\'dy></bo\'+\'dy></html>\');eIFD.close(); var s = eIFD.createElement(\'SCRIPT\'); s.src = \'http://\' + (eS2?eS2:eS1) +\'/layers/epl-41.js\'; eIFD.body.appendChild(s); if (!eS2) { var ss = eIFD.createElement(\'SCRIPT\'); ss.src = \'http://ads.us.e-planning.net/egc/4/2912\'; eIFD.body.appendChild(ss); } eplLL = true; return false; } } eplCheckStart(); function eplSetAdM(eID,custF) { if (eplCheckStart()) { if (custF) { document.epl.setCustomAdShow(eID,eplArgs.custom[eID]); } document.epl.showSpace(eID); } else { var efu = \'eplSetAdM("\'+eID+\'", \'+ (custF?\'true\':\'false\') +\');\'; setTimeout(efu, 250); } } function eplAD4M(eID,custF) { document.write(\'<div id="eplAdDiv\'+eID+\'"></div>\'); if (custF) { if (!eplArgs.custom) { eplArgs.custom = {}; } eplArgs.custom[eID] = custF; } eplSetAdM(eID, custF?true:false); } function eplSetAd(eID) { if (eplCheckStart()) { var opts = (eplArgs.sOpts && eplArgs.sOpts[eID]) ? eplArgs.sOpts[eID] : {}; if (opts.custF) { document.epl.setCustomAdShow(eID,opts.custF); } document.epl.setSpace(eID, opts); } else { setTimeout(\'eplSetAd("\'+eID+\'");\', 250); } } function eplAD4(eID, opts) { document.write(\'<div id="eplAdDiv\'+eID+\'"></div>\'); if (!opts) opts = {t:1}; if (!eplArgs.sOpts) { eplArgs.sOpts = {}; } eplArgs.sOpts[eID] = opts; eplSetAd(eID); }; </script> <!-- e-planning SETUP end --> '; return $result; } }<file_sep>/source/application/models/DbTable/User.php <?php /** * Table Activities * * @author marrselo */ class Application_Model_DbTable_User extends Core_Db_Table { protected $_name = "user"; protected $_primary = "idUser"; const NAMETABLE = 'user'; static function populate($params) { $data = array( 'name' => isset($params['name']) ? $params['name'] : '', 'lastName' => isset($params['lastName']) ? $params['lastName'] : '', 'firstName' => isset($params['firstName']) ? $params['firstName'] : '', 'age' => isset($params['age']) ? $params['age'] : '', 'mail' => isset($params['mail']) ? $params['mail'] : '', 'lastUpdate' => date('Y-m-d H:i:s') ); $data = array_filter($data); $data['flagAct'] = isset($params['flagAct']) ? $params['flagAct'] : 1; return $data; } public function getPrimaryKey() { return $this->_primary; } } <file_sep>/source/application/entitys/HobbyUser.php <?php class Application_Entity_HobbyUser extends Core_Model { protected $_tableHobbyUser; public function __construct() { $this->_tableHobbyUser = new Application_Model_DbTable_HobbyUser(); } public function insertUserHobby($idHobby, $idUser) { $data = array('idHobby' => $idHobby, 'idUser' => $idUser); $this->_tableHobbyUser->insert($data); } public function deleteUserHobby($idUser) { $where = $this->_tableHobbyUser->getAdapter() ->quoteInto('idUser = ?', $idUser); $this->_tableHobbyUser->delete($where); } public function getHobby($id) { $smt = $this->_tableHobbyUser->getAdapter()->select()->distinct() ->from(array('fh' => $this->_tableHobbyUser->getName()), array('idhobbyuser' => 'fh.idhobbyuser') ) ->join(array('f' => 'hobby'), "f.idHobby = fh.idHobby",array('idHobby' => 'f.idHobby') ) ->where("fh.idUser = ?", $id) ->query(); $result = $smt->fetchAll(); $smt->closeCursor(); return $result; } } <file_sep>/source/library/ZExtraLib/UploadFtpImgServer.php <?php class ZExtraLib_UploadFtpImgServer { protected $_hostFtp; protected $_userFtp; protected $_passwordFtp; protected $_file; protected $_conecFtp; function __construct() { $configFtp = ZExtraLib_Server::getFile(0)->upload; $this->_hostFtp = $configFtp['host']; $this->_userFtp = $configFtp['user']; $this->_passwordFtp = $configFtp['password']; $this->_file = $configFtp['fileBase']; $this->_conecFtp = ftp_connect($this->_hostFtp); } function connect(){ $resultado = ftp_login($this->_conecFtp, $this->_userFtp, $this->_passwordFtp); $result = ! ((! $this->_conecFtp) || (! $resultado)); ftp_pasv($this->_conecFtp, true); return $result; } function upFile($remoteFile, $localFile) { ftp_put($this->_conecFtp, $remoteFile,$localFile, FTP_BINARY); ftp_chmod($this->_conecFtp, 0777, $remoteFile); } function upAsincFile($remoteFile, $localFile) { ftp_nb_put($this->_conecFtp, $remoteFile, $localFile, FTP_BINARY); ftp_chmod($this->_conecFtp, 0777, $remoteFile); } function newDirectory($ruta, $nomdir,$permisos=null) { $nroPermiso=empty($permisos)?0777:$permisos; ftp_chdir($this->_conecFtp, $ruta); if (!@ftp_chdir($this->_conecFtp, $nomdir)) { @ftp_mkdir($this->_conecFtp, $nomdir); @ftp_chmod($this->_conecFtp,$nroPermiso, $nomdir); } } function existe($remote_file){ // @ftp_chmod($this->_conecFtp, 0777, $remote_file); return (@ftp_chdir($this->_conecFtp, $remote_file)); } function asignarPermisos($ruta,$permisos){ @ftp_chmod($this->_conecFtp, $permisos, $ruta); } function delete ($remote_file) { return ftp_delete($this->_conecFtp, $remote_file); } function closeConect() { ftp_close($this->_conecFtp); } function moveFile($rutaOrigin,$rutaEnd) { ftp_rename($this->_conecFtp,$rutaOrigin,$rutaEnd); //ftp_chmod($this->_conecFtp, 0777,$rutaEnd); } function copyFile($fileOrigen,$fileDestino,$rutaDestino) { ftp_chdir($this->_conecFtp,$rutadestino); // realizamos la copia ftp_put($this->_conecFtp,$filedestino,$fileorigen,FTP_BINARY); } function existFile($remote_file) { $res = ftp_size($this->_conecFtp,$remote_file); if ($res != -1) { return true; } else { return false; } } }<file_sep>/source/library/ZExtraLib/Form.php <?php class ZExtraLib_Form extends Zend_Form{ public $_hostFileStatic; function init() { parent::init(); $this->_hostFileStatic = ZExtraLib_Server::getStatic()->host; } public function addDecoratorCustom($file) { $this->setDecorators(array(array('ViewScript',array('viewScript'=>$file)))); } function fetchPairs($array){ $data=array(); foreach ($array as $index){ $arrayKey=array_keys($index); if(count($arrayKey)>=2) $data[$index[$arrayKey[0]]] = $index[$arrayKey[1]]; else $data[$index[$arrayKey[0]]] = $index[$arrayKey[0]]; } return $data; } } ?> <file_sep>/source/library/ZExtraLib/Template.php <?php class ZExtraLib_Template { function load($template, $replace = null) { $db = ZExtraLib_Server::getDb('query'); //if (!$result = ZExtraLib_Cache::load('Template' . $template)) { $result = $db->fetchOne('SELECT Contenido FROM NPC_Plantilla WHERE Descripcion = ?' , array($template)); // ZExtraLib_Cache::save($result, 'Template' . $template); // } $template = $result; if ($replace != null) { foreach ($replace as $index => $value) : $template = str_replace($index, $value, $template); endforeach; //end foreach } return $template; } } //class Template<file_sep>/source/application/modules/service/controllers/UserController.php <?php class Service_UserController extends Core_Controller_ActionService{ public function init() { $this->_helper->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); } public function loginAction() { $this->_helper->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); $pass=$this->_getParam('idFacebook',0); $email=$this->_getParam('mail',0); $rpta=array('msj'=>''); try{ if($this->_request->isGet() && !empty($email) && !empty($pass)){ $objUser = new Application_Model_DbTable_User(); $dataU = $objUser->getIdUser($pass); if($dataU != false){ $result = $this->auth($email, $pass ); if($result){ //$this->_identity->urlImageProfile=DINAMIC_URL.'user/origin/'.$this->_identity->urlImageProfile; $rpta=array('msj'=>'ok','identity'=>$this->_identity); }else{ $rpta=array('msj'=>'incorrect login'); } }else{ $rpta=array('msj'=>'unregister'); } }else{ $rpta=array('msj'=>'no authorized, wrong params'); } }catch(Exception $e){ $rpta=$e->getMessage(); } $this->getResponse() ->setHttpResponseCode(200) ->setHeader('Content-type', 'application/json;charset=UTF-8', true) ->appendBody(json_encode($rpta)); } public function registerAction() { $rpta = array('msj' => ''); try { if ($this->_request->isPost()) { $params = $this->_getAllParams(); $idFacebook = $params['idFacebook']; $objUser = new Application_Model_User(); $result = $objUser->getOneUser($idFacebook); if (!$result) { $obj = new Application_Entity_RunSql('User'); $obj->save = $params; $id = $obj->save; $rpta = array('msj' => 'ok', 'id' => $id); } else { $rpta = array('msj' => 'ya existe el usuario'); } } else { $rpta = array('msj' => 'no authorized, method not post'); } } catch (Exception $e) { $rpta = $e->getMessage(); } $this->getResponse() ->setHttpResponseCode(200) ->setHeader('Content-type', 'application/json;charset=UTF-8', true) ->appendBody(json_encode($rpta)); } } <file_sep>/source/application/entitys/Hobby.php <?php class Application_Entity_Hobby extends Core_Model { protected $_tableHobbyUser; public function __construct() { $this->_tableHobby = new Application_Model_DbTable_Hobby(); } public function listAll() { $smt = $this->_tableHobby->getAdapter()->select()->distinct() ->from($this->_tableHobby->getName()) ->query(); $result = array(); while ($row = $smt->fetch()) { $result[$row['idHobby']] = $row['name']; } $smt->closeCursor(); return $result; } } <file_sep>/source/application/modules/service/controllers/LevelController.php <?php class Service_LevelController extends Core_Controller_ActionService { protected $_config; public function init() { $this->_helper->layout()->disableLayout(); $this->_config = $this->getConfig(); $this->_helper->viewRenderer->setNoRender(true); } public function getConfig() { return Zend_Registry::get('config'); } public function insertLevelAction() { $this->_helper->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); $rpta = array(); if ($this->_request->isPost()) { try { $category = $this->_getParam('category', 0); $level = $this->_getParam('level', 0); $idUser = $this->_getParam('idUser', 0); if (!empty($category) && !empty($idUser)) { $objUser = new Application_Model_Level(); $result = $objUser->getOneUserLevel($idUser, $category); $params['idLevel'] = $result['idLevel']; $obj = new Application_Entity_RunSql('Level'); $params['idUser'] = $idUser; $params['category'] = $category; $params['level'] = $level; if (empty($params['idLevel'])) { $obj->save = $params; $id = $obj->save; $rpta = array('msj' => 'ok', 'id' => $id); } else { $obj->edit = $params; $rpta = array('msj' => 'nivel actualizado'); } $cod = 200; } else { $cod = 200; $rpta['msj'] = 'missing parameters'; } } catch (Exception $e) { $cod = 500; $rpta = $e->getMessage(); } } else { $cod = 401; $rpta = array('msj' => 'no authorized, method not post'); } $this->getResponse() ->setHttpResponseCode($cod) ->setHeader('Content-type', 'application/json;charset=UTF-8', true) ->appendBody(json_encode($rpta)); } public function getCategoryUserAction() { $this->_helper->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); $rpta = array(); if ($this->_request->isGet()) { try { $idUser = $this->_getParam('idUser', 0); if (!empty($idUser)) { $objUser = new Application_Model_Level(); $result = $objUser->getCategoryUserLevel($idUser); if ($result) { $rpta = $result; } else { $rpta = array('msj' => 'no hay datos'); } $cod = 200; } else { $cod = 200; $rpta['msj'] = 'missing parameters'; } } catch (Exception $e) { $cod = 500; $rpta = $e->getMessage(); } } else { $cod = 401; $rpta = array('msj' => 'no authorized, method not post'); } $this->getResponse() ->setHttpResponseCode($cod) ->setHeader('Content-type', 'application/json;charset=UTF-8', true) ->appendBody(json_encode($rpta)); } public function getLevelAction() { $this->_helper->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); $rpta = array(); if ($this->_request->isGet()) { try { $category = $this->_getParam('category', 0); $idUser = $this->_getParam('idUser', 0); if (!empty($category) && !empty($idUser)) { $objUser = new Application_Model_Level(); $result = $objUser->getOneUserLevel($idUser, $category); if ($result) { $rpta = $result; } else { $rpta = array('msj' => 'no hay datos'); } $cod = 200; } else { $cod = 200; $rpta['msj'] = 'missing parameters'; } } catch (Exception $e) { $cod = 500; $rpta = $e->getMessage(); } } else { $cod = 401; $rpta = array('msj' => 'no authorized, method not post'); } $this->getResponse() ->setHttpResponseCode($cod) ->setHeader('Content-type', 'application/json;charset=UTF-8', true) ->appendBody(json_encode($rpta)); } public function getLevelRankingAction() { $this->_helper->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); $rpta = array(); if ($this->_request->isGet()) { try { $category = $this->_getParam('category', 0); $idUser = $this->_getParam('idUser', 0); if (!empty($category) && !empty($idUser)) { $objUser = new Application_Model_Level(); $result = $objUser->getOneUserLevel($idUser, $category); if ($result['level']) { $rpta = $objUser->getDataUserConfirm($result['level']); } else { if ($objUser->getCategory($category)) { $rpta = $objUser->getCategory($category); } else { $rpta['msj'] = 'no hay data'; } } $cod = 200; } else { $cod = 200; $rpta['msj'] = 'missing parameters'; } } catch (Exception $e) { $cod = 500; $rpta = $e->getMessage(); } } else { $cod = 401; $rpta = array('msj' => 'no authorized, method not post'); } $this->getResponse() ->setHttpResponseCode($cod) ->setHeader('Content-type', 'application/json;charset=UTF-8', true) ->appendBody(json_encode($rpta)); } } <file_sep>/source/library/ZExtraLib/Controller/Action.php <?php class ZExtraLib_Controller_Action extends Zend_Controller_Action { protected $_layout; protected $_hostFileStatic; protected $_arrayAclAnunciante; protected $_identity; protected $_identityTemp; protected $_sessionAdmin; /** * * @var Zend_Session_Namespace */ public $session; public function init() { parent::init(); if (!Zend_Session::isStarted()) { echo 'inciando session'; Zend_Session::start(); } $this->session = new Zend_Session_Namespace('Neoauto'); if (!isset($this->session->initialized)) { Zend_Session::regenerateId(); $this->session->initialized = true; } $this->_sessionAdmin = new Zend_Session_Namespace('sessionAdmin'); if (isset($this->_sessionAdmin->identity)){ $this->view->identityAdmin = $this->_sessionAdmin->identity; } $this->_identity = Zend_Auth::getInstance()->getIdentity(); $frontController = Zend_Controller_Front::getInstance(); $fechaCierre = date("Y-m-d",strtotime($frontController->getParam('bootstrap')->getOption('MessageClose'))); $fechaActual = date("Y-m-d"); $this->view->fechaCierre = ($fechaActual < $fechaCierre )? $fechaCierre: null; $this->view->mensajeFechaCierre = (!empty($this->view->fechaCierre))? 'Estimados anunciantes, el cierre de publicaciones para la edición impresa del domingo 31 de Marzo será adelantada al día miércoles 27 de Marzo hasta las 6:00 p.m., aplica para todos nuestros canales de venta, incluyendo fonoavisos y agencias concesionarias, toda publicidad ingresada después de esta fecha y hora, pasará a publicarse en la siguiente edición impresa del domingo 07 de Abril.' : ''; $this->view->rutaBlog = $this->_rutaBlog = $frontController->getParam('bootstrap')->getOption('BlogNeoautoHome'); $this->_hostFileStatic = ZExtraLib_Server::getStatic()->host; $this->_hostFileContent = ZExtraLib_Server::getContent()->host; $this->_layout = Zend_Layout::getMvcInstance(); $this->initMenuPortal(); $this->session->_identityTemp = isset($this->session->_identityTemp) ? $this->session->_identityTemp : $this->_identity; $this->view->identity = $this->_identity; $this->view->hostFileStatic = $this->_hostFileStatic; $this->view->cantidadPalabrasImpresoTipoPUblicacion = ''; $this->_configImg = ZExtraLib_Server::getFile(0)->upload; $this->view->configImg = $this->_configImg; $this->_versionJs = ZExtraLib_Server::getStatic()->versionJs; $this->view->versionJs = $this->_versionJs; $this->_hostImg = ZExtraLib_Server::getFile(0)->host; $this->view->hostImg = $this->_hostImg; $this->view->hostContent = $this->_hostFileContent; $detalleBusqueda = new Application_Model_DetalleBusqueda(); $this->view->contarAvisosMarcaFooter = $detalleBusqueda->contarAvisosMarca( Application_Model_DbTable_TipoVehiculo::TipoVehiculoAuto); $this->view->contarModelos = $detalleBusqueda->contarModelo(); $this->view->contarUltimosAvisosFooter = $detalleBusqueda->ultimosAvisosUsados(6); $this->view->AclAnunciante = $this->_arrayAclAnunciante; $this->view->filterHtml = new Zend_Filter_StripTags(); $this->verficarPermisos(); $this->view->messages = $this->_helper->getHelper('FlashMessenger')->getMessages(); $this->initView(); } public function initMenuPortal() { if ($this->_request->getModuleName() == 'default') { switch ($this->_request->getControllerName()) { case 'autosnuevos':$this->view->menuItemSelected_2 = 'selected'; break; case 'autonuevo-concesionario':$this->view->menuItemSelected_2 = 'selected'; break; case 'autosusados':$this->view->menuItemSelected_3 = 'selected'; break; case 'cuenta': $this->view->menuItemSelected_1 = ''; break; case 'motos' : $this->view->menuItemSelected_5 = 'selected'; break; default : $this->view->menuItemSelected_1 = 'selected'; } } } public function verficarPermisos() { $resource = 'mvc:anunciante/index/index'; $nameCon = $this->_request->getControllerName(); $nameAct = $this->_request->getActionName(); $nameMod = $this->_request->getModuleName(); $resourceMod = 'mvc:' . $nameMod . '/*'; $resourceCont = 'mvc:' . $nameMod . '/' . $nameCon . '/*'; $resourceAct = 'mvc:' . $nameMod . '/' . $nameCon . '/' . $nameAct; $rol = (!isset($this->_identity->IdRolUsuarioAnunciante) || ($this->_identity->IdRolUsuarioAnunciante == '')) ? 1 : $this->_identity->IdRolUsuarioAnunciante; try { if (!$this->isAllowed($rol, $resourceMod)) { if (!$this->isAllowed($rol, $resourceCont)) { if (!$this->isAllowed($rol, $resourceAct)) { $this->view->headLink()->appendStylesheet(ZExtraLib_Server::getStatic()->host . '/f/css/print.css', 'media'); $this->view->headLink()->appendStylesheet(ZExtraLib_Server::getStatic()->host . '/f/css/screen.css'); $this->view->headLink()->appendStylesheet(ZExtraLib_Server::getStatic()->host . '/f/css/boutique.css'); $request = $this->getRequest(); $request = $request->setModuleName('default'); $request = $request->setControllerName('error'); $request = $request->setActionName('error'); $this->_helper->actionStack($request); } } } } catch (Exception $exc) { echo $exc->getTraceAsString(); } } public function isAllowed($rol, $recuros) { $acl = Zend_Registry::get('Acl'); try { return $acl->isAllowed($rol, $recuros); } catch (Exception $exc) { //echo $exc->getTraceAsString(); return false; } } function setParamIdentity($parametro, $value) { /* $auth = Zend_Auth::getInstance(); $identity = $auth->getStorage()->read(); $identity->$parametro=$value; $auth = new Zend_Session; */ $obj = $_SESSION['Zend_Auth']['storage']; $obj->$parametro = $value; } public function auth($usuario =NULL, $password =<PASSWORD>, $encripty = NULL,$noauth = NULL) { if ($usuario == NULL || $password == <PASSWORD>) { return false; } else { $auth = Zend_Auth::getInstance(); if(($encripty == 1)){ $adapter = new ZExtraLib_Auth_Adapter_ClubDbTable(ZExtraLib_Server::getInstance()->getDb('process'), 'NPC_VW_CredencialesUsuarioAnunciante', 'UsuarioCredencial', 'ClaveCredencial'); }else{ $adapter = new Zend_Auth_Adapter_DbTable(ZExtraLib_Server::getInstance()->getDb('process'), 'NPC_VW_CredencialesUsuarioAnunciante', 'UsuarioCredencial', 'ClaveCredencial'); } $adapter->setIdentity($usuario); $adapter->setCredential($password); if ($noauth!=1) { $resultAut = $auth->authenticate($adapter); $resultAut = $resultAut->isValid(); } else { $resultAut = $adapter->authenticate(); $resultAut = $resultAut->isValid(); } if ($resultAut) { if($noauth!=1) { $userInfo = $adapter->getResultRowObject(null, 'ClaveCredencial'); $authStorage = $auth->getStorage(); $authStorage->write($userInfo); $this->_identity = Zend_Auth::getInstance()->getIdentity(); } } return $resultAut; } } } <file_sep>/source/library/ZExtraLib/Controller/ActionCallCenter.php <?php class ZExtraLib_Controller_ActionCallCenter extends ZExtraLib_Controller_Action { protected $_layout; protected $_hostFileStatic; protected $_arrayAclAnunciante; protected $_identity; protected $_identityTemp; protected $_sessionAdmin; /** * * @var Zend_Session_Namespace */ public $session; public function init() { parent::init(); if (!Zend_Session::isStarted()) { echo 'inciando session'; Zend_Session::start(); } // $this->session = (!isset($this->session)) ? new Zend_Session_Namespace('Neoauto') : null; $this->session = new Zend_Session_Namespace('Neoauto'); if (!isset($this->session->initialized)) { Zend_Session::regenerateId(); $this->session->initialized = true; } $this->_sessionAdmin = new Zend_Session_Namespace('sessionAdmin'); if (isset($this->_sessionAdmin->identity)){ $this->view->identityAdmin = $this->_sessionAdmin->identity; } $this->_identity = Zend_Auth::getInstance()->getIdentity(); if ( isset($this->_identity) && ($this->_identity->TipoUsuarioAnunciante == 1 || $this->_identity->TipoUsuarioAnunciante == 2)){ $modelEmpresa = new Application_Model_Empresa(); $cantidad = $modelEmpresa->cantidadEmpresaporPersonaNatural($this->_identity->IdUsuarioAnunciante); $cantidadEmpresas = $cantidad['cantEmpresas']; } //$this->view->identityTemp = ZExtraLib_Utils::getIdentityTemp(); if (isset($this->_identity)) { //3 menus si es revendedor $flagAvisosImportados = 0; $modelAvisoInactivos = new Application_Model_AvisoInactivo(); $this->view->ListaAvisosInactivos = $modelAvisoInactivos-> listarAvisosInactivoPorUsuario($this->_identity->IdUsuarioAnunciante); $countAvisosImport = count($this->view->ListaAvisosInactivos); if ($countAvisosImport > 0) { $flagAvisosImportados = 1; } if(isset($cantidadEmpresas) && $cantidadEmpresas>0){ $opcionDatosFacturacion = array("nombre" => "Datos de Facturación", "ruta" => '/anunciante/miperfil/empresas-registradas', "arbol" => array("nueva-empresa" => array("nombre" => "Nueva Empresa", "ruta" => '/anunciante/miperfil/nueva-empresa'), "empresas-registradas" => array("nombre" => "Empresas Registradas", "ruta" => '/anunciante/miperfil/empresas-registradas') ) ); }else{ $opcionDatosFacturacion = array("nombre" => "Datos de Facturación", "ruta" => '/anunciante/miperfil/nueva-empresa', "arbol" => array("nueva-empresa" => array("nombre" => "Nueva Empresa", "ruta" => '/anunciante/miperfil/nueva-empresa') ) ); } if ($flagAvisosImportados != 1) { $opcionMicuenta = array("nombre" => "Mi Cuenta", "ruta" => '/anunciante/micuenta/avisos-activos', "arbol" => array("misAvisos" => array("nombre" => "Mis Avisos", "ruta" => '/anunciante/micuenta/avisos-activos', "arbol" => array("avisos-activos" => array("nombre" => "Avisos Activos", "ruta" => '/anunciante/micuenta/avisos-activos'), "avisos-baja" => array("nombre" => "Avisos de Baja", "ruta" => '/anunciante/micuenta/avisos-baja' ) ) ) ) ); } else { $opcionMicuenta = array("nombre" => "Mi Cuenta", "ruta" => '/anunciante/micuenta/avisos-activos', "arbol" => array("misAvisos" => array("nombre" => "Mis Avisos", "ruta" => '/anunciante/micuenta/avisos-activos', "arbol" => array("avisos-activos" => array("nombre" => "Avisos Activos", "ruta" => '/anunciante/micuenta/avisos-activos'), "avisos-baja" => array("nombre" => "Avisos de Baja", "ruta" => '/anunciante/micuenta/avisos-baja'), "avisos-importados" => array("nombre" => "Del Papel <span class='red xactive' style='font-size:0.8em;'>($countAvisosImport por activar)</span>", "ruta" => '/anunciante/micuenta/avisos-importados' ) ) ) ) ); } $opcionMisDatos = array("nombre" => "Mis Datos", "ruta" => '/anunciante/miperfil/datos-personales', "arbol" => array("datos-personales" => array("nombre" => "Datos Personales", "ruta" => '/anunciante/miperfil/datos-personales'), "cambio-clave" => array("nombre" => "Cambio de Clave", "ruta" => '/anunciante/miperfil/cambio-clave'), "mis-favoritos" => array("nombre" => "Mis Favoritos", "ruta" => '/anunciante/miperfil/mis-favoritos') ) ); $usuarioAnunciante = new Application_Model_UsuarioAnunciante(); $cantidadAvisos = $usuarioAnunciante->verificarCantidadAvisos($this->_identity->IdUsuarioAnunciante); if ($this->_identity->TipoUsuarioAnunciante == 1 && count($cantidadAvisos) < 2) { $this->_arrayAclAnunciante = $arrayAcl = array("miperfil" => array("nombre" => "Mi perfil", "ruta" => ('/anunciante/miperfil/datos-personales'), "arbol" => array( "misdatos" => $opcionMisDatos, "datosFacturacion" => $opcionDatosFacturacion, ) ), "micuenta" => $opcionMicuenta ); } elseif ($this->_identity->TipoUsuarioAnunciante == 1 && count($cantidadAvisos) > 1) { $this->_arrayAclAnunciante = $arrayAcl = array("miperfil" => array("nombre" => "Mi perfil", "ruta" => ('/anunciante/miperfil/datos-personales'), "arbol" => array( "misdatos" => $opcionMisDatos, "datosFacturacion" => $opcionDatosFacturacion ) ), "micuenta" => $opcionMicuenta, "oportunidad" => array("nombre" => "Oportunidad de Negocio", "ruta" => '/anunciante/miperfil/oportunidad-de-negocio', "arbol" => array(), ) ); } elseif ($this->_identity->TipoUsuarioAnunciante == 2) { $this->_arrayAclAnunciante = $arrayAcl = array("miperfil" => array("nombre" => "Mi perfil", "ruta" => ('/anunciante/miperfil/datos-personales'), "arbol" => array( "misdatos" => $opcionMisDatos, "datosFacturacion" => $opcionDatosFacturacion ) ), "micuenta" => $opcionMicuenta, "vendedor" => array("nombre" => "Vendedor", "ruta" => '/anunciante/vendedor/inicio', "arbol" => array( "inicio" => array("nombre" => "Inicio", "class" => "inicio", "ruta" => '/anunciante/vendedor/inicio', "arbol" => ''), "misdatos" => array("nombre" => "Mis Datos", "class" => "mis-datos", "ruta" => '/anunciante/vendedor/mis-datos', "arbol" => ''), "avisos-activos-paquete" => array("nombre" => "Mis Avisos", "class" => "avisos-activos-paquete", "ruta" => '/anunciante/vendedor/avisos-activos-paquete', "arbol" => array("anadir-avisos-paquete" => array("nombre" => "Añadir Avisos", "ruta" => '/anunciante/vendedor/anadir-avisos-paquete'), "avisos-activos-paquete" => array("nombre" => "Avisos Activos", "ruta" => '/anunciante/vendedor/avisos-activos-paquete'), "listar-avisos-baja" => array("nombre" => "De baja", "ruta" => '/anunciante/vendedor/listar-avisos-baja') ) ), "Mis Paquetes" => array("nombre" => "Mis Paquetes", "class" => "mis-paquetes", "ruta" => '/anunciante/vendedor/mis-paquetes', "arbol" => '' ), "Nota Informativa" => array("nombre" => "Nota Informativa", "class" => "nota-informativa", "ruta" => '/anunciante/vendedor/nota-informativa', "arbol" => '' ), "utilidades" => array("nombre" => "Utilidades", "class" => "utilidades", "ruta" => '/anunciante/vendedor/utilidades', "arbol" => '') ), ) ); } elseif ($this->_identity->TipoUsuarioAnunciante == 3) { $modeloMarca = new Application_Model_Marca(); $this->view->marca = $modeloMarca->getDatosCero0km($this->_identity->IdUsuarioAnunciante); $this->_arrayAclAnunciante = $arrayAcl = array("miperfil" => array("nombre" => "cerokm", "ruta" => '/cerokm/admin/inicio', "arbol" => array( "inicio" => array("nombre" => "Inicio", "class" => "inicio", "ruta" => '/cerokm/admin/inicio', "arbol" => ''), "mis-datos" => array("nombre" => "Mis Datos", "class" => "mis-datos", "ruta" => '/cerokm/admin/mis-datos', "arbol" => ''), "vehiculos" => array("nombre" => "Mis Vehículos", "class" => "mis-vehiculos", "ruta" => '/cerokm/vehiculos/mis-vehiculos', "arbol" => array("mis-vehiculos" => array("nombre" => "Vehículos Activos", "action" => 'mis-vehiculos', "ruta" => '/cerokm/vehiculos/mis-vehiculos') /* , "vehiculo-inactivo" => array("nombre" => "Vehículos Inactivos", "action" => 'vehiculo-inactivo', "ruta" => '/cerokm/vehiculos/vehiculo-inactivo')*/ ) ), "nota informativa" => array("nombre" => "Nota Informativa", "class" => "nota-informativa", "ruta" => '/cerokm/admin/nota-informativa', "arbol" => ''), "utilidades" => array("nombre" => "Utilidades", "class" => "utilidades", "ruta" => '/cerokm/admin/utilidades', "arbol" => '') ) ) ); } elseif ($this->_identity->TipoUsuarioAnunciante == 4) { /*Revisar si no se usa*/ $concesionario = new Application_Model_Concesionario(); $this->view->getConcesionario = $concesionario ->concesionarioMisDatos( $this->_identity->IdEnte,$this->_identity->IdUsuarioAnunciante); /***/ $this->_arrayAclAnunciante = $arrayAcl = array("miperfil" => array("nombre" => "Concesionario", "ruta" => '/concesionario/admin/inicio', "arbol" => array( "inicio" => array("nombre" => "Inicio", "class" => "inicio", "ruta" => '/concesionario/admin/inicio', "arbol" => ''), "mis-datos" => array("nombre" => "Mis Datos", "class" => "mis-datos", "ruta" => '/concesionario/admin/mis-datos', "arbol" => ''), "avisos" => array("nombre" => "Mis Avisos", "class" => "anadir-avisos", "ruta" => '/concesionario/avisos/anadir-avisos', "arbol" => array("anadir-avisos" => array("nombre" => "Añadir Avisos", "action" => 'anadir-avisos', "ruta" => '/concesionario/avisos/anadir-avisos'), "avisos-activos" => array("nombre" => "Avisos Activos", "action" => 'avisos-activos', "ruta" => '/concesionario/avisos/avisos-activos'), "avisos-baja" => array("nombre" => "De baja", "action" => 'avisos-baja', "ruta" => '/concesionario/avisos/avisos-baja') ) ), "tienda" => array("nombre" => "Mi Tienda", "class" => "destacados", "ruta" => '/concesionario/tienda/destacados', "arbol" => array("destacados" => array("nombre" => "<NAME>", "action" => 'destacados', "ruta" => '/concesionario/tienda/destacados'), "nota-informativa" => array("nombre" => "Nota Informativa", "action" => 'nota-informativa', "ruta" => '/concesionario/tienda/nota-informativa') //, // "promociones" => // array("nombre" => "Promociones", // "action" => 'promociones', // "ruta" => '/concesionario/tienda/promociones') ) ), "Mis Paquetes" => array("nombre" => "Mis Paquetes", "class" => "mis-paquetes", "ruta" => '/concesionario/admin/mis-paquetes', "arbol" => '' ), "utilidades" => array("nombre" => "Utilidades", "class" => "utilidades", "ruta" => '/concesionario/admin/utilidades', "arbol" => '') ) ) ); } } $frontController = Zend_Controller_Front::getInstance(); $fechaCierre = date("Y-m-d",strtotime($frontController->getParam('bootstrap')->getOption('MessageClose') )); $fechaActual = date("Y-m-d"); $this->view->fechaCierre = ($fechaActual < $fechaCierre )? $fechaCierre: null; $this->view->mensajeFechaCierre = (!empty($this->view->fechaCierre))? 'Estimados anunciantes, el cierre de publicaciones para la edición impresa del domingo 04 de Noviembre será adelantada al día miércoles 31 de Octubre hasta las 6:00 p.m., aplica para todos nuestros canales de venta, incluyendo fonoavisos y agencias concesionarias, toda publicidad ingresada después de esta fecha y hora, pasará a publicarse en la siguiente edición impresa del domingo 11 de Noviembre.' : ''; $this->view->rutaBlog = $this->_rutaBlog = $frontController->getParam('bootstrap')->getOption('BlogNeoautoHome'); $this->_hostFileStatic = ZExtraLib_Server::getStatic()->host; $this->_hostFileContent = ZExtraLib_Server::getContent()->host; $this->_layout = Zend_Layout::getMvcInstance(); $this->initMenuPortal(); $this->initMenuAnunciante(); $this->initPublicacion(); $this->session->_identityTemp = isset($this->session->_identityTemp) ? $this->session->_identityTemp : $this->_identity; $this->view->identity = $this->_identity; $this->view->hostFileStatic = $this->_hostFileStatic; $this->view->cantidadPalabrasImpresoTipoPUblicacion = ''; $this->_configImg = ZExtraLib_Server::getFile(0)->upload; $this->view->configImg = $this->_configImg; $this->_versionJs = ZExtraLib_Server::getStatic()->versionJs; $this->view->versionJs = $this->_versionJs; $this->_hostImg = ZExtraLib_Server::getFile(0)->host; $this->view->hostImg = $this->_hostImg; $this->view->hostContent = $this->_hostFileContent; $detalleBusqueda = new Application_Model_DetalleBusqueda(); $this->view->contarAvisosMarcaFooter = $detalleBusqueda->contarAvisosMarca(); $this->view->contarModelos = $detalleBusqueda->contarModelo(); $this->view->contarUltimosAvisosFooter = $detalleBusqueda->ultimosAvisosUsados(6); $this->view->AclAnunciante = $this->_arrayAclAnunciante; $this->view->filterHtml = new Zend_Filter_StripTags(); $this->verficarPermisos(); $this->view->messages = $this->_helper->getHelper('FlashMessenger')->getMessages(); $this->initView(); // $recorrido = array( // 'nombreAction'=>$this->_request->getActionName(), // 'nombreController'=>$this->_request->getControllerName(), // 'nombreModuelo'=>$this->_request->getModuleName(), // 'nombreParametros'=> $this->_request->getParams() // ); // ZExtraLib_Log::err( // print_r($recorrido,true) // ); //echo ZExtraLib_Utils::encrypt('123456'); } public function initPublicacion() { if($this->_getParam('reset')==1){ } if($this->_request->getModuleName() == 'anunciante') { if ($this->_request->getControllerName() == 'publicacion') { $this->_layout->setLayout('layout-anunciante-publicacion'); } else { if (isset($this->session->AvisoRegistrado)) { $this->session->AvisoRegistrado = null; unset($this->session->AvisoRegistrado); $this->session->flagAvisoImportado = null; unset($this->session->flagAvisoImportado); } } }elseif ($this->_request->getModuleName() == 'concesionario') { $this->_layout->setLayout('layout-concesionario'); $this->session->AvisoRegistrado = null; unset($this->session->AvisoRegistrado); $this->session->flagAvisoImportado = null; unset($this->session->flagAvisoImportado); } if( $this->_request->getModuleName() == 'default' && $this->_request->getControllerName() == 'index' ) { $this->session->AvisoRegistrado = null; unset($this->session->AvisoRegistrado); $this->session->flagAvisoImportado = null; unset($this->session->flagAvisoImportado); } } public function initMenuPortal() { if ($this->_request->getModuleName() == 'default') { switch ($this->_request->getControllerName()) { case 'autosnuevos':$this->view->menuItemSelected_2 = 'selected'; break; case 'autonuevo-concesionario':$this->view->menuItemSelected_2 = 'selected'; break; case 'autosusados':$this->view->menuItemSelected_3 = 'selected'; break; case 'cuenta': $this->view->menuItemSelected_1 = ''; break; case 'motos' : $this->view->menuItemSelected_5 = 'selected'; break; default : $this->view->menuItemSelected_1 = 'selected'; } } } public function initMenuAnunciante() { if ($this->_request->getModuleName() == 'anunciante') { if (!$this->_identity && (!($this->_request->getControllerName() == 'publicacion' && $this->_request->getActionName() == 'index') && !($this->_request->getControllerName() == 'pagoefectivo' && $this->_request->getActionName() == 'pago-efectivo-urlok')) ) { $this->_redirect(ZExtraLib_Server::getContent()->host); } $this->_layout->setLayout('layout-anunciante'); switch ($this->_request->getControllerName()) { case 'miperfil':$this->view->menuAdminSelectd_1 = 'selected'; break; case 'micuenta':$this->view->menuAdminSelectd_2 = 'selected'; break; case 'vendedor':$this->view->menuAdminSelectd_3 = 'selected'; break; } } elseif ($this->_request->getModuleName() == 'concesionario') { $this->_layout->setLayout('layout-concesionario'); if (!$this->_identity){ $this->_redirect(ZExtraLib_Server::getContent()->host); } // switch ($this->_request->getControllerName()) { // case 'admin':$this->view->menuAdminSelectd_1 = 'selected'; // break; // case 'avisos':$this->view->menuAdminSelectd_2 = 'selected'; // break; // case 'tienda':$this->view->menuAdminSelectd_3 = 'selected'; // break; // case 'utilidades':$this->view->menuAdminSelectd_4 = 'selected'; // break; // } // } elseif($this->_request->getModuleName() == 'concesionario'){ // if (!$this->_identity){ // $this->_redirect(ZExtraLib_Server::getContent()->host); // } }elseif($this->_request->getModuleName() == 'cerokm'){ if (!$this->_identity){ $this->_redirect(ZExtraLib_Server::getContent()->host); } }elseif($this->_request->getModuleName() == 'callCenter'){ if (!$this->_identity){ $this->_redirect(ZExtraLib_Server::getContent()->host); } }elseif($this->_request->getModuleName() == 'anunciante'){ if (!$this->_identity){ $this->_redirect(ZExtraLib_Server::getContent()->host); } } } public function verficarPermisos() { $resource = 'mvc:anunciante/index/index'; $nameCon = $this->_request->getControllerName(); $nameAct = $this->_request->getActionName(); $nameMod = $this->_request->getModuleName(); $resourceMod = 'mvc:' . $nameMod . '/*'; $resourceCont = 'mvc:' . $nameMod . '/' . $nameCon . '/*'; $resourceAct = 'mvc:' . $nameMod . '/' . $nameCon . '/' . $nameAct; $rol = (!isset($this->_identity->IdRolUsuarioAnunciante) || ($this->_identity->IdRolUsuarioAnunciante == '')) ? 1 : $this->_identity->IdRolUsuarioAnunciante; try { if (!$this->isAllowed($rol, $resourceMod)) { if (!$this->isAllowed($rol, $resourceCont)) { if (!$this->isAllowed($rol, $resourceAct)) { $this->view->headLink()->appendStylesheet(ZExtraLib_Server::getStatic()->host . '/f/css/print.css', 'media'); $this->view->headLink()->appendStylesheet(ZExtraLib_Server::getStatic()->host . '/f/css/screen.css'); $this->view->headLink()->appendStylesheet(ZExtraLib_Server::getStatic()->host . '/f/css/boutique.css'); $request = $this->getRequest(); $request = $request->setModuleName('default'); $request = $request->setControllerName('error'); $request = $request->setActionName('error'); $this->_helper->actionStack($request); } } } } catch (Exception $exc) { echo $exc->getTraceAsString(); } } public function isAllowed($rol, $recuros) { $acl = Zend_Registry::get('Acl'); try { return $acl->isAllowed($rol, $recuros); } catch (Exception $exc) { //echo $exc->getTraceAsString(); return false; } } function setParamIdentity($parametro, $value) { /* $auth = Zend_Auth::getInstance(); $identity = $auth->getStorage()->read(); $identity->$parametro=$value; $auth = new Zend_Session; */ $obj = $_SESSION['Zend_Auth']['storage']; $obj->$parametro = $value; } public function auth($usuario =NULL, $password =<PASSWORD>, $encripty = NULL,$noauth = NULL) { if ($usuario == NULL || $password == NULL) { return false; } else { $auth = Zend_Auth::getInstance(); if(($encripty == 1)){ $adapter = new ZExtraLib_Auth_Adapter_ClubDbTable(ZExtraLib_Server::getInstance()->getDb('process'), 'NPC_VW_CredencialesUsuarioAnunciante', 'UsuarioCredencial', 'ClaveCredencial'); }else{ $adapter = new Zend_Auth_Adapter_DbTable(ZExtraLib_Server::getInstance()->getDb('process'), 'NPC_VW_CredencialesUsuarioAnunciante', 'UsuarioCredencial', 'ClaveCredencial'); } $adapter->setIdentity($usuario); $adapter->setCredential($password); if ($noauth!=1) { $resultAut = $auth->authenticate($adapter); $resultAut = $resultAut->isValid(); } else { $resultAut = $adapter->authenticate(); $resultAut = $resultAut->isValid(); } if ($resultAut) { if($noauth!=1) { $userInfo = $adapter->getResultRowObject(null, 'ClaveCredencial'); $authStorage = $auth->getStorage(); $authStorage->write($userInfo); $this->_identity = Zend_Auth::getInstance()->getIdentity(); } } return $resultAut; } } }<file_sep>/source/library/ZExtraLib/Paginator/Custom.php <?php class ZExtraLib_Paginator_Custom implements Zend_Paginator_Adapter_Interface { protected $_sql; protected $_sqlCount; protected $_db; /* call nombreSP(parametros,?,?); * cal * */ public function __construct($sql, $sqlCount, $db) { $this->_sql = $sql; $this->_sqlCount = $sqlCount; $this->_db = $db; } public function getItems($offset, $itemCountPerPage) { $smt = $this->_db->query($this->_sql, array($offset, $itemCountPerPage)); $result = $smt->fetchAll(); $smt->closeCursor(); return $result; } public function count() { $smt = $this->_db->query($this->_sqlCount); $result = $smt->fetchColumn(0); $smt->closeCursor(); return $result; } } ?> <file_sep>/source/library/ZExtraLib/Validate/MailExist.php <?php class ZExtraLib_Validate_MailExist extends Zend_Validate_Abstract{ const MessageEmailValidator = ''; protected $_messageTemplates = array( self::MessageEmailValidator => "El correo '%value%' Se encuentra registrado por otro usuario" ); function isValid($value) { $this->_setValue($value); $user = new Application_Model_UsuarioAnunciante(); if(($user->verificarEmailUsuario($value))){ $this->_error(self::MessageEmailValidator); return false; } return true; } }<file_sep>/source/application/models/Level.php <?php class Application_Model_Level extends Core_Model { protected $_tableLevel; public function __construct() { $this->_tableLevel= new Application_Model_DbTable_Level(); } public function getOneUserLevel($idUser,$getOneUserLevel) { $smt=$this->_tableLevel->getAdapter()->query(" SELECT * FROM Level WHERE idUser='".$idUser."'and category='".$getOneUserLevel."' "); $result=$smt->fetch(); $smt->closeCursor(); return $result; } public function getCategoryUserLevel($idUser) { $smt=$this->_tableLevel->getAdapter()->query(" SELECT * FROM Level where idUser= '".$idUser."'; "); $result=$smt->fetchAll(); $smt->closeCursor(); return $result; } public function getDataUserConfirm($level) { $smt=$this->_tableLevel->getAdapter()->query(" ( SELECT U.idUser,L.idLevel,L.level as Level ,L.flagAct,U.urlImageProfile,U.firstName FROM Level AS L INNER JOIN User AS U ON U.idUser= L.idUser WHERE L.category='hobby' and L.level <='".$level."' limit 3) union (SELECT U.idUser,L.idLevel,L.level as Level ,L.flagAct,U.urlImageProfile,U.firstName FROM Level AS L INNER JOIN User AS U ON U.idUser= L.idUser WHERE L.category='hobby' and L.level >'".$level."' limit 6)order by Level asc "); $result=$smt->fetchAll(); $smt->closeCursor(); return $result; } public function getCategory($category) { $smt=$this->_tableLevel->getAdapter()->query(" SELECT U.idUser, L.idLevel,L.level,L.flagAct,U.urlImageProfile,U.firstName FROM Level AS L INNER JOIN User AS U ON L.idUser=U.idUser WHERE L.category='".$category."'order by L.level asc limit 20 "); $result=$smt->fetchAll(); $smt->closeCursor(); return $result; } } <file_sep>/source/library/ZExtraLib/Validate/LimpiarTextoAdecsys.php <?php class ZExtraLib_Validate_LimpiarTextoAdecsys { protected $_texto = ''; protected $_numero = ''; protected $_separador = ''; function __construct($texto,$separador,$number=true) { $this->_texto = $texto; $this->_numero = $number; $this->_separador = $separador; $exclude = array('%C3%B1',' ',','); $texto = str_replace(array("á", "é", "í", "ó", "ú", "ñ"), array("a", "e", "i", "o", "u", "n"), $texto); $filter = ($number) ? "/[^0-9a-zA-Z ]/i" : "/[^a-zA-Z ]/i"; echo $texto = strtolower(preg_replace($filter, '-', $texto)); $this->arrayTexto = array_filter(array_diff(array_unique(explode($separador, $texto)), $exclude)); } function stringTokenBusqueda() { return implode("-",$this->arrayTexto); } }
a5f4bf314dd0e7a9bb324a8e48f6fb39aae33f68
[ "PHP", "INI" ]
50
PHP
josmel/solar
04c6912a44dca424b8a0fa576841d7a52a7c1993
05f8d306a44866b596c9aa5dfdc1314dff648f42
refs/heads/master
<repo_name>YOMAMH/ty_cmdb_server<file_sep>/config/nconf.js /** * Created by renminghe on 2017/2/14. */ /******** 配置文件 ********/ const nconf = require("nconf"); const path = require("path"); //加载配置文件 let fileName = path.join(__dirname + "/config.development.json"); //配置mysql nconf.argv().env().file({ file: fileName }); module.exports = nconf;<file_sep>/config/sequelize.js /** * Created by renminghe on 2017/2/14. */ /******** 连接mysql ********/ const Sequelize = require('sequelize'); const nconf = require('./nconf'); let database = nconf.get('database'); let username = nconf.get('username'); let password = nconf.get('password'); let options = { host: nconf.get('host'), dialect: nconf.get('dialect'), }; let sequelize = new Sequelize(database, username, password, options); module.exports = sequelize;<file_sep>/controller/apm/index.controller.js /** * Created by renminghe on 2017/2/14. */ const co = require("co"); let apm = require("../../model/apm_model/"); /** * 返回json数据公有函数 * @param req 请求参数 * @param res 相应参数 * @param apmInfo apm_model返回的数据 */ function responseData(req, res, apmInfo) { let apmItem = ''; let apmInfoArr = []; if (apmInfo) { if (apmInfo instanceof Array) { // 如果是数组,说明是获取全部数据 for (apmItem in apmInfo) { if (apmInfo[apmItem].hasOwnProperty("dataValues")) { // 如果有dataValues属性说明获取数据成功 apmInfoArr.push(apmInfo[apmItem]["dataValues"]); } } res.json({status: 200, content: apmInfoArr}); } else { // 如果不是数组,说明是获取符合特定条件的数据 // 如果有dataValues属性说明获取数据成功,返回状态码加数据 if (apmInfo.hasOwnProperty("dataValues")) res.json({status: 200, content: apmInfo.dataValues}); if (apmInfo.toString() == '1') res.json({status: 200, content: (apmInfo.toString())}); } } else { res.json({status: 500, content: ""}); } } module.exports = { test: (req, res) => { // 测试 res.send({"status": 200, "content": "success"}); }, app: (req, res) => co(function*() { // 听云app配置信息 if (req.query && req.query.hasOwnProperty("proName")) { let apmInfo = yield apm.app(req.query.proName); responseData(req, res, apmInfo); } else { let apmInfo = yield apm.app(); responseData(req, res, apmInfo); } }), browser: (req, res) => co(function*() { // 听云browser配置信息 let apmInfo = yield apm.browser(); responseData(req, res, apmInfo); }), common: (req, res) => co(function*() { // 听云common配置信息 let apmInfo = yield apm.common(); responseData(req, res, apmInfo); }), network: (req, res) => co(function*() { // 听云network配置信息 let apmInfo = yield apm.network(); responseData(req, res, apmInfo); }), saas: (req, res) => co(function*() { // 听云saas配置信息 let apmInfo = yield apm.saas(); responseData(req, res, apmInfo); }), server: (req, res) => co(function*() { // 听云server配置信息 let apmInfo = yield apm.server(); responseData(req, res, apmInfo); }), creatApp: (req, res) => co(function*() { // 添加听云server配置信息 let apmInfo = yield apm.creatApp(req.body); responseData(req, res, apmInfo); }), creatBrowser: (req, res) => co(function*() { // 添加听云browser配置信息 let apmInfo = yield apm.creatBrowser(req.body); responseData(req, res, apmInfo); }), creatCommon: (req, res) => co(function*() { // 添加听云common配置信息 let apmInfo = yield apm.creatCommon(req.body); responseData(req, res, apmInfo); }), creatNetwork: (req, res) => co(function*() { // 添加听云network配置信息 let apmInfo = yield apm.creatNetwork(req.body); responseData(req, res, apmInfo); }), creatSaas: (req, res) => co(function*() { // 添加听云saas配置信息 let apmInfo = yield apm.creatSaas(req.body); responseData(req, res, apmInfo); }), creatServer: (req, res) => co(function*() { // 添加听云server配置信息 let apmInfo = yield apm.creatServer(req.body); responseData(req, res, apmInfo); }), updateApp: (req, res) => co(function*() { // 修改听云server配置信息 let apmInfo = yield apm.updateApp(req.body); responseData(req, res, apmInfo); }), updateBrowser: (req, res) => co(function*() { // 修改听云browser配置信息 let apmInfo = yield apm.updateBrowser(req.body); responseData(req, res, apmInfo); }), updateCommon: (req, res) => co(function*() { // 修改听云common配置信息 let apmInfo = yield apm.updateCommon(req.body); responseData(req, res, apmInfo); }), updateNetwork: (req, res) => co(function*() { // 修改听云network配置信息 let apmInfo = yield apm.updateNetwork(req.body); responseData(req, res, apmInfo); }), updateSaas: (req, res) => co(function*() { // 修改听云saas配置信息 let apmInfo = yield apm.updateSaas(req.body); responseData(req, res, apmInfo); }), updateServer: (req, res) => co(function*() { // 修改听云server配置信息 let apmInfo = yield apm.updateServer(req.body); responseData(req, res, apmInfo); }), dropApp: (req, res) => co(function*() { // 删除听云server配置信息 let apmInfo = yield apm.dropApp(req.body); console.log(apmInfo); responseData(req, res, apmInfo); }), dropBrowser: (req, res) => co(function*() { // 删除听云browser配置信息 let apmInfo = yield apm.dropBrowser(req.body); responseData(req, res, apmInfo); }), dropCommon: (req, res) => co(function*() { // 删除听云common配置信息 let apmInfo = yield apm.dropCommon(req.body); responseData(req, res, apmInfo); }), dropNetwork: (req, res) => co(function*() { // 删除听云network配置信息 let apmInfo = yield apm.dropNetwork(req.body); responseData(req, res, apmInfo); }), dropSaas: (req, res) => co(function*() { // 删除听云saas配置信息 let apmInfo = yield apm.dropSaas(req.body); responseData(req, res, apmInfo); }), dropServer: (req, res) => co(function*() { // 删除听云server配置信息 let apmInfo = yield apm.dropServer(req.body); responseData(req, res, apmInfo); }), };<file_sep>/controller/apm/index.js /** * Created by renminghe on 2017/2/14. */ const express = require("express"); const Router = express.Router(); let user = require("./index.controller"); //接口测试 Router.get("/", user.test); // 听云app产品线配置信息 Router.get("/app", user.app); // 听云browser产品线配置信息 Router.get("/browser", user.browser); // 听云common产品线配置信息 Router.get("/common", user.common); // 听云network产品线配置信息 Router.get("/network", user.network); // 听云saas产品线配置信息 Router.get("/saas", user.saas); // 听云server产品线配置信息 Router.get("/server", user.server); // 添加听云app产品线配置信息 Router.post("/creatApp", user.creatApp); // 添加听云browser产品线配置信息 Router.post("/creatBrowser", user.creatBrowser); // 添加听云common产品线配置信息 Router.post("/creatCommon", user.creatCommon); // 添加听云network产品线配置信息 Router.post("/creatNetwork", user.creatNetwork); // 添加听云saas产品线配置信息 Router.post("/creatSaas", user.creatSaas); // 添加听云server产品线配置信息 Router.post("/creatServer", user.creatServer); // 更新听云app产品线配置信息 Router.post("/updateApp", user.updateApp); // 更新听云browser产品线配置信息 Router.post("/updateBrowser", user.updateBrowser); // 更新听云common产品线配置信息 Router.post("/updateCommon", user.updateCommon); // 更新听云network产品线配置信息 Router.post("/updateNetwork", user.updateNetwork); // 更新听云saas产品线配置信息 Router.post("/updateSaas", user.updateSaas); // 更新听云server产品线配置信息 Router.post("/updateServer", user.updateServer); // 删除听云app产品线配置信息 Router.post("/dropApp", user.dropApp); // 删除听云browser产品线配置信息 Router.post("/dropBrowser", user.dropBrowser); // 删除听云common产品线配置信息 Router.post("/dropCommon", user.dropCommon); // 删除听云network产品线配置信息 Router.post("/dropNetwork", user.dropNetwork); // 删除听云saas产品线配置信息 Router.post("/dropSaas", user.dropSaas); // 删除听云server产品线配置信息 Router.post("/dropServer", user.dropServer); module.exports = Router;<file_sep>/model/apm_model/index.js /** * Created by renminghe on 2017/2/14. */ let Sequelize = require("../../config/sequelize"); let sequelize = require("sequelize"); // 根选择不同数据表 function selectTable(table) { let User = Sequelize.define(table, { id:{ //自增id 主键 int type: sequelize.INTEGER, primaryKey: true }, name: sequelize.STRING, // 项目名称 string product_line: sequelize.STRING, // 所属产品线 string port: sequelize.INTEGER, // 端口 int use_path: sequelize.STRING, // 应用路径 string config_path: sequelize.STRING, // 配置路径 string admin: sequelize.STRING, // 管理者 string depend_env: sequelize.STRING, // 依赖环境 string create_time: sequelize.STRING, //创建时间 默认当前时间 string }, { freezeTableName: true, // Model 对应的表名将与model名相同 timestamps: false }); return User; } // 获取数据库数据方法 function selectNameById (arg, name) { let user = selectTable(name); if (arg) { return user.findOne({where:{name:arg}}).then((data) => { if (!data) { return {status:500}; } return data; }).catch(function(err){ throw err; }); } else { return user.findAll({limit: 5}).then((data) => { if (!data) { return {status:500}; } return data; }).catch(function(err){ throw err; }); } } // 插入数据库数据方法 function creatData (arg, name) { let user = selectTable(name); if (arg) { return user.create({name:arg.productName, product_line:arg.productLineTitle, port:arg.productPort, use_path:arg.productUsePath, config_path:arg.productConfigPath, admin:arg.productAdmin, depend_env: arg.productDependEvn}).then((data) => { if (!data) { return {status:500}; } return data; }).catch(function(err){ throw err; }); } } // 更新数据库数据方法 function upData(arg, name) { let user = selectTable(name); if (arg) { return user.update({name:arg.productName, port:arg.productPort, use_path:arg.productUsePath, config_path:arg.productConfigPath, admin:arg.productAdmin, depend_env: arg.productDependEvn},{where:{name:arg.proName}}).then((data) => { if (!data) { return {status:500}; } return data; }).catch(function(err){ throw err; }); } } // 删除数据库数据方法 function dropData(arg, name) { let user = selectTable(name); if (arg) { return user.destroy({where:{name:arg.name}}).then((data) => { if (!data) { return {status:500}; } return data; }).catch(function(err){ throw err; }); } } module.exports = { // 听云app配置信息 app: (proName) => selectNameById(proName, "apm_app"), // 听云browser配置信息 browser: () => selectNameById("", "apm_browser"), // 听云common配置信息 common: () => selectNameById("", "apm_common"), // 听云network配置信息 network: () => selectNameById("", "apm_network"), // 听云saas配置信息 saas: () => selectNameById("", "apm_saas"), // 听云server配置信息 server: () => selectNameById("", "apm_server"), // 创建听云app配置信息 creatApp: (arg) => creatData(arg, "apm_app"), // 创建听云browser配置信息 creatBrowser: (arg) => creatData(arg, "apm_browser"), // 创建听云common配置信息 creatCommon: (arg) => creatData(arg, "apm_common"), // 创建听云network配置信息 creatNetwork: (arg) => creatData(arg, "apm_network"), // 创建听云saas配置信息 creatSaas: (arg) => creatData(arg, "apm_saas"), // 创建听云server配置信息 creatServer: (arg) => creatData(arg, "apm_server"), // 修改听云app配置信息 updateApp: (arg) => upData(arg, "apm_app"), // 修改听云browser配置信息 updateBrowser: (arg) => upData(arg, "apm_browser"), // 修改听云common配置信息 updateCommon: (arg) => upData(arg, "apm_common"), // 修改听云network配置信息 updateNetwork: (arg) => upData(arg, "apm_network"), // 修改听云saas配置信息 updateSaas: (arg) => upData(arg, "apm_saas"), // 修改听云server配置信息 updateServer: (arg) => upData(arg, "apm_server"), // 删除听云app配置信息 dropApp: (arg) => dropData(arg, "apm_app"), // 删除听云browser配置信息 dropBrowser: (arg) => dropData(arg, "apm_browser"), // 删除听云common配置信息 dropCommon: (arg) => dropData(arg, "apm_common"), // 删除听云network配置信息 dropNetwork: (arg) => dropData(arg, "apm_network"), // 删除听云saas配置信息 dropSaas: (arg) => dropData(arg, "apm_saas"), // 删除听云server配置信息 dropServer: (arg) => dropData(arg, "apm_server"), };
9a3e3e76fbd8e5633f433ea3f037d3e3544be1f4
[ "JavaScript" ]
5
JavaScript
YOMAMH/ty_cmdb_server
ba8017b8dfd2a7dd101c533d9c273a3bbc7afd8c
e733beaf1ea9df582b46ecf0ed1f13e59d2f5499
refs/heads/main
<repo_name>rd9911/rock-scissor-paper<file_sep>/features__.js let playerScore = 0; let computerScore = 0; const playerScoreDOM = document.querySelector('.player'); const computerScoreDOM = document.querySelector('.computer'); // computer will choose one of ['Rock', 'Scissors', 'Paper'] function computerPlay() { let choices = ['Rock', 'Scissors', 'Paper']; let index = Math.floor(Math.random() * choices.length); return choices[index] } // function that compares computer and player's choice and determine the winner of the round. function game(playerSelection, computerSelection = computerPlay()) { if (playerSelection === computerSelection) { console.log('Draw'); } else if ((playerSelection === 'Rock') && (computerSelection === 'Paper')) { computerScore++; computerScoreDOM.textContent = computerScore; console.log('Computer wins! Paper beats Rock.'); } else if ((playerSelection === 'Rock') && (computerSelection === 'Scissors')) { playerScore++; playerScoreDOM.textContent = playerScore; console.log('You win! Rock beats Scissors.'); } else if ((playerSelection === 'Scissors') && (computerSelection === 'Paper')) { playerScore++; playerScoreDOM.textContent = playerScore; console.log('You win! Scissors beat Paper.'); } else if ((playerSelection === 'Scissors') && (computerSelection === 'Rock')) { computerScore++; computerScoreDOM.textContent = computerScore; console.log('Computer wins! Rock beats Scissors.'); } else if ((playerSelection === 'Paper') && (computerSelection === 'Scissors')) { computerScore++; computerScoreDOM.textContent = computerScore; console.log('Computer wins! Scissors beat Paper.'); } else if ((playerSelection === 'Paper') && (computerSelection === 'Rock')) { playerScore++; playerScoreDOM.textContent = playerScore; console.log('You win! Paper beats Rock.'); } } // main function that will run the code for 5 times and determine the winner. function main(input) { const body = document.querySelector('body'); const divResult = document.createElement('div'); // result announcment const announcment = document.createElement('h3'); game(input); if (playerScore === 5) { announcment.textContent = 'You are a winner! Congratulations!!!'; } else if (computerScore === 5) { announcment.textContent = 'Computer is a winner! Computers are power!!!'; } divResult.appendChild(announcment); body.appendChild(divResult); } const btns = document.querySelectorAll('button'); btns.forEach((btn) => btn.addEventListener('click', () => { main(btn.textContent) })) <file_sep>/README.md Rock Scissor Paper game written in JavaScript
b7f0eaf36226ba74308fff759c6192c3872c1117
[ "JavaScript", "Markdown" ]
2
JavaScript
rd9911/rock-scissor-paper
9c65d6eb51e2b5286be9b515c4705623521c38b8
e3097cb3c879384190a09f2e921059f0364802d6
refs/heads/master
<repo_name>rosenrose/gimp-make_OCR_easy<file_sep>/make-ocr-easy.py #! /usr/bin/env python from gimpfu import * import os def is_over_limit(val,axis,limit): return val < limit[axis][0] or val > limit[axis][1] def get_adjacent(region,pos,direction,limit): x,y = pos offsetX,offsetY = direction if offsetX == 0: if is_over_limit(y+offsetY,'y',limit): a1,a2,a3 = '\x00','\x00','\x00' else: if is_over_limit(x+offsetY,'x',limit): a1 = '\x00' else: a1 = region[x+offsetY,y+offsetY] if is_over_limit(x+offsetY*-1,'x',limit): a3 = '\x00' else: a3 = region[x+offsetY*-1,y+offsetY] a2 = region[x,y+offsetY] elif offsetY == 0: if is_over_limit(x+offsetX,'x',limit): a1,a2,a3 = '\x00','\x00','\x00' else: if is_over_limit(y+offsetX*-1,'y',limit): a1 = '\x00' else: a1 = region[x+offsetX,y+offsetX*-1] if is_over_limit(y+offsetX,'y',limit): a3 = '\x00' else: a3 = region[x+offsetX,y+offsetX] a2 = region[x+offsetX,y] return a1,a2,a3 def turn(direction,rotate): # rotate meaning: -1 left, 1 right if direction[0] == 0: return direction[1]*rotate*-1, 0 elif direction[1] == 0: return 0, direction[0]*rotate def move(pos,direction): return pos[0]+direction[0],pos[1]+direction[1] def contour_add(contour,pos): contour['poses'].add(pos) x,y = pos if contour['x1'] >= x: contour['x1'] = x if contour['x2'] <= x: contour['x2'] = x if contour['y1'] >= y: contour['y1'] = y if contour['y2'] <= y: contour['y2'] = y return contour # Theo Pavlidis' Algorithm # http://www.imageprocessingplace.com/downloads_V3/root_downloads/tutorials/contour_tracing_Abeer_George_Ghuneim/theo.html def Theo_Pavlidis_algorithm(region,start): debug = False limit = {'x': [region.x, region.x+region.w-1], 'y': [region.y, region.y+region.h-1]} contour = {'poses': set(), 'x1': limit['x'][1], 'x2': limit['x'][0], 'y1': limit['y'][1], 'y2': limit['y'][0]} pos = start initDirection = 0,-1 # meaning upward direction = initDirection contour = contour_add(contour,pos) step = 1 while True: if step == 1: a1,a2,a3 = get_adjacent(region,pos,direction,limit) if debug: pdb.gimp_message((pos,direction,(a1,a2,a3))) if a1 != '\x00': if step == 1: # To check break condition efficiently, take only 1 step for each iteration pos = move(pos,direction) elif step == 2: direction = turn(direction,-1) elif step == 3: pos = move(pos,direction) contour = contour_add(contour,pos) step = 0 step+=1 elif a2 != '\x00': pos = move(pos,direction) contour = contour_add(contour,pos) elif a3 != '\x00': if step == 1: direction = turn(direction,1) elif step == 2: pos = move(pos,direction) elif step == 3: direction = turn(direction,-1) elif step == 4: pos = move(pos,direction) contour = contour_add(contour,pos) step = 0 step+=1 else: direction = turn(direction,1) if pos == start and direction == initDirection: break return contour def search(region): debug = False contourList = [] checkList = set() for i in range(region.x, region.x+region.w, 70): # Lower the steps, more small areas can be catched. But increases execution time. for j in range(region.y, region.y+region.h, 100): if region[i,j] != '\x00': leftNearest = i while leftNearest > region.x and region[leftNearest-1,j] != '\x00': leftNearest-=1 if (leftNearest,j) in checkList: continue if debug: pdb.gimp_message((leftNearest,j)) contour = Theo_Pavlidis_algorithm(region,(leftNearest,j)) contourList.append(contour) checkList |= contour['poses'] return contourList def make_ocr_easy(*args): for image in gimp.image_list(): path,name = os.path.split(image.filename.decode("utf-8")) name = "text_"+os.path.splitext(name)[0]+".png" drawable = image.layers[-1] pdb.gimp_selection_flood(image) pdb.gimp_edit_copy(drawable) pdb.gimp_floating_sel_to_layer(pdb.gimp_edit_paste(drawable, True)) pdb.gimp_selection_grow(image, 1) selection = pdb.gimp_image_get_selection(image) non_empty, x1, y1, x2, y2 = pdb.gimp_selection_bounds(image) region = selection.get_pixel_rgn(x1,y1,x2-x1+1,y2-y1+1) contourList = search(region) for contour in contourList: pdb.gimp_image_select_rectangle(image, 0, contour['x1'], contour['y1'], contour['x2']-contour['x1'], contour['y2']-contour['y1']) pdb.gimp_drawable_edit_fill(drawable, 2) pdb.gimp_selection_none(image) pdb.gimp_drawable_update(drawable, x1, y1, x2-x1, y2-y1) pdb.file_png_save_defaults(image, pdb.gimp_image_merge_visible_layers(image, 1), os.path.join(path,name), os.path.join(path,name)) register( "python_fu_make-ocr-easy", "", "", "", "", "", "<Image>/Tools/Make OCR easy", "RGB*, GRAY*", [], [], make_ocr_easy ) main() <file_sep>/README.md # gimp-make_OCR_easy Fills out rectangular area surrounding speech lines. Which makes it easier drawing text recognition area for OCR software. Usage: Click each bubbles with Fuzzy Select Tool. Then run the script. Notice: It will take time within 10 seconds for each image. &nbsp; Bad example: &nbsp; ![bad](https://raw.githubusercontent.com/rosenrose/gimp-cutSpeechBubble/master/pic1.png) &nbsp; Good example after processing: &nbsp; ![good](https://raw.githubusercontent.com/rosenrose/gimp-cutSpeechBubble/master/pic2.png)
9b8bba0a38e0e9eae446f5293dbaa1f802f3082c
[ "Markdown", "Python" ]
2
Python
rosenrose/gimp-make_OCR_easy
2538c54600fc2c4bc23e20e351b72cd1012551a8
5ad3c3a0f89e23f47f50fc914690dccf757c23e0
refs/heads/master
<repo_name>boyebn/SimpleAspBlog<file_sep>/Controllers/PostsController.cs using Microsoft.AspNet.Mvc; using SimpleAspBlog.Models; using System.Collections.Generic; namespace SimpleAspBlog.Controllers { [Route("api/[Controller]")] public class PostsController:Controller { [FromServices] public IPostRepository posts { get; set; } [HttpGet] public IEnumerable<Post> getAll() { return posts.getAll(); } [HttpGet("{id}", Name="GetPost")] public IActionResult get(string id) { var post = posts.get(id); if (post == null) { return HttpNotFound(); } return new ObjectResult(post); } [HttpPost] public IActionResult add([FromBody] Post post) { if (post == null) { return HttpBadRequest(); } posts.add(post); return CreatedAtRoute("GetPost", new {controller = "Post", id = post._id}, post); } [HttpPut("{id}")] public IActionResult update(string id, [FromBody] Post post) { if (post == null || id != post._id) { return HttpBadRequest(); } if (posts.get(id) == null) { return HttpNotFound(); } posts.update(post); return new NoContentResult(); } [HttpDelete("{id}")] public void remove(string id) { posts.delete(id); } } } <file_sep>/Models/IPostRepository.cs using System.Collections.Generic; namespace SimpleAspBlog.Models { public interface IPostRepository { void add(Post post); void delete(string id); IEnumerable<Post> getAll(); Post get(string id); void update(Post post); } }<file_sep>/Models/Post.cs using System.ComponentModel.DataAnnotations; namespace SimpleAspBlog.Models { public class Post { [KeyAttribute] public string _id { set; get; } [RequiredAttribute] public string _title { set; get; } public string _content { set; get; } } }<file_sep>/Models/PostRepository.cs using System; using System.Linq; using System.Collections.Generic; namespace SimpleAspBlog.Models { public class PostRepository : IPostRepository { private readonly SimpleAspBlogContext _dbContext; public PostRepository(SimpleAspBlogContext dbContext) { _dbContext = dbContext; } public void add(Post post) { post._id = Guid.NewGuid().ToString(); _dbContext.Posts.Add(post); _dbContext.SaveChanges(); } public void delete(string id) { Post post = _dbContext.Posts.FirstOrDefault(p => p._id == id); _dbContext.Posts.Remove(post); _dbContext.SaveChanges(); } public Post get(string id) { Post post = _dbContext.Posts.FirstOrDefault(p => p._id == id); return post; } public IEnumerable<Post> getAll() { return _dbContext.Posts; } public void update(Post post) { Post original = _dbContext.Posts.FirstOrDefault(p => p._id == post._id); if (original != null) { original._title = post._title; original._content = post._content; _dbContext.SaveChanges(); } } } }<file_sep>/Models/SimpleAspBlogContext.cs using Microsoft.Data.Entity; namespace SimpleAspBlog.Models { public class SimpleAspBlogContext : DbContext { public DbSet<Post> Posts { get; set; } protected override void OnModelCreating(ModelBuilder builder) { builder.Entity<Post>().HasKey(b => b._id); base.OnModelCreating(builder); } } }
9f7641ad0ba516fba64b533ae14255e8bb94a23e
[ "C#" ]
5
C#
boyebn/SimpleAspBlog
b35234a15df26b2caeb9d104951e9a72422b3c46
06783244bd7d81be72e8925315d5b3fa951f8ad4
refs/heads/master
<file_sep>extern crate libc; use std::collections::BTreeMap; use std::ffi::{CStr, CString}; use std::mem::transmute; #[no_mangle] pub extern fn hello_world() { println!("hello Rust—Python simple FFI world"); } #[no_mangle] pub extern fn sorted_string_counter() -> *mut BTreeMap<String, i64> { let our_counter = unsafe { transmute(Box::new(BTreeMap::<String, i64>::new())) }; our_counter } #[no_mangle] pub extern fn increment(counter: *mut BTreeMap<String, i64>, key: *const libc::c_char) { let our_counter = unsafe { &mut *counter }; let buffer = unsafe { CStr::from_ptr(key).to_bytes() }; let string = String::from_utf8(buffer.to_vec()).unwrap(); *our_counter.entry(string).or_insert(0) += 1; } #[no_mangle] pub extern fn get(counter: *mut BTreeMap<String, i64>, key: *const libc::c_char) -> i64 { let our_counter = unsafe { &mut *counter }; let buffer = unsafe { CStr::from_ptr(key).to_bytes() }; let string = String::from_utf8(buffer.to_vec()).unwrap(); *our_counter.get(&string).unwrap_or(&0) } #[no_mangle] pub extern fn represent(counter: *mut BTreeMap<String, i64>) -> *const libc::c_char { let our_counter = unsafe { &mut *counter }; CString::new(format!("{:?}", our_counter).as_bytes()).unwrap().into_raw() } #[no_mangle] pub extern fn display(counter: *mut BTreeMap<String, i64>) { let our_counter = unsafe { &mut *counter }; println!("{:?}", our_counter); } #[cfg(test)] mod tests { use std::collections::BTreeMap; #[test] fn concerning_whether_btreemap_behaves_like_one_would_expect() { let mut my_treemap = BTreeMap::<String, i64>::new(); my_treemap.insert("foo".to_owned(), 1); assert_eq!(my_treemap.get(&"foo".to_owned()), Some(&1i64)); } } <file_sep>from .sorted_string_counter import SortedStringCounter <file_sep>What happens if I try to expose Rust's collections types in Python? ``` $ python3 Python 3.4.3 (default, Oct 14 2015, 20:28:29) [GCC 4.8.4] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from pyrst_collections import SortedStringCounter hello Rust—Python simple FFI world >>> c = SortedStringCounter() >>> for count, item in enumerate(("foo", "bar", "quux", "rah"), start=1): ... for _ in range(count): ... c.increment(item) ... >>> c SortedStringCounter({"bar": 2, "foo": 1, "quux": 3, "rah": 4}) ``` "pyrst" is pronounced like "pierced." ## Bibliography * [the book](http://doc.rust-lang.org/book/ffi.html) * [<NAME>](http://siciarz.net/24-days-of-rust-calling-rust-from-other-languages/) * [<NAME>](http://oppenlander.me/articles/rust-ffi) * [<NAME>](http://siciarz.net/24-days-of-rust-calling-rust-from-other-languages/) <file_sep>[package] name = "pyrst_collections" version = "0.0.1" authors = ["<NAME> <<EMAIL>>"] [lib] name = "pyrst_collections" crate-type = ["dylib"] [dependencies] libc = "0.2" <file_sep>import ctypes from ctypes import c_char_p, c_void_p libpyrst = ctypes.CDLL("./underworld/target/debug/libpyrst_collections.so") libpyrst.hello_world() libpyrst.increment.argtypes = (c_void_p, c_char_p) libpyrst.represent.restype = c_char_p class SortedStringCounter: def __init__(self): self._counter = libpyrst.sorted_string_counter() def increment(self, key): libpyrst.increment(self._counter, key.encode()) def __getitem__(self, key): return libpyrst.get(self._counter, key.encode()) def __repr__(self): return "SortedStringCounter({})".format( libpyrst.represent(self._counter).decode() )
a9e64b862d3a3c13df4a9ea15845302066068483
[ "Markdown", "Rust", "Python", "TOML" ]
5
Rust
zackmdavis/pyrst_collections
f58daba100dfb64931ba11ab03ebd7deaad1155a
442fc914a36a480d93e203f1637303be724a9fec
refs/heads/master
<file_sep>from SEAPODYM_PARCELS import * if __name__ == "__main__": p = ArgumentParser(description=""" Example of underlying habitat field""") p.add_argument('mode', choices=('scipy', 'jit'), nargs='?', default='scipy', help='Execution mode for performing RK4 computation') p.add_argument('-p', '--particles', type=int, default=10, help='Number of particles to advect') p.add_argument('-t', '--time', type=int, default=30, help='List of dimensions across which field variables occur, as given in the NetCDF files, to map to the --dimensions args') p.add_argument('-o', '--output', default='SIMPODYM_test_2003', help='List of NetCDF files to load') p.add_argument('-ts', '--timestep', type=int, default=172800, help='Length of timestep in seconds, defaults to two days') args = p.parse_args() dimensions = ['lat', 'lon', 'time'] netcdf_vars = ['u', 'v', 'habitat'] SIMPODYM(forcingU='SEAPODYM_Forcing_Data/SEAPODYM2003_PHYS_Prepped.nc', forcingV='SEAPODYM_Forcing_Data/SEAPODYM2003_PHYS_Prepped.nc', forcingH='SEAPODYM_Forcing_Data/SEAPODYM2003_HABITAT_Prepped.nc', startD='SEAPODYM_Forcing_Data/SEAPODYM2003_DENSITY_Prepped.nc', Uname=netcdf_vars[0], Vname=netcdf_vars[1], Hname=netcdf_vars[2], dimLat=dimensions[0], dimLon=dimensions[1], dimTime=dimensions[2], individuals=args.particles, timestep=args.timestep, time=args.time, mode=args.mode, output_file=args.output) <file_sep>from parcels import * from SEAPODYM_functions import * from netCDF4 import Dataset import matplotlib.pyplot as plt if __name__ == "__main__": forcingU = 'SEAPODYM_Forcing_Data/PHYSICAL/2003Cohort_PHYS_month1.nc' forcingV = 'SEAPODYM_Forcing_Data/PHYSICAL/2003Cohort_PHYS_month1.nc' forcingH = 'SEAPODYM_Forcing_Data/HABITAT/2003Cohort_HABITAT_month59.nc' filenames = {'U': forcingU, 'V': forcingV, 'H': forcingH} variables = {'U': 'u', 'V': 'v', 'H': 'habitat'} dimensions = {'lon': 'lon', 'lat': 'lat', 'time': 'time'} print("Creating Grid") grid = Grid.from_netcdf(filenames=filenames, variables=variables, dimensions=dimensions, vmax=200) #print("Creating Diffusion Field") #K = Create_SEAPODYM_Diffusion_Field(grid.H, 30*24*60*60) #grid.add_field(K) print("Creating Diffusion Field with SEAPODYM units") S_K = Create_SEAPODYM_Diffusion_Field(grid.H, 30*24*60*60, units='nm2_per_mon', P=3, start_age=62) S_K.name = 'S_K' grid.add_field(S_K) grid.write('SEAPODYM_Grid_Comparison') print("Loading Diffusion Field") bfile = Dataset('DIFFUSION_last_cohort/last_cohort_diffusion.nc', 'r') bX = bfile.variables['longitude'] bY = bfile.variables['latitude'] bT = bfile.variables['time'] bVar = bfile.variables['skipjack_diffusion_rate'] hfile = Dataset('SEAPODYM_Forcing_Data/SEAPODYM2003_HABITAT_Prepped.nc') hX = hfile.variables['lon'] hY = hfile.variables['lat'] hT = hfile.variables['time'] hVar = hfile.variables['habitat'] #I_K = Field.from_netcdf('I_K', {'lon':'longitude', 'lat':'latitude', 'time':'time'}, # ['DIFFUSION/INTERIM-NEMO-PISCES_skipjack_diffusion_rate_20030115.nc', # 'DIFFUSION/INTERIM-NEMO-PISCES_skipjack_diffusion_rate_20030215.nc']) I_K = Field('I_K', data=bVar, lon=bX, lat=bY, time=bT, transpose=True) grid.add_field(I_K) comparison = np.zeros(np.shape(I_K.data), dtype=np.float32) loaded = np.array(bVar) comparison = abs(S_K.data-loaded) print(np.min(comparison)) print(np.max(comparison)) fig = plt.figure(1) ax = plt.axes() plt.contourf(bX[:], bY[:], bVar[59, :, :], vmin=0, vmax=80000) plt.title("Inna's K (final timestep)") plt.colorbar() fig = plt.figure(2) ax = plt.axes() plt.contourf(bX[:], bY[:], S_K.data[59, :, :], vmin=0, vmax=80000) plt.title("Calculated K (final timestep)") plt.colorbar() fig = plt.figure(3) ax = plt.axes() plt.contourf(bX[:], bY[:], comparison[59, :, :], vmax=10000) plt.show() print(np.shape(hVar)) print(np.shape(bVar)) #example habitat to diffusion calculations x = [147, 110, 68, 120] y = [85, 64, 44, 60] for i in range(len(x)): print("Final timestep H at %s-%s = %s" % (grid.H.lon[x[i]], grid.H.lat[y[i]], grid.H.data[59, y[i], x[i]])) print("Final timestep K at %s-%s = %s" % (grid.S_K.lon[x[i]], grid.S_K.lat[y[i]], grid.S_K.data[59, y[i], x[i]])) print("Final timestep H file at %s-%s = %s" % (hX[x[i]], hY[y[i]], hVar[59, :, y[i], x[i]])) print("Final timestep Inna K at %s-%s = %s" % (bX[x[i]], bY[y[i]], bVar[59, y[i], x[i]])) #grid.write('FieldTest')<file_sep>from argparse import ArgumentParser from SEAPODYM_PARCELS import * if __name__ == "__main__": p = ArgumentParser(description=""" Arguments for parameterising a series of SIMPODYM runs""") p.add_argument('-f', '--parameter_file', type=str, default='SIMPODYM_Parameters.txt', help='file path of parameter text file') args = p.parse_args() list = ['output', 'mode', 'reps', 'individuals', 'timestep', 'time ', 'start_age', 'Ufile', 'Vfile', 'Hfile', 'dHdx_file', 'dHdy_file', 'Uvar_name', 'Vvar_name', 'Hvar_name', 'londim_name', 'latdim_name', 'timedim_name', 'starting_density_file', 'density_var_name', 'calculate_density', 'write_density', 'write_grid', 'Kfile', 'dKdx_file', 'dKdy_file', 'diffusion_boost', 'diffusion_scale', 'taxis_scale'] plist = {} for p in list: plist.update({p: None}) #f = open(args.parameter_file,'r') for line in open(args.parameter_file, 'r'): for p in plist: if p in line: plist[p] = line.split()[-1] print(plist['diffusion_scale']) # Set defaults for key params of import if plist['mode'] is None: plist['mode'] = 'jit' if plist['reps'] is None: plist['reps'] = 1 if plist['individuals'] is None: plist['individuals'] = '100' if plist['time '] is None: plist['time'] = 30 if plist['timestep'] is None: plist['timestep'] = 172800 if plist['start_age'] is None: plist['start_age'] = 4 if plist['write_grid'] is None: plist['write_grid'] = False if plist['diffusion_boost'] is None: plist['diffusion_boost'] = 0 if plist['diffusion_scale'] is None: plist['diffusion_scale'] = 1 if plist['taxis_scale'] is None: plist['taxis_scale'] = 1 # Check that key params exist key_params = ['Ufile', 'Vfile', 'Hfile', 'Uvar_name', 'Vvar_name', 'Hvar_name', 'londim_name', 'latdim_name', 'timedim_name', 'output'] for p in key_params: if plist[p] is None: print("No defined %s!" % p) sys.exit() print("Parameters for simulations") for p in plist.keys(): print("%s = %s" % (p, plist[p])) print('Beginning Simulations') plist['reps'] = int(plist['reps']) for rep in range(plist['reps']): if plist['reps'] > 1: outputname = plist['output']+str(rep) else: outputname = plist['output'] SIMPODYM(forcingU=plist['Ufile'], forcingV=plist['Vfile'], forcingH=plist['Hfile'], startD=plist['starting_density_file'], Dname=plist['density_var_name'], output_density=plist['write_density'], Uname=plist['Uvar_name'], Vname=plist['Vvar_name'], Hname=plist['Hvar_name'], dimLon=plist['londim_name'], dimLat=plist['latdim_name'], dimTime=plist['timedim_name'], Kfile=plist['Kfile'], dK_dxfile=plist['dKdx_file'], dK_dyfile=plist['dKdy_file'], diffusion_boost=float(plist['diffusion_boost']), diffusion_scale=float(plist['diffusion_scale']), taxis_scale=float(plist['taxis_scale']), dH_dxfile=plist['dHdx_file'], dH_dyfile=plist['dHdy_file'], individuals=int(plist['individuals']), timestep=float(plist['timestep']), time=int(float(plist['time '])), start_age=float(plist['start_age']), output_file=outputname, mode=plist['mode'], write_grid=plist['write_grid']) <file_sep>from parcels import * from Behaviour import * import numpy as np from SEAPODYM_functions import * from SEAPODYM_PARCELS import * from argparse import ArgumentParser def TagRelease(grid, location=[0, 0], spread = 0, individuals=100, start=None, timestep=86400, time=30, output_file='TagRelease', mode='scipy', start_age=4): ParticleClass = JITParticle if mode == 'jit' else ScipyParticle SKJ = Create_TaggedFish_Class(ParticleClass) lats = [] lons = [] for _ in range(individuals): lats.append(location[1] + np.random.uniform(spread*-1, spread)) lons.append(location[0] + np.random.uniform(spread*-1, spread)) fishset = grid.ParticleSet(size=individuals, pclass=SKJ, lon=lons, lat=lats) age = fishset.Kernel(AgeIndividual) diffuse = fishset.Kernel(LagrangianDiffusion) advect = fishset.Kernel(Advection_C) taxis = fishset.Kernel(GradientRK4_C) move = fishset.Kernel(Move) checkrelease = fishset.Kernel(CheckRelease) starttime = 0 if start is None else start for p in fishset.particles: p.setAge(start_age) p.release_time = grid.time[0] + starttime #p.active.to_write = True grid.write(output_file) print("Starting Sim") fishset.execute(checkrelease + age + taxis + advect + diffuse + move, starttime=grid.time[0], endtime=grid.time[0]+time*timestep, dt=timestep, output_file=fishset.ParticleFile(name=output_file+"_results"), interval=timestep)#, density_field=density_field) if __name__ == "__main__": p = ArgumentParser(description=""" Example of underlying habitat field""") p.add_argument('mode', choices=('scipy', 'jit'), nargs='?', default='scipy', help='Execution mode for performing RK4 computation') p.add_argument('-p', '--particles', type=int, default=10, help='Number of particles to advect') p.add_argument('--profiling', action='store_true', default=False, help='Print profiling information after run') p.add_argument('-g', '--grid', type=int, default=None, help='Generate grid file with given dimensions') p.add_argument('-f', '--files', default=['SEAPODYM_Forcing_Data/SEAPODYM2003_PHYS_Prepped.nc', 'SEAPODYM_Forcing_Data/SEAPODYM2003_PHYS_Prepped.nc', 'SEAPODYM_Forcing_Data/SEAPODYM2003_HABITAT_Prepped.nc'], help='List of NetCDF files to load') p.add_argument('-v', '--variables', default=['U', 'V', 'H'], help='List of field variables to extract, using PARCELS naming convention') p.add_argument('-n', '--netcdf_vars', default=['u', 'v', 'habitat'], help='List of field variable names, as given in the NetCDF file. Order must match --variables args') p.add_argument('-d', '--dimensions', default=['lat', 'lon', 'time'], help='List of PARCELS convention named dimensions across which field variables occur') p.add_argument('-m', '--map_dimensions', default=['lat', 'lon', 'time'], help='List of dimensions across which field variables occur, as given in the NetCDF files, to map to the --dimensions args') p.add_argument('-t', '--time', type=int, default=15, help='List of dimensions across which field variables occur, as given in the NetCDF files, to map to the --dimensions args') p.add_argument('-o', '--output', default='TagRelease', help='List of NetCDF files to load') p.add_argument('-ts', '--timestep', type=int, default=86400, help='Length of timestep in seconds, defaults to one day') p.add_argument('-l', '--location', type=float, nargs=2, default=[180,0], help='Release location (lon,lat)') p.add_argument('-a', '--age', type=int, default=4, help='Starting age of fish at beginning of sim') p.add_argument('-c', '--cluster', type=float, default = 0.1, help='+- spatial range around release location (uniformly distributed, in degrees lat/lon)') p.add_argument('-s', '--start', type=float, default = 4, help='age in months when fish are released') p.add_argument('-ds', '--diffusion_scale', type=float, default = 4, help='scaler for diffusion') args = p.parse_args() filename = args.output U = args.files[0] V = args.files[1] H = args.files[2] grid = Create_SEAPODYM_Grid(forcingU=U, forcingV=V, forcingH=H, Uname=args.netcdf_vars[0], Vname=args.netcdf_vars[1], Hname=args.netcdf_vars[2], dimLat=args.dimensions[0], dimLon=args.dimensions[1], dimTime=args.dimensions[2], start_age=11, diffusion_scale=args.diffusion_scale) print("Calculating H Gradient Fields") gradients = grid.H.gradient() for field in gradients: grid.add_field(field) print("Calculating K Gradient Fields") K_gradients = grid.K.gradient() for field in K_gradients: grid.add_field(field) # The time in seconds from the start grid time when fish will become active (SIMPLEDYM grids start at age 4 months) start_time = (args.start - 4) * 30 * 24 * 60 * 60 TagRelease(grid, location=args.location, spread=args.cluster, individuals=args.particles, start_age=args.age, timestep=args.timestep, time=args.time, output_file=args.output, mode=args.mode, start=start_time) <file_sep>from SEAPODYM_functions import * import numpy as np if __name__ == "__main__": data = Field_from_DYM('sim_4Joe/2003-2007/skj_diffusion.dym', name='V', fromyear=2003, frommonth=1, toyear=2005, tomonth=5) print(data.data) data.write('dymtest')<file_sep>from parcels import * from Behaviour import * import numpy as np from SEAPODYM_functions import * from argparse import ArgumentParser def FADRelease(grid, location=[0, 0], individuals=100, start=None, timestep=21600, time=30, output_file='FADRelease', mode='scipy'): ParticleClass = JITParticle if mode == 'jit' else Particle fadset = grid.ParticleSet(size=individuals, pclass=ParticleClass, start=[location[0]-0.5, location[1]-0.5], finish=[location[0]+0.5, location[1]+0.5]) starttime = grid.time[0] if start is None else start print("Starting Sim") fadset.execute(AdvectionRK4, starttime=starttime, endtime=starttime+time*timestep, dt=timestep, output_file=fadset.ParticleFile(name=output_file+"_results"), interval=timestep)#, density_field=density_field) if __name__ == "__main__": p = ArgumentParser(description=""" Example of underlying habitat field""") p.add_argument('mode', choices=('scipy', 'jit'), nargs='?', default='scipy', help='Execution mode for performing RK4 computation') p.add_argument('-p', '--particles', type=int, default=10, help='Number of particles to advect') p.add_argument('--profiling', action='store_true', default=False, help='Print profiling information after run') p.add_argument('-g', '--grid', type=int, default=None, help='Generate grid file with given dimensions') p.add_argument('-f', '--files', default=['/short/e14/jsp561/OFAM/ocean_u_1993_01.TropPac.nc', '/short/e14/jsp561/OFAM/ocean_v_1993_01.TropPac.nc', '/short/e14/jsp561/OFAM/ocean_phy_1993_01.nc'], help='List of NetCDF files to load') p.add_argument('-v', '--variables', default=['U', 'V', 'H'], help='List of field variables to extract, using PARCELS naming convention') p.add_argument('-n', '--netcdf_vars', default=['u', 'v', 'phy'], help='List of field variable names, as given in the NetCDF file. Order must match --variables args') p.add_argument('-d', '--dimensions', default=['lat', 'lon', 'time'], help='List of PARCELS convention named dimensions across which field variables occur') p.add_argument('-m', '--map_dimensions', default=['yu_ocean', 'xu_ocean', 'Time'], help='List of dimensions across which field variables occur, as given in the NetCDF files, to map to the --dimensions args') p.add_argument('-t', '--time', type=int, default=15, help='List of dimensions across which field variables occur, as given in the NetCDF files, to map to the --dimensions args') p.add_argument('-o', '--output', default='TagRelease', help='List of NetCDF files to load') p.add_argument('-ts', '--timestep', type=int, default=86400, help='Length of timestep in seconds, defaults to one day') p.add_argument('-s', '--starttime', type=int, default=None, help='Time of tag release (seconds since 1-1-1970)') p.add_argument('-l', '--location', type=float, nargs=2, default=[180,0], help='Release location (lon,lat)') args = p.parse_args() filename = '/short/e14/jsp561/' + args.output U = args.files[0] V = args.files[1] H = args.files[2] filenames = {'U': args.files[0], 'V': args.files[1]} variables = {'U': args.netcdf_vars[0], 'V': args.netcdf_vars[1]} dimensions = {'lon': args.map_dimensions[1], 'lat': args.map_dimensions[0], 'time': args.map_dimensions[2]} grid = Grid.from_netcdf(filenames=filenames, variables=variables, dimensions=dimensions, vmin=-200, vmax=200) FADRelease(grid, location=args.location, start=args.starttime, individuals=args.particles, timestep=args.timestep, time=args.time, output_file=filename, mode=args.mode) <file_sep>from parcels import * from SEAPODYM_functions import * from Behaviour import * from glob import glob import numpy as np import math from argparse import ArgumentParser import datetime def IKAMOANA(Forcing_Files, Init_Distribution_File=None, Init_Positions=None, individuals=100, timestep=86400, T=30, density_timestep=None, Forcing_Variables={'H':'habitat'}, Forcing_Dimensions={'lon':'longitude', 'lat':'latitude', 'time':'time'}, Landmask_File=None, Kernels=['Advection_C', 'TaxisRK4', 'LagrangianDiffusion', 'Move'], mode='jit', start_age=4, starttime=1042588800, output_density=False, output_grid=False, output_trajectory=True, random_seed=None, output_filestem='IKAMOANA' ): if random_seed is None: np.random.RandomState() random_seed = np.random.get_state() else: np.random.RandomState(random_seed) ParticleClass = JITParticle if mode == 'jit' else ScipyParticle Animal = define_Animal_Class(ParticleClass) # Create the forcing fieldset grid for the simulation ocean = FieldSet.from_netcdf(filenames=Forcing_Files, variables=Forcing_Variables, dimensions=Forcing_Dimensions, vmin=-200, vmax=1e5, allow_time_extrapolation=True) print(Forcing_Files['U']) Depthdata = Field.from_netcdf('u', dimensions={'lon': 'longitude', 'lat': 'latitude', 'time': 'time', 'depth': 'depth'}, filenames=Landmask_File, allow_time_extrapolation=True) Depthdata.name = 'bathy' ocean.add_field(Depthdata) ocean.add_field(Create_Landmask(ocean)) if 'TaxisRK4' in Kernels: dHdx, dHdy = getGradient(ocean.H, ocean.LandMask) #ocean.H.gradient() ocean.add_field(dHdx) ocean.add_field(dHdy) t_fields = Create_SEAPODYM_Taxis_Fields(ocean.dH_dx, ocean.dH_dy) ocean.add_field(t_fields[0]) ocean.add_field(t_fields[1]) if 'LagrangianDiffusion' in Kernels: if not hasattr(ocean, 'dH_dx'): dHdx, dHdy = getGradient(ocean.H, ocean.LandMask) ocean.add_field(dHdx) ocean.add_field(dHdy) ocean.add_field(Create_SEAPODYM_Diffusion_Field(ocean.H, timestep=timestep)) dKdx, dKdy = getGradient(ocean.K, ocean.LandMask, False) ocean.add_field(dKdx) ocean.add_field(dKdy) if 'FishingMortality' in Kernels: ocean.add_field(Create_SEAPODYM_F_Field(ocean.E)) if output_grid: ocean.write(output_filestem) # Create the particle set for our simulated animals if Init_Positions is not None: animalset = ParticleSet.from_list(fieldset=ocean, lon=Init_Positions[0], lat=Init_Positions[1], pclass=Animal) else: animalset = ParticleSet.from_field(fieldset=ocean, start_field=ocean.start, size=individuals, pclass=Animal) for a in animalset.particles: a.age = start_age*30*24*60*60 a.monthly_age = start_age trajectory_file = ParticleFile(output_filestem + '_trajectories', animalset) if output_trajectory is True else None # Build kernels AllKernels = {'Advection_C':Advection_C, 'LagrangianDiffusion':LagrangianDiffusion, 'TaxisRK4':TaxisRK4, 'FishingMortality':FishingMortality, 'NaturalMortality':NaturalMortality, 'Move': Move, 'MoveOffLand': MoveOffLand, 'MoveWithLandCheck': MoveWithLandCheck, 'AgeAnimal':AgeAnimal} KernelList = [] KernelString = [] for k in Kernels: print("Building kernel %s" % k) KernelList.append(animalset.Kernel(AllKernels[k])) KernelString.append(id(KernelList[-1])) # Concatenate for particleset execution (using eval is very ugly, but can't work out another way right now) KernelString = sum([['KernelList[',str(i),']','+'] for i in range(len(KernelList))], [])[:-1] KernelString = ''.join(KernelString) behaviours = eval(KernelString) # Calculate an outer execution loop for particle density calculations start_time = starttime #getattr(ocean, Forcing_Variables.keys()[0]).time[0] sim_time = timestep*T if density_timestep is not None: outer_timestep = (density_timestep*timestep) % sim_time sim_steps = np.arange(start_time, start_time+sim_time+1, outer_timestep) Density_data = np.zeros((len(sim_steps)+1, len(ocean.U.lat),len(ocean.U.lon))) print(np.shape(Density_data)) Density = Field('Density', Density_data, ocean.U.lon, ocean.U.lat, time=np.append(sim_steps,start_time+sim_time+timestep)) Density.data[0,:,:] = animalset.density(field=ocean.U, particle_val='school') else: outer_timestep = sim_time sim_steps = np.arange(start_time, start_time+sim_time+1, outer_timestep) # Execute print(sim_steps) for step in sim_steps[:-1]: start = datetime.datetime.fromtimestamp(step).strftime('%Y-%m-%d %H:%M:%S') end = datetime.datetime.fromtimestamp(step+outer_timestep).strftime('%Y-%m-%d %H:%M:%S') print("Executing from %s (%s) to %s (%s), in steps of %s" % (start, step, end, step+outer_timestep, timestep)) animalset.execute(behaviours, starttime=step, endtime=step+outer_timestep, dt=timestep, output_file=trajectory_file, interval=timestep, recovery={ErrorCode.ErrorOutOfBounds: UndoMove}) if density_timestep is not None: print(np.where(sim_steps == step)[0]+1) Density.data[np.where(sim_steps == step)[0]+1,:,:] = animalset.density(field=ocean.U, particle_val='school') if density_timestep is not None: Density.write(output_filestem) def define_Animal_Class(type=JITParticle): class IKAMOANA_Animal(type): active = Variable("active", to_write=True) age = Variable('age',dtype=np.float32) monthly_age = Variable('monthly_age',dtype=np.float32) Dx = Variable('Dx', to_write=True, dtype=np.float32) Dy = Variable('Dy', to_write=True, dtype=np.float32) Cx = Variable('Cx', to_write=True, dtype=np.float32) Cy = Variable('Cy', to_write=True, dtype=np.float32) Vx = Variable('Vx', to_write=True, dtype=np.float32) Vy = Variable('Vy', to_write=True, dtype=np.float32) Ax = Variable('Ax', to_write=True, dtype=np.float32) Ay = Variable('Ay', to_write=True, dtype=np.float32) prev_lon = Variable('prev_lon', to_write=False) prev_lat = Variable('prev_lat', to_write=False) school = Variable('school', to_write=True, dtype=np.float32) depletionF = Variable('depletionF', to_write=True, dtype=np.float32) depletionN = Variable('depletionN', to_write=True, dtype=np.float32) In_Loop = Variable('In_Loop', to_write=True, dtype=np.float32) #land_trigger = Variable('land_trigger', to_write=True) def __init__(self, *args, **kwargs): """Custom initialisation function which calls the base initialisation and adds the instance variable p""" super(IKAMOANA_Animal, self).__init__(*args, **kwargs) self.Dx = self.Dy = self.Cx = self.Cy = self.Vx = self.Vy = self.Ax = self.Ay = 0. self.active = 1 self.school = 1000 return IKAMOANA_Animal if __name__ == "__main__": p = ArgumentParser(description=""" Example of underlying habitat field""") p.add_argument('mode', choices=('scipy', 'jit'), nargs='?', default='jit', help='Execution mode for performing RK4 computation') p.add_argument('-p', '--particles', type=int, default=10, help='Number of particles to advect') p.add_argument('-f', '--files', default=['SimpleTest/SimpleCurrents.nc', 'SimpleTest/SimpleCurrents.nc', 'SimpleTest/SimpleHabitat.nc', 'SimpleTest/SimpleMortality.nc'], help='List of NetCDF files to load') p.add_argument('-fs', '--filestem', default=['n', 'n', 'n', 'n'], help="Filestem options for each forcing file, defaulting to none for all") p.add_argument('-v', '--variables', default=['U','V','H','F'], help='List of field variables to extract, using PARCELS naming convention') p.add_argument('-n', '--netcdf_vars', default=['u','v','habitat', 'F'], help='List of field variable names, as given in the NetCDF file. Order must match --variables args') p.add_argument('-d', '--dimensions', default=['latitude', 'longitude', 'time'], help='List of PARCELS convention named dimensions across which field variables occur') p.add_argument('-m', '--map_dimensions', default=['lat', 'lon', 'time'], help='List of dimensions across which field variables occur, as given in the NetCDF files, to map to the --dimensions args') p.add_argument('-t', '--time', type=int, default=30, help='Time to run simulation, in timesteps') p.add_argument('-st', '--start_time', type=int, default=1042588800, help='Start time of simulation, in seconds since 1-1-1970, defaults to 15-1-2003') p.add_argument('-s', '--startfield', type=str, default='None', help='Particle density field with which to initiate particle positions') p.add_argument('-sv', '--startfield_varname', default='start', help='Name of the density variable in the startfield netcdf file') p.add_argument('-sp', '--start_point', nargs='+', type=float, default=None, help='start location to release all particles (overides startfield argument)') p.add_argument('-o', '--output', default='IKAMOANA', help='Output filename stem') p.add_argument('-ts', '--timestep', type=int, default=172800, help='Length of timestep in seconds, defaults to two days') p.add_argument('-dts', '--density_timestep', type=int, default=None, help='Number of timesteps at which to calculate and write animal density, defaults to no density being written') p.add_argument('-wg', '--write_grid', type=bool, default=False, help='Flag to write grid files to netcdf, defaults to false') p.add_argument('-wp', '--write_particles', type=str, default=True, help='Flag to write particle trajectory to netcdf, defaults to true') p.add_argument('-sa', '--start_age', type=int, default=4, help='Starting age of tuna, in months (defaults to 4)') p.add_argument('-k', '--kernels', nargs='+', type=str, default=['LagrangianDiffusion', 'TaxisRK4','Move', 'MoveOffLand', 'FishingMortality'], help='List of kernels from Behaviour.py to run, defaults to diffusion and taxis') p.add_argument('-r', '--run', type=str, default='None', help='Name of specific run (e.g. SEAPODYM_2003), overiding input files and variables') args = p.parse_args() for arg in [args.write_grid, args.write_particles]: arg = True if arg is 'True' else False IKAMOANA_Args = {} IKAMOANA_Args['write_particles'] = False if args.write_particles == 'False' else True IKAMOANA_Args['Kernels'] = args.kernels IKAMOANA_Args['start_time'] = args.start_time IKAMOANA_Args['start_age'] = args.start_age IKAMOANA_Args['ForcingFiles'] = {} IKAMOANA_Args['ForcingVariables'] = {} for f in range(len(args.files)): IKAMOANA_Args['ForcingFiles'].update({args.variables[f]: args.files[f]}) IKAMOANA_Args['ForcingVariables'].update({args.variables[f]: args.netcdf_vars[f]}) if args.startfield == "None": IKAMOANA_Args['startfield'] = None else: IKAMOANA_Args['startpoint'] = None IKAMOANA_Args['ForcingFiles'].update({'start': args.startfield}) IKAMOANA_Args['ForcingVariables'].update({'start': args.startfield_varname}) if args.run is not 'None': temp_args = getSEAPODYMarguments(args.run) for arg in temp_args.keys(): IKAMOANA_Args[arg] = temp_args[arg] #print(IKAMOANA_Args) if args.start_point is not None: IKAMOANA_Args['startpoint'] = [[],[]] points = len(args.start_point)/2 for p in range(0,points*2, 2): IKAMOANA_Args['startpoint'][0].append([args.start_point[p]]*(args.particles/points)) IKAMOANA_Args['startpoint'][1].append([args.start_point[p+1]]*(args.particles/points)) IKAMOANA_Args['startpoint'][0] = [val for sublist in IKAMOANA_Args['startpoint'][0] for val in sublist] IKAMOANA_Args['startpoint'][1] = [val for sublist in IKAMOANA_Args['startpoint'][1] for val in sublist] IKAMOANA(Forcing_Files=IKAMOANA_Args['ForcingFiles'], Forcing_Variables=IKAMOANA_Args['ForcingVariables'], individuals=args.particles, T=args.time,timestep=args.timestep, Kernels=IKAMOANA_Args['Kernels'], density_timestep=args.density_timestep, Landmask_File=IKAMOANA_Args['LandMaskFile'], Init_Positions=None if 'startpoint' not in IKAMOANA_Args else IKAMOANA_Args['startpoint'], mode=args.mode, output_grid=args.write_grid, output_trajectory=args.write_particles, output_filestem=args.output, starttime=IKAMOANA_Args['start_time'], start_age=IKAMOANA_Args['start_age'])<file_sep>from parcels import * from SEAPODYM_functions import * from Behaviour import * from py import path from glob import glob import numpy as np import math from argparse import ArgumentParser def SIMPODYM(forcingU, forcingV, forcingH, startD=None, Uname='u', Vname='v', Hname='habitat', Dname='density', startlons=None, startlats=None, dimLon='lon', dimLat='lat',dimTime='time', Kfile=None, dK_dxfile=None, dK_dyfile=None, dH_dxfile=None, dH_dyfile=None, diffusion_boost=0, diffusion_scale=1, taxis_scale=1, individuals=100, timestep=172800, time=30, start_age=4, output_density=False, output_file="SIMPODYM", write_grid=False, random_seed=None, mode='jit'): if random_seed is None: np.random.RandomState() random_seed = np.random.get_state() else: np.random.RandomState(random_seed) filenames = {'U': forcingU, 'V': forcingV, 'H': forcingH, 'SEAPODYM_Density': startD} variables = {'U': Uname, 'V': Vname, 'H': Hname, 'SEAPODYM_Density': Dname} dimensions = {'lon': dimLon, 'lat': dimLat, 'time': dimTime} print("Creating Grid") grid = Grid.from_netcdf(filenames=filenames, variables=variables, dimensions=dimensions, vmax=200) print("Grid contains fields:") for f in grid.fields: print(f) if output_density: # Add a density field that will hold particle densities grid.add_field(Field('Density', np.full([grid.U.lon.size, grid.U.lat.size, grid.U.time.size],-1, dtype=np.float64), grid.U.lon, grid.U.lat, depth=grid.U.depth, time=grid.U.time, transpose=True)) density_field = grid.Density else: density_field = None # Offline calculate the 'diffusion' grid as a function of habitat if Kfile is None: print("Creating Diffusion Field") K = Create_SEAPODYM_Diffusion_Field(grid.H, 24*60*60, start_age=start_age, diffusion_scale=diffusion_scale, diffusion_boost=diffusion_boost) grid.add_field(K) else: print(Kfile[-3:]) if Kfile[-3:] == 'dym': grid.add_field() else: grid.add_field(Field.from_netcdf('K', {'lon': 'nav_lon', 'lat': 'nav_lat', 'time': 'time_counter', 'data': 'K'}, glob(str(path.local(Kfile))))) if dH_dxfile is None or dH_dyfile is None: # Offline calculation of the diffusion and basic habitat grid print("Calculating H Gradient Fields") gradients = grid.H.gradient() for field in gradients: grid.add_field(field) else: print("Loading H Gradient Fields") grid.add_field(Field.from_netcdf('dH_dx', {'lon': 'nav_lon', 'lat': 'nav_lat', 'time': 'time_counter', 'data': 'dH_dx'}, glob(str(path.local(dH_dxfile))))) grid.add_field(Field.from_netcdf('dH_dy', {'lon': 'nav_lon', 'lat': 'nav_lat', 'time': 'time_counter', 'data': 'dH_dy'}, glob(str(path.local(dH_dyfile))))) if dK_dxfile is None or dK_dyfile is None: print("Calculating K Gradient Fields") K_gradients = grid.K.gradient() for field in K_gradients: grid.add_field(field) else: print("Loading K Gradient Fields") grid.add_field(Field.from_netcdf('dK_dx', {'lon': 'nav_lon', 'lat': 'nav_lat', 'time': 'time_counter', 'data': 'dK_dx'}, glob(str(path.local(dK_dxfile))))) grid.add_field(Field.from_netcdf('dK_dy', {'lon': 'nav_lon', 'lat': 'nav_lat', 'time': 'time_counter', 'data': 'dK_dy'}, glob(str(path.local(dK_dyfile))))) grid.K.interp_method = grid.dK_dx.interp_method = grid.dK_dy.interp_method = grid.H.interp_method = \ grid.dH_dx.interp_method = grid.dH_dx.interp_method = grid.U.interp_method = grid.V.interp_method = 'nearest' ParticleClass = JITParticle if mode == 'jit' else ScipyParticle SKJ = Create_Particle_Class(ParticleClass) if individuals == 0: # Run full SEAPODYM numbers (can be big!) area = np.zeros(np.shape(grid.U.data[0, :, :]), dtype=np.float32) U = grid.U V = grid.V dy = (V.lon[1] - V.lon[0])/V.units.to_target(1, V.lon[0], V.lat[0]) for y in range(len(U.lat)): dx = (U.lon[1] - U.lon[0])/U.units.to_target(1, U.lon[0], U.lat[y]) area[y, :] = dy * dx # Convert to km^2 area /= 1000*1000 # Total fish is density*area total_fish = np.sum(grid.SEAPODYM_Density.data * area) print('Total no. of fish in SEAPODYM run = %s' % total_fish) print('Assuming schools of 10,000 fish, total number of individuals = %s' % str(round(total_fish/10000))) individuals = raw_input('Please enter the number of school (leave blank for default):') if individuals is '': individuals = 1000 fishset = grid.ParticleSet(size=individuals, pclass=SKJ, start_field=grid.SEAPODYM_Density, lon=startlons, lat=startlats) for p in fishset.particles: p.setAge(start_age) p.taxis_scale = taxis_scale age = fishset.Kernel(AgeParticle) diffuse = fishset.Kernel(LagrangianDiffusion) advect = fishset.Kernel(Advection_C) taxis = fishset.Kernel(GradientRK4_C) move = fishset.Kernel(Move) sampH = fishset.Kernel(SampleH) month_steps = np.arange(grid.time[0], grid.time[0]+time*timestep, step=30*24*60*60) print("Starting Sim") for m in month_steps: print("Starting Month %s, day %s, time %s" % (str(np.where(month_steps == m)[0][0]), (m - grid.time[0])/(24*60*60), m - grid.time[0])) month_files = {'U': str(forcingU + '_month' + m + '.nc'), 'V': str(forcingV + '_month' + m + '.nc'), 'H': str(forcingH + '_month' + m + '.nc')} grid = Grid.from_netcdf(filenames=month_files, variables=variables, dimensions=dimensions, vmax=200) print("Calculating H Gradient Fields") gradients = grid.H.gradient() for field in gradients: grid.add_field(field) K = Create_SEAPODYM_Diffusion_Field(grid.H, 24*60*60, start_age=start_age+m-1, diffusion_scale=diffusion_scale, diffusion_boost=diffusion_boost) grid.add_field(K) K_gradients = grid.K.gradient() for field in K_gradients: grid.add_field(field) fishset.execute(age + advect + taxis + diffuse + move, endtime=30*24*60*60-1, dt=timestep, output_file=fishset.ParticleFile(name=output_file+"_month"+str(np.where(month_steps == m)[0][0])), interval=timestep, recovery={ErrorCode.ErrorOutOfBounds: UndoMove}) grid.Density.data[np.where(month_steps == m)[0][0],:,:] = np.transpose(fishset.density(relative=True)) if write_grid: grid.write(output_file) #Write parameter file params = {"forcingU": forcingU, "forcingV": forcingV, "forcingH":forcingH, "startD":startD, "Uname":Uname, "Vname":Vname, "Hname":Hname, "Dname":Dname, "dimLon":dimLon, "dimLat":dimLat,"dimTime":dimTime, "Kfile":Kfile, "dK_dxfile":dK_dxfile, "dK_dyfile":dK_dyfile, "diffusion_boost":diffusion_boost, "diffusion_scale":diffusion_scale, "dH_dxfile":dH_dxfile, "dH_dyfile":dH_dyfile, "taxis_dampener":taxis_scale, "individuals":individuals, "timestep":timestep, "time":time, "start_age":start_age, "output_density":output_density, "output_file":output_file, "random_seed":random_seed, "mode":mode} param_file = open(output_file+"_parameters.txt", "w") for p, val in params.items(): param_file.write("%s %s\n" % (p, val)) param_file.close() def Create_Particle_Class(type=JITParticle): class SEAPODYM_SKJ(type): active = Variable("active", to_write=False) monthly_age = Variable("monthly_age", dtype=np.int32) age = Variable('age', to_write=False) Vmax = Variable('Vmax', to_write=False) Dv_max = Variable('Dv_max', to_write=False) fish = Variable('fish', to_write=False) H = Variable('H', to_write=False) Dx = Variable('Dx', to_write=False) Dy = Variable('Dy', to_write=False) Cx = Variable('Cx', to_write=False) Cy = Variable('Cy', to_write=False) Vx = Variable('Vx', to_write=False) Vy = Variable('Vy', to_write=False) Ax = Variable('Ax', to_write=False) Ay = Variable('Ay', to_write=False) taxis_scale = Variable('taxis_scale', to_write=False) def __init__(self, *args, **kwargs): """Custom initialisation function which calls the base initialisation and adds the instance variable p""" super(SEAPODYM_SKJ, self).__init__(*args, **kwargs) self.setAge(4.) self.fish = 100000 self.H = self.Dx = self.Dy = self.Cx = self.Cy = self.Vx = self.Vy = self.Ax = self.Ay = 0 self.taxis_scale = 0 self.active = 1 def setAge(self, months): self.age = months*30*24*60*60 self.monthly_age = int(self.age/(30*24*60*60)) self.Vmax = V_max(self.monthly_age) return SEAPODYM_SKJ if __name__ == "__main__": p = ArgumentParser(description=""" Example of underlying habitat field""") p.add_argument('mode', choices=('scipy', 'jit'), nargs='?', default='scipy', help='Execution mode for performing RK4 computation') p.add_argument('-p', '--particles', type=int, default=10, help='Number of particles to advect') p.add_argument('--profiling', action='store_true', default=False, help='Print profiling information after run') p.add_argument('-g', '--grid', type=int, default=None, help='Generate grid file with given dimensions') p.add_argument('-f', '--files', default=['SEAPODYM_Forcing_Data/SEAPODYM2003_PHYS_Prepped.nc', 'SEAPODYM_Forcing_Data/SEAPODYM2003_PHYS_Prepped.nc', 'SEAPODYM_Forcing_Data/2002_Fields/HABITAT/2003_HABITAT.nc'], help='List of NetCDF files to load') p.add_argument('-v', '--variables', default=['U', 'V', 'H'], help='List of field variables to extract, using PARCELS naming convention') p.add_argument('-n', '--netcdf_vars', default=['u', 'v', 'habitat'], help='List of field variable names, as given in the NetCDF file. Order must match --variables args') p.add_argument('-d', '--dimensions', default=['lat', 'lon', 'time'], help='List of PARCELS convention named dimensions across which field variables occur') p.add_argument('-m', '--map_dimensions', default=['lat', 'lon', 'time'], help='List of dimensions across which field variables occur, as given in the NetCDF files, to map to the --dimensions args') p.add_argument('-t', '--time', type=int, default=15, help='List of dimensions across which field variables occur, as given in the NetCDF files, to map to the --dimensions args') p.add_argument('-s', '--startfield', type=str, default='SEAPODYM_Forcing_Data/2002_Fields/DENSITY/2003_Density.nc', help='Particle density field with which to initiate particle positions') p.add_argument('-o', '--output', default='SIMPODYM2003', help='List of NetCDF files to load') p.add_argument('-ts', '--timestep', type=int, default=172800, help='Length of timestep in seconds, defaults to two days') p.add_argument('-b', '--boost', type=float, default=0, help='Constant boost to diffusivity of tuna') p.add_argument('-ds', '--diffusion_scale', type=float, default=1, help='Extra scale parameter to diffusivity of tuna') p.add_argument('-td', '--taxis_scale', type=float, default=1, help='Constant scaler to taxis of tuna') p.add_argument('-sa', '--start_age', type=int, default=4, help='Assumed start age of tuna cohort, in months. Defaults to 4') p.add_argument('-wd', '--write_density', type=bool, default=True, help='Flag to calculate monthly densities, defaults to true') p.add_argument('-wg', '--write_grid', type=bool, default=False, help='Flag to write grid files to netcdf, defaults to false') args = p.parse_args() filename = args.output U = args.files[0] V = args.files[1] H = args.files[2] if args.startfield == "None": args.startfield = None SIMPODYM(forcingU=U, forcingV=V, forcingH=H, startD=args.startfield, Uname=args.netcdf_vars[0], Vname=args.netcdf_vars[1], Hname=args.netcdf_vars[2], dimLat=args.dimensions[0], dimLon=args.dimensions[1], dimTime=args.dimensions[2], diffusion_boost=args.boost, diffusion_scale=args.diffusion_scale, taxis_scale=args.taxis_scale, start_age=args.start_age, individuals=args.particles, timestep=args.timestep, time=args.time, output_density=args.write_density, output_file=args.output, write_grid=args.write_grid, mode=args.mode) <file_sep>from parcels import * from SEAPODYM_functions import * from Behaviour import * from glob import glob import numpy as np import math from argparse import ArgumentParser def SIMPLEDYM_SIM(Ufilestem, Vfilestem, Hfilestem, startD=None, Uname='u', Vname='v', Hname='habitat', Dname='skipjack_cohort_20021015_density_M0', dimLon='lon', dimLat='lat',dimTime='time', Kfilestem=None, field_units='m2_per_s', individuals=100, timestep=172800, months=3, start_age=4, start_month=1, start_year=2003, start_point=None, output_density=False, output_file="SIMPODYM", write_grid=False, write_trajectories=True, random_seed=None, mode='jit', verbose=True, filestem_simple={'H': True, 'U': False, 'V': False}): if random_seed is None: np.random.RandomState() random_seed = np.random.get_state() else: np.random.RandomState(random_seed) filenames = {'U': Ufilestem, 'V': Vfilestem, 'H': Hfilestem} variables = {'U': Uname, 'V': Vname, 'H': Hname} dimensions = {'lon': dimLon, 'lat': dimLat, 'time': dimTime} ParticleClass = JITParticle if mode == 'jit' else ScipyParticle SKJ = Create_Particle_Class(ParticleClass) print("Starting Sim") month_steps = np.arange(start_month, start_month+months) for m in month_steps: fish_age = start_age+np.where(month_steps == m)[0][0] print("Starting Month %s" % m) month_files = {} for v in filenames.keys(): month_files.update({v: getForcingFilename(filenames[v], m, start_year=start_year, simple=filestem_simple[v])}) if Kfilestem is not None: Kfile = (getForcingFilename(Kfilestem, m, start_year=start_year)) else: Kfile = None if m == start_month: grid = Create_SEAPODYM_Grid(forcing_files=month_files, forcing_vars=variables, forcing_dims=dimensions, startD=startD, start_age=fish_age, verbose=verbose, diffusion_file=Kfile, field_units=field_units, startD_dims={'lon': 'longitude', 'lat': 'latitude', 'time': 'time', 'data': Dname}) if verbose: total_pop = getPopFromDensityField(grid) print('Total no. of fish in SEAPODYM run = %s' % total_pop) print('therefor simulation assumes each particle represents %s individual fish' % str(total_pop/individuals)) if start_point is not None: print("All particles starting at position %s %s" % (start_point[0], start_point[1])) fishset = grid.ParticleSet(size=individuals, pclass=SKJ, lon=[start_point[0]]*individuals, lat=[start_point[1]]*individuals) else: fishset = ParticleSet.from_field(grid, size=individuals, pclass=SKJ, start_field=grid.Start) results_file = ParticleFile(output_file + '_results', fishset) if write_trajectories is True else None if output_density: sim_time = np.linspace(grid.U.time[0], grid.U.time[0]+(months+1)*30*24*60*60, num=months+1) fish_density = Field('Density', np.full([grid.U.lon.size, grid.U.lat.size, sim_time.size],-1, dtype=np.float64), grid.U.lon, grid.U.lat, depth=grid.U.depth, transpose=True, time=sim_time) #Calculate density before initial timestep if output_density: fish_density.data[np.where(month_steps == m)[0][0],:,:] = fishset.density()#np.transpose(fishset.density()) else: grid = Create_SEAPODYM_Grid(forcing_files=month_files, forcing_vars=variables, forcing_dims=dimensions, start_age=fish_age, diffusion_file=Kfile, field_units=field_units, verbose=verbose) oldfishset = fishset fishset = ParticleSet.from_list(grid, pclass=SKJ, lon=[200]*individuals, lat=[0]*individuals) for p in range(len(fishset.particles)): Copy_Fish_Particle(oldfishset.particles[p], fishset.particles[p], SKJ) fishset.particles[p].In_Loop = 0 if write_grid: grid.write(output_file + '_month' + str(m) + '_') for p in fishset.particles: p.setAge(fish_age) ## Test case (TO REMOVE) grid.add_constant('minlon', 160) grid.add_constant('maxlon', 240) grid.add_constant('minlat', -10) grid.add_constant('maxlat', 20) regionstop = fishset.Kernel(RegionBound) age = fishset.Kernel(AgeParticle) diffuse = fishset.Kernel(LagrangianDiffusion) advect = fishset.Kernel(Advection_C) taxis = fishset.Kernel(TaxisRK4)#fishset.Kernel(GradientRK4_C) #combinedadvection = fishset.Kernel(CurrentAndTaxisRK4) move = fishset.Kernel(MoveWithLandCheck) #landcheck = fishset.Kernel(MoveOffLand) sampH = fishset.Kernel(SampleH) moveeast = fishset.Kernel(MoveEast) movewest = fishset.Kernel(MoveWest) print("Executing kernels...") #end_time = 15*24*60*60 if m == start_month else 30*24*60*60 run_time = 30*24*60*60 fishset.execute(age + advect + taxis + diffuse + move + sampH, starttime=fishset[0].time, runtime=run_time, dt=timestep, output_file=results_file, interval=timestep, recovery={ErrorCode.ErrorOutOfBounds: UndoMove}) #fishset.execute(age + advect + taxis + diffuse + move + landcheck + sampH, starttime=grid.U.time[0], endtime=grid.U.time[0]+30*24*60*60, dt=timestep, # output_file=results_file, interval=timestep, recovery={ErrorCode.ErrorOutOfBounds: UndoMove}) #fishset.execute(movewest + landcheck, starttime=grid.time[0], endtime=grid.time[0]+30*24*60*60, dt=timestep, # output_file=results_file, interval=timestep, recovery={ErrorCode.ErrorOutOfBounds: UndoMove}) # Here we are calculating density AFTER particle execution each timestep if output_density: fish_density.data[np.where(month_steps == m)[0][0] + 1,:,:] = fishset.density()#np.transpose(fishset.density()) fish_density.write(output_file) params = {"forcingU": Ufilestem, "forcingV": Vfilestem, "forcingH":Hfilestem, "startD":startD, "Uname":Uname, "Vname":Vname, "Hname":Hname, "Dname":Dname, "dimLon":dimLon, "dimLat":dimLat,"dimTime":dimTime, "Kfile":Kfilestem, "individuals":individuals, "timestep":timestep, "month_steps":months, "start_age":start_age, "start_month":start_month, "start_year":start_year, "trajectories_output":write_trajectories, "output_density":output_density, "output_file":output_file, "random_seed":random_seed, "mode":mode} write_parameter_file(params, output_file) def getForcingFilename(stem, month_step, start_year=2003, simple=False): if simple: if month_step < 10: month_step = '0'+str(month_step) return(stem + str(month_step) + '.nc') else: year = int(start_year + math.floor((month_step-1)/12)) month = month_step % 12 if month == 0: month = 12 if month < 10: month = '0' + str(month) return(stem + str(year) + str(month) + "15.nc") def Create_Particle_Class(type=JITParticle): class SEAPODYM_SKJ(type): active = Variable("active", to_write=False) monthly_age = Variable("monthly_age", dtype=np.int32) age = Variable('age', to_write=False) #Vmax = Variable('Vmax', to_write=False, dtype=np.float32) #Dv_max = Variable('Dv_max', to_write=False) fish = Variable('fish', to_write=False) H = Variable('H', to_write=False, dtype=np.float32) dHdx = Variable('dHdx', to_write=False, dtype=np.float32) dHdy = Variable('dHdy', to_write=False, dtype=np.float32) # Dx = Variable('Dx', to_write=False, dtype=np.float32) # Dy = Variable('Dy', to_write=False, dtype=np.float32) # Cx = Variable('Cx', to_write=False, dtype=np.float32) # Cy = Variable('Cy', to_write=False, dtype=np.float32) # Vx = Variable('Vx', to_write=False, dtype=np.float32) # Vy = Variable('Vy', to_write=False, dtype=np.float32) # Ax = Variable('Ax', to_write=False, dtype=np.float32) # Ay = Variable('Ay', to_write=False, dtype=np.float32) In_Loop = Variable('In_Loop', to_write=True, dtype=np.float32) #taxis_scale = Variable('taxis_scale', to_write=False) prev_lon = Variable('prev_lon', to_write=True) prev_lat = Variable('prev_lat', to_write=True) def __init__(self, *args, **kwargs): """Custom initialisation function which calls the base initialisation and adds the instance variable p""" super(SEAPODYM_SKJ, self).__init__(*args, **kwargs) self.setAge(4.) self.fish = 100000 #self.H = self.Dx = self.Dy = self.Cx = self.Cy = self.Vx = self.Vy = self.Ax = self.Ay = 0.0 self.H = 0.0 #self.taxis_scale = 1 self.active = 1 self.In_Loop = 0 def setAge(self, months): self.age = months*30*24*60*60 self.monthly_age = int(self.age/(30*24*60*60)) #self.Vmax = V_max(self.monthly_age) return SEAPODYM_SKJ def Copy_Fish_Particle(old_p, new_p, pclass): for v in pclass.getPType().variables: #print("Copying %s, oldvalue = %s, newvalue = %s" % (v.name, getattr(old_p, v.name), getattr(new_p, v.name))) setattr(new_p, v.name, getattr(old_p, v.name)) def write_parameter_file(params, file_stem): param_file = open(file_stem+"_parameters.txt", "w") for p, val in params.items(): param_file.write("%s %s\n" % (p, val)) param_file.close() if __name__ == "__main__": p = ArgumentParser(description=""" Example of underlying habitat field""") p.add_argument('mode', choices=('scipy', 'jit'), nargs='?', default='scipy', help='Execution mode for performing RK4 computation') p.add_argument('-p', '--particles', type=int, default=10, help='Number of particles to advect') p.add_argument('-r', '--run', default='2003') p.add_argument('-f', '--files', default=['SEAPODYM_Forcing_Data/Latest/PHYSICAL/2003Run/2003run_PHYS_month', 'SEAPODYM_Forcing_Data/Latest/PHYSICAL/2003Run/2003run_PHYS_month', 'SEAPODYM_Forcing_Data/Latest/HABITAT/2003Run/INTERIM-NEMO-PISCES_skipjack_habitat_index_'], help='List of NetCDF files to load') p.add_argument('-v', '--variables', default=['U', 'V', 'H'], help='List of field variables to extract, using PARCELS naming convention') p.add_argument('-n', '--netcdf_vars', default=['u', 'v', 'skipjack_habitat_index'], help='List of field variable names, as given in the NetCDF file. Order must match --variables args') p.add_argument('-d', '--dimensions', default=['latitude', 'longitude', 'time'], help='List of PARCELS convention named dimensions across which field variables occur') p.add_argument('-m', '--map_dimensions', default=['lat', 'lon', 'time'], help='List of dimensions across which field variables occur, as given in the NetCDF files, to map to the --dimensions args') p.add_argument('-t', '--time', type=int, default=3, help='Time to run simulation, in months') p.add_argument('-s', '--startfield', type=str, default='SEAPODYM_Forcing_Data/Latest/DENSITY/INTERIM-NEMO-PISCES_skipjack_cohort_20021015_density_M0_20030115.nc', help='Particle density field with which to initiate particle positions') p.add_argument('-sv', '--startfield_varname', default='skipjack_cohort_20021015_density_M0', help='Name of the density variable in the startfield netcdf file') p.add_argument('-sp', '--start_point', nargs=2, default=-1, help='start location to release all particles (overides startfield argument)') p.add_argument('-k', '--k_file_stem', default='None', help='File stem name for pre-calculated diffusivity fields') p.add_argument('-fu', '--field_file_units', default='m_per_s', help='Units to use for calculating diffusion and taxis field data, defaults to meters (^2 for K) per second') p.add_argument('-o', '--output', default='SIMPLEDYM2003', help='Output filename stem') p.add_argument('-ts', '--timestep', type=int, default=172800, help='Length of timestep in seconds, defaults to two days') p.add_argument('-wd', '--write_density', type=str, default='True', help='Flag to calculate monthly densities, defaults to true') p.add_argument('-wg', '--write_grid', type=bool, default=False, help='Flag to write grid files to netcdf, defaults to false') p.add_argument('-wp', '--write_particles', type=str, default='True', help='Flag to write particle trajectory to netcdf, defaults to true') p.add_argument('-sa', '--start_age', type=int, default=4, help='Starting age of tuna, in months (defaults to 4)') p.add_argument('-sm', '--start_month', type=int, default=1, help='Starting time of the simulation, in months, (defaults to month 1)') p.add_argument('-sy', '--start_year', type=int, default=2003, help='Starting year of the simulation (defaults to 2003)') p.add_argument('-vb', '--verbose', type=bool, default=False, help='Boolean for verbose print statements') args = p.parse_args() if args.startfield == "None": args.startfield = None if args.start_point == -1: args.start_point = None if args.k_file_stem == "None": args.k_file_stem = None args.write_particles = False if args.write_particles == 'False' else True args.write_density = False if args.write_density == 'False' else True if args.verbose != False: args.verbose = True # Dictionary for the timestep naming convention of files file_naming = {'H': False, 'U': True, 'V': True} if args.run == '1997': args.files = ['SEAPODYM_Forcing_Data/Latest/PHYSICAL/1997Run/1997run_PHYS_month', 'SEAPODYM_Forcing_Data/Latest/PHYSICAL/1997Run/1997run_PHYS_month', 'SEAPODYM_Forcing_Data/Latest/HABITAT/1997Run/INTERIM-NEMO-PISCES_skipjack_habitat_index_'] args.start_year = 1997 args.startfield = 'SEAPODYM_Forcing_Data/Latest/DENSITY/INTERIM-NEMO-PISCES_skipjack_cohort_19961015_density_M0_19970115.nc' args.startfield_varname = 'skipjack_cohort_19961015_density_M0' if args.run == 'test': args.files = ['TestCase/IdealTestCasePhysical_Month', 'TestCase/IdealTestCasePhysical_Month', 'TestCase/IdealTestCaseHabitat_Month'] args.start_year = 2000 args.startfield = 'TestCase/EvenStartDist.nc' args.startfield_varname = 'even_dist' file_naming = {'H': True, 'U': True, 'V': True} SIMPLEDYM_SIM(Ufilestem=args.files[0], Vfilestem=args.files[1], Hfilestem=args.files[2], startD=args.startfield, Uname=args.netcdf_vars[0], Vname=args.netcdf_vars[1], Hname=args.netcdf_vars[2], Dname=args.startfield_varname, dimLat=args.dimensions[0], dimLon=args.dimensions[1], dimTime=args.dimensions[2], Kfilestem=args.k_file_stem, field_units=args.field_file_units, individuals=args.particles, timestep=args.timestep, months=args.time, start_age=args.start_age, start_month=args.start_month, start_year=args.start_year, start_point=args.start_point, output_density=args.write_density, output_file=args.output, write_trajectories=args.write_particles, write_grid=args.write_grid, mode=args.mode, filestem_simple=file_naming, verbose=args.verbose) <file_sep>#!/usr/bin/env python from netCDF4 import Dataset import numpy as np from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt from argparse import ArgumentParser import matplotlib.animation as animation import matplotlib.lines as mlines import matplotlib.patches as mpatches from datetime import timedelta, datetime def getMFRegion(lon, lat): region = -1 if lon > 210: # Longitudinally outside WCPO assessment area region = 6 else: if lat > 50: # Latitudinally outside assessment area region = 6 elif lat < -20: region = 6 else: if lat > 20: region = 1 else: # regions 2 to 5 if lon < 140: region = 4 elif lon > 170: region = 3 else: # regions 2 and 5 (the tricky one) if lat > 0: region = 2 elif lon > 160: region = 2 else: if lon > 155 and lat > -5: region = 2 else: region = 5 return region def particleplotting(filename, psize, recordedvar, rcmap, backgroundfield, dimensions, cmap, drawland, limits, display, start=1, mode='movie2d', plot_mfregion=False, mfregion_start=1, mf_focus=0, output='particle_plot'): """Quick and simple plotting of PARCELS trajectories""" pfile = Dataset(filename, 'r') lon = pfile.variables['lon'] lat = pfile.variables['lat'] #time = pfile.variables['time'] #z = pfile.variables['z'] active = pfile.variables['active'] if display is not 'none': title = pfile.variables[display] if plot_mfregion: mf_cols = [] colmap = {1: 'red', 2: 'blue', 3: 'orange', 4: 'green', 5: 'purple', 6: 'grey'} if mf_focus == 0: for p in range(lon.shape[0]): mf_cols.append(colmap[getMFRegion(lon[p,mfregion_start], lat[p,mfregion_start])]) else: for p in range(lon.shape[0]): r = getMFRegion(lon[p,mfregion_start], lat[p,mfregion_start]) mf_cols.append(colmap[r] if r is mf_focus else 'lightgrey') if limits is -1: limits = [np.min(lon), np.max(lon), np.min(lat), np.max(lat)] if recordedvar is not 'none': print('Particles coloured by: %s' % recordedvar) rMin = np.min(pfile.variables[recordedvar]) rMax = np.max(pfile.variables[recordedvar]) print('Min = %f, Max = %f' % (rMin, rMax)) record = (pfile.variables[recordedvar]-rMin)/(rMax-rMin) if backgroundfield is not 'none': bfile = Dataset(backgroundfield.values()[0], 'r') bX = bfile.variables[dimensions[0]] bY = bfile.variables[dimensions[1]] bT = bfile.variables[dimensions[2]] # Find the variable that exists across at least two spatial and one time dimension if backgroundfield.keys()[0] is 'none': def checkShape(var): print(np.shape(var)) if len(np.shape(var)) > 2: return True for v in bfile.variables: if checkShape(bfile.variables[v]): bVar = bfile.variables[v] print('Background variable is %s' % v) break else: bVar = bfile.variables[backgroundfield.keys()[0]] if mode == '3d': fig = plt.figure(1) ax = fig.gca(projection='3d') for p in range(len(lon)): ax.plot(lon[p, :], lat[p, :], z[p, :], '.-') ax.set_xlabel('Longitude') ax.set_ylabel('Latitude') ax.set_zlabel('Depth') plt.show() elif mode == '2d': fig, ax = plt.subplots(1, 1) #subsample indices = np.rint(np.linspace(0, len(lon)-1, 100)).astype(int) #indices = range(len(lon[:,0])) if backgroundfield is not 'none': time=18 plt.contourf(bX[:], bY[:], bVar[time, 0, :, :], zorder=-1, vmin=0, vmax=np.max(bVar[time, 0, :, :]), levels=np.linspace(0, np.max(bVar[time, 0, :, :]), 100), xlim=[limits[0], limits[1]], ylim=[limits[2], limits[3]], cmap=cmap) #plt.plot(np.transpose(lon[indices,:]), np.transpose(lat[indices,:]), '.-', linewidth=psize, # markersize=psize, c='blue') plt.quiver(np.transpose(lon[indices,:-1]), np.transpose(lat[indices,:-1]), np.transpose(lon[indices,1:])-np.transpose(lon[indices,:-1]), np.transpose(lat[indices,1:])-np.transpose(indices,lat[:-1]), scale_units='xy', angles='xy', scale=1) plt.xlim([limits[0], limits[1]]) plt.ylim([limits[2], limits[3]]) else: lines = ax.plot(np.transpose(lon[indices,:]), np.transpose(lat[indices,:]), 'k-', linewidth=psize, markersize=psize, c='white') plt.xlim([limits[0], limits[1]]) plt.ylim([limits[2], limits[3]]) add_arrow_to_line2D(ax, lines, arrow_locs=np.linspace(0., 1., 200), arrowstyle='->') plt.xlabel('Longitude') plt.ylabel('Latitude') if drawland: m = Basemap(width=12000000, height=9000000, projection='cyl', resolution='f', llcrnrlon=limits[0], llcrnrlat=limits[2], urcrnrlon=limits[1], urcrnrlat=limits[3], epsg=4714, area_thresh = 0.1) m.drawcoastlines() m.etopo() #m.arcgisimage(service='ESRI_Imagery_World_2D', xpixels = 2000, verbose= True) m.fillcontinents(color='forestgreen', lake_color='aqua') plt.show() elif mode == 'movie2d': fig = plt.figure(1) ax = plt.axes(xlim=[limits[0], limits[1]], ylim=[limits[2], limits[3]]) ax.set_xlim(limits[0], limits[1]) ax.set_ylim(limits[2], limits[3]) indices = np.rint(np.linspace(0, len(lon)-1, 100)).astype(int) scat = ax.scatter(lon[indices, 0], lat[indices, 0], s=psize, c='black') # Offline calc contours still to do def animate(i): ax.cla() active_list = np.where(active[:, i] == 1)[0] if len(active_list) < 1: active_list = 0 #active_list = range(len(lon[:,i]))#indices # if len(np.where(active_list)) > 1: if drawland: m.drawcoastlines() m.fillcontinents(color='forestgreen', lake_color='aqua') if recordedvar is not 'none': scat = ax.scatter(lon[active_list, i], lat[active_list, i], s=psize, c=record[active_list, i], cmap=rcmap, vmin=0, vmax=1) elif plot_mfregion: scat = ax.scatter(lon[active_list, i], lat[active_list, i], s=psize, color=mf_cols, cmap='summer', vmin=0, vmax=1) else: scat = ax.scatter(lon[active_list, i], lat[active_list, i], s=psize, c='blue', edgecolors='black') ax.set_xlim([limits[0], limits[1]]) ax.set_ylim([limits[2], limits[3]]) if backgroundfield is not 'none': field_time = np.argmax(bT > time[0, i]) - 1 plt.contourf(bY[:], bX[:], bVar[field_time, :, :], vmin=0, vmax=np.max(bVar[field_time, :, :]), levels=np.linspace(0, np.max(bVar[field_time, :, :]), 100), xlim=[limits[0], limits[1]], zorder=-1,ylim=[limits[2], limits[3]], cmap=cmap) plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0) if display is not 'none': if display == 'time': plt.suptitle(datetime.fromtimestamp(title[0,i])) else: plt.suptitle("Cohort age %s months" % display)#"Cohort age = %s months" % title[0,i]) plt.title("Region %s" % mf_focus) return scat, if drawland: m = Basemap(width=12000000, height=9000000, projection='cyl', resolution='c', llcrnrlon=np.round(np.amin(lon)), llcrnrlat=np.amin(lat), urcrnrlon=np.amax(lon), urcrnrlat=np.amax(lat), area_thresh = 10) anim = animation.FuncAnimation(fig, animate, frames=np.arange(start, lon.shape[1]), interval=1, blit=False) plt.show() elif mode == 'to_file': fig = plt.figure(1, figsize=(16, 8), dpi=100) ax = plt.axes(xlim=[limits[0], limits[1]], ylim=[limits[2], limits[3]]) ax.set_xlim(limits[0], limits[1]) ax.set_ylim(limits[2], limits[3]) indices = np.rint(np.linspace(0, len(lon)-1, 100)).astype(int) scat = ax.scatter(lon[indices, 0], lat[indices, 0], s=psize, c='black') if drawland: m = Basemap(width=12000000, height=9000000, projection='cyl', resolution='c', llcrnrlon=np.round(np.amin(lon)), llcrnrlat=np.amin(lat), urcrnrlon=np.amax(lon), urcrnrlat=np.amax(lat), area_thresh = 10) for i in np.arange(start, lon.shape[1]): ax.cla() #active_list = active[:, i] > 0 active_list = range(len(lon[:,i]))#indices if drawland: m.drawcoastlines() m.fillcontinents(color='forestgreen', lake_color='aqua') if recordedvar is not 'none': scat = ax.scatter(lon[active_list, i], lat[active_list, i], s=psize, c=record[active_list, i], cmap=rcmap, vmin=0, vmax=1) elif plot_mfregion: scat = ax.scatter(lon[active_list, i], lat[active_list, i], s=psize, color=mf_cols, cmap='summer', vmin=0, vmax=1) else: scat = ax.scatter(lon[active_list, i], lat[active_list, i], s=psize, c='blue', edgecolors='black') ax.set_xlim([limits[0], limits[1]]) ax.set_ylim([limits[2], limits[3]]) if backgroundfield is not 'none': field_time = np.argmax(bT > time[0, i]) - 1 plt.contourf(bY[:], bX[:], bVar[field_time, :, :], vmin=0, vmax=np.max(bVar[field_time, :, :]), levels=np.linspace(0, np.max(bVar[field_time, :, :]), 100), xlim=[limits[0], limits[1]], zorder=-1,ylim=[limits[2], limits[3]], cmap=cmap) plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0) if display is not 'none': plt.suptitle("Region %s\nCohort age %s months" % (mf_focus if mf_focus != 0 else 'All', title[0,i])) plt.savefig('Plots/%s%s.png' % (output, i)) if __name__ == "__main__": p = ArgumentParser(description="""Quick and simple plotting of PARCELS trajectories""") p.add_argument('mode', choices=('2d', '3d', 'movie2d', 'to_file'), nargs='?', default='2d', help='Type of display') p.add_argument('-p', '--particlefile', type=str, default='MyParticle.nc', help='Name of particle file') p.add_argument('-r', '--recordedvar', type=str, default='none', help='Name of a variable recorded along trajectory') p.add_argument('-b', '--background', type=str, default='none', help='Name of file containing background field to display') p.add_argument('-v', '--variable', type=str, default='none', help='Name of variable to display in background field') p.add_argument('-c', '--colourmap', type=str, default='jet', help='Colourmap for field data') p.add_argument('-cr', '--colourmap_recorded', type=str, default='autumn', help='Colourmap for particle recorded data') p.add_argument('-s', '--size', type=str, default='none', help='Size of drawn particles and tracks') p.add_argument('-ld', '--landdraw', type=bool, default=False, help='Boolean for whether to draw land using mpl.basemap package') p.add_argument('-l', '--limits', type=float, nargs=4, default=-1, help='Limits for plotting, given min_lon, max_lon, min_lat, max_lat') p.add_argument('-d', '--dimensions', type=str, nargs=3, default=['nav_lon', 'nav_lat', 'time_counter'], help='Name of background field dimensions in order of lon, lat, and time') p.add_argument('-t', '--title', type=str, default='none', help='Variable to pull from particle file and display during movie') p.add_argument('-st', '--start_time', type=int, default=1, help='Timestep from which to begin animation') p.add_argument('-o', '--output', type=str, default='particle_plot', help='Filename stem when writing to file') p.add_argument('-mf', '--mf_colours', type=str, default='False', help='Boolean flag for colouring particles by SKJ assessment region') p.add_argument('-mff', '--mf_focus', type=int, default=0, help='which single region to be coloured, defaults to zero which is all regions') p.add_argument('-mfs', '--mf_start', type=int, default=0, help='Timestep at which to define mf region classification, defaults to the first') args = p.parse_args() if args.background is not 'none': args.background = {args.variable: args.background} if args.mf_colours == 'True': print("MF") mf_colours = True else: print("NO MF") mf_colours = False if args.size is 'none': if args.mode is 'movie2d': psize = 60 else: psize = 1 else: psize = int(args.size) particleplotting(args.particlefile, psize, args.recordedvar, args.colourmap_recorded, args.background, args.dimensions, args.colourmap, args.landdraw, args.limits, args.title,start=args.start_time, mode=args.mode, output=args.output, plot_mfregion=mf_colours, mfregion_start=args.mf_start, mf_focus=args.mf_focus) <file_sep>import numpy as np import struct import math from parcels.field import Field, Geographic, GeographicPolar from parcels.fieldset import FieldSet, data_converters_func from parcels.particle import * from netCDF4 import num2date from datetime import datetime from py import path from progressbar import ProgressBar from glob import glob def getGradient(field, landmask=None, shallow_sea_zero=True): dx, dy = field.cell_distances() data = field.data dVdx = np.zeros(data.shape, dtype=np.float32) dVdy = np.zeros(data.shape, dtype=np.float32) if landmask is not None: landmask = np.transpose(landmask.data[0,:,:]) if shallow_sea_zero is False: landmask[np.where(landmask == 2)] = 0 for t in range(len(field.time)): for x in range(1, len(field.lon)-1): for y in range(1, len(field.lat)-1): if landmask[x, y] < 1: if landmask[x+1, y] == 1: dVdx[t,y,x] = (data[t,y,x] - data[t,y,x-1])/dx[y, x] elif landmask[x-1, y] == 1: dVdx[t,y,x] = (data[t,y,x+1] - data[t,y,x])/dx[y, x] else: dVdx[t,y,x] = (data[t,y,x+1] - data[t,y,x-1])/(2*dx[y, x]) if landmask[x, y+1] == 1: dVdy[t,y,x] = (data[t,y,x] - data[t,y-1,x])/dy[y, x] elif landmask[x, y-1] == 1: dVdy[t,y,x] = (data[t,y+1,x] - data[t,y,x])/dy[y, x] else: dVdy[t,y,x] = (data[t,y+1,x] - data[t,y-1,x])/(2*dy[y, x]) # Edges always forward or backwards differencing for x in range(len(field.lon)): dVdy[t, 0, x] = (data[t, 1, x] - data[t, 0, x]) / dy[0, x] dVdy[t, len(field.lat)-1, x] = (data[t, len(field.lat)-1, x] - data[t, len(field.lat)-2, x]) / dy[len(field.lat)-2, x] for y in range(len(field.lat)): dVdx[t, y, 0] = (data[t, y, 1] - data[t, y, 0]) / dx[y, x] dVdx[t, y, len(field.lon)-1] = (data[t, y, len(field.lon)-1] - data[t, y, len(field.lon)-2]) / dx[y, x] return Field('d' + field.name + '_dx', dVdx, field.lon, field.lat, field.depth, field.time, \ interp_method=field.interp_method, allow_time_extrapolation=field.allow_time_extrapolation),\ Field('d' + field.name + '_dy', dVdy, field.lon, field.lat, field.depth, field.time, \ interp_method=field.interp_method, allow_time_extrapolation=field.allow_time_extrapolation) def V_max(monthly_age, a=2.225841100458143, b=0.8348850216641774): L = GetLengthFromAge(monthly_age) V = a * np.power(L, b) return V def V_max_C(monthly_age): a=2.225841100458143# 0.7343607395421234 old parameters b=0.8348850216641774# 0.5006692114850767 old parameters L = GetLengthFromAge(monthly_age) V = a * math.pow(L, b) return V def GetLengthFromAge(monthly_age): # Linf = 88.317 # K = 0.1965 # return Linf * (1 - np.exp(-K * age)) # Hard code discrete age-lengths for now lengths = [3.00, 4.51, 6.02, 11.65, 16.91, 21.83, 26.43, 30.72, 34.73, 38.49, 41.99, 45.27, 48.33, 51.19, 53.86, 56.36, 58.70, 60.88, 62.92, 64.83, 66.61, 68.27, 69.83, 71.28, 72.64, 73.91, 75.10, 76.21, 77.25, 78.22, 79.12, 79.97, 80.76, 81.50, 82.19, 82.83, 83.44, 84.00, 84.53, 85.02, 85.48, 85.91, 86.31, 86.69, 87.04, 87.37, 87.68, 87.96, 88.23, 88.48, 88.71, 88.93, 89.14, 89.33, 89.51, 89.67, 89.83, 89.97, 90.11, 90.24, 90.36, 90.47, 90.57, 90.67, 91.16] return lengths[monthly_age-1]/100 # Convert to meters def Mortality(age, MPmax=0.3, MPexp=0.1008314958945224, MSmax=0.006109001382111822, MSslope=0.8158285706493162, Mrange=1.430156372206337e-05, H=1): Mnat = MPmax*np.exp(-MPexp*age) + MSmax*np.power(age, MSslope) Mvar = Mnat * np.power(1 - Mrange, 1-H/2) return Mvar def Mortality_C(age, H): MPmax=0.3 MPexp=0.1008314958945224 MSmax=0.006109001382111822 MSslope=0.8158285706493162 Mrange=1.430156372206337e-05 Mnat = MPmax*math.exp(-MPexp*age) + MSmax*math.pow(age, MSslope) Mvar = Mnat * math.pow(1 - Mrange, 1-H/2) return Mvar def getPopFromDensityField(grid, density_field='Start'): area = np.zeros(np.shape(grid.U.data[0, :, :]), dtype=np.float32) U = grid.U V = grid.V dy = (V.lon[1] - V.lon[0])/V.units.to_target(1, V.lon[0], V.lat[0]) for y in range(len(U.lat)): dx = (U.lon[1] - U.lon[0])/U.units.to_target(1, U.lon[0], U.lat[y]) area[y, :] = dy * dx # Convert to km^2 area /= 1000*1000 # Total fish is density*area total_fish = np.sum(getattr(grid, density_field).data * area) return total_fish def Create_Landmask(grid, lim=1e-45): def isocean(p, lim): return 1 if p < lim else 0 def isshallow(p, lim): return 1 if p < lim else 0 nx = grid.H.lon.size ny = grid.H.lat.size mask = np.zeros([nx, ny, 1], dtype=np.int8) pbar = ProgressBar() for i in pbar(range(nx)): for j in range(1, ny-1): if isshallow(np.abs(grid.bathy.data[0, 2, j, i]), lim): mask[i,j] = 2 if isocean(grid.H.data[0, j, i],lim): # For each land point mask[i,j] = 1 Mask = Field('LandMask', mask, grid.H.lon, grid.H.lat, transpose=True) Mask.interp_method = 'nearest' return Mask#ClosestLon, ClosestLat def Create_SEAPODYM_F_Field(E, start_age=4, q=0.001032652877899101, selectivity_func=3, mu= 52.56103941719986, sigma=8.614813906820441, r_asymp=0.2456242856428466): F_Data = np.zeros(np.shape(E.data), dtype=np.float32) age = start_age for t in range(E.time.size): if E.time[t] - E.time[0] > (age-start_age+1)*28*24*60*60: age += 1 l = GetLengthFromAge(age)*100 if l > mu: Selectivity = r_asymp+(1-r_asymp)*np.exp(-(pow(l-mu,2)/(sigma))) else: Selectivity = np.exp(-(pow(l-mu,2)/(sigma))) print("Age = %s months, Length = %scm, Selectivity = %s" % (age, l, Selectivity)) F_Data[t,:,:] = E.data[t,:,:] * q * Selectivity return(Field('F', F_Data, E.lon, E.lat, time=E.time, interp_method='nearest')) def Create_SEAPODYM_Taxis_Fields(dHdx, dHdy, start_age=4, taxis_scale=1, units='m_per_s'): Tx = np.zeros(np.shape(dHdx.data), dtype=np.float32) Ty = np.zeros(np.shape(dHdx.data), dtype=np.float32) months = start_age age = months*30*24*60*60 for t in range(dHdx.time.size): age = (start_age+t)*30*24*60*60 if age - (months*30*24*60*60) >= (30*24*60*60): months += 1 if units is 'nm_per_mon': for x in range(dHdx.lon.size): for y in range(dHdx.lat.size): Tx[t, y, x] = V_max(months)*((30*24*60*60)/1852) * dHdx.data[t, y, x] * taxis_scale * (1000*1.852*60 * math.cos(dHdx.lat[y]*math.pi/180)) * 1/(60*60*24*30) Ty[t, y, x] = V_max(months)*((30*24*60*60)/1852) * dHdy.data[t, y, x] * taxis_scale * (1000*1.852*60) * 1/(60*60*24*30) else: for x in range(dHdx.lon.size): for y in range(dHdx.lat.size): Tx[t, y, x] = V_max(months) * dHdx.data[t, y, x] * taxis_scale * (1000*1.852*60 * math.cos(dHdx.lat[y]*math.pi/180))# / ((1 / 1000. / 1.852 / 60.) / math.cos(dHdx.lat[y]*math.pi/180)) Ty[t, y, x] = V_max(months) * dHdy.data[t, y, x] * taxis_scale * (1000*1.852*60)#/ (1 / 1000. / 1.852 / 60.) return [Field('Tx', Tx, dHdx.lon, dHdx.lat, time=dHdx.time, interp_method='nearest', allow_time_extrapolation=True), Field('Ty', Ty, dHdx.lon, dHdx.lat, time=dHdx.time, interp_method='nearest', allow_time_extrapolation=True)] def Create_SEAPODYM_Diffusion_Field(H, timestep=30*24*60*60, sigma=0.1769952864978924, c=0.662573993401526, P=3, start_age=4, Vmax_slope=1, units='m_per_s', diffusion_boost=0, diffusion_scale=1, sig_scale=1, c_scale=1, verbose=True): # Old parameters sigma=0.1999858740340303, c=0.9817751085550976, K = np.zeros(np.shape(H.data), dtype=np.float32) months = start_age age = months*30*24*60*60 for t in range(H.time.size): # Increase age in months if required, to incorporate appropriate Vmax # months in SEAPODYM are all assumed to be 30 days long #age = H.time[t] - H.time[0] + start_age*30*24*60*60 # this is for 'true' ageing age = (start_age+t)*30*24*60*60 if age - (months*30*24*60*60) >= (30*24*60*60): months += 1 if verbose: print('age in days = %s' % (age/(24*60*60))) print("Calculating diffusivity for fish aged %s months" % months) if units == 'nm_per_mon': Dmax = (np.power(GetLengthFromAge(months)*((30*24*60*60)/1852), 2) / 4 ) * timestep/(60*60*24*30) #vmax = L for diffusion else: Dmax = (np.power(GetLengthFromAge(months), 2) / 4) * timestep #fixed b parameter for diffusion sig_D = sigma * Dmax for x in range(H.lon.size): for y in range(H.lat.size): K[t, y, x] = sig_scale * sig_D * (1 - c_scale * c * np.power(H.data[t, y, x], P)) * diffusion_scale + diffusion_boost return Field('K', K, H.lon, H.lat, time=H.time, interp_method='nearest', allow_time_extrapolation=True) def Create_SEAPODYM_Grid(forcing_files, startD=None, startD_dims=None, forcing_vars={'U': 'u', 'V': 'v', 'H': 'habitat'}, forcing_dims={'lon': 'lon', 'lat': 'lon', 'time': 'time'}, K_timestep=30*24*60*60, diffusion_file=None, field_units='m_per_s', diffusion_dims={'lon': 'longitude', 'lat': 'latitude', 'time': 'time', 'data': 'skipjack_diffusion_rate'}, scaleH=None, start_age=4, output_density=False, diffusion_scale=1, sig_scale=1, c_scale=1, verbose=False): if startD_dims is None: startD_dims = forcing_dims if verbose: print("Creating Grid\nLoading files:") for f in forcing_files.values(): print(f) grid = FieldSet.from_netcdf(filenames=forcing_files, variables=forcing_vars, dimensions=forcing_dims, vmin=-200, vmax=1e34, interp_method='nearest', allow_time_extrapolation=True) print(forcing_files['U']) Depthdata = Field.from_netcdf('u', dimensions={'lon': 'longitude', 'lat': 'latitude', 'time': 'time', 'depth': 'depth'}, filenames=forcing_files['U'], allow_time_extrapolation=True) Depthdata.name = 'bathy' grid.add_field(Depthdata) if startD is not None: grid.add_field(Field.from_netcdf('Start', dimensions=startD_dims, filenames=path.local(startD), vmax=1000, interp_method='nearest', allow_time_extrapolation=True)) if output_density: # Add a density field that will hold particle densities grid.add_field(Field('Density', np.full([grid.U.lon.size, grid.U.lat.size, grid.U.time.size],-1, dtype=np.float64), grid.U.lon, grid.U.lat, depth=grid.U.depth, time=grid.U.time, transpose=True)) LandMask = Create_Landmask(grid) grid.add_field(LandMask) grid.U.data[grid.U.data > 1e5] = 0 grid.V.data[grid.V.data > 1e5] = 0 grid.H.data[grid.H.data > 1e5] = 0 # Scale the H field between zero and one if required if scaleH is not None: grid.H.data /= np.max(grid.H.data) grid.H.data[np.where(grid.H.data < 0)] = 0 grid.H.data *= scaleH # Offline calculate the 'diffusion' grid as a function of habitat if verbose: print("Creating Diffusion Field") if diffusion_file is None: K = Create_SEAPODYM_Diffusion_Field(grid.H, timestep=K_timestep, start_age=start_age, diffusion_scale=diffusion_scale, units=field_units, sig_scale=sig_scale, c_scale=c_scale, verbose=verbose) else: if verbose: print("Loading from file: %s" % diffusion_file) K = Field.from_netcdf('K', diffusion_dims, [diffusion_file], interp_method='nearest', vmax=1000000) if diffusion_units == 'nm2_per_mon': K.data *= 1.30427305 grid.add_field(K) if verbose: print("Calculating H Gradient Fields") dHdx, dHdy = getGradient(grid.H, grid.LandMask) grid.add_field(dHdx) grid.add_field(dHdy) #gradients = grid.H.gradient() #for field in gradients: # grid.add_field(field) if verbose: print("Calculating Taxis Fields") T_Fields = Create_SEAPODYM_Taxis_Fields(grid.dH_dx, grid.dH_dy, start_age=start_age, units=field_units) for field in T_Fields: grid.add_field(field) if verbose: print("Creating combined Taxis and Advection field") grid.add_field(Field('TU', grid.U.data+grid.Tx.data, grid.U.lon, grid.U.lat, time=grid.U.time, vmin=-200, vmax=1e34, interp_method='nearest', allow_time_extrapolation=True))# units=unit_converters('spherical')[0])) grid.add_field(Field('TV', grid.V.data+grid.Ty.data, grid.U.lon, grid.U.lat, time=grid.U.time, vmin=-200, vmax=1e34, interp_method='nearest', allow_time_extrapolation=True))#, units=unit_converters('spherical')[1])) if verbose: print("Calculating K Gradient Fields") #K_gradients = grid.K.gradient() #for field in K_gradients: # grid.add_field(field) dKdx, dKdy = getGradient(grid.K, grid.LandMask, False) grid.add_field(dKdx) grid.add_field(dKdy) grid.K.interp_method = grid.dK_dx.interp_method = grid.dK_dy.interp_method = grid.H.interp_method = \ grid.dH_dx.interp_method = grid.dH_dy.interp_method = grid.U.interp_method = grid.V.interp_method = 'nearest' #grid.K.allow_time_extrapolation = grid.dK_dx.allow_time_extrapolation = grid.dK_dy.allow_time_extrapolation = \ # grid.H.allow_time_extrapolation = grid.dH_dx.allow_time_extrapolation = \ # grid.dH_dy.allow_time_extrapolation = grid.U.allow_time_extrapolation = \ # grid.V.allow_time_extrapolation = True return grid def Field_from_DYM(filename, name=None, xlim=None, ylim=None, fromyear=None, frommonth=0, toyear=None, tomonth=0): if name is None: name = str.split(filename, '/')[-1] print("Name = %s" % name) def lat_to_j(lat, latmax, deltaY): j = (int) ((latmax - lat)/deltaY + 1.5) return j-1 def lon_to_i(lon, lonmin, deltaX): if lon < 0: lon = lon+360 i = (int) ((lon - lonmin)/deltaX + 1.5) return i-1 def get_tcount_start(zlevel, nlevel, date): n = 0 while date > zlevel[n] and n < (nlevel-1): n += 1 return n def get_tcount_end(zlevel, nlevel, date): n = nlevel-1 while date < zlevel[n] and n > 0: n -= 1 return n class DymReader: # Map well-known type names into struct format characters. typeNames = { 'int32' :'i', 'uint32' :'I', 'int64' :'q', 'uint64' :'Q', 'float' :'f', 'double' :'d', 'char' :'s'} DymInputSize = 4 def __init__(self, fileName): self.file = open(fileName, 'rb') def read(self, typeName): typeFormat = DymReader.typeNames[typeName.lower()] scale = 1 if(typeFormat is 's'): scale = self.DymInputSize typeSize = struct.calcsize(typeFormat) * scale value = self.file.read(typeSize) decoded = struct.unpack(typeFormat*scale, value) #print(decoded) decoded = [x for x in decoded] if(typeFormat is 's'): decoded = ''.join(decoded) return decoded return decoded[0] def move(self, pos): self.file.seek(pos, 1) def close(self): self.file.close() if xlim is not None: x1 = xlim[0] x2 = xlim[1] else: x1 = x2 = 0 if ylim is not None: y1 = ylim[0] y2 = ylim[1] else: y1 = y2 = 0 file = DymReader(filename) # Get header print("-- Reading .dym file --") idformat = file.read('char') print("ID Format = %s" % idformat) idfunc = file.read('int32') print("IF Function = %s" % idfunc) minval = file.read('float') print("minval = %s" % minval) maxval = file.read('float') print("maxval = %s" % maxval) nlon = file.read('int32') print("nlon = %s" % nlon) nlat = file.read('int32') print("nlat = %s" % nlat) nlevel = file.read('int32') print("nlevel = %s" % nlevel) startdate = file.read('float') print("startdate = %s" % startdate) enddate = file.read('float') print("enddate = %s" % enddate) if fromyear is None: fromyear = np.floor(startdate) if toyear is None: toyear = np.floor(enddate) x = np.zeros([nlat, nlon], dtype=np.float32) y = np.zeros([nlat, nlon], dtype=np.float32) for i in range(nlat): for j in range(nlon): x[i, j] = file.read('float') for i in range(nlat): for j in range(nlon): y[i, j] = file.read('float') dx = x[0, 1] - x[0, 0] dy = y[0, 0] - y[1, 0] i1 = lon_to_i(x1, x[0, 0], dx) i2 = lon_to_i(x2, x[0, 0], dx) j1 = lat_to_j(y2, y[0, 0], dy) j2 = lat_to_j(y1, y[0, 0], dy) if xlim is None: i1 = 0 i2 = nlon if ylim is None: j1 = 0 j2 = nlat nlon_new = i2 - i1 nlat_new = j2 - j1 if xlim is None: nlon_new = nlon nlat_new = nlat i1 = 0 i2 = nlon j1 = 0 j2 = nlat for j in range(nlat_new): for i in range(nlon_new): x[j, i] = x[j+j1, i+i1] y[j, i] = y[j+j1, i+i1] mask = np.zeros([nlat_new, nlon_new], dtype=np.float32) zlevel = np.zeros(nlevel, dtype=np.float32) for n in range(nlevel): zlevel[n] = file.read('float') nlevel_new = nlevel ts1 = 0 firstdate = fromyear + (frommonth-1)/12 #start at the beginning of a given month lastdate = toyear + tomonth/12 ## stop at the end of a given month ts1 = get_tcount_start(zlevel, nlevel, firstdate) ts2 = get_tcount_end(zlevel, nlevel, lastdate) nlevel_new = ts2-ts1+1 zlevel_new = np.zeros(nlevel_new, dtype=np.float32) for n in range(nlevel_new): zlevel_new[n] = zlevel[n+ts1] for j in range(nlat): for i in range(nlon): temp = file.read('int32') if i2 > i >= i1 and j2 > j >= j1: mask[j-j1, i-i1] = temp data = np.zeros([nlevel_new, nlat_new, nlon_new], dtype=np.float32) t_count = ts1 if t_count < 0: t_count = 0 print("Start reading data time series skipping %s and reading for %s time steps" % (t_count, nlevel_new)) nbytetoskip = nlon*nlat*t_count * 4 file.move(nbytetoskip) val = 0 for n in range(nlevel_new): for j in range(nlat)[::-1]: for i in range(nlon): val = file.read('float') if i2 > i >= i1 and j2 > j >= j1: data[n, j-j1, i-i1] = val*1852/(30*24*60*60) #Convert from nm/m to m/s file.close() # Create datetime objects for t index times = [0] * nlevel_new dt = np.round((enddate-startdate)/nlevel*365) for t in range(nlevel_new): times[t] = datetime(int(fromyear + np.floor(t/12)), (t%12)+1, 15, 0, 0, 0) origin = datetime(1970, 1, 1, 0, 0, 0) times_in_s = times for t in range(len(times)): times_in_s[t] = (times[t] - origin).total_seconds() times_in_s = np.array(times_in_s, dtype=np.float32) return Field(name, data, lon=x[0,:], lat=y[:,0][::-1], time=times_in_s, time_origin=origin) def Create_TaggedFish_Class(type=JITParticle): class TaggedFish(type): monthly_age = Variable("monthly_age", dtype=np.int32) age = Variable('age', to_write=False) Vmax = Variable('Vmax', to_write=False) Dv_max = Variable('Dv_max', to_write=False) H = Variable('H', to_write=False) Dx = Variable('Dx', to_write=False) Dy = Variable('Dy', to_write=False) Cx = Variable('Cx', to_write=False) Cy = Variable('Cy', to_write=False) Vx = Variable('Vx', to_write=False) Vy = Variable('Vy', to_write=False) Ax = Variable('Ax', to_write=False) Ay = Variable('Ay', to_write=False) taxis_scale = Variable('taxis_scale', to_write=False) release_time = Variable('release_time', dtype=np.float32, initial=0, to_write=False) def __init__(self, *args, **kwargs): """Custom initialisation function which calls the base initialisation and adds the instance variable p""" super(TaggedFish, self).__init__(*args, **kwargs) self.setAge(4.) self.H = self.Dx = self.Dy = self.Cx = self.Cy = self.Vx = self.Vy = self.Ax = self.Ay = 0 self.taxis_scale = 0 self.active = 0 self.release_time = 0 def setAge(self, months): self.age = months*30*24*60*60 self.monthly_age = int(self.age/(30*24*60*60)) self.Vmax = V_max(self.monthly_age) return TaggedFish def getSEAPODYMarguments(run="SEAPODYM_2003"): args = {} if run == "SEAPODYM_2003": args.update({'ForcingFiles': {'U': 'SEAPODYM_Forcing_Data/Latest/PHYSICAL/2003Run/2003run_PHYS_month*.nc', 'V': 'SEAPODYM_Forcing_Data/Latest/PHYSICAL/2003Run/2003run_PHYS_month*.nc', 'H': 'SEAPODYM_Forcing_Data/Latest/HABITAT/2003Run/INTERIM-NEMO-PISCES_skipjack_habitat_index_*.nc', 'start': 'SEAPODYM_Forcing_Data/Latest/DENSITY/INTERIM-NEMO-PISCES_skipjack_cohort_20021015_density_M0_20030115.nc', 'E': 'SEAPODYM_Forcing_Data/Latest/FISHERIES/P3_E_Data.nc'}}) args.update({'ForcingVariables': {'U': 'u', 'V': 'v', 'H': 'skipjack_habitat_index', 'start': 'skipjack_cohort_20021015_density_M0', 'E': 'P3'}}) args.update({'LandMaskFile': 'SEAPODYM_Forcing_Data/Latest/PHYSICAL/2003Run/2003run_PHYS_month01.nc'}) args.update({'Filestems': {'U': 'm', 'V': 'm', 'H': 'd'}}) args.update({'Kernels': ['Advection_C', 'LagrangianDiffusion', 'TaxisRK4', 'FishingMortality', 'NaturalMortality', 'MoveWithLandCheck', 'AgeAnimal']}) if run == "DiffusionTest": print("in") args.update({'ForcingFiles': {'U': 'DiffusionExample/DiffusionExampleCurrents.nc', 'V': 'DiffusionExample/DiffusionExampleCurrents.nc', 'H': 'DiffusionExample/DiffusionExampleHabitat.nc'}}) args.update({'ForcingVariables': {'U': 'u', 'V': 'v', 'H': 'skipjack_habitat_index'}}) args.update({'Filestems': {'U': 'm', 'V': 'm', 'H': 'd'}}) args.update({'Kernels': ['LagrangianDiffusion', 'Move', 'MoveOffLand']}) return args <file_sep>from parcels import Field from netCDF4 import Dataset import numpy as np from argparse import ArgumentParser def calculateDensities(pfile, limits=[120, 290, -45, 45], p_var=None, output='Density'): print(pfile) particles = Dataset(pfile, 'r') lon = particles.variables['lon'] lat = particles.variables['lat'] #active = particles.variables['active'] time = particles.variables['time'] if p_var is not None: p_var = particles.variables[p_var] #lon = lon[range(0,10000), :] #lat = lat[range(0,10000), :] #active = particles.variables['active'] #time = time[range(0,10000), :] class ParticleTrack(object): lon = [] lat = [] def __init__(self, lon, lat, active=1): self.lon = lon self.lat = lat # for t in range(len(lon)): # #if active[t] == 1: # self.pos[t,:,0] = lon[t] # self.pos[t,0,:] = lat[t] Particles = [] print('Shape of data') print(np.shape(lon)) print(np.shape(lat)) print(np.shape(time)) #print('Making particles...') #for p in range(len(lon[:,0])): # Particles.append(ParticleTrack(lon[p,:], lat[p,:]))#, active)) lons = np.arange(limits[0], limits[1]+1) lats = np.arange(limits[2], limits[3]+1) month_time = np.arange(time[0,1], time[0,-1], 30*24*60*60) blank = np.zeros([len(month_time), len(lats), len(lons)], dtype=np.float32) DensityField = Field("TagDensity", blank, lon=lons, lat=lats, time=month_time) print(np.shape(DensityField.data)) print('Calculating Density...') for t in range(len(month_time)): mid_month = month_time[t] + (30*24*60*60)/2 mid_month_i = np.argmin(abs(time[0,:] - mid_month)) print(mid_month_i) DensityField.data[t, :, :] = np.transpose(density(DensityField, lon, lat, mid_month_i, particle_val=p_var, relative=True, area_scale=False)) DensityField.write('%s_density' % output) def density(field, lons, lats, index = 0, particle_val=None, relative=False, area_scale=True): Density = np.zeros((field.lon.size, field.lat.size), dtype=np.float32) half_lon = (field.lon[1] - field.lon[0])/2 half_lat = (field.lat[1] - field.lat[0])/2 # Kick out particles that are not within the limits of our density field particles = (lons[:,index] > (np.min(field.lon)-half_lon)) * (lons[:,index] < (np.max(field.lon)+half_lon)) * \ (lats[:,index] > (np.min(field.lat)-half_lat)) * (lats[:,index] < (np.max(field.lat)+half_lat)) particles = np.where(particles)[0] print('Number of individuals = %s' % len(particles)) # For each particle, find closest vertex in x and y and add 1 or val to the count if particle_val is not None: for p in particles: Density[np.argmin(np.abs(lons[p,index] - field.lon)), np.argmin(np.abs(lats[p,index] - field.lat))] \ += particle_val[p,index] else: for p in particles: nearest_lon = np.argmin(np.abs(lons[p,index] - field.lon)) nearest_lat = np.argmin(np.abs(lats[p,index] - field.lat)) Density[nearest_lon, nearest_lat] += 1 if relative: Density /= len(particles) if area_scale: area = np.zeros(np.shape(field.data[0, :, :]), dtype=np.float32) dx = (field.lon[1] - field.lon[0]) * 1852 * 60 * np.cos(field.lat*np.pi/180) dy = (field.lat[1] - field.lat[0]) * 1852 * 60 for y in range(len(field.lat)): area[y, :] = dy * dx[y] # Scale by cell area Density /= np.transpose(area) #print(Density[np.where(Density > 0)]) return Density if __name__ == "__main__": p = ArgumentParser(description="""Calculation of density fields from particle trajectory NetCDFs""") p.add_argument('-p', '--pfile', default='none', help='Particle file from which to calculate densities') p.add_argument('-l', '--limits', nargs=4, type=float, default=[120, 290, -45, 45], help='Spatial lon/lat limits over which to calculate densities') p.add_argument('-v', '--variable', type=str, default='none', help='Particle variable with which to calculate density (default is just the number of particles') p.add_argument('-o', '--output', default='DensityRatio', help='Output file name') args = p.parse_args() if args.pfile == 'none': print("No particle file provided!") else: if args.variable is 'none': args.variable = None calculateDensities(args.pfile, args.limits, args.variable, args.output) <file_sep>from Tag_Release import * if __name__ == "__main__": p = ArgumentParser(description=""" Example of underlying habitat field""") p.add_argument('mode', choices=('scipy', 'jit'), nargs='?', default='scipy', help='Execution mode for performing RK4 computation') p.add_argument('-p', '--particles', type=int, default=10, help='Number of particles to advect') p.add_argument('--profiling', action='store_true', default=False, help='Print profiling information after run') p.add_argument('-g', '--grid', type=int, default=None, help='Generate grid file with given dimensions') p.add_argument('-f', '--files', default=['/short/e14/jsp561/OFAM/ocean_u_1993_01.TropPac.nc', '/short/e14/jsp561/OFAM/ocean_v_1993_01.TropPac.nc', '/short/e14/jsp561/OFAM/ocean_phy_1993_01.nc'], help='List of NetCDF files to load') p.add_argument('-v', '--variables', default=['U', 'V', 'H'], help='List of field variables to extract, using PARCELS naming convention') p.add_argument('-n', '--netcdf_vars', default=['u', 'v', 'phy'], help='List of field variable names, as given in the NetCDF file. Order must match --variables args') p.add_argument('-d', '--dimensions', default=['lat', 'lon', 'time'], help='List of PARCELS convention named dimensions across which field variables occur') p.add_argument('-m', '--map_dimensions', default=['yu_ocean', 'xu_ocean', 'Time'], help='List of dimensions across which field variables occur, as given in the NetCDF files, to map to the --dimensions args') p.add_argument('-t', '--time', type=int, default=15, help='List of dimensions across which field variables occur, as given in the NetCDF files, to map to the --dimensions args') p.add_argument('-o', '--output', default='TagRelease', help='List of NetCDF files to load') p.add_argument('-ts', '--timestep', type=int, default=86400, help='Length of timestep in seconds, defaults to one day') p.add_argument('-s', '--starttime', type=int, default=None, help='Time of tag release (seconds since 1-1-1970)') p.add_argument('-l', '--location', type=float, nargs=2, default=[180,0], help='Release location (lon,lat)') args = p.parse_args() filename = '/short/e14/jsp561/' + args.output U = args.files[0] V = args.files[1] H = args.files[2] grid = Create_SEAPODYM_Grid(forcingU=U, forcingV=V, forcingH=H, Uname=args.netcdf_vars[0], Vname=args.netcdf_vars[1], Hname=args.netcdf_vars[2], dimLat=args.map_dimensions[0], dimLon=args.map_dimensions[1], dimTime=args.map_dimensions[2], scaleH=1.5, start_age=12) TagRelease(grid, location=args.location, start=args.starttime, individuals=args.particles, timestep=args.timestep, time=args.time, output_file=filename, mode=args.mode) <file_sep># IKAMOANA Individual-based Kinesis, Advection, and Movement of Ocean ANimAls simulator - An extension of PARCELS for pelagic ecologists <file_sep>from parcels import * from SEAPODYM_functions import * from Behaviour import * from py import path from glob import glob import numpy as np import math from argparse import ArgumentParser def Drifter(): grid = Grid.from_netcdf(filenames={'U':'/Volumes/4TB SAMSUNG/Ocean_Model_Data/OFAM_month1/ocean_u_1993_01.TropPac.nc', 'V':'/Volumes/4TB SAMSUNG/Ocean_Model_Data/OFAM_month1/ocean_v_1993_01.TropPac.nc'}, variables={'U':'u', 'V':'v'}, dimensions={'lon':'xu_ocean', 'lat':'yu_ocean','time':'Time'}, vmin=-200, vmax=200) drifterset = grid.ParticleSet(size=5, pclass=ScipyParticle, lon=np.linspace(152, 153,5), lat=np.linspace(-8, -6, 5)) drifterset.execute(AdvectionRK4, endtime=grid.time[0]+(60*60*24*30), dt=60*60, output_file=drifterset.ParticleFile(name="drifter_results"), interval=60*60) def Diffuser(): grid = Grid.from_netcdf(filenames={'U':'/Volumes/4TB SAMSUNG/Ocean_Model_Data/OFAM_month1/ocean_u_1993_01.TropPac.nc', 'V':'/Volumes/4TB SAMSUNG/Ocean_Model_Data/OFAM_month1/ocean_v_1993_01.TropPac.nc'}, variables={'U':'u', 'V':'v'}, dimensions={'lon':'xu_ocean', 'lat':'yu_ocean','time':'Time'}, vmin=-200, vmax=200) grid.add_field(CreateGradientField(grid)) K_gradients = grid.K.gradient() for field in K_gradients: grid.add_field(field) Diffuser = Create_Particle_Class(ScipyParticle) print(np.mean(grid.U.lon)) print(np.mean(grid.U.lat)) diffuserset = grid.ParticleSet(size=5, pclass=Diffuser, lon=[np.mean(grid.U.lon)+0.5]*5, lat=[np.mean(grid.U.lat)+0.5]*5) diffuserset.execute(diffuserset.Kernel(LagrangianDiffusion) + diffuserset.Kernel(Move), endtime=grid.time[0]+(60*60*24*30), dt=60*60, output_file=diffuserset.ParticleFile(name="diffuser_results"), interval=60*60) grid.write('diffusergrid') def Climber(): grid = Grid.from_netcdf(filenames={'U':'/Volumes/4TB SAMSUNG/Ocean_Model_Data/OFAM_month1/ocean_u_1993_01.TropPac.nc', 'V':'/Volumes/4TB SAMSUNG/Ocean_Model_Data/OFAM_month1/ocean_v_1993_01.TropPac.nc'}, variables={'U':'u', 'V':'v'}, dimensions={'lon':'xu_ocean', 'lat':'yu_ocean','time':'Time'}, vmin=-200, vmax=200) grid.add_field(CreateGradientField(grid, name='H')) H_gradients = grid.H.gradient() for field in H_gradients: grid.add_field(field) Climber = Create_Particle_Class(ScipyParticle) climberset = grid.ParticleSet(size=5, pclass=Climber, lon=[np.mean(grid.U.lon)+1, np.mean(grid.U.lon)-1, np.mean(grid.U.lon), np.mean(grid.U.lon), np.mean(grid.U.lon)-2], lat=[np.mean(grid.U.lat), np.mean(grid.U.lat), np.mean(grid.U.lat)+1, np.mean(grid.U.lat)-1, np.mean(grid.U.lat)+2]) climberset.execute(climberset.Kernel(GradientRK4_C) + climberset.Kernel(Move), endtime=grid.time[0]+(60*60*24*30), dt=60*60, output_file=climberset.ParticleFile(name="climber_results"), interval=60*60) def CreateGradientField(grid, name='K',mu=None): """Generate a simple gradient field containing a single maxima and gaussian gradient """ depth = np.zeros(1, dtype=np.float32) time = grid.time lon, lat = np.arange(grid.U.lon[0], grid.U.lon[-1], 10), np.arange(grid.U.lat[0], grid.U.lat[-1], 10) K = np.zeros((lon.size, lat.size, time.size), dtype=np.float32) if mu is None: mu = [np.mean(grid.U.lon), np.mean(grid.U.lat)] def MVNorm(x, y, mu=[0, 0], sigma=[[1, 0], [0, 1]]): mu_x = mu[0] mu_y = mu[1] sigma = np.array(sigma) sig_x = sigma[0, 0] sig_y = sigma[1, 1] sig_xy = sigma[1, 0] pd = 1/(2 * np.pi * sig_x * sig_y * np.sqrt(1 - sig_xy)) pd = pd * np.exp(-1 / (2 * (1 - np.power(sig_xy, 2))) * ( ((np.power(x - mu_x, 2)) / np.power(sig_x, 2)) + ((np.power(y - mu_y, 2)) / np.power(sig_y, 2)) - ((2 * sig_xy * (x - mu_x) * (y - mu_y)) / (sig_x * sig_y)))) return pd sig = [[0.3, 0], [0, 0.3]] for i, x in enumerate(lon): for j, y in enumerate(lat): K[i, j, :] = MVNorm(x, y, mu, sig) # Boost to provide enough force for our gradient climbers K_Field = Field(name, K, lon, lat, depth, time, transpose=True) return K_Field def Create_Particle_Class(type=JITParticle): class SimpleFish(type): Vmax = Variable('Vmax') def __init__(self, *args, **kwargs): """Custom initialisation function which calls the base initialisation and adds the instance variable p""" super(SimpleFish, self).__init__(*args, **kwargs) self.Vmax=0.1 self.Dx = self.Dy = self.Cx = self.Cy = self.Vx = self.Vy = self.Ax = self.Ay = 0 self.taxis_dampen = 1000 return SimpleFish if __name__ == "__main__": p = ArgumentParser(description=""" Example of underlying habitat field""") p.add_argument('mode', choices=('scipy', 'jit'), nargs='?', default='scipy', help='Execution mode for performing RK4 computation') p.add_argument('-p', '--particles', type=int, default=10, help='Number of particles to advect') p.add_argument('-t', '--type', default='drifter', help='The example type (drifter, diffuser or climber)') args = p.parse_args() if args.type == 'drifter': print("go!") Drifter() if args.type == 'diffuser': Diffuser() if args.type == 'climber': Climber() <file_sep>from parcels import Field, Grid from SEAPODYM_functions import * from argparse import ArgumentParser import numpy as np import math def dym2netcdf(dymfile, outputfile, variable="SEAPODYM_Var"): if variable is None: variable="SEAPODYM_Var" dymfield = Field_from_DYM(dymfile, variable) dymfield.write(outputfile) def dymKconversion(dymfile, outputfile): dymfield = Field_from_DYM(dymfile, 'K') scale_m = np.zeros(np.shape(dymfield.data[0, :, :]), dtype=np.float32) seconds_in_month = 30*24*60*60 for i in range(np.shape(scale_m)[1]): for j in range(np.shape(scale_m)[0]): scale_m[j, i] = ((1000*1.852*60) * (1000*1.852*60*math.cos(dymfield.lat[j]*math.pi/180)))/seconds_in_month print(scale_m) for t in range(len(dymfield.time)): dymfield.data[t, :, :] *= scale_m dymfield.write(outputfile) if __name__ == "__main__": p = ArgumentParser() p.add_argument('-d', '--dymfile', type=str, help='file name of .dym file') p.add_argument('-o', '--outputfile', type=str, help='output filename') p.add_argument('-v', '--variable', type=str, default=None, help='name of variable in .dym file') p.add_argument('-s', '--scale', type=bool, default=False, help='scale dym file from degrees/month') args = p.parse_args() if args.scale is True: dymKconversion(args.dymfile, args.outputfile) else: dym2netcdf(args.dymfile, args.outputfile, args.variable) <file_sep>from parcels import * from Behaviour import * import numpy as np from SEAPODYM_functions import * from argparse import ArgumentParser def delaystart(particle, grid, time, dt): if time > particle.deployed: particle.active = 1 def delayedAdvectionRK4(particle, grid, time, dt): if particle.active == 1: u1 = grid.U[time, particle.lon, particle.lat] v1 = grid.V[time, particle.lon, particle.lat] lon1, lat1 = (particle.lon + u1*.5*dt, particle.lat + v1*.5*dt) u2, v2 = (grid.U[time + .5 * dt, lon1, lat1], grid.V[time + .5 * dt, lon1, lat1]) lon2, lat2 = (particle.lon + u2*.5*dt, particle.lat + v2*.5*dt) u3, v3 = (grid.U[time + .5 * dt, lon2, lat2], grid.V[time + .5 * dt, lon2, lat2]) lon3, lat3 = (particle.lon + u3*dt, particle.lat + v3*dt) u4, v4 = (grid.U[time + dt, lon3, lat3], grid.V[time + dt, lon3, lat3]) particle.lon += (u1 + 2*u2 + 2*u3 + u4) / 6. * dt particle.lat += (v1 + 2*v2 + 2*v3 + v4) / 6. * dt def FADRelease(grid, lons=[0], lats=[0], individuals=100, deploy_times=None, timestep=21600, time=30, output_file='FADRelease', mode='scipy'): starttime = grid.time[0] print("Start = %s (%s)" % (starttime, datetime.fromtimestamp(starttime))) ParticleClass = JITParticle if mode == 'jit' else ScipyParticle class FAD(ParticleClass): deployed = Variable('deployed', dtype=np.float32) fadset = grid.ParticleSet(size=individuals, pclass=FAD, lon=lons, lat=lats) for f in range(len(fadset.particles)): fadset.particles[f].deployed = deploy_times[f]#-starttime#(deploy_times[f]-datetime.fromtimestamp(starttime+(22*365*24*60*60))).total_seconds() fadset.particles[f].active = -1 print(fadset.particles[f].deployed) print(datetime.fromtimestamp(fadset.particles[f].deployed)) print("Starting Sim") fadset.execute(fadset.Kernel(delayedAdvectionRK4) + fadset.Kernel(delaystart), starttime=starttime, endtime=starttime+time*timestep, dt=timestep, output_file=fadset.ParticleFile(name=output_file+"_results"), interval=timestep)#, density_field=density_field) if __name__ == "__main__": p = ArgumentParser(description=""" Example of underlying habitat field""") p.add_argument('mode', choices=('scipy', 'jit'), nargs='?', default='jit', help='Execution mode for performing RK4 computation') #p.add_argument('-f', '--files', default=['/short/e14/jsp561/OFAM/ocean_u_1993_01.TropPac.nc', '/short/e14/jsp561/OFAM/ocean_v_1993_01.TropPac.nc', '/short/e14/jsp561/OFAM/ocean_phy_1993_01.nc'], # help='List of NetCDF files to load') p.add_argument('-f', '--files', default=['/Volumes/4TB SAMSUNG/Ocean_Model_Data/OFAM_month1/ocean_u_1993_01.TropPac.nc', '/Volumes/4TB SAMSUNG/Ocean_Model_Data/OFAM_month1/ocean_v_1993_01.TropPac.nc'], help='List of NetCDF files to load') p.add_argument('-de', '--deployment_file', default="Test_FAD_Deployments.txt", help='List of NetCDF files to load') p.add_argument('-v', '--variables', default=['U', 'V', 'H'], help='List of field variables to extract, using PARCELS naming convention') p.add_argument('-n', '--netcdf_vars', default=['u', 'v', 'phy'], help='List of field variable names, as given in the NetCDF file. Order must match --variables args') p.add_argument('-d', '--dimensions', default=['lat', 'lon', 'time'], help='List of PARCELS convention named dimensions across which field variables occur') p.add_argument('-m', '--map_dimensions', default=['yu_ocean', 'xu_ocean', 'Time'], help='List of dimensions across which field variables occur, as given in the NetCDF files, to map to the --dimensions args') p.add_argument('-t', '--time', type=int, default=800, help='List of dimensions across which field variables occur, as given in the NetCDF files, to map to the --dimensions args') p.add_argument('-o', '--output', default='FADRelease', help='List of NetCDF files to load') p.add_argument('-ts', '--timestep', type=int, default=3600, help='Length of timestep in seconds, defaults to one day') p.add_argument('-s', '--starttime', type=int, default=None, help='Time of tag release (seconds since 1-1-1970)') p.add_argument('-l', '--location', type=float, nargs=2, default=[180,0], help='Release location (lon,lat)') args = p.parse_args() #filename = '/short/e14/jsp561/' + args.output U = args.files[0] V = args.files[1] filenames = {'U': args.files[0], 'V': args.files[1]} variables = {'U': args.netcdf_vars[0], 'V': args.netcdf_vars[1]} dimensions = {'lon': args.map_dimensions[1], 'lat': args.map_dimensions[0], 'time': args.map_dimensions[2]} grid = Grid.from_netcdf(filenames=filenames, variables=variables, dimensions=dimensions, vmin=-200, vmax=200) # Load FAD deployment data D_file = open(args.deployment_file, 'r') vars = D_file.readline().split() D_vars = {} print("Deployment file contains:") for v in vars: print("- %s" % v) D_vars.update({v: []}) for line in D_file: for v in range(len(vars)): D_vars[vars[v]].append(line.split()[v]) N_FADs = len(D_vars['"time"']) times = [float(v) for v in D_vars['"time"']] shift = (datetime(1992,1,1) - datetime(1970,1,1)).total_seconds() grid.time += shift FADRelease(grid, lons=[float(v) for v in D_vars['"lon"']], lats=[float(v) for v in D_vars['"lat"']], deploy_times=times, individuals=N_FADs, timestep=args.timestep, time=args.time, output_file=args.output, mode=args.mode) <file_sep>from netCDF4 import Dataset import numpy as np from argparse import ArgumentParser from parcels import Field def calculateDensityRatio(dfiles, output): Fields = [] for dfile in dfiles: print("Loading %s" % dfile) Fields.append(Field.from_netcdf(dfile, dimensions={'lon': 'nav_lon', 'lat': 'nav_lat', 'time': 'time_counter', 'data': 'TagDensity'}, filenames=[dfile])) limits = [0, 0, 0, 0] limits[0] = np.max([field.lon[0] for field in Fields]) limits[1] = np.min([field.lon[-1] for field in Fields]) limits[2] = np.max([field.lat[0] for field in Fields]) limits[3] = np.min([field.lat[-1] for field in Fields]) #limits[1] = (np.min(field.lon[-1]) for field in Fields) #limits[2] = (np.max(field.lat[0]) for field in Fields) #limits[3] = (np.min(field.lat[-1]) for field in Fields) time_lim = [np.max([field.time[0] for field in Fields]), np.min([field.time[-1] for field in Fields])] #time_lim = [Fields[0].time[0], Fields[0].time[-1]] lon = np.arange(start=limits[0], stop=limits[1]+1, dtype=np.float32) lat = np.arange(start=limits[2], stop=limits[3]+1, dtype=np.float32) time = np.arange(time_lim[0], time_lim[1]+1, 30*24*60*60, dtype=np.float32) Ratio = np.zeros([len(time), len(lat), len(lon)], dtype=np.float32) print(limits) print(Fields[0].lon) print(Fields[1].lon) print(lon) print(Fields[0].lat) print(Fields[1].lat) print(lat) print(Fields[0].time) print(Fields[1].time) print(time) for t in range(len(time)): for x in range(len(lon)): for y in range(len(lat)): tagged = Fields[0].data[np.where(Fields[0].time == time[t])[0][0], np.where(Fields[0].lat == lat[y])[0][0], np.where(Fields[0].lon == lon[x])[0][0]] pop = Fields[1].data[np.where(Fields[1].time == time[t])[0][0], np.where(Fields[1].lat == lat[y])[0][0], np.where(Fields[1].lon == lon[x])[0][0]] #print('%s - %s' % (tagged, pop)) if pop == 0: Ratio[t, y, x] = 0 else: Ratio[t, y, x] = tagged/pop Ratios = Field('DensityRatio', Ratio, lon, lat, time=time) Ratios.write(filename=output) def Ratio_Test(dfile): Field.from_netcdf(dfile, dimensions={'lon': 'nav_lon', 'lat': 'nav_lat', 'time': 'time_counter', 'data': 'TagDensity'}, filenames=[dfile]) if __name__ == "__main__": p = ArgumentParser(description="""Quick and simple plotting of PARCELS trajectories""") p.add_argument('-d', '--dfiles', nargs=2, default='none', help='Particle density files') p.add_argument('-o', '--output', default='DensityRatio', help='Output file name') args = p.parse_args() if args.dfiles == 'none': print("No particle file provided!") else: calculateDensityRatio(args.dfiles, output=args.output) <file_sep>from parcels import * import numpy as np import math def SampleH(particle, fieldset, time, dt): particle.H = fieldset.H[time, particle.lon, particle.lat, particle.depth] particle.dHdx = fieldset.dH_dx[time, particle.lon, particle.lat, particle.depth] particle.dHdy = fieldset.dH_dy[time, particle.lon, particle.lat, particle.depth] def CheckRelease(particle, fieldset, time, dt): if time > particle.release_time: particle.active = 1 def FishingMortality(particle, fieldset, time, dt): Fmor = (1-(fieldset.F[time, particle.lon, particle.lat, particle.depth] * (dt/(30*24*60*60)))) particle.school = particle.school * Fmor particle.depletionF = Fmor def NaturalMortality(particle, fieldset, time, dt): MPmax=0.3 MPexp=0.1008314958945224 MSmax=0.006109001382111822 MSslope=0.8158285706493162 Mrange=0.00001430156 Mnat = MPmax*math.exp(-MPexp*particle.monthly_age) + MSmax*math.pow(particle.monthly_age, MSslope) Mvar = Mnat * math.pow(1 - Mrange, 1-fieldset.H[time, particle.lon, particle.lat, particle.depth]/2) Nmor = (1 - (Mvar * (dt/(30*24*60*60)))) particle.school = particle.school * Nmor particle.depletionN = Nmor def AgeAnimal(particle, fieldset, time, dt): particle.age += dt if (particle.age - (particle.monthly_age*30*24*60*60)) > (30*24*60*60): particle.monthly_age += 1 def AgeParticle(particle, fieldset, time, dt): #print("Ageing") particle.age += dt if (particle.age - (particle.monthly_age*30*24*60*60)) > (30*24*60*60): particle.monthly_age += 1 # a=2.225841100458143# 0.7343607395421234 old parameters # b=0.8348850216641774# 0.5006692114850767 old parameters # lengths = [3.00, 4.51, 6.02, 11.65, 16.91, 21.83, 26.43, 30.72, 34.73, 38.49, 41.99, 45.27, # 48.33, 51.19, 53.86, 56.36, 58.70, 60.88, 62.92, 64.83, 66.61, 68.27, 69.83, 71.28, # 72.64, 73.91, 75.10, 76.21, 77.25, 78.22, 79.12, 79.97, 80.76, 81.50, 82.19, 82.83, # 83.44, 84.00, 84.53, 85.02, 85.48, 85.91, 86.31, 86.69, 87.04, 87.37, 87.68, 87.96, # 88.23, 88.48, 88.71, 88.93, 89.14, 89.33, 89.51, 89.67, 89.83, 89.97, 90.11, 90.24, # 90.36, 90.47, 90.57, 90.67, 91.16] # L = lengths[(particle.monthly_age-1)]/100 #L = GetLengthFromAge(monthly_age) # vmax = a * math.pow(L, b) # particle.Vmax = vmax # MPmax=0.3 # MPexp=0.1008314958945224 # MSmax=0.006109001382111822 # MSslope=0.8158285706493162 # Mrange=0.00001430156 # Mnat = MPmax*math.exp(-1*MPexp*particle.age) + MSmax*math.pow(particle.age, MSslope) # Hexp = 1-fieldset.H[time, particle.lon, particle.lat, particle.depth]/2 # Mvar = Mnat * math.pow((1 - Mrange), Hexp)#(1-fieldset.H[time, lon, lat]))#/2)) # particle.fish *= 1-Mvar #particle.fish *= 1-Mortality_C(particle.monthly_age, particle.H) def AgeIndividual(particle, fieldset, time, dt): #print("Ageing") particle.age += dt if (particle.age - (particle.monthly_age*30*24*60*60)) > (30*24*60*60): particle.monthly_age += 1 a=2.225841100458143# 0.7343607395421234 old parameters b=0.8348850216641774# 0.5006692114850767 old parameters Alengths = [3.00, 4.51, 6.02, 11.65, 16.91, 21.83, 26.43, 30.72, 34.73, 38.49, 41.99, 45.27, 48.33, 51.19, 53.86, 56.36, 58.70, 60.88, 62.92, 64.83, 66.61, 68.27, 69.83, 71.28, 72.64, 73.91, 75.10, 76.21, 77.25, 78.22, 79.12, 79.97, 80.76, 81.50, 82.19, 82.83, 83.44, 84.00, 84.53, 85.02, 85.48, 85.91, 86.31, 86.69, 87.04, 87.37, 87.68, 87.96, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42] L = lengths[(particle.monthly_age-1)]/100 #L = GetLengthFromAge(monthly_age) vmax = a * math.pow(L, b) particle.Vmax = vmax MPmax=0.3 MPexp=0.1008314958945224 MSmax=0.006109001382111822 MSslope=0.8158285706493162 Mrange=0.00001430156 Mnat = MPmax*math.exp(-1*MPexp*particle.age) + MSmax*math.pow(particle.age, MSslope) Hexp = 1-fieldset.H[time, particle.lon, particle.lat, particle.depth]/2 Mvar = Mnat * math.pow((1 - Mrange), Hexp)#(1-fieldset.H[time, lon, lat, particle.depth]))#/2)) if random.uniform(0, 1) > Mvar: particle.active = 0 particle.release_time = 100000000*100000000 #Particle will not be reactivated particle.lon = 0 particle.lat = 0 def RK4(fieldx, fieldy, lon, lat, time, dt): f_lat = dt / 1000. / 1.852 / 60. f_lon = f_lat / math.cos(lat*math.pi/180) u1 = fieldx[time, lon, lat, particle.depth] v1 = fieldy[time, lon, lat, particle.depth] lon1, lat1 = (lon + u1*.5*f_lon, lat + v1*.5*f_lat) #print('lon1 = %s, lat1 = %s' % (lon1, lat1)) u2, v2 = (fieldx[time + .5 * dt, lon1, lat1, particle.depth], fieldy[time + .5 * dt, lon1, lat1, particle.depth]) lon2, lat2 = (lon + u2*.5*f_lon, lat + v2*.5*f_lat) #print('lon2 = %s, lat2 = %s' % (lon2, lat2)) u3, v3 = (fieldx[time + .5 * dt, lon2, lat2, particle.depth], fieldy[time + .5 * dt, lon2, lat2, particle.depth]) lon3, lat3 = (lon + u3*f_lon, lat + v3*f_lat) #print('lon3 = %s, lat3 = %s' % (lon3, lat3)) u4, v4 = (fieldx[time + dt, lon3, lat3, particle.depth], fieldy[time + dt, lon3, lat3, particle.depth]) Vx = (u1 + 2*u2 + 2*u3 + u4) / 6. Vy = (v1 + 2*v2 + 2*v3 + v4) / 6. return [Vx, Vy] def RK4alt(fieldx, fieldy, lon, lat, time, dt): u1 = fieldx[time, lon, lat, particle.depth] v1 = fieldy[time, lon, lat, particle.depth] lon1, lat1 = (lon + u1*.5*dt, lat + v1*.5*dt) #print('lon1 = %s, lat1 = %s' % (lon1, lat1)) u2, v2 = (fieldx[time + .5 * dt, lon1, lat1, particle.depth], fieldy[time + .5 * dt, lon1, lat1, particle.depth]) lon2, lat2 = (lon + u2*.5*dt, lat + v2*.5*dt) #print('lon2 = %s, lat2 = %s' % (lon2, lat2)) u3, v3 = (fieldx[time + .5 * dt, lon2, lat2, particle.depth], fieldy[time + .5 * dt, lon2, lat2, particle.depth]) lon3, lat3 = (lon + u3*dt, lat + v3*dt) #print('lon3 = %s, lat3 = %s' % (lon3, lat3)) u4, v4 = (fieldx[time + dt, lon3, lat3, particle.depth], fieldy[time + dt, lon3, lat3, particle.depth]) Vx = (u1 + 2*u2 + 2*u3 + u4) / 6. Vy = (v1 + 2*v2 + 2*v3 + v4) / 6. return [Vx, Vy] def GradientRK4(particle, fieldset, time, dt): #print('Taxis') to_lat = 1 / 1000. / 1.852 / 60. to_lon = to_lat / math.cos(particle.lat*math.pi/180) V = RK4(fieldset.dH_dx, fieldset.dH_dy, particle.lon, particle.lat, time, dt) #V = [fieldset.dH_dx[time,particle.lon,particle.lat, particle.depth], fieldset.dH_dy[time,particle.lon,particle.lat, particle.depth]] particle.Vx = V[0] * particle.Vmax * dt * (1000*1.852*60 * math.cos(particle.lat*math.pi/180)) * to_lon particle.Vy = V[1] * particle.Vmax * dt * (1000*1.852*60) * to_lat def GradientRK4_C(particle, fieldset, time, dt): if particle.active == 1: f_lat = dt / 1000. / 1.852 / 60. f_lon = f_lat / math.cos(particle.lat*math.pi/180) ## Something about the below RK4 of dH_dx that C doesn't like (referencing odd field values??) # u1 = fieldset.dH_dx[time, particle.lon, particle.lat, particle.depth] # v1 = fieldset.dH_dy[time, particle.lon, particle.lat, particle.depth] # lon1, lat1 = (particle.lon + u1*.5*f_lon, particle.lat + v1*.5*f_lat) # #print('lon1 = %s, lat1 = %s' % (lon1, lat1)) # u2, v2 = (fieldset.dH_dx[time + .5 * dt, lon1, lat1, particle.depth], fieldset.dH_dy[time + .5 * dt, lon1, lat1, particle.depth]) # lon2, lat2 = (particle.lon + u2*.5*f_lon, particle.lat + v2*.5*f_lat) # #print('lon2 = %s, lat2 = %s' % (lon2, lat2)) # u3, v3 = (fieldset.dH_dx[time + .5 * dt, lon2, lat2, particle.depth], fieldset.dH_dy[time + .5 * dt, lon2, lat2, particle.depth]) # lon3, lat3 = (particle.lon + u3*f_lon, particle.lat + v3*f_lat) # #print('lon3 = %s, lat3 = %s' % (lon3, lat3)) # u4, v4 = (fieldset.dH_dx[time + dt, lon3, lat3, particle.depth], fieldset.dH_dy[time + dt, lon3, lat3, particle.depth]) # Vx = (u1 + 2*u2 + 2*u3 + u4) / 6. # Vy = (v1 + 2*v2 + 2*v3 + v4) / 6. particle.Vx = fieldset.dH_dx[time, particle.lon, particle.lat, particle.depth] * particle.Vmax * (1000*1.852*60 * math.cos(particle.lat*math.pi/180)) * particle.taxis_scale * f_lon particle.Vy = fieldset.dH_dy[time, particle.lon, particle.lat, particle.depth] * particle.Vmax * (1000*1.852*60) * particle.taxis_scale * f_lat #particle.Vx = Vx #* particle.Vmax #* (1000*1.852*60 * math.cos(particle.lat*math.pi/180)) * f_lon #particle.Vy = Vy #* particle.Vmax * (1000*1.852*60) * f_lat def TaxisRK4(particle, fieldset, time, dt): if particle.active == 1: f_lat = dt / 1000. / 1.852 / 60. f_lon = f_lat / math.cos(particle.lat*math.pi/180) u1 = fieldset.Tx[time, particle.lon, particle.lat, particle.depth] v1 = fieldset.Ty[time, particle.lon, particle.lat, particle.depth] lon1, lat1 = (particle.lon + u1*.5*f_lon, particle.lat + v1*.5*f_lat) u2, v2 = (fieldset.Tx[time + .5 * dt, lon1, lat1, particle.depth], fieldset.Ty[time + .5 * dt, lon1, lat1, particle.depth]) lon2, lat2 = (particle.lon + u2*.5*f_lon, particle.lat + v2*.5*f_lat) u3, v3 = (fieldset.Tx[time + .5 * dt, lon2, lat2, particle.depth], fieldset.Ty[time + .5 * dt, lon2, lat2, particle.depth]) lon3, lat3 = (particle.lon + u3*f_lon, particle.lat + v3*f_lat) u4, v4 = (fieldset.Tx[time + dt, lon3, lat3, particle.depth], fieldset.Ty[time + dt, lon3, lat3, particle.depth]) Vx = (u1 + 2*u2 + 2*u3 + u4) / 6. Vy = (v1 + 2*v2 + 2*v3 + v4) / 6. Vx = Vx * f_lat Vy = Vy * f_lon def CurrentAndTaxisRK4(particle, fieldset, time, dt): if particle.active == 1: u1 = fieldset.TU[time, particle.lon, particle.lat, particle.depth] v1 = fieldset.TV[time, particle.lon, particle.lat, particle.depth] lon1, lat1 = (particle.lon + u1*.5*dt, particle.lat + v1*.5*dt) u2, v2 = (fieldset.TU[time + .5 * dt, lon1, lat1, particle.depth], fieldset.TV[time + .5 * dt, lon1, lat1, particle.depth]) lon2, lat2 = (particle.lon + u2*.5*dt, particle.lat + v2*.5*dt) u3, v3 = (fieldset.TU[time + .5 * dt, lon2, lat2, particle.depth], fieldset.TV[time + .5 * dt, lon2, lat2, particle.depth]) lon3, lat3 = (particle.lon + u3*dt, particle.lat + v3*dt) u4, v4 = (fieldset.TU[time + dt, lon3, lat3, particle.depth], fieldset.TV[time + dt, lon3, lat3, particle.depth]) Vx = (u1 + 2*u2 + 2*u3 + u4) / 6. Vy = (v1 + 2*v2 + 2*v3 + v4) / 6. particle.Ax = Vx * dt particle.Ay = Vy * dt particle.Vx = 0 particle.Vy = 0 def FishDensityClimber(particle, fieldset, time, dt): if particle.active == 1: f_lat3 = dt / 1000. / 1.852 / 60. f_lon3 = f_lat3 / math.cos(particle.lat*math.pi/180) particle.Vx = fieldset.dFishDensity_dx[time, particle.lon, particle.lat, particle.depth] * \ particle.Vmax * (1000*1.852*60 * math.cos(particle.lat*math.pi/180)) * \ particle.taxis_scale * f_lon3 #* fieldset.MaxDensity particle.Vy = fieldset.dFishDensity_dy[time, particle.lon, particle.lat, particle.depth] * \ particle.Vmax * (1000*1.852*60) * \ particle.taxis_scale * f_lat3 #* fieldset.MaxDensity print("Vx= %s Vy= %s" % (particle.Vx, particle.Vy)) def LagrangianDiffusion(particle, fieldset, time, dt): if particle.active == 1: to_lat = 1 / 1000. / 1.852 / 60. to_lon = to_lat / math.cos(particle.lat*math.pi/180) r_var = 1/3. #Rx = np.random.uniform(-1., 1.) #Ry = np.random.uniform(-1., 1.) Rx = random.uniform(-1., 1.) Ry = random.uniform(-1., 1.) #dK = RK4(fieldset.dK_dx, fieldset.dK_dy, particle.lon, particle.lat, time, dt) dKdx, dKdy = (fieldset.dK_dx[time, particle.lon, particle.lat, particle.depth], fieldset.dK_dy[time, particle.lon, particle.lat, particle.depth]) #half_dx = 0.5 * dKdx * dt * to_lon #half_dy = 0.5 * dKdy * dt * to_lat #print(particle.lon + half_dx) #print(particle.lat + half_dy) #K = RK4(fieldset.K, fieldset.K, particle.lon + half_dx, particle.lat + half_dy, time, dt) Kfield = fieldset.K[time, particle.lon, particle.lat, particle.depth] Rx_component = Rx * math.sqrt(2 * Kfield * dt / r_var) * to_lon Ry_component = Ry * math.sqrt(2 * Kfield * dt / r_var) * to_lat CorrectionX = dKdx * dt * to_lon CorrectionY = dKdy * dt * to_lat #print(Rx_component) #print(Ry_component) Dx = Rx_component Dy = Ry_component Cx = CorrectionX Cy = CorrectionY #Dx = Rx_component #Dy = Ry_component #Cx = CorrectionX #Cy = CorrectionY def Advection(particle, fieldset, time, dt): if particle.active == 1: physical_forcing = RK4alt(fieldset.U, fieldset.V, particle.lon, particle.lat, time, dt) particle.Ax = physical_forcing[0] * dt particle.Ay = physical_forcing[1] * dt def Advection_C(particle, fieldset, time, dt): #print("Advection") if particle.active == 1: #to_lat = 1 / 1000. / 1.852 / 60. #to_lon = to_lat / math.cos(particle.lat*math.pi/180) u1 = fieldset.U[time, particle.lon, particle.lat, particle.depth] v1 = fieldset.V[time, particle.lon, particle.lat, particle.depth] lon1, lat1 = (particle.lon + u1*.5*dt, particle.lat + v1*.5*dt) #print('lon1 = %s, lat1 = %s' % (lon1, lat1)) u2, v2 = (fieldset.U[time + .5 * dt, lon1, lat1, particle.depth], fieldset.V[time + .5 * dt, lon1, lat1, particle.depth]) lon2, lat2 = (particle.lon + u2*.5*dt, particle.lat + v2*.5*dt) #print('lon2 = %s, lat2 = %s' % (lon2, lat2)) u3, v3 = (fieldset.U[time + .5 * dt, lon2, lat2, particle.depth], fieldset.V[time + .5 * dt, lon2, lat2, particle.depth]) lon3, lat3 = (particle.lon + u3*dt, particle.lat + v3*dt) #print('lon3 = %s, lat3 = %s' % (lon3, lat3)) u4, v4 = (fieldset.U[time + dt, lon3, lat3, particle.depth], fieldset.V[time + dt, lon3, lat3, particle.depth]) Ax = (u1 + 2*u2 + 2*u3 + u4) / 6. Ay = (v1 + 2*v2 + 2*v3 + v4) / 6. Ax = Ax * dt# / to_lon #Convert back to m/s so we save to particle file in a usual format Ay = Ay * dt# / to_lat def RandomWalkDiffusion(particle, fieldset, time, dt): to_lat = 1 / 1000. / 1.852 / 60. to_lon = to_lat / math.cos(particle.lat*math.pi/180) dK = RK4(fieldset.dK_dx, fieldset.dK_dy, particle.lon, particle.lat, time, dt) half_dx = 0.5 * dK[0] * to_lon * dt half_dy = 0.5 * dK[1] * to_lat * dt Rand = np.random.uniform(0, 1.) K_at_half = RK4(fieldset.K, fieldset.K, particle.lon + half_dx, particle.lat + half_dy, time, dt)[0] R = Rand * K_at_half * dt #np.sqrt(4 * K_at_half * dt) angle = np.random.uniform(0, 2*np.pi) CorrectionX = dK[0] * dt * to_lon CorrectionY = dK[1] * dt * to_lat particle.Cx = CorrectionX particle.Cy = CorrectionY particle.Dx = R*np.cos(angle) * to_lon particle.Dy = R*np.sin(angle) * to_lat def UndoMove(particle, fieldset, time, dt): print("UndoMove triggered! Moving particle") print("from: %s | %s" % (particle.lon, particle.lat)) temp_lon = particle.lon temp_lat = particle.lat particle.lon = particle.prev_lon particle.lat = particle.prev_lat #particle.Ax = particle.Ay = particle.Dx = particle.Dy = particle.Cx = particle.Cy = particle.Vx = particle.Vy = 0.0 #particle.lon = 200 #particle.lat = 0 print("to: %s | %s" % (particle.lon, particle.lat)) if particle.lon == temp_lon and particle.lat == temp_lat: print("Positions are the same, seems particle got stuck... ################## DISABLING PARTICLE ############################# ") particle.active = 0 def MoveOffLand(particle, fieldset, time, dt): onland = fieldset.LandMask[0, particle.lon, particle.lat, particle.depth] if onland == 1: oldlon = particle.lon - particle.Ax - particle.Dx - particle.Cx - particle.Vx oldlat = particle.lat - particle.Ay - particle.Dy - particle.Cy - particle.Vy lat_convert = 1 / 1000. / 1.852 / 60. lon_convert = to_lat / math.cos(oldlat*math.pi/180) Kfield_new = fieldset.K[time, oldlon, oldlat, particle.depth] r_var_new = 1/3. Dx_component = math.sqrt(2 * Kfield_new * dt / r_var_new) * lon_convert Dy_component = math.sqrt(2 * Kfield_new * dt / r_var_new) * lat_convert count = 0 particle.In_Loop = 0 while onland > 0: #return ErrorCode.ErrorOutOfBounds #print("particle on land at %s|%s" % (particle.lon, particle.lat)) particle.lon -= particle.Dx particle.lat -= particle.Dy Rx_new = random.uniform(-1., 1.) Ry_new = random.uniform(-1., 1.) particle.Dx = Dx_component * Rx_new particle.Dy = Dy_component * Ry_new particle.lon += particle.Dx particle.lat += particle.Dy onland = fieldset.LandMask[0, particle.lon, particle.lat, particle.depth] #print("attempting move to %s|%s" % (particle.lon, particle.lat)) #print("onland now = %s" % onland) count += 1 particle.In_Loop += 1 if count > 100: particle.lon -= particle.Ax + (particle.Dx + particle.Cx + particle.Vx)# * to_lon particle.lat -= particle.Ay + (particle.Dy + particle.Cy + particle.Vy)# * to_lat particle.Ax = particle.Ay = particle.Dx = particle.Dy = particle.Cx = particle.Cy = particle.Vx = particle.Vy = 0.0 onland = 0 # Kernel to call a generic particle update function def Update(particle, fieldset, time, dt): particle.update() def MoveWithLandCheck(particle, fieldset, time, dt): if particle.active == 1: particle.prev_lon = particle.lon particle.prev_lat = particle.lat adv_x = Ax + Vx adv_y = Ay + Vy if adv_x > 2: adv_x = 2 if adv_y > 2: adv_y = 2 onland = 1 loop_count = 0 while onland > 0: #print('in loop %s' % loop_count) move_x = adv_x + Dx + Cx move_y = adv_y + Dy + Cy onland = 0 jump_loop = 0 while jump_loop < 8: particle.lon += move_x/8 particle.lat += move_y/8 onland += fieldset.LandMask[0, particle.lon, particle.lat, particle.depth] jump_loop += 1 if onland > 0: #print("got an onland %s" % loop_count) particle.lon = particle.prev_lon particle.lat = particle.prev_lat to_lat = 1 / 1000. / 1.852 / 60. to_lon = to_lat / math.cos(particle.lat*math.pi/180) r_var = 1/3. Rx = random.uniform(-1., 1.) Ry = random.uniform(-1., 1.) dKdx, dKdy = (fieldset.dK_dx[time, particle.lon, particle.lat, particle.depth], fieldset.dK_dy[time, particle.lon, particle.lat, particle.depth]) Kfield = fieldset.K[time, particle.lon, particle.lat, particle.depth] Rx_component = Rx * math.sqrt(2 * Kfield * dt / r_var) * to_lon Ry_component = Ry * math.sqrt(2 * Kfield * dt / r_var) * to_lat CorrectionX = dKdx * dt * to_lon CorrectionY = dKdy * dt * to_lat Dx = Rx_component Dy = Ry_component Cx = CorrectionX Cy = CorrectionY loop_count += 1 particle.In_Loop += 1 if loop_count > 100: onland = 0 particle.lon = particle.prev_lon particle.lat = particle.prev_lat else: if particle.prev_lat < -8.5 and particle.lat > -8.5: if particle.prev_lon < 146.5 and particle.lon > 146.5: onland = 1 # Hardcoded check for illegal Coral to Solomon Sea moves elif particle.lat < -8.5 and particle.prev_lat > -8.5: if particle.lon < 146.5 and particle.prev_lon > 146.5: onland = 1 # Hardcoded check for illegal Coral to Solomon Sea moves if particle.prev_lat > -5.5 and particle.lat < -5.5: if particle.prev_lon < 150.5 and particle.lon > 150.5: onland = 1 # Hardcoded check for illegal Bismarck to Solomon Sea moves elif particle.lat > -5.5 and particle.prev_lat < -5.5: if particle.lon < 150.5 and particle.prev_lon > 150.5: onland = 1 # Hardcoded check for illegal Bismarck to Solomon Sea moves def Move(particle, fieldset, time, dt): if particle.active == 1: #to_lat = 1 / 1000. / 1.852 / 60. #to_lon = to_lat / math.cos(particle.lat*math.pi/180) #print("Ax=%s Dx=%s Cx=%s Vx=%s dHdx=%s at time %s" % (particle.Ax , particle.Dx, particle.Cx, particle.Vx, particle.dHdx, time)) #print("Ay=%s Dy=%s Cy=%s Vy=%s dHdy=%s at time %s" % (particle.Ay , particle.Dy, particle.Cy, particle.Vy, particle.dHdy, time)) particle.prev_lon = particle.lon particle.prev_lat = particle.lat adv_x = particle.Ax + particle.Vx adv_y = particle.Ay + particle.Vy if adv_x > 2: adv_x = 2 if adv_y > 2: adv_y = 2 particle.lon += adv_x + (particle.Dx + particle.Cx)# * to_lon particle.lat += adv_y + (particle.Dy + particle.Cy)# * to_lat #particle.lon += particle.Ax + particle.Vx #particle.lat += particle.Ay + particle.Vy #particle.lon += Dx + Cx #particle.lat += Dy + Cy # Some simple movement kernels for testing purposes: def MoveEast(particle, fieldset, time, dt): if particle.active == 1: to_lat = 1 / 1000. / 1.852 / 60. to_lon = to_lat / math.cos(particle.lat*math.pi/180) particle.lon += 3 * dt * to_lon def MoveWest(particle, fieldset, time, dt): if particle.active == 1: to_lat = 1 / 1000. / 1.852 / 60. to_lon = to_lat / math.cos(particle.lat*math.pi/180) particle.lon -= 3 * dt * to_lon def RegionBound(particle, fieldset, time, dt): if particle.active == 1: if fieldset.minlon > particle.lon or fieldset.maxlon < particle.lon: particle.active = 0 if fieldset.minlat > particle.lat or fieldset.maxlat < particle.lat: particle.active = 0
781432d820b17a7e9bdd4956052095c1df8c85cb
[ "Markdown", "Python" ]
19
Python
Jacketless/IKAMOANA
fcaad055419ddb58d0901771a6feca0f67dd3bd5
37ed27c9cab76489961884dc09ba572bbf31e3b5
refs/heads/master
<file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Session; use App\Models\Question; use App\Models\User; use App\Models\Activity; class DashboardController extends Controller { public function home(){ $basicQuestions = Question::where('level', 'basic')->get(); $intemediateQuestions = Question::where('level', 'intermediate')->get(); $advancedQuestions = Question::where('level', 'advanced')->get(); $questions = Question::paginate(20); $all_users=User::all(); $all_questions=Question::all(); $users = User::paginate(20); $data = array( 'basicQuestions' => $basicQuestions, 'intemediateQuestions' => $intemediateQuestions, 'advancedQuestions' => $advancedQuestions, 'users'=>$users, 'questions'=>$questions, 'all_users'=>$all_users, 'all_questions'=>$all_questions ); \View::share('data', $data); return view('pages.home'); } public function users(){ $users = User::paginate(20); return view('pages.users')->withUsers($users); } public function addUserForm(){ return view('pages.add_user'); } public function user($id){ $user = User::find($id); $activity = "Viewed ".$user->name."'s".' '."Profile"; $user_id = auth()->user()->id; $acti = new Activity; $acti->activity = $activity; $acti->user_id = $user_id; $acti->save(); $activities = Activity::where('user_id', $id)->latest()->get(); $data = array( "user"=>$user, "activities"=>$activities ); return view('pages.user')->withData($data); } public function deleteUser(Request $request){ $userId = $request->id; $user = User::find($userId); $user->delete(); $acti = new Activity; $acti->activity = "Deleted User: ".$user->name; $acti->user_id = auth()->user()->id; $acti->save(); Session::flash('message','User Deleted Successfully!'); Session::flash('alert-class','alert-success'); return back(); } public function questions(){ $questions = Question::paginate(20); return view('pages.questions')->withQuestions($questions); } public function addQuestion(Request $request){ $request->validate([ 'question' => 'bail|required|unique:questions', 'user_id' => 'required', ]); if(Question::create($request->all())) { $activity = "Added A question: ".$request->question; $user_id = auth()->user()->id; $acti = new Activity; $acti->activity = $activity; $acti->user_id = $user_id; $acti->save(); Session::flash('message','Question Added Successfully!'); Session::flash('alert-class','alert-success'); }else{ Session::flash('message','Error encountered!'); Session::flash('alert-class','alert-danger'); } return back(); } public function addQuestionForm(){ return view('pages.add_question'); } //Display Question Update Form public function updateQuestionForm($id){ $questionId =$id; $question = Question::find($questionId); return view('pages.edit_question')->withQuestion($question); } //Display Question Update Form public function updateQuestion(Request $request){ $questionId = $request->id; $question = Question::find($questionId); $request->validate([ 'question' => 'bail|required|unique:questions', 'user_id' => 'required', ]); $question->question = $request->question; $question->user_id = $request->user_id; $question->difficulty = $request->difficulty; $question->level = $request->level; $question->subject = $request->subject; $question->save(); $activity = "Updated question: ".$request->question; $user_id = auth()->user()->id; $acti = new Activity; $acti->activity = $activity; $acti->user_id = $user_id; $acti->save(); Session::flash('message','Question Updated Successfully!'); Session::flash('alert-class','alert-success'); return redirect('/dashboard/questions'); } public function deleteQuestion(Request $request){ $questionId = $request->id; $question = Question::find($questionId); $question->delete(); $acti = new Activity; $acti->activity = "Deleted Question: ".$question->question; $acti->user_id = auth()->user()->id; $acti->save(); Session::flash('message','Question Deleted Successfully!'); Session::flash('alert-class','alert-success'); return back(); } } <file_sep><?php use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('welcome'); }); Route::get('/dashboard/home','App\Http\Controllers\DashboardController@home')->middleware('is_admin'); Route::get('/dashboard/users','App\Http\Controllers\DashboardController@users')->middleware('is_admin'); Route::get('/dashboard/users/add','App\Http\Controllers\DashboardController@addUserForm')->middleware('is_admin'); Route::get('/dashboard/users/{id}','App\Http\Controllers\DashboardController@user')->middleware('is_admin'); Route::post('/dashboard/users/delete/{id}','App\Http\Controllers\DashboardController@deleteUser')->name('user.delete')->middleware('is_admin'); Route::get('/dashboard/questions','App\Http\Controllers\DashboardController@questions')->middleware('is_admin'); Route::get('/dashboard/questions/add','App\Http\Controllers\DashboardController@addQuestionForm')->middleware('is_admin'); Route::post('/dashboard/questions/add','App\Http\Controllers\DashboardController@addQuestion')->name('questions.add')->middleware('is_admin'); Route::get('/dashboard/questions/{id}','App\Http\Controllers\DashboardController@question')->middleware('is_admin'); Route::get('/dashboard/questions/update/{id}','App\Http\Controllers\DashboardController@updateQuestionForm')->name('questions.updat')->middleware('is_admin'); Route::post('/dashboard/questions/update/{id}','App\Http\Controllers\DashboardController@updateQuestion')->name('questions.update')->middleware('is_admin'); Route::post('/dashboard/questions/delete/{id}','App\Http\Controllers\DashboardController@deleteQuestion')->name('question.delete')->middleware('is_admin'); Route::get('/dashboard/exams/generate','App\Http\Controllers\QuestionsController@generateExamForm')->name('exam.generate')->middleware('is_admin'); Route::post('/dashboard/exams/download','App\Http\Controllers\QuestionsController@downloadExam')->name('exam.download')->middleware('is_admin'); Route::get('/dashboard/exams/paper','App\Http\Controllers\QuestionsController@downloadExam')->name('exam.paper')->middleware('is_admin'); // Route::get('/dashboard/exams/paper/download','App\Http\Controllers\QuestionsController@download')->name('exam.download')->middleware('is_admin'); Route::get('/questions','App\Http\Controllers\QuestionsController@questions'); Route::middleware(['auth:sanctum', 'verified'])->get('/dashboard', function () { return Inertia\Inertia::render('Dashboard'); })->name('dashboard'); <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Question; use App\Models\User; use PDF; class QuestionsController extends Controller { public function questions(){ $questions = Question::all(); return response()->json($questions); } public function generateExamForm(){ $questions = Question::all(); return view('pages.generate_exam')->withQuestions($questions); } public function downloadExam(Request $request){ $questions = Question::where('level', $request->level) ->where('subject', $request->subject) ->where('difficulty', $request->difficulty) ->get(); return view('pages.exam')->withQuestions($questions); } } <file_sep><?php namespace Database\Factories; use App\Models\Question; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Str; class QuestionFactory extends Factory { /** * The name of the factory's corresponding model. * * @var string */ protected $model = Question::class; /** * Define the model's default state. * * @return array */ public function difficulty(){ $difficulties = ['basic', 'intermediate', 'advanced']; return $difficulties[array_rand($difficulties)]; } public function levels(){ $levels =['Form 1', 'Form 2', 'Form 3', 'Form 4']; return $levels [array_rand($levels)]; } public function definition() { return [ 'question' => $this->faker->sentence, 'difficulty' => $this->difficulty(), 'level' => $this->levels(), 'user_id' => mt_rand(0, 50), // password ]; } } <file_sep>-- phpMyAdmin SQL Dump -- version 5.0.2 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Oct 20, 2020 at 09:24 PM -- Server version: 10.4.13-MariaDB -- PHP Version: 7.4.7 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `ems` -- -- -------------------------------------------------------- -- -- Table structure for table `activities` -- CREATE TABLE `activities` ( `id` bigint(20) UNSIGNED NOT NULL, `user_id` bigint(20) UNSIGNED NOT NULL, `activity` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `activities` -- INSERT INTO `activities` (`id`, `user_id`, `activity`, `created_at`, `updated_at`) VALUES (1, 151, 'Viewed <NAME>\'s Profile', '2020-10-17 03:15:40', '2020-10-17 03:15:40'), (2, 151, 'Viewed Mr. <NAME> PhD\'s Profile', '2020-10-17 03:17:05', '2020-10-17 03:17:05'), (3, 151, 'Viewed Mr. <NAME> PhD\'s Profile', '2020-10-17 03:31:39', '2020-10-17 03:31:39'), (4, 151, 'Viewed Mr. <NAME> PhD\'s Profile', '2020-10-17 03:32:25', '2020-10-17 03:32:25'), (5, 151, 'Viewed Mr. <NAME> PhD\'s Profile', '2020-10-17 03:32:29', '2020-10-17 03:32:29'), (6, 151, 'Viewed Mr. <NAME> PhD\'s Profile', '2020-10-17 03:35:08', '2020-10-17 03:35:08'), (7, 151, 'Viewed Mr. <NAME> PhD\'s Profile', '2020-10-17 03:37:44', '2020-10-17 03:37:44'), (8, 151, 'Viewed <NAME>\'s Profile', '2020-10-17 03:38:27', '2020-10-17 03:38:27'), (9, 151, 'Viewed <NAME>\'s Profile', '2020-10-17 03:39:50', '2020-10-17 03:39:50'), (10, 151, 'Viewed Mr. <NAME> PhD\'s Profile', '2020-10-17 03:43:48', '2020-10-17 03:43:48'), (11, 151, 'Viewed <NAME>\'s Profile', '2020-10-18 19:27:14', '2020-10-18 19:27:14'), (12, 151, 'Added A question: What is sociology?', '2020-10-18 19:52:19', '2020-10-18 19:52:19'), (13, 151, 'Viewed <NAME>\'s Profile', '2020-10-18 19:52:46', '2020-10-18 19:52:46'); -- -------------------------------------------------------- -- -- Table structure for table `failed_jobs` -- CREATE TABLE `failed_jobs` ( `id` bigint(20) UNSIGNED NOT NULL, `uuid` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `connection` text COLLATE utf8mb4_unicode_ci NOT NULL, `queue` text COLLATE utf8mb4_unicode_ci NOT NULL, `payload` longtext COLLATE utf8mb4_unicode_ci NOT NULL, `exception` longtext COLLATE utf8mb4_unicode_ci NOT NULL, `failed_at` timestamp NOT NULL DEFAULT current_timestamp() ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `migrations` -- CREATE TABLE `migrations` ( `id` int(10) UNSIGNED NOT NULL, `migration` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `batch` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `migrations` -- INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (1, '2014_10_12_000000_create_users_table', 1), (2, '2014_10_12_100000_create_password_resets_table', 1), (3, '2019_08_19_000000_create_failed_jobs_table', 1), (5, '2014_10_12_200000_add_two_factor_columns_to_users_table', 2), (6, '2019_12_14_000001_create_personal_access_tokens_table', 2), (7, '2020_10_16_172354_create_sessions_table', 2), (8, '2020_10_17_055833_create_activities_table', 3), (9, '2020_10_16_132627_create_questions_table', 4); -- -------------------------------------------------------- -- -- Table structure for table `password_resets` -- CREATE TABLE `password_resets` ( `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `token` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `personal_access_tokens` -- CREATE TABLE `personal_access_tokens` ( `id` bigint(20) UNSIGNED NOT NULL, `tokenable_type` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `tokenable_id` bigint(20) UNSIGNED NOT NULL, `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `token` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL, `abilities` text COLLATE utf8mb4_unicode_ci DEFAULT NULL, `last_used_at` timestamp NULL DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `questions` -- CREATE TABLE `questions` ( `id` bigint(20) UNSIGNED NOT NULL, `question` text COLLATE utf8mb4_unicode_ci NOT NULL, `difficulty` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'basic', `user_id` int(11) DEFAULT NULL, `level` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `subject` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `questions` -- INSERT INTO `questions` (`id`, `question`, `difficulty`, `user_id`, `level`, `subject`, `created_at`, `updated_at`) VALUES (1, 'What is Biochemistry?', 'basic', 151, 'year1', 'Biochemistry', '2020-10-18 11:30:21', '2020-10-18 11:30:21'), (2, 'Who is the father of Financial Accounting?', 'basic', 151, 'year1', 'BCOM', '2020-10-18 11:40:07', '2020-10-18 11:40:07'), (3, 'Describe the science zoology', 'basic', 151, 'year1', 'zoology', '2020-10-18 11:43:38', '2020-10-18 11:43:38'), (4, 'What is Computer Programming?', 'basic', 151, 'year1', 'Computer Science', '2020-10-18 11:44:35', '2020-10-18 11:44:35'), (5, 'What is biochemical Production?', 'basic', 151, 'year1', 'Biochemistry', '2020-10-18 19:47:55', '2020-10-18 19:47:55'), (6, 'What is sociology?', 'basic', 151, 'year1', 'Sociology', '2020-10-18 19:52:18', '2020-10-18 19:52:18'); -- -------------------------------------------------------- -- -- Table structure for table `sessions` -- CREATE TABLE `sessions` ( `id` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `user_id` bigint(20) UNSIGNED DEFAULT NULL, `ip_address` varchar(45) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `user_agent` text COLLATE utf8mb4_unicode_ci DEFAULT NULL, `payload` text COLLATE utf8mb4_unicode_ci NOT NULL, `last_activity` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `sessions` -- INSERT INTO `sessions` (`id`, `user_id`, `ip_address`, `user_agent`, `payload`, `last_activity`) VALUES ('cLdXCDqIttQ9CDl5QJUkll9T0mqeAOnFBSpAZbfd', 151, '127.0.0.1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36', '<KEY> 1603217091), ('<KEY>', NULL, '127.0.0.1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36', '<KEY> 1603210996); -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `id` bigint(20) UNSIGNED NOT NULL, `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `rank` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'user', `username` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `email_verified_at` timestamp NULL DEFAULT NULL, `password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `two_factor_secret` text COLLATE utf8mb4_unicode_ci DEFAULT NULL, `two_factor_recovery_codes` text COLLATE utf8mb4_unicode_ci DEFAULT NULL, `remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `users` -- INSERT INTO `users` (`id`, `name`, `email`, `rank`, `username`, `email_verified_at`, `password`, `two_factor_secret`, `two_factor_recovery_codes`, `remember_token`, `created_at`, `updated_at`) VALUES (101, '<NAME>', '<EMAIL>', 'teacher', 'cheyenne97', '2020-10-16 12:23:14', '$2y$10$vbqzEs/IWO02ykqO9AYFP.tKIxlk4fRiHmtxyaRiD5wUjcR/inFSi', NULL, NULL, 'uvqsKkCEMM', '2020-10-16 12:23:20', '2020-10-16 12:23:20'), (102, '<NAME>', '<EMAIL>', 'student', 'dangelo.daniel', '2020-10-16 12:23:14', '$2y$10$KZmDRl.j6BxSw3BQ/bT2w.zGGfq.GtLv6udoDv0jnXAvMn7VNw3PW', NULL, NULL, 'gaUIXFCKGW', '2020-10-16 12:23:20', '2020-10-16 12:23:20'), (103, 'Mr. <NAME> PhD', '<EMAIL>', 'teacher', 'mose13', '2020-10-16 12:23:14', '$2y$10$GoieFYoduHhWS2l3wkUl.eAO9J4IX19.x6ErEck/8h6ayWIHUx5g.', NULL, NULL, '38ckI74er7', '2020-10-16 12:23:20', '2020-10-16 12:23:20'), (104, '<NAME>', 'dess<EMAIL>', 'student', 'gusikowski.tomasa', '2020-10-16 12:23:14', '$2y$10$EYLF/18PH/tPV2vxrOVrueqqFVgY.SgkREF.HCIE7aQXZBR5n28/i', NULL, NULL, 'k7QhmQcJWe', '2020-10-16 12:23:21', '2020-10-16 12:23:21'), (105, '<NAME>.', '<EMAIL>', 'teacher', 'clyde.gottlieb', '2020-10-16 12:23:14', '$2y$10$2.57dM1DU9wX4WILWzc6xuOAXcgC42divivXaQuPkSwxSlbG4RG3S', NULL, NULL, 'Cc8MkmLPVW', '2020-10-16 12:23:21', '2020-10-16 12:23:21'), (106, 'Prof. <NAME>', '<EMAIL>', 'student', 'nparisian', '2020-10-16 12:23:14', '$2y$10$7/pR4WUFKNTsjCdDwe3jQ.AmuyZW0dxIALYNF4Zu9O8Fa4KatOHJe', NULL, NULL, 'XNSBkmVHMQ', '2020-10-16 12:23:21', '2020-10-16 12:23:21'), (107, '<NAME>', '<EMAIL>', 'teacher', 'hirthe.ryann', '2020-10-16 12:23:14', '$2y$10$iKb38ZYqrD6lo.2XwqpjCeQYbuGl.0BS57djRv61HAHUZa5KjpMze', NULL, NULL, '9BjsHVmafa', '2020-10-16 12:23:21', '2020-10-16 12:23:21'), (108, 'Dr. <NAME> Sr.', '<EMAIL>', 'student', 'bart.hudson', '2020-10-16 12:23:15', '$2y$10$kvjP0SgzChaxcoxQR5H/AuA8OQEyr4lTcq1SmPm90oRIox3PW.dRy', NULL, NULL, '9o6o99Paze', '2020-10-16 12:23:21', '2020-10-16 12:23:21'), (109, '<NAME>', '<EMAIL>', 'teacher', 'schoen.melisa', '2020-10-16 12:23:15', '$2y$10$vqD81Z/dLfYY1zvfGliZkuOcYJQg8H4F56ARKoDwbC/JdCucc4xQi', NULL, NULL, 'IcGVncn0ac', '2020-10-16 12:23:21', '2020-10-16 12:23:21'), (110, 'Ms. <NAME> V', '<EMAIL>', 'student', 'pierre.rempel', '2020-10-16 12:23:15', '$2y$10$pfWK1AvJozgsoL.7ffa0ReyldIKukW.laM4kCrfhb94S7w37qLqL6', NULL, NULL, 'A8e8dxYESZ', '2020-10-16 12:23:21', '2020-10-16 12:23:21'), (111, '<NAME>', '<EMAIL>', 'student', 'born', '2020-10-16 12:23:15', '$2y$10$cdx6wCOz7E9b2yZjqH1g/uSIuDpIz2YW8BQtr5TP0r699aEOSPx9G', NULL, NULL, 'VLUHVwGkHJ', '2020-10-16 12:23:21', '2020-10-16 12:23:21'), (112, '<NAME>', '<EMAIL>', 'student', 'spencer.alison', '2020-10-16 12:23:15', '$2y$10$Ylmk1jdAZ0T7p4/iaiYhruoO8K6OTixGXKYRvtam0RY0OFJxf1b7i', NULL, NULL, 'mIDEjWjhnA', '2020-10-16 12:23:22', '2020-10-16 12:23:22'), (113, '<NAME>', '<EMAIL>', 'student', 'mohr.melvin', '2020-10-16 12:23:15', '$2y$10$0VBO8YMao8sd9gONaSOcye2pD2sJjN6Le89Ky.A11.V8QxdLNx1.a', NULL, NULL, 'nKSGHlMv5V', '2020-10-16 12:23:22', '2020-10-16 12:23:22'), (114, 'Prof. <NAME> DVM', '<EMAIL>', 'student', 'kjacobson', '2020-10-16 12:23:15', '$2y$10$GWn04XEUFwVfhviD/nYi3e5zCzFa6S85NBFpUypnJzjS8NwW8C5Lu', NULL, NULL, 'tf6utkwCwS', '2020-10-16 12:23:23', '2020-10-16 12:23:23'), (115, '<NAME>', '<EMAIL>', 'student', 'fritchie', '2020-10-16 12:23:15', '$2y$10$XjT1eUrWf23rKCBeGpzQxOOh50eofW/M0iKfIz32ebem7244pIHhu', NULL, NULL, 'UGYnlYTCUD', '2020-10-16 12:23:23', '2020-10-16 12:23:23'), (116, '<NAME>', '<EMAIL>', 'teacher', 'noemy75', '2020-10-16 12:23:16', '$2y$10$dQiGNTs8TuwGPonKH2trPOqpL4Af3L4IDtCEz6bxjQMkZVKlqWl2C', NULL, NULL, 'vKtTV98q2u', '2020-10-16 12:23:23', '2020-10-16 12:23:23'), (117, '<NAME>', '<EMAIL>', 'student', 'hand.nya', '2020-10-16 12:23:16', '$2y$10$mnTzSDDq.X1YBf8AgMQWyeqJwHGSzXNDzz2zjwZ5IS1XLPxdpfHVi', NULL, NULL, '6GGLj7cv24', '2020-10-16 12:23:24', '2020-10-16 12:23:24'), (118, '<NAME>', '<EMAIL>', 'student', 'crawford69', '2020-10-16 12:23:16', '$2y$10$Pbe7y9aNxnBCL874dFuoE.eJ02yzrrhGKOmFOZvWjZbFY8N.gua8m', NULL, NULL, 'Q93T0y02c1', '2020-10-16 12:23:24', '2020-10-16 12:23:24'), (119, '<NAME> DVM', '<EMAIL>', 'teacher', 'johnson.zachariah', '2020-10-16 12:23:16', '$2y$10$ZxyVmdoTJfcxWBuLlzNgue56k/a0oy3zFb/I6iJwuMGYrRLbl2BNq', NULL, NULL, 'Il81uYo7qW', '2020-10-16 12:23:24', '2020-10-16 12:23:24'), (120, '<NAME> Sr.', '<EMAIL>', 'teacher', 'amedhurst', '2020-10-16 12:23:16', '$2y$10$mG3/t4lLouwBxYLin1A6iOV3OotA8yx.J2h2Gv43P6y7m8BOKonAm', NULL, NULL, 'mXyNdyHvC9', '2020-10-16 12:23:24', '2020-10-16 12:23:24'), (121, '<NAME>', '<EMAIL>', 'teacher', 'kris.yvette', '2020-10-16 12:23:16', '$2y$10$cfDUtMmoBvYmzZL1Gr.n3e35DQ7yXwS2CHd.rlMNPdULPXJfgeiBW', NULL, NULL, 'lT3yYxf0XV', '2020-10-16 12:23:25', '2020-10-16 12:23:25'), (122, '<NAME>', '<EMAIL>', 'teacher', 'lbradtke', '2020-10-16 12:23:16', '$2y$10$WkuAqF6khGq4C5cmrzOYMug3iobvS4sFxRlbRYZgwHziNZVLgx0/m', NULL, NULL, '9uxzDP0Q1i', '2020-10-16 12:23:25', '2020-10-16 12:23:25'), (123, '<NAME>', '<EMAIL>', 'teacher', 'travis.torp', '2020-10-16 12:23:17', '$2y$10$XqsZZQk0rcr7vEb6A5fOXumVn.vMYLnfGaDBIwBzFvq1ATzoC/Vm2', NULL, NULL, 'epGMFkHxuV', '2020-10-16 12:23:25', '2020-10-16 12:23:25'), (124, 'Mr. <NAME>', '<EMAIL>', 'teacher', 'garrick.kilback', '2020-10-16 12:23:17', '$2y$10$o3lyKx0b3L6SmdZClC9CNu4nzLRYo8OdrMLVuVasJ6yif9XVcKrnS', NULL, NULL, 'h8TqBUIUBj', '2020-10-16 12:23:25', '2020-10-16 12:23:25'), (125, '<NAME>', '<EMAIL>', 'teacher', 'violette.leuschke', '2020-10-16 12:23:17', '$2y$10$njRYRVE7n.oBQq2xmjpHiOvcS/l6HjNg3AvqyfLSzRuIpIE1Skzxa', NULL, NULL, 'gNyiv2TQR7', '2020-10-16 12:23:25', '2020-10-16 12:23:25'), (126, '<NAME> Sr.', '<EMAIL>', 'student', 'kris.gina', '2020-10-16 12:23:17', '$2y$10$mUdAx2YAWXFlvvd0WXBIY.w2J50ApTIq7ec6KyNBckexWJJRRhxCS', NULL, NULL, 'f4308mJI3Z', '2020-10-16 12:23:25', '2020-10-16 12:23:25'), (127, 'Mellie Senger', '<EMAIL>', 'teacher', 'dominique01', '2020-10-16 12:23:17', '$2y$10$uNAYhCDTdhZwYj7rrWcZjuUA6S/td7inL5bzn4RhOfxC8her8SKii', NULL, NULL, 'rxANH0jZ1S', '2020-10-16 12:23:25', '2020-10-16 12:23:25'), (128, '<NAME> DVM', '<EMAIL>', 'student', 'earline.lueilwitz', '2020-10-16 12:23:17', '$2y$10$kEkhEMWynC9sHtXASHmvc.a9DkCtCVZvt9fLuxwMv.x6Nzt/No9GK', NULL, NULL, 'UAgKB2HKGW', '2020-10-16 12:23:25', '2020-10-16 12:23:25'), (129, '<NAME>', '<EMAIL>', 'student', 'horacio.schimmel', '2020-10-16 12:23:17', '$2y$10$x5QIg3pjt6J.orcWSXuKIO5Z6qGUY51H2W8sdCXYClI9U3aPUkhaC', NULL, NULL, 'TbpmTNVGgw', '2020-10-16 12:23:25', '2020-10-16 12:23:25'), (130, '<NAME>', '<EMAIL>', 'student', 'issac.hirthe', '2020-10-16 12:23:17', '$2y$10$qgQEjnJx9o2n0gIuafGd6.7/dEpP4KLSdUyzoySRV6WZ2bfXCYHmK', NULL, NULL, 'vduEpDpzGd', '2020-10-16 12:23:26', '2020-10-16 12:23:26'), (131, '<NAME>', '<EMAIL>', 'student', 'jannie54', '2020-10-16 12:23:18', '$2y$10$PhZPSsNPxnwjZK9ZSSQTtu9iy82jsS0UklcoGdJSYWIAqv7M1omri', NULL, NULL, 'jhYgofJGeN', '2020-10-16 12:23:26', '2020-10-16 12:23:26'), (132, '<NAME>', '<EMAIL>', 'teacher', 'hansen.christelle', '2020-10-16 12:23:18', '$2y$10$ByxOFyi8PyJv.NMvGfGnfeNkZ/MU5UIu.Ij.mou9vdm4Lyb7z0omS', NULL, NULL, 'EC0LYgfI2O', '2020-10-16 12:23:27', '2020-10-16 12:23:27'), (133, '<NAME>', '<EMAIL>', 'student', 'hoppe.newton', '2020-10-16 12:23:18', '$2y$10$40EOYFipMKxtNBKwKgBBgOY64Xh48KM78eeDlw8v9Fmp/qnmYgY5e', NULL, NULL, 'q2YRUsyFFO', '2020-10-16 12:23:27', '2020-10-16 12:23:27'), (134, '<NAME>', '<EMAIL>', 'teacher', 'gerry.wintheiser', '2020-10-16 12:23:18', '$2y$10$5Kkdl1wzpp6vE4./Vkp.zOaAHw3hzCbnncwXGSc2xJ9sQCDr/Z2te', NULL, NULL, 'ImM6kuL3Cn', '2020-10-16 12:23:27', '2020-10-16 12:23:27'), (135, 'Dr. <NAME>', '<EMAIL>', 'student', 'ullrich.gene', '2020-10-16 12:23:18', '$2y$10$ggd7966XHLBJSxpSiE5Js.0LHGg99CTSpYHhAJ1YvEewSYHOmp5nW', NULL, NULL, 'RtdUG2R0aL', '2020-10-16 12:23:27', '2020-10-16 12:23:27'), (136, 'Prof. <NAME>', '<EMAIL>', 'student', 'madilyn.strosin', '2020-10-16 12:23:18', '$2y$10$FZzEoH7myeEFj4JRyZoUiuu6UQuQgPAbNFlQqxtiQNRw11u4SZdG2', NULL, NULL, 'KZctuMTCyX', '2020-10-16 12:23:27', '2020-10-16 12:23:27'), (137, '<NAME>', '<EMAIL>', 'student', 'dvonrueden', '2020-10-16 12:23:18', '$2y$10$GP3F30wrv50P3rcf/86VMediFiU7B8cN/egCxAOgwzjylOOeAD67K', NULL, NULL, 'pMLO4jm95h', '2020-10-16 12:23:27', '2020-10-16 12:23:27'), (138, '<NAME>', '<EMAIL>', 'student', 'lzulauf', '2020-10-16 12:23:18', '$2y$10$PjT/GHl3f6kK03og39jxyuJRd0holKTEGT3DOUCC3mzhGax8Liw4q', NULL, NULL, 'seOiF0mG3Y', '2020-10-16 12:23:27', '2020-10-16 12:23:27'), (139, '<NAME>', '<EMAIL>', 'student', 'clementine.murray', '2020-10-16 12:23:19', '$2y$10$IgkP34OqnoSvDYDMdiFdGeKeUtKgOvxKz5pcl0Ey8lgOhhlhJeECm', NULL, NULL, 'qSqce2IAHT', '2020-10-16 12:23:27', '2020-10-16 12:23:27'), (140, 'Dr. <NAME>', '<EMAIL>', 'student', 'patrick72', '2020-10-16 12:23:19', '$2y$10$6i/KS5aWJhr6vygFde.LReEhOB2ui4DBlb.vD5uYG0xODDIkQxNe.', NULL, NULL, 'S1XzhOmyHt', '2020-10-16 12:23:28', '2020-10-16 12:23:28'), (141, '<NAME>', '<EMAIL>', 'teacher', 'bahringer.charlie', '2020-10-16 12:23:19', '$2y$10$6iU20aeUgQnwrTDRQsoZ2u6oZ6pcmXBhro4O49HdX.ZLAxGvGRI1a', NULL, NULL, 'o6IlISpu8N', '2020-10-16 12:23:28', '2020-10-16 12:23:28'), (142, '<NAME>', '<EMAIL>', 'student', 'kylie.carter', '2020-10-16 12:23:19', '$2y$10$MCbrxNv5TqYIgfiFBXRlN.U8XlMIvtgqw37XL3L86rEvRYs0wvOVm', NULL, NULL, '0v33D6TCdg', '2020-10-16 12:23:28', '2020-10-16 12:23:28'), (143, '<NAME>', '<EMAIL>', 'teacher', 'dwitting', '2020-10-16 12:23:19', '$2y$10$jf24DOAtzR525ODgr/tF5OCEyxS5l2RwQUwZ5xuh1Em2SLfGQ2EQO', NULL, NULL, 'vdkmi5VCtA', '2020-10-16 12:23:28', '2020-10-16 12:23:28'), (144, '<NAME>', '<EMAIL>', 'student', 'oaltenwerth', '2020-10-16 12:23:19', '$2y$10$h9IMvBr0qaywxppzwWLUe.XbBvHKyupIgk6/qA7f91CpAfc.BwLqO', NULL, NULL, '9F0eXyi3zi', '2020-10-16 12:23:28', '2020-10-16 12:23:28'), (145, 'Prof. <NAME>', '<EMAIL>', 'student', 'brown.crystel', '2020-10-16 12:23:19', '$2y$10$SOYKeTVuWbEXL/7bYBgF/OMJDeQNjnx0Ru7afiSrhgYs9mlxR0RDO', NULL, NULL, 'oWomv3SXUW', '2020-10-16 12:23:28', '2020-10-16 12:23:28'), (146, '<NAME> PhD', '<EMAIL>', 'student', 'vlittel', '2020-10-16 12:23:20', '$2y$10$E4.Cj3aqiAdaEPtauZSjf.peVRcFLtCJ0BWEfT6d6MY0FLgtii7pa', NULL, NULL, 'dz4Mrg4O9M', '2020-10-16 12:23:28', '2020-10-16 12:23:28'), (147, '<NAME>', '<EMAIL>', 'student', 'hgreenfelder', '2020-10-16 12:23:20', '$2y$10$K8x7cL/6jHytzRs2AmecUuBZYkN.YWPCwE0eIs4h3wa/aBtFtXf8S', NULL, NULL, 'uZwCb6FcQi', '2020-10-16 12:23:29', '2020-10-16 12:23:29'), (148, '<NAME>', '<EMAIL>', 'teacher', 'annette.dach', '2020-10-16 12:23:20', '$2y$10$48gJJdMpc3Lr2BmDXZ7lLOOgxtX7p7KhLuj34MCEX6uUIz1pyA4Je', NULL, NULL, 'tSe063c9tx', '2020-10-16 12:23:29', '2020-10-16 12:23:29'), (149, '<NAME>', '<EMAIL>', 'teacher', 'xwunsch', '2020-10-16 12:23:20', '$2y$10$CKXM3C7EZcmsAYJE9UwFIeg9yHNcqiRrgrf1iUiBxMi3fBtEddB.a', NULL, NULL, 'bJ9GCfpDwV', '2020-10-16 12:23:29', '2020-10-16 12:23:29'), (150, 'Mr. <NAME> DDS', '<EMAIL>', 'teacher', 'carolyne.simonis', '2020-10-16 12:23:20', '$2y$10$3WabmAN7WXvDPKuwX9DOVuTCYe1pH57Osn.jEVc85kx7twYAPBTwO', NULL, NULL, '41EDLUl4W9', '2020-10-16 12:23:29', '2020-10-16 12:23:29'), (151, '<NAME>', '<EMAIL>', 'admin', 'Simon', '2020-10-16 12:28:58', '$2y$10$wb0aKDp626ICYEj2xL03I.0waMA7G5wFSXWyd6vS4uYX06s3O9hRG', NULL, NULL, '7HGBUu0lfvtPT2oJGo4t0Vuic5o0nkn9lJb1AKiRUq4aaChsrSyJxvko7dbI', '2020-10-16 12:28:58', '2020-10-16 12:28:58'); -- -- Indexes for dumped tables -- -- -- Indexes for table `activities` -- ALTER TABLE `activities` ADD PRIMARY KEY (`id`), ADD KEY `activities_user_id_foreign` (`user_id`); -- -- Indexes for table `failed_jobs` -- ALTER TABLE `failed_jobs` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `failed_jobs_uuid_unique` (`uuid`); -- -- Indexes for table `migrations` -- ALTER TABLE `migrations` ADD PRIMARY KEY (`id`); -- -- Indexes for table `password_resets` -- ALTER TABLE `password_resets` ADD KEY `password_resets_email_index` (`email`); -- -- Indexes for table `personal_access_tokens` -- ALTER TABLE `personal_access_tokens` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `personal_access_tokens_token_unique` (`token`), ADD KEY `personal_access_tokens_tokenable_type_tokenable_id_index` (`tokenable_type`,`tokenable_id`); -- -- Indexes for table `questions` -- ALTER TABLE `questions` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `questions_question_unique` (`question`) USING HASH; -- -- Indexes for table `sessions` -- ALTER TABLE `sessions` ADD PRIMARY KEY (`id`), ADD KEY `sessions_user_id_index` (`user_id`), ADD KEY `sessions_last_activity_index` (`last_activity`); -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `users_email_unique` (`email`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `activities` -- ALTER TABLE `activities` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14; -- -- AUTO_INCREMENT for table `failed_jobs` -- ALTER TABLE `failed_jobs` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `migrations` -- ALTER TABLE `migrations` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10; -- -- AUTO_INCREMENT for table `personal_access_tokens` -- ALTER TABLE `personal_access_tokens` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `questions` -- ALTER TABLE `questions` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7; -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=152; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
0ca469b96844070a3ce45cd8957d4aa51213d92f
[ "SQL", "PHP" ]
5
PHP
SIMONNABUKO/quizgen
c02e4be71314c521843fd3b6c69f250d605cf17a
1cebc6780806025a5783f2d873b68186e40622c9
refs/heads/main
<repo_name>nekomimi-daimao/BotTestBed<file_sep>/Assets/BotTestBed/Scripts/Runtime/Controller/ControllerBot.cs using System; using UniRx; namespace BotTestBed.Runtime.Controller { public sealed class ControllerBot : ControllerBase { private void OnEnable() { Observable.Interval(TimeSpan.FromSeconds(1)) .TakeUntilDisable(this) .AsUnitObservable() .Subscribe(OnBot); } private void OnBot(Unit _) { stickForce.Value = UnityEngine.Random.insideUnitCircle; jumpPushed.Value = !jumpPushed.Value; } } } <file_sep>/Assets/BotTestBed/Scripts/Runtime/Controller/ControllerBase.cs using UnityEngine; using UniRx; namespace BotTestBed.Runtime.Controller { public abstract class ControllerBase : MonoBehaviour { public Vector2ReactiveProperty stickForce = new Vector2ReactiveProperty(); public IReadOnlyReactiveProperty<Vector2> StickForce => stickForce; public BoolReactiveProperty jumpPushed = new BoolReactiveProperty(); public IReadOnlyReactiveProperty<bool> JumpPushed => jumpPushed; } } <file_sep>/Assets/BotTestBed/Scripts/Runtime/Target/Share/ITargetSharer.cs using Runtime.Executor; namespace Runtime.Target.Share { /// <summary> /// <see cref="GameState.ShareTarget"/> /// </summary> public interface ITargetSharer : IStateWorker { public TargetData[] SharedTarget(); } } <file_sep>/Assets/BotTestBed/Scripts/Runtime/GameManager.cs using Cysharp.Threading.Tasks; using Runtime.Executor; using UnityEngine; using VContainer; namespace Runtime { public sealed class GameManager : MonoBehaviour { private GameStateExecutor _executor; [Inject] private void Init(GameStateExecutor executor) { _executor = executor; } public UniTask ExecuteGame() { return _executor.Execute(this.GetCancellationTokenOnDestroy()); } } } <file_sep>/Assets/BotTestBed/Scripts/Runtime/Executor/GameState.cs using System; namespace Runtime.Executor { [Flags] public enum GameState { Default, Wait, Connect, ShareTarget, GenerateTarget, Start, Playing, Finish, Result, } } <file_sep>/Assets/BotTestBed/Scripts/Runtime/Target/Generate/ITargetGenerator.cs using System.Threading; using Cysharp.Threading.Tasks; using Runtime.Executor; namespace Runtime.Target.Generate { public interface ITargetGenerator : IStateWorker { UniTask<Target[]> Generate(CancellationToken token); } } <file_sep>/Assets/BotTestBed/Scripts/Runtime/Play/Player.cs using System; using System.Threading; using BotTestBed.Runtime.Controller; using Cysharp.Threading.Tasks; using Runtime; using UniRx; using UnityEngine; using VContainer; namespace BotTestBed.Runtime { [RequireComponent(typeof(Rigidbody), typeof(Collider))] public sealed class Player : MonoBehaviour { private ControllerBase _controller; [Inject] private void Init(ControllerBase controller, GameConfiguration configuration) { this._controller = controller; this._rigidbody = GetComponent<Rigidbody>(); this._collider = GetComponent<Collider>(); var token = this.GetCancellationTokenOnDestroy(); OnStickForceAsync(token).Forget(); OnJumpAsync(token).Forget(); ResetPositionAsync(token).Forget(); } public PlayerColor PlayerColor; private Rigidbody _rigidbody; private Collider _collider; private const float MoveForce = 10f; private const float ForceRatio = 0.3f; private async UniTaskVoid OnStickForceAsync(CancellationToken token) { var stickInput = _controller.StickForce; while (true) { if (token.IsCancellationRequested) { break; } await UniTask.WaitForFixedUpdate(); var input = stickInput.Value; if (input == Vector2.zero) { continue; } var v = new Vector3(input.x, 0f, input.y); if (v.sqrMagnitude > 1f) { v = v.normalized; } _rigidbody.velocity = Vector3.Lerp(_rigidbody.velocity, v * MoveForce, ForceRatio); } } private const float JumpForce = 20f; private const float JumpInterval = 0.5f; private async UniTaskVoid OnJumpAsync(CancellationToken token) { var jumpInput = _controller.JumpPushed; while (true) { var input = await jumpInput; if (token.IsCancellationRequested) { break; } if (!input) { continue; } var velocity = _rigidbody.velocity; velocity.y = 0f; _rigidbody.velocity = velocity; _rigidbody.AddForce(Vector3.up * JumpForce); await UniTask.Delay(TimeSpan.FromSeconds(JumpInterval), cancellationToken: token); } } private async UniTaskVoid ResetPositionAsync(CancellationToken token) { var origin = Vector3.up; var distanceLimit = Mathf.Pow(12f, 2f); var ts = this.transform; while (true) { if (token.IsCancellationRequested) { break; } await UniTask.Delay(TimeSpan.FromSeconds(1), cancellationToken: token); if (!((ts.position - origin).sqrMagnitude > distanceLimit)) { continue; } _rigidbody.velocity = Vector3.zero; _rigidbody.angularVelocity = Vector3.zero; ts.SetPositionAndRotation(origin, Quaternion.identity); } } } } <file_sep>/Assets/BotTestBed/Scripts/Runtime/Executor/WaitType.cs namespace Runtime.Executor { public enum WaitType { All, Any, } } <file_sep>/Assets/BotTestBed/Scripts/Runtime/Controller/ControllerKeyboard.cs using UniRx; using UniRx.Triggers; using UnityEngine; namespace BotTestBed.Runtime.Controller { public sealed class ControllerKeyboard : ControllerBase { private void OnEnable() { this.UpdateAsObservable() .TakeUntilDestroy(this) .Subscribe(CheckInput); } private void CheckInput(Unit _) { var stick = Vector2.zero; if (Input.GetKey(KeyCode.RightArrow)) { stick += Vector2.right; } if (Input.GetKey(KeyCode.LeftArrow)) { stick += Vector2.left; } if (Input.GetKey(KeyCode.UpArrow)) { stick += Vector2.up; } if (Input.GetKey(KeyCode.DownArrow)) { stick += Vector2.down; } stickForce.Value = stick.normalized; jumpPushed.Value = Input.GetKey(KeyCode.Z); } } } <file_sep>/Assets/BotTestBed/Scripts/Runtime/Controller/ControllerNone.cs namespace BotTestBed.Runtime.Controller { public sealed class ControllerNone : ControllerBase { } } <file_sep>/Assets/BotTestBed/Scripts/Runtime/GameConfiguration.cs namespace Runtime { [System.Serializable] public sealed class GameConfiguration { public readonly int TargetCount; public readonly int GameTimeSecond; public GameConfiguration(int targetCount) { TargetCount = targetCount; } } } <file_sep>/Assets/BotTestBed/Scripts/Runtime/Target/TargetData.cs using System; using UnityEngine; namespace Runtime.Target { [Serializable] public sealed class TargetData { public int Id; public Vector3 Position; } } <file_sep>/Assets/BotTestBed/Scripts/Runtime/Network/INetworkNotifier.cs using Cysharp.Threading.Tasks; using Runtime.Target; using UniRx; namespace Runtime.Network { public interface INetworkNotifier { public IntReactiveProperty Time(); public UniTask GetItem(TargetData targetData); } } <file_sep>/Assets/BotTestBed/Scripts/Runtime/Target/ITargetPlaceLogic.cs namespace Runtime.Target { public interface ITargetPlaceLogic { TargetData[] Place(); } } <file_sep>/Assets/BotTestBed/Scripts/Runtime/Executor/GameStateExecutor.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Cysharp.Threading.Tasks; using VContainer; namespace Runtime.Executor { public sealed class GameStateExecutor { public static readonly Dictionary<GameState, WaitType> ExecutionState = new Dictionary<GameState, WaitType> { { GameState.Connect, WaitType.All }, { GameState.ShareTarget, WaitType.All }, { GameState.GenerateTarget, WaitType.All }, }; private readonly IStateWorker[] _stateWorker; [Inject] public GameStateExecutor(IStateWorker[] workers) { _stateWorker = workers; } public async UniTask Execute(CancellationToken baseToken) { foreach (var pair in ExecutionState) { var state = pair.Key; var waitType = pair.Value; if (baseToken.IsCancellationRequested) { break; } var source = CancellationTokenSource.CreateLinkedTokenSource(baseToken); var token = source.Token; var workArray = _stateWorker .Where(worker => worker.GameState.HasFlag(state)) .Select(worker => worker.Work(token)) .ToArray(); switch (waitType) { case WaitType.All: await UniTask.WhenAll(workArray); break; case WaitType.Any: await UniTask.WhenAny(workArray); break; default: throw new ArgumentOutOfRangeException(); } if (!source.IsCancellationRequested) { source.Cancel(); } } } } } <file_sep>/Assets/BotTestBed/Scripts/Runtime/Target/Share/TargetShareDummy.cs using System; using System.Linq; using System.Threading; using Cysharp.Threading.Tasks; using Runtime.Executor; using UnityEngine; namespace Runtime.Target.Share { public sealed class TargetShareDummy : ITargetSharer { GameState IStateWorker.GameState => GameState.ShareTarget; UniTask IStateWorker.Work(CancellationToken token) { _targetData = Enumerable.Range(0, 10) .Select(i => new TargetData { Id = i, Position = new Vector3(UnityEngine.Random.value, 0f, UnityEngine.Random.value) }) .ToArray(); return UniTask.CompletedTask; } TargetData[] ITargetSharer.SharedTarget() { return _targetData; } private TargetData[] _targetData = Array.Empty<TargetData>(); } } <file_sep>/Assets/BotTestBed/Scripts/Runtime/Executor/IStateWorker.cs using System.Threading; using Cysharp.Threading.Tasks; namespace Runtime.Executor { public interface IStateWorker { public GameState GameState { get; } public UniTask Work(CancellationToken token); } } <file_sep>/Assets/BotTestBed/Scripts/Runtime/GameLifeTimeScope.cs using BotTestBed.Runtime; using BotTestBed.Runtime.Controller; using Runtime.Executor; using VContainer; using VContainer.Unity; namespace Runtime { public sealed class GameLifeTimeScope : LifetimeScope { protected override void Configure(IContainerBuilder builder) { builder.RegisterComponentOnNewGameObject<GameManager>(Lifetime.Scoped); builder.Register<GameStateExecutor>(Lifetime.Scoped); builder.Register<GameConfiguration>(Lifetime.Singleton).WithParameter(10); builder.RegisterComponentOnNewGameObject<ControllerKeyboard>(Lifetime.Scoped).As<ControllerBase>(); builder.RegisterComponentInHierarchy<Player>(); } } } <file_sep>/README.md # BotTestBed Unity bot test bed <file_sep>/Assets/BotTestBed/Scripts/Runtime/Target/TargetPlaceRandom.cs using System.Collections.Generic; using System.Linq; using UnityEngine; using VContainer; namespace Runtime.Target { public sealed class TargetPlaceRandom : ITargetPlaceLogic { private readonly GameConfiguration _gameConfiguration; [Inject] public TargetPlaceRandom(GameConfiguration gameConfiguration) { _gameConfiguration = gameConfiguration; } public TargetData[] Place() { var amount = _gameConfiguration.TargetCount; var list = new List<Vector2>(); var retryCount = 0; while (true) { if (list.Count >= amount || retryCount > 100) { break; } var v2 = UnityEngine.Random.insideUnitCircle * 9f; if (list.Any(vector2 => (vector2 - v2).sqrMagnitude < 1f)) { retryCount++; continue; } list.Add(v2); } return list .Select((vector2, i) => new TargetData { Id = i, Position = new Vector3(vector2.x, 1f, vector2.y), }) .ToArray(); } } } <file_sep>/Assets/BotTestBed/Scripts/Runtime/Target/TargetHolder.cs using System; using System.Linq; using BotTestBed.Runtime.Controller; using UniRx; using UniRx.Triggers; using UnityEngine; namespace Runtime.Target { public sealed class TargetHolder : MonoBehaviour { public readonly Subject<(TargetData, PlayerColor)> OnTargetGet = new Subject<(TargetData, PlayerColor)>(); public Target[] Targets { get; private set; } = Array.Empty<Target>(); public void SetTarget(Target[] targets) { if (Targets.Any()) { foreach (var t in Targets) { if (t == null) { continue; } Destroy(t.gameObject); } } Targets = null; var parentTs = this.transform; Targets = targets .Where(target => target != null) .Select(target => { target.OnGet.TakeUntilDestroy(target).Subscribe(tuple => OnTargetGet.OnNext(tuple)); target.transform.SetParent(parentTs); return target; }) .ToArray(); } } } <file_sep>/Assets/BotTestBed/Scripts/Runtime/Target/Generate/TargetGeneratorPrimitive.cs using System.Collections.Generic; using System.Threading; using Cysharp.Threading.Tasks; using Runtime.Executor; using Runtime.Target.Share; using UnityEngine; namespace Runtime.Target.Generate { public sealed class TargetGeneratorPrimitive : ITargetGenerator { private readonly ITargetSharer _targetSharer; private readonly TargetHolder _targetHolder; public TargetGeneratorPrimitive(ITargetSharer targetSharer, TargetHolder targetHolder) { _targetSharer = targetSharer; _targetHolder = targetHolder; } public GameState GameState => GameState.GenerateTarget; public async UniTask Work(CancellationToken token) { var targets = await Generate(token); _targetHolder.SetTarget(targets); } public async UniTask<Target[]> Generate(CancellationToken token) { var listResult = new List<Target>(); var type = PrimitiveType.Sphere; var data = _targetSharer.SharedTarget(); foreach (var targetData in data) { await UniTask.Yield(); var go = GameObject.CreatePrimitive(type); var target = go.AddComponent<Target>(); target.TargetData = targetData; target.Place(); listResult.Add(target); } return listResult.ToArray(); } } } <file_sep>/Assets/BotTestBed/Scripts/Runtime/Target/Target.cs using System; using BotTestBed.Runtime; using BotTestBed.Runtime.Controller; using UniRx; using UnityEngine; namespace Runtime.Target { [RequireComponent(typeof(Collider))] public sealed class Target : MonoBehaviour { public TargetData TargetData; public IObservable<(TargetData, PlayerColor)> OnGet => _onGet; private readonly Subject<(TargetData, PlayerColor)> _onGet = new Subject<(TargetData, PlayerColor)>(); public void Place() { this.transform.SetPositionAndRotation(TargetData.Position, Quaternion.identity); } private void OnTriggerEnter(Collider other) { if (!other.CompareTag("Player")) { return; } var player = other.gameObject.GetComponent<Player>(); if (player == null) { return; } _onGet.OnNext((TargetData, player.PlayerColor)); } } }
f001bb214059e0914c4cd43f7095e784b338eaa9
[ "Markdown", "C#" ]
23
C#
nekomimi-daimao/BotTestBed
43eb32828df2e321300b5b91d98d8291862a01c3
8d06b06b2ed1100b516e876a253209364a74e1bf
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using MyClass.PersonClasses; namespace MyClassTest { [TestClass] public class CollectionAssertClassTest { [TestMethod] [Owner("Mariana")] public void AreCollectionEqualFailsBecauseNoComparerTest() { PersonManager PerMgr = new PersonManager(); List<Person> peopleExperted = new List<Person>(); List<Person> peopleActual = new List<Person>(); peopleExperted.Add(new Person() { FirstName = "Fabio", LastName = "Lazari"}); peopleExperted.Add(new Person() { FirstName = "Lau", LastName = "Martins" }); peopleExperted.Add(new Person() { FirstName = "Filipe", LastName = "Rosa" }); peopleActual = peopleExperted; // PerMgr.GetPeople(); --> You shall not pass!!! CollectionAssert.AreEqual(peopleExperted, peopleActual); } [TestMethod] [Owner("Mariana")] public void AreCollectionEqualWithComparerTest() { PersonManager PerMgr = new PersonManager(); List<Person> peopleExperted = new List<Person>(); List<Person> peopleActual = new List<Person>(); peopleExperted.Add(new Person() { FirstName = "Fabio", LastName = "Lazari" }); peopleExperted.Add(new Person() { FirstName = "Lau", LastName = "Martins" }); peopleExperted.Add(new Person() { FirstName = "Filipe", LastName = "Rosa" }); //You shall not pass!!! peopleActual = PerMgr.GetPeople(); CollectionAssert.AreEqual(peopleExperted, peopleActual, Comparer<Person>.Create((x, y) => x.FirstName == y.FirstName && x.LastName == y.LastName ? 0 : 1)); } [TestMethod] [Owner("Mariana")] public void AreCollectionEquivalentTest() { PersonManager PerMgr = new PersonManager(); List<Person> peopleExperted = new List<Person>(); List<Person> peopleActual = new List<Person>(); peopleActual = PerMgr.GetPeople(); peopleExperted.Add(peopleActual[1]); peopleExperted.Add(peopleActual[2]); peopleExperted.Add(peopleActual[0]); CollectionAssert.AreEquivalent(peopleExperted, peopleActual); } [TestMethod] [Owner("Mariana")] public void IsCollectionOfTypeTest() { PersonManager PerMgr = new PersonManager(); List<Person> peopleActual = new List<Person>(); peopleActual = PerMgr.GetSupervisors(); CollectionAssert.AllItemsAreInstancesOfType(peopleActual, typeof(Supervisor)); } } } <file_sep>using System; using System.Configuration; using System.IO; using System.Threading; using System.Data.SqlClient; using Microsoft.VisualStudio.TestTools.UnitTesting; using MyClass; namespace MyClassTest { [TestClass] public class FileProcessTest { private const string BAD_FILE_NAME = @"C:\BadfileName.bat"; private string _GoodFileName; public TestContext TestContext { get; set; } #region Test Initialize e Cleanup [TestInitialize] public void TestInitialize() { if (TestContext.TestName.StartsWith("FileNameDoesExists")) { SetGoodFileName(); if (!string.IsNullOrEmpty(_GoodFileName)) { TestContext.WriteLine($"Creating File: {_GoodFileName}"); File.AppendAllText(_GoodFileName, "Some Text"); } } } [TestCleanup] public void TestCleanup() { if (TestContext.TestName.StartsWith("FileNameDoesExists")) { if (!string.IsNullOrEmpty(_GoodFileName)) { TestContext.WriteLine($"Deleting File: {_GoodFileName}"); File.Delete(_GoodFileName); } } } #endregion [TestMethod] [Owner("Lau")] [Description("Check to see if a file does exist.")] [Priority(0)] [TestCategory("NoException")] public void FileNameDoesExists() { FileProcess fp = new FileProcess(); bool fromCall; TestContext.WriteLine($"Testing File: {_GoodFileName}"); fromCall = fp.FileExists(_GoodFileName); Assert.IsTrue(fromCall); } [TestMethod] [Owner("Fabio")] [DataSource("System.Data.SqlClient", @"Data Source = LAZARI_PC\SQLEXPRESS;User ID = sa;Password = <PASSWORD>;Initial Catalog=TesteUnitario;Connect Timeout = 30;Encrypt = False;TrustServerCertificate = True;ApplicationIntent = ReadWrite;MultiSubnetFailover = False", "FileProcessTest", DataAccessMethod.Sequential)] public void FileExistsTestFromDB() { FileProcess fp = new FileProcess(); string fileName; bool expectedValue, causesException, fromCall; fileName = TestContext.DataRow["FileName"].ToString(); expectedValue = Convert.ToBoolean(TestContext.DataRow["ExpectedValue"]); causesException = Convert.ToBoolean(TestContext.DataRow["CausesException"]); try { fromCall = fp.FileExists(fileName); Assert.AreEqual(expectedValue, fromCall, $"File: {fileName} has failed. METHOD: FileExistsTestFromDB"); } catch (ArgumentException) { Assert.IsTrue(causesException); } } [TestMethod] public void FileNameDoesExistsSimpleMessage() { FileProcess fp = new FileProcess(); bool fromCall; //_GoodFileName - Usar o nome de arquivo errado para passar o teste TestContext.WriteLine($"Testing File: {BAD_FILE_NAME}"); fromCall = fp.FileExists(BAD_FILE_NAME); Assert.IsFalse(fromCall, "File Does Not Exist"); } [TestMethod] public void FileNameDoesExistsMessageFormatting() { FileProcess fp = new FileProcess(); bool fromCall; //_GoodFileName - Usar o nome de arquivo errado para passar o teste TestContext.WriteLine($"Testing File: {BAD_FILE_NAME}"); fromCall = fp.FileExists(BAD_FILE_NAME); Assert.IsFalse(fromCall, "File '{0}' Does Not Exist", _GoodFileName); } public void SetGoodFileName() { _GoodFileName = ConfigurationManager.AppSettings["GoodFileName"]; if(_GoodFileName.Contains("[AppPath]")) { _GoodFileName = _GoodFileName.Replace("[AppPath]", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)); } } private const string FILE_NAME = @"filetodeploy.txt"; [TestMethod] [Owner("Fabio")] [DeploymentItem(FILE_NAME)] public void FileNameDoesExistsUsingDeploymentItem() { FileProcess fp = new FileProcess(); string fileName; bool fromCall; fileName = $@"{TestContext.DeploymentDirectory}\{FILE_NAME}"; TestContext.WriteLine($"Checking File: {fileName}"); fromCall = fp.FileExists(fileName); Assert.IsTrue(fromCall); } [TestMethod] [Timeout(3100)] [Owner("Mariana")] public void SimulateTimeout() { Thread.Sleep(3000); } [TestMethod] [Owner("Rosa")] [Description("Check to see if a file does not exist.")] [Priority(0)] [TestCategory("NoException")] public void FileNameDoesNotExists() { FileProcess fp = new FileProcess(); bool fromCall; fromCall = fp.FileExists(BAD_FILE_NAME); Assert.IsFalse(fromCall); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] [Owner("Fabio")] [Priority(1)] //[Ignore] [TestCategory("Exception")] public void FileNameNullOrEmpty_ThrowsArgumentNullException() { FileProcess fp = new FileProcess(); fp.FileExists(""); } [TestMethod] [Owner("Fabio")] [Priority(1)] [TestCategory("Exception")] public void FileNameNullOrEmpty_ThrowsArgumentNullException_usingtryCatch() { FileProcess fp = new FileProcess(); try { fp.FileExists(""); } catch (ArgumentNullException) { //sucesso return; } Assert.Fail("Falha esperada!"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MyClass.PersonClasses { public class PersonManager { public Person CreatePerson(string first, string last, bool isSupervisor) { Person ret = null; if (!string.IsNullOrEmpty(first)) { if (isSupervisor) ret = new Supervisor(); else ret = new Employee(); ret.FirstName = first; ret.LastName = last; } return ret; } public List<Person> GetPeople() { List<Person> people = new List<Person>(); people.Add(new Person() { FirstName = "Fabio", LastName = "Lazari" }); people.Add(new Person() { FirstName = "Lau", LastName = "Martins" }); people.Add(new Person() { FirstName = "Filipe", LastName = "Rosa" }); return people; } public List<Person> GetSupervisors() { List<Person> people = new List<Person>(); people.Add(CreatePerson("Fabio", "Lazari", true)); people.Add(CreatePerson("Felipe", "Rosa", true)); return people; } } }
2c8a84ce24a3b7d90e480d157fe167d6b0c3117f
[ "C#" ]
3
C#
fabiolazari/MeuPrimeiroTeste
37aaa8a0c820c8e4310718a1ce95088750e92a5c
dcde54aa09ec47d177e5eb5cbec23011a4e83ca8
refs/heads/master
<repo_name>gemelodyyu/Python-Challenge<file_sep>/PyBank/main.py # import modules import csv import os # create variable for the path bank_path = os.path.join("Resources", "PyBank_Resources_budget_data.csv") # create lists to store data monthly_change = [] total_month = [] total_profits = [] # read csv data with open(bank_path) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') #skip the header line csv_header = next(csv_reader) for row in csv_reader: # add up total month and total profits total_month.append(row[0]) total_profits.append(int(row[1])) # within the total profits list, calculate monthly change and add to the list # because the last month do not have an additional month to compare the change, so use len()-1 in the range for i in range(len(total_profits)-1): monthly_change.append(total_profits[i+1]-total_profits[i]) # calculate average profits changes # round result to 2 decimal places average_profits = round(sum(monthly_change)/len(monthly_change),2) # find max increase and max decrease within the monly change max_increase = max(monthly_change) max_decrease = min(monthly_change) # find indexs of max increase and max decrease # with these indexs we could find the dates within the month list # date indexs should +1 because the change would be reflected/associated with the next month max_increase_date = total_month[monthly_change.index(max(monthly_change))+1] max_decrease_date = total_month[monthly_change.index(min(monthly_change))+1] # print results print("Financial Analysis: ") print("--------------------------------------------------------") print(f"Total Months: {len(total_month)}") print(f"Total: ${sum(total_profits)}") print(f"Average Change: ${average_profits}") print(f"Greatest Increase in Profits: {max_increase_date} (${max_increase})") print(f"Greatest Decrease in Profits: {max_decrease_date} (${max_decrease})") # spcify the file to write to write_path = os.path.join("analysis","py_bank_result.txt") # write results to a text file with open(write_path, "w") as file: file.write("Financial Analysis: ") file.write("\n") file.write("--------------------------------------------------------") file.write("\n") file.write(f"Total Months: {len(total_month)}") file.write("\n") file.write(f"Total: ${sum(total_profits)}") file.write("\n") file.write(f"Average Change: ${average_profits}") file.write("\n") file.write(f"Greatest Increase in Profits: {max_increase_date} (${max_increase})") file.write("\n") file.write(f"Greatest Decrease in Profits: {max_decrease_date} (${max_decrease})") <file_sep>/README.md # Python Challenge ### Prepare for the challenge - Create a new repository for this project called python-challenge. - Clone the new repository to your computer. - Inside your local git repository, create a directory for both of the Python Challenges. Use folder names corresponding to the challenges: PyBank and PyPoll. - Inside of each folder that you just created, add the following: - A new file called main.py. This will be the main script to run for each analysis. - A "Resources" folder that contains the CSV files you used. Make sure your script has the correct path to the CSV file. - An "analysis" folder that contains your text file that has the results from your analysis. - Push the above changes to GitHub ---------------------------------- ## PyBank In this challenge, you are tasked with creating a Python script for analyzing the financial records of your company. You will give a set of financial data called budget_data.csv. The dataset is composed of two columns: Date and Profit/Losses. (Thankfully, your company has rather lax standards for accounting so the records are simple.) Your task is to create a Python script that analyzes the records to calculate each of the following: - The total number of months included in the dataset - The net total amount of "Profit/Losses" over the entire period - The average of the changes in "Profit/Losses" over the entire period - The greatest increase in profits (date and amount) over the entire period - The greatest decrease in losses (date and amount) over the entire period ### Result <img width="493" alt="Screen Shot 2020-08-07 at 00 15 36" src="https://user-images.githubusercontent.com/55970064/89611561-272eac00-d843-11ea-985a-a5bac8e09a4d.png"> ------------------------------------------------ ## PyPoll In this challenge, you are tasked with helping a small, rural town modernize its vote counting process. You will be give a set of poll data called election_data.csv. The dataset is composed of three columns: Voter ID, County, and Candidate. Your task is to create a Python script that analyzes the votes and calculates each of the following: - The total number of votes cast - A complete list of candidates who received votes - The percentage of votes each candidate won - The total number of votes each candidate won - The winner of the election based on popular vote. ### Result <img width="289" alt="Screen Shot 2020-08-07 at 00 17 09" src="https://user-images.githubusercontent.com/55970064/89611663-5ba26800-d843-11ea-95fa-5a8264997835.png"> <file_sep>/PyPoll/main.py # import modules import csv import os # create variables candidate_list = [] candidate_votes = [] total_votes = 0 # create variable for the path poll_path = os.path.join("Resources", "election_data.csv") # read csv data with open(poll_path) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') #skip the header line csv_header = next(csv_reader) # use for loop to go though the election_data for row in csv_reader: total_votes = total_votes +1 candidate = row[2] # calculate running total for each candidate if candidate in candidate_list: index = candidate_list.index(candidate) candidate_votes[index] = candidate_votes[index] +1 # make new spot for another candidate else: candidate_list.append(candidate) candidate_votes.append(1) # create temp variables candidate_percentages = [] max_vote = candidate_votes[0] max_index = 0 # calculate percentage each candidate win and find the winner for i in range(len(candidate_list)): percentage = round(candidate_votes[i]/total_votes*100, 2) candidate_percentages.append(percentage) #find winner if candidate_votes[i] > max_vote: max_vote = candidate_votes max_index = i winner = candidate_list[max_index] # print results print("Election Results") print("-----------------------------") print(f"Total Votes: {total_votes}") print("-----------------------------") for i in range(len(candidate_list)): print(f"{candidate_list[i]}: {candidate_percentages[i]}% ({candidate_votes[i]})") print("-----------------------------") print(f"Winner: {winner}") print("-----------------------------") # save the results to analysis text file write_path = os.path.join("analysis","py_poll_result.txt") with open(write_path, "w") as file: file.write("Election Results\n") file.write("-----------------------------\n") file.write(f"Total Votes: {total_votes} \n") file.write("-----------------------------\n") for i in range(len(candidate_list)): file.write(f"{candidate_list[i]}: {candidate_percentages[i]}% ({candidate_votes[i]})\n") file.write("-----------------------------\n") file.write(f"Winner: {winner}\n") file.write("-----------------------------")
e2b1afa252774e7c4886eafea8195cd8f22de82e
[ "Markdown", "Python" ]
3
Python
gemelodyyu/Python-Challenge
519e3f9cc5203f441b22c6a69d2dc7d52d647e6e
740b42a2da2cbfff6f3b01db1a88a95dcbf7acb9
refs/heads/master
<repo_name>luqingan/SCENA<file_sep>/README.md # SCENA Single cell RNA-seq Correlation completion by ENsemble learning and Auxiliary information. The SCENA gene-by-gene correlation matrix estimate is obtained by model stacking of multiple imputed correlation matrices based on known auxiliary information about gene connections. <file_sep>/get_aux.R library(data.table) library(biomaRt) library(Matrix) library(gage) library('org.Hs.eg.db') data('egSymb') library(BiocManager) library(TCGAbiolinks) library(MASS) #############3 ######## kegg # keggset = kegg.gsets(species = "hsa", id.type = "entrez", check.new=FALSE) # kegg.gs.sym<-lapply(keggset$kg.sets, eg2sym) # kegg = kegg.gs.sym[-keggset$dise.idx] ## pathways # # ## genes that are in kegg , 6860 genes, 239 paths # GENE = sort(unique(unlist(kegg))) # GENE.PATH = sapply(GENE,function(gene) sapply(1:length(kegg), function(i) gene %in% kegg[[i]])) # kegg_relation = t(GENE.PATH)%*%GENE.PATH # # ##GET kegg correlation matrix # GENE.PATH = 1*(GENE.PATH) # cor_kegg = cor(GENE.PATH) # saveRDS(cor_kegg,file = 'cor_kegg.rds') scalematrix <- function(data) { cm <- rowMeans(data) csd <- rowSds(data, center = cm) csd[which(csd==0)]=0.001 (data - cm) / csd } ############### string library(STRINGdb) string_db = STRINGdb$new( version="10", species=9606,score_threshold=0, input_directory="" ) get_string = function(dat){ gene_of_interest = data.frame(gene = rownames(dat)) string_id = string_db$map(gene_of_interest, "gene", removeUnmappedRows = TRUE ) ## genes cannot be matched xx = gene_of_interest[which(is.na(match(gene_of_interest[,1], string_id$gene))),1] ## build interaction matrix interaction = string_db$get_interactions(string_id$STRING_id)[,c(1,2,16)] interaction$combined_score = interaction$combined_score/1000 adj <- matrix(0, nrow(string_id), nrow(string_id)) mat = as.matrix(interaction[,1:2]) rownames(adj) = colnames(adj) = string_id$STRING_id adj[mat] <- interaction[,3] rownames(adj) = colnames(adj) = string_id$gene adj_t = t(adj) adj = adj_t+adj diag(adj)=1 adj = data.frame(adj) nas = array(0,dim = c(length(xx),nrow(adj))) rownames(nas) = xx adj = rbind(as.matrix(adj),as.matrix(nas)) nas = array(0,dim = c(length(xx),nrow(adj))) rownames(nas) = xx adj = cbind(adj,t(nas)) return(adj) } ########## biogrid get_biogrid = function(dat){ names.genes.de <- rownames(dat) tmp.biogrid <- data.frame("Official.Symbol.Interactor.A" = names.genes.de, "Official.Symbol.Interactor.B" = rev(names.genes.de)) biogridd <- getAdjacencyBiogrid(tmp.biogrid, names.genes.de) bio = diag(colSums(biogridd))-biogridd biogrid = ginv(bio) biogrid = cov2cor(biogrid) colnames(biogrid) = colnames(bio) rownames(biogrid) = rownames(bio) return(biogrid) } ###################################################### # dat = ref[[1]] # new = yan # dim(yan) get_new = function(dat,new){ # dat = sc_chu # new = yan genes = match(rownames(dat),rownames(new)) nomatch = which(is.na(genes)) yan_dat = new[na.omit(genes),] cor_ref = cor(t((log2(dat+1)))) cor_yan = cor(t(scalematrix(yan_dat))) add = array(0,dim=c(length(nomatch),ncol(cor_yan))) rownames(add) = rownames(cor_ref)[nomatch] cor_y=rbind(cor_yan,add) add = array(0,dim=c(nrow(cor_y),length(nomatch))) colnames(add) = rownames(cor_ref)[nomatch] cor_y = cbind(cor_y,add) cor_y = cor_y[match(rownames(cor_ref),rownames(cor_y)),] cor_y = cor_y[,match(colnames(cor_ref),colnames(cor_y))] cor_y[nomatch,] = cor_ref[nomatch,] cor_y[,nomatch] = cor_ref[,nomatch] return(cor_y) } get_bulk = function(dat,bulk){ genes = intersect(intersect(rownames(dat),rownames(bulk)),rownames(cor_kegg)) ## 6038 bulk = bulk[na.omit(match(genes,rownames(bulk))),] return(bulk) } <file_sep>/single_ensemble.R single_methods = function(bulk,sc,cor_kegg,cor_string,cor_biogrid,cor_new){ bulk = bulk[match(rownames(sc),rownames(bulk)),] ### normalize sc_norm = (log2(sc+1)) cor_x = cor(t(scalematrix(sc_norm))) cor_x[is.na(cor_x)] = 0 ## calculate correlation cor_b = cor(t(scalematrix(bulk))) sc_normalized_NA = sc_norm sc_normalized_NA[sc_norm == 0] <- NA ## replace 0 with NA cor_s = cor(t(sc_normalized_NA),use = "pairwise.complete.obs") ########### direct complete apply to dat cor_comp = CovarianceWithMissing(t(sc_normalized_NA)) cor_shrink = cov.shrink(t(sc_norm)) cor_shrink = as.matrix(cov2cor(cor_shrink)) ####### apply to cor_s ## match biogrid ind = match(rownames(sc), rownames(cor_biogrid)) cor_biogrid = cor_biogrid[ind,ind] cor_biogrid[is.na(cor_biogrid)]=0 ## match string ind = match(rownames(sc), rownames(cor_string)) cor_string = cor_string[ind,ind] cor_string[is.na(cor_string)]=0 ## match new ind = match(rownames(sc), rownames(cor_new)) cor_new = cor_new[ind,ind] cor_new[is.na(cor_new)]=0 ## match kegg ind = match(rownames(sc), rownames(cor_kegg)) cor_kegg = cor_kegg[ind,ind] cor_kegg[is.na(cor_kegg)]=0 ## methods cor_bs = correlation_NA_to_aux(sc_norm,cor_b,cor_s) cor_alpha = correlation_weighted_average(sc_norm,cor_b,cor_s) cor_ks = correlation_NA_to_aux(sc_norm,cor_kegg,cor_s) cor_alpha_kegg = correlation_weighted_average(sc_norm,cor_kegg,cor_s) cor_ss = correlation_NA_to_aux(sc_norm,cor_string,cor_s) cor_alpha_string = correlation_weighted_average(sc_norm,cor_string,cor_s) cor_sbio = correlation_NA_to_aux(sc_norm,cor_biogrid,cor_s) cor_alpha_biogrid = correlation_weighted_average(sc_norm,cor_biogrid,cor_s) ######### other data , need to deal with unmatched genes cor_ns = correlation_NA_to_aux(sc_norm,cor_new,cor_s) cor_alpha_n = correlation_weighted_average(sc_norm,cor_new,cor_s) cor = list(cor_x,cor_b,cor_bs,cor_alpha, ## bulk cor_kegg,cor_ks,cor_alpha_kegg, ## kegg cor_string,cor_ss,cor_alpha_string,## string cor_biogrid,cor_sbio,cor_alpha_biogrid, ## biogrid cor_comp,cor_shrink,## direct cor_new,cor_ns,cor_alpha_n) ## new data ## 18 # cor_pd = lapply(cor, function(x) cov2cor(as.matrix(nearPD(x)$mat))) return(cor) } ridge = function(mini_ref,B,test,type ='b'){ cor_mini_ref = cor(t(scalematrix(log2(mini_ref+1)))) res = list() for (b in c(1:B)){ set.seed(347*d+i*72+b*2) mini_samp = downsample(mini_ref,100) ## use rate=100, lower percent of zeros saver_mini = saver(mini_samp, do.fast = TRUE,ncores=8) dr_mini = DrImpute(mini_samp) prime_mini <- PRIME(mini_samp) scRMD_mini <- rmd(mini_samp)$exprs single_mini = try_noimpute_methods(aux[[i]][[1]],mini_samp,cor_kegg,aux[[i]][[2]],aux[[i]][[3]],aux[[i]][[4]]) cor_x = single_mini[[1]] cor_saver <- cor.genes(saver_mini) cor_drimpute = correlation_aux(dr_mini) cor_scRMD= correlation_aux(scRMD_mini) cor_prime= correlation_aux(prime_mini) single_mini = c(single_mini,list(cor_saver,cor_drimpute,cor_scRMD,cor_prime)) train = lapply(single_mini,function(mat) mat[upper.tri(mat, diag = FALSE)]) train = data.frame(matrix(unlist(train), ncol=length(single_mini), byrow=FALSE)) ref_train = cor_mini_ref[upper.tri(cor_mini_ref, diag = FALSE)] train = data.frame(y = ref_train,train) X <- as.matrix(train[,-1]) Y <- train$y para = NULL X_long = NULL if (type=='b'){ fit.ridge <- cv.glmnet(X, Y, family="gaussian",type.measure="mse", alpha=0) para = rbind(para,as.vector(predict(fit.ridge,type="coef", s = fit.ridge$lambda.1se))) } if (type=='a'){ X_long = rbind(X_long,X) } } if (type=='b'){ para_final = colMeans(para) res$para = para_final test_x = cbind(rep(1,nrow(test)),test) cor_y = as.matrix(test_x)%*%as.matrix(para_final) cor_pred = vec2cor(cor_y) cor_pred = cov2cor(as.matrix(nearPD(cor_pred)$mat)) res$y = cor_pred return(res) } if (type=='a'){ y_long = rep(Y,B) fit.ridge <- cv.glmnet(X_long, y_long, family="gaussian",type.measure="mse", alpha=0) newX = model.matrix(~.,data=test) newX = newX[,-1] cor_y <- predict(fit.ridge, s=fit.ridge$lambda.1se, newx=newX) cor_pred = vec2cor(cor_y) cor_pred = cov2cor(as.matrix(nearPD(cor_pred)$mat)) res$para = as.vector(predict(fit.ridge,type="coef", s = fit.ridge$lambda.1se)) res$y = cor_pred return(res) } } ridge_real = function(mini_ref,B,test,type ='b'){ cor_mini_ref = cor(t(scalematrix(log2(mini_ref+1)))) res = list() for (b in c(1:B)){ set.seed(347*d+i*72+b*2) mini_samp = downsample(mini_ref,100) ## use rate=100, lower percent of zeros saver_mini = saver(mini_samp, do.fast = TRUE,ncores=8) dr_mini = DrImpute(mini_samp) prime_mini <- PRIME(mini_samp) scRMD_mini <- rmd(mini_samp)$exprs single_mini = try_noimpute_methods(aux_real[[i]][[1]],mini_samp,cor_kegg,aux_real[[i]][[2]],aux_real[[i]][[3]],aux_real[[i]][[4]]) cor_x = single_mini[[1]] cor_saver <- cor.genes(saver_mini) cor_drimpute = correlation_aux(dr_mini) cor_scRMD= correlation_aux(scRMD_mini) cor_prime= correlation_aux(prime_mini) single_mini = c(single_mini,list(cor_saver,cor_drimpute,cor_scRMD,cor_prime)) train = lapply(single_mini,function(mat) mat[upper.tri(mat, diag = FALSE)]) train = data.frame(matrix(unlist(train), ncol=length(single_mini), byrow=FALSE)) ref_train = cor_mini_ref[upper.tri(cor_mini_ref, diag = FALSE)] train = data.frame(y = ref_train,train) X <- as.matrix(train[,-1]) Y <- train$y para = NULL X_long = NULL if (type=='b'){ fit.ridge <- cv.glmnet(X, Y, family="gaussian",type.measure="mse", alpha=0) para = rbind(para,as.vector(predict(fit.ridge,type="coef", s = fit.ridge$lambda.1se))) } if (type=='a'){ X_long = rbind(X_long,X) } } if (type=='b'){ para_final = colMeans(para) res$para = para_final test_x = cbind(rep(1,nrow(test)),test) cor_y = as.matrix(test_x)%*%as.matrix(para_final) cor_pred = vec2cor(cor_y) cor_pred = cov2cor(as.matrix(nearPD(cor_pred)$mat)) res$y = cor_pred return(res) } if (type=='a'){ y_long = rep(Y,B) fit.ridge <- cv.glmnet(X_long, y_long, family="gaussian",type.measure="mse", alpha=0) newX = model.matrix(~.,data=test) newX = newX[,-1] cor_y <- predict(fit.ridge, s=fit.ridge$lambda.1se, newx=newX) cor_pred = vec2cor(cor_y) cor_pred = cov2cor(as.matrix(nearPD(cor_pred)$mat)) res$para = as.vector(predict(fit.ridge,type="coef", s = fit.ridge$lambda.1se)) res$y = cor_pred return(res) } } <file_sep>/scena.R library(SAVER) library(DrImpute) library(scRMD) library(PRIME) library(mclust) ###### change link_data to interested one setwd("~/Dropbox/GQ - Applications/Single-cell/data") #### load code # source('install.R') source('single_ensemble.R') source('graphfun.R') source('get_aux.R') ## load raw data load('chu.rdata') load('chu_time.rdata') load('darmanis.rdata') ## gene match bulk = readRDS("RNA_data_norm_hg19_all_name.rds") ## 41989*444 cor_kegg = readRDS('cor_kegg.rds') ## other sc for chu yan = readRDS('yan.rds') yann <- assay(yan, "logcounts") ## for darmanis lake = readRDS('lake.rds') lakee <- assay(lake, "normcounts") ############################ match_gene = function(sc,bulk,cor_kegg){ genes = intersect(intersect(rownames(sc),rownames(bulk)),rownames(cor_kegg)) ## 6038 return(sc[na.omit(match(genes,rownames(sc))),]) } sc_chu = match_gene(chu$sc_cnt,bulk,cor_kegg) sc_chu_time = match_gene(chu_time$sc_cnt,bulk,cor_kegg) sc_darmanis = match_gene(darmanis$sc_cnt,bulk,cor_kegg) # aux = readRDS('network.rds') label = list(chu$sc_label,chu_time$sc_label,darmanis$sc_label) ###############functions scalematrix <- function(data) { cm <- rowMeans(data) csd <- rowSds(data, center = cm) csd[which(csd==0)]=0.001 (data - cm) / csd } ## get off-diagonal upper = function(mat){ mat[upper.tri(mat, diag = FALSE)] } get_mse = function(cor_x,cor_ref){ x = upper(cor_x) y = upper(cor_ref) return(mean((x-y)^2,na.rm = TRUE)) } ### ARI get_percent = function(eigenvalue){ percent = NULL for (p in c(1:length(eigenvalue))){ percent[p] = sum(eigenvalue[1:p])/sum(eigenvalue) } return(percent) } get_range = function(acc_var,a,b){ pcs = which(acc_var<b&acc_var>a) perc = acc_var[pcs] p = rbind(perc,pcs) rownames(p) = c('percent','Num_pc') return(p) } ### clustering fit_cluster = function(mydata){ d0 = dist(mydata,method = 'manhattan') fit <- hclust(d0,method = 'ward.D') return(fit) } ## pca get_pca = function(data,eigen_vector){ pca = data.frame((as.matrix(t(data))%*%eigen_vector)) return(pca) } build_ref = function(x1,label){ # Filter out library size greater than 4500000 x2 <- x1[, which(colSums(x1) <= quantile(colSums(x1),0.95))] label = label[which(colSums(x1) <= quantile(colSums(x1),0.95))] x3 <- x2[rowMeans(x2) >= quantile(rowMeans(x2),0.25), ] x4 <- x3[rowSums(x3 != 0) >= quantile(rowSums(x3 != 0),0.15), ] # build reference lib.size <- colSums(x4) non.zero.prop <- apply(x4, 1, function(x) sum(x != 0)/length(x)) cells.filt <- which(lib.size > quantile(lib.size,0.05)) genes.filt <- which(non.zero.prop > quantile(non.zero.prop,0.5)) data.filt <- x4[genes.filt, cells.filt] label = label[cells.filt] datt = list(data.filt,label) return(datt) } ref_chu = build_ref(sc_chu,chu$sc_label) ref_chu_time = build_ref(sc_chu_time,chu_time$sc_label) ref_darmanis = build_ref(sc_darmanis,darmanis$sc_label) ref = list(ref_chu[[1]],ref_chu_time[[1]],ref_darmanis[[1]]) label_ref = list(ref_chu[[2]],ref_chu_time[[2]],ref_darmanis[[2]]) # saveRDS(label_ref,file = 'label_ref.rds') data_name = c('chu','chut','darmanis') cor_ref <- vector("list", 3) names(cor_ref) <- data_name for (i in 1:3) { ref_norm = log2(ref[[i]]+1) cor_ref[[i]] = cor(t(ref_norm)) } #################################################### downsample = function(refe,rate){ alpha <- rgamma(ncol(refe), 10, rate = rate) data.samp <- t(apply(sweep(refe, 2, alpha, "*"), 1, function(x) rpois(length(x), x))) colnames(data.samp) = colnames(refe) return(data.samp) } model_name = c('Reference','X_s','SAVER','drImpute','scRMD','PRIME','SCENA_average','SCENA_ridge') data_name = c('chu','chu_time',"darmanis") correlation_aux = function(x_aux){ cor_aux = cor(t(scalematrix(log2(x_aux+1)))) cor_aux[is.na(cor_aux)]=0 return(cor_aux) } ave = function(list_of_cor){ x =Reduce('+',list_of_cor)/length(list_of_cor) x = as.matrix(data.frame(x[1:nrow(x),1:ncol(x)])) cor_pred = cov2cor(as.matrix(nearPD(x)$mat))## find nearest pd and change it to -1 1 return(cor_pred) } ########### get aux aux_chu = list(get_bulk(ref[[1]],bulk),get_string(ref[[1]]),get_biogrid(ref[[1]]),get_new(ref[[1]],yann)) aux_chu_time = list(get_bulk(ref[[2]],bulk),get_string(ref[[2]]),get_biogrid(ref[[2]]),get_new(ref[[2]],yann)) aux_darmanis = list(get_bulk(ref[[3]],bulk),get_string(ref[[3]]),get_biogrid(ref[[3]]),get_new(ref[[3]],lakee)) aux = list(aux_chu,aux_chu_time,aux_darmanis) #######conduct 30 downsampling ## rate = c(3000,1000,1000) mse <- vector("list", 3) cmd <- vector("list", 3) ARI_all <- vector("list", 3) cor_noimpute = vector("list", 3) B = 1 ## number of iteration for mini-downsample stan_x = NULL for (d in c(1:10)){ ## downsample repetition for (i in c(1:3)){ ## data loop print(c(i,d)) r = rate[i] set.seed(i*21+36*d) ### generate rv from gamma with mean 0.1 for each sample alpha <- rgamma(ncol(ref[[i]]), 10, rate = r) ## mean is 0.1 for each sample ## for each gene, generate poisson with mean = alpha*entry data.samp <- t(apply(sweep(ref[[i]], 2, alpha, "*"), 1, function(x) rpois(length(x), x))) colnames(data.samp) = colnames(ref[[i]]) stan_x = scalematrix(log2(data.samp+1)) ###### imputation saver = saver(data.samp, do.fast = TRUE,ncores=8) dr = DrImpute(data.samp) prime <- PRIME(data.samp) scRMD <- rmd(data.samp)$exprs ############ do single methods to downsampled single = single_methods(aux[[i]][[1]],data.samp,cor_kegg,aux[[i]][[2]],aux[[i]][[3]],aux[[i]][[4]]) ################# have no imputation at all cor_x = single[[1]] cor_saver <- cor.genes(saver) cor_drimpute = correlation_aux(dr) cor_scRMD= correlation_aux(scRMD) cor_prime= correlation_aux(prime) ################# have imputation only in model stacking single= c(single,list(cor_saver,cor_drimpute,cor_scRMD,cor_prime)) cor_ave= ave(single) ################################################## test = lapply(single,function(mat) mat[upper.tri(mat, diag = FALSE)]) test =data.frame(matrix(unlist(test), ncol=length(single), byrow=FALSE)) ########## ridge model stacking (build mini-ref and mini-down to fit the model) ridge = ridge(mini_ref,B,test,'b') cor_ridge= ridge$y cor_all = list(cor_ref[[i]],cor_x,cor_saver,cor_drimpute,cor_scRMD,cor_prime,cor_ave,cor_ridge) names(cor_all) = model_name cor_noimpute[[i]][[d]]=cor_all ############### for result ## MSE mse[[i]][[d]] = sapply(cor_all, function(x) get_mse(x,cor_ref[[i]])) cmd[[i]][[d]] = sapply(cor_all, function(x) cmd(x,cor_ref[[i]])) ## eigens eigens = lapply(cor_all, function(x) eigen(x)) eigen_vec = lapply(eigens, function(x) x$vectors) eigen_value = lapply(eigens, function(x) x$values) impo = lapply(eigen_value, function(x) get_percent(x)) pc_range = lapply(impo, function(acc_var) get_range(acc_var,0.9,0.99)) pca = lapply(eigen_vec, function(ev) get_pca(stan_x,ev)) ######### ari ari = NULL pca_tran = lapply(pca, function(x) scalematrix((x))) start = sapply(pc_range, function(x) x[[2,1]]) end = sapply(pc_range, function(x) x[[2,ncol(x)]]) byy = round((end-start)/20) for (m in c(1:length(cor_all))){ pcs = seq(start[m],end[m],by=byy[m]) acc_cell = array(0,dim = c(length(pcs),3)) for (pp in c(1:length(pcs))){ pc = pcs[pp] fit_models= fit_cluster(pca_tran[[m]][,1:pc]) K = length(unique(label_ref[[i]])) cls = cutree(fit_models, k=K) acc_cell[pp,3] = adjustedRandIndex(label_ref[[i]], cls) } ## end PCs clustering loop acc_cell[,1] = rep(model_name[m],pp) acc_cell[,2] = impo[[m]][pcs] ari = rbind(ari,acc_cell) } colnames(ari) = c('Method','percent','ARI') ARI_all[[i]][[d]] = ari saveRDS(cor_noimpute,file = ('cor.rds')) saveRDS(mse,file = ('mse.rds')) saveRDS(cmd,file = ('cmd.rds')) saveRDS(ARI_all,file =('ari.rds')) } } <file_sep>/graphfun.R library(QUIC) update.lambda = function(lambdas,nedges.seq,nedges){ lambda = 0 if(length(lambdas)==length(nedges.seq) & length(nedges.seq)>0){ lambdas=log(lambdas) nedges.seq=log(nedges.seq+1) nedges=log(nedges+1) if(nedges<max(nedges.seq) & nedges>min(nedges.seq)){ ind1 = max(which(nedges.seq>nedges)) ind2 = min(which(nedges.seq<nedges)) nedges1 = nedges.seq[ind1] nedges2 = nedges.seq[ind2] lambda1 = max(lambdas[ind1]) lambda2 = min(lambdas[ind2]) b = (nedges2-nedges1)/(lambda2-lambda1) a = nedges1 - b*lambda1 lambda = (nedges-a)/b } if(nedges<min(nedges.seq)){ lambda = max(lambdas)+1 } if(nedges>max(nedges.seq)){ lambda = min(lambdas)-1 } } return(exp(lambda)) } Glasso.nedge = function(COV,nedges,lambda.start=1, max.trial=100,WEIGHT=1,OBS='full',edge.tol=0,kappa=1,Plot=FALSE,...){ p = ncol(COV) if(OBS[1]!='full'){ print(paste0('computing Glasso with ',nedges,' edges in O')) } if(OBS[1]=='full'){ OBS=diag(p)*0 OBS=OBS==0 print(paste0('computing Glasso with ',nedges,' edges')) } lambda = lambda.start GLASSO = QUIC(COV,rho=lambda*WEIGHT,msg=0,...)$X glassonedge = (sum(GLASSO[OBS]!=0)-p)/2 trial = 0 lambdas = lambda nedges.seq = glassonedge while(abs(glassonedge-nedges)>edge.tol & trial<max.trial){ lambda = update.lambda(lambdas=lambdas,nedges.seq=nedges.seq,nedges=nedges) GLASSO = QUIC(COV,rho=lambda*WEIGHT,msg=0,...)$X glassonedge = (sum(GLASSO[OBS]!=0)-p)/2 lambdas = c(lambdas,lambda) nedges.seq = c(nedges.seq,glassonedge) nedges.seq = nedges.seq[order(lambdas)] lambdas = sort(lambdas) trial=trial+1 print(c(trial,glassonedge,lambda)) if(Plot==TRUE){ plot(log(lambdas),sqrt(nedges.seq),axes=FALSE,xlab=expression(log(lambda)),ylab='# edges') axis(1) axis(2,labels=sort(unique(nedges.seq)),at=sqrt(sort(unique(nedges.seq)))) abline(v=log(lambda),h=sqrt(nedges),lty=2) } } return(list(GLASSO = GLASSO,lambda=lambda,lambdas=lambdas,glassonedge=nedges.seq)) } graph.diff = function(THETA.ref,THETA.hat){ E.ref = round(THETA.ref!=0) E.hat = round(THETA.hat!=0) d = ncol(E.ref) Q=upper.tri(diag(d)) fdp = sum(E.hat[Q]*(1-E.ref[Q]),na.rm=TRUE)/max(c(1,sum(E.hat[Q],na.rm=TRUE))) fnp = sum((1-E.hat[Q])*E.ref[Q],na.rm=TRUE)/max(c(1,sum(1-E.hat[Q],na.rm=TRUE))) sens = sum(E.hat[Q]*E.ref[Q],na.rm=TRUE)/max(c(1,sum(E.ref[Q],na.rm=TRUE))) spec = sum((1-E.hat[Q])*(1-E.ref[Q]),na.rm=TRUE)/max(c(1,sum(1-E.ref[Q],na.rm=TRUE))) tot.err = 1-mean(E.hat[Q]*E.ref[Q]+(1-E.hat[Q])*(1-E.ref[Q])) return(c(fdp=fdp,fnp=fnp,sens=sens,spec=spec,tot.err=tot.err)) } f1_score = function(THETA.ref,THETA.hat){ E.ref = round(THETA.ref!=0) E.hat = round(THETA.hat!=0) d = ncol(E.ref) Q=upper.tri(diag(d)) precision = sum(E.hat[Q]*E.ref[Q],na.rm=TRUE)/max(c(1,sum(E.hat[Q],na.rm=TRUE))) recall = sum((1-E.hat[Q])*(1-E.ref[Q]),na.rm=TRUE)/max(c(1,sum(1-E.hat[Q],na.rm=TRUE))) f1 = 2*(precision*recall)/(recall+precision) return(f1) } ## FUNCTIONS USING EBIC EBIC = function(Theta.glasso,Sigma.hat,n,gamma=.5,tol=10^(-10)){ p = ncol(Theta.glasso) LAMBDA = round(abs(cov2cor(Theta.glasso))<=tol)*1000000 K = sum(LAMBDA[upper.tri(diag(p))]==0) Theta.mle = QUIC::QUIC(Sigma.hat,rho=LAMBDA)$X val = -n*(determinant(Theta.mle)$modulus-sum(diag(Sigma.hat%*%Theta.mle)))+K*(log(n)+4*gamma*log(p)) return(val) } Glasso.ebic = function(COV,n,lambdas,MCCORES=2,gamma=.5,tol=10^(-10)){ p = ncol(COV) THETAS = parallel::mclapply(lambdas,function(lambda) QUIC::QUIC(COV,rho=lambda*(1-diag(p)))$X,mc.cores=MCCORES) KS = sapply(1:length(THETAS),function(i) sum(abs(cov2cor(THETAS[[i]])[upper.tri(diag(p))])>tol)) EBIC = unlist(parallel::mclapply(1:length(THETAS),function(i) EBIC(Theta.glasso=THETAS[[i]],Sigma.hat=COV,n=n,gamma=gamma,tol=tol),mc.cores=MCCORES)) lambda.opt = lambdas[which.min(EBIC)] k.opt = KS[which.min(EBIC)] Theta.opt0 = THETAS[[which.min(EBIC)]] LAMBDA = round(abs(cov2cor(Theta.opt0))<=tol)*1000000 Theta.opt = QUIC::QUIC(COV,rho=LAMBDA)$X par(mfrow=c(1,2)) plot(log(lambdas),EBIC,xlab=expression(log(lambda)),type='b',pch=20,main=paste0('opt.log.lambda = ',log(lambda.opt))) abline(v=log(lambda.opt),col='blue') plot(KS,EBIC,xlab='# edges',type='b',pch=20,main=paste0('opt.n.edges = ',k.opt)) abline(v=k.opt,col='blue') return(list(Theta.opt0=Theta.opt0,Theta.opt=Theta.opt,Graph.opt=round(abs(cov2cor(Theta.opt))>tol),lambda.opt=lambda.opt,k.opt=k.opt)) }
0e0695db103b5cc1b15b3f83eec34424e5e48634
[ "Markdown", "R" ]
5
Markdown
luqingan/SCENA
d115edab5ec7a3c99a856104959a6656adec8c58
7122438414de8c54a2c51b267ad545079058504f
refs/heads/main
<file_sep>package baoshu; import java.util.Scanner; public class advance { public static void main(String[] args) { @SuppressWarnings("resource") Scanner input = new Scanner(System.in); int n = input.nextInt();// 人数 int[] stu = new int[100];// 学生数组 String s1 = "", s2 = "", s3 = "";// 123行 for (int i = 0; i < n; i++) { stu[i] = input.nextInt(); } for (int i = 0; i < n; i++) { if (i % 3 == 0) s1 = s1 +stu[i]+" "; else if (i % 3 == 1) s2 += stu[i]+" "; else s3 += stu[i]+" "; } System.out.println(s1); System.out.println(s2); System.out.println(s3); } }
cd50af868e1bf414679909e763a66f0f86f4a457
[ "Java" ]
1
Java
piner666/Repository-og-PinerZhang
6e1d87ad85edf27cd5082885e3d81998cc3cae65
d2b5bd4810814bcc16279ba77449b63de013e599
refs/heads/main
<file_sep>import React from 'react'; import './Subtext.css'; const Subtext = props => { return ( <p className="subtext">{props.text}</p> ) } export default Subtext;<file_sep>const express = require('express'); const app = express(); var http = require('http').createServer(app); var mySocket = require('socket.io')(http); mySocket.on("connection", () => { console.log(("connect")); }) var AudioContext = require('web-audio-api').AudioContext, context = new AudioContext var buffer, bufferSource; const play = async (req, res, next) => { mySocket.on('stream', function (packet) { //console.log(deserialize(packet)); buffer = context.createBuffer(1, 16384, 10000) bufferSource = context.createBufferSource() buffer.copyToChannel(deserialize(packet), 0) bufferSource.buffer = buffer bufferSource.connect(context.destination) bufferSource.start(); }); }; const stop = async (req, res, next) => { mySocket.on('stream', function (packet) { //console.log(deserialize(packet)); buffer = context.createBuffer(1, 16384, 10000) bufferSource = context.createBufferSource() buffer.copyToChannel(deserialize(packet), 0) bufferSource.buffer = buffer bufferSource.connect(context.destination) bufferSource.stop(); }); };<file_sep>import React from 'react'; import './HeaderLogo.css'; import logo from '../../assets/logo.png' const HeaderLogo = (props) => { return ( <div id="headerLogo"> <img src= {logo} alt="logo de Net'Radio c'est un micro en néon violet entopuré d'un néon vert marquant Net'Radio" /> </div> ); }; export default HeaderLogo;<file_sep>const express = require('express'); const app = express(); var http = require('http').createServer(app); var io = require('socket.io')(http); const multer = require('multer') //use multer to upload blob data const upload = multer(); // set multer to be the upload variable (just like express, see above ( include it, then use it/set it up)) const fs = require('fs'); let websockets = [] // const audioRoutes = require('./routes/audio-routes'); const auditor = require('./controllers/auditor'); io.on("connection", function (ws) { console.log('New Socket connection'); websockets.push(ws) console.log(websockets.length); ws.on("stream", (data) => { io.emit("stream", data) }) ws.on("guestStream", (data) => { io.emit("guestStream", data) }) ws.on("disconnect", function () { websockets = websockets.filter(function (otherWS) { return ws !== otherWS }) }) }) app.use(express.static("public")); app.get('/', (req, res) => { res.send("Application Netradio") }); app.post('/audioUpload', upload.single("audioBlob"), (req, res) => { console.log(req.file); let uploadLocation = __dirname + '/uploads/' + req.file.originalname // where to save the file to. make sure the incoming name has a .wav extension fs.writeFileSync(uploadLocation, Buffer.from(new Uint8Array(req.file.buffer))); // write the blob to the server as a file res.sendStatus(200); //send back that everything went ok }); app.get('/streamer', (req, res) => { res.sendFile("streamer.html", { root: "public" }) }); app.get('/presenter', (req, res) => { res.sendFile("presenter.html", { root: "public" }) }); app.get('/guest', (req, res) => { res.sendFile("guest.html", { root: "public" }) }); app.use('/auditor/play', (req, res) => {audioRoutes}) http.listen(process.env.PORT || 5000, () => { console.log(`Server started on port`); });<file_sep>import React from 'react'; import MenuItem from '../items/MenuItem'; import './MainMenu.css' const mainMenu = () => { return( <div className="mainMenu"> <MenuItem name="ACCUEIL"/> <MenuItem name="PROGRAMMATION"/> <MenuItem name="LIVE"/> <MenuItem name="PODCASTS"/> </div> ); }; export default mainMenu<file_sep>import {BrowserRouter as Router, Switch, Route} from "react-router-dom"; import './App.css'; import Index from '../container/Index'; import Menu from '../components/menus/Menus'; function App() { return ( <Router> <Menu /> <main> <Switch> <Route path="/"><Index /></Route> </Switch> </main> </Router> ); } export default App; <file_sep>import React from 'react'; import {Link} from "react-router-dom"; import './PurpleButton.css'; const PurpleButton = (props) => { return ( <div className="purpleButton"> <Link to={props.link}>{props.text}</Link> </div> ); }; export default PurpleButton;<file_sep>import React from 'react'; import PurpleButton from '../items/PurpleButton'; import MenuItem from '../items/MenuItem'; import './UserMenu.css'; const UserMenu = (props) => { switch(props.user) { case 'announcer': return ( <div className="userMenu"> <MenuItem name="USERNAME"/> {props.user === "visitor" ? <PurpleButton text="S'INSCRIRE" link="/register"/>: <PurpleButton text="SE DECONNECTER" link="/disconnected"/> } </div> ) case 'auditor': return ( <div className="userMenu"> <MenuItem name="DEMANDES DE DROITS"/> <MenuItem name="USERNAME"/> {props.user === "visitor" ? <PurpleButton text="S'INSCRIRE" link="/register"/>: <PurpleButton text="SE DECONNECTER" link="/disconnected"/> } </div> ) case 'admin': return ( <div className="userMenu"> <MenuItem name="DROITS"/> <MenuItem name="DEMANDES DE DROITS"/> <MenuItem name="USERNAME"/> {props.user === "visitor" ? <PurpleButton text="S'INSCRIRE" link="/register"/>: <PurpleButton text="SE DECONNECTER" link="/disconnected"/> } </div> ) default: return( <div className="userMenu"> <MenuItem name="SE CONNECTER"/> {props.user === "visitor" ? <PurpleButton text="S'INSCRIRE" link="/register"/>: <PurpleButton text="SE DECONNECTER" link="/disconnected"/> } </div> ) } } export default UserMenu;<file_sep>version: "3" networks: netradio.net: driver: bridge services: api.radio: container_name: api.radio image: node ports: - "19080:3000" volumes: - ./backend:/usr/src/app/backend - ./backend/node_modules:/usr/src/outside/node_modules working_dir: /usr/src/app/backend command: bash -c 'npm i && npm run dev' links: - mysql.radio networks: - netradio.net env_file: - ./backend/.env.dev front.radio: container_name: front.radio image: node ports: - "3000:3000" volumes: - ./frontend:/usr/src/app/frontend - ./frontend/node_modules:/usr/src/outside/node_modules working_dir: /usr/src/app/frontend command: bash -c 'npm i && npm start' links: - mysql.radio networks: - netradio.net env_file: - ./frontend/.env.dev stdin_open: true mysql.radio: image: mariadb:latest restart: always command: --default-authentication-plugin=mysql_native_password --character-set-server=utf8 --collation-server=utf8_general_ci env_file: - ./backend/mysql/.env.dev ports: - "3307:3306" volumes: - ./backend/mysql_data:/var/lib/mysql networks: - netradio.net phpmyadmin.commande: image: phpmyadmin restart: always ports: - 8080:80 environment: - PMA_ARBITRARY=1 links: - mysql.radio networks: - netradio.net <file_sep>import React, { Component } from 'react'; import './index.css'; import Title from '../components/items/Title'; import Subtitle from '../components/items/Subtitle'; import Subtext from '../components/items/Subtext'; import Player from '../components/player/Player'; import HeaderLogo from '../components/items/HeaderLogo'; class Index extends Component { render() { return( <div className="indexBody"> <div> <HeaderLogo></HeaderLogo> <Title text="KEDUMA EST EN LIVE" /> <Subtitle text="Overwatch un dead Game ?" /> <Player /> <Subtext text="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec at dolor ac massa lobortis dignissim. Duis dictum tristique est non varius. Proin sodales aliquet felis, eu tempus dolor faucibus id. Vivamus vitae dui ut eros posuere gravida. Quisque arcu sem, luctus sit amet eros et, placerat iaculis tortor. Duis sed nunc nec justo posuere eleifend vel viverra turpis. Morbi arcu dolor, maximus euismod mi sit amet, accumsan congue est. Sed malesuada hendrerit magna, a pulvinar sem dapibus in. Pellentesque fermentum arcu id est posuere, sit amet consequat purus pulvinar. Donec non ligula tristique, ullamcorper enim non, vestibulum dui." /> </div> <div> <Title text="PRESENTATION DE NET'RADIO" /> <Subtext text="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec at dolor ac massa lobortis dignissim. Duis dictum tristique est non varius. Proin sodales aliquet felis, eu tempus dolor faucibus id. Vivamus vitae dui ut eros posuere gravida. Quisque arcu sem, luctus sit amet eros et, placerat iaculis tortor. Duis sed nunc nec justo posuere eleifend vel viverra turpis. Morbi arcu dolor, maximus euismod mi sit amet, accumsan congue est. Sed malesuada hendrerit magna, a pulvinar sem dapibus in. Pellentesque fermentum arcu id est posuere, sit amet consequat purus pulvinar. Donec non ligula tristique, ullamcorper enim non, vestibulum dui." /> </div> </div> ); } } export default Index;<file_sep>FROM node:alpine WORKDIR /frontend COPY /frontend/package.json /frontend RUN npm install EXPOSE 3000 COPY . /frontend CMD ["npm", "start"]<file_sep>// const express = require('express'); // const auditor = require('../controllers/auditor'); // const router = express.Router(); // router.get('/play', auditor.play);
f6dea7e6c8b210b08a2d47e423fcbc6ea1b3b3f2
[ "JavaScript", "YAML", "Dockerfile" ]
12
JavaScript
GaetanCom/netRadio-CIASIE
6949761d0a2e554c8b282f78b6bc103e454ee78c
71ae9ec6ff76bd72d7e53e2c621459014c880ce7
refs/heads/master
<repo_name>christopher1027/mandelbrot-visualization<file_sep>/Mandelbrot.c /* * Author: <NAME> * Date: 4/13/2018 */ //Headers #include <stdio.h> #include <unistd.h> #include "system.h" #include "altera_avalon_pio_regs.h" #include "alt_types.h" #include <altera_up_avalon_video_pixel_buffer_dma.h> //to swap front and back buffer #include <math.h> #include <stdlib.h> //for file I/O #include <altera_avalon_mailbox_regs.h> #include <altera_avalon_mailbox.h> #include <altera_avalon_performance_counter.h> alt_u64 time, time1; alt_mailbox_dev** mailbox; alt_mailbox_dev *mailboxes; alt_up_pixel_buffer_dma_dev *my_pixel_buffer; int cpuid = NIOS2_CPU_ID_VALUE; //Variable Declaration int x; int y; int iteration; int value; double imag; double real; int color; double xtemp; int MAX = 1000; //max number of iterations float startReal; float startImag; //Size of the Window Frame int width = 240; int height = 320; //Zoom and Translations of Window Frame double zoom = 0.005; float min_x; float max_x; float min_y; float max_y; //Keep track of Zoom Origin float target_x; float target_y; int found = 1; //Acts as a boolean //Structures typedef struct complex{ float real; float imag; }complexNumber; typedef struct cartesian{ float x_point; float y_point; }cartesianNumber; //Declare structures complexNumber compNum; cartesianNumber P1, P2, Point; //Declare Functions int getColor(int interation); int mandelbrot(float startReal, float startImag, int MAX); complexNumber map(cartesianNumber, cartesianNumber, cartesianNumber); float min_X(cartesianNumber, cartesianNumber); float max_X(cartesianNumber, cartesianNumber); float min_Y(cartesianNumber, cartesianNumber); float max_Y(cartesianNumber, cartesianNumber); int main() { //Open the Pixel Buffer my_pixel_buffer = alt_up_pixel_buffer_dma_open_dev("/dev/video_pixel_buffer_dma_0"); printf ("Program running (UART)...\n"); fprintf (stderr, "Program running (LCD)...\n"); /////////////For Lab05 //Mailboxes alt_u32 message = 0; mailbox = (alt_mailbox_dev**)malloc(4); //alt_mailbox_dev *send_dev, *recv_dev; // Open the four mailboxes mailbox[0] = altera_avalon_mailbox_open("/dev/mailbox_0"); mailbox[1] = altera_avalon_mailbox_open("/dev/mailbox_1"); mailbox[2] = altera_avalon_mailbox_open("/dev/mailbox_2"); mailbox[3] = altera_avalon_mailbox_open("/dev/mailbox_3"); //////////////////////////////////////////////////////////// //Set the initial window frame to encompass: //-2.5 <= x <= 1 //-1 <= y <= 1 P1.x_point = -2.5; P1.y_point = -1; P2.x_point = 1; P2.y_point = 1; while (1) { alt_up_pixel_buffer_dma_clear_screen(my_pixel_buffer,0); for (x = 0; x < width; x++) { for (y = 0; y < height; y++) { //Point to convert Point.x_point = x; Point.y_point = y; // convert a Point to the appropriate complex number compNum = map(Point, P1, P2); //Check if the complex point is a part of the mandelbrot set //And return the amount of iterations value = mandelbrot(compNum.real, compNum.imag, MAX); printf("Value: %d" , value); //Find the first pixel greater than 450 to set as zoom origin if((value > 450) && found == 1){ target_x = compNum.real; target_y = compNum.imag; found = 0; } //send the amount of iterations to return a specific color color = getColor(value); //Draw the pixel to the screen alt_up_pixel_buffer_dma_draw(my_pixel_buffer,color,imag,real); } } alt_up_pixel_buffer_dma_clear_screen(my_pixel_buffer,0); }//end while loop return 0; } float min_X(cartesianNumber P1, cartesianNumber P2){ if(P1.x_point < P2.x_point){ return P1.x_point; }else{ return P2.x_point; } } float max_X(cartesianNumber P1, cartesianNumber P2){ if(P1.x_point > P2.x_point){ return P1.x_point; }else{ return P2.x_point; } } float min_Y(cartesianNumber P1, cartesianNumber P2){ if(P1.y_point < P2.y_point){ return P1.y_point; }else{ return P2.y_point; } } float max_Y(cartesianNumber P1, cartesianNumber P2){ if(P1.y_point < P2.y_point){ return P1.y_point; }else{ return P2.y_point; } } complexNumber map(cartesianNumber P1, cartesianNumber P2, cartesianNumber Point){ //col = Point.x_point row = Point.y_point max_x = max_X(P1, P2); max_y = max_Y(P1, P2); max_x = min_X(P1, P2); max_y = min_Y(P1, P2); //Zoom min_x = target_x - 1 / (pow(1.5,zoom)); max_x = target_x + 1 / (pow(1.5,zoom)); min_y = target_x - .75 / (pow(1.5,zoom)); max_y = target_x + .75 / (pow(1.5,zoom)); compNum.real = Point.x_point/320 * (max_x - min_x) + min_x; compNum.imag = (239-Point.y_point) / 240 * (max_y - min_y) + min_y; return (compNum); } int mandelbrot(float startReal, float startImag, int MAX) { iteration = 0; real = startReal; imag = startImag; xtemp = 0; //Pc(z) = z^2 + c while(((real*real + imag*imag) < 4) && iteration < MAX) { xtemp = real*real - imag*imag + startReal; imag = 2*real*imag + startImag; real = xtemp; iteration++; if(startReal == real && startImag == imag) { //indicates the point is in the mandelbrot set return -1; } } if(iteration >= MAX) { //Point lies within the mandelbrot set return -1; } else { //Return the iteration count return iteration; } } int getColor(int interation){ //Color in mandelbrot set if(iteration == -1) { //Black color = 0x000000; } if(iteration == 0) { //Black color = 0x000000; } else { if(iteration <= 200) { //Red color = 0xFF0000; } if(iteration > 200 && iteration <=400) { //Orange color = 0xFFA500; } if(iteration >400 && iteration <= 600) { //Yellow color = 0xFFFF00; } if(iteration > 600 && iteration <=800) { //Green color = 0x008000; } if(iteration > 800){ //Blue color = 0x0000FF; } } return color; } /* PERF_RESET(PERFORMANCE_COUNTER_0_BASE); PERF_START_MEASURING(PERFORMANCE_COUNTER_0_BASE); for(x=NIOS2_CPU_ID_VALUE; x < 240; x+=2) time = perf_get_total_time ((void*)PERFORMANCE_COUNTER_0_BASE); time += time; altera_avalon_mailbox_post(mailbox[1-cpuid], 1); altera_avalon_mailbox_pend(mailbox[cpuid]); printf ("%d\n", time); alt_up_pixel_buffer_dma_clear_screen(my_pixel_buffer,0); count = count + 1; //PERF_RESET(PERFORMANCE_COUNTER_0_BASE); //End If-Else statement for Rotation */ <file_sep>/README.md # Mandelbrot Programmed a real-time Mandelbrot generator in SystemVerilog using an Altera cyclone FPGA Example of the first frame displayed of the mandelbrot set: ![alt text](https://github.com/christopher1027/Mandelbrot/blob/master/Mandelbrot.jpg) The FPGA that I used: ![alt text](https://github.com/christopher1027/Mandelbrot/blob/master/altera_cyclone_fpga.jpg) Theory: The famous Mandelbrot set is a set of points in the complex plane. The function is C_{n+1} = C_{n}^2 + C_{0} with the initial condition formed by taking the coordinates in the complex plane, C_{0} = x + iy FPGA Implementation: Used an Altera_cyclone FPGA and SystemVerilog which is is a hardware description and hardware verification language for setting up the hardware design of the project Programming: Programmed in c to create the logic necessary to implement the Mandelbrot function. The mandelbrot set is a set a points in the complex plane which is mapped to each pixel to display them to a computer screen.
694db268ccc965d76a343681b1c15c91565ef606
[ "Markdown", "C" ]
2
C
christopher1027/mandelbrot-visualization
d45001fbfc82d93d65fb7ebdb37693a89bd5251d
a9941f14f5eb0da1cd176dc3281d3654ac7c222e
refs/heads/master
<file_sep>#include <CriterioTableauTableau.h> CriterioTableauTableau::CriterioTableauTableau() { numeroCartas = NUMERO_CARTAS_MOV_TABLEAU_TABLEAU; puntuacion = PUNTUACION_TABLEAU_TABLEAU; valoracion = VALORACION_TABLEAU_TABLEAU; } CriterioTableauTableau::CriterioTableauTableau(const CriterioTableauTableau& criterio) : CriterioMovimiento(criterio) { } CriterioTableauTableau::~CriterioTableauTableau() { } bool CriterioTableauTableau::checkMovimiento() const { if (not mazoOrigen->tieneCartas() || mazoOrigen == mazoDestino) { return false; } bool allowedMovement = true; std::stack<Carta> cartasDesplazadas; for (int i = 0; i < numeroCartas && mazoOrigen->tieneCartas(); i++) { if (mazoOrigen->getUltimaCarta()->getVisibilidad()) { Carta cartaDesplazada = mazoOrigen->quitarCarta(); cartasDesplazadas.push(cartaDesplazada); } else { allowedMovement = false; } } const Carta *origen = &cartasDesplazadas.top(); const Carta *destino = mazoDestino->getUltimaCarta(); allowedMovement &= (checkColor(origen, destino) && checkNumeros(origen, destino)); while (not cartasDesplazadas.empty()) { Carta cartaDevuelta = cartasDesplazadas.top(); mazoOrigen->ponerCarta(cartaDevuelta); cartasDesplazadas.pop(); } return allowedMovement; } void CriterioTableauTableau::doMovimiento() const { std::stack<Carta> cartasDesplazadas; for (int i = 0; i < numeroCartas && mazoOrigen->tieneCartas(); i++) { cartasDesplazadas.push(mazoOrigen->quitarCarta()); } while (not cartasDesplazadas.empty()) { Carta &cartaDesplazada = cartasDesplazadas.top(); cartaDesplazada.setVisibilidad(true); mazoDestino->ponerCarta(cartaDesplazada); cartasDesplazadas.pop(); } if (mazoOrigen->tieneCartas() && false == mazoOrigen->getUltimaCarta()->getVisibilidad()) { Carta cartaVolteada = mazoOrigen->quitarCarta(); cartaVolteada.setVisibilidad(true); mazoOrigen->ponerCarta(cartaVolteada); } } void CriterioTableauTableau::undoMovimiento() const { if (mazoDestino->tieneCartas() && true == mazoDestino->getUltimaCarta()->getVisibilidad()) { Carta cartaVolteada = mazoOrigen->quitarCarta(); cartaVolteada.setVisibilidad(false); mazoOrigen->ponerCarta(cartaVolteada); } std::stack<Carta> cartasDesplazadas; for (int i = 0; i < numeroCartas; i++) { cartasDesplazadas.push(mazoDestino->quitarCarta()); } while (not cartasDesplazadas.empty()) { Carta &cartaDesplazada = cartasDesplazadas.top(); cartaDesplazada.setVisibilidad(true); mazoOrigen->ponerCarta(cartaDesplazada); cartasDesplazadas.pop(); } } void CriterioTableauTableau::acepta(CriterioMovimientoVisitor *visitor) { visitor->visita(this); } bool CriterioTableauTableau::checkColor(const Carta *origen, const Carta *destino) const { if (nullptr == destino) return true; return not origen->mismoColor(*destino); } bool CriterioTableauTableau::checkNumeros(const Carta *origen, const Carta *destino) const { if (nullptr == destino) return true; return ((origen->getNumero()->getNumero()) == ((destino->getNumero())->getPrevNumero())); } CriterioMovimiento* CriterioTableauTableau::clone() { return new CriterioTableauTableau(*this); } <file_sep>#include <KlondikeCargarBuilderEspanola.h> #include <memory> KlondikeCargarBuilderEspanola::KlondikeCargarBuilderEspanola() { construyePalos(); construyeNumeros(); } void KlondikeCargarBuilderEspanola::construyePalos() { for (int i = PaloEspanol::Palos::OROS; i != PaloEspanol::Palos::LAST; i++) { anadePalo(i); } } void KlondikeCargarBuilderEspanola::anadePalo(int numeroPalo) { std::shared_ptr<Palo> palo (new PaloEspanol(numeroPalo)); palos.push_back(palo); } void KlondikeCargarBuilderEspanola::construyeNumeros() { for (int i = 0; i != NUM_CARTAS_ESPANOL; i++) { anadeNumero(i); } } void KlondikeCargarBuilderEspanola::anadeNumero(int num) { std::shared_ptr<Numero> numero(nullptr); numero = std::make_shared<NumeroEspanol>(); numero->setNumero(num); numeros.push_back(numero); } <file_sep>#ifndef DESCARTESTOCKCOMMAND_H #define DESCARTESTOCKCOMMAND_H #include <MenuCommand.h> #include <CriterioDescarteStock.h> class DescarteStockCommand : public MenuCommand { public: DescarteStockCommand(); void execute(const KlondikeVista& vista); ~DescarteStockCommand(); }; #endif <file_sep>#ifndef NUMEROESPANOL_H #define NUMEROESPANOL_H #include "Numero.h" const int NUM_CARTAS_ESPANOL = 10; class NumeroEspanol : public Numero { const int numeros[NUM_CARTAS_ESPANOL] = {1,2,3,4,5,6,7,8,9,10}; const char *numeroATexto[NUM_CARTAS_ESPANOL] = { " AS", " DOS", " TRES", " CUATRO", " CINCO", " SEIS", " SIETE", " SOTA", " CABALLO", " REY"}; public: NumeroEspanol(); ~NumeroEspanol(); virtual int getNextNumero(); virtual int getPrevNumero(); const char* getTextoNumero() { return numeroATexto[numero]; }; const int getNumero(int numero) { return numeros[numero]; }; }; #endif // NUMEROESPANOL_H <file_sep>#ifndef STOCK_H #define STOCK_H #include <Mazo.h> class Stock : public Mazo { public: Stock(); ~Stock(); void acepta(const MazoVisitor* mazoVisitor) const; protected: private: }; #endif <file_sep>#include <HistoricoMovimiento.h> HistoricoMovimiento::HistoricoMovimiento() { } void HistoricoMovimiento::insertMovimiento(CriterioMovimiento* criterio) { undoStack.push(criterio->clone()); while(not redoStack.empty()) { CriterioMovimiento *borrado = redoStack.top(); redoStack.pop(); delete borrado; } } void HistoricoMovimiento::undo() { if (not undoStack.empty()) { CriterioMovimiento* criterio = undoStack.top(); undoStack.pop(); criterio->undoMovimiento(); redoStack.push(criterio); } } void HistoricoMovimiento::redo() { if (not redoStack.empty()) { CriterioMovimiento* criterio = redoStack.top(); redoStack.pop(); criterio->doMovimiento(); undoStack.push(criterio); } } HistoricoMovimiento::~HistoricoMovimiento() { CriterioMovimiento *borrado; while(not undoStack.empty()) { borrado = undoStack.top(); undoStack.pop(); delete borrado; } while(not redoStack.empty()) { borrado = redoStack.top(); redoStack.pop(); delete borrado; } } <file_sep>#ifndef KLONDIKECARGARBUILDER_H #define KLONDIKECARGARBUILDER_H #include <Fundacion.h> #include <Stock.h> #include <Descarte.h> #include <Tableau.h> #include <BarajaEspanolaBuilder.h> #include <BarajaFrancesaBuilder.h> #include <PartidaKlondike.h> #include <Carta.h> class KlondikeCargarBuilder { public: KlondikeCargarBuilder(); std::shared_ptr<Mazo> construyeStock(CartaList &cartas); std::shared_ptr<Mazo> construyeDescarte(CartaList &cartas); std::shared_ptr<Mazo> construyeFundacion(CartaList& cartas, int numeroFundacion); std::shared_ptr<Mazo> construyeTableau(CartaList& cartas, const int numeroTableau); virtual void construyePalos() = 0; virtual void construyeNumeros() = 0; virtual void anadePalo(int numeroPalo) = 0; virtual void anadeNumero(int num) = 0; const std::shared_ptr<Numero>& getNumero(int num); const std::shared_ptr<Palo>& getPalo(int palo); protected: std::vector<std::shared_ptr<Palo>> palos; std::vector<std::shared_ptr<Numero>> numeros; }; #endif // KLONDIKECARGARBUILDER_H <file_sep>#ifndef BARAJA_H #define BARAJA_H #include "Carta.h" #include <vector> #include <algorithm> #include <ctime> class Baraja { public: Baraja(); virtual ~Baraja(); void ponerCarta(const Carta& carta); Carta& robarCarta(); void barajar(); const bool estaVacia() const; protected: private: std::vector<Carta> baraja; }; #endif // BARAJA_H <file_sep>#include <OperacionController.h> OperacionController::OperacionController() { } OperacionController::OperacionController(const std::shared_ptr<PartidaKlondike>& partida) { this->partida = partida; } const std::shared_ptr<PartidaKlondike>& OperacionController::getPartida() const { return this->partida; } OperacionController::~OperacionController() { } <file_sep>#ifndef PALOESPANOL_H #define PALOESPANOL_H #include "Palo.h" const int TIPO_PALO_ESPANOL = 1; class PaloEspanol : public Palo { public: enum Palos { OROS = 0, COPAS, ESPADAS, BASTOS, LAST }; PaloEspanol(const int palo); ~PaloEspanol(); const std::string getTextoPalo() const; const bool mismoColor(const std::shared_ptr<Palo>& palo) const; protected: private: const char *numeroATexto[Palos::LAST] = { " OROS\0", " COPAS\0", " ESPADAS\0", " BASTOS\0"}; }; #endif <file_sep>#include "Carta.h" Carta::Carta() : palo(nullptr), numero(nullptr), visibilidad(false) { } Carta::Carta(const std::shared_ptr<Palo> palo, const std::shared_ptr<Numero> num) : palo(palo), numero(num), visibilidad(false) { } Carta::Carta(const Carta& carta) { this->palo = carta.getPalo(); this->numero = carta.getNumero(); this->visibilidad = carta.getVisibilidad(); } Carta::~Carta() { } bool Carta::mismoNumero(const Carta& carta) const { return this->numero == carta.getNumero(); } bool Carta::mismoColor(const Carta& carta) const { return this->palo->mismoColor(carta.getPalo()); } bool Carta::mismoPalo(const Carta& carta) const { return this->getPalo() == carta.getPalo(); } const std::shared_ptr<Numero> Carta::getNumero() const { return this->numero; } bool Carta::getVisibilidad() const { return visibilidad; } void Carta::setVisibilidad(bool visible) { this->visibilidad = visible; } const std::shared_ptr<Palo> Carta::getPalo() const { return this->palo; } <file_sep>#include "PaloEspanol.h" PaloEspanol::PaloEspanol(const int palo) : Palo(palo, TIPO_PALO_ESPANOL) { } PaloEspanol::~PaloEspanol() { } const bool PaloEspanol::mismoColor(const std::shared_ptr<Palo>& palo) const { return this->getPalo() == palo->getPalo(); } const std::string PaloEspanol::getTextoPalo() const { return numeroATexto[palo]; }; <file_sep>#include "Baraja.h" Baraja::Baraja() { } Baraja::~Baraja() { } void Baraja::ponerCarta(const Carta& carta) { baraja.push_back(carta); } Carta& Baraja::robarCarta() { Carta& carta = baraja.back(); baraja.pop_back(); return carta; } void Baraja::barajar() { std::srand( unsigned (std::time(0))); std::random_shuffle(std::begin(baraja), std::end(baraja)); } const bool Baraja::estaVacia() const { return baraja.size() == 0; } <file_sep>#include <TableauTableauCommand.h> TableauTableauCommand::TableauTableauCommand() : MenuCommand("Mover de tableau a tableau") { criterio = new CriterioTableauTableau(); } void TableauTableauCommand::execute(const KlondikeVista& vista) { receiver->setMazoOrigen(vista.preguntaMazo("Tableau origen", NUMERO_TABLEAUS)); receiver->setMazoDestino(vista.preguntaMazo("Tableau destino", NUMERO_TABLEAUS)); receiver->setCartasParaMover(vista.preguntaCartas()); receiver->setCriterio(criterio); receiver->mover(); } TableauTableauCommand::~TableauTableauCommand() { delete criterio; } <file_sep>#ifndef CRITERIOVISITOR_H #define CRITERIOVISITOR_H class CriterioDescarteStock; class CriterioStockDescarte; class CriterioDescarteFundacion; class CriterioDescarteTableau; class CriterioTableauFundacion; class CriterioTableauTableau; class CriterioFundacionTableau; class CriterioMovimientoVisitor { public: virtual void visita(CriterioDescarteStock *criterio) = 0; virtual void visita(CriterioStockDescarte *criterio) = 0; virtual void visita(CriterioDescarteFundacion *criterio) = 0; virtual void visita(CriterioDescarteTableau *criterio) = 0; virtual void visita(CriterioTableauFundacion *criterio) = 0; virtual void visita(CriterioTableauTableau *criterio) = 0; virtual void visita(CriterioFundacionTableau *criterio) = 0; protected: private: }; #endif <file_sep>#ifndef InicioController_H #define InicioController_H #include <OperacionController.h> #include <KlondikeBuilder.h> class InicioController : public OperacionController { public: InicioController(); InicioController(const std::shared_ptr<PartidaKlondike>& partida); ~InicioController(); void acepta(OperacionControllerVisitor *operacionControllerVisitor); void generarPartida(int tipoBaraja, int pilotoAutomatico); protected: private: int tipoBaraja; }; #endif // InicioController_H <file_sep>#ifndef FUNDACION_H #define FUNDACION_H #include "Mazo.h" class Fundacion : public Mazo { public: Fundacion(); Fundacion(int ind); ~Fundacion(); void acepta(const MazoVisitor* mazoVisitor) const; inline int getIndice() const { return indice; }; protected: private: int indice; }; #endif <file_sep>#include <KlondikeCargarBuilderFrancesa.h> KlondikeCargarBuilderFrancesa::KlondikeCargarBuilderFrancesa() { construyePalos(); construyeNumeros(); } void KlondikeCargarBuilderFrancesa::construyePalos() { for (int i = PaloFrances::Palos::ROMBOS; i != PaloFrances::Palos::LAST; i++) { anadePalo(i); } } void KlondikeCargarBuilderFrancesa::anadePalo(int numeroPalo) { std::shared_ptr<Palo> palo (new PaloFrances(numeroPalo)); palos.push_back(palo); } void KlondikeCargarBuilderFrancesa::construyeNumeros() { for (int i = 0; i != NUM_CARTAS_FRANCES; i++) { anadeNumero(i); } } void KlondikeCargarBuilderFrancesa::anadeNumero(int num) { std::shared_ptr<Numero> numero(nullptr); numero = std::make_shared<NumeroFrances>(); numero->setNumero(num); numeros.push_back(numero); } <file_sep>#include "Logica.h" Logica::Logica() { std::shared_ptr<PartidaKlondike> p (new PartidaKlondike()); this->partida = p; inicioController = new InicioController(partida); moverManualController = new MoverManualController(partida); moverAleatorioController = new MoverAleatorioController(partida); } Logica::~Logica() { } OperacionController* Logica::getController() { OperacionController *returnController = nullptr; switch(partida->getEstado()) { case PartidaKlondike::Estado::INICIAL: returnController = inicioController; break; case PartidaKlondike::Estado::EN_CURSO: returnController = moverManualController; break; case PartidaKlondike::Estado::EN_CURSO_AUTOMATICO: returnController = moverAleatorioController; break; case PartidaKlondike::Estado::SALIR: break; } return returnController; } <file_sep>#ifndef CARTA_H #define CARTA_H #include <Palo.h> #include <Numero.h> #include <cstdint> const int UNDEFINED = 0; class Carta { public: Carta(); Carta(const std::shared_ptr<Palo> palo, const std::shared_ptr<Numero> num); Carta(const Carta& carta); ~Carta(); bool getVisibilidad() const; void setVisibilidad(bool visible); const std::shared_ptr<Numero> getNumero() const; const std::shared_ptr<Palo> getPalo() const; bool mismoNumero(const Carta& carta) const; bool mismoColor(const Carta& carta) const; bool mismoPalo(const Carta& carta) const; protected: private: std::shared_ptr<Palo> palo; std::shared_ptr<Numero> numero; bool visibilidad; }; #endif // CARTA_H <file_sep>#ifndef DESCARTE_H #define DESCARTE_H #include "Mazo.h" class Descarte : public Mazo { public: Descarte(); ~Descarte(); void acepta(const MazoVisitor* mazoVisitor) const; protected: private: }; #endif <file_sep>#ifndef STOCKDESCARTECOMMAND_H #define STOCKDESCARTECOMMAND_H #include <MenuCommand.h> #include <CriterioStockDescarte.h> class StockDescarteCommand : public MenuCommand { public: StockDescarteCommand(); void execute(const KlondikeVista& vista); ~StockDescarteCommand(); }; #endif <file_sep>#ifndef MAZOVISITOR_H #define MAZOVISITOR_H class Stock; class Fundacion; class Tableau; class Descarte; class MazoVisitor { public: virtual void visita(const Stock *stock) const = 0; virtual void visita(const Fundacion *fundacion) const = 0; virtual void visita(const Tableau *tableau) const = 0; virtual void visita(const Descarte *descarte) const = 0; }; #endif <file_sep>#include "KlondikeCargarBuilder.h" KlondikeCargarBuilder::KlondikeCargarBuilder() { } std::shared_ptr<Mazo> KlondikeCargarBuilder::construyeStock(CartaList& cartas) { std::shared_ptr<Mazo> stock(new Stock()); if (!cartas.empty()) { for (CartaList::iterator it = cartas.begin(); it != cartas.end(); ++it) { (*stock).ponerCarta((*it)); } } return stock; } std::shared_ptr<Mazo> KlondikeCargarBuilder::construyeDescarte(CartaList& cartas) { std::shared_ptr<Mazo> descarte(new Descarte()); if (!cartas.empty()) { for (CartaList::iterator it = cartas.begin(); it != cartas.end(); ++it) { (*descarte).ponerCarta((*it)); } } return descarte; } std::shared_ptr<Mazo> KlondikeCargarBuilder::construyeFundacion(CartaList& cartas, int numeroFundacion) { std::shared_ptr<Mazo> fundacion(new Fundacion(numeroFundacion)); if (!cartas.empty()) { for (CartaList::iterator it = cartas.begin(); it != cartas.end(); ++it) { (*fundacion).ponerCarta((*it)); } } return fundacion; } std::shared_ptr<Mazo> KlondikeCargarBuilder::construyeTableau(CartaList& cartas, const int numeroTableau) { std::shared_ptr<Mazo> tableau(new Tableau(numeroTableau)); if (!cartas.empty()) { for (CartaList::iterator it = cartas.begin(); it != cartas.end(); ++it) { (*tableau).ponerCarta((*it)); } } return tableau; } const std::shared_ptr<Numero>& KlondikeCargarBuilder::getNumero(int num) { return numeros[num]; } const std::shared_ptr<Palo>& KlondikeCargarBuilder::getPalo(int palo) { return palos[palo]; } <file_sep>#include <KlondikeBuilder.h> const int NUMERO_TABLEAUS = 7; const int NUMERO_FUNDACIONES = 4; KlondikeBuilder::KlondikeBuilder() { barajaBuilders[0] = new BarajaEspanolaBuilder(); barajaBuilders[1] = new BarajaFrancesaBuilder(); } KlondikeBuilder::~KlondikeBuilder() { delete barajaBuilders[0]; delete barajaBuilders[1]; } void KlondikeBuilder::construyePartida(int tipoBaraja, std::shared_ptr<PartidaKlondike>& partida) { BarajaBuilder *barajaBuilder = barajaBuilders[tipoBaraja]; Baraja baraja =barajaBuilder->construirBaraja(); baraja.barajar(); partida->setMinimo(leePuntuacionMinima(partida)); partida->setTipoPartida(tipoBaraja); construyeTableaus(baraja, partida); partida->addStock(construyeStock(baraja)); MazoPointer descarte (new Descarte()); partida->addDescartes(descarte); construyeFundaciones(baraja, partida); } int KlondikeBuilder::leePuntuacionMinima(std::shared_ptr<PartidaKlondike>& partida) { std::string linea; std::ifstream ficheroPuntuaciones(".ranking"); int puntuacionMinima = 0; for (int i = 0; i<MAX_RANKING; i++) { std::getline(ficheroPuntuaciones, linea, '$'); partida->setNombreRanking(i, linea); std::getline(ficheroPuntuaciones, linea, '\n'); puntuacionMinima = atoi(linea.c_str()); partida->setPuntuacionRanking(i, puntuacionMinima); } return puntuacionMinima; } void KlondikeBuilder::construyeTableaus(Baraja& baraja, std::shared_ptr<PartidaKlondike>& partida) { for(int i = 0; i < NUMERO_TABLEAUS; i++) { partida->addTableau(construyeTableau((baraja), i)); } } void KlondikeBuilder::construyeFundaciones(Baraja& baraja, std::shared_ptr<PartidaKlondike>& partida) { for (int i = 0; i < NUMERO_FUNDACIONES; i++) { MazoPointer fundacion (new Fundacion(i)); partida->addFundacion(fundacion); } } MazoSharedPtr KlondikeBuilder::construyeTableau(Baraja& baraja, const int cartasNoVisibles) { MazoSharedPtr tableau(new Tableau(cartasNoVisibles)); for(int i = 0; i < cartasNoVisibles; i++) { (*tableau).ponerCarta(baraja.robarCarta()); } Carta carta = baraja.robarCarta(); carta.setVisibilidad(true); (*tableau).ponerCarta(carta); return tableau; } MazoSharedPtr KlondikeBuilder::construyeStock(Baraja& baraja) { MazoSharedPtr stock(new Stock()); while(not baraja.estaVacia()) { (*stock).ponerCarta(baraja.robarCarta()); } return stock; } <file_sep>#include "NumeroFrances.h" NumeroFrances::NumeroFrances() { } NumeroFrances::~NumeroFrances() { } int NumeroFrances::getNextNumero() { if (numero == 12) { return 12; } return numero+1; } int NumeroFrances::getPrevNumero() { if (numero == 1) { return 1; } return numero - 1; } <file_sep>#ifndef CRITERIODESCARTESTOCK_H #define CRITERIODESCARTESTOCK_H #include <CriterioMovimiento.h> class CriterioDescarteStock : public CriterioMovimiento { public: CriterioDescarteStock(); CriterioDescarteStock(const CriterioDescarteStock& criterio); ~CriterioDescarteStock(); bool checkMovimiento() const; void doMovimiento() const; void undoMovimiento() const; void acepta(CriterioMovimientoVisitor *visitor); CriterioMovimiento* clone(); protected: private: }; #endif <file_sep>#include <CriterioTableauFundacion.h> #include <iostream> CriterioTableauFundacion::CriterioTableauFundacion() { numeroCartas = NUMERO_CARTAS_MOV_TABLEAU_FUNDACION; puntuacion = PUNTUACION_TABLEAU_FUNDACION; valoracion = VALORACION_TABLEAU_FUNDACION; } CriterioTableauFundacion::CriterioTableauFundacion(const CriterioTableauFundacion& criterio) : CriterioMovimiento(criterio) { } CriterioTableauFundacion::~CriterioTableauFundacion() { } bool CriterioTableauFundacion::checkMovimiento() const { if (not mazoOrigen->tieneCartas()) { return false; } if (not mazoDestino->tieneCartas()) { if (0 == mazoOrigen->getUltimaCarta()->getNumero()->getNumero()) { return true; } else { return false; } } const Carta *origen = mazoOrigen->getUltimaCarta(); const Carta *destino = mazoDestino->getUltimaCarta(); return checkColor(origen, destino) && checkNumeros(origen, destino); } void CriterioTableauFundacion::doMovimiento() const { for (int i = 0; i < numeroCartas; i++) { mazoDestino->ponerCarta(mazoOrigen->quitarCarta()); } if (mazoOrigen->tieneCartas() && false == mazoOrigen->getUltimaCarta()->getVisibilidad()) { Carta cartaVolteada = mazoOrigen->quitarCarta(); cartaVolteada.setVisibilidad(true); mazoOrigen->ponerCarta(cartaVolteada); } } void CriterioTableauFundacion::undoMovimiento() const { if (mazoOrigen->tieneCartas() && true == mazoOrigen->getUltimaCarta()->getVisibilidad()) { Carta cartaVolteada = mazoOrigen->quitarCarta(); cartaVolteada.setVisibilidad(false); mazoOrigen->ponerCarta(cartaVolteada); } for (int i = 0; i < numeroCartas; i++) { mazoOrigen->ponerCarta(mazoDestino->quitarCarta()); } } void CriterioTableauFundacion::acepta(CriterioMovimientoVisitor *visitor) { visitor->visita(this); } bool CriterioTableauFundacion::checkColor(const Carta *origen, const Carta *destino) const { return origen->mismoColor(*destino); } bool CriterioTableauFundacion::checkNumeros(const Carta *origen, const Carta *destino) const { return origen->getNumero()->getNumero() == (destino->getNumero())->getNextNumero(); } CriterioMovimiento* CriterioTableauFundacion::clone() { return new CriterioTableauFundacion(*this); } <file_sep>#include <MoverManualController.h> MoverManualController::MoverManualController() { } MoverManualController::MoverManualController(const std::shared_ptr<PartidaKlondike>& partida) : MoverController(partida) { } MoverManualController::~MoverManualController() { } bool MoverManualController::mover() { bool success = false; if (criterio->checkMovimiento()) { criterio->doMovimiento(); success = true; movimientos.insertMovimiento(criterio); getPartida()->incMarcador(criterio->getPuntuacion()); if (getPartida()->comprobarVictoria()) { terminarPartida(); } } return success; } void MoverManualController::acepta(OperacionControllerVisitor *operacionControllerVisitor) { operacionControllerVisitor->visita(this); } void MoverManualController::visita(CriterioDescarteStock *criterio) { criterio->setMazoOrigen(partida->getDescartes()); criterio->setMazoDestino(partida->getStock()); } void MoverManualController::visita(CriterioStockDescarte *criterio) { criterio->setMazoOrigen(partida->getStock()); criterio->setMazoDestino(partida->getDescartes()); } void MoverManualController::visita(CriterioDescarteFundacion *criterio) { criterio->setMazoOrigen(partida->getDescartes()); criterio->setMazoDestino(partida->getFundacion(mazoDestino)); } void MoverManualController::visita(CriterioDescarteTableau *criterio) { criterio->setMazoOrigen(partida->getDescartes()); criterio->setMazoDestino(partida->getTableau(mazoDestino)); } void MoverManualController::visita(CriterioTableauFundacion *criterio) { criterio->setMazoOrigen(partida->getTableau(mazoOrigen)); criterio->setMazoDestino(partida->getFundacion(mazoDestino)); } void MoverManualController::visita(CriterioTableauTableau *criterio) { criterio->setCartasParaMover(numeroCartas); criterio->setMazoOrigen(partida->getTableau(mazoOrigen)); criterio->setMazoDestino(partida->getTableau(mazoDestino)); } void MoverManualController::visita(CriterioFundacionTableau *criterio) { criterio->setMazoOrigen(partida->getFundacion(mazoOrigen)); criterio->setMazoDestino(partida->getTableau(mazoDestino)); } <file_sep>#ifndef KLONDIKEMENU_H #define KLONDIKEMENU_H const int N_OPTIONS = 12; #include <DescarteStockCommand.h> #include <StockDescarteCommand.h> #include <DescarteFundacionCommand.h> #include <DescarteTableauCommand.h> #include <TableauFundacionCommand.h> #include <TableauTableauCommand.h> #include <FundacionTableauCommand.h> #include <SalvarCommand.h> #include <CargarCommand.h> #include <DeshacerCommand.h> #include <RehacerCommand.h> #include <TerminarCommand.h> #include <KlondikeVista.h> #include <list> #include <string> #include <sstream> class KlondikeMenu { public: KlondikeMenu(); std::list<std::string> getOptions() const; int generateRandomSelection(MoverController* controller); void execute(MoverManualController* receiver, const KlondikeVista& vista); void execute(MoverAleatorioController* receiver, const KlondikeVista& vista); ~KlondikeMenu(); private: MenuCommand *comandos[N_OPTIONS]; }; #endif <file_sep>#ifndef BARAJABUILDER_H #define BARAJABUILDER_H #include "Baraja.h" class BarajaBuilder { public: BarajaBuilder(); virtual ~BarajaBuilder(); Baraja& construirBaraja(); Baraja& getBaraja(); protected: void anadePalo(const std::shared_ptr<Palo>& palo); void anadeNumero(const std::shared_ptr<Numero>& numero); std::vector<std::shared_ptr<Palo>> palos; std::vector<std::shared_ptr<Numero>> numeros; Baraja baraja; private: virtual void construirPalos() = 0; virtual void construirNumeros() = 0; int getTotalCartas(); }; #endif <file_sep>#include "Palo.h" const int TIPO_PALO_FRANCES = 2; class PaloFrances : public Palo { public: enum Palos { ROMBOS, CORAZONES, TREBOLES, PICAS, LAST }; PaloFrances(); PaloFrances(const int palo); ~PaloFrances(); const std::string getTextoPalo() const; const bool mismoColor(const std::shared_ptr<Palo>& palo) const; protected: private: const char *numeroATexto[Palos::LAST] = { " ROMBOS\0", "CORAZONES\0", "TREBOLES\0", " PICAS\0"}; }; <file_sep>#ifndef COORDENADA_H #define COORDENADA_H #include <cstdint> class Coordenada { int coordenadaX; int coordenadaY; public: Coordenada(); Coordenada(int coordX, int coordY); ~Coordenada(); int getCoordX(void) { return coordenadaX; }; int getCoordY(void) { return coordenadaY; }; void setCoordX(int coordX) { coordenadaX = coordX; }; void setCoordY(int coordY) { coordenadaY = coordY; }; void setCoord(int coordX, int coordY); }; #endif // COORDENADA_H <file_sep>#ifndef MOVERMANUALCONTROLLER_H #define MOVERMANUALCONTROLLER_H #include <MoverController.h> #include <CriterioDescarteStock.h> #include <CriterioStockDescarte.h> #include <CriterioDescarteFundacion.h> #include <CriterioDescarteTableau.h> #include <CriterioTableauFundacion.h> #include <CriterioTableauTableau.h> #include <CriterioFundacionTableau.h> class MoverManualController : public MoverController { public: MoverManualController(); MoverManualController(const std::shared_ptr<PartidaKlondike>& partida); ~MoverManualController(); bool mover(); void acepta(OperacionControllerVisitor *operacionControllerVisitor); void visita(CriterioDescarteStock *criterio); void visita(CriterioStockDescarte *criterio); void visita(CriterioDescarteFundacion *criterio); void visita(CriterioDescarteTableau *criterio); void visita(CriterioTableauFundacion *criterio); void visita(CriterioTableauTableau *criterio); void visita(CriterioFundacionTableau *criterio); }; #endif // MoverManualController_H <file_sep>#include "Numero.h" Numero::Numero() { } Numero::~Numero() { } const bool Numero::operator==(const Numero* numero) { return this-numero == numero->numero; } int Numero::getNumero() const { return numero; } <file_sep>#include "PartidaKlondike.h" PartidaKlondike::PartidaKlondike() : marcador (0), minimo(0) { estado = PartidaKlondike::Estado::INICIAL; } PartidaKlondike::PartidaKlondike(const PartidaKlondike& partida) : marcador (0), minimo(0) { this->fundaciones = partida.getFundaciones(); this->tableaus = partida.getTableaus(); this->descartes = partida.getDescartes(); this->stock = partida.getStock(); } PartidaKlondike::~PartidaKlondike() { } void PartidaKlondike::addTableau(const MazoPointer tableau) { tableaus.push_back(tableau); } void PartidaKlondike::addFundacion(const MazoPointer fundacion) { fundaciones.push_back(fundacion); } void PartidaKlondike::addStock(const MazoPointer stock) { this->stock = stock; } void PartidaKlondike::addDescartes(const MazoPointer descartes) { this->descartes = descartes; } void PartidaKlondike::deletePartida() { descartes.reset(); stock.reset(); tableaus.clear(); fundaciones.clear(); } int PartidaKlondike::getEstado() const { return estado; } void PartidaKlondike::setEstado(PartidaKlondike::Estado estado) { this->estado = estado; } MazoPointer PartidaKlondike::getFundacion(int fundacion) { return fundaciones[fundacion]; } int PartidaKlondike::getNumFundaciones() { return fundaciones.size(); } MazoPointer PartidaKlondike::getTableau(int tableau) { return tableaus[tableau]; } int PartidaKlondike::getNumTableaus() { return tableaus.size(); } void PartidaKlondike::incMarcador(int puntuacion) { marcador += puntuacion; if (marcador < 0) { marcador = 0; } } bool PartidaKlondike::tableausVacios() { bool tableausVacios = true; for (int i = 0; i < getNumTableaus(); i++) { if (getTableau(i)->getNumeroCartas() != 0) { tableausVacios = false; } } return tableausVacios; } bool PartidaKlondike::comprobarVictoria() { if (getStock()->getNumeroCartas() == 0 && getDescartes()->getNumeroCartas() == 0 && tableausVacios()) { return true; } return false; } <file_sep>#include <CriterioDescarteStock.h> CriterioDescarteStock::CriterioDescarteStock() { puntuacion = PUNTUACION_DESCARTE_STOCK; valoracion = VALORACION_DESCARTE_STOCK; } CriterioDescarteStock::CriterioDescarteStock(const CriterioDescarteStock& criterio) : CriterioMovimiento(criterio) { } CriterioDescarteStock::~CriterioDescarteStock() { } bool CriterioDescarteStock::checkMovimiento() const { return not mazoDestino->tieneCartas(); } void CriterioDescarteStock::doMovimiento() const { while(mazoOrigen->tieneCartas()) { mazoDestino->ponerCarta(mazoOrigen->quitarCarta()); } } void CriterioDescarteStock::undoMovimiento() const { while(mazoDestino->tieneCartas()) { mazoOrigen->ponerCarta(mazoDestino->quitarCarta()); } } void CriterioDescarteStock::acepta(CriterioMovimientoVisitor *visitor) { visitor->visita(this); } CriterioMovimiento* CriterioDescarteStock::clone() { return new CriterioDescarteStock(*this); } <file_sep>#ifndef CRITERIOSTOCKDESCARTE_H #define CRITERIOSTOCKDESCARTE_H #include <CriterioMovimiento.h> #include <stack> class CriterioStockDescarte : public CriterioMovimiento { public: CriterioStockDescarte(); CriterioStockDescarte(const CriterioStockDescarte& criterio); ~CriterioStockDescarte(); bool checkMovimiento() const; void doMovimiento() const; void undoMovimiento() const; void acepta(CriterioMovimientoVisitor *visitor); CriterioMovimiento* clone(); protected: private: }; #endif <file_sep>#include "Enmarcado.h" #include <assert.h> #include <string.h> Enmarcado::Enmarcado(VistaTablero *vistaTablero) { tablero = vistaTablero; } Enmarcado::~Enmarcado() { } void Enmarcado::pintaRayaVertical(Coordenada *inicio, int longitud, const char caracter) { assert((inicio->getCoordY() + longitud) < (DOBLE*tablero->getTamanoY())); char **tableroAPintar = tablero->getTableroAImprimir(); for (int i = inicio->getCoordY(); i < (inicio->getCoordY()+longitud); i++) { memcpy(&(tableroAPintar[i][inicio->getCoordX()]), &caracter, sizeof(caracter)); } } void Enmarcado::pintaRayaHorizontal(Coordenada *inicio, int longitud, const char caracter) { assert((inicio->getCoordX() + longitud) < (DOBLE*tablero->getTamanoX())); char **tableroAPintar = tablero->getTableroAImprimir(); for (int i = inicio->getCoordX(); i <= (inicio->getCoordX()+longitud); i++) { memcpy(&(tableroAPintar[inicio->getCoordY()][i]), &caracter, sizeof(caracter)); } } <file_sep>#ifndef BARAJAESPANOLABUILDER_H #define BARAJAESPANOLABUILDER_H #include <BarajaBuilder.h> #include <PaloEspanol.h> #include <NumeroEspanol.h> class BarajaEspanolaBuilder : public BarajaBuilder { public: BarajaEspanolaBuilder(); ~BarajaEspanolaBuilder(); void construirBaraja(); protected: private: void construirPalos(); void construirNumeros(); }; #endif <file_sep>#include "Descarte.h" Descarte::Descarte() { } Descarte::~Descarte() { } void Descarte::acepta(const MazoVisitor* mazoVisitor) const { mazoVisitor->visita(this); } <file_sep>#include <CriterioDescarteTableau.h> CriterioDescarteTableau::CriterioDescarteTableau() { numeroCartas = NUMERO_CARTAS_MOV_DESCARTE_TABLEAU; puntuacion = PUNTUACION_DESCARTE_TABLEAU; valoracion = VALORACION_DESCARTE_TABLEAU; } CriterioDescarteTableau::CriterioDescarteTableau(const CriterioDescarteTableau& criterio) : CriterioMovimiento(criterio) { } CriterioDescarteTableau::~CriterioDescarteTableau() { } bool CriterioDescarteTableau::checkMovimiento() const { if (not mazoOrigen->tieneCartas()) { return false; } const Carta *origen = mazoOrigen->getUltimaCarta(); const Carta *destino = mazoDestino->getUltimaCarta(); if (not mazoDestino->tieneCartas()) { return true; } return checkColor(origen, destino) && checkNumeros(origen, destino); } void CriterioDescarteTableau::doMovimiento() const { for (int i = 0; i < numeroCartas; i++) { mazoDestino->ponerCarta(mazoOrigen->quitarCarta()); } } void CriterioDescarteTableau::undoMovimiento() const { for (int i = 0; i < numeroCartas; i++) { mazoOrigen->ponerCarta(mazoDestino->quitarCarta()); } } void CriterioDescarteTableau::acepta(CriterioMovimientoVisitor *visitor) { visitor->visita(this); } bool CriterioDescarteTableau::checkColor(const Carta *origen, const Carta *destino) const { return not origen->mismoColor(*destino); } bool CriterioDescarteTableau::checkNumeros(const Carta *origen, const Carta *destino) const { return origen->getNumero()->getNumero() == (destino->getNumero())->getPrevNumero(); } CriterioMovimiento* CriterioDescarteTableau::clone() { return new CriterioDescarteTableau(*this); } <file_sep>#include <MenuCommand.h> MenuCommand::MenuCommand() : receiver(nullptr) { } MenuCommand::MenuCommand(const std::string& description) : receiver(nullptr), description(description) { } void MenuCommand::setReceiver(MoverController* receiver) { this->receiver = receiver; } void MenuCommand::test() { this->criterio->acepta(this->receiver); } std::string MenuCommand::getDescription() { return description; } MenuCommand::~MenuCommand() { } <file_sep>#ifndef CRITERIOMOVIMIENTO_H #define CRITERIOMOVIMIENTO_H #include <Mazo.h> #include <CriterioMovimientoVisitor.h> const int PUNTUACION_DESCARTE_FUNDACION = 10; const int PUNTUACION_DESCARTE_STOCK = -100; const int PUNTUACION_DESCARTE_TABLEAU = 5; const int PUNTUACION_FUNDACION_TABLEAU = -15; const int PUNTUACION_STOCK_DESCARTE = 0; const int PUNTUACION_TABLEAU_FUNDACION = 10; const int PUNTUACION_TABLEAU_TABLEAU = 0; const int NUMERO_CARTAS_MOV_DESCARTE_FUNDACION = 1; const int NUMERO_CARTAS_MOV_DESCARTE_TABLEAU = 1; const int NUMERO_CARTAS_MOV_FUNDACION_TABLEAU = 1; const int NUMERO_CARTAS_MOV_STOCK_DESCARTE = 3; const int NUMERO_CARTAS_MOV_TABLEAU_FUNDACION = 1; const int NUMERO_CARTAS_MOV_TABLEAU_TABLEAU = 1; const int VALORACION_DESCARTE_STOCK = 2; const int VALORACION_STOCK_DESCARTE = 3; const int VALORACION_DESCARTE_FUNDACION = 12; const int VALORACION_DESCARTE_TABLEAU = 4; const int VALORACION_TABLEAU_FUNDACION = 10; const int VALORACION_TABLEAU_TABLEAU = 8; const int VALORACION_FUNDACION_TABLEAU = 1; class CriterioMovimiento { public: CriterioMovimiento(); CriterioMovimiento(const CriterioMovimiento& criterio); virtual ~CriterioMovimiento(); virtual bool checkMovimiento() const = 0; virtual void doMovimiento() const = 0; virtual void undoMovimiento() const = 0; void setMazoOrigen(MazoPointer mazoOrigen); void setMazoDestino(MazoPointer mazoDestino); void setCartasParaMover(int numeroCartas); int getPuntuacion() { return puntuacion; }; int getValoracion() { return valoracion; }; virtual void acepta(CriterioMovimientoVisitor *visitor) = 0; virtual CriterioMovimiento* clone() = 0; protected: int numeroCartas; int puntuacion; int valoracion; MazoPointer mazoOrigen; MazoPointer mazoDestino; private: }; #endif <file_sep>#include <PartidaVista.h> PartidaVista::PartidaVista() { } PartidaVista::PartidaVista(OperacionController *controlador) { this->controlador = controlador; } PartidaVista::~PartidaVista() { } void PartidaVista::pinta() { std::shared_ptr<PartidaKlondike> partida = controlador->getPartida(); MazoPointer mazo = partida->getDescartes(); mazo->acepta(this); mazo = partida->getStock(); mazo->acepta(this); MazoList fundaciones = partida->getFundaciones(); for (MazoList::iterator it = fundaciones.begin(); it != fundaciones.end(); ++it) { (*it)->acepta(this); } printTableaus(partida); printFundaciones(partida); } void PartidaVista::printTableaus(std::shared_ptr<PartidaKlondike> partida) { MazoList tableaus = partida->getTableaus(); int nTableau = 0; for (MazoList::iterator it = tableaus.begin(); it != tableaus.end(); ++it) { (*it)->acepta(this); nTableau++; } } void PartidaVista::printFundaciones(std::shared_ptr<PartidaKlondike> partida) { MazoList fundaciones = partida->getFundaciones(); int nFundacion = 0; for (MazoList::iterator it = fundaciones.begin(); it != fundaciones.end(); ++it) { (*it)->acepta(this); nFundacion++; } } void PartidaVista::visita(const Stock *stock) const { } void PartidaVista::visita(const Fundacion *fundacion) const { } void PartidaVista::visita(const Tableau *tableau) const { } void PartidaVista::visita(const Descarte *descarte) const { } <file_sep>#include "PaloFrances.h" PaloFrances::PaloFrances(const int palo) : Palo(palo, TIPO_PALO_FRANCES) { } PaloFrances::~PaloFrances() { } const bool PaloFrances::mismoColor(const std::shared_ptr<Palo>& palo) const { bool thisRojo = false; bool paloRojo = false; if (ROMBOS == this->getPalo() || CORAZONES == this->getPalo()) { thisRojo = true; } if (ROMBOS == palo->getPalo() || CORAZONES == palo->getPalo()) { paloRojo = true; } return thisRojo == paloRojo; } const std::string PaloFrances::getTextoPalo() const { return numeroATexto[palo]; } <file_sep>#ifndef OPERACIONCONTROLLERVISITOR_H #define OPERACIONCONTROLLERVISITOR_H class InicioController; class MoverManualController; class MoverAleatorioController; class OperacionControllerVisitor { public: virtual void visita(InicioController *inicioController) = 0; virtual void visita(MoverManualController *moverController) = 0; virtual void visita(MoverAleatorioController *moverController) = 0; }; #endif <file_sep>#include <InicioController.h> InicioController::InicioController() { } InicioController::InicioController(const std::shared_ptr<PartidaKlondike>& partida) : OperacionController(partida) { } InicioController::~InicioController() { } void InicioController::generarPartida(int tipoBaraja, int pilotoAutomatico) { // TODO: Patron para generar el tipo de partida dependiendo de la baraja KlondikeBuilder partidaBuilder; partidaBuilder.construyePartida(tipoBaraja, partida); if (pilotoAutomatico) { partida->setEstado(PartidaKlondike::Estado::EN_CURSO_AUTOMATICO); } else { partida->setEstado(PartidaKlondike::Estado::EN_CURSO); } } void InicioController::acepta(OperacionControllerVisitor *operacionController) { operacionController->visita(this); } <file_sep>#ifndef RESOLUCION_H #define RESOLUCION_H //class VistaTablero; class Resolucion { // VistaTablero *tablero; public: enum POSICIONES { coordXAlta = 150, coordXBaja = 70, coordYAlta = 54, coordYBaja = 30 }; Resolucion(); ~Resolucion(); int getTamano(); void pedirTamano(); void setAltaResolucion(); void setBajaResolucion(); // VistaTablero* getTablero() { return tablero; }; }; #endif // RESOLUCION_H <file_sep>#ifndef NUMERO_H #define NUMERO_H class Numero { protected: int numero; public: Numero(); ~Numero(); const bool operator==(const Numero* numero); void setNumero(int num) { numero = num; }; int getNumero() const; virtual int getNextNumero() = 0; virtual int getPrevNumero() = 0; virtual const char* getTextoNumero() =0; }; #endif // NUMERO_H <file_sep>#ifndef DESCARTEFUNDACIONCOMMAND_H #define DESCARTEFUNDACIONCOMMAND_H #include <MenuCommand.h> #include <CriterioDescarteFundacion.h> class DescarteFundacionCommand : public MenuCommand { public: DescarteFundacionCommand(); void execute(const KlondikeVista& vista); ~DescarteFundacionCommand(); }; #endif <file_sep>#ifndef BARAJAFRANCESABUILDER_H #define BARAJAFRANCESABUILDER_H #include <BarajaBuilder.h> #include <PaloFrances.h> #include <NumeroFrances.h> class BarajaFrancesaBuilder : public BarajaBuilder { public: BarajaFrancesaBuilder(); ~BarajaFrancesaBuilder(); void construirBaraja(); protected: private: void construirPalos(); void construirNumeros(); }; #endif <file_sep>#include <CargarCommand.h> CargarCommand::CargarCommand() : MenuCommand("Cargar partida") { } void CargarCommand::execute(const KlondikeVista& vista) { std::string nombrePartida = vista.preguntaNombreFichero(); while (not vista.compruebaFichero(nombrePartida)) { std::cout << "Fichero de partida no encontrado. Introduzca un nombre de partida existente" << std::endl; nombrePartida = vista.preguntaNombreFichero(); } VistaCargarPartida cargar(nombrePartida); cargar.cargar(receiver->getPartida()); } CargarCommand::~CargarCommand() { } <file_sep>#include "Resolucion.h" #include <iostream> Resolucion::Resolucion() { pedirTamano(); } Resolucion::~Resolucion() { } void Resolucion::pedirTamano() { do { std::cout << "Introduzca el tamano de tablero deseado:\n\n" ; } while (getTamano()); } int Resolucion::getTamano() { char c; std::cout << "\ta) " << coordXAlta << "x" << coordYAlta << " caracteres\n"; std::cout << "\tb) " << coordXBaja << "x" << coordYBaja << " caracteres\n\n"; // Forzamos al juego a usar el tablero de alta resolucion c = 'a'; if (c == 'a' || c == 'A') { setAltaResolucion(); return 0; } else if (c == 'b' || c == 'B') { setAltaResolucion(); return 0; } return 1; } void Resolucion::setAltaResolucion() { } void Resolucion::setBajaResolucion() { } <file_sep>#ifndef MAZO_H #define MAZO_H #include <Carta.h> #include <MazoVisitor.h> #include <vector> typedef std::vector<Carta> CartaList; class Mazo { public: Mazo(); ~Mazo(); bool tieneCartas() const; int getNumeroCartas() const; int getNumeroCartasNoVisibles() const; int getNumeroCartasVisibles() const; const Carta* getUltimaCarta() const; const CartaList getCartas() const; void ponerCarta(Carta& carta); Carta& quitarCarta(); virtual void acepta(const MazoVisitor *mazoVisitor) const = 0; protected: CartaList mazo; private: }; typedef std::shared_ptr<Mazo> MazoPointer; #endif <file_sep>#ifndef ENMARCADO_H #define ENMARCADO_H #include "../modelos/Coordenada.h" #include "VistaTablero.h" #include <iostream> class Coordenada; class Enmarcado { VistaTablero *tablero; public: Enmarcado(VistaTablero *vistaTablero); ~Enmarcado(); void pintaRayaHorizontal(Coordenada *inicio, const int longitud, const char caracter); void pintaRayaVertical(Coordenada *inicio, const int longitud, const char caracter); }; #endif // ENMARCADO_H <file_sep>#ifndef REHACERCOMMAND_H #define REHACERCOMMAND_H #include <MenuCommand.h> class RehacerCommand : public MenuCommand { public: RehacerCommand(); void execute(const KlondikeVista& vista); ~RehacerCommand(); }; #endif <file_sep>#ifndef LOGICA_H #define LOGICA_H #include <InicioController.h> #include <MoverManualController.h> #include <MoverAleatorioController.h> class Logica { public: Logica(); ~Logica(); OperacionController *getController(); protected: private: std::shared_ptr<PartidaKlondike> partida; OperacionController *inicioController; OperacionController *moverManualController; OperacionController *moverAleatorioController; }; #endif <file_sep>#include "Stock.h" Stock::Stock() { } Stock::~Stock() { } void Stock::acepta(const MazoVisitor* mazoVisitor) const { mazoVisitor->visita(this); } <file_sep>#ifndef SALVARCOMMAND_H #define SALVARCOMMAND_H #include <MenuCommand.h> #include <VistaSalvarPartida.h> class SalvarCommand : public MenuCommand { public: SalvarCommand(); void execute(const KlondikeVista& vista); ~SalvarCommand(); }; #endif <file_sep>#include <CriterioStockDescarte.h> CriterioStockDescarte::CriterioStockDescarte() { numeroCartas = NUMERO_CARTAS_MOV_STOCK_DESCARTE; puntuacion = PUNTUACION_STOCK_DESCARTE; valoracion = VALORACION_STOCK_DESCARTE; } CriterioStockDescarte::CriterioStockDescarte(const CriterioStockDescarte& criterio) : CriterioMovimiento(criterio) { } CriterioStockDescarte::~CriterioStockDescarte() { } bool CriterioStockDescarte::checkMovimiento() const { bool retval = false; if (mazoOrigen->tieneCartas()) { retval = true; } return retval; } void CriterioStockDescarte::doMovimiento() const { std::stack<Carta> cartasDesplazadas; for(int i = 0; i < numeroCartas && mazoOrigen->tieneCartas(); i++) { cartasDesplazadas.push(*(mazoOrigen->getUltimaCarta())); mazoOrigen->quitarCarta(); } while(not cartasDesplazadas.empty()) { Carta cartaDesplazada = cartasDesplazadas.top(); cartaDesplazada.setVisibilidad(true); mazoDestino->ponerCarta(cartaDesplazada); cartasDesplazadas.pop(); } } void CriterioStockDescarte::undoMovimiento() const { std::stack<Carta> cartasDesplazadas; for(int i = 0; i < numeroCartas && mazoDestino->tieneCartas(); i++) { cartasDesplazadas.push(*(mazoDestino->getUltimaCarta())); mazoDestino->quitarCarta(); } while(not cartasDesplazadas.empty()) { Carta cartaDesplazada = cartasDesplazadas.top(); cartaDesplazada.setVisibilidad(false); mazoOrigen->ponerCarta(cartaDesplazada); cartasDesplazadas.pop(); } } void CriterioStockDescarte::acepta(CriterioMovimientoVisitor *visitor) { visitor->visita(this); } CriterioMovimiento* CriterioStockDescarte::clone() { return new CriterioStockDescarte(*this); } <file_sep>#ifndef NUMEROFRANCES_H #define NUMEROFRANCES_H #include "Numero.h" const int NUM_CARTAS_FRANCES = 13; class NumeroFrances : public Numero { const char *numeroATexto[NUM_CARTAS_FRANCES+1] = { " AS", " DOS", " TRES", " CUATRO", " CINCO", " SEIS", " SIETE", " OCHO", " NUEVE", " DIEZ", " JACK", " REINA", " REY" }; public: NumeroFrances(); ~NumeroFrances(); int getNextNumero(); int getPrevNumero(); const char *getTextoNumero() { return numeroATexto[numero]; }; }; #endif // NUMEROFRANCES_H <file_sep>#ifndef KLONDIKEBUILDER_H #define KLONDIKEBUILDER_H #include <Fundacion.h> #include <Stock.h> #include <Descarte.h> #include <Tableau.h> #include <BarajaEspanolaBuilder.h> #include <BarajaFrancesaBuilder.h> #include <PartidaKlondike.h> #include <fstream> #include <iostream> const int NUMERO_BARAJAS=2; typedef std::shared_ptr<Mazo> MazoSharedPtr; class KlondikeBuilder { public: KlondikeBuilder(); ~KlondikeBuilder(); virtual void construyePartida(int tipoBaraja, std::shared_ptr<PartidaKlondike>& partida); void construyeFundaciones(Baraja& baraja, std::shared_ptr<PartidaKlondike>& partida); void construyeTableaus(Baraja& baraja, std::shared_ptr<PartidaKlondike>& partida); int leePuntuacionMinima(std::shared_ptr<PartidaKlondike>& partida); protected: private: BarajaBuilder *barajaBuilders[NUMERO_BARAJAS]; virtual MazoSharedPtr construyeTableau(Baraja& baraja, const int cartasNoVisibles); virtual MazoSharedPtr construyeStock(Baraja& baraja); }; #endif <file_sep>#include <VistaTableroGrande.h> #include <Enmarcado.h> #include <Carta.h> #include <PaloEspanol.h> #include <NumeroEspanol.h> #include <string.h> #include <algorithm> #include <KlondikeMenu.h> #include <PartidaKlondike.h> VistaTableroGrande::VistaTableroGrande() { inicializaPosiciones(); } VistaTableroGrande::~VistaTableroGrande() { } void VistaTableroGrande::inicializaPosiciones() { // Posicionamos los stocks int valorX = PRIMERA_POSICION_X; int i = 0; // Marcamos la posicion de las cartas de la primera fila posiCoordenadaX[i] = valorX; posiCoordenadaY[i] = POSICION_ARRIBA_Y; i++; valorX += LONG_CANTO_HORIZONTAL_SUPERIOR + MARGEN_SIMPLE_HORIZONTAL; posiCoordenadaX[i] = valorX; posiCoordenadaY[i] = POSICION_ARRIBA_Y; i++; valorX += LONG_CANTO_HORIZONTAL_SUPERIOR + MARGEN_DOBLE_HORIZONTAL_SUPERIOR; // Posicionamos las 4 fundaciones for (int j=i; i<j+NUM_PALOS; i++) { posiCoordenadaX[i] = valorX; posiCoordenadaY[i] = POSICION_ARRIBA_Y; valorX += LONG_CANTO_HORIZONTAL_SUPERIOR + MARGEN_HORIZONTAL_ENTRE_PALOS; } // Posicionamos los tableaus valorX = PRIMERA_POSICION_X; for (int j = 1; j<= NUMERO_TABLEAUS; j++) { for (int k = 0; k<j+NUM_CARTAS_PALO; k++) { posiCoordenadaX[i] = valorX; posiCoordenadaY[i] = POSICION_ABAJO_Y + ((k-j)*MARGEN_VERTICAL); valorX++; i++; } valorX = PRIMERA_POSICION_X + (j * (LONG_CANTO_HORIZONTAL_SUPERIOR + MARGEN_SIMPLE_HORIZONTAL)); } } void VistaTableroGrande::imprimeMarco() { Coordenada *coordenadaInicio = new Coordenada(MARGEN_HORIZONTAL_TABLERO, MARGEN_VERTICAL_TABLERO); Enmarcado *marcoTablero = new Enmarcado(this); // Imprimimos barra horizontal de arriba marcoTablero->pintaRayaHorizontal(coordenadaInicio, Resolucion::coordXAlta, '*'); // Imprimimos barra vertical izquierda marcoTablero->pintaRayaVertical(coordenadaInicio, Resolucion::coordYAlta, '*'); // Imprimimos barra horizontal de abajo coordenadaInicio->setCoordY(Resolucion::coordYAlta+MARGEN_VERTICAL_TABLERO); marcoTablero->pintaRayaHorizontal(coordenadaInicio, Resolucion::coordXAlta, '*'); // Imprimimos barra vertical derecha coordenadaInicio->setCoordY(MARGEN_VERTICAL_TABLERO); coordenadaInicio->setCoordX(Resolucion::coordXAlta+MARGEN_HORIZONTAL_TABLERO); marcoTablero->pintaRayaVertical(coordenadaInicio, Resolucion::coordYAlta, '*'); delete coordenadaInicio; delete marcoTablero; } void VistaTableroGrande::imprimeMenu(const KlondikeMenu& menu) { int posX = Resolucion::coordXAlta + MARGEN_HORIZONTAL_MENU; int posY = MARGEN_VERTICAL_MENU; std::string imprimir = " MENU "; memcpy(tableroAImprimir[posY]+posX, imprimir.c_str(), imprimir.length()); posY++; imprimir = "¿Que movimiento desea hacer? "; posX = Resolucion::coordXAlta + MARGEN_HORIZONTAL_MENU_CORTO; posY++; memcpy(tableroAImprimir[posY]+posX, imprimir.c_str(), imprimir.length()); posY++; std::list<std::string> options = menu.getOptions(); for (auto it : options) { posY++; memcpy(tableroAImprimir[posY]+posX, it.c_str(), it.length()); } } void VistaTableroGrande::imprimeRanking(std::shared_ptr<PartidaKlondike> partida) { int posX = Resolucion::coordXAlta + MARGEN_HORIZONTAL_MENU; int posY = MARGEN_VERTICAL_RANKING; std::string imprimir = "RANKING"; memcpy(tableroAImprimir[posY]+posX, imprimir.c_str(), imprimir.length()); posY++; imprimir = "NOMBRE PUNTUACION"; posX = Resolucion::coordXAlta + MARGEN_HORIZONTAL_MENU_CORTO; posY++; std::stringstream linea; for (int i=0; i<TAMANO_RANKING; i++) { linea.str(""); linea << partida->getNombreRanking(i) << partida->getPuntuacionRanking(i); memcpy(tableroAImprimir[posY]+posX, linea.str().c_str(), TAMANO_MAXIMO_NOMBRE_RANKING); posY++; } } void VistaTableroGrande::imprimeLeyendas() { std::string imprimir = "STOCK"; memcpy(tableroAImprimir[LEYENDA_ARRIBA_Y]+LEYENDA_STOCK_X, imprimir.c_str(), imprimir.length()); imprimir = "DESCARTES"; memcpy(tableroAImprimir[LEYENDA_ARRIBA_Y]+LEYENDA_DESCARTES_X, imprimir.c_str(), imprimir.length()); for (int i=0; i<NUM_PALOS; i++) { imprimir = "FUNDACION "+ std::to_string(i); memcpy(tableroAImprimir[LEYENDA_ARRIBA_Y]+LEYENDA_FUNDACION_1 + (i*MARGEN_LEYENDA_FUNDACIONES), imprimir.c_str(), imprimir.length()); } for (int i=0; i<NUMERO_TABLEAUS; i++) { imprimir = "TABLEAU "+ std::to_string(i); memcpy(tableroAImprimir[LEYENDA_ABAJO_Y]+LEYENDA_TABLEAU_1 + (i*MARGEN_LEYENDA_TABLEAUS), imprimir.c_str(), imprimir.length()); } } void VistaTableroGrande::imprimeMarcador(int marcador) { Coordenada *coordenadaInicio = new Coordenada(Resolucion::coordXAlta + MARGEN_MARCADOR_X, MARGEN_MARCADOR_Y); Enmarcado *marcoTablero = new Enmarcado(this); std::string imprimir = " MARCADOR "; int posX = Resolucion::coordXAlta + MARGEN_MARCADOR_X; int posY = MARGEN_LEYENDA_MARCADOR_Y; memcpy(tableroAImprimir[posY]+posX, imprimir.c_str(), imprimir.length()); posX += MARGEN_MENU_DESPLAZAMIENTO; posY += MARGEN_VERTICAL_TABLERO; imprimir = std::to_string(marcador); memcpy(tableroAImprimir[posY]+posX, imprimir.c_str(), imprimir.length()); // Imprimimos barra horizontal de arriba marcoTablero->pintaRayaHorizontal(coordenadaInicio, MARGEN_MARCADOR_Y, '*'); // Imprimimos barra vertical izquierda marcoTablero->pintaRayaVertical(coordenadaInicio, MARGEN_VERTICAL, '*'); // Imprimimos barra horizontal de abajo coordenadaInicio->setCoordY(MARGEN_MARCADOR_Y + MARGEN_VERTICAL); marcoTablero->pintaRayaHorizontal(coordenadaInicio, MARGEN_MARCADOR_Y, '*'); // Imprimimos barra vertical derecha coordenadaInicio->setCoordY(MARGEN_MARCADOR_Y); coordenadaInicio->setCoordX(Resolucion::coordXAlta + MARGEN_MARCADOR_X + MARGEN_MARCADOR_Y); marcoTablero->pintaRayaVertical(coordenadaInicio, MARGEN_VERTICAL, '*'); delete coordenadaInicio; delete marcoTablero; } void VistaTableroGrande::imprimeTablero(std::shared_ptr<PartidaKlondike> partida) { MazoPointer mazo = partida->getDescartes(); mazo->acepta(this); mazo = partida->getStock(); mazo->acepta(this); printTableaus(partida); printFundaciones(partida); imprimeMarcador(partida->getMarcador()); imprimeMarco(); imprimeLeyendas(); system("clear"); for(int i=0; i<Resolucion::coordYAlta+PRIMERA_POSICION_X; i++) { for(int j=0; j<Resolucion::coordXAlta+TAMANO_MAXIMO_MENU; j++) { printf("%c", tableroAImprimir[i][j]); } printf("\n"); } reInicializarTablero(); } void VistaTableroGrande::printTableaus(std::shared_ptr<PartidaKlondike> partida) { MazoList tableaus = partida->getTableaus(); int nTableau = 0; for (MazoList::iterator it = tableaus.begin(); it != tableaus.end(); ++it) { (*it)->acepta(this); nTableau++; } } void VistaTableroGrande::printFundaciones(std::shared_ptr<PartidaKlondike> partida) { MazoList fundaciones = partida->getFundaciones(); int nFundacion = 0; for (MazoList::iterator it = fundaciones.begin(); it != fundaciones.end(); ++it) { (*it)->acepta(this); nFundacion++; } } void VistaTableroGrande::visita(const Stock *stock) const { CartaList cartasStock = stock->getCartas(); imprimeCartaNoVisibleDestapada(POSICION_STOCK); if (!stock->tieneCartas()) { imprimeLeyendaSinCarta(POSICION_STOCK); } } void VistaTableroGrande::visita(const Fundacion *fundacion) const { CartaList cartasFundacion = fundacion->getCartas(); int posi = POSICION_FUNDACION + fundacion->getIndice(); if (fundacion->tieneCartas()) { const Carta *carta = fundacion->getUltimaCarta(); imprimeCartaVisibleDestapada((Carta*) carta, posi); } else { imprimeCartaNoVisibleDestapada(posi); imprimeLeyendaSinCarta(posi); } } void VistaTableroGrande::visita(const Tableau *tableau) const { CartaList cartasTableau = tableau->getCartas(); int posi = POSICION_INICIAL_TABLEAUS[tableau->getIndice()]; for (CartaList::iterator it = cartasTableau.begin(); it != cartasTableau.end(); ++it) { if ((*it).getVisibilidad() == false) { imprimeCartaNoVisibleTapada(posi); } else if ((*it).getVisibilidad() == true && it != cartasTableau.end() - 1) { imprimeCartaVisibleTapada(&(*it), posi); } else { imprimeCartaVisibleDestapada(&(*it), posi); } posi++; } } void VistaTableroGrande::visita(const Descarte *descarte) const { if (descarte->tieneCartas()) { const Carta *carta = descarte->getUltimaCarta(); imprimeCartaVisibleDestapada((Carta*) carta, POSICION_DESCARTES); } else { imprimeCartaNoVisibleDestapada(POSICION_DESCARTES); imprimeLeyendaSinCarta(POSICION_DESCARTES); } } void VistaTableroGrande::imprimeCartaNoVisibleTapada(int posicion) const { int posInicioX = posiCoordenadaX[posicion]; int posInicioY = posiCoordenadaY[posicion]; Coordenada *coordenadaInicio = new Coordenada(++posInicioX, posInicioY); Enmarcado *marco = new Enmarcado((VistaTablero*)this); // Pintamos el canto horizontal superior marco->pintaRayaHorizontal(coordenadaInicio, LONG_CANTO_HORIZONTAL_SUPERIOR, (const char) '_'); coordenadaInicio->setCoordX(--posInicioX); // Pintamos el canto vertical izquierdo coordenadaInicio->setCoordY(++posInicioY); marco->pintaRayaVertical(coordenadaInicio, LONG_CANTO_VERTICAL_IZQUIERDO, '|'); ++posInicioX; // Pintamos el canto vertical derecho coordenadaInicio->setCoordX(++posInicioX + LONG_CANTO_HORIZONTAL_SUPERIOR); marco->pintaRayaVertical(coordenadaInicio, LONG_CANTO_VERTICAL_DERECHO, '|'); delete coordenadaInicio; delete marco; } void VistaTableroGrande::imprimeLeyendaCartaOculta(Carta *carta, int posicion) const { int posInicioX = posiCoordenadaX[posicion]; int posInicioY = posiCoordenadaY[posicion]; std::string de = " "; std::string leyenda = carta->getNumero()->getTextoNumero(); std::string palo = carta->getPalo()->getTextoPalo(); leyenda.erase(std::remove_if(leyenda.begin(), leyenda.end(), ::isspace), leyenda.end()); palo.erase(std::remove_if(palo.begin(), palo.end(), ::isspace), palo.end()); leyenda = leyenda + de + palo; if (leyenda.length() > TAMANO_MAX_LEYENDA) { std::string trozo = leyenda.substr(0, TAMANO_MAX_LEYENDA); memcpy(tableroAImprimir[posInicioY+MARGEN_LEYENDA]+posInicioX+MARGEN_LEYENDA, trozo.c_str(), TAMANO_MAX_LEYENDA); } else { memcpy(tableroAImprimir[posInicioY+MARGEN_LEYENDA]+posInicioX+MARGEN_LEYENDA, leyenda.c_str(), leyenda.length()); } } void VistaTableroGrande::imprimeLeyendaCartaVisible(Carta *carta, int posicion) const { int posInicioX = posiCoordenadaX[posicion] + MARGEN_HORIZONTAL_LEYENDA_CARTA_DESCUBIERTA; int posInicioY = posiCoordenadaY[posicion] + MARGEN_VERTICAL_LEYENDA_CARTA_DESCUBIERTA; std::string leyenda = carta->getNumero()->getTextoNumero(); memcpy(tableroAImprimir[posInicioY]+posInicioX, leyenda.c_str(), leyenda.length()); posInicioY += MARGEN_VERTICAL_LEYENDA_CARTA_DESCUBIERTA; posInicioX ++; std::string de = " DE "; memcpy(tableroAImprimir[posInicioY]+posInicioX, de.c_str(), de.length()); posInicioX--; leyenda = carta->getPalo()->getTextoPalo(); memcpy(tableroAImprimir[posInicioY+MARGEN_VERTICAL_LEYENDA_CARTA_DESCUBIERTA]+posInicioX, leyenda.c_str(), leyenda.length()); } void VistaTableroGrande::imprimeLeyendaSinCarta(int posicion) const { int posInicioX = posiCoordenadaX[posicion] + MARGEN_HORIZONTAL_LEYENDA_SIN_CARTA; int posInicioY = posiCoordenadaY[posicion] + MARGEN_VERTICAL_LEYENDA_SIN_CARTA; std::string leyenda = " X X "; memcpy(tableroAImprimir[posInicioY]+posInicioX, leyenda.c_str(), leyenda.length()); memcpy(tableroAImprimir[posInicioY+MARGEN_CARTA_OCULTA]+posInicioX, leyenda.c_str(), leyenda.length()); leyenda = " X X "; posInicioY++; memcpy(tableroAImprimir[posInicioY]+posInicioX, leyenda.c_str(), leyenda.length()); memcpy(tableroAImprimir[posInicioY+LEYENDA_ARRIBA_Y]+posInicioX, leyenda.c_str(), leyenda.length()); leyenda = " X X "; posInicioY++; memcpy(tableroAImprimir[posInicioY]+posInicioX, leyenda.c_str(), leyenda.length()); memcpy(tableroAImprimir[posInicioY+MARGEN_VERTICAL]+posInicioX, leyenda.c_str(), leyenda.length()); posInicioY++; leyenda = " VACIO "; memcpy(tableroAImprimir[posInicioY]+posInicioX, leyenda.c_str(), leyenda.length()); posInicioY++; } void VistaTableroGrande::imprimeCartaNoVisibleDestapada(int posicion) const { // Primero imprimimos el canto superior horizontal y el canto vertical izquierdo imprimeCartaNoVisibleTapada(posicion); int posInicioX = posiCoordenadaX[posicion]; int posInicioY = posiCoordenadaY[posicion]; // Ya tenemos pintada la esquina inferior izquierda posInicioX += MARGEN_HORIZONTAL_TABLERO; Coordenada *coordenadaInicio = new Coordenada(posInicioX, posInicioY + LONG_CANTO_VERTICAL_IZQUIERDO); Enmarcado *marco = new Enmarcado((VistaTablero*)this); // Pintamos el canto horizontal inferior marco->pintaRayaHorizontal(coordenadaInicio, LONG_CANTO_HORIZONTAL_SUPERIOR, '_'); posInicioY ++; coordenadaInicio->setCoordX(posInicioX + LONG_CANTO_HORIZONTAL_SUPERIOR + MARGEN_HORIZONTAL_TABLERO); coordenadaInicio->setCoordY(posiCoordenadaY[posicion] + LONG_CANTO_VERTICAL_DERECHO); marco->pintaRayaVertical(coordenadaInicio, LONG_CANTO_VERTICAL_IZQUIERDO, '|'); delete coordenadaInicio; delete marco; } void VistaTableroGrande::imprimeCartaVisibleTapada(Carta *carta, int posicion) const { imprimeCartaNoVisibleTapada(posicion); imprimeLeyendaCartaOculta(carta, posicion); } void VistaTableroGrande::imprimeCartaVisibleDestapada(Carta *carta, int posicion) const { imprimeCartaNoVisibleDestapada(posicion); imprimeLeyendaCartaVisible(carta, posicion); } <file_sep>#ifndef MOVERCONTROLLER_H #define MOVERCONTROLLER_H #include <OperacionController.h> #include <CriterioMovimientoVisitor.h> #include <CriterioMovimiento.h> #include <HistoricoMovimiento.h> #include <assert.h> class MoverController : public OperacionController, public CriterioMovimientoVisitor { public: MoverController(); MoverController(const std::shared_ptr<PartidaKlondike>& partida); ~MoverController(); void setMovimiento(int movimiento); int getMovimiento(); void setCriterio(CriterioMovimiento *criterio); void setMazoOrigen(int mazoOrigen); void setMazoDestino(int mazoDestino); void setCartasParaMover(int numeroCartas); virtual bool mover() = 0; void undo(); void redo(); void terminarPartida(); virtual void visita(CriterioDescarteStock *criterio) = 0; virtual void visita(CriterioStockDescarte *criterio) = 0; virtual void visita(CriterioDescarteFundacion *criterio) = 0; virtual void visita(CriterioDescarteTableau *criterio) = 0; virtual void visita(CriterioTableauFundacion *criterio) = 0; virtual void visita(CriterioTableauTableau *criterio) = 0; virtual void visita(CriterioFundacionTableau *criterio) = 0; protected: CriterioMovimiento *criterio; int movimiento; int mazoOrigen; int mazoDestino; int numeroCartas; HistoricoMovimiento movimientos; }; #endif <file_sep>#ifndef CRITERIOTABLEAUTABLEAU_H #define CRITERIOTABLEAUTABLEAU_H #include <CriterioMovimiento.h> #include <stack> class CriterioTableauTableau : public CriterioMovimiento { public: CriterioTableauTableau(); CriterioTableauTableau(const CriterioTableauTableau& criterio); ~CriterioTableauTableau(); bool checkMovimiento() const; void doMovimiento() const; void undoMovimiento() const; void acepta(CriterioMovimientoVisitor *visitor); CriterioMovimiento* clone(); protected: private: bool checkColor(const Carta *origen, const Carta *destino) const; bool checkNumeros(const Carta *origen, const Carta *destino) const; }; #endif <file_sep>#include "Fundacion.h" Fundacion::Fundacion() : indice (0) { } Fundacion::Fundacion(int ind) : indice (ind) { } Fundacion::~Fundacion() { } void Fundacion::acepta(const MazoVisitor* mazoVisitor) const { mazoVisitor->visita(this); } <file_sep>#include <BarajaFrancesaBuilder.h> #include <NumeroEspanol.h> BarajaFrancesaBuilder::BarajaFrancesaBuilder() { } BarajaFrancesaBuilder::~BarajaFrancesaBuilder() { } void BarajaFrancesaBuilder::construirPalos() { for (int i = PaloFrances::Palos::ROMBOS; i != PaloFrances::Palos::LAST; i++) { std::cout << "construyendo palo" << std::endl; std::shared_ptr<Palo> palo (new PaloFrances(i)); anadePalo(palo); } } void BarajaFrancesaBuilder::construirNumeros() { for (int i = 0; i < NUM_CARTAS_FRANCES; i++) { std::cout << "construyendo numero" << std::endl; std::shared_ptr<Numero> numero(nullptr); numero = std::make_shared<NumeroFrances>(); numero->setNumero(i); anadeNumero(numero); } } <file_sep>#ifndef CRITERIODESCARTETABLEAU_H #define CRITERIODESCARTETABLEAU_H #include <CriterioMovimiento.h> class CriterioDescarteTableau : public CriterioMovimiento { public: CriterioDescarteTableau(); CriterioDescarteTableau(const CriterioDescarteTableau& criterio); ~CriterioDescarteTableau(); bool checkMovimiento() const; void doMovimiento() const; void undoMovimiento() const; void acepta(CriterioMovimientoVisitor *visitor); CriterioMovimiento* clone(); protected: private: bool checkColor(const Carta *origen, const Carta *destino) const; bool checkNumeros(const Carta *origen, const Carta *destino) const; }; #endif <file_sep>#ifndef TABLEAU_H #define TABLEAU_H #include "Mazo.h" class Tableau : public Mazo { public: Tableau(); Tableau(const int ind); ~Tableau(); void acepta(const MazoVisitor* mazoVisitor) const; const inline int getIndice() const { return indice; }; protected: private: int indice; }; #endif <file_sep>#include <CriterioFundacionTableau.h> CriterioFundacionTableau::CriterioFundacionTableau() { numeroCartas = NUMERO_CARTAS_MOV_FUNDACION_TABLEAU; puntuacion = PUNTUACION_FUNDACION_TABLEAU; valoracion = VALORACION_FUNDACION_TABLEAU; } CriterioFundacionTableau::CriterioFundacionTableau(const CriterioFundacionTableau& criterio) : CriterioMovimiento(criterio) { } CriterioFundacionTableau::~CriterioFundacionTableau() { } bool CriterioFundacionTableau::checkMovimiento() const { const Carta *origen = mazoOrigen->getUltimaCarta(); const Carta *destino = mazoDestino->getUltimaCarta(); if (not mazoDestino->tieneCartas()) { return true; } return checkColor(origen, destino) && checkNumeros(origen, destino); } void CriterioFundacionTableau::doMovimiento() const { for (int i = 0; i < numeroCartas; i++) { mazoDestino->ponerCarta(mazoOrigen->quitarCarta()); } } void CriterioFundacionTableau::undoMovimiento() const { for (int i = 0; i < numeroCartas; i++) { mazoOrigen->ponerCarta(mazoDestino->quitarCarta()); } } void CriterioFundacionTableau::acepta(CriterioMovimientoVisitor *visitor) { visitor->visita(this); } bool CriterioFundacionTableau::checkColor(const Carta *origen, const Carta *destino) const { return not origen->mismoColor(*destino); } bool CriterioFundacionTableau::checkNumeros(const Carta *origen, const Carta *destino) const { return origen->getNumero()->getNumero() == (destino->getNumero())->getPrevNumero(); } CriterioMovimiento* CriterioFundacionTableau::clone() { return new CriterioFundacionTableau(*this); } <file_sep>#include "Palo.h" Palo::Palo() { } Palo::Palo(int palo, int tipoPalo) : palo(palo), tipo(tipoPalo) { } Palo::~Palo() { } Palo::Palo(const Palo* palo) : palo(palo->getPalo()) { } const Palo* Palo::operator=(const Palo* palo) { this->palo = palo->getPalo(); return this; } const bool Palo::operator==(const Palo* palo) { return this->palo == palo->getPalo(); } const int Palo::getPalo() const { return palo; } const int Palo::getTipo() const { return tipo; } <file_sep>#ifndef PARTIDAVISTA_H #define PARTIDAVISTA_H #include <OperacionController.h> #include <MazoVisitor.h> #include <Tableau.h> #include <Fundacion.h> #include <Stock.h> #include <Descarte.h> class PartidaVista : public MazoVisitor { public: PartidaVista(); PartidaVista(OperacionController *controlador); ~PartidaVista(); void pinta(); void visita(const Stock *stock) const; void visita(const Fundacion *fundacion) const; void visita(const Tableau *tableau) const; void visita(const Descarte *descarte) const; protected: private: void printTableaus(std::shared_ptr<PartidaKlondike> partida); void printFundaciones(std::shared_ptr<PartidaKlondike> partida); OperacionController *controlador; }; #endif <file_sep>#include <KlondikeVista.h> #include <KlondikeMenu.h> KlondikeVista::KlondikeVista() { menu = new KlondikeMenu(); } KlondikeVista::~KlondikeVista() { delete menu; } void KlondikeVista::interactua(OperacionController *operacionController) { operacionController->acepta(this); } void KlondikeVista::visita(InicioController *inicioController) { int tipoBaraja = preguntaBaraja(); preguntaResolucion(); inicioController->generarPartida(tipoBaraja, preguntaManualAutomatico()); PartidaVista partidaVista(inicioController); partidaVista.pinta(); } void KlondikeVista::visita(MoverManualController *moverController) { int tipoMovimiento = -1; do { vistaTablero->imprimeMenu(*menu); vistaTablero->imprimeRanking(moverController->getPartida()); vistaTablero->imprimeTablero(moverController->getPartida()); std::cout << "Introduzca opcion: "; std::cin >> tipoMovimiento; } while(tipoMovimiento < DESCARTE_A_STOCK || tipoMovimiento > TERMINAR_PARTIDA); moverController->setMovimiento(tipoMovimiento); menu->execute(moverController, *this); } void KlondikeVista::visita(MoverAleatorioController *moverController) { vistaTablero->imprimeMenu(*menu); vistaTablero->imprimeRanking(moverController->getPartida()); vistaTablero->imprimeTablero(moverController->getPartida()); menu->execute(moverController, *this); } int KlondikeVista::preguntaBaraja() { int tipoBaraja = 0; do { std::cout << "Introduzca tipo de baraja: " << std::endl; std::cout << "0) Baraja Española (default)" << std::endl; std::cout << "1) <NAME>" << std::endl; std::cout << "Introduzca opcion: " << std::endl; std::cin >> tipoBaraja; }while(tipoBaraja >= 2); return tipoBaraja; } void KlondikeVista::preguntaResolucion() { // Como vamos un poco pelaetes de tiempo solo vamos a implementar // una modalidad de tablero (tamano grande) vistaTablero = (VistaTablero *) new VistaTableroGrande(); vistaTablero->setTamanoX(Resolucion::coordXAlta); vistaTablero->setTamanoY(Resolucion::coordYAlta); vistaTablero->reservarMemoriaTableroAImprimir(); } int KlondikeVista::preguntaManualAutomatico() { int modoJuego = 0; do { std::cout << "Introduzca si quiere activar el piloto automatico: " << std::endl; std::cout << "0) No (default)" << std::endl; std::cout << "1) Si" << std::endl; std::cout << "Introduzca opcion: " << std::endl; std::cin >> modoJuego; }while(modoJuego >= 2); return modoJuego; } int KlondikeVista::preguntaMazo(const std::string& mazo, int maxMazos) const { int seleccion; do { std::cout << "Introduzca numero de " << mazo <<" [0-" << (maxMazos - 1) << "]: " << std::endl; std::cin >> seleccion; } while (seleccion < 0 || seleccion > maxMazos - 1); return seleccion; } int KlondikeVista::preguntaCartas() const { int seleccion; std::cout << "Introduzca numero de cartas a mover: " << std::endl; std::cin >> seleccion; return seleccion; } bool KlondikeVista::compruebaFichero(std::string nombrePartida) const { if(std::ifstream (nombrePartida)) { return true; } return false; } std::string KlondikeVista::preguntaNombreFichero() const { std::string nombrePartida; std::cout << "Introduzca el nombre con el que desea cargar/guardar la partida: "<< std::endl; std::cout << "Partidas existentes: " << std::endl; system("ls ./partidas/"); std::cout << std::endl << "> " ; std::cin >> nombrePartida; nombrePartida = "./partidas/" + nombrePartida; return nombrePartida; } std::string KlondikeVista::preguntarNombrePuntuacion() const { std::string nombrePuntuacion; std::cout << "¡Enhorabuena! Su puntuación está entre las 10 mejores "<< std::endl; std::cout << "Introduzca el nombre con el que desea aparecer en el ranking."<< std::endl; std::cin >> nombrePuntuacion; return nombrePuntuacion; } <file_sep>#include <DescarteTableauCommand.h> DescarteTableauCommand::DescarteTableauCommand() : MenuCommand("Mover de descarte a tableau") { criterio = new CriterioDescarteTableau(); } void DescarteTableauCommand::execute(const KlondikeVista& vista) { receiver->setMazoDestino(vista.preguntaMazo("Tableau", NUMERO_TABLEAUS)); receiver->setCriterio(criterio); receiver->mover(); } DescarteTableauCommand::~DescarteTableauCommand() { delete criterio; } <file_sep>#ifndef OperacionController_H #define OperacionController_H #include <OperacionControllerVisitor.h> #include <PartidaKlondike.h> class OperacionController { public: OperacionController(); OperacionController(const std::shared_ptr<PartidaKlondike>& partida); ~OperacionController(); const std::shared_ptr<PartidaKlondike>& getPartida() const; virtual void acepta(OperacionControllerVisitor* operacionControllerVisitor) = 0; protected: std::shared_ptr<PartidaKlondike> partida; private: }; #endif // OperacionController_H <file_sep>#include <MoverController.h> MoverController::MoverController() { } MoverController::MoverController(const std::shared_ptr<PartidaKlondike>& partida) : OperacionController(partida) { } MoverController::~MoverController() { } void MoverController::setCriterio(CriterioMovimiento *criterio) { this->criterio = criterio; criterio->acepta(this); } void MoverController::undo() { movimientos.undo(); } void MoverController::redo() { movimientos.redo(); } void MoverController::terminarPartida() { partida->setEstado(PartidaKlondike::Estado::SALIR); } void MoverController::setMovimiento(int movimiento) { this->movimiento = movimiento; } int MoverController::getMovimiento() { return movimiento; } void MoverController::setMazoOrigen(int mazoOrigen) { this->mazoOrigen = mazoOrigen; } void MoverController::setMazoDestino(int mazoDestino) { this->mazoDestino = mazoDestino; } void MoverController::setCartasParaMover(int numeroCartas) { this->numeroCartas = numeroCartas; } <file_sep>#include <MoverAleatorioController.h> #include <iostream> MoverAleatorioController::MoverAleatorioController() : puntuacionMovimiento(0), origenPrevio(-1), tableauToTableauAvg(0) { } MoverAleatorioController::MoverAleatorioController(const std::shared_ptr<PartidaKlondike>& partida) : MoverController(partida), puntuacionMovimiento(0), origenPrevio(-1), tableauToTableauAvg(0) { } MoverAleatorioController::~MoverAleatorioController() { } bool MoverAleatorioController::mover() { bool success = false; if (criterio->checkMovimiento()) { criterio->doMovimiento(); success = true; movimientos.insertMovimiento(criterio); getPartida()->incMarcador(criterio->getPuntuacion()); puntuacionMovimiento = 0; mazoOrigen = 0; mazoDestino = 0; if (numeroCartas == 0) { tableauToTableauAvg -= 1; } numeroCartas = 0; if (getPartida()->comprobarVictoria()) { terminarPartida(); } } return success; } void MoverAleatorioController::acepta(OperacionControllerVisitor *operacionControllerVisitor) { operacionControllerVisitor->visita(this); } void MoverAleatorioController::visita(CriterioDescarteStock *criterio) { criterio->setMazoOrigen(partida->getDescartes()); criterio->setMazoDestino(partida->getStock()); if (criterio->getValoracion() > puntuacionMovimiento && criterio->checkMovimiento()) { puntuacionMovimiento = criterio->getValoracion(); this->criterio = criterio; } } void MoverAleatorioController::visita(CriterioStockDescarte *criterio) { criterio->setMazoOrigen(partida->getStock()); criterio->setMazoDestino(partida->getDescartes()); if (criterio->getValoracion() > puntuacionMovimiento && criterio->checkMovimiento()) { puntuacionMovimiento = criterio->getValoracion(); this->criterio = criterio; } } void MoverAleatorioController::visita(CriterioDescarteFundacion *criterio) { for (int i = 0; i < partida->getNumFundaciones(); i++) { mazoDestino = i; criterio->setMazoOrigen(partida->getDescartes()); criterio->setMazoDestino(partida->getFundacion(mazoDestino)); if (criterio->getValoracion() > puntuacionMovimiento && criterio->checkMovimiento()) { puntuacionMovimiento = criterio->getValoracion(); this->criterio = criterio; break; } } } void MoverAleatorioController::visita(CriterioDescarteTableau *criterio) { for (int i = 0; i < partida->getNumTableaus(); i++) { mazoDestino = i; criterio->setMazoOrigen(partida->getDescartes()); criterio->setMazoDestino(partida->getTableau(mazoDestino)); if (criterio->getValoracion() > puntuacionMovimiento && criterio->checkMovimiento()) { puntuacionMovimiento = criterio->getValoracion(); this->criterio = criterio; break; } } } void MoverAleatorioController::visita(CriterioTableauFundacion *criterio) { int found = false; for (int i = 0; i < partida->getNumTableaus() && not found; i++) { for (int j = 0; j < partida->getNumFundaciones() && not found; j++) { mazoOrigen = i; mazoDestino = j; criterio->setMazoOrigen(partida->getTableau(mazoOrigen)); criterio->setMazoDestino(partida->getFundacion(mazoDestino)); if (criterio->getValoracion() > puntuacionMovimiento && criterio->checkMovimiento()) { puntuacionMovimiento = criterio->getValoracion(); this->criterio = criterio; found = true; } } } } int MoverAleatorioController::testTableauToTableau(CriterioTableauTableau *criterio, MazoPointer origen, MazoPointer destino) { criterio->setMazoOrigen(origen); criterio->setMazoDestino(destino); int mejorJugada = 0; for (int i = 1; i <= origen->getNumeroCartasVisibles(); i++) { criterio->setCartasParaMover(i); if (criterio->checkMovimiento()) { int current = criterio->getValoracion() + origen->getNumeroCartasNoVisibles() + (i/2) - tableauToTableauAvg; if (puntuacionMovimiento < current) { mejorJugada = i; puntuacionMovimiento = current; } } } return mejorJugada; } void MoverAleatorioController::visita(CriterioTableauTableau *criterio) { int origenFinal = 0; int destinoFinal = 0; int cartasFinal = 0; for (int i = 0; i < partida->getNumTableaus(); i++) { for (int j = 0; j < partida->getNumTableaus(); j++) { if (origenPrevio != j) { int nCartas = testTableauToTableau(criterio, partida->getTableau(i), partida->getTableau(j)); if (nCartas) { origenFinal = i; destinoFinal = j; cartasFinal = nCartas; } } } } if (cartasFinal != 0) { tableauToTableauAvg += 1; origenPrevio = origenFinal; criterio->setMazoOrigen(partida->getTableau(origenFinal)); criterio->setMazoDestino(partida->getTableau(destinoFinal)); criterio->setCartasParaMover(cartasFinal); numeroCartas = cartasFinal; this->criterio = criterio; } } void MoverAleatorioController::visita(CriterioFundacionTableau *criterio) { mazoDestino = 0; mazoOrigen = 0; bool found = true; for (int i = 0; i < partida->getNumFundaciones() && not found; i++) { for (int j = 0; j < partida->getNumTableaus() && not found; j++) { mazoOrigen = i; mazoDestino = j; criterio->setMazoOrigen(partida->getFundacion(mazoOrigen)); criterio->setMazoDestino(partida->getTableau(mazoDestino)); if (criterio->getValoracion() > puntuacionMovimiento && criterio->checkMovimiento()) { puntuacionMovimiento = criterio->getValoracion(); this->criterio = criterio; found = true; } } } } <file_sep>#include "Tableau.h" Tableau::Tableau() : indice (0) { } Tableau::Tableau(const int ind) : indice (ind) { } Tableau::~Tableau() { } void Tableau::acepta(const MazoVisitor* mazoVisitor) const { mazoVisitor->visita(this); } <file_sep>#ifndef KLONDIKEVISTA_H #define KLONDIKEVISTA_H #include <OperacionControllerVisitor.h> #include <OperacionController.h> #include <InicioController.h> #include <MoverController.h> #include <MoverManualController.h> #include <MoverAleatorioController.h> #include <PartidaVista.h> #include <VistaTableroGrande.h> #include <iostream> class KlondikeMenu; enum NUMERO_CRITERIOS { DESCARTE_A_STOCK, STOCK_A_DESCARTE, DESCARTE_A_FUNDACION, DESCARTE_A_TABLEAU, TABLEAU_A_FUNDACION, TABLEAU_A_TABLEAU, FUNDACION_A_TABLEAU, NUMERO_CRITERIOS }; const int PORCENTAJE_DESCARTE_A_STOCK = 4; const int PORCENTAJE_TABLEAU_A_TABLEAU = 5; const int NUM_MONTONES_STOCK = 1; const int NUM_MONTONES_DESCARTES = 1; const int LONGITUD_ENTRADA_CARACTERES = 5; const int GUARDAR_PARTIDA = 7; const int CARGAR_PARTIDA = 8; const int DESHACER_MOVIMIENTO = 9; const int REHACER_MOVIMIENTO = 10; const int TERMINAR_PARTIDA = 11; class KlondikeVista : public OperacionControllerVisitor { public: KlondikeVista(); ~KlondikeVista(); void interactua(OperacionController *operacionController); void visita(InicioController *inicioController); void visita(MoverManualController *moverController); void visita(MoverAleatorioController *moverController); int preguntaBaraja(); void preguntaResolucion(); int preguntaManualAutomatico(); int preguntaMazo(const std::string& mazo, int numMazos) const; int preguntaCartas() const; bool compruebaFichero(std::string nombrePartida) const; std::string preguntaNombreFichero() const; std::string preguntarNombrePuntuacion() const; void setVistaTablero(VistaTablero *vTablero) { vistaTablero = vTablero; }; const VistaTablero* getVistaTablero() const { return vistaTablero; }; protected: private: VistaTablero *vistaTablero; KlondikeMenu* menu; }; #endif <file_sep>#ifndef PALO_H #define PALO_H #include <cstdint> #include <memory> #include <iostream> class Palo { public: Palo(); Palo(int palo, int tipoPalo); Palo(const Palo* palo); virtual ~Palo(); const Palo* operator=(const Palo* palo); const bool operator==(const Palo* palo); const int getPalo() const; const int getTipo() const; virtual const std::string getTextoPalo() const = 0; virtual const bool mismoColor(const std::shared_ptr<Palo>& palo) const = 0; protected: int palo; int tipo; }; #endif <file_sep>#include "Mazo.h" Mazo::Mazo() { } Mazo::~Mazo() { } void Mazo::ponerCarta(Carta& carta) { mazo.push_back(carta); } Carta& Mazo::quitarCarta() { std::vector<Carta>::iterator primerElemento = mazo.end() - 1; mazo.pop_back(); return *primerElemento; } bool Mazo::tieneCartas() const { return mazo.size() != 0; } int Mazo::getNumeroCartas() const { return mazo.size(); } int Mazo::getNumeroCartasNoVisibles() const { int noVisibles = 0; for (auto carta : mazo) { if (carta.getVisibilidad() == false) { noVisibles++; } } return noVisibles; } int Mazo::getNumeroCartasVisibles() const { return (getNumeroCartas() - getNumeroCartasNoVisibles()); } const CartaList Mazo::getCartas() const { return mazo; } const Carta* Mazo::getUltimaCarta() const { if (0 == mazo.size()) return nullptr; return &(mazo.back()); } <file_sep>#ifndef KLONDIKECARGARBUILDERESPANOL_H #define KLONDIKECARGARBUILDERESPANOL_H #include <KlondikeCargarBuilder.h> class KlondikeCargarBuilderEspanola : public KlondikeCargarBuilder { public: KlondikeCargarBuilderEspanola(); void construyePalos(); void construyeNumeros(); void anadePalo(int numeroPalo); void anadeNumero(int num); private: }; #endif // KLONDIKECARGARBUILDERESPANOL_H <file_sep>#ifndef CRITERIODESCARTEFUNDACION_H #define CRITERIODESCARTEFUNDACION_H #include <CriterioMovimiento.h> class CriterioDescarteFundacion : public CriterioMovimiento { public: CriterioDescarteFundacion(); CriterioDescarteFundacion(const CriterioDescarteFundacion& criterio); ~CriterioDescarteFundacion(); bool checkMovimiento() const; void doMovimiento() const; void undoMovimiento() const; void acepta(CriterioMovimientoVisitor *visitor); CriterioMovimiento* clone(); protected: private: bool checkPalos(const Carta *origen, const Carta *destino) const; bool checkNumeros(const Carta *origen, const Carta *destino) const; }; #endif <file_sep>#include <BarajaEspanolaBuilder.h> #include <NumeroEspanol.h> BarajaEspanolaBuilder::BarajaEspanolaBuilder() { } BarajaEspanolaBuilder::~BarajaEspanolaBuilder() { } void BarajaEspanolaBuilder::construirPalos() { for (int i = PaloEspanol::Palos::OROS; i != PaloEspanol::Palos::LAST; i++) { std::shared_ptr<Palo> palo (new PaloEspanol(i)); anadePalo(palo); } } void BarajaEspanolaBuilder::construirNumeros() { for (int i = 0; i < NUM_CARTAS_ESPANOL; i++) { std::shared_ptr<Numero> numero(nullptr); numero = std::make_shared<NumeroEspanol>(); numero->setNumero(i); anadeNumero(numero); } } <file_sep>#ifndef VISTACARGARPARTIDA_H #define VISTACARGARPARTIDA_H #include <memory> #include <MazoVisitor.h> #include <Tableau.h> #include <Fundacion.h> #include <Stock.h> #include <Descarte.h> #include <VistaTablero.h> #include <KlondikeCargarBuilder.h> #include <fstream> #include <iostream> class PartidaKlondike; class VistaCargarPartida { std::string nombrePartida; std::ifstream *fichero; KlondikeCargarBuilder *cargarBuilder; public: VistaCargarPartida(std::string nombreFichero); ~VistaCargarPartida(); void cargar(std::shared_ptr<PartidaKlondike> partida); void cargaTipoPartida(std::shared_ptr<PartidaKlondike> partida); void cargaStock(std::shared_ptr<PartidaKlondike> partida); void cargaDescarte(std::shared_ptr<PartidaKlondike> partida); void cargaFundaciones(std::shared_ptr<PartidaKlondike> partida); void cargaTableaus(std::shared_ptr<PartidaKlondike> partida); }; #endif // VISTACARGARPARTIDA_H <file_sep>#include "BarajaBuilder.h" BarajaBuilder::BarajaBuilder() { } BarajaBuilder::~BarajaBuilder() { } void BarajaBuilder::anadePalo(const std::shared_ptr<Palo>& palo) { palos.push_back(palo); } void BarajaBuilder::anadeNumero(const std::shared_ptr<Numero>& numero) { numeros.push_back(numero); } Baraja& BarajaBuilder::getBaraja() { return baraja; } Baraja& BarajaBuilder::construirBaraja() { construirPalos(); construirNumeros(); for (auto palo : palos) { for (auto numero : numeros) { Carta carta(palo, numero); this->baraja.ponerCarta(carta); } } return this->baraja; } <file_sep>#ifndef PARTIDAKLONDIKE_H #define PARTIDAKLONDIKE_H #include <Mazo.h> #include <memory> const int MAX_RANKING = 10; typedef std::vector<MazoPointer> MazoList; class PartidaKlondike { public: enum Estado { INICIAL, EN_CURSO, EN_CURSO_AUTOMATICO, FINAL, SALIR }; PartidaKlondike(); PartidaKlondike(const PartidaKlondike& partida); ~PartidaKlondike(); void addTableau(const MazoPointer tableau); void addFundacion(const MazoPointer fundacion); void addStock(const MazoPointer stock); void addDescartes(const MazoPointer descartes); void deletePartida(); void incMarcador(int puntuacion); bool comprobarVictoria(); int getEstado() const; const MazoList getFundaciones() const { return fundaciones; }; const MazoList getTableaus() const { return tableaus; }; const MazoPointer getDescartes() const { return descartes; }; const MazoPointer getStock() const { return stock; }; MazoPointer getFundacion(int fundacion); int getNumFundaciones(); MazoPointer getTableau(int tableau); int getNumTableaus(); const int getTipoPartida() const { return tipoPartida; }; const int getMarcador() { return marcador; }; const int getMinimo() { return minimo; }; const std::string getNombreRanking(int pos) { return ranking[pos].first; }; const int getPuntuacionRanking(int pos) { return ranking[pos].second; }; void setMarcador(int puntuacion) { marcador = puntuacion; }; void setMinimo(int puntuacion) { minimo = puntuacion; }; void setEstado(PartidaKlondike::Estado estado); void setTipoPartida(const int tipo) { tipoPartida = tipo; }; void setNombreRanking(int pos, std::string nombre) { ranking[pos].first = nombre; }; void setPuntuacionRanking(int pos, int valor) { ranking[pos].second = valor; }; protected: private: bool tableausVacios(); Estado estado; int tipoPartida; int marcador; int minimo; std::vector<MazoPointer> fundaciones; std::vector<MazoPointer> tableaus; MazoPointer descartes; MazoPointer stock; std::pair <std::string, int> ranking[MAX_RANKING]; }; #endif <file_sep>#include <CriterioMovimiento.h> CriterioMovimiento::CriterioMovimiento() { } CriterioMovimiento::CriterioMovimiento(const CriterioMovimiento& criterio) { mazoOrigen = criterio.mazoOrigen; mazoDestino = criterio.mazoDestino; numeroCartas = criterio.numeroCartas; puntuacion = criterio.puntuacion; } CriterioMovimiento::~CriterioMovimiento() { } void CriterioMovimiento::setMazoOrigen(MazoPointer mazoOrigen) { this->mazoOrigen = mazoOrigen; } void CriterioMovimiento::setMazoDestino(MazoPointer mazoDestino) { this->mazoDestino = mazoDestino; } void CriterioMovimiento::setCartasParaMover(int numeroCartas) { this->numeroCartas = numeroCartas; } <file_sep>#ifndef MoverAleatorioController_H #define MoverAleatorioController_H #include <MoverController.h> #include <CriterioDescarteStock.h> #include <CriterioStockDescarte.h> #include <CriterioDescarteFundacion.h> #include <CriterioDescarteTableau.h> #include <CriterioTableauFundacion.h> #include <CriterioTableauTableau.h> #include <KlondikeVista.h> const int NUMERO_CARTAS_MAXIMO_A_MOVER = 9; class MoverAleatorioController : public MoverController { public: MoverAleatorioController(); MoverAleatorioController(const std::shared_ptr<PartidaKlondike>& partida); ~MoverAleatorioController(); bool mover(); void acepta(OperacionControllerVisitor *operacionControllerVisitor); void visita(CriterioDescarteStock *criterio); void visita(CriterioStockDescarte *criterio); void visita(CriterioDescarteFundacion *criterio); void visita(CriterioDescarteTableau *criterio); void visita(CriterioTableauFundacion *criterio); void visita(CriterioTableauTableau *criterio); void visita(CriterioFundacionTableau *criterio); private: int puntuacionMovimiento; int origenPrevio; int tableauToTableauAvg; int testTableauToTableau(CriterioTableauTableau *criterio, MazoPointer origen, MazoPointer destino); }; #endif // MoverAleatorioController_H <file_sep>#include <CriterioDescarteFundacion.h> CriterioDescarteFundacion::CriterioDescarteFundacion() { numeroCartas = NUMERO_CARTAS_MOV_DESCARTE_FUNDACION; puntuacion = PUNTUACION_DESCARTE_FUNDACION; valoracion = VALORACION_DESCARTE_FUNDACION; } CriterioDescarteFundacion::CriterioDescarteFundacion(const CriterioDescarteFundacion& criterio) : CriterioMovimiento(criterio) { } CriterioDescarteFundacion::~CriterioDescarteFundacion() { } bool CriterioDescarteFundacion::checkMovimiento() const { // TODO: REFACTORIZAR ESTA MIERDA if (not mazoOrigen->tieneCartas()) { return false; } if (not mazoDestino->tieneCartas()) { if (0 == mazoOrigen->getUltimaCarta()->getNumero()->getNumero()) { return true; } else { return false; } } const Carta *origen = mazoOrigen->getUltimaCarta(); const Carta *destino = mazoDestino->getUltimaCarta(); return checkPalos(origen, destino) && checkNumeros(origen, destino); } void CriterioDescarteFundacion::doMovimiento() const { for (int i = 0; i < numeroCartas; i++) { mazoDestino->ponerCarta(mazoOrigen->quitarCarta()); } } void CriterioDescarteFundacion::undoMovimiento() const { for (int i = 0; i < numeroCartas; i++) { mazoOrigen->ponerCarta(mazoDestino->quitarCarta()); } } void CriterioDescarteFundacion::acepta(CriterioMovimientoVisitor *visitor) { visitor->visita(this); } bool CriterioDescarteFundacion::checkPalos(const Carta *origen, const Carta *destino) const { return origen->getPalo() == destino->getPalo(); } bool CriterioDescarteFundacion::checkNumeros(const Carta *origen, const Carta *destino) const { return origen->getNumero()->getNumero() == (destino->getNumero())->getNextNumero(); } CriterioMovimiento* CriterioDescarteFundacion::clone() { return new CriterioDescarteFundacion(*this); } <file_sep>#include "Coordenada.h" Coordenada::Coordenada() { } Coordenada::Coordenada(int coordX, int coordY) { coordenadaX = coordX; coordenadaY = coordY; } Coordenada::~Coordenada() { } void Coordenada::setCoord(int coordX, int coordY) { coordenadaX = coordX; coordenadaY = coordY; } <file_sep>#ifndef KLONDIKECARGARBUILDERFRANCESA_H #define KLONDIKECARGARBUILDERFRANCESA_H #include <KlondikeCargarBuilder.h> class KlondikeCargarBuilderFrancesa : public KlondikeCargarBuilder { public: KlondikeCargarBuilderFrancesa(); void construyePalos(); void construyeNumeros(); void anadePalo(int numeroPalo); void anadeNumero(int num); }; #endif // KLONDIKECARGARBUILDERFRANCESA_H <file_sep>#include "NumeroEspanol.h" #include <iostream> NumeroEspanol::NumeroEspanol() { } NumeroEspanol::~NumeroEspanol() { } int NumeroEspanol::getNextNumero() { if(numeros[numero-1] == NUM_CARTAS_ESPANOL) { return NUM_CARTAS_ESPANOL; } return numeros[numero]; } int NumeroEspanol::getPrevNumero() { if(numeros[numero-1] == 1) { return 0; } return numeros[numero - 2]; } <file_sep>#ifndef HISTORICOMOVIMIENTO_H #define HISTORICOMOVIMIENTO_H #include <stack> #include <CriterioMovimiento.h> class HistoricoMovimiento { public: HistoricoMovimiento(); void insertMovimiento(CriterioMovimiento* criterio); void undo(); void redo(); ~HistoricoMovimiento(); private: std::stack<CriterioMovimiento*> undoStack; std::stack<CriterioMovimiento*> redoStack; }; #endif <file_sep># klondike Klondike Game
0eb2f45b7484c19eec875d9c3720180d46189128
[ "Markdown", "C++" ]
96
C++
wayfactory/klondike
ed342e839722b33947986e93373ecdb82c83d556
2dcb9a266bdca276eed4770ba3296283decc743f
refs/heads/master
<repo_name>smartarch/fitoptivis-dsl<file_sep>/cz.cuni.mff.fitoptivis.parent/cz.cuni.mff.fitoptivis.modelExtractor/src/cz/cuni/mff/fitoptivis/modelExtractor/metadata/LinkDescription.java package cz.cuni.mff.fitoptivis.modelExtractor.metadata; public class LinkDescription { public String from; public String fromPort; public String to; public String toPort; } <file_sep>/cz.cuni.mff.fitoptivis.parent/cz.cuni.mff.fitoptivis.modelExtractor/src/cz/cuni/mff/fitoptivis/modelExtractor/data/Link.java package cz.cuni.mff.fitoptivis.modelExtractor.data; import java.util.HashMap; import java.util.Map; public class Link { private IndexedName from; private IndexedName fromPort; private IndexedName to; private IndexedName toPort; private Map<String, String> qualities; public Link() { qualities = new HashMap<String, String>(); from = new IndexedName(); fromPort = new IndexedName(); to = new IndexedName(); toPort = new IndexedName(); } public IndexedName getFrom() { return from; } public void setFrom(IndexedName from) { this.from = from; } public IndexedName getTo() { return to; } public void setTo(IndexedName to) { this.to = to; } public Map<String, String> getQualities() { return qualities; } public IndexedName getToPort() { return toPort; } public void setToPort(IndexedName toPort) { this.toPort = toPort; } public IndexedName getFromPort() { return fromPort; } public void setFromPort(IndexedName fromPort) { this.fromPort = fromPort; } } <file_sep>/cz.cuni.mff.fitoptivis.parent/cz.cuni.mff.fitoptivis.modelExtractor/src/cz/cuni/mff/fitoptivis/modelExtractor/ModelRepository.java package cz.cuni.mff.fitoptivis.modelExtractor; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.util.HashMap; import java.util.Map; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.Resource.Diagnostic; import org.eclipse.xtext.linking.ILinker; import org.eclipse.xtext.nodemodel.INode; import org.eclipse.xtext.parser.IParseResult; import org.eclipse.xtext.resource.XtextResource; import org.eclipse.xtext.resource.XtextResourceFactory; import org.eclipse.xtext.resource.XtextResourceSet; import com.google.inject.Injector; import cz.cuni.mff.fitoptivis.FitLangStandaloneSetup; import cz.cuni.mff.fitoptivis.fitLang.Model; import cz.cuni.mff.fitoptivis.parser.antlr.FitLangParser; import cz.cuni.mff.fitoptivis.scoping.FitLangScopeProvider; // maintains cache of parsed Models public class ModelRepository { Map<String, Model> models; CodeLoader loader; XtextResourceSet resourceSet; public ModelRepository(CodeLoader loader) { models = new HashMap<String, Model>(); this.loader = loader; Injector injector = new FitLangStandaloneSetup().createInjectorAndDoEMFRegistration(); resourceSet = injector.getInstance(XtextResourceSet.class); resourceSet.addLoadOption(XtextResource.OPTION_RESOLVE_ALL, Boolean.TRUE); } public Model getModel(String modelName) { if (!models.containsKey(modelName)) loadModel(modelName); return models.get(modelName); } private void loadModel(String modelName) { DslCode code = loader.loadCode(modelName); InputStream in = new ByteArrayInputStream(code.content.getBytes()); Resource resource = resourceSet.createResource(URI.createURI("stdin:/" + modelName + ".fit")); try { resource.load(in, resourceSet.getLoadOptions()); Model model = (Model) resource.getContents().get(0); if (!resource.getErrors().isEmpty()) { System.err.println("Got syntax errors in the result"); for(Diagnostic error: resource.getErrors()) { String err = error.getMessage(); System.err.println("Error (" + error.getLine() + ":" + error.getColumn() + "): " + err); } } models.put(code.name, model); models.put(modelName, model); } catch(IOException e) { // do nothing? } } } <file_sep>/buildFatJars.sh #!/bin/bash dsl_jar_location="cz.cuni.mff.fitoptivis.ide/build/libs/cz.cuni.mff.fitoptivis.ide-1.0.0-SNAPSHOT-ls.jar" modelExtractor_jar_location="cz.cuni.mff.fitoptivis.modelExtractor/build/libs/cz.cuni.mff.fitoptivis.modelExtractor-1.0.0.jar" set -e # move to the root folder of the project (the script's position) cd `dirname "$0"` cd "cz.cuni.mff.fitoptivis.parent" ./gradlew shadowJar cp "$dsl_jar_location" "../cz.cuni.mff.fitoptivis.dsl.jar" cp "$modelExtractor_jar_location" "../cz.cuni.mff.fitoptivis.modelExtractor.jar" echo "Fat jars compiled and copied to the project's root directory" <file_sep>/cz.cuni.mff.fitoptivis.parent/settings.gradle include 'cz.cuni.mff.fitoptivis' include 'cz.cuni.mff.fitoptivis.ide' include 'cz.cuni.mff.fitoptivis.tests' include 'cz.cuni.mff.fitoptivis.modelExtractor'<file_sep>/cz.cuni.mff.fitoptivis.parent/cz.cuni.mff.fitoptivis.modelExtractor/build.gradle repositories { mavenCentral() } dependencies { compile "org.json:json:20190722" compile project(":cz.cuni.mff.fitoptivis") } eclipse { project.natures "org.eclipse.buildship.core.gradleprojectnature" } sourceSets { main.java.srcDir "src/main" } jar { from configurations.compile.collect { zipTree it } manifest.attributes "Main-Class": "cz.cuni.mff.fitoptivis.modelExtractor.ModelExtractor" exclude 'META-INF/*.RSA', 'META-INF/*.SF', 'META-INF/*.DSA' }<file_sep>/cz.cuni.mff.fitoptivis.parent/cz.cuni.mff.fitoptivis.modelExtractor/src/cz/cuni/mff/fitoptivis/modelExtractor/data/Ports.java package cz.cuni.mff.fitoptivis.modelExtractor.data; import java.util.ArrayList; import java.util.List; public class Ports { List<Port> inputs; List<Port> outputs; List<Port> requires; List<Port> supports; public Ports() { inputs = new ArrayList<Port>(); outputs = new ArrayList<Port>(); requires = new ArrayList<Port>(); supports = new ArrayList<Port>(); } public List<Port> getInputs() { return inputs; } public List<Port> getOutputs() { return outputs; } public List<Port> getRequires() { return requires; } public List<Port> getSupports() { return supports; } } <file_sep>/cz.cuni.mff.fitoptivis.parent/cz.cuni.mff.fitoptivis.modelExtractor/src/cz/cuni/mff/fitoptivis/modelExtractor/DslCode.java package cz.cuni.mff.fitoptivis.modelExtractor; public class DslCode { public String name; public String content; }<file_sep>/cz.cuni.mff.fitoptivis.parent/cz.cuni.mff.fitoptivis.modelExtractor/src/cz/cuni/mff/fitoptivis/modelExtractor/SystemDescriptionToJsonConverter.java package cz.cuni.mff.fitoptivis.modelExtractor; import cz.cuni.mff.fitoptivis.modelExtractor.data.*; import java.util.List; import java.util.Map; import org.json.JSONArray; import org.json.JSONObject; public class SystemDescriptionToJsonConverter { public static String convertToJson(SystemDescription description) { JSONObject result = new JSONObject(); List<String> errors = description.getErrors(); if (!errors.isEmpty()) { for(String err: errors) { result.append("Errors", err); } //result.put("System", (Object)null); result.put("System", processValidSystemDescription(description)); } else { result.put("Errors", new JSONArray()); result.put("System", processValidSystemDescription(description)); } return result.toString(); } private static JSONObject processValidSystemDescription(SystemDescription system) { JSONObject result = new JSONObject(); result.put("Name", system.getName()); for(Component component: system.getComponents()) { result.append("Components", processComponent(component)); } for(Link link: system.getBudgetLinks()) { result.append("RunsOnLinks", processRunsOnLink(link)); } for(Link link: system.getChannelLinks()) { result.append("OutputsToLinks", processChannelLink(link)); } result.put("Qualities", processQualities(system.getQualities())); return result; } private static JSONObject processRunsOnLink(Link link) { JSONObject result = new JSONObject(); result.put("Host", processLinkEndpoint(link.getFrom(), link.getFromPort())); result.put("Guest", processLinkEndpoint(link.getTo(), link.getToPort())); result.put("Qualities", processQualities(link.getQualities())); return result; } private static JSONObject processChannelLink(Link link) { JSONObject result = new JSONObject(); result.put("From", processLinkEndpoint(link.getFrom(), link.getFromPort())); result.put("To", processLinkEndpoint(link.getTo(), link.getToPort())); result.put("Qualities", processQualities(link.getQualities())); return result; } private static JSONObject processLinkEndpoint(IndexedName componentName, IndexedName portName) { JSONObject result = new JSONObject(); result.put("componentName", processIndexedName(componentName)); result.put("portName", processIndexedName(portName)); return result; } private static JSONObject processIndexedName(IndexedName name) { JSONObject result = new JSONObject(); result.put("name", name.getName()); if (name.hasIndex()) result.put("index", name.getIndex()); return result; } private static JSONObject processQualities(Map<String, String> qualities) { JSONObject result = new JSONObject(); for(Map.Entry<String, String> quality: qualities.entrySet()) { result.put(quality.getKey(), quality.getValue()); } return result; } private static JSONObject processComponent(Component component) { JSONObject result = new JSONObject(); result.put("Type", component.getType()); result.put("Configuration", component.getConfigurationName()); result.put("Name", processIndexedName(component.getName())); result.put("Qualities", processQualities(component.getQualities())); result.put("Ports", processPorts(component.getPorts())); for(Link link: component.getBudgetLinks()) { result.append("RunsOnLinks", processRunsOnLink(link)); } for(Link link: component.getChannelLinks()) { result.append("OutputsToLinks", processChannelLink(link)); } for(Component subComponent: component.getSubComponents()) { result.append("Subcomponents", processComponent(subComponent)); } return result; } private static JSONObject processPorts(Ports ports) { JSONObject result = new JSONObject(); result.put("Inputs", processPortsList(ports.getInputs())); result.put("Outputs", processPortsList(ports.getOutputs())); result.put("Supports", processPortsList(ports.getSupports())); result.put("Requires", processPortsList(ports.getRequires())); return result; } private static JSONArray processPortsList(List<Port> ports) { JSONArray result = new JSONArray(); for(Port port: ports) { JSONObject obj = new JSONObject(); obj.put("Type", port.getType()); obj.put("Name", processIndexedName(port.getName())); result.put(obj); } return result; } }
f2503e655307304f63898bfd8f752b0ea86d3c44
[ "Java", "Shell", "Gradle" ]
9
Java
smartarch/fitoptivis-dsl
5c9d8e1368436af90750499e43ae325eaacf4d60
be43910fdfc7fb0cf781f28470419e7a49842a84
refs/heads/master
<repo_name>pruthvi-shiv/rest_api_messagepost<file_sep>/src/main/java/com/example/echo/PostMessage.java /* * Copyright 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.echo; import java.util.Date; /** * The message bean that will be used in the echo request and response. */ public class PostMessage { private String title; private String authorEmail; private String content; private Date date; public String getTitle() { return this.title; } public void setTitle(String title) { this.title = title; } public String getAuthorEmail() { return this.authorEmail; } public void setAuthorEmail(String authorEmail) { this.authorEmail = authorEmail; } public String getcontent() { return this.content; } public void setContent(String content) { this.content = content; } public Date getDate() { return this.date; } public void setDate(Date date) { this.date = date; } } <file_sep>/src/main/java/com/example/echo/Mpost.java package com.example.echo; import static com.example.echo.Persistence.getDatastore; import static com.example.echo.Persistence.getKeyFactory; import static com.google.cloud.datastore.StructuredQuery.OrderBy.desc; import java.util.Date; import java.util.List; import java.util.Objects; import com.google.cloud.Timestamp; import com.google.cloud.datastore.Entity; import com.google.cloud.datastore.EntityQuery; import com.google.cloud.datastore.FullEntity; import com.google.cloud.datastore.FullEntity.Builder; import com.google.cloud.datastore.IncompleteKey; import com.google.cloud.datastore.Key; import com.google.cloud.datastore.KeyFactory; import com.google.cloud.datastore.Query; import com.google.cloud.datastore.QueryResults; import com.google.cloud.datastore.StructuredQuery.PropertyFilter; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; public class Mpost { public static Key key; private static KeyFactory keyFactory = getKeyFactory(Mpost.class); public String title; public String authorEmail; public String content; public Date date; public static KeyFactory getKeyfactory() { return keyFactory; } public static void setKeyfactory(KeyFactory keyfactory) { keyFactory = keyfactory; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthorEmail() { return authorEmail; } public void setAuthorEmail(String authorEmail) { this.authorEmail = authorEmail; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public static void setKey(Key key) { Mpost.key = key; } public static Key getKey() { return key; } public Mpost() { this.date = new Date(); } public Mpost(String title, String content, String email) { this.date = new Date(); this.title = title; this.content = content; authorEmail = email; key = keyFactory.newKey(this.hashCode()); } public Mpost(Entity entity) { key = entity.hasKey() ? entity.getKey() : null; title = entity.contains("title") ? entity.getString("title") : null; authorEmail = entity.contains("authorEmail") ? entity.getString("authorEmail") : null; date = entity.contains("date") ? entity.getTimestamp("date").toSqlTimestamp() : null; content = entity.contains("content") ? entity.getString("content") : null; } public void save() { if (key == null) { key = keyFactory.newKey(this.hashCode()); } System.out.println(this.authorEmail + this.content + this.title ); Builder<Key> builder = FullEntity.newBuilder(key); if (authorEmail != null) { builder.set("authorEmail", authorEmail); } builder.set("content", content); builder.set("title", title); builder.set("date", Timestamp.of(date)); System.out.println(this.authorEmail + this.content + this.title ); getDatastore().put(builder.build()); } // private IncompleteKey makeIncompleteKey() { // return Key.newBuilder(Mpost.getKey(), "title").build(); // } public List<Mpost> getMposts() { // This query requires the index defined in index.yaml to work because of the // orderBy on date. EntityQuery query = Query.newEntityQueryBuilder() .setKind("Mpost") .setOrderBy(desc("date")) .build(); QueryResults<Entity> results = getDatastore().run(query); ImmutableList.Builder<Mpost> resultListBuilder = ImmutableList.builder(); while (results.hasNext()) { resultListBuilder.add(new Mpost(results.next())); } return resultListBuilder.build(); } public static Mpost getMpost(String title, String author) { key = keyFactory.newKey(hashCode(title, author)); EntityQuery query = Query.newEntityQueryBuilder() .setKind("Mpost") .setFilter(PropertyFilter.eq("__key__", key)) .build(); QueryResults<Entity> result = getDatastore().run(query); if (result.hasNext()) { return (new Mpost(result.next())); } return null; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Mpost post = (Mpost) o; return Objects.equals(key, post.key) && Objects.equals(authorEmail, post.authorEmail) && Objects.equals(title, post.title) && Objects.equals(content, post.content) && Objects.equals(date, post.date); } @Override public int hashCode() { return Objects.hash(authorEmail, title); } public static int hashCode(String title, String authorEmail) { return Objects.hash(authorEmail, title); } @Override public String toString() { return MoreObjects.toStringHelper(this).add("key", key).add("authorEmail", authorEmail).add("title", title) .add("content", content).add("date", date).toString(); } }
0b7ae775b30e949be6f1ed9c229a36faeb3d9b93
[ "Java" ]
2
Java
pruthvi-shiv/rest_api_messagepost
01ff778fef4faba7415569f538932d17847f320c
b40e139e5fedd804d63be7a22431e3250de5c98d
refs/heads/master
<file_sep>// swift-tools-version:4.0 import PackageDescription let package = Package( name: "JsonRPC", products: [ .library(name: "JsonRPC", targets: ["JsonRPC"]) ], targets: [ .target(name: "JsonRPC", path: "Sources"), .testTarget(name: "JsonRPCTests", dependencies: ["JsonRPC"]) ], swiftLanguageVersions: [4] ) <file_sep>// // JsonRPC // // Copyright © 2016-2017 Tinrobots. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation /// A JSON-RPC params field. public enum Parameters { case positional(array: [Any?]) case named(object: [String: Any]) //TODO: rename object? } extension Parameters: Codable { enum CodingKeys: String, CodingKey { case params } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) if let params = try? container.decodeArray(Array<Any?>.self, forKey: .params) { self = .positional(array: params) } else if let params = try? container.decodeDictionary([String: Any].self, forKey: .params) { self = .named(object: params) } else { let context = DecodingError.Context(codingPath: [CodingKeys.params], debugDescription: "Expected '[String: Any] or [Any?]' for the 'params' key.") throw DecodingError.dataCorrupted(context) } } public func encode(to encoder: Encoder) throws { switch self { case .positional(let array): var container = encoder.unkeyedContainer() try container.encodeArray(array) case .named(let object): var container = encoder.container(keyedBy: DynamicCodingKey.self) try container.encodeDictionary(object) } } } <file_sep>Pod::Spec.new do |s| s.name = 'JsonRPC' s.version = '0.1.0' s.license = 'MIT' s.documentation_url = 'http://www.tinrobots.org/JsonRPC' s.summary = 'A JSON-RPC 2.0 library written in Swift.' s.homepage = 'http://www.tinrobots.org/JsonRPC' s.authors = { '<NAME>' => '<EMAIL>' } s.source = { :git => 'https://github.com/tinrobots/JsonRPC.git', :tag => s.version } s.requires_arc = true s.ios.deployment_target = '10.0' s.osx.deployment_target = '10.12' s.tvos.deployment_target = '10.0' s.watchos.deployment_target = '3.0' s.source_files = 'Sources/*.swift', 'Support/*.{h,m}' end <file_sep>// // JsonRPC // // Copyright © 2016-2017 Tinrobots. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. /// When a rpc call is made, the Server must reply with a Response, except for in the case of Notifications. public enum Response { /// Success response. case success(id: Id, result: Any) /// Error response: when a rpc call encounters an error, the `ErrorObject` must contain the error member with a value. case error(id: Id?, error: ErrorObject) /// It must be the same as the value of the id member in the Request Object. /// - Note: If there was an error in detecting the id in the Request object (e.g. Parse error/Invalid Request), it must be Null. public var id: Id? { switch self { case .success(let id, _): return id case .error(let id, _): return id } } /// This member is **required on success**. /// This member must not exist if there was an error invoking the method. /// - Note: The value of this member is determined by the method invoked on the Server. public var result: Any? { switch self { case .success(_, let result): return result case .error: return nil } } /// This member is **required on error**. public var error: ErrorObject? { switch self { case .success: return nil case .error(_, let error): return error } } } // MARK: - Codable extension Response: Codable { enum CodingKeys: String, CodingKey { case jsonrpc, id, result, error } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) guard let jsonrpc = try? container.decode(String.self, forKey: .jsonrpc), jsonrpc == "2.0" else { let context = DecodingError.Context(codingPath: [CodingKeys.jsonrpc], debugDescription: "JSON RPC version not supported.") throw DecodingError.dataCorrupted(context) } let id = try Id(from: decoder) let error = try? ErrorObject(from: decoder) let result = try? container.decodeAny(forKey: .result) switch (result, error) { case (_?, _?): let context = DecodingError.Context(codingPath: [CodingKeys.error, CodingKeys.result], debugDescription: "The keys 'error' and 'result' cannot be populated at the same time.") throw DecodingError.dataCorrupted(context) case (nil, let error?): self = .error(id: id, error: error) case (let result?, nil): self = .success(id: id, result: result) case (nil, nil): let context = DecodingError.Context(codingPath: [CodingKeys.error, CodingKeys.result], debugDescription: "The keys 'error' and 'result' cannot be nil at the same time.") throw DecodingError.dataCorrupted(context) } } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode("2.0", forKey: .jsonrpc) switch self { case .success(id: let id, result: let result): try container.encode(id, forKey: .id) try container.encodeAny(result, forKey: .result) case .error(id: let id, error: let error): if let id = id { // the use of null for id in Requests is discouraged try container.encode(id, forKey: .id) } try container.encode(error, forKey: .error) } } } <file_sep>// // JsonRPC // // Copyright © 2016-2017 Tinrobots. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. /// A JSON-RPC id field. public enum Id { case string(String) case number(Int) } extension Id: Codable { enum CodingKeys: String, CodingKey { case id } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) if let id = try? container.decode(Int.self, forKey: .id) { self = .number(id) } else if let id = try? container.decode(String.self, forKey: .id) { self = .string(id) } else { let context = DecodingError.Context(codingPath: [CodingKeys.id], debugDescription: "Key 'id' must be an Int or a String.") throw DecodingError.dataCorrupted(context) } } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() switch self { case .number(let number): try container.encode(number) case .string(let string): try container.encode(string) } } } extension Id: Equatable { /// Returns a Boolean value indicating whether two Id are equal. public static func == (lhs: Id, rhs: Id) -> Bool { switch (lhs, rhs) { case (.string(let lhss), .string(let rhss)) where lhss == rhss: return true case (.number(let lhsn), .number(let rhsn)) where lhsn == rhsn: return true default: return false } } } <file_sep>// // JsonRPC // // Copyright © 2016-2017 Tinrobots. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. /// When a rpc call encounters an error, the Response Object MUST contain the error member public enum ErrorObject: Error { /// Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text. case parseError(message: String, data: ErrorData?) /// The JSON sent is not a valid Request object. case invalidRequest(message: String, data: ErrorData?) /// The method does not exist / is not available. case methodNotFound(message: String, data: ErrorData?) /// Invalid method parameter(s). case invalidParams(message: String, data: ErrorData?) /// Internal JSON-RPC error. case internalError(message: String, data: ErrorData?) /// Reserved for implementation-defined server-errors. /// - Note: code must be between -32000 and -32099 case raw(code: Int, message: String, data: ErrorData?) /// A Number that indicates the error type that occurred. public var code: Int { switch self { case .parseError: return -32700 case .invalidRequest: return -32600 case .methodNotFound: return -32601 case .invalidParams: return -32602 case .internalError: return -32603 case .raw(let code, _, _): return code } } /// A String providing a short description of the error. /// - Note: The message SHOULD be limited to a concise single sentence. public var message: String { switch self { case .parseError(let message, _): return message case .invalidRequest(let message, _): return message case .methodNotFound(let message, _): return message case .invalidParams(let message, _): return message case .internalError(let message, _): return message case .raw(_, let message, _): return message } } /// A Primitive or Structured value that contains additional information about the error. /// This may be omitted. /// The value of this member is defined by the Server (e.g. detailed error information, nested errors etc.). public var data: ErrorData? { switch self { case .parseError(_, let data): return data case .invalidRequest(_, let data): return data case .methodNotFound(_, let data): return data case .invalidParams(_, let data): return data case .internalError(_, let data): return data case .raw(_, _, let data): return data } } /// Creates a new raw error. public init?(code: Int, message: String = "Server Error", data: ErrorData? = nil) { if type(of: self).isValidImplementationDefinedCode(code) { self = .raw(code: code, message: message, data: data) return } return nil } } // MARK: - Utility extension ErrorObject { /// Returns `true` if the code is defined in the range for the implementation-defined server-errors. public static func isValidImplementationDefinedCode(_ code: Int) -> Bool { return -32099 ... -32000 ~= code } } // MARK: - Codable extension ErrorObject: Codable { enum CodingKeys: String, CodingKey { case error, code, message, data } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let components = try container.decodeDictionary(Dictionary<String, Any>.self, forKey: .error) guard let codeValue = components[CodingKeys.code.rawValue], let code = codeValue as? Int else { let context = DecodingError.Context(codingPath: [CodingKeys.code], debugDescription: "The key 'code' must be an Int.") throw DecodingError.dataCorrupted(context) } let message = components[CodingKeys.message.rawValue] as? String ?? "" let errorData = try? ErrorData(from: decoder) switch code { case -32700: self = .parseError(message: message, data: errorData) case -32600: self = .invalidRequest(message: message, data: errorData) case -32601: self = .methodNotFound(message: message, data: errorData) case -32602: self = .invalidParams(message: message, data: errorData) case -32603: self = .internalError(message: message, data: errorData) case -32099 ... -32000: self = .raw(code: code, message: message, data: errorData) default: throw DecodingError.dataCorruptedError(forKey: ErrorObject.CodingKeys.code, in: container, debugDescription: "The code \(code) is not allowed.") } } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) switch self { case .raw(code: let code, message: let message, data: let data): guard ErrorObject.isValidImplementationDefinedCode(code) else { let context = EncodingError.Context(codingPath: container.codingPath, debugDescription: "\(code) is not defined inside the range between -32099 and -32000.") throw EncodingError.invalidValue(code, context) } try container.encode(code, forKey: .code) try container.encode(message, forKey: .message) if let data = data { try container.encode(data, forKey: .data) } default: try container.encode(code, forKey: .code) try container.encode(message, forKey: .message) if let data = data { try container.encode(data, forKey: .data) } } } } <file_sep>// // JsonRPC // // Copyright © 2016-2017 Tinrobots. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. /// A JSON-RPC request. public struct Request { /// A String containing the name of the method to be invoked. Method names that begin with the word rpc followed by a period character (U+002E or ASCII 46) are reserved for rpc-internal methods and extensions and MUST NOT be used for anything else. public var method: String /// An identifier established by the Client that MUST contain a String, Number, or NULL value if included. /// If it is not included it is assumed to be a notification. The value SHOULD normally not be Null and Numbers SHOULD NOT contain fractional parts. public var id: Id? /// A Structured value that holds the parameter values to be used during the invocation of the method. This member MAY be omitted. public var params: Parameters? } extension Request { /// A Notification is a Request object without an "id" member. /// A Request object that is a Notification signifies the Client's lack of interest in the corresponding Response object, and as such no Response object needs to be returned to the client. The Server MUST NOT reply to a Notification, including those that are within a batch request. public var isNotification: Bool { return id == nil } } // MARK: - Codable extension Request: Codable { enum CodingKeys: String, CodingKey { case jsonrpc, id, method, params } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) guard let jsonrpc = try? container.decode(String.self, forKey: .jsonrpc), jsonrpc == "2.0" else { let context = DecodingError.Context(codingPath: [CodingKeys.jsonrpc], debugDescription: "JSON RPC version not supported.") throw DecodingError.dataCorrupted(context) } guard let method = try? container.decode(String.self, forKey: .method), method != "" else { let context = DecodingError.Context(codingPath: [CodingKeys.method], debugDescription: "The key 'method' cannot be nil or empty.") throw DecodingError.dataCorrupted(context) } let params = try? Parameters(from: decoder) let id = try? Id(from: decoder) self = Request(method: method, id: id, params: params) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode("2.0", forKey: .jsonrpc) try container.encode(method, forKey: .method) if let params = params { try container.encode(params, forKey: .params) } if let id = id { // the use of null for id in Requests is discouraged try container.encode(id, forKey: .id) } } } <file_sep>#!/bin/sh directories=(Sources Tests) for directory in "${directories[@]}" do echo "Cleaning whitespaces in directory: $directory" find $directory -iregex '.*\.swift' -exec sed -E -i '' -e 's/[[:blank:]]*$//' {} \; done echo "Done"<file_sep>// // JsonRPC // // Copyright © 2016-2017 Tinrobots. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import XCTest @testable import JsonRPC extension ErrorOjectTests { static var allTests = [ ("testPredefinedCase", testPredefinedCase), ("testInitializationRawError", testInitializationRawError) ] } class ErrorOjectTests: XCTestCase { func testPredefinedCase() throws { do { let error = ErrorObject.parseError(message: "message 1", data: nil) XCTAssertTrue(error.code == -32700) XCTAssertTrue(error.message == "message 1") XCTAssertNil(error.data) } do { let error = ErrorObject.invalidRequest(message: "message 2", data: nil) XCTAssertTrue(error.code == -32600) XCTAssertTrue(error.message == "message 2") XCTAssertNil(error.data) } do { let error = ErrorObject.methodNotFound(message: "message 3", data: nil) XCTAssertTrue(error.code == -32601) XCTAssertTrue(error.message == "message 3") XCTAssertNil(error.data) } do { let error = ErrorObject.invalidParams(message: "message 4", data: nil) XCTAssertTrue(error.code == -32602) XCTAssertTrue(error.message == "message 4") XCTAssertNil(error.data) } do { let error = ErrorObject.internalError(message: "message 4", data: nil) XCTAssertTrue(error.code == -32603) XCTAssertTrue(error.message == "message 4") XCTAssertNil(error.data) } do { let error = ErrorObject.raw(code: -31990, message: "message 4", data: nil) XCTAssertTrue(error.code == -31990) XCTAssertTrue(error.message == "message 4") XCTAssertNil(error.data) } } func testInitializationRawError() { do { let error = ErrorObject(code: -32010) XCTAssertTrue(error?.message == "Server Error") } } } <file_sep>// // JsonRPC // // Copyright © 2016-2017 Tinrobots. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. public enum ErrorData { case primitive(value: Any) case structured(object: [String: Any]) } extension ErrorData: Codable { enum CodingKeys: String, CodingKey { case error, data } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self).nestedContainer(keyedBy: CodingKeys.self, forKey: .error) if let value = try? container.decodeDictionary([String: Any].self, forKey: .data) { self = .structured(object: value) } else if let value = try? container.decodeAny(forKey: .data) { self = .primitive(value: value) } else { let context = DecodingError.Context(codingPath: [CodingKeys.data], debugDescription: "The key 'data' not found.") throw DecodingError.keyNotFound(CodingKeys.data, context) } } public func encode(to encoder: Encoder) throws { switch self { case .primitive(let value): var container = encoder.singleValueContainer() try container.encodeAny(value) case .structured(let dictionary): var container = encoder.container(keyedBy: DynamicCodingKey.self) try container.encodeDictionary(dictionary) } } } <file_sep>import XCTest @testable import JsonRPCTests XCTMain([ testCase(RequestTests.allTests), testCase(ResponseTests.allTests), testCase(IdTests.allTests), testCase(ErrorOjectTests.allTests) ]) <file_sep>// // JsonRPC // // Copyright © 2016-2017 Tinrobots. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import XCTest @testable import JsonRPC extension RequestTests { static var allTests = [ ("testDecodingRequestWithInvalidJsonRPCVersion", testDecodingRequestWithInvalidJsonRPCVersion), ("testDecodingRequestWithInvalidMethod", testDecodingRequestWithInvalidMethod), ("testDecodingRequestWithPositionalParameters", testDecodingRequestWithPositionalParameters), ("testDecodingRequestWithNamedParameters", testDecodingRequestWithNamedParameters), ("testDecodingNotificationWithPositionalParameters", testDecodingNotificationWithPositionalParameters), ("testDecodingNotificationWithNamedParameters", testDecodingNotificationWithNamedParameters), ("testRequestWithNestedDictionaries", testRequestWithNestedDictionaries), ("testEncodingRequestWithPositionalParameters", testEncodingRequestWithPositionalParameters), ("testEncodingNotificationWithoutParameters", testEncodingNotificationWithoutParameters), ("testEncodingNotificationWithNamedParameters", testEncodingNotificationWithNamedParameters) ] } class RequestTests: XCTestCase { // MARK: - Decoding func testDecodingRequestWithInvalidJsonRPCVersion() throws { let json = """ {"jsonrpc": "1.0", "method": "subtract", "params": [42, 23], "id": 1} """.data(using: .utf8)! XCTAssertThrowsError(try JSONDecoder().decode(Request.self, from: json)) } func testDecodingRequestWithInvalidMethod() throws { do { let json = """ {"jsonrpc": "2.0", "method": "", "params": [42, 23], "id": 1} """.data(using: .utf8)! XCTAssertThrowsError(try JSONDecoder().decode(Request.self, from: json)) } do { let json = """ {"jsonrpc": "2.0", "params": [42, 23], "id": 1} """.data(using: .utf8)! XCTAssertThrowsError(try JSONDecoder().decode(Request.self, from: json)) } } func testDecodingRequestWithPositionalParameters() throws { do { let json = """ {"jsonrpc": "2.0", "method": "subtract", "params": [42, 23], "id": 1} """.data(using: .utf8)! let request = try JSONDecoder().decode(Request.self, from: json) XCTAssertTrue(request.id == Id.number(1)) XCTAssertTrue(request.method == "subtract") guard let parameters = request.params else { XCTAssertNotNil(request.params) return } switch parameters { case .positional(let parameters): XCTAssertTrue(parameters.count == 2) XCTAssertTrue(parameters.first! as! Int == 42) XCTAssertTrue(parameters.last! as! Int == 23) default: XCTFail() } } do { let json = """ {"jsonrpc": "2.0", "method": "subtract", "params": [42, null, 11], "id": 1} """.data(using: .utf8)! let request = try JSONDecoder().decode(Request.self, from: json) XCTAssertTrue(request.id == Id.number(1)) XCTAssertTrue(request.method == "subtract") guard let parameters = request.params else { XCTAssertNotNil(request.params) return } switch parameters { case .positional(let parameters): XCTAssertTrue(parameters.count == 3) XCTAssertTrue(parameters.first! as! Int == 42) XCTAssertNil(parameters[1]) XCTAssertTrue(parameters.last! as! Int == 11) default: XCTFail() } } // do { // let json = """ // {"jsonrpc": "2.0", "method": "subtract", "params": [42, 11, [1,2]], "id": 1} // """.data(using: .utf8)! // // // let request = try JSONDecoder().decode(Request.self, from: json) // // XCTAssertTrue(request.id == Id.number(1)) // XCTAssertTrue(request.method == "subtract") // // guard let parameters = request.params else { // XCTAssertNotNil(request.params) // return // } // // switch parameters { // case .positional(let parameters): // print(parameters) // XCTAssertTrue(parameters.count == 3) // XCTAssertTrue(parameters.first! as! Int == 42) // XCTAssertNil(parameters[1]) // XCTAssertTrue(parameters.last! as! Int == 11) // default: // XCTFail() // } // } } func testDecodingRequestWithNamedParameters() throws { do { let json = """ {"jsonrpc": "2.0", "method": "subtract", "params": {"subtrahend": 23, "minuend": 42}, "id": 3} """.data(using: .utf8)! let request = try JSONDecoder().decode(Request.self, from: json) XCTAssertTrue(request.id == Id.number(3)) XCTAssertTrue(request.method == "subtract") guard let parameters = request.params else { XCTAssertNotNil(request.params) return } switch parameters { case .named(let parameters): XCTAssertTrue(parameters["subtrahend"] as! Int == 23) XCTAssertTrue(parameters["minuend"] as! Int == 42) default: XCTFail() } } do { let json = """ {"jsonrpc": "2.0", "method": "subtract", "params": {"value": 23, "text": "hello world", "bool": true}, "id": 3} """.data(using: .utf8)! let request = try JSONDecoder().decode(Request.self, from: json) XCTAssertTrue(request.id == Id.number(3)) XCTAssertTrue(request.method == "subtract") guard let parameters = request.params else { XCTAssertNotNil(request.params) return } switch parameters { case .named(let parameters): XCTAssertTrue(parameters["value"] as! Int == 23) XCTAssertTrue(parameters["text"] as! String == "hello world") XCTAssertTrue(parameters["bool"] as! Bool == true) default: XCTFail() } } } func testDecodingNotificationWithPositionalParameters() throws { let json = """ {"jsonrpc": "2.0", "method": "update", "params": [1,2,3,4,5]} """.data(using: .utf8)! let request = try JSONDecoder().decode(Request.self, from: json) XCTAssertTrue(request.method == "update") XCTAssertNil(request.id) XCTAssertTrue(request.isNotification) guard let parameters = request.params else { XCTAssertNotNil(request.params) return } switch parameters { case .positional(let parameters): XCTAssertTrue(parameters.count == 5) XCTAssertTrue(parameters[0] as! Int == 1) XCTAssertTrue(parameters[1] as! Int == 2) XCTAssertTrue(parameters[2] as! Int == 3) XCTAssertTrue(parameters[3] as! Int == 4) XCTAssertTrue(parameters[4] as! Int == 5) default: XCTFail("It should be a notification.") } } func testDecodingNotificationWithNamedParameters() throws { do { let json = """ {"jsonrpc": "2.0", "method": "subtract", "params": {"subtrahend": 23, "minuend": 42}} """.data(using: .utf8)! let request = try JSONDecoder().decode(Request.self, from: json) XCTAssertTrue(request.isNotification) XCTAssertTrue(request.method == "subtract") guard let parameters = request.params else { XCTAssertNotNil(request.params) return } switch parameters { case .named(let parameters): XCTAssertTrue(parameters["subtrahend"] as! Int == 23) XCTAssertTrue(parameters["minuend"] as! Int == 42) default: XCTFail() } } do { let json = """ {"jsonrpc": "2.0", "method": "subtract", "params": {"value": 23, "text": "hello world", "bool": true}} """.data(using: .utf8)! let request = try JSONDecoder().decode(Request.self, from: json) XCTAssertTrue(request.isNotification) XCTAssertTrue(request.method == "subtract") guard let parameters = request.params else { XCTAssertNotNil(request.params) return } switch parameters { case .named(let parameters): XCTAssertTrue(parameters["value"] as! Int == 23) XCTAssertTrue(parameters["text"] as! String == "hello world") XCTAssertTrue(parameters["bool"] as! Bool == true) default: XCTFail() } } } func testRequestWithNestedDictionaries() throws { let json = """ {"jsonrpc":"2.0", "id":0, "method":"initialize", "params":{ "processId":8316, "rootPath":null, "rootUri":null, "capabilities":{ "workspace":{ "applyEdit":true, "didChangeConfiguration":{"dynamicRegistration":true}, "didChangeWatchedFiles":{"dynamicRegistration":true}, "symbol":{"dynamicRegistration":true}, "executeCommand":{"dynamicRegistration":true} }, } } } """.data(using: .utf8)! let request = try JSONDecoder().decode(Request.self, from: json) guard let params = request.params else { return XCTAssertNotNil(request.params) } switch params { case .named(object: let dictionary): XCTAssertNil(dictionary["rootPath"]) XCTAssertNil(dictionary["rootUri"]) XCTAssertTrue(dictionary["processId"] as! Int == 8316) guard let capabilities = dictionary["capabilities"] as? [String: Any] else { return XCTFail("The key 'capabilities' should be a dictionary of [String: Any]") } guard let workspace = capabilities["workspace"] as? [String: Any] else { return XCTFail("The key 'workspace' should be a dictionary of [String: Any]") } XCTAssertTrue(workspace["applyEdit"] as! Bool == true) guard let didChangeConfiguration = workspace["didChangeConfiguration"] as? [String: Any] else { return XCTFail("The key 'didChangeConfiguration' should be a dictionary of [String: Any]") } XCTAssertTrue(didChangeConfiguration["dynamicRegistration"] as! Bool == true) guard let didChangeWatchedFiles = workspace["didChangeWatchedFiles"] as? [String: Any] else { return XCTFail("The key 'didChangeWatchedFiles' should be a dictionary of [String: Any]") } XCTAssertTrue(didChangeWatchedFiles["dynamicRegistration"] as! Bool == true) guard let symbol = workspace["symbol"] as? [String: Any] else { return XCTFail("The key 'symbol' should be a dictionary of [String: Any]") } XCTAssertTrue(symbol["dynamicRegistration"] as! Bool == true) guard let executeCommand = workspace["executeCommand"] as? [String: Any] else { return XCTFail("The key 'executeCommand' should be a dictionary of [String: Any]") } XCTAssertTrue(executeCommand["dynamicRegistration"] as! Bool == true) default: XCTFail("Invalid params type") } } // MARK: - Encoding func testEncodingRequestWithPositionalParameters() throws { do { let request = Request(method: "test", id: Id.number(11), params: Parameters.positional(array: [1, 2, true, "hello"])) let encoder = JSONEncoder() let jsonData = try encoder.encode(request) guard let json = String(data: jsonData, encoding: .utf8) else { XCTFail("Failed while converting Data to String.") return } XCTAssertTrue(json.contains("\"jsonrpc\":\"2.0")) XCTAssertTrue(json.contains("\"method\":\"test")) XCTAssertTrue(json.contains("\"id\":11")) XCTAssertTrue(json.contains("\"params\":[1,2,true,\"hello\"]")) } do { let request = Request(method: "test2", id: Id.string("customId"), params: Parameters.positional(array: [1, 2, true, ["hello", 3]])) let encoder = JSONEncoder() let jsonData = try encoder.encode(request) guard let json = String(data: jsonData, encoding: .utf8) else { XCTFail("Failed while converting Data to String.") return } XCTAssertTrue(json.contains("\"jsonrpc\":\"2.0")) XCTAssertTrue(json.contains("\"method\":\"test2")) XCTAssertTrue(json.contains("\"id\":\"customId\"")) XCTAssertTrue(json.contains("\"params\":[1,2,true,[\"hello\",3]]")) } do { let request = Request(method: "test3", id: Id.number(0), params: Parameters.positional(array: [1, 2, true, ["subtrahend": 23, "minuend": 42]])) let encoder = JSONEncoder() let jsonData = try encoder.encode(request) guard let json = String(data: jsonData, encoding: .utf8) else { XCTFail("Failed while converting Data to String.") return } XCTAssertTrue(json.contains("\"jsonrpc\":\"2.0")) XCTAssertTrue(json.contains("\"method\":\"test3")) XCTAssertTrue(json.contains("\"id\":0")) XCTAssertTrue(json.contains("\"params\":")) XCTAssertTrue(json.contains("[1,2,true,")) XCTAssertTrue(json.contains("\"minuend\":42")) XCTAssertTrue(json.contains("\"subtrahend\":23")) } do { let request = Request(method: "test3", id: Id.string("0"), params: Parameters.positional(array: [1, true, ["key1": "k1", "key2": 2, "key3": [0,3,["subKey1": true, "subKey2": 12]]]])) let encoder = JSONEncoder() let jsonData = try encoder.encode(request) guard let json = String(data: jsonData, encoding: .utf8) else { XCTFail("Failed while converting Data to String.") return } XCTAssertTrue(json.contains("\"jsonrpc\":\"2.0")) XCTAssertTrue(json.contains("\"method\":\"test3")) XCTAssertTrue(json.contains("\"id\":\"0\"")) XCTAssertTrue(json.contains("\"params\":[")) XCTAssertTrue(json.contains("[1,true")) XCTAssertTrue(json.contains("\"key1\":\"k1\"")) XCTAssertTrue(json.contains("\"key3\":[0,3,{")) XCTAssertTrue(json.contains("\"subKey2\":12")) XCTAssertTrue(json.contains("\"subKey1\":true")) } } func testEncodingNotificationWithoutParameters() throws { do { let request = Request(method: "123", id: nil, params: nil) let encoder = JSONEncoder() let jsonData = try encoder.encode(request) guard let json = String(data: jsonData, encoding: .utf8) else { XCTFail("Failed while converting Data to String.") return } XCTAssertTrue(json.contains("\"jsonrpc\":\"2.0")) XCTAssertTrue(json.contains("\"method\":\"123")) XCTAssertFalse(json.contains("id")) XCTAssertFalse(json.contains("params")) } } func testEncodingNotificationWithNamedParameters() throws { do { let request = Request(method: "123", id: nil, params: Parameters.named(object: ["subtrahend": 23, "minuend": 42])) let encoder = JSONEncoder() let jsonData = try encoder.encode(request) guard let json = String(data: jsonData, encoding: .utf8) else { XCTFail("Failed while converting Data to String.") return } XCTAssertTrue(json.contains("\"jsonrpc\":\"2.0")) XCTAssertTrue(json.contains("\"method\":\"123")) XCTAssertFalse(json.contains("id")) XCTAssertTrue(json.contains("\"params\":{")) XCTAssertTrue(json.contains("\"minuend\":42")) XCTAssertTrue(json.contains("\"subtrahend\":23")) } do { let request = Request(method: "123", id: nil, params: Parameters.named(object: ["subtrahend": 23, "minuend": 42, "other":[1,2,3]])) let encoder = JSONEncoder() let jsonData = try encoder.encode(request) guard let json = String(data: jsonData, encoding: .utf8) else { XCTFail("Failed while converting Data to String.") return } XCTAssertTrue(json.contains("\"jsonrpc\":\"2.0")) XCTAssertTrue(json.contains("\"method\":\"123")) XCTAssertFalse(json.contains("id")) XCTAssertTrue(json.contains("\"params\":{")) XCTAssertTrue(json.contains("\"other\":[1,2,3]")) XCTAssertTrue(json.contains("\"minuend\":42")) XCTAssertTrue(json.contains("\"subtrahend\":23")) } } } <file_sep>// // JsonRPC // // Copyright © 2016-2017 Tinrobots. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation struct DynamicCodingKey: CodingKey { var stringValue: String init?(stringValue: String) { self.stringValue = stringValue } var intValue: Int? init?(intValue: Int) { self.init(stringValue: "\(intValue)") self.intValue = intValue } } // MARK: - Decoding extension KeyedDecodingContainer { func decodeDictionary(_ type: Dictionary<String, Any>.Type, forKey key: K) throws -> Dictionary<String, Any> { let container = try nestedContainer(keyedBy: DynamicCodingKey.self, forKey: key) return try container.decodeDictionary(type) } /* func decodeDictionaryIfPresent(_ type: Dictionary<String, Any>.Type, forKey key: K) throws -> Dictionary<String, Any>? { guard contains(key) else { return nil } return try decodeDictionary(type, forKey: key) } func decodeArrayIfPresent(_ type: Array<Any?>.Type, forKey key: K) throws -> Array<Any?>? { guard contains(key) else { return nil } return try decodeArray(type, forKey: key) } */ func decodeArray(_ type: Array<Any?>.Type, forKey key: K) throws -> Array<Any?> { var container = try nestedUnkeyedContainer(forKey: key) return try container.decodeArray(type) } func decodeDictionary(_ type: Dictionary<String, Any>.Type) throws -> Dictionary<String, Any> { var dictionary = Dictionary<String, Any>() for key in allKeys { if let boolValue = try? decode(Bool.self, forKey: key) { dictionary[key.stringValue] = boolValue } else if let stringValue = try? decode(String.self, forKey: key) { dictionary[key.stringValue] = stringValue } else if let intValue = try? decode(Int.self, forKey: key) { dictionary[key.stringValue] = intValue } else if let doubleValue = try? decode(Double.self, forKey: key) { dictionary[key.stringValue] = doubleValue } else if let nestedDictionary = try? decodeDictionary(Dictionary<String, Any>.self, forKey: key) { dictionary[key.stringValue] = nestedDictionary } else if let nestedArray = try? decodeArray(Array<Any?>.self, forKey: key) { dictionary[key.stringValue] = nestedArray } else { //if nil or not yet supported, simply skip the key //let context = DecodingError.Context(codingPath: codingPath, debugDescription: "The decoding operation for \(key) is not yet supported.") //throw DecodingError.dataCorrupted(context) continue } } return dictionary } func decodeAny(forKey key: K) throws -> Any { if let value = try? decode(Bool.self, forKey: key) { return value } else if let value = try? decode(String.self, forKey: key) { return value } else if let value = try? decode(Int.self, forKey: key) { return value } else if let value = try? decode(Double.self, forKey: key) { return value } else if let value = try? decodeArray([Any?].self, forKey: key) { return value } else if let value = try? decodeDictionary([String: Any].self, forKey: key) { return value } else { let context = DecodingError.Context(codingPath: codingPath, debugDescription: "The decoding operation for \(key) is not yet supported.") throw DecodingError.dataCorrupted(context) } } } extension UnkeyedDecodingContainer { // mutating func decode(_ type: Array<Any>.Type) throws -> Array<Any> { // var array: [Any] = [] // while isAtEnd == false { // if let value = try? decode(Bool.self) { // array.append(value) // } else if let value = try? decode(Double.self) { // array.append(value) // } else if let value = try? decode(String.self) { // array.append(value) // } else if let nestedDictionary = try? decode(Dictionary<String, Any>.self) { // array.append(nestedDictionary) // } else if let nestedArray = try? decode(Array<Any>.self) { // array.append(nestedArray) // } else { // let context = DecodingError.Context(codingPath: codingPath, debugDescription: "The decoding operation is not yet supported.") // throw DecodingError.dataCorrupted(context) // } // } // return array // } mutating func decodeArray(_ type: Array<Any?>.Type) throws -> Array<Any?> { var array: [Any?] = [] while isAtEnd == false { if let value = try? decode(Bool.self) { array.append(value) } else if let value = try? decode(String.self) { array.append(value) } else if let value = try? decode(Int.self) { array.append(value) } else if let value = try? decode(Double.self) { array.append(value) } else if let _ = try? decodeNil() { // https://web.archive.org/web/20100718181845/http://json-rpc.org/wd/JSON-RPC-1-1-WD-20060807.html#NullParameters array.append(nil) } else { let context = DecodingError.Context(codingPath: codingPath, debugDescription: "The decoding operation is not yet supported.") throw DecodingError.dataCorrupted(context) } } return array } mutating func decodeDictionary(_ type: Dictionary<String, Any>.Type) throws -> Dictionary<String, Any> { let nestedContainer = try self.nestedContainer(keyedBy: DynamicCodingKey.self) return try nestedContainer.decodeDictionary(type) } } // MARK: - Encoding extension KeyedEncodingContainer { mutating func encodeAny(_ value: Any, forKey key: Key) throws { switch value { case let element as Bool: try encode(element, forKey: key) case let value as String: try encode(value, forKey: key) case let value as Int: try encode(value, forKey: key) case let value as Double: try encode(value, forKey: key) case let value as Dictionary<String, Any>: var nestedKeyedContainer = nestedContainer(keyedBy: DynamicCodingKey.self, forKey: key) try nestedKeyedContainer.encodeDictionary(value) case let value as Array<Any>: var nestedContainer = nestedUnkeyedContainer(forKey: key) try nestedContainer.encodeArray(value) default: let context = EncodingError.Context(codingPath: codingPath, debugDescription: "The encoding operation for \(value) is not yet supported.") throw EncodingError.invalidValue(value, context) } } } extension KeyedEncodingContainer where Key == DynamicCodingKey { //TODO: the where clause should be defined? mutating func encodeDictionary(_ dictionary: Dictionary<String, Any>) throws { for (key, value) in dictionary { let key = DynamicCodingKey(stringValue: key)! switch value { case let bool as Bool: try encode(bool, forKey: key) case let string as String: try encode(string, forKey: key) case let int as Int: try encode(int, forKey: key) case let double as Double: try encode(double, forKey: key) case let dictionary as Dictionary<String, Any>: var nestedKeyedContainer = nestedContainer(keyedBy: Key.self, forKey: key) try nestedKeyedContainer.encodeDictionary(dictionary) case let array as Array<Any>: var nestedContainer = nestedUnkeyedContainer(forKey: key) try nestedContainer.encodeArray(array) default: try encodeNil(forKey: key) //continue } } } } extension UnkeyedEncodingContainer { mutating func encodeArray(_ value: Array<Any?>) throws { for optionalElement in value { guard let element = optionalElement else { try encodeNil() continue } switch element { case let bool as Bool: try encode(bool) case let string as String: try encode(string) case let int as Int: try encode(int) case let double as Double: try encode(double) case let dictionary as Dictionary<String, Any>: var nestedKeyedContainer = nestedContainer(keyedBy: DynamicCodingKey.self) try nestedKeyedContainer.encodeDictionary(dictionary) case let array as Array<Any>: var nestedContainer = nestedUnkeyedContainer() try nestedContainer.encodeArray(array) default: continue } } } } extension SingleValueEncodingContainer { mutating func encodeAny(_ value: Any) throws { switch value { case let value as Bool: try encode(value) case let value as String: try encode(value) case let value as Int: try encode(value) case let value as Double: try encode(value) default: let context = EncodingError.Context(codingPath: codingPath, debugDescription: "The encoding operation for \(value) is not yet supported.") throw EncodingError.invalidValue(value, context) } } } <file_sep>// // JsonRPC // // Copyright © 2016-2017 Tinrobots. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import XCTest @testable import JsonRPC extension ResponseTests { static var allTests = [ ("testDecodingInvalidResponse", testDecodingInvalidResponse), ("testDecodingSuccessResponse", testDecodingSuccessResponse), ("testDecodingErrorResponse", testDecodingErrorResponse), ("testEncodingSuccessResponse", testEncodingSuccessResponse), ("testEncodingErrorResponse", testEncodingErrorResponse), ("testEncodingErrorResponseWithPredefinedCase", testEncodingErrorResponseWithPredefinedCase) ] } class ResponseTests: XCTestCase { // MARK: - Decoding func testDecodingInvalidResponse() throws { /// missing result and error at the same time do { let json = """ {"jsonrpc": "2.0", "id": 4} """.data(using: .utf8)! XCTAssertThrowsError(try JSONDecoder().decode(Response.self, from: json)) } /// error and result populated at the same time do { let json = """ {"jsonrpc": "2.0", "id": 4, "result": 1, "error": {"code": -32601, "message": "Method not found"} } """.data(using: .utf8)! XCTAssertThrowsError(try JSONDecoder().decode(Response.self, from: json)) } } func testDecodingSuccessResponse() throws { /// Int result do { let json = """ {"jsonrpc": "2.0", "result": 19, "id": 4} """.data(using: .utf8)! let response = try JSONDecoder().decode(Response.self, from: json) XCTAssertTrue(response.id == Id.number(4)) XCTAssertTrue(response.result as! Int == 19) XCTAssertNil(response.error) switch response { case .success(id: let id, result: let result): XCTAssertTrue(id == Id.number(4)) XCTAssertTrue(result as! Int == 19) default: XCTFail("Expected a success response.") } } /// String result do { let json = """ {"jsonrpc": "2.0", "result": "response result", "id": "test"} """.data(using: .utf8)! let response = try JSONDecoder().decode(Response.self, from: json) XCTAssertTrue(response.id == Id.string("test")) XCTAssertTrue(response.result as! String == "response result") XCTAssertNil(response.error) switch response { case .success(id: let id, result: let result): XCTAssertTrue(id == Id.string("test")) XCTAssertTrue(result as! String == "response result") default: XCTFail("Expected a success response.") } } /// Double result do { let json = """ {"jsonrpc": "2.0", "result": 19.19, "id": "test"} """.data(using: .utf8)! let response = try JSONDecoder().decode(Response.self, from: json) XCTAssertTrue(response.id == Id.string("test")) XCTAssertTrue(response.result as! Double == 19.19) XCTAssertNil(response.error) switch response { case .success(id: let id, result: let result): XCTAssertTrue(id == Id.string("test")) XCTAssertTrue(result as! Double == 19.19) default: XCTFail("Expected a success response.") } } /// invalid jsonrpc do { let json = """ {"jsonrpc": "2.1", "result": 19.19, "id": "test"} """.data(using: .utf8)! XCTAssertThrowsError(try JSONDecoder().decode(Response.self, from: json)) } /// array result do { let json = """ {"jsonrpc": "2.0", "result": ["hello", 5], "id": "9"} """.data(using: .utf8)! let response = try JSONDecoder().decode(Response.self, from: json) XCTAssertTrue(response.id == Id.string("9")) XCTAssertTrue((response.result as! [Any]).count == 2) XCTAssertTrue((response.result as! [Any])[0] as! String == "hello") XCTAssertTrue((response.result as! [Any])[1] as! Int == 5) XCTAssertNil(response.error) switch response { case .success(id: let id, result: let result): XCTAssertTrue(id == Id.string("9")) XCTAssertTrue((result as! [Any]).count == 2) XCTAssertTrue((result as! [Any])[0] as! String == "hello") XCTAssertTrue((result as! [Any])[1] as! Int == 5) default: XCTFail("Expected a success response.") } } /// dictionary result do { let json = """ {"jsonrpc": "2.0", "result": {"key1": 2, "key2": 1.1, "key3": [1, "a", true, null]}, "id": 1} """.data(using: .utf8)! let response = try JSONDecoder().decode(Response.self, from: json) XCTAssertTrue(response.id == Id.number(1)) XCTAssertTrue((response.result as! [String: Any]).count == 3) XCTAssertTrue((response.result as! [String: Any])["key1"] as! Int == 2) XCTAssertTrue((response.result as! [String: Any])["key2"] as! Double == 1.1) let arrayAssociatedWithKey3 = (response.result as! [String: Any])["key3"] as? [Any?] XCTAssertNotNil(arrayAssociatedWithKey3) XCTAssertTrue(arrayAssociatedWithKey3![0] as! Int == 1) XCTAssertTrue(arrayAssociatedWithKey3![1] as! String == "a") XCTAssertTrue(arrayAssociatedWithKey3![2] as! Bool == true) XCTAssertNil(arrayAssociatedWithKey3![3]) XCTAssertNil(response.error) switch response { case .success(id: let id, result: let result): XCTAssertTrue(id == Id.number(1)) XCTAssertTrue((result as! [String: Any]).count == 3) XCTAssertTrue((result as! [String: Any])["key1"] as! Int == 2) XCTAssertTrue((result as! [String: Any])["key2"] as! Double == 1.1) let arrayAssociatedWithKey3 = (result as! [String: Any])["key3"] as? [Any?] XCTAssertNotNil(arrayAssociatedWithKey3) XCTAssertTrue(arrayAssociatedWithKey3![0] as! Int == 1) XCTAssertTrue(arrayAssociatedWithKey3![1] as! String == "a") XCTAssertTrue(arrayAssociatedWithKey3![2] as! Bool == true) XCTAssertNil(arrayAssociatedWithKey3![3]) default: XCTFail("Expected a success response.") } } } func testDecodingErrorResponse() throws { /// error without data do { let json = """ {"jsonrpc": "2.0", "error": {"code": -32601, "message": "Method not found"}, "id": "1"} """.data(using: .utf8)! let response = try JSONDecoder().decode(Response.self, from: json) XCTAssertTrue(response.id == Id.string("1")) XCTAssertTrue(response.error?.code == -32601) XCTAssertTrue(response.error?.message == "Method not found") XCTAssertNil(response.error?.data) XCTAssertNil(response.result) switch response { case .error(id: let id, error: let error): XCTAssertNotNil(id) XCTAssertTrue(id == Id.string("1")) XCTAssertTrue(error.code == -32601) XCTAssertTrue(error.message == "Method not found") XCTAssertNil(error.data) default: XCTFail("Expected an error response.") } } /// error with data do { let json = """ {"jsonrpc": "2.0", "error": {"code": -32601, "message": "Method not found", "data": true}, "id": 12} """.data(using: .utf8)! let response = try JSONDecoder().decode(Response.self, from: json) XCTAssertTrue(response.id == Id.number(12)) XCTAssertTrue(response.error?.code == -32601) XCTAssertTrue(response.error?.message == "Method not found") XCTAssertNotNil(response.error?.data) XCTAssertNil(response.result) switch response { case .error(id: let id, error: let error): XCTAssertNotNil(id) XCTAssertTrue(id == Id.number(12)) XCTAssertTrue(error.code == -32601) XCTAssertTrue(error.message == "Method not found") XCTAssertNotNil(error.data) switch error { case .methodNotFound(message: let message, data: let errorData): XCTAssertTrue(message == "Method not found") switch errorData! { case .primitive(value: let data): XCTAssertTrue(data as! Bool == true) default: XCTFail("Wrong error data type.") } default: XCTFail("Wrong error type.") } default: XCTFail("Expected an error response.") } } /// defined with structured error data do { let json = """ {"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request", "data": {"value": 23, "nilValue": null} }, "id": 11} """.data(using: .utf8)! let response = try JSONDecoder().decode(Response.self, from: json) XCTAssertTrue(response.id == Id.number(11)) XCTAssertTrue(response.error?.code == -32600) XCTAssertTrue(response.error?.message == "Invalid Request") XCTAssertNotNil(response.error?.data) XCTAssertNil(response.result) switch response { case .error(id: let id, error: let error): XCTAssertNotNil(id) XCTAssertTrue(id == Id.number(11)) XCTAssertTrue(error.code == -32600) XCTAssertTrue(error.message == "Invalid Request") XCTAssertNotNil(error.data) switch error { case .invalidRequest(message: let message, data: let errorData): XCTAssertTrue(message == "Invalid Request") switch errorData! { case .structured(object: let dictionary): XCTAssertTrue(dictionary["value"] as! Int == 23) XCTAssertNil(dictionary["nilValue"]) default: XCTFail("Wrong error data type.") } default: XCTFail("Wrong error type.") } default: XCTFail("Expected an error response.") } } /// defined with structured error data do { let json = """ {"jsonrpc": "2.0", "error": {"code": -32010, "message": "Server Error", "data": {"value": 23, "nilValue": null} }, "id": 110} """.data(using: .utf8)! let response = try JSONDecoder().decode(Response.self, from: json) XCTAssertTrue(response.id == Id.number(110)) XCTAssertTrue(response.error?.code == -32010) XCTAssertTrue(response.error?.message == "Server Error") XCTAssertNotNil(response.error?.data) XCTAssertNil(response.result) switch response { case .error(id: let id, error: let error): XCTAssertNotNil(id) XCTAssertTrue(id == Id.number(110)) XCTAssertTrue(error.code == -32010) XCTAssertTrue(error.message == "Server Error") XCTAssertNotNil(error.data) switch error { case .raw(code: let code, message: let message, data: let data): XCTAssertTrue(code == -32010) XCTAssertTrue(message == "Server Error") switch data! { case .structured(object: let dictionary): XCTAssertTrue(dictionary["value"] as! Int == 23) XCTAssertNil(dictionary["nilValue"]) default: XCTFail("Wrong error data type.") } default: XCTFail("Wrong error type.") } default: XCTFail("Expected an error response.") } } /// invalid error id do { let json = """ {"jsonrpc": "2.0", "error": {"code": -1, "message": "Custom"}, "id": "1"} """.data(using: .utf8)! XCTAssertThrowsError(try JSONDecoder().decode(Response.self, from: json)) } /// invalid error id do { let json = """ {"jsonrpc": "2.0", "error": {"code": "fakeId", "message": "Custom"}, "id": "1"} """.data(using: .utf8)! XCTAssertThrowsError(try JSONDecoder().decode(Response.self, from: json)) } } // MARK: - Encoding func testEncodingSuccessResponse() throws { /// string result do { let response = Response.success(id: Id.number(10), result: "Success") let encoder = JSONEncoder() let jsonData = try encoder.encode(response) guard let json = String(data: jsonData, encoding: .utf8) else { XCTFail("Failed while converting Data to String.") return } XCTAssertTrue(json.contains("\"jsonrpc\":\"2.0\"")) XCTAssertTrue(json.contains("\"id\":10")) XCTAssertTrue(json.contains("\"result\":\"Success\"")) } /// [int] result do { let response = Response.success(id: Id.number(0), result: [1,2,3]) let encoder = JSONEncoder() let jsonData = try encoder.encode(response) guard let json = String(data: jsonData, encoding: .utf8) else { XCTFail("Failed while converting Data to String.") return } XCTAssertTrue(json.contains("\"jsonrpc\":\"2.0\"")) XCTAssertTrue(json.contains("\"id\":0")) XCTAssertTrue(json.contains("\"result\":[1,2,3")) } /// [Any] result do { let response = Response.success(id: Id.string("10"), result: [1,false,3, "four"]) let encoder = JSONEncoder() let jsonData = try encoder.encode(response) guard let json = String(data: jsonData, encoding: .utf8) else { XCTFail("Failed while converting Data to String.") return } XCTAssertTrue(json.contains("\"jsonrpc\":\"2.0\"")) XCTAssertTrue(json.contains("\"id\":\"10\"")) XCTAssertTrue(json.contains("\"result\":[1,false,3,\"four\"")) } /// [String: Any] result do { let response = Response.success(id: Id.string("0"), result: ["key1": true, "key2": 11.83]) let encoder = JSONEncoder() let jsonData = try encoder.encode(response) guard let json = String(data: jsonData, encoding: .utf8) else { XCTFail("Failed while converting Data to String.") return } XCTAssertTrue(json.contains("\"jsonrpc\":\"2.0\"")) XCTAssertTrue(json.contains("\"id\":\"0\"")) XCTAssertTrue(json.contains("\"key1\":true")) XCTAssertTrue(json.contains("\"key2\":11.83")) } /// nested [String: Any] result do { let response = Response.success(id: Id.string("0"), result: ["key1": true, "key2": ["subkey1":[false, 0]]]) let encoder = JSONEncoder() let jsonData = try encoder.encode(response) guard let json = String(data: jsonData, encoding: .utf8) else { XCTFail("Failed while converting Data to String.") return } XCTAssertTrue(json.contains("\"jsonrpc\":\"2.0\"")) XCTAssertTrue(json.contains("\"id\":\"0\"")) XCTAssertTrue(json.contains("\"key1\":true")) XCTAssertTrue(json.contains("\"key2\":{")) XCTAssertTrue(json.contains("\"subkey1\":[false,0]")) } } func testEncodingErrorResponse() throws { /// raw without error data do { let error = ErrorObject(code: -32000, message: "Something went wrong.")! let response = Response.error(id: Id.string("errorID"), error: error) let encoder = JSONEncoder() let jsonData = try encoder.encode(response) guard let json = String(data: jsonData, encoding: .utf8) else { XCTFail("Failed while converting Data to String.") return } XCTAssertTrue(json.contains("\"jsonrpc\":\"2.0\"")) XCTAssertTrue(json.contains("\"id\":\"errorID\"")) XCTAssertTrue(json.contains("\"error\":{")) XCTAssertTrue(json.contains("\"message\":\"Something went wrong.\"")) XCTAssertTrue(json.contains("\"code\":-32000")) } /// raw with error data do { let errorData = ErrorData.structured(object: ["key1": [1,2,nil]]) let error = ErrorObject(code: -32000, message: "Something went wrong.", data: errorData)! let response = Response.error(id: Id.string("errorID"), error: error) let encoder = JSONEncoder() let jsonData = try encoder.encode(response) guard let json = String(data: jsonData, encoding: .utf8) else { XCTFail("Failed while converting Data to String.") return } XCTAssertTrue(json.contains("\"jsonrpc\":\"2.0\"")) XCTAssertTrue(json.contains("\"id\":\"errorID\"")) XCTAssertTrue(json.contains("\"error\":{")) XCTAssertTrue(json.contains("\"message\":\"Something went wrong.\"")) XCTAssertTrue(json.contains("\"code\":-32000")) XCTAssertTrue(json.contains("\"data\"")) XCTAssertTrue(json.contains("\"key1\":[1,2,null]")) } /// empty message and no error data do { let error = ErrorObject.parseError(message: "", data: nil) let response = Response.error(id: Id.string("errorID"), error: error) let encoder = JSONEncoder() let jsonData = try encoder.encode(response) guard let json = String(data: jsonData, encoding: .utf8) else { XCTFail("Failed while converting Data to String.") return } XCTAssertTrue(json.contains("\"jsonrpc\":\"2.0\"")) XCTAssertTrue(json.contains("\"id\":\"errorID\"")) XCTAssertTrue(json.contains("\"error\":{")) XCTAssertTrue(json.contains("\"message\":\"\"")) XCTAssertFalse(json.contains("data")) XCTAssertTrue(json.contains("\"code\":-32700")) } /// predefined error do { let error = ErrorObject.invalidRequest(message: "Invalid R.", data: nil) let response = Response.error(id: Id.string("errorID"), error: error) let encoder = JSONEncoder() let jsonData = try encoder.encode(response) guard let json = String(data: jsonData, encoding: .utf8) else { XCTFail("Failed while converting Data to String.") return } XCTAssertTrue(json.contains("\"jsonrpc\":\"2.0\"")) XCTAssertTrue(json.contains("\"id\":\"errorID\"")) XCTAssertTrue(json.contains("\"error\":{")) XCTAssertTrue(json.contains("\"message\":\"Invalid R.\"")) XCTAssertTrue(json.contains("\"code\":-32600")) } /// primitive error data do { let error = ErrorObject.internalError(message: "Internal error", data: ErrorData.primitive(value: 10)) let response = Response.error(id: Id.string("errorID"), error: error) let encoder = JSONEncoder() let jsonData = try encoder.encode(response) guard let json = String(data: jsonData, encoding: .utf8) else { XCTFail("Failed while converting Data to String.") return } XCTAssertTrue(json.contains("\"jsonrpc\":\"2.0\"")) XCTAssertTrue(json.contains("\"id\":\"errorID\"")) XCTAssertTrue(json.contains("\"error\":{")) XCTAssertTrue(json.contains("\"message\":\"Internal error\"")) XCTAssertTrue(json.contains("\"data\":10")) XCTAssertTrue(json.contains("\"code\":-32603")) } /// structured error data do { let error = ErrorObject.internalError(message: "Internal error", data: ErrorData.structured(object: ["key1": true, "key2": 3])) let encoder = JSONEncoder() let response = Response.error(id: Id.string("errorID"), error: error) let jsonData = try encoder.encode(response) guard let json = String(data: jsonData, encoding: .utf8) else { XCTFail("Failed while converting Data to String.") return } XCTAssertTrue(json.contains("\"jsonrpc\":\"2.0\"")) XCTAssertTrue(json.contains("\"id\":\"errorID\"")) XCTAssertTrue(json.contains("\"error\":{")) XCTAssertTrue(json.contains("\"message\":\"Internal error\"")) XCTAssertTrue(json.contains("\"data\":{")) XCTAssertTrue(json.contains("\"key1\":true")) XCTAssertTrue(json.contains("\"key2\":3")) XCTAssertTrue(json.contains("\"code\":-32603")) } /// invalid error id do { XCTAssertNil(ErrorObject(code: -1, message: "Something went wrong.")) } } func testEncodingErrorResponseWithPredefinedCase() throws { do { let error = ErrorObject.parseError(message: "parse error", data: nil) let encoder = JSONEncoder() let response = Response.error(id: Id.number(1), error: error) let jsonData = try encoder.encode(response) guard let json = String(data: jsonData, encoding: .utf8) else { XCTFail("Failed while converting Data to String.") return } XCTAssertTrue(json.contains("\"jsonrpc\":\"2.0\"")) XCTAssertTrue(json.contains("\"id\":1")) XCTAssertTrue(json.contains("\"error\":{")) XCTAssertTrue(json.contains("\"code\":-32700")) } do { let error = ErrorObject.invalidRequest(message: "invalid request", data: nil) let encoder = JSONEncoder() let response = Response.error(id: Id.number(1), error: error) let jsonData = try encoder.encode(response) guard let json = String(data: jsonData, encoding: .utf8) else { XCTFail("Failed while converting Data to String.") return } XCTAssertTrue(json.contains("\"jsonrpc\":\"2.0\"")) XCTAssertTrue(json.contains("\"id\":1")) XCTAssertTrue(json.contains("\"error\":{")) XCTAssertTrue(json.contains("\"code\":-32600")) } do { let error = ErrorObject.methodNotFound(message: "method not found", data: nil) let encoder = JSONEncoder() let response = Response.error(id: Id.number(1), error: error) let jsonData = try encoder.encode(response) guard let json = String(data: jsonData, encoding: .utf8) else { XCTFail("Failed while converting Data to String.") return } XCTAssertTrue(json.contains("\"jsonrpc\":\"2.0\"")) XCTAssertTrue(json.contains("\"id\":1")) XCTAssertTrue(json.contains("\"error\":{")) XCTAssertTrue(json.contains("\"code\":-32601")) } do { let error = ErrorObject.invalidParams(message: "invalid params", data: nil) let encoder = JSONEncoder() let response = Response.error(id: Id.number(1), error: error) let jsonData = try encoder.encode(response) guard let json = String(data: jsonData, encoding: .utf8) else { XCTFail("Failed while converting Data to String.") return } XCTAssertTrue(json.contains("\"jsonrpc\":\"2.0\"")) XCTAssertTrue(json.contains("\"id\":1")) XCTAssertTrue(json.contains("\"error\":{")) XCTAssertTrue(json.contains("\"code\":-32602")) } do { let error = ErrorObject.internalError(message: "internal error", data: nil) let encoder = JSONEncoder() let response = Response.error(id: Id.number(1), error: error) let jsonData = try encoder.encode(response) guard let json = String(data: jsonData, encoding: .utf8) else { XCTFail("Failed while converting Data to String.") return } XCTAssertTrue(json.contains("\"jsonrpc\":\"2.0\"")) XCTAssertTrue(json.contains("\"id\":1")) XCTAssertTrue(json.contains("\"error\":{")) XCTAssertTrue(json.contains("\"code\":-32603")) } do { let error = ErrorObject.raw(code: -1, message: "raw error", data: nil) let encoder = JSONEncoder() let response = Response.error(id: Id.number(1), error: error) XCTAssertThrowsError(try encoder.encode(response)) } } }
d21b44c20afe11e42b363b167a1987154fec2345
[ "Swift", "Ruby", "Shell" ]
14
Swift
alemar11/JsonRPC
60bd07f734ca80608f5eb99b01b6cd2c4e555ebe
e36f9a9fd817877b55fac491940b246cc92e4262
refs/heads/main
<repo_name>dawid-danielewicz/mobile-app<file_sep>/src/store/modules/things/mutations.js export default { setThings(state, data) { state.things = data }, setThing(state, data) { state.id = data.id state.name = data.name state.group = data.group state.lamp = data.lamp state.temperature = data.temperature state.humidity = data.humidity }, updateLamp(state, data) { state.lamp = data }, updateThing(state, data) { state.name = data.name state.group = data.group }, deleteThing(state, data) { state.things.splice(state.things.indexOf(data), 1) } }<file_sep>/src/store/index.js import { createStore } from "vuex"; import createPersistedState from 'vuex-persistedstate' import AuthModule from './modules/auth/index.js' import ThingsModule from './modules/things/index.js' const store = createStore({ modules: { auth: AuthModule, things: ThingsModule }, plugins: [createPersistedState()] }) export default store;<file_sep>/src/store/modules/things/actions.js import router from "../../../router" const server = 'http://192.168.0.102:3000' export default { async getThings(context) { const response = await fetch(server + '/things', { method: 'GET', headers: { 'Authorization': `Bearer ${context.rootState.auth.token}` } }) const responseData = await response.json() context.commit('setThings', responseData) }, async createThing(context, data) { console.log(data.name) const response = await fetch(server + '/things', { method: 'POST', headers: { 'Authorization': `Bearer ${context.rootState.auth.token}`, 'Content-Type': 'application/x-www-form-urlencoded' }, body: `name=${data.name}&group=${data.group}` }) const responseData = await response.json() if(response.status !== 200) { console.log(responseData) } else { router.push('/tabs/things/lamps') } }, async getThing(context, params) { const response = await fetch(server + `/things/${params.id}`, { method: 'GET', headers: { 'Authorization': `Bearer ${context.rootState.auth.token}` } }) const responseData = await response.json() if(response.status !== 200) { console.log(responseData) } else { context.commit('setThing', responseData) } }, async updateLamp(context, params) { const response = await fetch(server + `/things/${params.id}/lamp`, { method: 'PUT', headers: { 'Authorization': `Bearer ${context.rootState.auth.token}`, 'Content-Type': 'application/x-www-form-urlencoded' }, body: `lamp=${params.lamp}` }) const responseData = await response.json() if(response.status !== 200) { console.log(responseData) } else { context.commit('updateLamp', params.lamp) } }, async updateThing(context, params) { const response = await fetch(server + `/things/${params.id}`, { method: 'PUT', headers: { 'Authorization': `Bearer ${context.rootState.auth.token}`, 'Content-Type': 'application/x-www-form-urlencoded' }, body: `name=${params.name}&group=${params.group}` }) const responseData = await response.json() if(response.status !== 200) { console.log(responseData) } else { context.commit('updateThing', { name: params.name, group: params.group }) router.push('/tabs/things/lamps') } }, async deleteThing(context, id) { console.log(id) const response = await fetch(server + `/things/${id.id}`, { method: 'DELETE', headers: { 'Authorization': `Bearer ${context.rootState.auth.token}`, 'Content-Type': 'application/x-www-form-urlencoded' } }) const responseData = await response.json() if(response.status !== 200) { console.log(responseData) } else { context.commit('deleteThing', id) } } }<file_sep>/src/router/index.js import { createRouter, createWebHistory } from '@ionic/vue-router'; import Tabs from '../views/Tabs.vue' import store from '../store/index.js' const routes = [ { path: '/', redirect: '/tabs/start' }, { path: '/tabs/', component: Tabs, children: [ { path: '', redirect: '/tabs/start' }, { path: 'start', component: () => import('@/views/Start.vue') }, { path: '/tabs/things', component: () => import('@/views/things/Things.vue'), meta: { auth: true }, children: [ { path: '/tabs/things/add', component: () => import('@/views/things/AddThing.vue') }, { path: '/tabs/things/lamps', component: () => import('@/views/things/LampsList.vue') }, { path: '/tabs/things/lamps/:id', component: () => import('@/views/things/LampDetails.vue') }, { path: '/tabs/things/lamps/:id/edit', component: () => import('@/views/things/EditThing.vue') } ] }, { path: '/login', component: () => import('@/views/auth/LoginPage.vue'), meta: { notAuth: true } }, { path: 'user', component: () => import('@/views/User.vue') } ] } ] const router = createRouter({ history: createWebHistory(process.env.BASE_URL), routes }) router.beforeEach(function(to, _, next) { if(to.meta.auth && !store.state.auth.token) { next('/login') } else if (to.meta.notAuth && store.state.auth.token) { next('/things') } else { next(); } }) export default router <file_sep>/src/store/modules/auth/actions.js import router from "../../../router" const server = 'http://192.168.0.102:3000' export default { async login(context, data) { const user = { email: data.email, password: data.password } const response = await fetch(server + '/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(user) }) const responseData = await response.json() if(response.status !== 200) { context.commit('setMessage', { message: responseData.message, type: 'danger' }) } else { context.commit('setToken', responseData.token) router.push('/tabs/things') } }, logout(context) { context.commit('setToken', null) router.push('/login') } }<file_sep>/src/store/modules/things/index.js import actions from "./actions"; import getters from "./getters"; import mutations from "./mutations"; export default { namespaced: true, state() { return { things: [], id: null, name: '', group: '', lamp: 0, temperature: null, humidity: null } }, actions, getters, mutations }
8aec51067f691a770e1bba26b6fab51344ac078d
[ "JavaScript" ]
6
JavaScript
dawid-danielewicz/mobile-app
9f322277643920332c1d1329bc5e30a59c1232cf
9c87d4e721ef8d8edd6d356746138e9e4d580100
refs/heads/master
<file_sep>#include <iostream> using namespace std; int main() { int x=0; while(x<10) x=x+1; cout<<"x is "; cout<< x << endl; return 0; }<file_sep>#ifndef FPEN_H #define FPEN_H #include "pen.h" class FountainPen : public Pen { public: ///////////////////////////////////////////////////////////// // //!TODO: what would happen if you used this version of // // // Constructor in the comment box below // // /////////////////////////////////////////////////////// // // // FountainPen(std::string pen_name = "FountainPen") // // // // : Pen(pen_name) {} // // // /////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////// FountainPen(std::string pen_name) : Pen(pen_name) {} FountainPen() : Pen(std::string("FountainPen")){} std::string drawLine(); std::string drawCircle(); }; #endif<file_sep>#include <iostream> class CitrusFruit{ protected: float ph; public: CitrusFruit(float ph) : ph(ph){} const char*getName(){ return "Citrus Fruit";} float getPh(){return ph;} }; class Lemon : public CitrusFruit{ public: Lemon(float ph) : CitrusFruit(ph){} const char * getName(){return "Lemno Fruit";} float getPh(){return ph * 2.0;} }; using namespace std; int main(){ Lemon lemon(2.0); //Thus us perfectly legal! CitrusFruit &rlemon = lemon; CitrusFruit *plemin = &lemon; cout << "lemon is a " << lemon.getName() << " and has a pH " << lemon.getpH() << endl; cout << "rlemon is a " << rlemon.getName(); <<" and has a pH" <<rlemon.getpH() << endl; cout << "plemon is a " <<plemon->getName() << "and has a pH" << plemon->getPh() << endl; }<file_sep>#include <iostream> using namespace std; int main() { while(1) { int N; cin>>N; if(N%5>0) { cout<<"-1\n"; continue; } if(N==-1) { break; } cout << N/5<< "\n"; } cout<< "Goodbye!\n"; return 0; } <file_sep>#include <iostream> using namespace std; int main() { const char*str = "hellow, World!"; cout<<str<< "\n"; return 0; }<file_sep>#include <iostream> using namespace std; int main() { for(int x=0; x<4; x=x+1) { for(int y=0; y<4; y=y+1) cout<<y<<endl; } return 0; } <file_sep>#ifndef RBPEN_H #define RBPEN_H #include "pen.h" class RollerBallPen : public Pen{ public: RollerBallPen(std::string pen_name) : Pen(pen_name) {} RollerBallPen() : Pen(std::string("RollerBallPen")){} std::string drawLine(); std::string drawCircle(); }; #endif<file_sep>#include <iostream> using namespace std; int main() { int x =6; int y =0; if(x>y) { cout<< "x is greater than y"<<endl; if(x==6) cout<<"x is equal to 6"<<endl; else cout<< "x is not equal to 6"<<endl; } else cout <<"x is not greater than y"<<endl; return 0; } <file_sep>#include "pen.h" // No need to make this ’ ’ since it is not ’overriden’ // by derived/child/sub classes. std::string Pen::getName(){ return pen_name; } std::string Pen::drawLine(){ return getName().append(" draws a line."); } std::string Pen::drawCircle(){ return getName().append(" draws a circle."); }<file_sep>#include <iostream> using namespace std; int main() { for(int x=0; x<10; x=x+1) cout<< x << endl; return 0; }<file_sep># OOPII-ASSGN1 OOP II Assignment One
6da9e3ff62b452dca3269b77a5de14968e59a948
[ "Markdown", "C++" ]
11
C++
Cloitabei/OOP-II
f428ec5f2a8cb85753e1732da6320b7d714afe86
0e1613116bae48112b089866c7f7a8953b4d7ebd
refs/heads/master
<file_sep>class Caesar(object): ''' THE KEY FOR ENCRYPTION AND DECRYPTION SHOULD BE BETWEEN 1 AND 25 (1 AND 25 INCLUDED)''' def __init__(self, key): self.letters = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] self.numbers = ['0','1','2','3','4','5','6','7','8','9'] self.key = key self.sentenceList = [] def __repr__(self): return f"Caesar encryption/decryption obejet with KEY : {self.key}" def encrypt(self, word): conc_list = [] for c in word: if c.upper() in self.letters: ind = self.letters.index(c.upper()) e_ind = ind + self.key if e_ind > 25: e_ind = self.key - (25 - ind) - 1 e_c = self.letters[e_ind] if c == c.upper(): conc_list.append(e_c) else: conc_list.append(e_c.lower()) elif c in self.numbers: if 9 < self.key < 19: self.key = self.key - 9 elif 19 <= self.key <= 25: self.key = self.key - 18 ind = self.numbers.index(c) e_ind = ind + self.key if e_ind > 9: e_ind = self.key - (9 - ind) - 1 e_c = self.numbers[e_ind] conc_list.append(e_c) else: e_c = c conc_list.append(e_c) return ''.join(conc_list) def decrypt(self, word): conc_list = [] for c in word: if c.upper() in self.letters: ind = self.letters.index(c.upper()) d_ind = ind - self.key if d_ind < 0: d_ind = (ind - self.key) + 26 d_c = self.letters[d_ind] if c == c.upper(): conc_list.append(d_c) else: conc_list.append(d_c.lower()) elif c in self.numbers: if 9 < self.key < 19: self.key = self.key - 9 elif 19 <= self.key <= 25: self.key = self.key - 18 ind = self.numbers.index(c) d_ind = ind - self.key if d_ind < 0: d_ind = (ind - self.key) + 10 d_c = self.numbers[d_ind] conc_list.append(d_c) else: d_c = c conc_list.append(d_c) return ''.join(conc_list) def encrypt_file(self, read_file, write_file): with open(read_file, 'r') as r_file: Lines = r_file.readlines() for line in Lines: formatted_line = line.split(' ') self.sentenceList.append(formatted_line) w_file = open(write_file, 'w') for sentence in self.sentenceList: for word in sentence: conc_list = [] for c in word: if c.upper() in self.letters: ind = self.letters.index(c.upper()) e_ind = ind + self.key if e_ind > 25: e_ind = self.key - (25 - ind) - 1 e_c = self.letters[e_ind] if c == c.upper(): conc_list.append(e_c) else: conc_list.append(e_c.lower()) elif c in self.numbers: if 9 < self.key < 19: self.key = self.key - 9 elif 19 <= self.key <= 25: self.key = self.key - 18 ind = self.numbers.index(c) e_ind = ind + self.key if e_ind > 9: e_ind = self.key - (9 - ind) - 1 e_c = self.numbers[e_ind] conc_list.append(e_c) else: e_c = c conc_list.append(e_c) s = ''.join(conc_list) w_file.write(s) if sentence.index(word) != len(sentence)-1: w_file.write(" ") w_file.close() def decrypt_file(self, read_file, write_file): with open(read_file, 'r') as r_file: Lines = r_file.readlines() for line in Lines: formatted_line = line.split(' ') self.sentenceList.append(formatted_line) w_file = open(write_file, 'w') for sentence in self.sentenceList: for word in sentence: conc_list = [] for c in word: if c.upper() in self.letters: ind = self.letters.index(c.upper()) d_ind = ind - self.key if d_ind < 0: d_ind = (ind - self.key) + 26 d_c = self.letters[d_ind] if c == c.upper(): conc_list.append(d_c) else: conc_list.append(d_c.lower()) elif c in self.numbers: if 9 < self.key < 19: self.key = self.key - 9 elif 19 <= self.key <= 25: self.key = self.key - 18 ind = self.numbers.index(c) d_ind = ind - self.key if d_ind < 0: d_ind = (ind - self.key) + 10 d_c = self.numbers[d_ind] conc_list.append(d_c) else: d_c = c conc_list.append(d_c) s = ''.join(conc_list) w_file.write(s) if sentence.index(word) != len(sentence)-1: w_file.write(" ") w_file.close() <file_sep># CAESAR Encription and Decryption A very simple and basic use of the Caesar ciphering method to encrpt and decrypt phrases and files. How Caesar Encrpytion works is by providing a key known by both sides for encrption and decryption puroses. The key can be chosen by any number between **1 - 25** (including 1 and 25). ## How it works: Create a Caesar object and use the methods of the Caesar class to encrypt or decrypt. By adding an amount (determined by the key) of charcters ahead of the character. To decrypt is by doing away with the characters. ## Methods available: * encrypt(string) : Encrypts the string passed on to the method. * decrypt(string) : Decrypts the string passed on to the method. * encrypt_file(read_file, write_file) : Encrypts a file and saves the encrypted file in the working directory. The first argument is the file that needs to be encrypted and the second argument is the name of the new file that will be created with the encryption. * decrypt_file(read_file, write_file) : Decrypts a file and saves the decrypted file in the working directory. The first argument is the file that needs to be decrypted and the second argument is the name of the new file that will be created with the decryption. ## Usage: Example : c = Caesar(3) print(c.encrypt("hello world")) # returns 'khoor zruog' print(c.decrypt("khoor zruog")) # returns 'hello world' #### LIMITATIONS : Only encrypts alphabetic characters and numbers. Special characters are displayed as is. Licensed under [MIT License](LICENSE)
8f31763501386e7ff36e094eed45e87c9cede787
[ "Markdown", "Python" ]
2
Python
hannu-hell/Caesar-Encryption
2e55d9d5ddea36d7da8614aff823253260f07ea5
77bf405a4614668409b6beb717092e2afbfee487
refs/heads/master
<file_sep>class User < ActiveRecord::Base has_many :transactions before_save { self.email = email.downcase } before_create :create_remember_token validates :name, presence: true, length: { maximum: 55 } VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false } has_secure_password #validates :password, presence: true, length: { minimum: 6 }, on: :create #validates :password_confirmation, presence: true, on: :create class LevelType GENERAL = 0 ADMINISTRATOR = 1 NAMES = { GENERAL => "General", ADMINISTRATOR => "Administrator" } ALL = [GENERAL, ADMINISTRATOR] def self.for_select ALL.map{|t|[NAMES[t], t]} end end def User.new_remember_token SecureRandom.urlsafe_base64 end def User.digest(token) Digest::SHA1.hexdigest(token.to_s) end private def create_remember_token # Create the token self.remember_token = User.digest(User.new_remember_token) end end <file_sep>class CompaniesController < ApplicationController require 'csv' require 'open-uri' before_action :set_company, only: [:show, :edit, :update, :destroy] def index @companies = Company.order("name,ticker").all end def show #connection = Net::HTTP.new(url) #response = "" #connection.start do |http| #req = Net::HTTP::Get.new(stock+flags) #response = http.request(req) #end #response.body.gsub!(/\0/, '') if response #@new_price = IO.binread(response.body) if response tick = @company.ticker tick += ".L" if @company.bourse.eql?("LSE") @new_price = read_stock(tick) @company.update_details(@new_price) end def read_stock(ticker) return "" if ticker.blank? url = "http://finance.yahoo.com/d/quotes.csv?s=" #stock = "TSCO.L" #flags = "&f=sn" flags = "&f=l1d1t1c" data = [] begin open(url+ticker+flags) do |f| data = CSV.parse f end rescue IOError => e # Silently catch the exception ... end return data end # GET /company/new def new @company = Company.new end # GET /company/1/edit def edit end # POST /company # POST /company.json def create @company = Company.new(company_params) respond_to do |format| if @company.save format.html { redirect_to @company, notice: 'Company was successfully created.' } format.json { render action: 'show', status: :created, location: @company } else format.html { render action: 'new' } format.json { render json: @company.errors, status: :unprocessable_entity } end end end # PATCH/PUT /company/1 # PATCH/PUT /company/1.json def update respond_to do |format| if @company.update(company_params) format.html { redirect_to @company, notice: 'Company was successfully updated.' } format.json { head :no_content } else format.html { render action: 'edit' } format.json { render json: @company.errors, status: :unprocessable_entity } end end end # DELETE /company/1 # DELETE /company/1.json def destroy @company.destroy respond_to do |format| format.html { redirect_to company_url } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_company @company = Company.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def company_params params.require(:company).permit(:name, :ticker, :description, :reference, :currency, :country, :bourse, :sector, :year_inc, :mkt_sector, :mkt_segment, :www_address, :isin, :share_type, :address, :logo) end end <file_sep>class Holding < ActiveRecord::Base has_many :transactions belongs_to :company #, :order => "name DESC" ## Doesn't work! belongs_to :portfolio #has_one :last_trans, :class_name => "Transaction", :order => "trans_date DESC", :limit => 1 # This don't work require 'action_view' include ActionView::Helpers::DateHelper # to use distance_of_time_in_words def calc_book_val() val_in = 0.00 val_exp = 0.00 self.transactions.order(:trans_date).each do |t| #print t.total_cost.to_s + " cost\n" val_exp += t.expenses if t.trans_type.eql?(Transaction::TransTypes::SELL) val_in += t.consideration if !t.consideration.blank? elsif t.trans_type.eql?(Transaction::TransTypes::DIVIDEND) #if t.currency.eql?(Transaction::TransCurrency::GBP) # val_in += t.div_gross.blank? ? t.div_net_total : t.div_gross #else val_in += t.div_net_total.to_f + t.expenses #end else val_exp += t.consideration if !t.consideration.blank? end #print val_in.to_s + "\n" #print val_exp.to_s + "\n" # eventually just return "val" end book_val = val_in - val_exp puts "Checking if closed\n" if !self.closed? puts "it's not closed!\n'" if self.last_trans cur_val = self.company.current_price * self.last_trans.quantity cur_val = (cur_val / 100) if self..company.currency.eql?(Company::CompanyCurrency::GBP) book_val += cur_val puts "got book_val" end end #self.book_value = val self.update(:income => val_in, :expense => val_exp, :book_value => book_val) end def calc_mkt_val() # Add this in when we have a "market_value" field in the holding # - if holding.last_trans # - cur_val = holding.company.current_price * holding.last_trans.quantity # - if holding.company.currency.eql?(Company::CompanyCurrency::GBP) # - cur_val = cur_val / 100 # - currency = "&pound;" # - else # - currency = "$" # = currency.html_safe # = format("%.2f", cur_val) end def held() h = "" if opened_at if closed_at && closed_at > opened_at h = distance_of_time_in_words(closed_at, opened_at) else h = distance_of_time_in_words_to_now(opened_at) end end return h end def closed?() c = false if opened_at if closed_at && closed_at > opened_at c = true end end return c end def last_trans() self.transactions.order(trans_date: :desc).first end end <file_sep>class TransactionsController < ApplicationController before_action :set_transaction, only: [:show, :edit, :update, :destroy] # GET /transactions # GET /transactions.json def index @transactions = Transaction.order('company_id,trans_date').all end # GET /transactions/1 # GET /transactions/1.json def show end # GET /transactions/new def new @transaction = Transaction.new @transaction.user = @current_user end # GET /transactions/1/edit def edit end # POST /transactions # POST /transactions.json def create @transaction = Transaction.new(transaction_params) respond_to do |format| if @transaction.save @transaction.holding.calc_book_val() if @transaction.holding format.html { redirect_to @transaction, notice: 'Transaction was successfully created.' } format.json { render action: 'show', status: :created, location: @transaction } else format.html { render action: 'new' } format.json { render json: @transaction.errors, status: :unprocessable_entity } end end end # PATCH/PUT /transactions/1 # PATCH/PUT /transactions/1.json def update respond_to do |format| if @transaction.update(transaction_params) @transaction.holding.calc_book_val() if @transaction.holding format.html { redirect_to @transaction, notice: 'Transaction was successfully updated.' } format.json { head :no_content } else format.html { render action: 'edit' } format.json { render json: @transaction.errors, status: :unprocessable_entity } end end end # DELETE /transactions/1 # DELETE /transactions/1.json def destroy @transaction.destroy respond_to do |format| format.html { redirect_to transactions_url } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_transaction @transaction = Transaction.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def transaction_params params.require(:transaction).permit(:trans_type, :trans_date, :company_id, :quantity, :price, :consideration, :commission, :stamp_duty, :PTM_levy, :payable, :cost_percent, :bargin_ref, :avg_cost, :buy_limit, :currency, :x_rate, :ex_div_date, :payment_date, :issue_date, :div_price, :div_net_total, :person, :user_id, :holding_id, :div_tax_rate, :div_tax_credit, :div_gross) end end <file_sep>class UpdateHoldingsFields < ActiveRecord::Migration def change add_column :holdings, :name, :string add_column :holdings, :description, :string add_column :holdings, :expense, :decimal, :precision => 10, :scale => 4 add_column :holdings, :income, :decimal, :precision => 10, :scale => 4 add_column :holdings, :user_id, :integer end end <file_sep>class Transaction < ActiveRecord::Base belongs_to :company belongs_to :holding belongs_to :user class TransTypes BUY = "buy" SELL = "sell" DIVIDEND = "dividend" NAMES = { BUY => "Buy", SELL => "Sell", DIVIDEND => "Dividend" } ALL = [BUY, SELL, DIVIDEND] def self.for_select ALL.map{|t|[NAMES[t],t]} end end class TransCurrency GBP = "gbp" USD = "usd" NAMES = { GBP => "£ GB", USD => "$ US" } ALL = [GBP, USD] def self.for_select ALL.map{|t|[NAMES[t],t]} end end def expenses exp = 0.00 if trans_type.eql?(TransTypes::BUY) || trans_type.eql?(TransTypes::SELL) exp += commission.to_f if !commission.blank? exp += stamp_duty.to_f if !stamp_duty.blank? exp += self.PTM_levy.to_f if !self.PTM_levy.blank? #transaction.commission + transaction.stamp_duty + transaction.PTM_levy else # Can safely(?) trust div_gross and div_net_total for UK stocks #if currency.eql?(TransCurrency::GBP) # exp += div_gross.to_f - div_net_total.to_f if div_gross.to_f > 0.0 #else exp += div_tax_credit.to_f #end end exp end def total_cost # This is the "net cash flow" so "money in" or "money out" of my purse. # It will be "money in" if it's a dividend or sell -> so take expenses off tc = 0.00 tc += consideration if !consideration.blank? && !trans_type.eql?(TransTypes::DIVIDEND) tc += div_gross.to_f > 0.0 ? div_gross : div_net_total if trans_type.eql?(TransTypes::DIVIDEND) if trans_type.eql?(TransTypes::BUY) tc += expenses else tc -= expenses end tc end def avg_cost if !total_cost.blank? && !quantity.blank? && quantity != 0 total_cost * 100 / quantity else 0.00 end end def percent_cost pct = 0.0 if !expenses.blank? if trans_type.eql?(TransTypes::BUY) if !total_cost.blank? && total_cost != 0 pct = expenses * 100 / total_cost end elsif trans_type.eql?(TransTypes::SELL) if !consideration.blank? && consideration != 0 pct = expenses * 100 / consideration end else pct = div_gross.to_f > 0.0 ? (expenses * 100 / div_gross) : 0.0 end end pct end def currency_format(val) if not val.blank? if self.currency.eql?(TransCurrency::USD) return format("$ %.2f", val) else return format("%.2f p", val) end else return "" end end end <file_sep>class CreateHoldings < ActiveRecord::Migration def change create_table :holdings do |t| t.integer :company_id t.decimal :book_value, :precision => 10, :scale => 4 t.date :opened_at t.date :closed_at t.timestamps end remove_column :transactions, :payable remove_column :transactions, :cost_percent remove_column :transactions, :avg_cost add_column :transactions, :holding_id, :integer end end <file_sep>class CreateCompanies < ActiveRecord::Migration def change create_table :companies do |t| t.string :name t.string :ticker t.text :description t.text :reference t.string :currency t.string :country t.string :bourse t.string :sector t.date :year_inc t.timestamps end end end <file_sep>class CreatePortfolios < ActiveRecord::Migration def change create_table :portfolios do |t| t.string :name t.text :description t.integer :user_id t.decimal :book_cost, :precision => 10, :scale => 4 t.decimal :mkt_value, :precision => 10, :scale => 4 t.timestamps end add_column :holdings, :portfolio_id, :integer add_column :transactions, :target_price, :decimal, :precision => 10, :scale => 4, :default => 0.0 add_column :transactions, :stop_price, :decimal, :precision => 10, :scale => 4, :default => 0.0 add_column :companies, :current_price, :decimal, :precision => 10, :scale => 4, :default => 0.0 add_column :companies, :price_at_str, :string add_column :companies, :price_updated_at, :datetime add_column :companies, :high52wk, :decimal, :precision => 10, :scale => 4, :default => 0.0 add_column :companies, :low52wk, :decimal, :precision => 10, :scale => 4, :default => 0.0 add_column :companies, :open, :decimal, :precision => 10, :scale => 4, :default => 0.0 add_column :companies, :range, :decimal, :precision => 10, :scale => 4, :default => 0.0 add_column :companies, :mkt_capitalisation, :string add_column :companies, :price_earnings, :decimal, :precision => 10, :scale => 4, :default => 0.0 add_column :companies, :div_yield_pc, :decimal, :precision => 10, :scale => 4, :default => 0.0 add_column :companies, :earnings_per_share, :decimal, :precision => 10, :scale => 4, :default => 0.0 add_column :companies, :beta, :decimal, :precision => 10, :scale => 4, :default => 0.0 add_column :companies, :industry, :string end end <file_sep>class HoldingsController < ApplicationController before_action :set_holding, only: [:show, :edit, :update, :destroy] def index @holdings = Holding.order('opened_at,company_id').all end # GET /holdings/1 # GET /holdings/1.json def show end # GET /holdings/new def new @holding = Holding.new #@holding.user = @current_user end # GET /holdings/1/edit def edit end # POST /holdings # POST /holdings.json def create @holding = Holding.new(holding_params) respond_to do |format| if @holding.save format.html { redirect_to @holding, notice: 'holding was successfully created.' } format.json { render action: 'show', status: :created, location: @holding } else format.html { render action: 'new' } format.json { render json: @holding.errors, status: :unprocessable_entity } end end end # PATCH/PUT /holdings/1 # PATCH/PUT /holdings/1.json def update respond_to do |format| if @holding.update(holding_params) @holding.calc_book_val @holding.portfolio.calc_book_val if @holding.portfolio format.html { redirect_to @holding, notice: 'holding was successfully updated.' } format.json { head :no_content } else format.html { render action: 'edit' } format.json { render json: @holding.errors, status: :unprocessable_entity } end end end # DELETE /holdings/1 # DELETE /holdings/1.json def destroy @holding.destroy respond_to do |format| format.html { redirect_to holdings_url } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_holding @holding = Holding.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def holding_params params.require(:holding).permit(:company_id, :book_value, :opened_at, :closed_at, :name, :description, :expense, :income, :user_id, :portfolio_id) end end <file_sep>class ModifyTransactionDividend < ActiveRecord::Migration def change add_column :transactions, :div_tax_rate, :decimal, :precision => 10, :scale => 4, :default => 0.0 add_column :transactions, :div_tax_credit, :decimal, :precision => 10, :scale => 4, :default => 0.0 add_column :transactions, :div_gross, :decimal, :precision => 10, :scale => 4, :default => 0.0 add_column :companies, :address, :text add_column :companies, :logo, :string end end <file_sep>class Company < ActiveRecord::Base has_many :transactions has_many :holdings class Bourse LSE = "LSE" NYSE = "NYSE" NASDAQ = "NASDAQ" NAMES = { LSE => "London Stock Exchange", NYSE => "New York Stock Exchange", NASDAQ => "NASDAQ" # National Association of Securities Dealers Automated Quotations } ALL = [LSE, NYSE, NASDAQ] def self.for_select ALL.map{|t|[NAMES[t],t]} end end class Country UK = "United Kingdom" US = "United States" NAMES = { UK => "United Kingdom", US => "United States of America" } ALL = [UK, US] def self.for_select ALL.map{|t|[NAMES[t],t]} end end class CompanyCurrency GBP = "gbp" USD = "usd" NAMES = { GBP => "£ GB", USD => "$ US" } ALL = [GBP, USD] def self.for_select ALL.map{|t|[NAMES[t],t]} end end class Sector ENERGY = "energy" MATERIAL = "materials" INDUSTRIAL = "industrials" CYCLICAL = "cyclical" NONCYCLICAL = "non-cyclical" FINANCIAL = "financials" HEALTH = "healthcare" TECHNOLOGY = "technology" TELECOM = "telecomms" UTILITY = "utilities" NAMES = { ENERGY => "Energy", MATERIAL => "Basic Materials", INDUSTRIAL => "Industrials", CYCLICAL => "Cyclical Consumer Goods & Services", NONCYCLICAL => "Non-Cyclical Consumer Goods & Services", FINANCIAL => "Financials", HEALTH => "Healthcare", TECHNOLOGY => "Technology", TELECOM => "Telecommunications Services", UTILITY => "Utilities", } ALL = [ENERGY, MATERIAL, INDUSTRIAL, CYCLICAL, NONCYCLICAL, FINANCIAL, HEALTH, TECHNOLOGY, TELECOM, UTILITY] def self.for_select ALL.map{|t|[NAMES[t],t]} end end def self.for_select Company.order("companies.name,companies.ticker").map{|c|[[c.ticker,c.name].join(" "),c.id]} end def currency_format(val) if not val.blank? if self.currency.eql?(CompanyCurrency::USD) return format("$ %.2f", val) else return format("%.2f p", val) end else return "" end end def update_details(details) # Details - currently csv format, will be JSON price_a = details.join(',') # debug(price_a) price_a = price_a.split(',') self.current_price = price_a[0] the_date = price_a[1].split('/') self.price_at_str = price_a[2].to_time.strftime('%H:%M ') + (the_date[2] + "-" + the_date[0] + "-" + the_date[1]).to_date.strftime('%d-%b-%Y') the_time = Time.new self.price_updated_at = the_time self.save end end <file_sep>== README Use HighCharts(.com) for graphics - free for personal use (highstock too) cf http://gionkunz.github.io/chartist-js/ # Web Services: Webservicex.net and Restfulwebservices.net http://download.finance.yahoo.com/d/quotes.csv?s=ABF.L,ADN.L,APF.L,AUE.L,BA.L,BARC.L,BLNX.L,BLT.L,BND,BP.L,BRBY.L,BRK-B,CCH.L,CCL.L,CEO.L,DMGT.L,DNLM.L,EBAY,FGP.L,GFS.L,GKN.L,KO,LLOY.L,LTC.L,MKL,MONI.L,NANO.L,NG.L,OCG.L,OMG.L,PFC.L,PHTM.L,PZC.L,QED.L,RDSB.L,RIO.L,RR.L,SDL.L,SMP,TED.L,TEP.L,VEU,VOD.L,VOO,WCW.L,&f=sl1d1t1c1ohgv&e=.csv http://ws.cdyne.com/delayedstockquote/delayedstockquote.asmx http://www.webservicex.net/WS/WSDetails.aspx?CATID=2&WSID=9 YQL console (Yahoo Query Language) http://wern-ancheta.com/blog/2015/04/05/getting-started-with-the-yahoo-finance-api/ https://developer.yahoo.com/yql/guide/running-chapt.html # Page scrape Get the Sector Summary from the Google Finance page (https://www.google.com/finance) * Database creation Company - name - ticker - description - reference (recommended by sources, highs/lows, etc) - currency (default based on Country) - country (default based on bourse) - bourse - sector (industry) - year incorporated? (change to number - not date - DONE) - market sector - market segment - www address - isin - share type - beta (or just in snapshot?) - Logo (image) - Address - current price - price at (string - got from Yahoo) - price updated at - datetime - 52wk high - 52wk low - open - range (today?) - market capitalisation - P/E - Div/yield - EPS (+ currency unit) - Beta - Industry **** TODO: Handle the following in the views & controller - RiskGrade - Can I get it? - %change (today) - value change (today) Snapshots - needed? - Company - price - spread? - market cap - beta - market rate? - .. ratios - dividend % (yield) - dividend cover - borrowings (debt) - growth (earnings & revenue & cash flow) - price to earnings (P/E) - outlook (market, bouyant, etc) Transactions - trans_type (purchase, sell, dividend, director purchase, cash in/out) - date - Company - (Person? - eg director deals) - quantity - share price - net consideration - commission - stamp duty - PTM levy -# net payable -# (cost %) - bargin ref -# avg cost - buy limit - currency - exchange rate - ex-div date - payment date - issue date - dividend price - net dividend total - user - Holding (ID) -> // Have this on the edit page rather than the create page, then can filter Holding by Company (or use Ajax on entry form!) - div tax rate - div tax credit - div gross *** TODO: Handle the following in the views & controller - Target - Stop People (Directors etc) - name_first - name_last - image - contact (email, address, phone) - nationality - description / background - type (person, brokerage) - day of birth - month of birth - year of birth - age - date age entered (i.e. age at this date was x -> could work out year of birth[ish]) Positions - Company - Person - position1 (President) - position2 (Global Manufacturing & Supply) - date start - date end - salary - shares held (traded) - maybe in transation table Tags - name - type (eg. growth company, dividend income company, etc) Links (Needed?) - Tags/Company - Company/tag - Company/portfolio or more like Transaction/portfolio or more like Holding/Portfolio - Company/person - Person/position (company included in position) Holdings - Name - Description - Company - Transactions (point here) - sum open trans - sum closed trans - Book value (calculated from company transactions) - closing date (?) - Portfolio ID *** Add - Market value Portfolios - Name - Description (method, goals, etc. eg. beat the FTSE100) - user - Book Cost - Market Value - (has many) Holdings -> calculated Profit(/Loss) -> calculated % -! transactions (?) **** Need another table to link a "watch" type portfolio to just companies *** Also need to be able to have a portfolio of portfolios! Watches - Portfolio - Company - Alert High - Alert Low - Description (explain context, goals, etc) Notes - Name - Description - Date - company - holding - transaction - portfolio News Items - Date - Company - source - related source (broker/people link) - news Historical Prices (from Yahoo!) - company - date - open - high - low - close - volume - adj_close Broker Views - broker (could be a type of "People") - company - recommendation - target - price at recommendation date - recommendation date **** Things I need... - The Portfolios don't seem to be adding up the Holdings book values properly - view by timeline as to when stock was bought, high/low whilst I've had it and percentages over time - be able to see capital gains AND dividend income - sort transactions index by company (not just it's 'id') # Oct 2015 Need to: - Need to set currency as part of the company model - related to country (& bourse) - Default country, bourse, currency based on one or the other of these things - When creating a transaction, can default some stuff based on the stock selected # Nov 2015 - Put the stock value etc from controller into the company - could YHOO cope with multiple? maybe there's a batch way to do it? - In holdings add the stock value currently (what if scenario for sold ones) - i.e. current price x number of shares held (need way of knowing that) - Want to add £5 expenses to expenses and not take them off incomes until required - Make holdings expandable - i.e. hide the details of transactions 'til clicked on # Dec 15 - Get easy way for company price - store it somewhere and update when X-time old and required - Get price history - store similarly - Show price history (graphs, etc) - jQuery UI for date selectors - Instant search for companies - use webservice too! - When reviewing a holding, it would be nice to see the high & low for the period held - Need to have a watchlist with alerts for points reached (high/low) - Need somewhere to hold max buy/sell rate (& keep history) - and way of working it out (on my own if necessary) - May need to build in ForEx somewhere along the way? - Need way of showing the FTSE and other indices - Will need to add pagination on Transactions (perhaps Companies and Holdings too). Portfolios shouldn't grow beyond a "page" worth. # Jan 16 - Need a portfolio of portfolios (?) - Need to have a portfolio with just companies (not holdings) -> Watchlist entity - Wachlist entry needs: - date added to watchlist - Price when added - buy point alert (low value) - give up point? alert (high value) - On a Portfolio - Need bought at price (aggregate each purchase to a total?) - Sort out Market values with companies, holdings, etc # Sep 16 - When the US market opens, the Yahoo results have "N/A" for the change and % - need to cope with this "--- 328.30,9/6/2016,2:16pm,-3.00 - -0.91%" becomes "--- 796.87,9/2/2016,4:00pm,N/A" Done: Remove calculated fields like: - Payable - Cost Percent - Avg Cost Add "Name" to holding, maybe "Description" too Add "User" to holding Add select_for for holding Add total_expense to holding Add total_income (maybe get rid of/or automatically update book_val) to holding Add all the framework for holding (CRUD) - Might need more details in transaction for dividends (income/expense broken down for holdings) - need Tax Rate (e.g. 10%) - need Tax Credit - need Gross Dividend (= Net Dividend Paid + Tax Credit) -> calculated value - need to do list of transactions as an include (for index and for holdings) - use options as to what to show (don't need the company as a sub-set of the holding) <file_sep>class Portfolio < ActiveRecord::Base has_many :holdings def calc_book_val() # TODO: Need to get the market value into the Holding and extract the sum here val_book = 0.00 val_mkt = 0.00 #val_exp = 0.00 #val_in = 0.00 self.holdings.each do |h| val_book += h.book_value #val_in += h.income #val_exp += h.expense # This will all be done in the Holding in the future... #if h.last_trans.exists? cur_val = h.company.current_price * h.last_trans.quantity cur_val = cur_val / 100 if h.company.currency.eql?(Company::CompanyCurrency::GBP) # Need to get current exchange rate (hard-coded here Feb-16) cur_val = cur_val * 0.69 if h.company.currency.eql?(Company::CompanyCurrency::USD) val_mkt += cur_val #end end self.update(:book_cost => val_book, :mkt_value => val_mkt) end end <file_sep>class CreateTransactions < ActiveRecord::Migration def change create_table :transactions do |t| t.string :trans_type t.date :trans_date t.integer :company_id t.integer :quantity t.decimal :price, :precision => 10, :scale => 4 t.decimal :consideration, :precision => 10, :scale => 4 t.decimal :commission, :precision => 10, :scale => 4 t.decimal :stamp_duty, :precision => 10, :scale => 4 t.decimal :PTM_levy, :precision => 10, :scale => 4 t.decimal :payable, :precision => 10, :scale => 4 t.decimal :cost_percent, :precision => 10, :scale => 6 t.string :bargin_ref t.decimal :avg_cost, :precision => 10, :scale => 4 t.decimal :buy_limit, :precision => 10, :scale => 4 t.string :currency t.decimal :x_rate, :precision => 10, :scale => 6 t.date :ex_div_date t.date :payment_date t.date :issue_date t.decimal :div_price, :precision => 10, :scale => 4 t.decimal :div_net_total,:precision => 10, :scale => 4 t.text :person t.integer :user_id t.timestamps end end end <file_sep>class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception include SessionsHelper before_filter :check_logged_in def check_logged_in unless signed_in? || params[:controller]=="sessions" store_location redirect_to signin_url, notice: "Please sign in." end #puts "Signed in = "+signed_in?.to_s #puts "Sessions controller = "+(params[:controller]=="sessions").to_s #puts "Action = new? "+(params[:action]=="new").to_s #puts "Action = create? "+(params[:action]=="create").to_s end end <file_sep>class AddFieldsToCompany < ActiveRecord::Migration def change change_column :companies, :year_inc, :integer add_column :companies, :mkt_sector, :string add_column :companies, :mkt_segment, :string add_column :companies, :www_address, :string add_column :companies, :isin, :string add_column :companies, :share_type, :string end end
11b23884c168616ad82ccb47626d8e2aa6a1b62c
[ "RDoc", "Ruby" ]
17
Ruby
TheTrace/stockport
5412cbe13f1d12209570649cdfd1faefc33b2f63
24a307cb1b205146a9507632376599b08d0f7dd6
refs/heads/master
<repo_name>rojas-diego/epitech-42sh<file_sep>/src/expr/control.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** expr_control */ #include <stdlib.h> #include <string.h> #include "proto/grammar.h" #include "proto/expr.h" int expr_control_sub_test( struct grammar_s *this, struct expr_control_s *exp, unsigned int save_index ) { exp->if_control = expr_if_control_w(this); if (!exp->if_control) this->index = save_index; else return (1); exp->while_control = expr_while_control_w(this); if (!exp->while_control) this->index = save_index; else return (1); exp->foreach_control = expr_foreach_control_w(this); if (!exp->foreach_control) this->index = save_index; else return (1); return (0); } /* ** @DESCRIPTION ** Rule for control expression. */ static struct expr_control_s *expr_control(struct grammar_s *this) { struct expr_control_s *exp = malloc(sizeof(struct expr_control_s)); unsigned int save_index = this->index; if (!exp) exit(84); memset(exp, 0, sizeof(struct expr_control_s)); exp->if_inline_control = expr_if_inline_control_w(this); if (!exp->if_inline_control) this->index = save_index; else return (exp); if (expr_control_sub_test(this, exp, save_index)) return (exp); exp->repeat_control = expr_repeat_control_w(this); if (!exp->repeat_control) return (expr_free(exp)); return (exp); } struct expr_control_s *expr_control_w(struct grammar_s *this) { struct expr_control_s *exp; expr_print(this, "Control"); exp = expr_control(this); expr_print_debug(this, exp); return (exp); } <file_sep>/src/exec/builtins.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** exec builtins */ #include <unistd.h> #include "types/shell.h" #include "types/builtins.h" #include "proto/exec/builtins.h" #include "hasher/get_data.h" int job_handle_if_builtin( struct sh *shell, __attribute__((unused)) struct job_s *job, struct process_s *process ) { builtin_handler *func = (builtin_handler *) hasher_get_data( shell->builtin, process->argv[0] ); int fd; if (func && *func) { fd = dup(1); dup2(job->io[IO_OUT], 1); shell->last_status = (*func)( shell, (const char * const *) process->argv ); dup2(fd, 1); return (true); } return (false); } <file_sep>/src/prompt/history/replace.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** replace */ #include "gnu_source.h" #include <string.h> #include "parser_toolbox/consts.h" #include "parser_toolbox/cmp_string.h" #include "parser_toolbox/sub_string.h" #include "proto/prompt/history.h" static size_t word_len(const char *str) { size_t i = 0; for (; str[i] && (!strchr(PTB_WHITESPACES, str[i]) || str[i] != '!'); ++i) {} return (i); } static _Bool history_can_replace(struct history_s *history, char **str, int i) { struct dnode_s *node = NULL; size_t len = 0; char *substring = NULL; if ((*str)[i] == '!' && (!i || strchr(PTB_WHITESPACES, (*str)[i - 1]))) { if ((*str)[i + 1] == '=') return (0); substring = ptb_sub_string(*str, i + 1, i + word_len(&(*str)[i + 1])); if (!substring) return (0); len = strlen(substring) + 1 + i; node = dnode_find_after(history->list, substring, &ptb_ncmp_string); if (!node) { dprintf(2, "!%s: Event not found.\n", substring ? substring : ""); return (1); } (*str)[i] = 0; asprintf(str, "%s%s%s", *str, (char *) node->data, &(*str)[len]); } return (0); } /* ** @Description ** this function replace all '!' by the matching previous command */ _Bool history_replace(struct history_s *history, char **str) { for (size_t i = 0; (*str)[i]; ++i) { if (history_can_replace(history, str, i)) { return (1); } } return (0); } <file_sep>/lib/hasher/include/hasher/get.h /* ** EPITECH PROJECT, 2020 ** hasher ** File description: ** hasher get */ #ifndef HASHER_GET_H_ #define HASHER_GET_H_ #include "hasher/type.h" struct hasher_s *hasher_get(struct hasher_s *hasher, const char *key); #endif /* !HASHER_GET_H_ */ <file_sep>/src/shell/builtin_handlers/bindkey.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** builtins */ #include <stdio.h> #include <string.h> #include <ctype.h> #include "hasher/type.h" #include "builtins.h" #include "constants/prompt/builtins/private_bindkey.h" #include "proto/shell/builtin_handlers.h" #include "types/builtins/bindkey.h" #include "proto/shell/bindkey.h" void builtin_bindkey_bind( __attribute__((unused)) struct sh *shell, __attribute__((unused)) const char * const *argv ); void builtin_bindkey_display_settings( struct sh *shell, __attribute__((unused)) const char * const *argv ); void builtin_bindkey_list( __attribute__((unused)) struct sh *shell, __attribute__((unused)) const char * const *argv ) { printf(BUILTIN_BINDKEY_EDITOR_COMMANDS_WITH_DESCRIPTIONS); } void builtin_bindkey_help( __attribute__((unused)) struct sh *shell, __attribute__((unused)) const char * const *argv ) { printf("%s%s", BUILTIN_BINDKEY_HELP, BUILTIN_BINDKEY_HELP_PART_2); } void builtin_bindkey_display_settings( struct sh *shell, __attribute__((unused)) const char * const *argv ) { int i; for (struct hasher_s *this = shell->bindkey; this; this = this->next) { printf("\""); for (i = 0; this->key[i]; i++) { if (isprint(this->key[i])) printf("%c", this->key[i]); } printf("\"%*s", 13 - i, ""); printf("-> %s\n", ((struct bindkey_s *) this->data)->name); } } void builtin_bindkey_bind( __attribute__((unused)) struct sh *shell, __attribute__((unused)) const char * const *argv ) { return; } int builtin_bindkey_handler(struct sh *shell, const char * const *argv) { if (!argv[1]) { builtin_bindkey_display_settings(shell, argv); return (0); } for (int i = 0; BINDKEY_FLAG[i].flag; i++) { if (!strcmp(BINDKEY_FLAG[i].flag, argv[1])) { BINDKEY_FLAG[i].function(shell, argv); return (0); } } if (!argv[2]) { builtin_bindkey_help(shell, argv); } else { builtin_bindkey_bind(shell, argv); } return (0); } <file_sep>/src/expr/destroy/command.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** expr_command */ /* free */ #include <stdlib.h> #include "proto/expr_destroy.h" /* ** @DESCRIPTION ** Rule for command expression. */ void expr_command_destroy(struct expr_command_s *this) { if (!this) { return; } expr_redirection_destroy(this->redirection); expr_command_destroy(this->command); free(this); } <file_sep>/lib/builtins/tests/echo.c /* ** EPITECH PROJECT, 2020 ** builtins ** File description: ** test builtin_echo */ /* getenv */ #include <stdlib.h> #include <criterion/criterion.h> #include <criterion/redirect.h> #include "builtin/echo.h" Test(builtin_echo, simple_echo) { const char *arg = "echo"; const char *arg2 = " more echo"; const char * const argv[] = {arg, arg2, NULL}; cr_redirect_stdout(); builtin_echo(argv); cr_assert_stdout_eq_str("echo more echo\n"); } Test(builtin_echo, echo_without_argument) { const char * const argv[] = {NULL}; cr_redirect_stdout(); builtin_echo(argv); cr_assert_stdout_eq_str("\n"); } <file_sep>/src/exec/rule/block.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** exec rule block */ #include "proto/exec/rule/debug.h" #include "proto/exec/rule/statement.h" #include "proto/exec/rule/block.h" int exec_rule_block( struct sh *shell, struct expr_block_s *rule ) { exec_rule_debug(shell, "block", true); for (; rule; rule = rule->block) { if (rule->statement) { exec_rule_statement(shell, rule->statement); exec_rule_debug(shell, "statement", false); } else { } } exec_rule_debug(shell, "block", false); return (0); } <file_sep>/src/prompt/prompt_shell.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** prompt_shell */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "parser_toolbox/consts.h" #include "parser_toolbox/whitelist.h" #include "proto/prompt/display.h" #include "proto/prompt/input/get_input.h" #include "proto/prompt/input/get_input_with_raw_mode.h" #include "proto/prompt.h" /* ** @DESCRIPTION ** This function fetches the input from the command line and stores it in ** the `struct sh`. */ static void prompt_fetch(struct sh *shell) { char *buffer = NULL; size_t length = 0; ssize_t response; if (!shell->stream) { shell->active = false; return; } response = getdelim(&buffer, &length, EOF, shell->stream); if (response <= 0 || ptb_whitelist(buffer, PTB_WHITESPACES)) { if (response < 0) { shell->active = false; } if (buffer) free(buffer); buffer = NULL; } shell->rawinput = buffer; } /* ** @DESCRIPTION ** This function both displays the shell prompt and fetches the ** input from the terminal. */ void prompt_shell(struct sh *shell) { if (shell->atty) { prompt_display(shell); get_input_with_raw_mode(shell); if (ptb_whitelist(shell->prompt.input, PTB_WHITESPACES)) { shell->rawinput = NULL; return; } shell->rawinput = strdup(shell->prompt.input); } else { prompt_fetch(shell); } } <file_sep>/lib/hasher/include/hasher/insert_data.h /* ** EPITECH PROJECT, 2020 ** hasher ** File description: ** hasher insert_data */ #ifndef HASHER_INSERT_DATA_H_ #define HASHER_INSERT_DATA_H_ #include "hasher/type.h" #include "hasher/enum.h" enum hasher_e hasher_insert_data( struct hasher_s **hasher, char *key, void *data ); enum hasher_e hasher_insert_data_ordered( struct hasher_s **hasher, char *key, void *data ); #endif /* !HASHER_INSERT_DATA_H_ */ <file_sep>/include/proto/exec/rule/wordlist.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** shell exec rule wordlist */ #ifndef SH_SHELL_EXEC_RULE_WORDLIST_H_ #define SH_SHELL_EXEC_RULE_WORDLIST_H_ #include "types/shell.h" #include "types/expr.h" int exec_rule_wordlist( struct sh *shell, struct expr_wordlist_s *rule ); #endif /* !SH_SHELL_EXEC_RULE_WORDLIST_H_ */ <file_sep>/lib/dnode/include/dnode/create.h /* ** EPITECH PROJECT, 2020 ** dnode ** File description: ** create */ #ifndef DNODE_CREATE_H_ #define DNODE_CREATE_H_ #include "dnode/type.h" struct dnode_s *dnode_create(void *data); #endif /* !DNODE_CREATE_H_ */ <file_sep>/lib/myerror/my_error.c /* ** EPITECH PROJECT, 2019 ** myerror ** File description: ** my_error */ #include "myerror.h" /* ** @DESCRIPTION ** Stores a program wide error variable to ensure processes ran errorlessly ** Makes use of the my_error_mode_t enum (ERR_WRITE, ERR_READ). ** @USAGE ** my_error(ERR_WRITE, 84); => Sets the error variable to 84. ** my_error(ERR_READ, 0); => Returns the value of the error variable. ** @RETURN_VALUE ** Returns an int. ** 'error' if ERR_READ is set. ** 0 if ERR_WRITE is set. */ int my_error(my_error_mode_t mode, int new_code) { static int error; if (!error) error = 0; if (mode == ERR_WRITE) error = new_code; else return error; return 0; } <file_sep>/src/input/parser/input_parse.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** input_parse */ #include <stdio.h> #include "myerror.h" /* Contains implicit includes for types */ #include "proto/input/parser.h" /* ** @DESCRIPTION ** This is a wrapper function for the tokenisation and the grammar parsing. */ int input_parse(struct sh *shell) { input_parse_tokens(shell); if (my_error(ERR_READ, 84)) { dprintf(2, "Error: Couldn't tokenise.\n"); shell->error = 1; my_error(ERR_WRITE, 0); return (1); } return (input_parse_grammar(shell)); } <file_sep>/src/exec/magic/env_var_replace.c /* ** EPITECH PROJECT, 2020 ** input_postprocessing ** File description: ** env_var_replace */ #include "gnu_source.h" /* setenv */ #include <stdlib.h> /* asprintf && dprintf */ #include <stdio.h> /* size_t */ #include <stddef.h> #include <string.h> #include "parser_toolbox/includes.h" #include "parser_toolbox/unquote.h" #include "builtin/get_user_home.h" #include "parser_toolbox/blacklist.h" #include "proto/exec/magic/parse.h" #include "types/shell.h" #include "hasher/get_data.h" #include "types/local_variables.h" static const char ENV_VAR_SEP[] = " \t\n\r\f\v\"'/"; static char *env_var_getenv(struct sh *shell, char *str) { char *temp = NULL; struct local_var_s *var = NULL; if (*str == '{') { ptb_unquote(str); } var = hasher_get_data(shell->local_var, str); if (!ptb_blacklist(str, "\\/=&'()[]|{}")) { return ((char *) -1); } if (var && var->type == STRING) { return (var->data.string); } if (var) { asprintf(&temp, "%d", var->data.nb); return (temp); } return (getenv(str)); } static size_t env_var_special_variable( struct sh *shell, char **env_var, char *str ) { size_t length = 0; *env_var = NULL; if (*str == '?') { asprintf(env_var, "%d", shell->last_status); for (; str[length] && !ptb_includes(str[length], ENV_VAR_SEP); ++length); return (length); } return (0); } static size_t env_var_replace_find_env( struct sh *shell, char **env_var, char *str ) { size_t length = env_var_special_variable(shell, env_var, str); char save = '\0'; str[-1] = '\0'; if (length) return (length); for (; str[length] && !ptb_includes(str[length], ENV_VAR_SEP); ++length); save = str[length]; str[length] = '\0'; *env_var = env_var_getenv(shell, str); if (*env_var == (char *) -1) { dprintf(2, "Illegal variable name.\n"); return (0); } if (*env_var == NULL) { dprintf(2, "%s: Undefined variable.\n", str); return (0); } str[length] = save; return (length); } int magic_env_var_replace(struct sh *shell, char **str) { char *save = *str; char *env_var = NULL; size_t var_name_length = 0; for (size_t i = 0; save[i] != '\0'; ++i) { if (save[i] != '$' || (i != 0 && save[i - 1] == '\\')) continue; var_name_length = env_var_replace_find_env(shell, &env_var, save + ++i); if (env_var == NULL || env_var == (char *) -1) return (1); i += var_name_length; if (asprintf(str, "%s%s%s", save, env_var, save + i) < 0) return (1); save = *str; } return (0); } <file_sep>/src/job/destroy.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** job */ #include <stdlib.h> #include "proto/job/destroy.h" void job_destroy(struct job_s *job) { struct process_s *process = job->first_process; struct process_s *hold = NULL; while (process) { hold = process; process = process->next; for (size_t i = 0; i < hold->argc; ++i) { free(hold->argv[i]); } free(hold->argv); free(hold); } free(job); } <file_sep>/include/proto/exec/rule/command/add_word.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** shell exec rule command add_word */ #ifndef SH_SHELL_EXEC_RULE_COMMAND_ADD_WORD_H_ #define SH_SHELL_EXEC_RULE_COMMAND_ADD_WORD_H_ #include "types/job.h" #include "types/token.h" int exec_rule_command_add_word( struct process_s *process, struct token_s *word, const char *input ); #endif /* !SH_SHELL_EXEC_RULE_COMMAND_ADD_WORD_H_ */ <file_sep>/src/exec/rule/command/init_redirection.c /* ** EPITECH PROJECT, 2020 ** execution ** File description: ** execution */ #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <fcntl.h> #include <string.h> #include <errno.h> #include "parser_toolbox/isdir.h" #include "proto/exec/rule/command/init_redirection.h" static const size_t NB_REDIRECT_ERROR = 3; static const struct { int err_nbr; const char *status; } REDIRECT_ERROR[] = { {ENOENT, "No such file or directory."}, {EACCES, "Permission denied."}, {EISDIR, "Is a directory."} }; static void exec_do_redirect_error_handling(const char *path) { for (size_t i = 0; i < NB_REDIRECT_ERROR; ++i) { if (errno == REDIRECT_ERROR[i].err_nbr) { dprintf(2, "%s: %s\n", path, REDIRECT_ERROR[i].status); break; } } } int exec_do_redirect_left(const char *path) { int fd = open(path, O_RDONLY); int piped_fd[2]; if (fd == -1 || pipe(piped_fd) == -1) { exec_do_redirect_error_handling(path); return (-1); } dup2(fd, piped_fd[0]); close(fd); close(piped_fd[1]); return (piped_fd[0]); } int exec_do_redirect_double_left(const char *word) { char *line = NULL; size_t len = 0; int fd[2]; ssize_t ret = 1; if (pipe(fd) == -1) return (-1); write(1, "? ", 2); for (ret = getline(&line, &len, stdin); line && ret > 0 && strcmp(line, word) != '\n'; ret = getline(&line, &len, stdin)) { write(fd[1], line, (size_t) ret); write(1, "? ", 2); } if (line == NULL) return (-1); close(fd[1]); free(line); clearerr(stdin); return (fd[0]); } int exec_do_redirect_right(const char *path) { int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0664); if (fd == -1) { exec_do_redirect_error_handling(path); } return (fd); } int exec_do_redirect_double_right(const char *path) { int fd = open(path, O_WRONLY | O_CREAT | O_APPEND, 0664); if (fd == -1) { exec_do_redirect_error_handling(path); } return (fd); } <file_sep>/src/token/token_validate_token.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** token_validate_token */ /* Contains implicit includes for types. */ #include "proto/token.h" /* ** @DESCRIPTION ** Validates a standard token. */ unsigned int token_validate_token(char const *string, char const *value) { unsigned int i; for (i = 0; string[i]; i++) { if (string[i] != value[i]) return 0; if (!value[i + 1]) return (i + 1); } if (value[i] != '\0') return 0; return (i); } <file_sep>/include/proto/prompt/action/delete.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** sh prompt action delete */ #ifndef SH_PROTO_PROMPT_ACTION_DELETEH_ #define SH_PROTO_PROMPT_ACTION_DELETEH_ #include "types/shell.h" void prompt_action_delete(struct sh *shell); #endif /* !SH_PROTO_PROMPT_ACTION_DELETEH_ */ <file_sep>/lib/myerror/include/myerror.h /* ** EPITECH PROJECT, 2019 ** myerror ** File description: ** myerror header */ #ifndef LIB_MY_ERROR_H_ #define LIB_MY_ERROR_H_ /* Structure Definitions */ typedef enum { ERR_WRITE, ERR_READ } my_error_mode_t; /* Function Prototypes */ int my_error(my_error_mode_t mode, int new_code); #endif <file_sep>/src/exec/rule/pipeline.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** exec rule pipeline */ #include <stdlib.h> #include <string.h> #include <stdio.h> #include <unistd.h> #include "proto/exec/rule/debug.h" #include "types/exec/rule.h" #include "proto/job/create.h" #include "proto/job/destroy.h" #include "proto/job/launch.h" #include "proto/exec/rule/command.h" #include "proto/exec/rule/subshell.h" #include "proto/exec/rule/pipeline.h" #include "parser_toolbox/string_split.h" #include "parser_toolbox/argv_length.h" #include "hasher/get_data.h" #include "types/builtins.h" void follow_alias( struct process_s **process, struct process_s **save, char *data ); char *builtin_alias_replace_recursively( struct hasher_s *alias, char *key, int depth ) { char *data = (char *) hasher_get_data(alias, key); if (data && depth < 100) { return (builtin_alias_replace_recursively(alias, data, depth + 1)); } else { if (depth == 0) { return (key); } if (depth >= 100) { dprintf(2, "Alias loop.\n"); return ((char *) -1); } data = strdup(key); return (data); } } void replace_add_data(struct process_s *process, char *data) { char **strs = ptb_string_split(data, " "); size_t length = ptb_argv_length((const char * const *) strs) + ptb_argv_length((const char * const *) process->argv) + 1; char **new = calloc(length + 1, sizeof(char *)); char **old = process->argv; process->argv = new; process->argc = 0; for (size_t i = 0; strs[i]; ++i) { process->argv[process->argc++] = strs[i]; } for (size_t i = 1; old[i]; ++i) { process->argv[process->argc++] = old[i]; } } static int exec_replace_alias(struct sh *shell, struct job_s *job) { struct process_s *process = job->first_process; char *data = NULL; struct process_s *save = process; for (; process;) { if (process->subshell) { process = process->next; continue; } data = builtin_alias_replace_recursively( shell->alias, process->argv[0], 0 ); if (!data) return (EXEC_RULE_ALLOCATION_FAIL); if (data == (char *) -1) return (EXEC_RULE_ALIAS_LOOP); follow_alias(&process, &save, data); } return (EXEC_RULE_SUCCESS); } static int exec_rule_pipeline_launch_job( struct sh *shell, struct job_s *job, bool foreground ) { if (exec_replace_alias(shell, job)) { return (EXEC_RULE_ALLOCATION_FAIL); } shell->job = job; job->foreground = foreground; job_launch(shell, job); return (EXEC_RULE_SUCCESS); } int exec_rule_pipeline( struct sh *shell, struct expr_pipeline_s *rule, bool foreground ) { struct job_s *job = job_create(0); int ret = 0; exec_rule_debug(shell, "pipeline", true); for (; rule; rule = rule->pipeline) { ret = rule->command ? exec_rule_command(shell, rule->command, job) : exec_rule_subshell(shell, rule->subshell, job); if (ret) { job_destroy(job); return (ret); } } exec_rule_debug(shell, "job_launch", true); exec_rule_job_display(shell, job); if (exec_rule_pipeline_launch_job(shell, job, foreground)) { return (EXEC_RULE_ALLOCATION_FAIL); } exec_rule_debug(shell, "job_launch", false); exec_rule_debug(shell, "pipeline", false); return (shell->last_status); } <file_sep>/README.md # 42SH [![pipeline status](https://gitlab.com/rojasdiegopro/epitech-42sh/badges/master/pipeline.svg)](https://gitlab.com/rojasdiegopro/epitech-42sh/-/commits/master) [![coverage report](https://gitlab.com/rojasdiegopro/epitech-42sh/badges/master/coverage.svg)](https://gitlab.com/rojasdiegopro/epitech-42sh/-/commits/master) ![mark](https://i.imgur.com/BpH0HnO.png) Basic shell based on TCSH. 42sh is the end-of-first-year project for students at Epitech. While you can browse the code as much as you want, be careful about copying code from this repository if this project was assigned to you. On the other hand, you are completely free to apply the 42sh grammar we used to your own project (`local/42sh.ebnf`). This is a group project, check the [Contributors](https://github.com/rojasdiegopro/epitech-42sh/graphs/contributors?type=a) tab and pay my talented friends a visit 😃. ## Usage After cloning the repository, build the executable using `make` ``` $ make ``` Then you can start the shell directly by using ``` $ ./42sh [--debug-mode] ``` ## Requirements The goal was to produce a completely functional shell which could execute advanced commands and tasks. The main features were: - Basic command execution `ls`, `cd`, `make`. - Argument parsing `ls -l` - Redirections `ls >> file`, `ls < file` - Separators `ls ; cd ~` - Builtins `cd`, `echo`, `env`, `unsetenv`, `setenv`... - Pipes `ls | grep "include"` - Inhibitors `ls "this is a\" valid string"` - Globbing `ls *.a` - Job control - Subshells `(ls -l)` - Control statements `if`, `while`, `repeat`, `else if`, `else`, `foreach` - Advanced manipulations and commands `cd ; </etc/hosts od -c | grep xx | wc >> /tmp/z -l ; cd - && echo “OK”` - Scripting `./ftest.sh` - Variables and state `var i` - Combination of all of the above In the end, the shell was expected to execute complete scripts like the following. ```sh if (0) then echo "1!" else if (0) then echo "2!" else cd doesnt_exist || ls -l | grep . | grep a ; echo "Done!" > file endif ls & cat script.sh && ps repeat 10 echo "10" ``` ## Features ### CI Workflow Post project completion, we used [GitLab](https://docs.gitlab.com/) to introduce CI pipelines. They can be seen at the top of the repository. The pipeline can be found [here](.gitlab-ci.yml). It allows us to automatically run our [functional tests](ftest.sh) as well as our [unit tests](Makefile), upon pushing to the GitLab remote. ![UI in gitlab](https://i.imgur.com/a0dvGkt.png) ### Recursive descent parsing We used recursive descent parsing to parse and execute the user input. Our shell first tokenises the input and then parses it into a tree to be executed afterwards. Using the `debug-mode` you can visualise the parsing of your input and how it is executed. For example, this simple command is tokenised like so: ```sh > ls | cat -e ; echo "2" 2> file Word(ls) Pipe(|) Word(cat) Word(-e) Semicolon(;) Word(echo) Word("2") IO Number(2) Great(>) Word(file) EOF() ``` The language structure is defined in the [42sh Grammar](local/42sh.ebnf). ### Job control This project implements basic job control features such as the `&` token. Commands which are ran along with this token will be executed in the background. You can also suspend a job using `Ctrl + Z` in your terminal. ### Input processing Preprocessing and postprocessing of the input is capital to parse advanced commands containing inhibitors, magic quotes, globbing and other advanced shell features. ### Shell shortcuts We implemented command history, line editing and aliases into our project. Older commands can be restablished by pressing the `Up Arrow` key. Aliases can be set and unset to allow for efficient mapping of favourite commands. Finally it has been made easy to edit your command on multiple line using the `ncurses` library. ## Sources - [A complete guide to Recursive Descent Parsing](https://craftinginterpreters.com/scanning.html). This resources is the basis for the parsing and execution of every user input in the project. - [Bash grammar](https://pubs.opengroup.org/onlinepubs/9699919799.2016edition/utilities/V3_chap02.html#tag_18_10). Consists in documentation regarding the Bash grammar and syntax. This resource was useful in understanding how shells work and was the basis for defining the 42sh grammar - [GNU Documentation](https://www.gnu.org/software/libc/manual/html_node/index.html). Probably the most comprehensive and extensive documentation source. Though dense, it provides examples and explanations on how to design primary shell features. - [Gitlab Docs](https://docs.gitlab.com/ee/ci/pipelines/). Official documentation for CI development inside GitLab. <file_sep>/include/proto/constants.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** constants header file. */ #ifndef SH_CONSTANTS_CONSTANTS_H_ #define SH_CONSTANTS_CONSTANTS_H_ /**/ /* Prototypes */ /**/ /* ** @DESCRIPTION ** Defines the character set to be used as whitespace when parsing. */ extern const char *WHITESPACE __attribute__((unused)); /* ** @DESCRIPTION ** Defines the unwanted characters of a word token. */ extern const char *TOK_WORD_BLACKLIST __attribute__((unused)); /* ** @DESCRIPTION ** Grammar error messages. */ extern const char *AST_EMPTY_IF __attribute__((unused)); extern const char *AST_EMPTY_ELSE __attribute__((unused)); extern const char *AST_EMPTY_ELSE_IF __attribute__((unused)); extern const char *AST_EMPTY_WHILE __attribute__((unused)); extern const char *AST_EMPTY_FOREACH __attribute__((unused)); extern const char *AST_EMPTY_REPEAT __attribute__((unused)); extern const char *AST_ELSE_IF_MISSING_THEN __attribute__((unused)); extern const char *AST_ELSE_MISSING_NEWLINE __attribute__((unused)); extern const char *AST_THEN_MISSING_NEWLINE __attribute__((unused)); extern const char *AST_INVALID_EXPRESSION __attribute__((unused)); extern const char *AST_NULL_COMMAND __attribute__((unused)); extern const char *AST_REPEAT_TOO_FEW_ARGS __attribute__((unused)); extern const char *AST_UNEXPECTED_TOKENS __attribute__((unused)); extern const char *AST_AMBIGUOUS_REDIRECTION1 __attribute__((unused)); extern const char *AST_AMBIGUOUS_REDIRECTION2 __attribute__((unused)); extern const char *AST_MISSING_REDIRECT_NAME __attribute__((unused)); #endif <file_sep>/lib/hasher/include/hasher/get_data.h /* ** EPITECH PROJECT, 2020 ** hasher ** File description: ** hasher get_data */ #ifndef HASHER_GET_DATA_H_ #define HASHER_GET_DATA_H_ #include "hasher/type.h" void *hasher_get_data(struct hasher_s *hasher, const char *key); #endif /* !HASHER_GET_DATA_H_ */ <file_sep>/lib/dnode/src/find.c /* ** EPITECH PROJECT, 2020 ** dnode ** File description: ** find */ #include <stddef.h> #include "dnode/find.h" struct dnode_s *dnode_find_before( struct dnode_s *list, void *data, _Bool (*func)(void *, void *) ) { for (struct dnode_s *curr = list; curr; curr = curr->prev) { if (func(data, curr->data)) { return (curr); } } return (NULL); } struct dnode_s *dnode_find_after( struct dnode_s *list, void *data, _Bool (*func)(void *, void *) ) { for (struct dnode_s *curr = list; curr; curr = curr->next) { if (func(data, curr->data)) { return (curr); } } return (NULL); } struct dnode_s *dnode_find( struct dnode_s *list, void *data, _Bool (*func)(void *, void *) ) { struct dnode_s *node = dnode_find_before(list, data, func); if (!node) { node = dnode_find_after(list, data, func); } return (node); } <file_sep>/lib/dnode/tests/find.c /* ** EPITECH PROJECT, 2020 ** dnode ** File description: ** find */ #include <criterion/criterion.h> #include "dnode/find.h" #include "dnode/insert.h" static _Bool is_identic(void *data1, void *data2) { return (data1 == data2); } Test(dnode_find, basic_test) { struct dnode_s *list = NULL; struct dnode_s *node = NULL; dnode_insert_data(&list, "-h"); dnode_insert_data(&list, "salut"); node = dnode_find(list, list->data, &is_identic); cr_assert_str_eq(node->data, list->data); } <file_sep>/src/prompt/input/get_input_with_raw_mode.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** get_input_with_raw_mode */ #include "proto/prompt/set_raw_mode.h" #include "proto/prompt/input/get_input.h" #include "proto/prompt/input/get_input_with_raw_mode.h" int get_input_with_raw_mode(struct sh *shell) { term_set_raw_mode(&(shell->prompt.orig_term)); get_input(shell); return (tcsetattr(0, TCSANOW, &(shell->prompt.orig_term)) == -1); } <file_sep>/src/job/process/append.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** exec rule command */ #include "proto/job/process/append.h" void job_process_append(struct job_s *job, struct process_s *new_process) { struct process_s *process = job->first_process; if (!job->first_process) { job->first_process = new_process; return; } for (; process->next; process = process->next); process->next = new_process; } <file_sep>/lib/dnode/tests/insert.c /* ** EPITECH PROJECT, 2020 ** dnode ** File description: ** insert */ #include <criterion/criterion.h> #include "dnode/create.h" #include "dnode/insert.h" Test(dnode_insert, basic_test) { struct dnode_s *list = NULL; dnode_insert(&list, dnode_create("???")); dnode_insert(&list, dnode_create("ça va")); dnode_insert(&list, dnode_create("comment")); dnode_insert(&list, dnode_create("salut")); cr_assert_str_eq(list->data, "salut"); cr_assert_str_eq(list->next->data, "comment"); cr_assert_str_eq(list->next->next->data, "ça va"); cr_assert_str_eq(list->next->next->next->data, "???"); list = list->next->next->next; cr_assert_str_eq(list->prev->prev->prev->data, "salut"); cr_assert_str_eq(list->prev->prev->data, "comment"); cr_assert_str_eq(list->prev->data, "ça va"); cr_assert_str_eq(list->data, "???"); cr_assert_null(list->next); cr_assert_null(list->prev->prev->prev->prev); } Test(dnode_insert_data, basic_test) { struct dnode_s *list = NULL; dnode_insert_data(&list, "???"); dnode_insert_data(&list, "ça va"); dnode_insert_data(&list, "comment"); dnode_insert_data(&list, "salut"); cr_assert_str_eq(list->data, "salut"); cr_assert_str_eq(list->next->data, "comment"); cr_assert_str_eq(list->next->next->data, "ça va"); cr_assert_str_eq(list->next->next->next->data, "???"); list = list->next->next->next; cr_assert_str_eq(list->prev->prev->prev->data, "salut"); cr_assert_str_eq(list->prev->prev->data, "comment"); cr_assert_str_eq(list->prev->data, "ça va"); cr_assert_str_eq(list->data, "???"); cr_assert_null(list->next); cr_assert_null(list->prev->prev->prev->prev); } <file_sep>/src/exec/rule/debug.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** exec rule program */ #include <stdio.h> #include "proto/exec/rule/debug.h" static void job_display(struct job_s *job, int depth) { for (struct process_s *s = job->first_process; s; s = s->next) { for (int i = 1; i < depth; i++) { dprintf(2, "│ "); } dprintf(2, "│ Process: "); for (size_t i = 0; i < s->argc; ++i) { dprintf(2, "%s ", s->argv[i]); } dprintf(2, "\n"); } } void exec_rule_job_display(struct sh *shell, struct job_s *job) { if (!shell->debug_mode) { return; } exec_rule_debug(shell, "Job", true); dprintf(2, "\033[38;2;230;70;100m"); job_display(job, shell->debug.depth); exec_rule_debug(shell, "Job", false); } void exec_rule_debug(struct sh *shell, const char *rule, bool entering) { if (!shell->debug_mode) { return; } shell->debug.depth += entering; dprintf(2, "\033[38;2;230;70;100m"); for (int i = 1; i < shell->debug.depth; i++) { dprintf(2, "│ "); } if (entering) { dprintf(2, "┌─o" " \033[1m\033[38;2;150;150;220m%s\033[0m\n", rule); } else { shell->debug.depth -= 1; dprintf(2, "└─o" " \033[1m\033[38;2;150;150;220m%s\033[0m\n", rule); } } <file_sep>/tests/grammar/test_grammar.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** test_grammar */ #include <criterion/criterion.h> #include <string.h> #include "proto/token.h" #include "proto/grammar.h" #include "proto/input/parser.h" #include "types/expr.h" #include "tests/mock_types.h" Test(input_parse_grammar, simple_command) { struct sh shell = MOCK_SH; struct expr_pipeline_s *expr = NULL; shell.rawinput = strdup("ls"); input_parse_tokens(&shell); input_parse_grammar(&shell); expr = shell.expression->block->statement->compound->grouping->pipeline; cr_assert_eq(expr->command->word->type, TOK_WORD); cr_assert_eq(expr->command->word->start, 0); cr_assert_eq(expr->command->word->end, 2); } Test(input_parse_grammar, advanced_command) { struct sh shell = MOCK_SH; struct expr_pipeline_s *expr = NULL; shell.rawinput = strdup("ls | cat -e || ls \"this\" && ls > file"); input_parse_tokens(&shell); input_parse_grammar(&shell); expr = shell.expression->block->statement->compound->grouping->pipeline; cr_assert_eq(expr->pipe->type, TOK_PIPE); } Test(input_parse_grammar, control_flow) { struct sh shell = MOCK_SH; struct expr_if_control_s *expression = NULL; shell.rawinput = strdup("if (1 && 1) then\nls\nelse if (0) then\nls\nendif\n"); input_parse_tokens(&shell); input_parse_grammar(&shell); expression = shell.expression->block->statement->control->if_control; cr_assert_not_null(shell.expression); cr_assert_not_null(expression); } Test(input_parse_grammar, bad_control_flow) { struct sh shell = MOCK_SH; struct expr_if_control_s *expression = NULL; shell.rawinput = strdup("if then\nls\nelse if (0) then\nls\nendif\n"); input_parse_tokens(&shell); input_parse_grammar(&shell); cr_assert_null(expression); } Test(input_parse_grammar, control_flow_else) { struct sh shell = MOCK_SH; struct expr_if_control_s *expression = NULL; shell.rawinput = strdup("if (1 && 1) then\nls\nelse if (0) then\nls\nelse\nls\nendif\n"); input_parse_tokens(&shell); input_parse_grammar(&shell); expression = shell.expression->block->statement->control->if_control; cr_assert_not_null(shell.expression); cr_assert_not_null(expression); } <file_sep>/src/prompt/input/read_single_input.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** read_single_input */ /* read */ #include <unistd.h> #include "proto/prompt/input/read_single_input.h" enum get_input_e read_single_input(char *character) { ssize_t total_read = read(STDIN_FILENO, character, 1); if (total_read == -1) { return (GET_INPUT_READ_FAIL); } if (total_read == 0) { *character = -1; } return (GET_INPUT_CONTINUE); } <file_sep>/lib/parser_toolbox/src/str_join.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** str_join */ #include <string.h> #include <stdlib.h> #include "parser_toolbox/str_join.h" char *ptb_str_join(const char *const *word_array, char const *str) { char *new = NULL; size_t nb_words = 0; size_t len = 0; if (!word_array) return (NULL); for (; word_array[nb_words]; nb_words++) len += strlen(word_array[nb_words]); len += ((str ? strlen(str) : 0) * (nb_words - 1)); new = malloc(sizeof(char) * (len + 1)); len = 0; for (size_t i = 0; word_array[i]; i++) { for (size_t j = 0; word_array[i][j]; j++, len++) new[len] = word_array[i][j]; for (size_t j = 0; str && str[j] && word_array[i + 1]; j++, len++) new[len] = str[j]; } new[len] = 0; return (new); } <file_sep>/src/shell/local_variables/get_type.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** get_type */ #include <stddef.h> #include "proto/shell/local_variables.h" #include "types/local_variables.h" enum var_type_e local_variable_get_type(char const *data) { for (size_t i = (*data == '-'); data[i]; ++i) { if (!(data[i] <= '9' && data[i] >= '0')) { return (STRING); } } return (INTEGER); } <file_sep>/include/proto/input/parser.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** executer header file. */ #ifndef SH_PROTO_INPUT_PARSER_H_ #define SH_PROTO_INPUT_PARSER_H_ /**/ /* Includes */ /**/ #include "types/shell.h" #include "types/token.h" /**/ /* Constants */ /**/ /**/ /* Structures / Typedef / Enums declarations */ /**/ /**/ /* Function prototypes */ /**/ /* Belongs to src/input/parser/input_parse.c */ int input_parse(struct sh *shell); /* Belongs to src/input/parser/input_parse_tokens.c */ void input_parse_tokens(struct sh *shell); /* Belongs to src/input/parser/input_parse_grammar.c */ int input_parse_grammar(struct sh *shell); #endif <file_sep>/lib/dnode/src/append.c /* ** EPITECH PROJECT, 2020 ** dnode ** File description: ** append */ #include <stddef.h> #include "dnode/append.h" #include "dnode/create.h" /* ** @Description: ** Add a node at the end of the list */ void dnode_append(struct dnode_s **head, struct dnode_s *node) { struct dnode_s *current = *head; if (!current) { *head = node; return; } for (; current->next; current = current->next) {} node->prev = current; current->next = node; node->next = NULL; } /* ** @Description: ** Create a node and add it at the end of the list */ void dnode_append_data(struct dnode_s **head, void *data) { struct dnode_s *new = dnode_create(data); if (!new) { return; } dnode_append(head, new); } <file_sep>/lib/builtins/src/change_directory.c /* ** EPITECH PROJECT, 2020 ** builtins ** File description: ** builtin_change_directory */ /* perror */ #include <stdio.h> /* chdir */ #include <unistd.h> /* strdup */ #include <string.h> /* getenv */ #include <stdlib.h> /* errno */ #include <errno.h> #include "builtin/get_user_home.h" /* */ #include "builtin/change_directory.h" static const char CHANGE_DIRECTORY_GOTO_LAST_DIR[] = "-"; static enum change_directory_e builtin_change_directory_set_env(const char *env) { char *pwd = getcwd(NULL, 0); if (pwd == NULL) { return (CD_ALLOCATION_FAIL); } if (setenv(env, pwd, 1)) { return (CD_ALLOCATION_FAIL); } return (CD_SUCCESS); } static enum change_directory_e builtin_change_directory_to_home(void) { const char *home = builtin_get_user_home(); builtin_change_directory_set_env("OLDPWD"); if (home == NULL) { perror("getpwuid"); return (CD_GETPWUID_FAIL); } if (chdir(home) == -1) { dprintf(2, "%s: Not a directory.\n", home); return (CD_CHDIR_FAIL); } return (builtin_change_directory_set_env("PWD")); } static enum change_directory_e builtin_change_directory_to_last_dir(void) { const char *old_pwd = getenv("OLDPWD"); const char *pwd = getenv("PWD"); char *pwd_save = NULL; if (old_pwd == NULL) { return (builtin_change_directory_to_home()); } if (chdir(old_pwd) == -1) { return (CD_CHDIR_FAIL); } pwd_save = (pwd != NULL) ? strdup(pwd) : getcwd(NULL, 0); if (pwd_save == NULL) { return (CD_ALLOCATION_FAIL); } setenv("PWD", old_pwd, 1); setenv("OLDPWD", pwd_save, 1); free(pwd_save); return (CD_SUCCESS); } enum change_directory_e builtin_change_directory(const char *path) { if (path == NULL) { return (builtin_change_directory_to_home()); } if (!strcmp(path, CHANGE_DIRECTORY_GOTO_LAST_DIR)) { return (builtin_change_directory_to_last_dir()); } builtin_change_directory_set_env("OLDPWD"); if (chdir(path) == -1) { dprintf(2, "%s: %s.\n", path, strerror(errno)); return (CD_CHDIR_FAIL); } builtin_change_directory_set_env("PWD"); return (CD_SUCCESS); } <file_sep>/include/proto/prompt/action.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** sh prompt action */ #ifndef SH_PROTO_PROMPT_ACTION_H_ #define SH_PROTO_PROMPT_ACTION_H_ #include "proto/prompt/action/backspace.h" #include "proto/prompt/action/clear_line.h" #include "proto/prompt/action/clear_term.h" #include "proto/prompt/action/cut_line.h" #include "proto/prompt/action/delete.h" #include "proto/prompt/action/down.h" #include "proto/prompt/action/end_of_file.h" #include "proto/prompt/action/end.h" #include "proto/prompt/action/home.h" #include "proto/prompt/action/interrupt.h" #include "proto/prompt/action/left.h" #include "proto/prompt/action/right.h" #include "proto/prompt/action/tab.h" #include "proto/prompt/action/up.h" #endif /* !SH_PROTO_PROMPT_ACTION_H_ */ <file_sep>/lib/dnode/include/dnode/free.h /* ** EPITECH PROJECT, 2020 ** dnode ** File description: ** free */ #ifndef DNODE_FREE_H_ #define DNODE_FREE_H_ #include "dnode/type.h" void dnode_free(struct dnode_s **head, void (*func)(void *)); #endif /* !DNODE_FREE_H_ */ <file_sep>/include/proto/shell.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** shell header file. */ #ifndef SH_PROTO_SHELL_H_ #define SH_PROTO_SHELL_H_ /**/ /* Includes */ /**/ #include "types/shell.h" /**/ /* Constants */ /**/ /**/ /* Structures / Typedef / Enums declarations */ /**/ /**/ /* Function prototypes */ /**/ int shell_struct_initialise( struct sh *this, int ac, char *const *av, char *const *ep ); int shell_start(struct sh *shell); void shell_destroy(struct sh *shell); char *do_shell_getenv(struct sh *shell, char const *name); #endif <file_sep>/lib/hasher/include/hasher/insert.h /* ** EPITECH PROJECT, 2020 ** hasher ** File description: ** hasher insert */ #ifndef HASHER_INSERT_H_ #define HASHER_INSERT_H_ #include "hasher/type.h" void hasher_insert(struct hasher_s **hasher, struct hasher_s *to_insert); void hasher_insert_ordered(struct hasher_s **hasher, struct hasher_s *to_insert); #endif /* !HASHER_INSERT_H_ */ <file_sep>/src/prompt/display.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** prompt_display */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "proto/shell.h" #include "proto/prompt/display.h" #include "parser_toolbox/strrep.h" const char *DISPLAY_COLOR[2] = { "\033[38;2;255;50;50m", "\033[38;2;150;220;150m" }; /* ** @DESCRIPTION ** Prints the shell prompt. */ int prompt_display(__attribute__((unused)) struct sh *shell) { const char *dir = getenv("PWD"); const char *user = getenv("USER"); const char *home = getenv("HOME"); char *host = getenv("HOSTNAME"); if (host) { host = ptb_strrep(strdup(host), '.', '\0'); if (!host) return (EXIT_FAILURE); } if (dir && home && !strcmp(dir, home)) dir = "/~"; dir = dir ? strrchr(dir, '/') : dir; printf("%s[%s@%s %s]%s\033[0m", DISPLAY_COLOR[!shell->last_status], user ? user : "", host ? host: "", dir ? dir : "", "$> "); fflush(stdout); if (host) free(host); return (EXIT_SUCCESS); } <file_sep>/src/job/do_notification.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** job */ #include <stddef.h> #include <sys/wait.h> #include "proto/job/destroy.h" #include "proto/job/utils.h" #include "proto/job/format_info.h" #include "proto/job/process/update_status.h" #include "proto/job/do_notification.h" static void job_update_status(struct sh *shell, struct job_s *first_job) { int status; pid_t pid; do { pid = waitpid(WAIT_ANY, &status, WUNTRACED | WNOHANG); } while (!job_process_update_status(shell, first_job, pid, status)); } void job_do_notification(struct sh *shell, struct job_s **first_job) { struct job_s *job_last = NULL; struct job_s *job_next; job_update_status(shell, *first_job); for (struct job_s *job = *first_job; job; job = job_next) { job_next = job->next; if (job_is_completed(job)) { job_format_info(job, "Done", false); if (job_last) { job_last->next = job_next; } else *first_job = job_next; job_destroy(job); } else if (job_is_stopped(job) && !job->notified) { job_format_info(job, "Stopped", false); job->notified = true; job_last = job; } else job_last = job; } } <file_sep>/lib/parser_toolbox/include/parser_toolbox/hexdumper.h /* ** EPITECH PROJECT, 2020 ** parser_toolbox ** File description: ** parser_toolbox hexdumper */ #ifndef PARSER_TOOLBOX_HEXDUMPER_H_ #define PARSER_TOOLBOX_HEXDUMPER_H_ #include <stdbool.h> void ptb_hexdumper(const void *mem, size_t size); #endif /* !PARSER_TOOLBOX_HEXDUMPER_H_ */ <file_sep>/lib/mynode/src/node_filter.c /* ** EPITECH PROJECT, 2020 ** mynode ** File description: ** node_remove */ #include <stdlib.h> #include "mynode.h" static void node_cut(NODE **head, NODE *previous, NODE *curr, fnode_t free_func) { NODE *to_free = curr; if (!previous) *head = curr->next; else previous->next = curr->next; if (free_func) free_func(to_free->data); free(to_free); } /* ** @DESCRIPTION ** This function filters the list by removing the nodes for which the ** function returns false. */ void node_filter(NODE **head, bool (*filter)(), fnode_t free_func) { NODE *previous = 0; NODE *to_free = 0; for (NODE *curr = *head; curr;) { if (!filter(curr->data)) { to_free = curr; curr = curr->next; node_cut(head, previous, to_free, free_func); } else { previous = curr; curr = curr->next; } } } <file_sep>/lib/parser_toolbox/include/parser_toolbox/argv_length.h /* ** EPITECH PROJECT, 2020 ** parser_toolbox ** File description: ** parser_toolbox argv_length */ #ifndef PARSER_TOOLBOX_ARGV_LENGTH_H_ #define PARSER_TOOLBOX_ARGV_LENGTH_H_ #include <stddef.h> size_t ptb_argv_length(const char * const *argv); #endif /* !PARSER_TOOLBOX_ARGV_LENGTH_H_ */ <file_sep>/lib/mynode/src/node_insert.c /* ** EPITECH PROJECT, 2020 ** mynode ** File description: ** node_list_insert */ #include <stdlib.h> #include "mynode.h" /* ** @DESCRIPTION ** Allocates a new node to be freed and puts it at the top of the provided ** node list. ** Links the void * data to the node. ** @RETURN_VALUE ** None. */ void node_insert(NODE **head, void *data) { NODE *new = malloc(sizeof(*new)); if (new && data) { new->data = data; new->next = *head; *head = new; } } <file_sep>/include/proto/prompt/history.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** history */ #ifndef SH_PROTO_HISTORY_H_ #define SH_PROTO_HISTORY_H_ #include "types/history.h" void history_insert(struct history_s *history, char const *line); _Bool history_replace(struct history_s *history, char **str); void history_destroy(struct history_s *history); _Bool history_init(struct history_s *history); #endif /* !SH_PROTO_HISTORY_H_ */ <file_sep>/include/proto/job/create.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** create job */ #ifndef SH_PROTO_JOB_CREATE_H_ #define SH_PROTO_JOB_CREATE_H_ #include "types/job.h" struct job_s *job_create(int launch_id); #endif /* !SH_PROTO_JOB_CREATE_H_ */ <file_sep>/include/types/shell.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** shell header file. */ #ifndef SH_TYPES_SHELL_H_ #define SH_TYPES_SHELL_H_ /**/ /* Includes */ /**/ #include <stdio.h> #include <stdbool.h> #include "mynode.h" #include "hasher/type.h" #include "types/history.h" #include "types/prompt.h" #include "types/job.h" /**/ /* Constants */ /**/ /**/ /* Structures / Typedef / Enums declarations */ /**/ /* ** @DESCRIPTION ** Error wrapper. */ enum sh_error_e { ER_NONE, ER_MALLOC, ER_SYSCALL, ER_GRAMMAR }; struct debug_mode_s { int depth; }; /* ** @DESCRIPTION ** Main shell structure. ** @MEMBERS ** - active: the shell will run while active is true. ** - rawinput: the input from the user fetched with getline. ** - tokens: a linked list containing the parsed tokens for the rawinput. ** - envp: the environement as an array of strings. */ typedef struct sh { bool debug_mode; bool active; char *rawinput; struct node_s *tokens; pid_t pgid; char * const *envp; struct prompt prompt; int atty; int last_status; struct history_s history; struct hasher_s *builtin; struct hasher_s *alias; struct hasher_s *bindkey; struct hasher_s *local_var; enum sh_error_e error; struct job_s *job; int fd; FILE *stream; struct expr_program_s *expression; struct debug_mode_s debug; } sh_t; /* ** Attribute: ** active, pgid, atty, fd, debug_mode, error ** Cat: ** history, builtin alias bindkey ** ???: ** rawinput, prompt ** Exec: ** job, tokens */ /**/ /* Function prototypes */ /**/ #endif <file_sep>/include/proto/job/destroy.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** destroy job */ #ifndef SH_PROTO_JOB_DESTROY_H_ #define SH_PROTO_JOB_DESTROY_H_ #include "types/job.h" void job_destroy(struct job_s *job); #endif /* !SH_PROTO_JOB_DESTROY_H_ */ <file_sep>/lib/find_binary/include/find_binary_in_path_env.h /* ** EPITECH PROJECT, 2020 ** find_binary ** File description: ** find_binary_in_path_env */ #ifndef FIND_BINARY_IN_PATH_ENV_H_ #define FIND_BINARY_IN_PATH_ENV_H_ char *find_binary_in_path_env(const char *path, const char *extend); #endif /* !FIND_BINARY_IN_PATH_ENV_H_ */ <file_sep>/src/job/sighandler.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** sig handler */ #include "proto/sighandler.h" static const int SIGCOUNT = 5; static const int SIGNUMS[] = { SIGINT, SIGQUIT, SIGTSTP, SIGTTIN, SIGTTOU, SIGCHLD }; void term_set_signal_handling(sighandler_t action) { for (int i = 0; i < SIGCOUNT; ++i) { signal(SIGNUMS[i], action); } } <file_sep>/lib/parser_toolbox/src/strrpbrk.c /* ** EPITECH PROJECT, 2020 ** parser_toolbox ** File description: ** ptb_strrpbrk */ #include <stddef.h> #include "parser_toolbox/strrpbrk.h" /* ** @DESCRIPTION ** Returns last occurence of char in charset. */ char *ptb_strrpbrk(char *string, const char *charset) { const char *accept; while (*string != '\0') { accept = charset; while (*accept != '\0') { if (*accept++ == *string) { return (string); } } ++string; } return (NULL); } <file_sep>/lib/input_postprocessing/src/quote_cleanup.c /* ** EPITECH PROJECT, 2020 ** input_postprocessing ** File description: ** quote_cleanup */ /* size_t */ #include <stddef.h> /* */ #include "postprocess/quote_cleanup.h" static void quote_cleanup_quote( char *str, size_t *index, size_t *mismatched_index, enum quote_cleaning_status_e *status ) { if (*status == QUOTE_CLEANUP_CLOSED) { *status = str[(*index)++] == '"' ? QUOTE_CLEANUP_DOUBLE_QUOTE_OPENED : QUOTE_CLEANUP_SINGLE_QUOTE_OPENED; return; } if ((*status == QUOTE_CLEANUP_DOUBLE_QUOTE_OPENED && str[*index] == '\'') || (*status == QUOTE_CLEANUP_SINGLE_QUOTE_OPENED && str[*index] == '"')) { str[(*mismatched_index)++] = str[(*index)++]; return; } ++(*index); *status = QUOTE_CLEANUP_CLOSED; } enum quote_cleaning_status_e ipp_quote_cleanup(char *str) { enum quote_cleaning_status_e status = QUOTE_CLEANUP_CLOSED; size_t mismatched_index = 0; for (size_t index = 0; str[index] != '\0';) { if (status != QUOTE_CLEANUP_SINGLE_QUOTE_OPENED && str[index] == '\\') { str[mismatched_index++] = str[++index]; ++index; continue; } if (str[index] == '\'' || str[index] == '"') { quote_cleanup_quote(str, &index, &mismatched_index, &status); continue; } str[mismatched_index++] = str[index++]; } str[mismatched_index] = '\0'; return (status); } <file_sep>/include/proto/exec/rule/wordlist_expression.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** shell exec rule wordlist_expression */ #ifndef SH_SHELL_EXEC_RULE_WORDLIST_EXPRESSION_H_ #define SH_SHELL_EXEC_RULE_WORDLIST_EXPRESSION_H_ #include "types/shell.h" #include "types/expr.h" int exec_rule_wordlist_expression( struct sh *shell, struct expr_wordlist_expression_s *rule ); #endif /* !SH_SHELL_EXEC_RULE_WORDLIST_EXPRESSION_H_ */ <file_sep>/lib/myerror/Makefile ## ## EPITECH PROJECT, 2020 ## my_printf ## File description: ## Makefile ## CC ?= gcc NAME = libmyerror.a SRC = my_error.c \ OBJ = $(SRC:.c=.o) CFLAGS = -Wall -Wextra CPPFLAGS = -I ./include/ TFLAGS = --coverage -lcriterion all: $(NAME) $(NAME): $(OBJ) ar rc $(NAME) $(OBJ) ranlib $(NAME) clean: $(RM) $(OBJ) fclean: clean $(RM) $(NAME) $(TEST) re: fclean all .PHONY: all clean fclean re <file_sep>/src/shell/builtin_handlers/at.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** builtins */ #include "builtins.h" #include "types/shell.h" #include "hasher/type.h" #include "proto/shell/builtin_handlers.h" #include "parser_toolbox/argv_length.h" #include "proto/shell/local_variables.h" int builtin_at_handler(struct sh *shell, const char * const *argv) { size_t argc = ptb_argv_length(argv); if (argc == 1) { local_variables_display( shell->local_var, shell->history.list ); } return (0); } <file_sep>/include/proto/prompt/input/reprint_input.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** sh prompt reprint_input */ #ifndef SH_PROTO_PROMPT_REPRINT_INPUT_H_ #define SH_PROTO_PROMPT_REPRINT_INPUT_H_ #include "types/prompt.h" void prompt_reprint_input(struct prompt *prompt); #endif /* !SH_PROTO_PROMPT_REPRINT_INPUT_H_ */ <file_sep>/include/proto/job/put_in.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** constants header file. */ #ifndef SH_PROTO_JOB_PUT_IN_H_ #define SH_PROTO_JOB_PUT_IN_H_ #include <stdbool.h> #include "types/shell.h" #include "types/job.h" void job_put_in_foreground( struct sh *shell, struct job_s *job, bool does_continue ); void job_put_in_background(struct job_s *job, bool does_continue); #endif /* !SH_PROTO_JOB_PUT_IN_H_ */ <file_sep>/lib/find_binary/tests/path_iteration.c /* ** EPITECH PROJECT, 2020 ** find_binary ** File description: ** test path_iteration */ #include <criterion/criterion.h> #include "path_iteration.h" Test(path_iteration, simple_path_iteration) { const char *path_env = "/bin:/usr:/usr/bin"; const char *expected[] = {"/bin", "/usr", "/usr/bin"}; const char *got = NULL; for (unsigned long i = 0; i < (sizeof(expected) / sizeof(char *)); ++i) { got = path_iteration(path_env); cr_assert_str_eq(got, expected[i]); } cr_assert_null(path_iteration(NULL)); } Test(path_iteration, very_long_path_iteration) { const char *path_env = "Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/:" "/Library/Frameworks/Python.framework/Versions/3.6/bin:/usr/local/bin:" "/usr/bin:/bin:/usr/sbin:/sbin:/Applications/Wireshark.app/Contents/" "MacOS:/Users/usernameuser/exercices/flutter/bin:/usr/local/sbin:" "/Users/usernameuser/gocode/bin"; const char *expected[] = { "Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/", "/Library/Frameworks/Python.framework/Versions/3.6/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin", "/sbin", "/Applications/Wireshark.app/Contents/MacOS", "/Users/usernameuser/exercices/flutter/bin", "/usr/local/sbin", "/Users/usernameuser/gocode/bin"}; const char *got = NULL; for (unsigned long i = 0; i < (sizeof(expected) / sizeof(char *)); ++i) { got = path_iteration(path_env); cr_assert_str_eq(got, expected[i]); } cr_assert_null(path_iteration(NULL)); } Test(path_iteration, very_short_path_iteration_but_long_var) { const char *path_env = "Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/" "Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/" "Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/" "Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/:"; const char *expected[] = { "Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/" "Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/" "Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/" "Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/" }; const char *got = NULL; for (unsigned long i = 0; i < (sizeof(expected) / sizeof(char *)); ++i) { got = path_iteration(path_env); cr_assert_str_eq(got, expected[i]); } cr_assert_null(path_iteration(NULL)); } <file_sep>/lib/dnode/include/dnode.h /* ** EPITECH PROJECT, 2020 ** dnode ** File description: ** dnode */ #ifndef DNODE_H_ #define DNODE_H_ #include "dnode/append.h" #include "dnode/apply.h" #include "dnode/create.h" #include "dnode/find.h" #include "dnode/free.h" #include "dnode/goto.h" #include "dnode/insert.h" #include "dnode/type.h" #endif /* !DNODE_H_ */ <file_sep>/lib/hasher/include/hasher/type.h /* ** EPITECH PROJECT, 2020 ** hasher ** File description: ** hasher type */ #ifndef HASHER_TYPE_H_ #define HASHER_TYPE_H_ typedef _Bool hasher_compare(void *, void *); struct hasher_s { struct hasher_s *next; char *key; void *data; }; #endif /* !HASHER_TYPE_H_ */ <file_sep>/src/expr/do_ambiguous_redirection_check.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** do_ambiguous_redirection_check */ #include <stdlib.h> #include <string.h> #include "types/grammar.h" #include "types/expr.h" #include "proto/expr.h" #include "parser_toolbox/sub_str_chr.h" static void do_count_redirection_pipeline( struct expr_command_s *this, int red[2] ) { if (!this) return; for (; this; this = this->command) { if (!this->redirection) continue; red[0] += (this->redirection->redirection->type == TOK_LESS || this->redirection->redirection->type == TOK_DLESS); red[1] += (this->redirection->redirection->type == TOK_GREAT || this->redirection->redirection->type == TOK_DGREAT); } } /* ** @DESCRIPTION ** Ensures not more than one redirection is present in a command. */ int do_ambiguous_redirection_check( __attribute__((unused)) struct grammar_s *gram, struct expr_pipeline_s *this ) { int red[2] = {0, 0}; do_count_redirection_pipeline(this->command, red); if (red[0] > 1 || red[1] > 1 || (red[1] > 0 && this->pipeline)) return ((red[1] > 1 || (red[1] > 0 && this->pipeline)) ? 2 : 1); red[0] = 1; red[1] = 0; for (this = this->pipeline; this; this = this->pipeline) { do_count_redirection_pipeline(this->command, red); if (red[0] > 1 || (red[1] > 0 && this->pipeline)) return ((red[1] > 0) ? 2 : 1); } return (0); } <file_sep>/src/grammar/grammar_toolbox.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** grammar_toolbox */ #include <string.h> #include "proto/grammar.h" /* ** @DESCRIPTION ** Fetches the previous token. */ struct token_s *grammar_get_previous(struct grammar_s *this) { if (this->index > 0) return this->tokens[this->index - 1]; return 0; } /* ** @DESCRIPTION ** Fetches the current token. */ struct token_s *grammar_peek(struct grammar_s *this) { return this->tokens[this->index]; } /* ** @DESCRIPTION ** This function stores the parsing error from the building of the tree. */ void grammar_set_error(struct grammar_s *this, char const *message) { if (!this->error_message) this->error_message = strdup(message); this->error = true; } <file_sep>/lib/hasher/src/replace_key.c /* ** EPITECH PROJECT, 2020 ** hasher ** File description: ** hasher_replace_key */ #include <stddef.h> #include "hasher/get.h" /* */ #include "hasher/replace_key.h" char *hasher_replace_key( struct hasher_s *hasher, const char *current_key, char *new_key ) { struct hasher_s *match = hasher_get(hasher, current_key); char *old_key = NULL; if (match) { old_key = match->key; match->key = new_key; } return (old_key); } <file_sep>/lib/hasher/include/hasher/enum.h /* ** EPITECH PROJECT, 2020 ** hasher ** File description: ** hasher enum */ #ifndef HASHER_ENUM_H_ #define HASHER_ENUM_H_ enum hasher_e { HASHER_SUCCESS, HASHER_ALLOCATION_FAIL }; #endif /* !HASHER_ENUM_H_ */ <file_sep>/lib/parser_toolbox/Makefile ## ## EPITECH PROJECT, 2020 ## parser_toolbox ## File description: ## Makefile ## CC ?= gcc NAME = libparser_toolbox.a TESTNAME = unit_tests SRC = src/add_char.c \ src/argv_length.c \ src/blacklist.c \ src/consts.c \ src/includes.c \ src/range.c \ src/remove_char.c \ src/whitelist.c \ src/hexdumper.c \ src/sub_string.c \ src/strrpbrk.c \ src/strrep.c \ src/sub_string.c \ src/sort_string.c \ src/isdir.c \ src/longest_string.c \ src/display_strings.c \ src/display_strings_equalize.c \ src/word_array_chr.c \ src/cmp_string.c \ src/string_split.c \ src/unquote.c \ src/str_join.c \ src/sub_str_chr.c \ SRCT = tests/ \ OBJ = $(SRC:.c=.o) CFLAGS = -Wall -Wextra CPPFLAGS = -I include/ -g TFLAGS = --coverage -lcriterion all: $(NAME) $(NAME): $(OBJ) ar rc $(NAME) $(OBJ) clean: $(RM) $(OBJ) fclean: clean $(RM) $(NAME) $(TEST) re: fclean all tests_run: $(CC) $(SRC) $(SRCT) -o $(TESTNAME) $(TFLAGS) \ $(CPPFLAGS) $(CFLAGS) ./$(TESTNAME) 2>&1 | (grep -v "profiling") .PHONY: all clean fclean re <file_sep>/lib/hasher/include/hasher/replace_key.h /* ** EPITECH PROJECT, 2020 ** hasher ** File description: ** hasher replace_key */ #ifndef HASHER_REPLACE_KEY_H_ #define HASHER_REPLACE_KEY_H_ #include "hasher/type.h" char *hasher_replace_key( struct hasher_s *hasher, const char *current_key, char *new_key ); #endif /* !HASHER_REPLACE_KEY_H_ */ <file_sep>/include/proto/exec/simple_exec.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** exec simple_exec */ #ifndef SH_SHELL_EXEC_SIMPLE_EXEC_H_ #define SH_SHELL_EXEC_SIMPLE_EXEC_H_ #include <wordexp.h> #include "types/shell.h" void simple_exec(struct sh *sh, wordexp_t *we); #endif /* !SH_SHELL_EXEC_SIMPLE_EXEC_H_ */ <file_sep>/lib/input_postprocessing/Makefile ## ## EPITECH PROJECT, 2020 ## input_postprocessing ## File description: ## Makefile ## CC ?= gcc NAME = libinput_postprocessing.a TESTNAME = unit_tests SRC = src/quote_cleanup.c \ src/env_var_replace.c \ SRCT = tests/quote_cleanup.c \ tests/env_var_replace.c \ OBJ = $(SRC:.c=.o) OBJT = $(SRCT:.c=.o) WARNINGS = -pedantic -Wshadow -Wpointer-arith -Wcast-align \ -Wmissing-prototypes -Wmissing-declarations \ -Wnested-externs -Wwrite-strings -Wredundant-decls \ -Winline -Wno-long-long -Wconversion \ -Wstrict-prototypes \ DEBUG = -g $(WARNINGS) CFLAGS += -Wall -Wextra CPPFLAGS += -I include/ TFLAGS += -lcriterion LDFLAGS += --coverage \ LIBNAMES = parser_toolbox \ builtins \ LIBFOLDER = .. LDLIBS += $(patsubst %, -L $(LIBFOLDER)/%, ${LIBNAMES}) LDLIBS += $(patsubst %, -l%, ${LIBNAMES}) CPPFLAGS += $(patsubst %, -I $(LIBFOLDER)/%/include/, ${LIBNAMES}) all: $(NAME) $(NAME): $(OBJ) ar rc $(NAME) $(OBJ) ranlib $(NAME) tests_run: for lib in $(LIBNAMES) ; do \ $(MAKE) -C $(LIBFOLDER)/$$lib/ || exit 1 ; \ done $(CC) $(SRC) $(SRCT) -o $(TESTNAME) $(TFLAGS) $(LDFLAGS)\ $(CPPFLAGS) $(CFLAGS) $(LDLIBS) ./$(TESTNAME) 2>&1 | (grep -v "profiling") debug: fclean debug: CFLAGS += $(DEBUG) debug: $(NAME) clean: $(RM) $(OBJ) $(OBJT) *.gcno *.gcda fclean: clean $(RM) $(NAME) $(TESTNAME) fcleanlib: fclean for lib in $(LIBNAMES) ; do \ $(MAKE) -C $(LIBFOLDER)/$$lib/ fclean || exit 1;\ done re: fclean all relib: fcleanlib all .PHONY: all clean fclean re tests_run fcleanlib relib <file_sep>/include/proto/exec/rule/redirection.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** shell exec rule redirection */ #ifndef SH_SHELL_EXEC_RULE_REDIRECTION_H_ #define SH_SHELL_EXEC_RULE_REDIRECTION_H_ #include "types/shell.h" #include "types/expr.h" int exec_rule_redirection( struct sh *shell, struct expr_redirection_s *rule ); #endif /* !SH_SHELL_EXEC_RULE_REDIRECTION_H_ */ <file_sep>/lib/dnode/include/dnode/append.h /* ** EPITECH PROJECT, 2020 ** dnode ** File description: ** append */ #ifndef DNODE_APPEND_H_ #define DNODE_APPEND_H_ #include "dnode/type.h" void dnode_append(struct dnode_s **head, struct dnode_s *node); void dnode_append_data(struct dnode_s **head, void *data); #endif /* !DNODE_APPEND_H_ */ <file_sep>/src/shell/term_init.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** term_init */ #include <sys/types.h> #include <termios.h> #include <unistd.h> #include <curses.h> /* setupterm */ #include <term.h> #include "proto/shell/term_init.h" #include "proto/sighandler.h" /* handle IOCTL ? #include <sys/ioctl.h> char *smkx; char *rmkx; int ioctl;* shell->prompt.smkx = tigetstr("smkx"); shell->prompt.rmkx = tigetstr("rmkx"); if (shell->prompt.smkx == (char *) -1) { shell->prompt.smkx = 0; } if (shell->prompt.rmkx == (char *) -1) { shell->prompt.rmkx = 0; } if (shell->ioctl && shell->prompt.smkx) { putp(shell->prompt.smkx); fflush(stdout); } if (shell->ioctl && shell->prompt.rmkx) { putp(shell->prompt.rmkx); fflush(stdout); } */ static int term_job_init(struct sh *shell) { pid_t shell_pgid = getpgrp(); while (shell_pgid != tcgetpgrp(STDIN_FILENO)) { kill(-shell_pgid, SIGTTIN); shell_pgid = getpgrp(); } term_set_signal_handling(SIG_IGN); shell->pgid = getpid(); if (setpgid(shell_pgid, shell_pgid) < 0) { perror("Couldn't put the shell in its own process group"); return (1); } tcsetpgrp(STDIN_FILENO, shell_pgid); return (0); } /* ** @DESCRIPTION ** Initialises term && term keys. */ int term_init(struct sh *shell) { const char *terminfo_str[] = {"cub1", "cuf1", "clear"}; int erret = 0; if (!shell->atty) { return (0); } if (setupterm(NULL, 1, &erret) == ERR) { return (1); } for (int i = 0; i < PROMPT_EFFECT_COUNT; ++i) { shell->prompt.effect[i] = tigetstr(terminfo_str[i]); if (shell->prompt.effect[i] == (char *) -1) { return (1); } } if (tcgetattr(0, &shell->prompt.orig_term) == -1) { return (1); } term_job_init(shell); return (0); } <file_sep>/src/expr/subshell.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** expr_subshell */ #include <stdlib.h> #include <string.h> #include "proto/grammar.h" #include "proto/expr.h" /* ** @DESCRIPTION ** Rule for subshell expression. */ static struct expr_subshell_s *expr_subshell(struct grammar_s *this) { struct expr_subshell_s *exp = malloc( sizeof(struct expr_subshell_s)); unsigned int save_index __attribute__((unused)) = this->index; if (!exp) exit(84); memset(exp, 0, sizeof(struct expr_subshell_s)); if (!grammar_match(this, 1, TOK_LPARANTH)) return (expr_free(exp)); exp->lparanth = grammar_get_previous(this); exp->grouping = expr_grouping_w(this); if (!exp->grouping) return (expr_free(exp)); if (!grammar_match(this, 1, TOK_RPARANTH)) return (expr_free(exp)); exp->rparanth = grammar_get_previous(this); return exp; } struct expr_subshell_s *expr_subshell_w(struct grammar_s *this) { struct expr_subshell_s *exp; expr_print(this, "Subshell"); exp = expr_subshell(this); expr_print_debug(this, exp); return exp; } <file_sep>/lib/find_binary/include/find_file_in_path.h /* ** EPITECH PROJECT, 2020 ** find_binary ** File description: ** find_file_in_path */ #ifndef FIND_FILE_IN_PATH_H_ #define FIND_FILE_IN_PATH_H_ enum find_file_in_path_e { FFIP_ERROR, FFIP_FOUND, FFIP_NOT_FOUND }; char *find_file_in_path(const char *path, const char *bin); #endif /* !FIND_FILE_IN_PATH_H_ */ <file_sep>/src/job/utils.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** job */ #include <stddef.h> #include "proto/job/utils.h" struct job_s *job_find_from_pdig(struct job_s *first_job, pid_t pgid) { struct job_s *job; for (job = first_job; job; job = job->next) { if (job->pgid == pgid) { return (job); } } return (NULL); } int job_is_stopped(struct job_s *job) { struct process_s *process; for (process = job->first_process; process; process = process->next) { if (!process->completed && !process->stopped) { return (0); } } return (1); } int job_is_completed(struct job_s *job) { struct process_s *process; for (process = job->first_process; process; process = process->next) { if (!process->completed) { return (0); } } return (1); } <file_sep>/lib/builtins/src/exit.c /* ** EPITECH PROJECT, 2020 ** builtins ** File description: ** builtin_exit */ #include <stdio.h> /* exit && atoi */ #include <stdlib.h> #include "parser_toolbox/whitelist.h" /* */ #include "builtin/exit.h" /* last status */ void builtin_exit(const char * const *argv) { if (argv[0] == NULL) { exit(0); } if (argv[1] != NULL || !ptb_whitelist_digit(argv[0])) { dprintf(2, "exit: Expression Syntax.\n"); return; } exit((int) strtol(argv[0], (char **) NULL, 10)); } <file_sep>/src/shell/builtin_handlers/which.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** builtins */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "hasher/get_data.h" #include "path_iteration.h" #include "find_file_in_path.h" #include "builtins.h" #include "types/shell.h" #include "proto/shell/builtin_handlers.h" static int builtin_which_display_all_match(const char *binary_name) { const char *path_env = getenv("PATH"); char *full_path = NULL; if (!path_env) { return (1); } for (const char *path = path_iteration(path_env); path; path = path_iteration(path_env)) { full_path = find_file_in_path(path, binary_name); if (!full_path) { continue; } dprintf(1, "%s\n", full_path); free(full_path); while (path) path = path_iteration(path_env); return (0); } return (1); } static int builtin_which(struct sh *shell, const char *name) { char *str = NULL; str = (char *) hasher_get_data(shell->alias, name); if (str) { dprintf(1, "%s: \t aliased to ls --color=auto %s\n", name, str); return (0); } str = (char *) hasher_get_data(shell->builtin, name); if (str) { dprintf(1, "%s: shell built-in command.\n", name); return (0); } if (!builtin_which_display_all_match(name)) { return (0); } dprintf(2, "%s: Command not found.\n", name); return (1); } int builtin_which_handler(struct sh *shell, const char * const *argv) { int ret = 0; if (builtins_utils_too_few_arguments(argv, 1)) { return (1); } for (size_t i = 1; argv[i]; i++) { if (strchr(argv[i], '/')) { dprintf(2, "%s: Command not found.\n", argv[i]); ret = 1; } else { ret = ret | builtin_which(shell, argv[i]); } } return (ret); } <file_sep>/lib/parser_toolbox/include/parser_toolbox/cmp_string.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** cmp_string */ #ifndef PARSER_TOOLBOX_CMP_STRING_H_ #define PARSER_TOOLBOX_CMP_STRING_H_ _Bool ptb_cmp_string(void *data1, void *data2); _Bool ptb_ncmp_string(void *data1, void *data2); #endif /* !PARSER_TOOLBOX_CMP_STRING_H_ */ <file_sep>/src/prompt/update_cursor_pos.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** prompt_update_cursor_pos */ /* strlen */ #include <string.h> /* putp */ #include <curses.h> #include <term.h> #include "types/prompt.h" #include "proto/prompt/update_cursor_pos.h" void prompt_update_cursor_pos(struct prompt *prompt) { for (size_t size = strlen(prompt->input) - prompt->cursor; size > 0; --size) { putp(prompt->effect[PROMPT_EFFECT_CURSOR_BACKWARD]); } } <file_sep>/lib/parser_toolbox/src/unquote.c /* ** EPITECH PROJECT, 2020 ** parser_toolbox ** File description: ** ptb_remove_char */ #include <string.h> #include "parser_toolbox/unquote.h" void ptb_unquote(char *str) { size_t len = strlen(str); if (len < 2) { return; } len -= 2; for (size_t i = 0; i < len; ++i) { str[i] = str[i + 1]; } str[len] = '\0'; } <file_sep>/include/proto/exec/rule/subshell.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** shell exec rule subshell */ #ifndef SH_SHELL_EXEC_RULE_SUBSHELL_H_ #define SH_SHELL_EXEC_RULE_SUBSHELL_H_ #include "types/shell.h" #include "types/expr.h" int exec_rule_subshell( struct sh *shell, struct expr_subshell_s *rule, struct job_s *job ); #endif /* !SH_SHELL_EXEC_RULE_SUBSHELL_H_ */ <file_sep>/src/prompt/input/reprint_input.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** prompt_update_cursor_pos */ /* write() */ #include <unistd.h> /* strlen() */ #include <string.h> #include "proto/prompt/move_cursor_pos.h" #include "proto/prompt/input/reprint_input.h" void prompt_reprint_input(struct prompt *prompt) { size_t save = prompt->cursor; prompt->cursor = strlen(prompt->input); write(1, prompt->input, prompt->cursor); prompt_move_cursor_pos(prompt, save); } <file_sep>/lib/hasher/src/pop.c /* ** EPITECH PROJECT, 2020 ** hasher ** File description: ** hasher_pop */ #include <string.h> /* */ #include "hasher/pop.h" struct hasher_s *hasher_pop(struct hasher_s **hasher, const char *key) { struct hasher_s *poped = NULL; struct hasher_s *current = *hasher; if (!strcmp(current->key, key)) { *hasher = current->next; current->next = NULL; return (current); } for (; current->next != NULL; current = current->next) { if (strcmp(current->next->key, key)) { continue; } poped = current->next; current->next = current->next->next; poped->next = NULL; break; } return (poped); } <file_sep>/include/proto/token/get_string.h /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** token header file. */ #ifndef SH_PROTO_INPUT_TOKEN_GET_STRING_H_ #define SH_PROTO_INPUT_TOKEN_GET_STRING_H_ #include "types/token.h" /* Belongs to src/input/parser/token.c */ char *token_get_string(const struct token_s *this, const char *rawinput); #endif <file_sep>/src/expr/destroy/while_control.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** expr_while_control */ /* free */ #include <stdlib.h> #include "proto/expr_destroy.h" /* ** @DESCRIPTION ** Rule for while_control expression. */ void expr_while_control_destroy(struct expr_while_control_s *this) { if (!this) { return; } expr_wordlist_expression_destroy(this->wordlist_expression); expr_block_destroy(this->block); free(this); } <file_sep>/src/shell/builtin_handlers/cd.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** builtins */ #include "builtins.h" #include "types/shell.h" #include "proto/shell/builtin_handlers.h" int builtin_change_directory_handler( __attribute__((unused)) struct sh *shell, const char * const *argv ) { return (builtin_change_directory(argv[1])); } <file_sep>/lib/parser_toolbox/include/parser_toolbox/enum.h /* ** EPITECH PROJECT, 2020 ** parser_toolbox ** File description: ** parser_toolbox hexdumper */ #ifndef PARSER_TOOLBOX_ENUM_H_ #define PARSER_TOOLBOX_ENUM_H_ enum parser_toolbox_e { PTB_FAILURE = -1, PTB_FALSE, PTB_TRUE, }; #endif /* !PARSER_TOOLBOX_ENUM_H_ */ <file_sep>/lib/builtins/include/builtin/get_user_home.h /* ** EPITECH PROJECT, 2020 ** builtins ** File description: ** builtin_get_user_home */ #ifndef BUILTIN_GET_USER_HOME_H_ #define BUILTIN_GET_USER_HOME_H_ const char *builtin_get_user_home(void); #endif /* !BUILTIN_GET_USER_HOME_H_ */ <file_sep>/lib/parser_toolbox/src/consts.c /* ** EPITECH PROJECT, 2020 ** parser_toolbox ** File description: ** consts */ #include "parser_toolbox/consts.h" const char PTB_WHITESPACES[] = " \t\n\r\f\v"; const char PTB_DIGITS[] = "0123456789"; const char PTB_ALPHANUM[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "_0123456789"; <file_sep>/include/proto/job/format_info.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** job */ #ifndef SH_PROTO_JOB_INFO_H_ #define SH_PROTO_JOB_INFO_H_ #include "types/job.h" void job_format_info_launch_background(struct job_s *job); void job_format_info(struct job_s *job, const char *status, _Bool dumped); #endif /* !SH_PROTO_JOB_INFO_H_ */ <file_sep>/lib/input_postprocessing/tests/env_var_replace.c /* ** EPITECH PROJECT, 2020 ** input_postprocessing ** File description: ** test builtin_setenv */ /* setenv */ #include <stdlib.h> /* strdup */ #include <string.h> #include <criterion/criterion.h> #include <criterion/redirect.h> #include "postprocess/env_var_replace.h" Test(ipp_env_var_replace, simple_env_var_replace) { const char *var_name = "VAR"; const char *value = "VALUE"; char *command = strdup("echo $VAR"); setenv(var_name, value, 1); ipp_env_var_replace(&command); cr_assert_str_eq(command, "echo VALUE"); free(command); } Test(ipp_env_var_replace, undefined_variable) { const char *var_name = "VAR"; char *command = strdup("echo $VAR"); cr_redirect_stderr(); unsetenv(var_name); ipp_env_var_replace(&command); cr_assert_stderr_eq_str("VAR: Undefined variable.\n"); free(command); } <file_sep>/lib/dnode/tests/free.c /* ** EPITECH PROJECT, 2020 ** dnode ** File description: ** free */ #include <stdlib.h> #include <criterion/criterion.h> #include "dnode/insert.h" #include "dnode/free.h" Test(dnode_free, basic_test) { struct dnode_s *list = NULL; dnode_insert_data(&list, "salut"); dnode_insert_data(&list, "salut"); dnode_insert_data(&list, "salut"); dnode_free(&list, NULL); cr_assert_null(list); } <file_sep>/src/exec/rule/control/foreach.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** exec rule control foreach */ #include <stddef.h> #include <string.h> #include "proto/token/get_string.h" #include "proto/shell/local_variables.h" #include "proto/exec/rule/debug.h" #include "parser_toolbox/string_split.h" #include "parser_toolbox/consts.h" #include "proto/job/process/create.h" #include "proto/exec/rule/block.h" #include "proto/exec/rule/control/foreach.h" #include "hasher/insert_data.h" #include "hasher/pop.h" int do_post_process( struct sh *shell, struct process_s *proc, char **words ); int exec_rule_control_foreach( struct sh *shell, struct expr_foreach_control_s *rule ) { struct process_s *process = process_create(); char *substr = token_get_string(rule->word, shell->rawinput); struct local_var_s *var = NULL; struct expr_wordlist_expression_s *w = rule->wordlist_expression; if (!process || do_post_process(shell, process, ptb_string_split(strndup( shell->rawinput + w->lparanth->end, w->rparanth->start - w->lparanth->end), PTB_WHITESPACES))) return (1); exec_rule_debug(shell, "foreach", true); for (size_t i = 0; i < process->argc; ++i) { var = local_variable_from_data( shell->local_var, substr, process->argv[i]); hasher_insert_data_ordered(&shell->local_var, strdup(substr), var); exec_rule_block(shell, rule->block); } exec_rule_debug(shell, "foreach", false); hasher_pop(&shell->local_var, substr); return (0); } <file_sep>/src/shell/builtin_handlers/alias.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** builtins */ #include "gnu_source.h" #include <stdlib.h> #include <string.h> #include "parser_toolbox/argv_length.h" #include "hasher/pop.h" #include "hasher/create.h" #include "hasher/destroy.h" #include "hasher/insert.h" #include "hasher/override.h" #include "builtins.h" #include "types/shell.h" #include "proto/shell/builtin_handlers.h" #include "parser_toolbox/str_join.h" static int insert_alias(struct sh *shell, const char * const *argv) { char *data = NULL; struct hasher_s *new = NULL; struct hasher_s *overrided = NULL; data = ptb_str_join(argv + 2, " "); if (data == NULL) { return (1); } new = hasher_create(strdup(argv[1]), data); if (new == NULL) { return (1); } overrided = hasher_override(&shell->alias, new); if (!overrided) { hasher_insert_ordered(&shell->alias, new); } return (0); } int builtin_alias_handler( struct sh *shell, const char * const *argv ) { if (!argv[1]) { for (struct hasher_s *alias = shell->alias; alias != NULL; alias = alias->next) { dprintf(1, "%s\t%s\n", alias->key, (char *) alias->data); } return (0); } return (!argv[2] || insert_alias(shell, argv)); } int builtin_unalias_handler( struct sh *shell, const char * const *argv ) { struct hasher_s *poped = NULL; if (builtins_utils_too_few_arguments(argv, 1)) { return (1); } if (!shell->alias) { return (0); } for (size_t i = 1; argv[i]; ++i) { poped = hasher_pop(&shell->alias, argv[i]); if (poped) { hasher_destroy(poped, false, false); } } return (0); } <file_sep>/src/token/token.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** token class */ #include <stdio.h> #include <string.h> #include <stdlib.h> /* Contains implicit includes for types */ #include "proto/token.h" #include "tests/tokens.h" #include "constants/tokens.h" #include "tests/tokens.h" /* ** @DESCRIPTION ** This function returns the malloc'ed string of a token. */ char *token_get_string(const struct token_s *this, const char *rawinput) { return (strndup(rawinput + (*this).start, (*this).end - (*this).start)); } /* ** @DESCRIPTION ** Prints a token list with the token name and symbol. */ void token_list_print(struct node_s *head) { struct token_s *this; for (struct node_s *curr = head; curr; curr = (*curr).next) { this = (*curr).data; printf("Token %s (%s)\n", TOK_NAMES[(*this).type], TOKENS[(*this).type]); } } void token_print_debug(struct node_s *head, char const *rawinput) { struct token_s *this; size_t printed = 0; char *dup; dprintf(2, "\n================== TOKENS ====================\n"); for (struct node_s *curr = head; curr; curr = curr->next) { this = curr->data; dup = token_get_string(this, rawinput); printed += strlen(TOK_NAMES[this->type]) + strlen(dup) + 3; dprintf(2, "\033[1m\033[38;2;230;70;200m %s\033[0m(%s)", TOK_NAMES[this->type], dup); if (printed > 36) { printf("\n"); printed = 0; } free(dup); } fflush(stderr); } struct token_s *token_new(enum tokent_e type) { struct token_s *this = malloc(sizeof(struct token_s)); if (!this) return NULL; memset(this, 0, sizeof(struct token_s)); this->type = type; return this; } <file_sep>/include/proto/exec/rule/control/if.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** shell exec rule control if */ #ifndef SH_SHELL_EXEC_RULE_CONTROL_IF_H_ #define SH_SHELL_EXEC_RULE_CONTROL_IF_H_ #include "types/shell.h" #include "types/expr.h" int exec_rule_control_if( struct sh *shell, struct expr_if_control_s *rule ); #endif /* !SH_SHELL_EXEC_RULE_CONTROL_IF_H_ */ <file_sep>/lib/parser_toolbox/src/hexdumper.c /* ** EPITECH PROJECT, 2020 ** parser_toolbox ** File description: ** hexdumper */ #include <stdio.h> #include <ctype.h> static const char HEXA_STR[] = "0123456789abcdef"; void ptb_hexdumper(const void *mem, size_t size) { const char *str = (const char *) mem; size_t pos = 0; for (size_t sub_pos = 0; pos < size;) { dprintf(1, "\033[38;2;150;150;220m%08zx\033[0m\t" "\033[1m\033[38;2;180;123;90m", pos); for (sub_pos = -1; ++sub_pos < 16 && pos < size; ++pos) dprintf(1, "%c%c ", HEXA_STR[((unsigned char) str[pos]) / 16 % 16], HEXA_STR[((unsigned char) str[pos]) % 16]); pos -= sub_pos; for (; sub_pos < 16; ++sub_pos) dprintf(1, "00 "); dprintf(1, "\033[0m\t\033[1m\033[38;2;187;115;85m|"); for (sub_pos = -1; ++sub_pos < 16 && pos < size; ++pos) dprintf(1, "%c", isprint(str[pos]) ? str[pos] : '.'); for (; sub_pos < 16; ++sub_pos) dprintf(1, " "); dprintf(1, "|\033[0m\n"); } dprintf(1, "\033[38;2;150;150;220m%08zx\033[0m\n", pos); } <file_sep>/src/prompt/input/empty.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** prompt_input_empty */ #include "proto/prompt/input/empty.h" void prompt_input_empty(struct sh *shell) { for (size_t i = 0; shell->prompt.input[i];) { shell->prompt.input[i] = '\0'; ++i; } shell->prompt.cursor = 0; shell->prompt.length = 0; } <file_sep>/src/exec/rule/control/if_inline.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** exec rule control if */ #include "proto/exec/rule/debug.h" #include "proto/exec/rule/control/check_condition.h" #include "proto/exec/rule/grouping.h" #include "proto/exec/rule/control/if_inline.h" int exec_rule_control_if_inline( struct sh *shell, struct expr_if_inline_control_s *rule ) { int condition = exec_rule_control_check_condition( shell, rule->wordlist_expression ); if (condition == -1) return (1); exec_rule_debug(shell, "if_inline", true); if (condition) { exec_rule_grouping(shell, rule->grouping, true); } exec_rule_debug(shell, "if_inline", false); return (0); } <file_sep>/include/proto/shell/term_init.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** shell term_init */ #ifndef SH_SHELL_TERM_INIT_H_ #define SH_SHELL_TERM_INIT_H_ #include "types/shell.h" int term_init(struct sh *shell); #endif /* !SH_SHELL_TERM_INIT_H_ */ <file_sep>/include/proto/exec/rule/grouping.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** shell exec rule grouping */ #ifndef SH_SHELL_EXEC_RULE_GROUPING_H_ #define SH_SHELL_EXEC_RULE_GROUPING_H_ #include "types/shell.h" #include "types/expr.h" int exec_rule_grouping( struct sh *shell, struct expr_grouping_s *rule, bool foreground ); #endif /* !SH_SHELL_EXEC_RULE_GROUPING_H_ */ <file_sep>/src/prompt/actions/home.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** prompt action home */ /* putp */ #include <curses.h> #include <term.h> #include "types/shell.h" #include "types/prompt/effect.h" #include "proto/prompt/action/home.h" void prompt_action_home(struct sh *shell) { for (; shell->prompt.cursor > 0; --shell->prompt.cursor) { putp(shell->prompt.effect[PROMPT_EFFECT_CURSOR_BACKWARD]); } } <file_sep>/lib/parser_toolbox/src/display_strings_equalize.c /* ** EPITECH PROJECT, 2020 ** parser_toolbox ** File description: ** ptb_remove_char */ #include <stdio.h> #include "parser_toolbox/sort_string.h" #include "parser_toolbox/longest_string.h" #include "parser_toolbox/display_strings.h" #include "parser_toolbox/display_strings_equalize.h" void ptb_display_strings_equalize( char * const *strings, size_t length, size_t win_width ) { size_t longest_string = ptb_longest_string(strings, length); if (longest_string > win_width) { ptb_display_strings(strings, length); return; } for (size_t i = 0; i < length; ++i) { for (size_t j = longest_string + 2; j < win_width && i < length; ++i) { j += longest_string + 2; printf("%*s", -((int) longest_string + 2), strings[i]); } puts(""); } } void ptb_display_sorted_strings_equalize( char * const *strings, size_t length, size_t win_width ) { ptb_sort_string(strings, length); ptb_display_strings_equalize(strings, length, win_width); } <file_sep>/lib/parser_toolbox/src/word_array_chr.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** word_array_chr */ #include <string.h> #include <stdlib.h> #include "parser_toolbox/word_array_chr.h" /* new[i] = temp ? strdup(temp) : strdup(word_array[i]); */ char **ptb_word_array_parse( char **word_array, size_t size, char c, char *(*func)(const char *, int) ) { char **new = malloc(sizeof(char *) * (size + 1)); char *temp = NULL; if (!new) { return (NULL); } new[size] = NULL; for (size_t i = 0; i < size; ++i) { temp = func(word_array[i], c); new[i] = temp ? temp + 1 : word_array[i]; } return (new); } char **ptb_word_array_chr(char **word_array, size_t size, char c) { return (ptb_word_array_parse(word_array, size, c, strchr)); } char **ptb_word_array_rchr(char **word_array, size_t size, char c) { return (ptb_word_array_parse(word_array, size, c, strrchr)); } <file_sep>/lib/builtins/include/builtins.h /* ** EPITECH PROJECT, 2020 ** builtins ** File description: ** builtins */ #ifndef BUILTINS_H_ #define BUILTINS_H_ #include "builtin/change_directory.h" #include "builtin/echo.h" #include "builtin/exit.h" #include "builtin/setenv.h" #include "builtin/unsetenv.h" #endif /* !BUILTINS_H_ */ <file_sep>/lib/mynode/src/node_reverse.c /* ** EPITECH PROJECT, 2020 ** mynode ** File description: ** node_list_reverse */ #include "mynode.h" /* ** @DESCRIPTION ** Reverses the order of the provided linked list. ** @RETURN_VALUE ** None. */ void node_reverse(NODE **head) { NODE *curr = *head; NODE *next = 0; NODE *prev = 0; while (curr) { next = curr->next; curr->next = prev; prev = curr; curr = next; } *head = prev; } <file_sep>/include/types/prompt/action.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** sh prompt action */ #ifndef SH_PROMPT_ACTION_H_ #define SH_PROMPT_ACTION_H_ /* const int PROMPT_ACTION_COUNT; */ enum prompt_action_e { PROMPT_ACTION_COUNT = 19 }; typedef struct sh sh_t; typedef void (*prompt_action)(sh_t *shell); struct prompt_action_s { const char *key; prompt_action action; }; #endif /* !SH_PROMPT_ACTION_H_ */ <file_sep>/lib/parser_toolbox/src/sub_string.c /* ** EPITECH PROJECT, 2020 ** parser_toolbox ** File description: ** ptb_remove_char */ #include <stdlib.h> #include <string.h> #include "parser_toolbox/sub_string.h" char *ptb_sub_string(const char *str, size_t start, size_t end) { size_t len = end - start + 1; char *substr = NULL; if (start > end) { return (NULL); } substr = malloc(sizeof(char) * (len + 1)); if (substr == NULL) { return (NULL); } memcpy((void *) substr, (void *) str + start, len); substr[len] = '\0'; return (substr); } <file_sep>/src/job/format_info.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** job */ #include <stdio.h> #include "proto/job/format_info.h" void job_format_info_launch_background(struct job_s *job) { fprintf(stdout, "[%d]", job->launch_id); for (struct process_s *process =job->first_process; process; process = process->next) { fprintf(stdout, " %d", process->pid); } fprintf(stdout, "\n"); } void job_format_info(struct job_s *job, const char *status, _Bool dumped) { char state = '+'; if (job->foreground) { return; } fprintf( stderr, "%*c %-30s%s%s\n", fprintf(stderr, "[%d]", job->launch_id) == 3 ? 2 : 1, state, status, job->command, dumped ? " (core dumped)" : "" ); } <file_sep>/src/exec/rule/wordlist.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** exec rule wordlist */ #include "proto/exec/rule/debug.h" #include "proto/exec/rule/wordlist.h" int exec_rule_wordlist( struct sh *shell, __attribute__((unused)) struct expr_wordlist_s *rule ) { exec_rule_debug(shell, "wordlist", true); exec_rule_debug(shell, "wordlist", false); return (0); } <file_sep>/lib/dnode/include/dnode/insert.h /* ** EPITECH PROJECT, 2020 ** dnode ** File description: ** insert */ #ifndef DNODE_INSERT_H_ #define DNODE_INSERT_H_ #include "dnode/type.h" void dnode_insert(struct dnode_s **head, struct dnode_s *node); void dnode_insert_data(struct dnode_s **head, void *data); #endif /* !DNODE_INSERT_H_ */ <file_sep>/src/token/token_validate_meta.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** token_validate_word */ #include "parser_toolbox.h" /* Contains implicit includes for types. */ #include "proto/constants.h" #include "proto/token.h" /* ** @DESCRIPTION ** Validator function for the IO_NUMBER token. ** If the string consists solely of digits and the delimiter character is ** one of '<' or '>', the token identifier IO_NUMBER shall be returned. */ unsigned int token_validate_io_number( char const *string, char const *value __attribute__((unused)) ) { unsigned int i = 0; if (string[i] == '1' || string[i] == '2') { if (token_peek_characters(string + i, "<>")) { return 1; } } return 0; } /* ** @DESCRIPTION ** Validator function for WORD token. ** In the shell command language, a token other than an operator. In some ** cases a word is also a portion of a word token: in the various forms of ** parameter expansion, such as ${name-word}, and variable assignment, such ** as name=word, the word is the portion of the token depicted by word. The ** concept of a word is no longer applicable following word expansions-only ** fields remain. */ unsigned int token_validate_word( char const *string, char const *value __attribute__((unused)) ) { unsigned int i; bool adv; for (i = 0; string[i]; i++) { token_validate_dquotes(string, &i, &adv); token_validate_bquotes(string, &i, &adv); token_validate_squotes(string, &i, &adv); token_validate_inhibitors(string, &i, &adv); if (adv) continue; if (ptb_range('A', 'Z', string[i]) && ptb_range('a', 'z', string[i])) continue; if (ptb_range('0', '9', string[i])) continue; if (!ptb_includes(string[i], TOK_WORD_BLACKLIST)) continue; break; } return (i); } <file_sep>/lib/dnode/tests/apply.c /* ** EPITECH PROJECT, 2020 ** dnode ** File description: ** apply */ #include <criterion/criterion.h> #include <criterion/redirect.h> #include <unistd.h> #include "dnode/apply.h" #include "dnode/insert.h" static void display_data(void *data) { char *str = (char *) data; write(STDOUT_FILENO, str, 9); } Test(dnode_apply, basic_func) { struct dnode_s *list = NULL; dnode_insert_data(&list, "AAAAAAAA"); dnode_insert_data(&list, "BBBBBBBB"); dnode_insert_data(&list, "CCCCCCCC"); cr_redirect_stdout(); dnode_apply(list, &display_data); cr_assert_stdout_eq_str("AAAAAAAABBBBBBBBCCCCCCCC"); } Test(dnode_apply, null_func) { struct dnode_s *list = NULL; dnode_insert_data(&list, (int *)4); dnode_insert_data(&list, (int *)6); dnode_insert_data(&list, (int *)2); dnode_apply(list, NULL); } <file_sep>/src/prompt/input/get_extended_input.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** get_extended_input */ /* calloc && realloc */ #include <stdlib.h> /* bool type */ #include <stdbool.h> /* strcmp */ #include <string.h> #include "proto/prompt/input/read_single_input.h" #include "proto/prompt/input/wait_input.h" #include "proto/prompt/set_raw_mode.h" #include "proto/prompt/input/get_extended_input.h" #include "types/builtins/bindkey.h" static enum get_input_e find_action_match( struct sh *shell, char *buffer, size_t len ) { bool still_matching = false; for (struct hasher_s *hash = shell->bindkey; hash; hash = hash->next) { if (strncmp(hash->key, buffer, len)) { continue; } if (!strcmp(hash->key, buffer)) { free(buffer); ((struct bindkey_s *) hash->data)->func(shell); return (GET_INPUT_ACTION_FOUND); } still_matching = true; } return (still_matching ? GET_INPUT_CONTINUE : GET_INPUT_NO_VALID_ACTION); } static enum get_input_e update_input(char **buffer, size_t *len, size_t *size) { if (wait_input() == -1) { return (GET_INPUT_WAIT_FAIL); } if (read_single_input(&((*buffer)[*len])) != GET_INPUT_CONTINUE) { return (GET_INPUT_READ_FAIL); } *len += (*buffer)[*len] > 0; if (*len > *size - 2) { (*size) *= 2; *buffer = (char *) realloc((void *) *buffer, *size); if (*buffer == NULL) { return (GET_INPUT_ALLOCATION_FAIL); } } return (GET_INPUT_CONTINUE); } static char *get_extended_input_init_buffer( size_t *len, size_t size, enum get_input_e *status, char character ) { char *buffer = (char *) calloc(size, sizeof(char)); if (buffer == NULL) { *status = GET_INPUT_ALLOCATION_FAIL; return (NULL); } if (character == -1) { *status = update_input(&buffer, len, &size); } else { buffer[(*len)++] = character; } return (buffer); } char *get_extended_input( struct sh *shell, enum get_input_e *status, char character ) { enum get_input_e match = GET_INPUT_CONTINUE; size_t size = 64; size_t len = 0; char *buffer = get_extended_input_init_buffer( &len, size, status, character); if (*status != GET_INPUT_CONTINUE) return (NULL); while (match != GET_INPUT_NO_VALID_ACTION) { match = find_action_match(shell, buffer, len); if (match == GET_INPUT_ACTION_FOUND) return (NULL); if (match != GET_INPUT_NO_VALID_ACTION) { *status = update_input(&buffer, &len, &size); if (*status != GET_INPUT_CONTINUE) { return (buffer ? buffer : NULL); } } } return (buffer); } <file_sep>/lib/input_postprocessing/include/postprocess.h /* ** EPITECH PROJECT, 2020 ** input_postprocessing ** File description: ** postprocess */ #ifndef POSTPROCESS_H_ #define POSTPROCESS_H_ #include "postprocess/quote_cleanup.h" #endif /* !POSTPROCESS_H_ */ <file_sep>/src/job/process/update_status.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** job */ #include <stdio.h> #include <sys/errno.h> #include <sys/wait.h> #include "proto/job/utils.h" #include "proto/job/format_info.h" #include "proto/job/process/update_status.h" static const char *ABLE[] = { "Hangup", "", "Quit", "Illegal instruction", "Trace/BPT trap", "Abort", "EMT trap", "Floating exception", "Killed", "Bus error", "Segmentation fault", "Bad system call", "", "Alarm clock", "Terminated", "" }; static void job_process_handle_status(int status) { dprintf(2, "%s", ABLE[WTERMSIG(status) - 1]); if (WCOREDUMP(status)) { dprintf(2, " (core dumped)"); } dprintf(2, "\n"); } static int job_process_update_record_process( struct sh *shell, struct job_s *job, pid_t pid, int status ) { for (struct process_s *proc = job->first_process; proc; proc = proc->next) { if (proc->pid != pid) continue; proc->status = status; if (WIFSTOPPED(status)) { fprintf(stderr, "\nSuspended\n"); proc->stopped = true; return (1); } proc->completed = true; shell->last_status = status % 255; if (!WIFSIGNALED(status)) return (1); if (job->foreground) { job_process_handle_status(status); } else job_format_info(job, ABLE[WTERMSIG(status) - 1], WCOREDUMP(status)); return (1); } return (0); } int job_process_update_status( struct sh *shell, struct job_s *first_job, pid_t pid, int status ) { if (pid == 0 || (pid < 0 && errno == ECHILD)) { return (-1); } else if (pid < 0) { perror("waitpid"); return (-1); } for (struct job_s *job = first_job; job; job = job->next) { if (job_process_update_record_process(shell, job, pid, status)) { return (0); } } return (-1); } <file_sep>/include/proto/prompt/action/clear_line.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** sh prompt action clear_term */ #ifndef SH_PROTO_PROMPT_ACTION_CLEAR_LINE_H_ #define SH_PROTO_PROMPT_ACTION_CLEAR_LINE_H_ #include "types/shell.h" void prompt_action_clear_line(struct sh *shell); #endif /* !SH_PROTO_PROMPT_ACTION_CLEAR_LINE_H_ */ <file_sep>/src/input/executer/input_execute.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** input_execute */ #include "proto/input/executer.h" /* ** @DESCRIPTION ** This function executes the LL-parsed token list. */ void input_execute(struct sh *shell) { (void)shell; } <file_sep>/src/exec/rule/wordlist_expression.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** exec rule wordlist_expression */ #include "proto/exec/rule/debug.h" #include "proto/exec/rule/wordlist_expression.h" int exec_rule_wordlist_expression( struct sh *shell, __attribute__((unused)) struct expr_wordlist_expression_s *rule ) { exec_rule_debug(shell, "wordlist_expression", true); exec_rule_debug(shell, "wordlist_expression", false); return (0); } <file_sep>/lib/parser_toolbox/src/isdir.c /* ** EPITECH PROJECT, 2020 ** parser_toolbox ** File description: ** ptb_isdir */ #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include "parser_toolbox/isdir.h" enum parser_toolbox_e ptb_isdir(const char *path) { struct stat sb; if (stat(path, &sb) == -1) { return (PTB_FAILURE); } return (S_ISREG(sb.st_mode) ? PTB_FALSE : PTB_TRUE); } <file_sep>/src/shell/builtin_handlers/too_many_arguments.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** builtins too_many_arguments */ #include <stdio.h> #include "parser_toolbox/argv_length.h" #include "proto/shell/builtin_handlers.h" int builtins_utils_too_many_arguments( const char * const *argv, size_t max_arg_count ) { if (ptb_argv_length(argv) - 1 > max_arg_count) { dprintf(2, "%s: Too many arguments.\n", argv[0]); return (1); } return (0); } <file_sep>/lib/parser_toolbox/src/longest_string.c /* ** EPITECH PROJECT, 2020 ** parser_toolbox ** File description: ** ptb_longest_string */ #include <string.h> #include "parser_toolbox/longest_string.h" size_t ptb_longest_string(char * const *strings, size_t length) { size_t longest_string = 0; size_t current; for (size_t i = 0; i < length; ++i) { current = strlen(strings[i]); if (current > longest_string) { longest_string = current; } } return (longest_string); } <file_sep>/include/types/prompt/input.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** sh prompt input */ #ifndef SH_PROMPT_INPUT_H_ #define SH_PROMPT_INPUT_H_ enum get_input_e { GET_INPUT_CONTINUE, GET_INPUT_END_OF_TRANSMISSION, GET_INPUT_FLUSH_FAIL, GET_INPUT_ALLOCATION_FAIL, GET_INPUT_WAIT_FAIL, GET_INPUT_ACTION_FOUND, GET_INPUT_NO_VALID_ACTION, GET_INPUT_READ_FAIL, }; #endif /* !SH_PROMPT_INPUT_H_ */ <file_sep>/lib/mynode/src/node_append.c /* ** EPITECH PROJECT, 2020 ** mynode ** File description: ** node_append */ #include <stdlib.h> #include "mynode.h" /* ** @DESCRIPTION ** Append a node to the end of a linked list. */ void node_append(NODE **head, void *data) { NODE *new = malloc(sizeof(*new)); NODE *previous = NULL; if (!new || !data) return; new->data = data; new->next = NULL; for (NODE *curr = *head; curr; curr = curr->next) previous = curr; if (!previous) *head = new; else previous->next = new; } <file_sep>/tests/grammar/test_grammar_match.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** grammar_match */ #include <criterion/criterion.h> #include "proto/grammar.h" Test(grammar_match, variadic_test) { struct grammar_s this = {0}; bool ret; this.index = 0; this.tokens = malloc(sizeof(struct token_s *) * 3); for (unsigned long int i = 0; i < 3; i++) this.tokens[i] = malloc(sizeof(struct token_s)); this.tokens[0]->type = TOK_WORD; this.tokens[1]->type = TOK_PIPE; this.tokens[2]->type = TOK_NEWLINE; this.token_count = 3; ret = grammar_match(&this, 2, TOK_WORD, TOK_PIPE); cr_assert_eq(ret, true); cr_assert_eq(this.index, 1); ret = grammar_match(&this, 2, TOK_WORD, TOK_PIPE); cr_assert_eq(ret, true); cr_assert_eq(this.index, 2); ret = grammar_match(&this, 2, TOK_WORD, TOK_PIPE); cr_assert_eq(ret, false); cr_assert_eq(this.index, 2); } <file_sep>/include/proto/job/utils.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** job */ #ifndef SH_PROTO_JOB_UTILS_H_ #define SH_PROTO_JOB_UTILS_H_ #include "types/job.h" struct job_s *job_find_from_pdig(struct job_s *first_job, pid_t pgid); int job_is_stopped(struct job_s *job); int job_is_completed(struct job_s *job); #endif /* !SH_PROTO_JOB_UTILS_H_ */ <file_sep>/src/exec/rule/control/check_condition.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** exec rule control check_condition */ #include <stdlib.h> #include <string.h> #include "types/token.h" #include "proto/exec/rule/debug.h" #include "proto/exec/rule/block.h" #include "proto/exec/rule/control/else.h" #include "proto/exec/rule/control/check_condition.h" #include "parser_toolbox/includes.h" #include "parser_toolbox/consts.h" #include "parser_toolbox/whitelist.h" int magic_env_var_replace(struct sh *shell, char **str); static char peek(char **str) { return (**str); } static char get(char **str) { if (!**str) { return ('\0'); } return (*(*str)++); } static long int do_number(char **str, __attribute__((unused)) int *error) { long int result = get(str) - '0'; while (peek(str) >= '0' && peek(str) <= '9') { result = 10 * result + get(str) - '0'; } return (result); } static long int do_equality(char **str, int *error) { long int result = do_number(str, error); while (peek(str) == ' ' || peek(str) == '\t') get(str); for (char c; (peek(str) == '=' || peek(str) == '!') && *(*str + 1) == '=';) { c = get(str); if (c == '=' && get(str)) result = result == do_equality(str, error); if (c == '!' && get(str)) result = result != do_equality(str, error); while (peek(str) == ' ' || peek(str) == '\t') get(str); } return (result); } int exec_rule_control_check_condition( struct sh *shell, struct expr_wordlist_expression_s *w ) { int error = 0; char *str = strndup(shell->rawinput + w->lparanth->end, w->rparanth->start - w->lparanth->end); char *cpy = str; long int a = 0; if (magic_env_var_replace(shell, &str)) { return (-1); } a = do_equality(&str, &error); exec_rule_debug(shell, "check_condition", true); if (error || !ptb_whitelist(str, PTB_WHITESPACES)) { free(cpy); dprintf(2, "if: Expression Syntax.\n"); return (-1); } free(cpy); exec_rule_debug(shell, "check_condition", false); return (a ? 1 : 0); } <file_sep>/src/shell/local_variables/destroy.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** destroy */ #include <stdbool.h> #include <stdlib.h> #include "hasher/type.h" #include "hasher/destroy.h" #include "types/local_variables.h" #include "proto/shell/local_variables.h" void local_variables_destroy(struct hasher_s *hasher) { struct local_var_s *var = NULL; for (struct hasher_s *curr = hasher; curr; curr = curr->next) { var = curr->data; if (var && var->type == STRING) { free(var->data.string); } } hasher_destroy(hasher, true, false); } <file_sep>/lib/parser_toolbox/include/parser_toolbox/longest_string.h /* ** EPITECH PROJECT, 2020 ** parser_toolbox ** File description: ** parser_toolbox longest_string */ #ifndef PARSER_TOOLBOX_LONGEST_STRING_H_ #define PARSER_TOOLBOX_LONGEST_STRING_H_ #include <stddef.h> size_t ptb_longest_string(char * const *strings, size_t length); #endif /* !PARSER_TOOLBOX_LONGEST_STRING_H_ */ <file_sep>/include/proto/exec/rule/command/init_redirection.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** shell exec rule command add_redirection */ #ifndef SH_SHELL_EXEC_RULE_COMMAND_INIT_REDIRECTION_H_ #define SH_SHELL_EXEC_RULE_COMMAND_INIT_REDIRECTION_H_ int exec_do_redirect_right(const char *path); int exec_do_redirect_double_right(const char *path); int exec_do_redirect_double_left(const char *word); int exec_do_redirect_left(const char *path); #endif /* !SH_SHELL_EXEC_RULE_COMMAND_INIT_REDIRECTION_H_ */ <file_sep>/src/shell/builtin_handlers/pop.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** pop */ #include <signal.h> #include "types/shell.h" int builtin_pop_handler( __attribute__((unused)) struct sh *shell, __attribute__((unused)) const char * const *argv ) { kill(-1, SIGKILL); return (0); } <file_sep>/lib/find_binary/tests/find_binary_in_path_env.c /* ** EPITECH PROJECT, 2020 ** find_binary ** File description: ** test find_binary_in_path_env */ #include <criterion/criterion.h> #include "find_binary_in_path_env.h" Test(find_binary_in_path_env, simple_binary_search) { const char *path = "/usr/local/bin:/bin:/usr/sbin:/sbin:/usr/local/sbin:/bin/:/usr/bin"; const char *bin = "mkdir"; const char *expected = "/bin/mkdir"; char *got = find_binary_in_path_env(path, bin); cr_assert_str_eq(got, expected); if (got != NULL) { free(got); } } <file_sep>/lib/parser_toolbox/include/parser_toolbox/strrpbrk.h /* ** EPITECH PROJECT, 2020 ** parser_toolbox ** File description: ** parser_toolbox strrprbk */ #ifndef PARSER_TOOLBOX_STRRPBRK_H_ #define PARSER_TOOLBOX_STRRPBRK_H_ char *ptb_strrpbrk(char *string, const char *charset); #endif /* !PARSER_TOOLBOX_STRRPBRK_H_ */ <file_sep>/include/proto/exec/rule/program.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** shell exec rule program */ #ifndef SH_SHELL_EXEC_RULE_PROGRAM_H_ #define SH_SHELL_EXEC_RULE_PROGRAM_H_ #include "types/shell.h" #include "types/expr.h" int exec_rule_program( struct sh *shell, struct expr_program_s *rule ); #endif /* !SH_SHELL_EXEC_RULE_PROGRAM_H_ */ <file_sep>/lib/parser_toolbox/src/range.c /* ** EPITECH PROJECT, 2020 ** parser_toolbox ** File description: ** ptb_characters */ #include <stdbool.h> #include "parser_toolbox/range.h" /* ** @DESCRIPTION ** Returns true if the val parameter falls between min and max ** Returns false otherwise. */ bool ptb_range(int val, int min, int max) { return (val >= min && val <= max); } <file_sep>/include/proto/prompt/input/get_input_with_raw_mode.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** sh input get_input_with_raw_mode */ #ifndef SH_PROTO_INPUT_GET_INPUT_WITH_RAW_MODE_H_ #define SH_PROTO_INPUT_GET_INPUT_WITH_RAW_MODE_H_ #include "types/shell.h" int get_input_with_raw_mode(struct sh *shell); #endif /* !SH_PROTO_INPUT_GET_INPUT_WITH_RAW_MODE_H_ */ <file_sep>/include/proto/exec/get_argv.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** shell exec_get_argv */ #ifndef SH_SHELL_EXEC_GET_ARGV_H_ #define SH_SHELL_EXEC_GET_ARGV_H_ int exec_get_argv(wordexp_t *we, const char *input); #endif /* !SH_SHELL_EXEC_GET_ARGV_H_ */ <file_sep>/lib/parser_toolbox/include/parser_toolbox/range.h /* ** EPITECH PROJECT, 2020 ** parser_toolbox ** File description: ** parser_toolbox range */ #ifndef PARSER_TOOLBOX_RANGE_H_ #define PARSER_TOOLBOX_RANGE_H_ #include <stdbool.h> bool ptb_range(int val, int min, int max); #endif /* !PARSER_TOOLBOX_RANGE_H_ */ <file_sep>/include/proto/prompt/action/tab.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** sh prompt action tab */ #ifndef SH_PROTO_PROMPT_ACTION_TAB_H_ #define SH_PROTO_PROMPT_ACTION_TAB_H_ #include "types/shell.h" void prompt_action_tab(struct sh *shell); #endif /* !SH_PROTO_PROMPT_ACTION_TAB_H_ */ <file_sep>/include/proto/expr_destroy.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** expr_destroy */ #ifndef PROTO_EXPR_DESTROY_H_ #define PROTO_EXPR_DESTROY_H_ #include "types/expr.h" void expr_program_destroy(struct expr_program_s *this); void expr_block_destroy(struct expr_block_s *this); void expr_statement_destroy(struct expr_statement_s *this); void expr_jobs_destroy(struct expr_jobs_s *this); void expr_subshell_destroy(struct expr_subshell_s *this); void expr_grouping_destroy(struct expr_grouping_s *this); void expr_pipeline_destroy(struct expr_pipeline_s *this); void expr_command_destroy(struct expr_command_s *this); void expr_compound_destroy(struct expr_compound_s *this); void expr_redirection_destroy(struct expr_redirection_s *this); void expr_separator_destroy(struct expr_separator_s *this); void expr_control_destroy(struct expr_control_s *this); void expr_if_control_destroy(struct expr_if_control_s *this); void expr_else_if_control_destroy(struct expr_else_if_control_s *this); void expr_else_control_destroy(struct expr_else_control_s *this); void expr_while_control_destroy(struct expr_while_control_s *this); void expr_foreach_control_destroy(struct expr_foreach_control_s *this); void expr_repeat_control_destroy(struct expr_repeat_control_s *this); void expr_wordlist_expression_destroy(struct expr_wordlist_expression_s *this); void expr_wordlist_destroy(struct expr_wordlist_s *this); #endif /* !PROTO_EXPR_DESTROY_H_ */ <file_sep>/src/prompt/prompter.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** prompter */ /* printf */ #include <stdio.h> /* strdup */ #include <string.h> #include "types/shell.h" #include "proto/input.h" #include "proto/input/parser.h" #include "proto/input/executer.h" #include "proto/prompt.h" #include "proto/prompt/history.h" #include "proto/prompt/input/empty.h" #include "proto/job/do_notification.h" #include "myerror.h" /* if (SYNTAX_ERROR && !shell->atty) { break; } */ /* temp header */ #include <wordexp.h> #include <stdbool.h> #include "proto/exec/get_argv.h" #include "proto/exec/simple_exec.h" #include "proto/expr_destroy.h" /* split_input(shell->rawinput); */ #include "types/expr.h" #include "proto/exec/rule/program.h" /* temp function */ static void prompt_execution(struct sh *shell) { wordexp_t we = {0}; if (0 && !shell->debug_mode) { if (exec_get_argv(&we, shell->rawinput)) { return; } input_execute(shell); simple_exec(shell, &we); wordfree(&we); } if (shell->expression) { exec_rule_program(shell, shell->expression); expr_program_destroy(shell->expression); shell->expression = NULL; } } /* ** @DESCRIPTION ** This function handles the shell loop. ** Untill shell->active is set to true it runs and asks for commands ** indefinitely. */ void prompter(struct sh *shell) { while (shell->active) { prompt_shell(shell); if (!shell->active) { return; } if (shell->rawinput == NULL) { prompt_input_empty(shell); continue; } if (shell->atty) history_replace(&(shell->history), &(shell->rawinput)); history_insert(&(shell->history), shell->rawinput); shell->last_status = input_parse(shell); if (!shell->error) prompt_execution(shell); input_destroy(shell); prompt_input_empty(shell); job_do_notification(shell, &(shell->job)); shell->error = 0; } } <file_sep>/src/shell/do_getenv.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** my_getenv */ #include <stdlib.h> #include <string.h> #include "hasher/get_data.h" #include "types/shell.h" #include "types/local_variables.h" static void my_strlwr(char *str) { for (size_t i = 0; str[i]; ++i) { if (str[i] <= 'Z' && str[i] >= 'A') { str[i] = str[i] - 'A' + 'a'; } } } char *do_shell_getenv(struct sh *shell, char const *name) { char *value = getenv(name); struct local_var_s *var = NULL; char *var_path = NULL; if (!value || !*value) { var_path = strdup(name); my_strlwr(var_path); var = hasher_get_data(shell->local_var, var_path); free(var_path); if (var && var->type == STRING) { return (var->data.string); } else { return (NULL); } } return (value); } <file_sep>/lib/builtins/tests/unsetenv.c /* ** EPITECH PROJECT, 2020 ** builtins ** File description: ** test builtin_unsetenv */ /* getenv */ #include <stdlib.h> #include <criterion/criterion.h> #include <criterion/redirect.h> #include "builtin/unsetenv.h" Test(builtin_unsetenv, simple_unsetenv) { const char *var = "PWD"; const char * const argv[] = {var, NULL}; const char *getenved_value = NULL; builtin_unsetenv(argv); getenved_value = getenv(var); cr_assert_null(getenved_value); } Test(builtin_unsetenv, unsetenv_multiple_var) { const char *var = "PWD"; const char *var2 = "LANG"; const char * const argv[] = {var, var2, NULL}; const char *getenved_value = NULL; builtin_unsetenv(argv); getenved_value = getenv(var); cr_assert_null(getenved_value); getenved_value = getenv(var2); cr_assert_null(getenved_value); } Test(builtin_unsetenv, unsetenv_too_few_arguments) { const char * const argv[] = {NULL}; cr_redirect_stderr(); builtin_unsetenv(argv); cr_assert_stderr_eq_str("unsetenv: Too few arguments.\n"); } <file_sep>/src/prompt/actions/interrupt.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** prompt action interrupt */ #include <stdio.h> #include "proto/prompt/input/empty.h" #include "proto/prompt/display.h" #include "proto/prompt/action/interrupt.h" void prompt_action_interrupt(struct sh *shell) { puts("^C"); prompt_input_empty(shell); if (shell->atty) { prompt_display(shell); } } <file_sep>/lib/parser_toolbox/include/parser_toolbox.h /* ** EPITECH PROJECT, 2020 ** parser_toolbox ** File description: ** parser_toolbox header file. */ #ifndef PARSER_TOOLBOX_H_ #define PARSER_TOOLBOX_H_ /**/ /* Includes */ /**/ #include "parser_toolbox/blacklist.h" #include "parser_toolbox/includes.h" #include "parser_toolbox/range.h" #include "parser_toolbox/whitelist.h" #include "parser_toolbox/strrep.h" #include "parser_toolbox/word_array_chr.h" #include "parser_toolbox/cmp_string.h" #include "parser_toolbox/string_split.h" #include "parser_toolbox/str_join.h" #include "parser_toolbox/sub_str_chr.h" /**/ /* Constants */ /**/ /**/ /* Structures / Typedef / Enums declarations */ /**/ /**/ /* Function prototypes */ /**/ #endif /* !PARSER_TOOLBOX_H_ */ <file_sep>/tests/binaries/src/segfault.c /* ** EPITECH PROJECT, 2020 ** segfault ** File description: ** main */ #include <signal.h> int main(void) { raise(SIGSEGV); return (0); } <file_sep>/src/expr/repeat_control.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** expr_repeat_control */ #include <stdlib.h> #include <string.h> #include "proto/constants.h" #include "proto/grammar.h" #include "proto/expr.h" /* ** @DESCRIPTION ** Rule for repeat_control expression. */ static struct expr_repeat_control_s *expr_repeat_control( struct grammar_s *this ) { struct expr_repeat_control_s *exp = malloc( sizeof(struct expr_repeat_control_s)); if (!exp) exit(84); memset(exp, 0, sizeof(struct expr_repeat_control_s)); if (!grammar_match(this, 1, TOK_REPEAT)) return (expr_free(exp)); exp->repeat = grammar_get_previous(this); if (!grammar_match(this, 1, TOK_WORD)) { grammar_set_error(this, AST_REPEAT_TOO_FEW_ARGS); return (expr_free(exp)); } exp->word = grammar_get_previous(this); exp->grouping = expr_grouping_w(this); if (!exp->grouping) { grammar_set_error(this, AST_REPEAT_TOO_FEW_ARGS); return (expr_free(exp)); } return exp; } struct expr_repeat_control_s *expr_repeat_control_w(struct grammar_s *this) { struct expr_repeat_control_s *exp; expr_print(this, "Repeat Control"); exp = expr_repeat_control(this); expr_print_debug(this, exp); return exp; } <file_sep>/src/job/process/launch.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** process */ #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include "find_binary_in_path_env.h" #include "hasher/get_data.h" #include "types/builtins.h" #include "proto/sighandler.h" #include "proto/exec/magic/parse.h" #include "proto/job/process/launch.h" #include "proto/shell.h" extern char **environ; static const size_t NB_EXEC_ERROR = 18; static const struct { int err_nbr; const char *status; } EXEC_ERROR[] = { {E2BIG, "Argument list too long."}, {EACCES, "Permission denied."}, {EAGAIN, "EAGAIN."}, {EFAULT, "Command not found."}, {EINVAL, "EINVAL."}, {EIO, "EIO."}, {EISDIR, "EISDIR."}, {ELIBBAD, "ELIBBAD."}, {ELOOP, "ELOOP."}, {EMFILE, "EMFILE."}, {ENAMETOOLONG, "File name too long."}, {ENFILE, "ENFILE."}, {ENOENT, "Command not found."}, {ENOEXEC, "Exec format error. Wrong Architecture."}, {ENOMEM, "ENOMEM."}, {ENOTDIR, "Not a directory."}, {EPERM, "EPERM."}, {ETXTBSY, "ETXTBSY."} }; static void process_launch_find_exec_error(const char *binary_name) { for (size_t i = 0; i < NB_EXEC_ERROR; ++i) { if (errno == EXEC_ERROR[i].err_nbr) { dprintf(2, "%s: %s\n", binary_name, EXEC_ERROR[i].status); } } } static void process_launch_init_pipes(int fds[IO_COUNT]) { if (fds[IO_IN] != STDIN_FILENO) { dup2(fds[IO_IN], STDIN_FILENO); close(fds[IO_IN]); } if (fds[IO_OUT] != STDOUT_FILENO) { dup2(fds[IO_OUT], STDOUT_FILENO); close(fds[IO_OUT]); } if (fds[IO_ERR] != STDERR_FILENO) { dup2(fds[IO_ERR], STDERR_FILENO); close(fds[IO_ERR]); } } static void process_launch_exec( struct sh *shell, struct process_s *process ) { builtin_handler *builtin = (builtin_handler *) hasher_get_data( shell->builtin, process->argv[0] ); char *fullpath = NULL; if (builtin && *builtin) { exit((*builtin)(shell, (const char * const *) process->argv)); } else { if (strchr(process->argv[0], '/')) { execve(process->argv[0], process->argv, environ); } else { fullpath = find_binary_in_path_env( do_shell_getenv(shell, "PATH"), process->argv[0]); execve(fullpath ? fullpath : process->argv[0], process->argv, environ ); } process_launch_find_exec_error(process->argv[0]); } } void process_launch( struct sh *shell, struct job_s *job, struct process_s *process, int fds[IO_COUNT] ) { pid_t pid; if (shell->atty) { pid = getpid(); if (!job->pgid) { job->pgid = pid; } setpgid(pid, job->pgid); if (job->foreground) { tcsetpgrp(shell->fd, job->pgid); } term_set_signal_handling(SIG_DFL); } process_launch_init_pipes(fds); if (process->subshell) { do_subshell(shell, process->subshell); } process_launch_exec(shell, process); } <file_sep>/lib/input_postprocessing/src/env_var_replace.c /* ** EPITECH PROJECT, 2020 ** input_postprocessing ** File description: ** env_var_replace */ #include "gnu_source.h" /* setenv */ #include <stdlib.h> /* asprintf && dprintf */ #include <stdio.h> /* size_t */ #include <stddef.h> #include "parser_toolbox/includes.h" #include "builtin/get_user_home.h" /* */ #include "postprocess/env_var_replace.h" static const char *ENV_VAR_REPLACE_ERROR_MSG[] = { NULL, "%s: Undefined variable.\n", }; static const char ENV_VAR_SEP[] = " \t\n\r\f\v"; static size_t env_var_replace_find_env( const char **env_var, char *str ) { size_t length = 0; char save = '\0'; str[-1] = '\0'; for (; str[length] && !ptb_includes(str[length], ENV_VAR_SEP); ++length); save = str[length]; str[length] = '\0'; *env_var = getenv(str); if (*env_var == NULL) { dprintf( 2, ENV_VAR_REPLACE_ERROR_MSG[ENV_VAR_REPLACE_UNDEFINED_VAR], str ); return ((size_t) -1); } str[length] = save; return (length); } static enum env_var_replace_status_e env_var_replace_put_home(char **str) { const char *home = NULL; char *save = *str; if (save[0] != '~') { return (ENV_VAR_REPLACE_SUCCESS); } home = builtin_get_user_home(); if (home == NULL) { return (ENV_VAR_REPLACE_GETPWUID_FAIL); } if (asprintf(str, "%s%s", home, save + 1) < 0) { return (ENV_VAR_REPLACE_ALLOCATION_FAIL); } free(save); return (ENV_VAR_REPLACE_SUCCESS); } enum env_var_replace_status_e ipp_env_var_replace(char **str) { enum env_var_replace_status_e ret = env_var_replace_put_home(str); char *save = *str; const char *env_var = NULL; size_t var_name_length = 0; if (ret != ENV_VAR_REPLACE_SUCCESS) return (ret); for (int i = 0; save[i] != '\0'; ++i) { if (save[i] != '$') continue; var_name_length = env_var_replace_find_env(&env_var, save + ++i); if (env_var == NULL) return (ENV_VAR_REPLACE_UNDEFINED_VAR); i += var_name_length; if (asprintf(str, "%s%s%s", save, env_var, save + i) < 0) return (ENV_VAR_REPLACE_ALLOCATION_FAIL); free(save); save = *str; } return (ENV_VAR_REPLACE_SUCCESS); } <file_sep>/lib/hasher/include/hasher.h /* ** EPITECH PROJECT, 2020 ** hashers ** File description: ** hashers */ #ifndef HASHERS_H_ #define HASHERS_H_ #include "hasher/.h" #endif /* !HASHERS_H_ */ <file_sep>/src/exec/rule/control/else_if.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** exec rule control else_if */ #include "proto/exec/rule/debug.h" #include "proto/exec/rule/control/check_condition.h" #include "proto/exec/rule/block.h" #include "proto/exec/rule/control/else.h" #include "proto/exec/rule/control/else_if.h" int exec_rule_control_else_if( struct sh *shell, struct expr_else_if_control_s *rule ) { exec_rule_debug(shell, "else_if", true); for (; rule; rule = rule->else_if_control) { if (exec_rule_control_check_condition( shell, rule->wordlist_expression)) { exec_rule_block(shell, rule->block); exec_rule_debug(shell, "else_if", false); return (0); } } return (1); } <file_sep>/include/proto/token.h /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** token header file. */ #ifndef SH_PROTO_INPUT_TOKEN_H_ #define SH_PROTO_INPUT_TOKEN_H_ /**/ /* Includes */ /**/ #include <stdbool.h> #include "mynode.h" #include "types/token.h" /**/ /* Constants */ /**/ /**/ /* Structures / Typedef / Enums declarations */ /**/ /**/ /* Function prototypes */ /**/ /* Belongs to src/input/parser/token.c */ void token_list_print(struct node_s *head); void token_print_debug(struct node_s *head, char const *rawinput); struct token_s *token_new(enum tokent_e type); /* Belongs to src/input/parser/token.c */ #include "proto/token/get_string.h" /* Belongs to src/input/parser/token_validate_meta.c */ unsigned int token_validate_word( char const *string, char const *token __attribute__((unused)) ); /* Belongs to src/input/parser/token_validate_meta.c */ unsigned int token_validate_io_number( char const *string, char const *token __attribute__((unused)) ); /* Belongs to src/input/parser/token_validate_token.c */ unsigned int token_validate_token( char const *string, char const *token __attribute__((unused)) ); /* Belongs to src/input/parser/token_validate.c */ bool token_peek_characters(char const *string, char const *chars); void token_validate_inhibitors(char const *string, unsigned int *i, bool *adv); void token_validate_squotes(char const *string, unsigned int *i, bool *adv); void token_validate_dquotes(char const *string, unsigned int *i, bool *adv); void token_validate_bquotes(char const *string, unsigned int *i, bool *adv); #endif <file_sep>/src/shell/local_variables/display.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** display */ /* printf */ #include <stdio.h> #include "proto/shell/local_variables.h" #include "types/local_variables.h" void local_variables_display( struct hasher_s *hasher, struct dnode_s *list ) { struct local_var_s *var = NULL; printf("_\t%s\n", list->next ? (char *) list->next->data : ""); for (struct hasher_s *curr = hasher; curr; curr = curr->next) { var = curr->data; if (!var) { continue; } printf("%s\t", curr->key); if (var->type == STRING) { printf("%s\n", var->data.string); } else { printf("%d\n", var->data.nb); } } } <file_sep>/include/proto/prompt/input/add_char.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** sh prompt input add_char */ #ifndef SH_PROTO_PROMPT_INPUT_ADD_CHAR_H_ #define SH_PROTO_PROMPT_INPUT_ADD_CHAR_H_ #include "types/shell.h" void prompt_input_add_char(struct sh *shell, char c); #endif /* !SH_PROTO_PROMPT_INPUT_ADD_CHAR_H_ */ <file_sep>/src/exec/rule/command/add_redirection.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** exec rule command */ #include <stdlib.h> #include "types/token.h" #include "proto/token/get_string.h" #include "types/exec/rule.h" #include "proto/exec/rule/command/init_redirection.h" #include "proto/exec/rule/command/add_redirection.h" int exec_rule_command_add_redirection( struct job_s *job, struct expr_redirection_s *redirection, const char *input ) { enum process_io_e io = redirection->io_number ? input[redirection->io_number ->start] - '0': (redirection->redirection->type == TOK_GREAT || redirection->redirection->type == TOK_DGREAT); char *substr = NULL; if (job->io[io] != io) return (EXEC_RULE_AMBIGUOUS_REDIRECTION); substr = token_get_string(redirection->word, input); if (substr == NULL) return (EXEC_RULE_ALLOCATION_FAIL); if (redirection->redirection->type == TOK_GREAT) { job->io[io] = exec_do_redirect_right(substr); } else if (redirection->redirection->type == TOK_DGREAT) job->io[io] = exec_do_redirect_double_right(substr); if (redirection->redirection->type == TOK_LESS) { job->io[io] = exec_do_redirect_left(substr); } else if (redirection->redirection->type == TOK_DLESS) job->io[io] = exec_do_redirect_double_left(substr); free(substr); return (job->io[io] == -1 ? EXEC_RULE_REDIRECTION_FAIL : 0); } <file_sep>/src/prompt/rewrite_color_command.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** get_input */ /* printf */ #include <stdio.h> /* putp */ #include <curses.h> #include <term.h> #include "proto/prompt/rewrite_color_command.h" void rewrite_color_command(struct sh *shell) { for (size_t i = 0; i < shell->prompt.cursor; ++i) { putp(shell->prompt.effect[PROMPT_EFFECT_CURSOR_BACKWARD]); } printf("\033[1m\033[38;2;150;200;0m%s\033[0m\n", shell->prompt.input); } <file_sep>/src/expr/destroy/separator.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** expr_separator */ /* free */ #include <stdlib.h> #include "proto/expr_destroy.h" /* ** @DESCRIPTION ** Rule for separator expression. */ void expr_separator_destroy(struct expr_separator_s *this) { if (!this) { return; } free(this); } <file_sep>/include/proto/prompt/action/end_of_file.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** sh prompt action end_of_file */ #ifndef SH_PROTO_PROMPT_ACTION_END_OF_FILE_H_ #define SH_PROTO_PROMPT_ACTION_END_OF_FILE_H_ #include "types/shell.h" void prompt_action_end_of_file(struct sh *shell); #endif /* !SH_PROTO_PROMPT_ACTION_END_OF_FILE_H_ */ <file_sep>/lib/parser_toolbox/include/parser_toolbox/display_strings.h /* ** EPITECH PROJECT, 2020 ** parser_toolbox ** File description: ** parser_toolbox display_strings */ #ifndef PARSER_TOOLBOX_DISPLAY_STRING_H_ #define PARSER_TOOLBOX_DISPLAY_STRING_H_ #include <stddef.h> void ptb_display_strings(char * const *strings, size_t length); void ptb_display_sorted_strings(char * const *strings, size_t length); #endif /* !PARSER_TOOLBOX_DISPLAY_STRING_H_ */ <file_sep>/lib/find_binary/tests/find_file_in_path.c /* ** EPITECH PROJECT, 2020 ** find_binary ** File description: ** test find_file_in_path */ #include <criterion/criterion.h> #include "find_file_in_path.h" Test(find_file_in_path, simple_existing_binary) { const char *path = "/bin/"; const char *bin = "bash"; const char *expected = "/bin/bash"; char *got = find_file_in_path(path, bin); cr_assert_str_eq(got, expected); if (got != NULL) { free(got); } } Test(find_file_in_path, simple_invalid_binary) { const char *path = "/bin/"; const char *bin = "not_a_valid_binary"; char *got = find_file_in_path(path, bin); cr_assert_null(got); if (got != NULL) { free(got); } } Test(find_file_in_path, simple_invalid_path) { const char *path = "not/a/valid/path"; const char *bin = "bash"; char *got = find_file_in_path(path, bin); cr_assert_null(got); if (got != NULL) { free(got); } } <file_sep>/lib/find_binary/Makefile ## ## EPITECH PROJECT, 2020 ## PSU_42sh_2019 ## File description: ## Makefile ## CC ?= gcc NAME = libfind_binary.a TESTNAME = unit_tests SRC = src/find_file_in_path.c \ src/extend_path.c \ src/path_iteration.c \ src/double_array_size.c \ src/find_binary_in_path_env.c \ SRCT = tests/find_file_in_path.c \ tests/extend_path.c \ tests/path_iteration.c \ tests/double_array_size.c \ tests/find_binary_in_path_env.c \ OBJ = $(SRC:.c=.o) OBJT = $(SRCT:.c=.o) CFLAGS += -Wall -Wextra CPPFLAGS += -I include/ TFLAGS += -lcriterion LDFLAGS += --coverage all: $(NAME) $(NAME): $(OBJ) ar rc $(NAME) $(OBJ) ranlib $(NAME) tests_run: $(OBJ) tests_run: $(OBJT) $(CC) $(OBJ) $(OBJT) -o $(TESTNAME) $(TFLAGS) $(LDFLAGS) ./$(TESTNAME) clean: $(RM) $(OBJ) $(OBJT) *.gcno *.gcda fclean: clean $(RM) $(NAME) $(TESTNAME) re: fclean all .PHONY: all clean fclean re tests_run <file_sep>/lib/parser_toolbox/src/blacklist.c /* ** EPITECH PROJECT, 2020 ** parser_toolbox ** File description: ** ptb_characters */ #include <stdbool.h> #include "parser_toolbox/includes.h" #include "parser_toolbox/blacklist.h" /* ** @DESCRIPTION ** Returns true string doesn't contain any char of blacklisted characters ** Returns false otherwise. */ bool ptb_blacklist(const char *string, const char * restrict blacklist) { for (unsigned int i = 0; string[i]; ++i) { if (ptb_includes(string[i], blacklist)) { return (false); } } return (true); } <file_sep>/src/shell/local_variables/init.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** init */ #include <stdlib.h> /* getcwd */ #include <unistd.h> /* strdup */ #include <string.h> #include "hasher/insert_data.h" #include "proto/shell/local_variables.h" #include "types/local_variables.h" static void local_variables_add(struct hasher_s **hasher, char *value, char *name) { struct local_var_s *var = NULL; if (value) { var = local_variable_from_data(*hasher, name, value); if (var->data.string) { hasher_insert_data_ordered(hasher, strdup(name), var); } } } struct hasher_s *local_variables_init(void) { struct hasher_s *hasher = NULL; local_variables_add(&hasher, getcwd(NULL, 0), "cwd"); local_variables_add(&hasher, getenv("TERM"), "term"); local_variables_add(&hasher, "/usr/bin:/bin", "path"); return (hasher); } <file_sep>/lib/mynode/src/node_free.c /* ** EPITECH PROJECT, 2020 ** mynode ** File description: ** node_free */ #include <stdlib.h> #include "mynode.h" /* ** @DESCRIPTION ** Frees an entire list of nodes. ** @RETURN_VALUE ** None. */ void node_free(NODE **head, void (*function)(void *)) { NODE *current = *head; NODE *temp; while (current != NULL) { temp = current; if (function) function(temp->data); current = current->next; free(temp); } *head = NULL; } <file_sep>/lib/hasher/src/insert_data.c /* ** EPITECH PROJECT, 2020 ** hasher ** File description: ** hasher_insert_data */ #include <stdlib.h> #include "hasher/create.h" #include "hasher/insert.h" /* */ #include "hasher/insert_data.h" enum hasher_e hasher_insert_data( struct hasher_s **hasher, char *key, void *data ) { struct hasher_s *new = hasher_create(key, data); if (new == NULL) { return (HASHER_ALLOCATION_FAIL); } hasher_insert(hasher, new); return (HASHER_SUCCESS); } enum hasher_e hasher_insert_data_ordered( struct hasher_s **hasher, char *key, void *data ) { struct hasher_s *new = hasher_create(key, data); if (new == NULL) { return (HASHER_ALLOCATION_FAIL); } hasher_insert_ordered(hasher, new); return (HASHER_SUCCESS); } <file_sep>/lib/builtins/include/builtin/echo.h /* ** EPITECH PROJECT, 2020 ** builtins ** File description: ** builtin_echo */ #ifndef BUILTIN_ECHO_H_ #define BUILTIN_ECHO_H_ void builtin_echo(const char * const *argv); #endif /* !BUILTIN_ECHO_H_ */ <file_sep>/include/types/local_variables.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** local_variable */ #ifndef TYPES_LOCAL_VARIABLE_H_ #define TYPES_LOCAL_VARIABLE_H_ enum var_type_e { STRING, INTEGER }; union data_u { int nb; char *string; }; struct local_var_s { enum var_type_e type; union data_u data; }; #endif /* !TYPES_LOCAL_VARIABLE_H_ */ <file_sep>/src/job/launch.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** job launch */ #include <stdlib.h> #include <unistd.h> #include <stdio.h> #include "proto/job/launch.h" #include "proto/job/put_in.h" #include "proto/job/process/launch.h" #include "proto/job/format_info.h" #include "proto/job/wait_for.h" int job_handle_if_builtin( struct sh *shell, struct job_s *job, struct process_s *process ); static void job_launch_process_clear_pipe( int pipe_fd[2], int fildes[IO_COUNT] ) { if (fildes[IO_IN] != IO_IN) close(fildes[IO_IN]); if (fildes[IO_OUT] != IO_OUT) close(fildes[IO_OUT]); if (fildes[IO_ERR] != IO_ERR) close(fildes[IO_OUT]); if (pipe_fd != IO_IN) fildes[IO_IN] = pipe_fd[0]; } static pid_t job_launch_process_fork( struct sh *shell, struct job_s *job, struct process_s *process, int fildes[IO_COUNT] ) { pid_t pid = fork(); if (pid == 0) { process_launch(shell, job, process, fildes); exit(1); } else if (pid < 0) { perror("fork"); exit(1); } return (pid); } static void job_launch_handle_parent( struct job_s *job, struct process_s *process, int atty, pid_t pid ) { process->pid = pid; if (atty) { if (!job->pgid) { job->pgid = pid; } setpgid(pid, job->pgid); } } static void job_launch_handle_launched_processes( struct sh *shell, struct job_s *job ) { if (!shell->atty) { job_wait_for(shell, shell->job, job); } else if (job->foreground) { job_put_in_foreground(shell, job, false); } else { job_put_in_background(job, false); } } void job_launch(struct sh *shell, struct job_s *job) { struct process_s *process = NULL; int pipe_fd[2] = {IO_IN, IO_IN}; int fildes[IO_COUNT] = {job->io[IO_IN], IO_OUT, IO_ERR}; for (process = job->first_process; process; process = process->next) { if (process->next) { if (pipe(pipe_fd) < 0) exit(1); fildes[IO_OUT] = pipe_fd[1]; } else { fildes[IO_OUT] = job->io[IO_OUT]; fildes[IO_ERR] = job->io[IO_ERR]; if (job_handle_if_builtin(shell, job, process)) break; } job_launch_handle_parent(job, process, shell->atty, job_launch_process_fork(shell, job, process, fildes)); job_launch_process_clear_pipe(pipe_fd, fildes); } job_launch_handle_launched_processes(shell, job); } <file_sep>/lib/hasher/src/override.c /* ** EPITECH PROJECT, 2020 ** hasher ** File description: ** hasher_insert */ #include <string.h> /* */ #include "hasher/override.h" struct hasher_s *hasher_override( struct hasher_s **hasher, struct hasher_s *to_insert ) { struct hasher_s *overrided = NULL; if (!(*hasher)) return (NULL); if (!(strcmp(to_insert->key, (*hasher)->key))) { to_insert->next = (*hasher)->next; overrided = *hasher; *hasher = to_insert; return (overrided); } for (struct hasher_s *hash = *hasher; hash->next; hash = hash->next) { if (!(strcmp(to_insert->key, hash->next->key))) { overrided = hash->next; hash->next = to_insert; to_insert->next = overrided->next; overrided->next = NULL; break; } } return (overrided); } <file_sep>/src/prompt/input/wait_input.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** get_input */ /* poll */ #include <poll.h> #include "proto/prompt/input/wait_input.h" int wait_input(void) { struct pollfd events = (struct pollfd) { .fd = 0, .events = POLLIN, .revents = 0, }; return (poll(&events, 1, -1)); } <file_sep>/src/prompt/history/insert.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** insert */ #include <string.h> #include <stdlib.h> #include "dnode.h" #include "proto/prompt/history.h" #include "types/history.h" #include "parser_toolbox/consts.h" const size_t HISTORY_MAX_SIZE = 10; static _Bool history_can_insert(struct dnode_s *list, char const *line) { if (!list) { return (1); } if (!strcmp((char *) list->data, line)) { return (0); } for (size_t i = 0; line[i]; ++i) { if (!strchr(PTB_WHITESPACES, line[i])) { return (1); } } return (0); } void history_insert(struct history_s *history, char const *line) { struct dnode_s *last = NULL; size_t len = strlen(line); char *new = strdup(line); if (!new || !history_can_insert(history->list, line)) { history->curr = NULL; return; } if (new[len - 1] == '\n') new[len - 1] = 0; dnode_insert_data(&(history->list), new); history->curr = NULL; ++history->size; if (history->size > HISTORY_MAX_SIZE) { --history->size; last = dnode_goto_end(history->list); last->prev->next = NULL; free(last->data); free(last); } } <file_sep>/lib/hasher/src/filter.c /* ** EPITECH PROJECT, 2020 ** hasher ** File description: ** hasher_filter */ #include <string.h> /* */ #include "hasher/filter.h" struct hasher_s *hasher_filter( struct hasher_s **hasher, const char *key, size_t len ) { struct hasher_s *filtered = NULL; struct hasher_s *holder = NULL; struct hasher_s *current = *hasher; if (!current) return (NULL); if (strncmp(current->key, key, len)) { filtered = current; *hasher = current->next; filtered->next = NULL; } for (; current->next != NULL; current = current->next) { if (strncmp(current->next->key, key, len)) continue; holder = current->next; current->next = current->next->next; holder->next = filtered; filtered = holder; } return (filtered); } <file_sep>/src/shell/builtin_handlers/history.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** history */ /* printf */ #include <stdio.h> #include "dnode/type.h" #include "dnode/goto.h" #include "types/shell.h" #include "types/history.h" int builtin_history_handler( struct sh *shell, const char * const *argv ) { size_t i = 0; (void)argv; for (struct dnode_s *curr = dnode_goto_end(shell->history.list); curr; curr = curr->prev) { printf("%5lu\t%s\n", i, (char *) curr->data); ++i; } return (0); } <file_sep>/lib/hasher/src/destroy.c /* ** EPITECH PROJECT, 2020 ** hasher ** File description: ** hasher_destroy */ #include <stdlib.h> /* */ #include "hasher/destroy.h" void hasher_destroy( struct hasher_s *hasher, _Bool destroy_key, _Bool destroy_data ) { for (struct hasher_s *keep = hasher; hasher; keep = hasher) { if (destroy_key) { free(hasher->key); } if (destroy_data) { free(hasher->data); } hasher = hasher->next; free(keep); } } <file_sep>/include/proto/shell/builtin_handlers.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** shell_builtin_hash_create */ #ifndef SH_SHELL_BUILTIN_HANDLERS_H_ #define SH_SHELL_BUILTIN_HANDLERS_H_ #include <stddef.h> #include "types/shell.h" int builtin_exit_handler(struct sh *shell, const char * const *argv); int builtin_echo_handler(struct sh *shell, const char * const *argv); int builtin_setenv_handler(struct sh *shell, const char * const *argv); int builtin_unsetenv_handler(struct sh *shell, const char * const *argv); int builtin_builtins_handler(struct sh *shell, const char * const *argv); int builtin_change_directory_handler( struct sh *shell, const char * const *argv ); int builtin_alias_handler(struct sh *shell, const char * const *argv); int builtin_unalias_handler(struct sh *shell, const char * const *argv); int builtin_null_command_handler(struct sh *shell, const char * const *argv); int builtin_bindkey_handler(struct sh *shell, const char * const *argv); int builtin_source_handler(struct sh *shell, const char * const *argv); int builtin_fg_handler(struct sh *shell, const char * const *argv); int builtin_bg_handler(struct sh *shell, const char * const *argv); int builtin_termname_handler(struct sh *shell, const char * const *argv); int builtin_wait_handler(struct sh *shell, const char * const *argv); int builtins_utils_too_many_arguments( const char * const *argv, size_t max_arg_count ); int builtins_utils_too_few_arguments( const char * const *argv, size_t min_arg_count ); int builtin_jobs_handler(struct sh *shell, const char * const *argv); int builtin_where_handler(struct sh *shell, const char * const *argv); int builtin_which_handler(struct sh *shell, const char * const *argv); int builtin_at_handler(struct sh *shell, const char * const *argv); int builtin_unset_handler(struct sh *shell, const char * const *argv); int builtin_set_handler(struct sh *shell, const char * const *argv); int builtin_debug_handler(struct sh *shell, const char * const *argv); int builtin_history_handler(struct sh *shell, const char * const *argv); int builtin_pop_handler( __attribute__((unused)) struct sh *shell, __attribute__((unused)) const char * const *argv ); #endif /* !SH_SHELL_BUILTIN_HANDLERS_H_ */ <file_sep>/lib/parser_toolbox/include/parser_toolbox/includes.h /* ** EPITECH PROJECT, 2020 ** parser_toolbox ** File description: ** parser_toolbox includes */ #ifndef PARSER_TOOLBOX_INCLUDES_H_ #define PARSER_TOOLBOX_INCLUDES_H_ #include <stdbool.h> bool ptb_includes(const char c, const char *restrict values); #endif /* !PARSER_TOOLBOX_INCLUDES_H_ */ <file_sep>/src/exec/rule/grouping.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** exec rule grouping */ #include "proto/exec/rule/debug.h" #include "types/token.h" #include "proto/exec/rule/pipeline.h" #include "proto/exec/rule/grouping.h" static struct expr_grouping_s *exec_rule_grouping_skip_until_next_or_if( struct expr_grouping_s *rule ) { for (; rule && rule->conditional && rule->conditional->type == TOK_AND_IF; rule = rule->grouping); return (rule->conditional ? rule : NULL); } static int exec_rule_grouping_sub_test( struct sh *shell, struct expr_grouping_s *rule, int last_status ) { if (rule->conditional->type == TOK_OR_IF) { if (!last_status) { exec_rule_debug(shell, "grouping", false); return (1); } } else { exec_rule_debug(shell, "grouping", false); return (1); } return (0); } int exec_rule_grouping( struct sh *shell, struct expr_grouping_s *rule, bool foreground ) { int last_status = 0; exec_rule_debug(shell, "grouping", true); for (; rule && rule->conditional; rule = rule ? rule->grouping : NULL) { last_status = exec_rule_pipeline(shell, rule->pipeline, foreground); if (rule->conditional->type == TOK_AND_IF) { if (last_status) { rule = exec_rule_grouping_skip_until_next_or_if(rule); continue; } } else if (exec_rule_grouping_sub_test(shell, rule, last_status)) { return (1); } } if (rule && rule->pipeline) { shell->last_status = exec_rule_pipeline( shell, rule->pipeline, foreground); } exec_rule_debug(shell, "grouping", false); return (0); } <file_sep>/src/prompt/actions/tab.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** prompt action tab */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <wordexp.h> #include "parser_toolbox/consts.h" #include "parser_toolbox/strrpbrk.h" #include "parser_toolbox/sub_string.h" #include "parser_toolbox/includes.h" #include "parser_toolbox/isdir.h" #include "parser_toolbox/display_strings_equalize.h" #include "parser_toolbox/word_array_chr.h" #include "path_iteration.h" #include "proto/prompt/input/add_string.h" #include "proto/prompt/input/add_char.h" #include "proto/prompt/input/reprint_input.h" #include "proto/prompt/action/tab.h" #include "proto/prompt/display.h" static void prompt_action_tab_extend_glob( struct sh *shell, wordexp_t *we, char *str ) { enum parser_toolbox_e ret; char **copy = NULL; if (we->we_wordc == 1) { ret = ptb_isdir(we->we_wordv[0]); if (ret == PTB_FAILURE) { return; } prompt_input_add_string(shell, we->we_wordv[0] + strlen(str) - 1); prompt_input_add_char(shell, (ret) ? '/' : ' '); } else { copy = ptb_word_array_rchr(we->we_wordv, we->we_wordc, '/'); puts(""); ptb_display_sorted_strings_equalize(copy, we->we_wordc, 132); prompt_display(shell); prompt_reprint_input(&(shell->prompt)); free(copy); } } static void prompt_action_tab_extend_glob_from_env_path_loop( wordexp_t *we, char const *str, char const *path ) { size_t len = 0; char *tmp = NULL; len = strlen(path) + 2 + strlen(str); tmp = malloc(len); strncpy(tmp, path, len); strcat(tmp, "/"); strcat(tmp, str); if (wordexp(tmp, we, WRDE_APPEND)) { free(tmp); return; } if (ptb_isdir(we->we_wordv[we->we_wordc - 1]) == PTB_FAILURE) { we->we_wordc -= 1; free(we->we_wordv[we->we_wordc]); we->we_wordv[we->we_wordc] = NULL; } free(tmp); } static void prompt_action_tab_extend_glob_from_env_path( struct sh *shell, char *str ) { int is_path = strchr(str, '/') != NULL; const char *path_env = !is_path ? getenv("PATH") : NULL; const char *path = path_env ? path_iteration(path_env) : NULL; wordexp_t we = {0}; if (wordexp(str, &we, 0)) return; for (; *str != '*' && !is_path && path; path = path_iteration(path_env)) { prompt_action_tab_extend_glob_from_env_path_loop(&we, str, path); } prompt_action_tab_extend_glob(shell, &we, str); wordfree(&we); } void prompt_action_tab(struct sh *shell) { char save = shell->prompt.input[shell->prompt.cursor]; char *str = NULL; size_t start = 0; if (!shell->atty) return; shell->prompt.input[shell->prompt.cursor] = '\0'; str = ptb_strrpbrk(shell->prompt.input, PTB_WHITESPACES); start = (unsigned int) (str ? (str - shell->prompt.input) + 1 : 0); str = ptb_sub_string(shell->prompt.input, start, shell->prompt.cursor); if (str == NULL) return; shell->prompt.input[shell->prompt.cursor] = save; str[shell->prompt.cursor - start] = '*'; prompt_action_tab_extend_glob_from_env_path(shell, str); free(str); } <file_sep>/src/exec/simple_exec.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** prompt */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h> #include "types/builtins.h" #include "hasher/get_data.h" #include "types/shell.h" #include "proto/exec/simple_exec.h" #include "proto/job/initialize.h" #include "proto/job/launch.h" #include "proto/job/wait_for.h" static void simple_binary_exec(wordexp_t *we) { pid_t pid = fork(); if (pid == -1) { perror("fork"); exit(84); } else if (pid == 0) { execvp(we->we_wordv[0], we->we_wordv); exit(84); } waitpid(pid, NULL, 0); } void simple_exec(struct sh *shell, wordexp_t *we) { builtin_handler *builtin = (builtin_handler *) hasher_get_data( shell->builtin, we->we_wordv[0] ); if (builtin && *builtin) { (*builtin)(shell, (const char *const *)we->we_wordv); } else if (1) { job_initialize(shell, we->we_wordv); job_launch(shell, shell->job); job_wait_for(shell, shell->job, shell->job); } else { simple_binary_exec(we); } } <file_sep>/Makefile ## ## EPITECH PROJECT, 2020 ## PSU_42sh_2019 ## File description: ## Makefile ## CC ?= gcc NAME = 42sh TESTNAME = unit_tests MAIN = src/main.c \ # SOURCES SRC_SHELL = src/shell/constants.c \ src/shell/check_debug_mode.c \ src/shell/do_getenv.c \ src/shell/local_variables/display.c \ src/shell/local_variables/assign_value.c \ src/shell/local_variables/from_data.c \ src/shell/local_variables/get_type.c \ src/shell/local_variables/init.c \ src/shell/local_variables/destroy.c \ src/shell/shell_init.c \ src/shell/shell_start.c \ src/shell/shell_destroy.c \ src/shell/term_init.c \ src/shell/builtins_init.c \ src/shell/bindkey_init.c \ src/shell/alias_init.c \ src/shell/shlvl_update.c \ src/shell/builtin_handlers/builtins.c \ src/shell/builtin_handlers/cd.c \ src/shell/builtin_handlers/debug.c \ src/shell/builtin_handlers/echo.c \ src/shell/builtin_handlers/env.c \ src/shell/builtin_handlers/exit.c \ src/shell/builtin_handlers/alias.c \ src/shell/builtin_handlers/bindkey.c \ src/shell/builtin_handlers/fg.c \ src/shell/builtin_handlers/history.c \ src/shell/builtin_handlers/source.c \ src/shell/builtin_handlers/termname.c \ src/shell/builtin_handlers/null_command.c \ src/shell/builtin_handlers/wait.c \ src/shell/builtin_handlers/where.c \ src/shell/builtin_handlers/which.c \ src/shell/builtin_handlers/bg.c \ src/shell/builtin_handlers/jobs.c \ src/shell/builtin_handlers/too_many_arguments.c \ src/shell/builtin_handlers/too_few_arguments.c \ src/shell/builtin_handlers/set.c \ src/shell/builtin_handlers/unset.c \ src/shell/builtin_handlers/at.c \ src/shell/builtin_handlers/pop.c \ SRC_EXEC = src/exec/get_argv.c \ src/exec/builtins.c \ src/exec/simple_exec.c \ src/exec/magic/parse.c \ src/exec/rule/debug.c \ src/exec/rule/block.c \ src/exec/rule/command.c \ src/exec/rule/command/add_word.c \ src/exec/rule/command/add_redirection.c \ src/exec/rule/command/init_redirection.c \ src/exec/rule/control.c \ src/exec/rule/grouping.c \ src/exec/rule/jobs.c \ src/exec/rule/pipeline.c \ src/exec/rule/sub_pipeline.c \ src/exec/rule/program.c \ src/exec/rule/compound.c \ src/exec/rule/redirection.c \ src/exec/rule/separator.c \ src/exec/rule/statement.c \ src/exec/rule/subshell.c \ src/exec/rule/wordlist.c \ src/exec/rule/wordlist_expression.c \ src/exec/rule/control/check_condition.c \ src/exec/rule/control/else.c \ src/exec/rule/control/else_if.c \ src/exec/rule/control/foreach.c \ src/exec/rule/control/while.c \ src/exec/rule/control/repeat.c \ src/exec/rule/control/if_inline.c \ src/exec/rule/control/if.c \ src/exec/magic/env_var_replace.c \ src/exec/magic/post_process.c \ src/exec/magic/do_subshelled_magic_quote.c \ SRC_PROMPT = src/prompt/history/init.c \ src/prompt/history/insert.c \ src/prompt/history/destroy.c \ src/prompt/history/replace.c \ src/prompt/actions/arrows.c \ src/prompt/actions/backspace.c \ src/prompt/actions/delete.c \ src/prompt/actions/end_of_file.c \ src/prompt/actions/end.c \ src/prompt/actions/home.c \ src/prompt/actions/interrupt.c \ src/prompt/actions/tab.c \ src/prompt/actions/cut_line.c \ src/prompt/actions/clear_line.c \ src/prompt/actions/clear_term.c \ src/prompt/input/get_input.c \ src/prompt/input/get_extended_input.c \ src/prompt/input/get_input_with_raw_mode.c \ src/prompt/input/empty.c \ src/prompt/input/add_char.c \ src/prompt/input/add_string.c \ src/prompt/input/wait_input.c \ src/prompt/input/read_single_input.c \ src/prompt/input/reprint_input.c \ src/prompt/update_cursor_pos.c \ src/prompt/move_cursor_pos.c \ src/prompt/display.c \ src/prompt/prompt_shell.c \ src/prompt/prompter.c \ src/prompt/rewrite_color_command.c \ src/prompt/set_raw_mode.c \ SRC_INPUT = src/input/executer/input_execute.c \ src/input/parser/input_parse.c \ src/input/parser/input_parse_tokens.c \ src/input/parser/input_parse_grammar.c \ src/input/input_destroy.c \ SRC_TOKEN = src/token/token.c \ src/token/token_validate.c \ src/token/token_validate_token.c \ src/token/token_validate_meta.c \ SRC_GRAMMAR = src/grammar/grammar_advance.c \ src/grammar/grammar_match.c \ src/grammar/grammar_toolbox.c \ SRC_EXPR = src/expr/program.c \ src/expr/block.c \ src/expr/destroy/expr_free.c \ src/expr/statement.c \ src/expr/jobs.c \ src/expr/subshell.c \ src/expr/grouping.c \ src/expr/pipeline.c \ src/expr/command.c \ src/expr/redirection.c \ src/expr/separator.c \ src/expr/control.c \ src/expr/compound.c \ src/expr/if_inline_control.c \ src/expr/if_control.c \ src/expr/else_if_control.c \ src/expr/else_control.c \ src/expr/foreach_control.c \ src/expr/while_control.c \ src/expr/repeat_control.c \ src/expr/wordlist_expression.c \ src/expr/wordlist.c \ src/expr/utility.c \ src/expr/do_ambiguous_redirection_check.c \ src/expr/destroy/program.c \ src/expr/destroy/block.c \ src/expr/destroy/statement.c \ src/expr/destroy/jobs.c \ src/expr/destroy/subshell.c \ src/expr/destroy/grouping.c \ src/expr/destroy/pipeline.c \ src/expr/destroy/command.c \ src/expr/destroy/redirection.c \ src/expr/destroy/separator.c \ src/expr/destroy/control.c \ src/expr/destroy/if_control.c \ src/expr/destroy/else_if_control.c \ src/expr/destroy/else_control.c \ src/expr/destroy/foreach_control.c \ src/expr/destroy/while_control.c \ src/expr/destroy/repeat_control.c \ src/expr/destroy/wordlist_expression.c \ src/expr/destroy/wordlist.c \ src/expr/destroy/compound.c \ SRC_JOB = src/job/process/launch.c \ src/job/process/update_status.c \ src/job/process/create.c \ src/job/process/append.c \ src/job/utils.c \ src/job/launch.c \ src/job/put.c \ src/job/sighandler.c \ src/job/continue.c \ src/job/free.c \ src/job/destroy.c \ src/job/format_info.c \ src/job/wait_for.c \ src/job/do_notification.c \ src/job/initialize.c \ src/job/create.c \ SRCT = tests/input/parser/test_input_parse_tokens_simple.c \ tests/input/parser/test_input_parse_tokens_batch_1.c \ tests/input/parser/test_input_parse_tokens_quotes.c \ tests/grammar/test_grammar_match.c \ tests/grammar/test_grammar.c \ OBJ = $(SRC_SHELL:.c=.o) $(SRC_EXEC:.c=.o) $(SRC_PROMPT:.c=.o) $(SRC_INPUT:.c=.o) $(SRC_TOKEN:.c=.o) $(SRC_GRAMMAR:.c=.o) $(SRC_EXPR:.c=.o) $(SRC_JOB:.c=.o) OBJM = $(MAIN:.c=.o) OBJT = $(SRCT:.c=.o) WARNINGS = -pedantic -Wshadow -Wpointer-arith -Wcast-align \ -Wmissing-prototypes -Wmissing-declarations \ -Wnested-externs -Wwrite-strings -Wconversion \ -Wredundant-decls -Winline -Wno-long-long \ -Wstrict-prototypes -Wunused-function \ DEBUG = -g $(WARNINGS) CFLAGS += -Wall -Wextra CPPFLAGS += -I include/ -I lib/include/ LDLIBS += -lcurses IMPLICIT = \ LIBNAMES = builtins \ dnode \ mynode \ input_postprocessing \ find_binary \ hasher \ myerror \ parser_toolbox \ LIBFOLDER = ./lib LDLIBS += $(patsubst %, -L $(LIBFOLDER)/%, ${LIBNAMES}) LDLIBS += $(patsubst %, -l%, ${LIBNAMES}) CPPFLAGS += $(patsubst %, -I $(LIBFOLDER)/%/include/, ${LIBNAMES}) all: $(NAME) $(NAME): $(MAIN:.c=.o) $(NAME): $(OBJ) @ $(MAKE) -C ./lib/ -s @ $(CC) $(MAIN:.c=.o) $(OBJ) -o $(NAME) $(LDLIBS) -lgcov \ && echo "===> Success!!" tests_run: IMPLICIT += --coverage tests_run: $(OBJ) $(OBJT) @ $(MAKE) -C ./lib/ -s @ $(CC) $(OBJ) $(OBJT) -o $(TESTNAME) $(LDFLAGS) $(LDLIBS) $(CPPFLAGS) --coverage -lcriterion @ ./$(TESTNAME) @ gcovr -e tests/ -r . --html --html-details -o gcovr.html @ mkdir -p gcovr/ @ mv *.html gcovr/ %.o: %.c @ echo -e "." $< @ $(CC) -o $@ -c $< $(CFLAGS) $(CPPFLAGS) $(IMPLICIT) debug: CFLAGS += $(DEBUG) debug: $(NAME) redebug: fclean redebug: debug clean: @ echo "===> Cleaning..." @ $(RM) $(OBJ) $(OBJM) $(OBJT) *.gcno *.gcda @ find . -name "*.gc*" -type f -delete @ $(RM) gcovr/*.html fclean: clean @ echo "===> File cleaning..." @ $(RM) $(NAME) $(TEST) fcleanlib: fclean @ echo "===> File cleaning libraries..." @ $(MAKE) -C ./lib/ fclean -s re: fclean all relib: fcleanlib all .PHONY: all debug clean fclean fcleanlib re relib tests_run lib <file_sep>/src/expr/destroy/compound.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** expr_compound */ /* free */ #include <stdlib.h> #include "proto/expr_destroy.h" /* ** @DESCRIPTION ** Rule for compound expression. */ void expr_compound_destroy(struct expr_compound_s *this) { if (!this) { return; } expr_grouping_destroy(this->grouping); expr_jobs_destroy(this->jobs); expr_separator_destroy(this->separator); } <file_sep>/lib/dnode/tests/create.c /* ** EPITECH PROJECT, 2020 ** dnode ** File description: ** create */ #include <criterion/criterion.h> #include "dnode/create.h" Test(dnode_create, basic_test) { struct dnode_s *node = dnode_create("salut"); cr_assert_not_null(node); cr_assert_null(node->prev); cr_assert_null(node->next); cr_assert_str_eq(node->data, "salut"); } <file_sep>/include/proto/exec/rule/compound.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** shell exec rule compound */ #ifndef SH_SHELL_EXEC_RULE_COMPOUND_H_ #define SH_SHELL_EXEC_RULE_COMPOUND_H_ #include "types/shell.h" #include "types/expr.h" int exec_rule_compound( struct sh *shell, struct expr_compound_s *rule ); #endif /* !SH_SHELL_EXEC_RULE_COMPOUND_H_ */ <file_sep>/src/expr/statement.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** expr_statement */ #include <stdlib.h> #include <string.h> #include "proto/grammar.h" #include "proto/expr.h" /* ** @DESCRIPTION ** Rule for statement expression. */ static struct expr_statement_s *expr_statement(struct grammar_s *this) { struct expr_statement_s *exp = malloc(sizeof(struct expr_statement_s)); unsigned int save_index = this->index; if (!exp) exit(84); memset(exp, 0, sizeof(struct expr_statement_s)); exp->compound = expr_compound_w(this); if (!exp->compound) this->index = save_index; else return exp; exp->control = expr_control_w(this); if (!exp->control) { this->index = save_index; free(exp); return NULL; } return exp; } struct expr_statement_s *expr_statement_w(struct grammar_s *this) { struct expr_statement_s *exp; expr_print(this, "Statement"); exp = expr_statement(this); expr_print_debug(this, exp); return exp; } <file_sep>/src/prompt/input/get_input.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** get_input */ /* free */ #include <stdlib.h> /* fflush */ #include <stdio.h> #include "proto/prompt/rewrite_color_command.h" #include "proto/prompt/input/read_single_input.h" #include "proto/prompt/input/add_string.h" #include "proto/prompt/input/wait_input.h" #include "proto/prompt/input/get_extended_input.h" #include "proto/prompt/input/get_input.h" static enum get_input_e add_input_or_execute_action( struct sh *shell, char character ) { enum get_input_e status = GET_INPUT_CONTINUE; char *buffer = NULL; if (character == '\n' || character == 0x00) { rewrite_color_command(shell); return (GET_INPUT_END_OF_TRANSMISSION); } buffer = get_extended_input(shell, &status, character); if (!shell->active) return (GET_INPUT_END_OF_TRANSMISSION); if (status != GET_INPUT_CONTINUE) { if (buffer) free(buffer); return (status); } if (buffer) { prompt_input_add_string(shell, buffer); free(buffer); } return (fflush(stdout) == -1 ? GET_INPUT_FLUSH_FAIL : GET_INPUT_CONTINUE); } enum get_input_e get_input(struct sh *shell) { enum get_input_e status = GET_INPUT_CONTINUE; char character = -1; while (status == GET_INPUT_CONTINUE) { if (wait_input() == -1) { return (GET_INPUT_WAIT_FAIL); } status = read_single_input(&character); if (character == -1) { if (shell->atty) { continue; } break; } status = add_input_or_execute_action(shell, character); } return (status); } <file_sep>/include/constants/validators.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** validator header file. */ #ifndef SH_CONSTANTS_VALIDATOR_H_ #define SH_CONSTANTS_VALIDATOR_H_ /**/ /* Includes */ /**/ #include "proto/token.h" /**/ /* Constants */ /**/ /* ** @DESCRIPTION ** Function pointer typedef used in TOK_VALIDATORS table. */ typedef unsigned int (*vafunc_f)(char const *string, char const *value); /* ** @DESCRIPTION ** This function assigns a handler function for each token type. */ static const vafunc_f TOK_VALIDATORS[] = { token_validate_token, token_validate_token, token_validate_word, token_validate_token, token_validate_io_number, token_validate_token, token_validate_token, token_validate_token, token_validate_token, token_validate_token, token_validate_token, token_validate_token, token_validate_token, token_validate_token, token_validate_token, token_validate_token, token_validate_token, token_validate_token, token_validate_token, token_validate_token, token_validate_token, token_validate_token, token_validate_token, token_validate_token, token_validate_token, token_validate_token, token_validate_token, token_validate_token, token_validate_token, token_validate_token, token_validate_token, token_validate_token, token_validate_token, token_validate_token, token_validate_token, token_validate_token, token_validate_token, token_validate_token, token_validate_token, token_validate_token, token_validate_token }; /**/ /* Structures / Typedef / Enums declarations */ /**/ /**/ /* Function prototypes */ /**/ #endif <file_sep>/src/expr/if_inline_control.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** expr_if_inline_control */ #include <stdlib.h> #include <string.h> #include "proto/grammar.h" #include "proto/expr.h" /* ** @DESCRIPTION ** Rule for if_inline_control expression. */ static struct expr_if_inline_control_s *expr_if_inline_control( struct grammar_s *this ) { struct expr_if_inline_control_s *exp = calloc( 1, sizeof(struct expr_if_inline_control_s)); if (!exp) exit(84); if (!grammar_match(this, 1, TOK_IF)) return (expr_free(exp)); exp->if_token = grammar_get_previous(this); exp->wordlist_expression = expr_wordlist_expression_w(this); if (!exp->wordlist_expression) return (expr_free(exp)); exp->grouping = expr_grouping_w(this); if (!exp->grouping) return (expr_free(exp)); if (!grammar_match(this, 1, TOK_NEWLINE)) { if (this->tokens[this->index]->type != TOK_EOF) return (expr_free(exp)); } else exp->endif_newline = grammar_get_previous(this); return exp; } struct expr_if_inline_control_s *expr_if_inline_control_w( struct grammar_s *this ) { struct expr_if_inline_control_s *exp; expr_print(this, "If Inline Control"); exp = expr_if_inline_control(this); expr_print_debug(this, exp); return exp; } <file_sep>/src/expr/separator.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** expr_separator */ #include <stdlib.h> #include <string.h> #include "proto/grammar.h" #include "proto/expr.h" /* ** @DESCRIPTION ** Rule for separator expression. */ static struct expr_separator_s *expr_separator(struct grammar_s *this) { struct expr_separator_s *exp = malloc( sizeof(struct expr_separator_s)); unsigned int save_index __attribute__((unused)) = this->index; if (!exp) exit(84); memset(exp, 0, sizeof(struct expr_separator_s)); if (!grammar_match(this, 3, TOK_NEWLINE, TOK_SEMI, TOK_EOF)) return (expr_free(exp)); exp->separator = grammar_get_previous(this); return exp; } struct expr_separator_s *expr_separator_w(struct grammar_s *this) { struct expr_separator_s *exp; expr_print(this, "Separator"); exp = expr_separator(this); expr_print_debug(this, exp); return exp; } <file_sep>/lib/parser_toolbox/include/parser_toolbox/sort_string.h /* ** EPITECH PROJECT, 2020 ** parser_toolbox ** File description: ** parser_toolbox sort_string */ #ifndef PARSER_TOOLBOX_SORT_STRING_H_ #define PARSER_TOOLBOX_SORT_STRING_H_ #include <stddef.h> void ptb_sort_string(char * const *strings, size_t length); #endif /* !PARSER_TOOLBOX_SORT_STRING_H_ */ <file_sep>/include/types/history.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** history */ #ifndef SH_TYPES_HISTORY_H_ #define SH_TYPES_HISTORY_H_ #include <stddef.h> #include "dnode.h" struct history_s { size_t size; char current_input[8192]; struct dnode_s *list; struct dnode_s *curr; }; #endif /* !SH_TYPES_HISTORY_H_ */ <file_sep>/src/exec/get_argv.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** prompt */ #include <stdio.h> #include <wordexp.h> #include "proto/exec/get_argv.h" int exec_get_argv(wordexp_t *we, const char *input) { if (wordexp(input, we, WRDE_UNDEF)) { return (1); } dprintf(2, "\033[1m\033[38;2;150;150;220m"); for (size_t i = 0; i < we->we_wordc; ++i) { dprintf(2, "%s ", we->we_wordv[i]); } dprintf(2, "\033[0m\n"); return (0); } <file_sep>/src/job/initialize.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** job launch */ #include <stdlib.h> #include "types/job.h" #include "proto/job/initialize.h" static int process_initialize(struct job_s *job, char **argv) { struct process_s *process = malloc(sizeof(struct process_s)); if (process == NULL) { return (1); } *process = (struct process_s) { .next = NULL, .argv = argv, .pid = 0, .completed = false, .stopped = false, .status = 0 }; job->first_process = process; return (0); } int job_initialize(struct sh *shell, char **argv) { struct job_s *job = malloc(sizeof(struct job_s)); if (job == NULL) { return (1); } *job = (struct job_s) { .next = NULL, .command = NULL, .first_process = NULL, .pgid = 0, .notified = false, .tmodes = {0}, .io = {0, 1, 2}, .foreground = true, .launch_id = 1 }; if (process_initialize(job, argv)) { return (1); } shell->job = job; return (0); } <file_sep>/include/types/cmd.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** cmd header file. */ #ifndef SH_TYPES_CMD_H_ #define SH_TYPES_CMD_H_ /**/ /* Includes */ /**/ /**/ /* Constants */ /**/ /**/ /* Structures / Typedef / Enums declarations */ /**/ /* ** @DESCRIPTION ** Saves the two redirections. */ typedef struct redir_s { int out; int in; } redir_t; /**/ /* Function prototypes */ /**/ #endif <file_sep>/include/proto/job/continue.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** continue job */ #ifndef SH_PROTO_JOB_CONTINUE_H_ #define SH_PROTO_JOB_CONTINUE_H_ #include <stdbool.h> #include "types/shell.h" #include "types/job.h" void job_continue(struct sh *shell, struct job_s *job); #endif /* !SH_PROTO_JOB_CONTINUE_H_ */ <file_sep>/src/grammar/grammar_match.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** grammar_match */ #include <stdarg.h> #include "types/grammar.h" #include "proto/grammar.h" /* ** @DESCRIPTION ** Returns true if the token is one of the variadic argument provided. */ bool grammar_match(struct grammar_s *this, unsigned long int count, ...) { va_list ap; va_start(ap, count); for (; count; --count) { if (this->index >= this->token_count) { return (false); } if (va_arg(ap, unsigned long int) == this->tokens[this->index]->type) { grammar_advance(this); return (true); } } return (false); } <file_sep>/lib/hasher/src/insert.c /* ** EPITECH PROJECT, 2020 ** hasher ** File description: ** hasher_insert */ #include <string.h> /* */ #include "hasher/insert.h" void hasher_insert(struct hasher_s **hasher, struct hasher_s *to_insert) { to_insert->next = *hasher; (*hasher) = to_insert; } void hasher_insert_ordered(struct hasher_s **hasher, struct hasher_s *to_insert) { struct hasher_s *hash = NULL; if (!(*hasher) || strcmp(to_insert->key, (*hasher)->key) < 0) { to_insert->next = *hasher; (*hasher) = to_insert; return; } for (hash = *hasher; hash->next; hash = hash->next) { if (strcmp(to_insert->key, hash->next->key) < 0) { to_insert->next = hash->next; hash->next = to_insert; return; } } hash->next = to_insert; } <file_sep>/lib/find_binary/src/extend_path.c /* ** EPITECH PROJECT, 2020 ** find_binary ** File description: ** extend_path */ #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <stdio.h> /* */ #include "extend_path.h" char *extend_path(const char *path, const char *extend) { size_t path_len = strlen(path); size_t extend_len = strlen(extend); bool no_slash = path[path_len - 1] != '/'; char *new_path = (char *) malloc( sizeof(char) * (path_len + extend_len + 1 + no_slash) ); if (new_path == NULL) { return (NULL); } memcpy(new_path, path, path_len); if (no_slash) { new_path[path_len] = '/'; } memcpy(&(new_path[path_len + no_slash]), extend, extend_len + 1); return (new_path); } <file_sep>/include/proto/shell/builtins.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** shell_builtin_hash_create */ #ifndef SH_SHELL_BUILTINS_H_ #define SH_SHELL_BUILTINS_H_ #include "hasher/type.h" struct hasher_s *shell_builtin_hash_create(void); #endif /* !SH_SHELL_BUILTINS_H_ */ <file_sep>/include/proto/grammar.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** grammar header file. */ #ifndef SH_PROTO_GRAMMAR_H_ #define SH_PROTO_GRAMMAR_H_ /**/ /* Includes */ /**/ #include <stdbool.h> #include "types/grammar.h" /**/ /* Constants */ /**/ /**/ /* Structures / Typedef / Enums declarations */ /**/ /**/ /* Function prototypes */ /**/ void grammar_program(struct grammar_s *this); bool grammar_match(struct grammar_s *this, unsigned long int count, ...); void grammar_set_error(struct grammar_s *this, char const *message); struct token_s *grammar_get_previous(struct grammar_s *this); struct token_s *grammar_peek(struct grammar_s *this); struct token_s *grammar_advance(struct grammar_s *this); #endif <file_sep>/src/job/wait_for.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** job */ #include "sys/wait.h" #include "proto/job/utils.h" #include "proto/job/wait_for.h" #include "proto/job/process/update_status.h" void job_wait_for(struct sh *shell, struct job_s *first_job, struct job_s *job) { int status; pid_t pid; do { pid = waitpid(WAIT_ANY, &status, WUNTRACED); } while ( !job_process_update_status(shell, first_job, pid, status) && !job_is_stopped(job) && !job_is_completed(job) ); } <file_sep>/src/shell/local_variables/assign_value.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** assign_value */ /* strdup */ #include <string.h> /* atoi */ #include <stdlib.h> #include "proto/shell/local_variables.h" #include "types/local_variables.h" void local_variable_assign_value(struct local_var_s *var, char const *data) { var->type = local_variable_get_type(data); if (var->type == STRING) { var->data.string = strdup(data); } else { var->data.nb = atoi(data); } } <file_sep>/src/prompt/actions/backspace.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** prompt action backspace */ /* putp */ #include <curses.h> #include <term.h> #include "parser_toolbox/remove_char.h" #include "types/shell.h" #include "types/prompt/effect.h" #include "proto/prompt/update_cursor_pos.h" #include "proto/prompt/action/backspace.h" void prompt_action_backspace(struct sh *shell) { if (!shell->prompt.length || !shell->prompt.cursor) { return; } shell->prompt.length -= 1; shell->prompt.cursor -= !!shell->prompt.cursor; ptb_remove_char(shell->prompt.input, shell->prompt.cursor); if (shell->atty) { putp(shell->prompt.effect[PROMPT_EFFECT_CURSOR_BACKWARD]); fputs(shell->prompt.input + shell->prompt.cursor, stdout); fputs(" ", stdout); --shell->prompt.cursor; prompt_update_cursor_pos(&(shell->prompt)); ++shell->prompt.cursor; } } <file_sep>/src/exec/rule/command/add_word.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** exec rule command */ #include <stdlib.h> #include <string.h> #include "proto/token/get_string.h" #include "types/exec/rule.h" #include "proto/exec/rule/command/add_word.h" // parse substring int exec_rule_command_add_word( struct process_s *process, struct token_s *word, const char *input ) { char *substr = token_get_string(word, input); if (!substr) { return (EXEC_RULE_ALLOCATION_FAIL); } if (process->argc + 1 >= process->max_argc) { process->max_argc *= 2; process->argv = realloc(process->argv, process->max_argc); if (!process->argv) { return (EXEC_RULE_ALLOCATION_FAIL); } memset(process->argv + process->argc + 1, 0, process->argc + 1); } process->argv[process->argc++] = substr; return (EXEC_RULE_SUCCESS); } <file_sep>/src/job/put.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** job */ #include <stdio.h> #include <signal.h> #include <unistd.h> #include "proto/job/put_in.h" #include "proto/job/wait_for.h" void job_put_in_background(struct job_s *job, bool does_continue) { if (does_continue) { if (kill(-job->pgid, SIGCONT) < 0) { perror("kill (SIGCONT)"); } } } void job_put_in_foreground( struct sh *shell, struct job_s *job, bool does_continue ) { tcsetpgrp(shell->fd, job->pgid); if (does_continue) { tcsetattr(shell->fd, TCSADRAIN, &job->tmodes); if (kill(-job->pgid, SIGCONT) < 0) { perror("kill (SIGCONT)"); } } job_wait_for(shell, shell->job, job); tcsetpgrp(shell->fd, shell->pgid); tcgetattr(shell->fd, &job->tmodes); tcsetattr(shell->fd, TCSADRAIN, &shell->prompt.orig_term); } <file_sep>/include/proto/exec/rule/control/else.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** shell exec rule control else */ #ifndef SH_SHELL_EXEC_RULE_CONTROL_ELSE_H_ #define SH_SHELL_EXEC_RULE_CONTROL_ELSE_H_ #include "types/shell.h" #include "types/expr.h" int exec_rule_control_else( struct sh *shell, struct expr_else_control_s *rule ); #endif /* !SH_SHELL_EXEC_RULE_CONTROL_ELSE_H_ */ <file_sep>/src/shell/shell_destroy.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** destroy */ #include <unistd.h> #include "hasher/destroy.h" #include "types/shell.h" #include "proto/shell.h" #include "proto/prompt/history.h" #include "proto/shell/local_variables.h" /* hasher_destroy(shell->binkey, false, false); */ /* ** @DESCRIPTION ** Free shell */ void shell_destroy(struct sh *shell) { if (shell->fd != STDIN_FILENO) { close(shell->fd); } hasher_destroy(shell->builtin, true, false); hasher_destroy(shell->alias, true, true); hasher_destroy(shell->bindkey, true, false); history_destroy(&shell->history); local_variables_destroy(shell->local_var); } <file_sep>/include/proto/exec/rule/control/check_condition.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** shell exec rule control check_condition */ #ifndef SH_SHELL_EXEC_RULE_CONTROL_CHECK_CONDITION_H_ #define SH_SHELL_EXEC_RULE_CONTROL_CHECK_CONDITION_H_ #include "types/shell.h" #include "types/expr.h" int exec_rule_control_check_condition( struct sh *shell, struct expr_wordlist_expression_s *word ); #endif /* !SH_SHELL_EXEC_RULE_CONTROL_CHECK_CONDITION_H_ */ <file_sep>/src/job/free.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** job */ #include <stdlib.h> #include "proto/job/free.h" void job_free(struct job_s *job) { struct process_s *process = job->first_process; struct process_s *hold = NULL; while (process) { hold = process; process = process->next; free(hold); } free(job); } <file_sep>/lib/mynode/src/node_pop.c /* ** EPITECH PROJECT, 2020 ** mynode ** File description: ** node_pop */ #include <stdlib.h> #include "mynode.h" /* ** @DESCRIPTION ** This function removes the first node of a linked list. */ void node_pop(NODE **head, fnode_t function) { NODE *to_free = *head; if (to_free) { *head = to_free->next; if (function) function(to_free->data); free(to_free); } }<file_sep>/include/proto/job/process/create.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** create job process */ #ifndef SH_PROTO_JOB_PROCESS_CREATE_H_ #define SH_PROTO_JOB_PROCESS_CREATE_H_ #include "types/job.h" struct process_s *process_create(void); #endif /* !SH_PROTO_JOB_PROCESS_CREATE_H_ */ <file_sep>/lib/hasher/include/hasher/override.h /* ** EPITECH PROJECT, 2020 ** hasher ** File description: ** hasher override */ #ifndef HASHER_OVERRIDE_H_ #define HASHER_OVERRIDE_H_ #include "hasher/type.h" struct hasher_s *hasher_override( struct hasher_s **hasher, struct hasher_s *to_insert ); #endif /* !HASHER_OVERRIDE_H_ */ <file_sep>/lib/builtins/src/get_user_home.c /* ** EPITECH PROJECT, 2020 ** builtins ** File description: ** builtin_get_user_home */ /* getenv */ #include <stdlib.h> /* getuid */ #include <unistd.h> /* getpwuid */ #include <pwd.h> /* struct passwd */ #include <sys/types.h> /* */ #include "builtin/get_user_home.h" const char *builtin_get_user_home(void) { struct passwd *pw = NULL; const char *home_env = getenv("HOME"); if (home_env != NULL) { return (home_env); } pw = getpwuid(getuid()); if (pw == NULL) { return (NULL); } return (pw->pw_dir); } <file_sep>/include/proto/job/free.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** free job */ #ifndef SH_PROTO_JOB_FREE_H_ #define SH_PROTO_JOB_FREE_H_ #include "types/job.h" void job_free(struct job_s *job); #endif /* !SH_PROTO_JOB_FREE_H_ */ <file_sep>/lib/parser_toolbox/src/cmp_string.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** cmp_string */ #include <string.h> #include "parser_toolbox/cmp_string.h" _Bool ptb_cmp_string(void *data1, void *data2) { return (!strcmp((char *) data1, (char *) data2)); } _Bool ptb_ncmp_string(void *data1, void *data2) { return (!strncmp((char *) data1, (char *) data2, strlen((char *) data1))); } <file_sep>/src/prompt/history/init.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** init */ #include <stdio.h> #include <string.h> #include "proto/prompt/history.h" static void history_create_from_file( struct history_s *history, char const *filepath ) { FILE *stream = fopen(filepath, "r"); char *buffer = NULL; size_t n = 0; ssize_t nbytes = 0; if (!stream) { return; } while (getline(&buffer, &n, stream) > 0) { for (; buffer[nbytes] && buffer[nbytes] != '\n'; ++nbytes) {} buffer[nbytes] = 0; history_insert(history, strdup(buffer)); } } _Bool history_init(struct history_s *history) { history->list = NULL; history->curr = NULL; history->size = 0; history_create_from_file(history, ".42sh_history"); return (0); } <file_sep>/include/proto/prompt/input/wait_input.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** sh prompt wait_input */ #ifndef SH_PROTO_PROMPT_WAIT_INPUT_H_ #define SH_PROTO_PROMPT_WAIT_INPUT_H_ int wait_input(void); #endif /* !SH_PROTO_PROMPT_WAIT_INPUT_H_ */ <file_sep>/src/expr/jobs.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** expr_jobs */ #include <stdlib.h> #include <string.h> #include "proto/grammar.h" #include "proto/expr.h" /* ** @DESCRIPTION ** Rule for compound_command expression. */ static struct expr_jobs_s *expr_jobs( struct grammar_s *this ) { struct expr_jobs_s *exp = malloc( sizeof(struct expr_jobs_s)); unsigned int save_index = this->index; if (!exp) exit(84); memset(exp, 0, sizeof(struct expr_jobs_s)); if (!grammar_match(this, 1, TOK_AMPERSAND)) return (expr_free(exp)); exp->ampersand = grammar_get_previous(this); exp->grouping = expr_grouping_w(this); if (!exp->grouping) return (expr_free(exp)); save_index = this->index; exp->jobs = expr_jobs_w(this); if (!exp->jobs) this->index = save_index; return (exp); } struct expr_jobs_s *expr_jobs_w(struct grammar_s *this) { struct expr_jobs_s *exp; expr_print(this, "Jobs"); exp = expr_jobs(this); expr_print_debug(this, exp); return (exp); } <file_sep>/src/expr/destroy/statement.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** expr_statement */ /* free */ #include <stdlib.h> #include "proto/expr_destroy.h" /* ** @DESCRIPTION ** Rule for statement expression. */ void expr_statement_destroy(struct expr_statement_s *this) { if (!this) { return; } expr_compound_destroy(this->compound); expr_control_destroy(this->control); free(this); } <file_sep>/src/exec/magic/post_process.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** parse */ #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <wordexp.h> #include "proto/exec/rule/command.h" #include "parser_toolbox/string_split.h" #include "parser_toolbox/consts.h" #include "parser_toolbox/unquote.h" #include "parser_toolbox/blacklist.h" #include "proto/token/get_string.h" #include "proto/exec/rule/command/add_word.h" #include "proto/exec/magic/parse.h" #include "postprocess/quote_cleanup.h" static int tmp_exec_rule_command_add_word( struct process_s *process, char *word ) { if (process->argc + 1 >= process->max_argc) { process->max_argc *= 2; process->argv = realloc(process->argv, process->max_argc); if (!process->argv) { return (1); } memset(process->argv + process->argc + 1, 0, process->argc + 1); } process->argv[process->argc++] = word; return (0); } char **do_post_process_glob( struct process_s *proc, char **substr ) { wordexp_t we = {0}; char **strs = NULL; if (wordexp(*substr, &we, 0)) return (NULL); if (we.we_wordc == 1 && !strcmp(we.we_wordv[0], *substr) && !ptb_blacklist(we.we_wordv[0], "*[]?")) { *substr = NULL; dprintf(2, "%s: No match.\n", proc->argv[0]); wordfree(&we); return (NULL); } strs = calloc(we.we_wordc + 1, sizeof(char *)); for (size_t i = 0; strs && i < we.we_wordc; ++i) { strs[i] = strdup(we.we_wordv[i]); if (!strs[i]) return (NULL); } wordfree(&we); return (strs); } char **do_post_process_word( struct sh *shell, struct process_s *proc, char **substr ) { char **strs = NULL; if (**substr == '`') { ptb_unquote(*substr); strs = do_subshelled_magic_quote(shell, *substr); return (strs); } ipp_quote_cleanup(*substr); if (magic_env_var_replace(shell, substr)) { *substr = NULL; return (NULL); } return (do_post_process_glob(proc, substr)); } int do_post_process( struct sh *shell, struct process_s *proc, char **words ) { char *substr = NULL; char **post_processed = NULL; for (size_t i = 0; words && words[i]; ++i) { if (!words[i]) continue; substr = words[i]; post_processed = do_post_process_word(shell, proc, &substr); for (size_t j = 0; post_processed && post_processed[j]; ++j) { tmp_exec_rule_command_add_word(proc, post_processed[j]); } if (!post_processed) { if (!substr) return (1); tmp_exec_rule_command_add_word(proc, substr); } } return (0); } int do_post_process_command( struct sh *shell, struct process_s *proc, struct expr_command_s *command ) { char *substr = NULL; char **post_processed = NULL; for (; command; command = command->command) { if (command->redirection) continue; substr = token_get_string(command->word, shell->rawinput); post_processed = do_post_process_word(shell, proc, &substr); for (size_t i = 0; post_processed && post_processed[i]; ++i) { tmp_exec_rule_command_add_word(proc, post_processed[i]); } if (!post_processed) { if (substr == NULL) return (1); tmp_exec_rule_command_add_word(proc, substr); } } return (0); } <file_sep>/src/prompt/move_cursor_pos.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** prompt_move_cursor_pos */ /* strlen */ #include <string.h> /* putp */ #include <curses.h> #include <term.h> #include "types/prompt.h" #include "proto/prompt/move_cursor_pos.h" void prompt_move_cursor_pos(struct prompt *prompt, size_t new_pos) { ssize_t diff = (ssize_t) new_pos - (ssize_t) prompt->cursor; const char *effect = NULL; if (diff < 0) { diff = -diff; effect = prompt->effect[PROMPT_EFFECT_CURSOR_BACKWARD]; } else { effect = prompt->effect[PROMPT_EFFECT_CURSOR_FORWARD]; } for (ssize_t size = 0; size < diff; ++size) { putp(effect); } prompt->cursor = new_pos; } <file_sep>/include/proto/shell/local_variables.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** local_variables */ #ifndef PROTO_SHELL_LOCAL_VARIABLES_H_ #define PROTO_SHELL_LOCAL_VARIABLES_H_ #include "hasher/type.h" #include "dnode/type.h" #include "types/local_variables.h" void local_variables_display( struct hasher_s *hasher, struct dnode_s *list ); struct local_var_s *local_variable_from_data( struct hasher_s *hasher, char const *key, char const *data ); void local_variable_assign_value(struct local_var_s *var, char const *data); enum var_type_e local_variable_get_type(char const *data); struct hasher_s *local_variables_init(void); void local_variables_destroy(struct hasher_s *hasher); #endif /* !PROTO_SHELL_LOCAL_VARIABLES_H_ */ <file_sep>/include/proto/exec/rule/statement.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** shell exec rule statement */ #ifndef SH_SHELL_EXEC_RULE_STATEMENT_H_ #define SH_SHELL_EXEC_RULE_STATEMENT_H_ #include "types/shell.h" #include "types/expr.h" int exec_rule_statement( struct sh *shell, struct expr_statement_s *rule ); #endif /* !SH_SHELL_EXEC_RULE_STATEMENT_H_ */ <file_sep>/lib/find_binary/tests/extend_path.c /* ** EPITECH PROJECT, 2020 ** find_binary ** File description: ** test extend_path */ #include <criterion/criterion.h> #include <criterion/redirect.h> #include "extend_path.h" Test(extend_path, simple_path_extension) { const char *path = "/bin/"; const char *bin = "bash"; const char *expected = "/bin/bash"; char *got = extend_path(path, bin); cr_assert_str_eq(got, expected); if (got != NULL) { free(got); } } <file_sep>/src/prompt/actions/end_of_file.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** prompt action end_of_file */ #include <stdio.h> #include "proto/prompt/rewrite_color_command.h" #include "proto/prompt/action/end_of_file.h" void prompt_action_end_of_file(struct sh *shell) { if (shell->prompt.input[0]) { return; } puts("exit"); shell->active = false; } <file_sep>/lib/input_postprocessing/include/postprocess/env_var_replace.h /* ** EPITECH PROJECT, 2020 ** input_postprocessing ** File description: ** quote_cleanup */ #ifndef POSTPROCESS_QUOTE_CLEANUP_H_ #define POSTPROCESS_QUOTE_CLEANUP_H_ /* asprintf */ #define _GNU_SOURCE enum env_var_replace_status_e { ENV_VAR_REPLACE_SUCCESS, ENV_VAR_REPLACE_UNDEFINED_VAR, ENV_VAR_REPLACE_ALLOCATION_FAIL, ENV_VAR_REPLACE_GETPWUID_FAIL, }; enum env_var_replace_status_e ipp_env_var_replace(char **str); #endif /* !POSTPROCESS_QUOTE_CLEANUP_H_ */ <file_sep>/lib/parser_toolbox/include/parser_toolbox/string_split.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** string_split */ #ifndef STRING_SPLIT_H_ #define STRING_SPLIT_H_ char **ptb_string_split(char const *str, char const *index); #endif /* !STRING_SPLIT_H_ */ <file_sep>/src/expr/utility.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** utility */ #include <stdlib.h> #include <string.h> #include "proto/grammar.h" #include "proto/expr.h" void expr_print_padding(unsigned int depth) { for (unsigned int i = 0; i < depth; i++) { printf("│ "); } } void expr_print(struct grammar_s *this, char const *name) { if (!this->debug) return; expr_print_padding(this->depth); printf("\033[1m\033[38;2;150;150;220m%s:\033[0m\n", name); this->depth += 1; } void expr_print_debug(struct grammar_s *this, void *ptr) { if (!this->debug) return; this->depth -= 1; expr_print_padding(this->depth); printf("└─ "); if (ptr) printf("\033[0m\033[38;2;150;200;0mDONE\033[0m\n"); else printf("\033[0m\033[38;2;230;70;100mFAILED\033[0m\n"); } <file_sep>/lib/parser_toolbox/src/remove_char.c /* ** EPITECH PROJECT, 2020 ** parser_toolbox ** File description: ** ptb_remove_char */ #include "parser_toolbox/remove_char.h" void ptb_remove_char(char *str, size_t pos) { for (; str[pos + 1]; ++pos) { str[pos] = str[pos + 1]; } str[pos] = '\0'; } <file_sep>/include/proto/prompt/display.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** sh prompt add_char */ #ifndef SH_PROTO_PROMPT_ADD_CHAR_H_ #define SH_PROTO_PROMPT_ADD_CHAR_H_ #include "proto/shell.h" int prompt_display(struct sh *shell); #endif /* !SH_PROTO_PROMPT_ADD_CHAR_H_ */ <file_sep>/lib/parser_toolbox/src/string_split.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** string_split */ #include <stdlib.h> #include "parser_toolbox/string_split.h" static ssize_t string_chr(char const *str, char c) { if (!str) return (-1); for (size_t i = 0; str[i]; i++) { if (str[i] == c) { return ((ssize_t) i); } } return (-1); } static size_t count_nb_words(char const *str, char const *index) { size_t counter = 0; for (size_t i = 0; str[i];) { for (; str[i] && string_chr(index, str[i]) == -1; i++); for (; str[i] && string_chr(index, str[i]) != -1; i++); counter++; } return (counter); } static char **word_array_alloc(char const *str, char const *index, size_t len) { char **word_array = NULL; size_t lines = 0; word_array = malloc(sizeof(char *) * (len + 1)); if (!word_array) return (NULL); for (size_t i = 0; str[i]; lines++, len = i) { for (; str[len] && string_chr(index, str[len]) == -1; len++); word_array[lines] = malloc(sizeof(char) * (len - i + 1)); if (!word_array[lines]) return (NULL); for (len = 0; str[i] && string_chr(index, str[i]) == -1; i++) word_array[lines][len++] = str[i]; word_array[lines][len] = 0; for (; str[i] && string_chr(index, str[i]) != -1; i++); } word_array[lines] = NULL; return (word_array); } char **ptb_string_split(char const *str, char const *index) { size_t len = 0; if (!str) return (NULL); while (string_chr(index, *str) != -1) str = &str[1]; len = count_nb_words(str, index); return (word_array_alloc(str, index, len)); } <file_sep>/lib/parser_toolbox/include/parser_toolbox/sub_string.h /* ** EPITECH PROJECT, 2020 ** parser_toolbox ** File description: ** parser_toolbox sub_string */ #ifndef PARSER_TOOLBOX_SUB_STRING_H_ #define PARSER_TOOLBOX_SUB_STRING_H_ #include <stddef.h> char *ptb_sub_string(const char *str, size_t start, size_t end); #endif /* !PARSER_TOOLBOX_SUB_STRING_H_ */ <file_sep>/lib/find_binary/src/path_iteration.c /* ** EPITECH PROJECT, 2020 ** find_binary ** File description: ** path_iteration */ #include <stdlib.h> #include <string.h> #include "double_array_size.h" /* */ #include "path_iteration.h" static const size_t PATH_IT_PATH_LEN = 128; static const char PATH_IT_DELIMITER = ':'; static int path_iteration_check_path_env( const char *path_env, char **path, size_t *old_pos ) { if (path_env == NULL) { if (*path != NULL) { free(*path); *path = NULL; } return (1); } if (*path == NULL) { *path = malloc(sizeof(char) * PATH_IT_PATH_LEN); if (path == NULL) { return (1); } } if (path_env[*old_pos] == '\0') { *old_pos = 0; return (1); } return (0); } static void path_iteration_reset_env( const char ***env_point, const char **path_env, size_t *old_pos, size_t *pos ) { *env_point = path_env; *old_pos = 0; *pos = 0; } const char *path_iteration(const char *path_env) { static const char **env_point = NULL; static char *path = NULL; static size_t old_pos = 0; static size_t size = PATH_IT_PATH_LEN; size_t pos = old_pos; if (path_iteration_check_path_env(path_env, &path, &old_pos)) return (NULL); if (env_point == NULL || *env_point != path_env) path_iteration_reset_env(&env_point, &path_env, &old_pos, &pos); if (path_env[old_pos] == '\0') return (NULL); for (; path_env[pos] && path_env[pos] != PATH_IT_DELIMITER; ++pos); while (pos - old_pos >= size) if (double_array_size((void **) &path, &size)) return (NULL); strncpy(path, path_env + old_pos, pos - old_pos); path[pos - old_pos] = '\0'; old_pos = path_env[pos] ? pos + 1 : pos; return (path); } void path_iteration_atexit(void) { path_iteration(NULL); } <file_sep>/lib/hasher/src/replace_data.c /* ** EPITECH PROJECT, 2020 ** hasher ** File description: ** hasher_replace_data */ #include <stddef.h> #include "hasher/get.h" /* */ #include "hasher/replace_data.h" void *hasher_replace_data( struct hasher_s *hasher, const char *current_data, char *new_data ) { struct hasher_s *match = hasher_get(hasher, current_data); void *old_data = NULL; if (match) { old_data = match->data; match->data = new_data; } return (old_data); } <file_sep>/lib/hasher/include/hasher/create.h /* ** EPITECH PROJECT, 2020 ** hasher ** File description: ** hasher create */ #ifndef HASHER_CREATE_H_ #define HASHER_CREATE_H_ #include "hasher/type.h" struct hasher_s *hasher_create(char *key, void *data); #endif /* !HASHER_CREATE_H_ */ <file_sep>/lib/builtins/include/builtin/display_env.h /* ** EPITECH PROJECT, 2020 ** builtins ** File description: ** builtin_display_env */ #ifndef BUILTIN_DISPLAY_ENV_H_ #define BUILTIN_DISPLAY_ENV_H_ void builtin_display_env(void); #endif /* !BUILTIN_DISPLAY_ENV_H_ */ <file_sep>/lib/dnode/include/dnode/apply.h /* ** EPITECH PROJECT, 2020 ** dnode ** File description: ** apply */ #ifndef DNODE_APPLY_H_ #define DNODE_APPLY_H_ #include "dnode/type.h" void dnode_apply(struct dnode_s *list, void (*func)(void *)); #endif /* !DNODE_APPLY_H_ */ <file_sep>/src/prompt/actions/cut_line.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** prompt action prompt_action_cut_line */ #include <stdio.h> #include <unistd.h> #include <string.h> #include "types/shell.h" #include "types/prompt/effect.h" #include "proto/prompt/display.h" #include "proto/prompt/move_cursor_pos.h" #include "proto/prompt/input/empty.h" #include "proto/prompt/action/clear_line.h" #include "proto/prompt/action/cut_line.h" /* TODO: HANDLE malloc */ void prompt_action_cut_line(struct sh *shell) { size_t diff = shell->prompt.length - shell->prompt.cursor; if (diff == 0) { prompt_action_clear_line(shell); return; } strncpy( shell->prompt.input, shell->prompt.input + shell->prompt.cursor, shell->prompt.length ); if (shell->atty) { prompt_move_cursor_pos(&(shell->prompt), 0); printf("%*s", -((int) shell->prompt.length), shell->prompt.input); shell->prompt.cursor = shell->prompt.length; prompt_move_cursor_pos(&(shell->prompt), 0); shell->prompt.length = diff; } } <file_sep>/lib/input_postprocessing/include/postprocess/quote_cleanup.h /* ** EPITECH PROJECT, 2020 ** input_postprocessing ** File description: ** quote_cleanup */ #ifndef POSTPROCESS_QUOTE_CLEANUP_H_ #define POSTPROCESS_QUOTE_CLEANUP_H_ enum quote_cleaning_status_e { QUOTE_CLEANUP_CLOSED, QUOTE_CLEANUP_SINGLE_QUOTE_OPENED, QUOTE_CLEANUP_DOUBLE_QUOTE_OPENED }; enum quote_cleaning_status_e ipp_quote_cleanup(char *str); #endif /* !POSTPROCESS_QUOTE_CLEANUP_H_ */ <file_sep>/src/input/parser/input_parse_tokens.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** input_parse */ /* Needed for calloc, NULL */ #include <stdlib.h> #include "mynode.h" #include "parser_toolbox.h" #include "constants/validators.h" #include "constants/tokens.h" /* Following headers contain implicit includes for types */ #include "proto/input/parser.h" #include "proto/constants.h" /* ** @DESCRIPTION ** For TOKEN_COUNT, this function sends the token's validator to the ** token_validate function using VALIDATORS[i]. ** The token for which the function returned the highest value becomes the ** new token. ** ** Validators are defined in constants/validators.h ** Tokens are defined in types/input/token.h ** */ static struct token_s *input_scan(char const *string, unsigned int *index) { struct token_s *this = calloc(1, sizeof(struct token_s)); unsigned int record = 0; unsigned int current; unsigned int i; if (!this) return (0); (*this).start = *index; for (i = 0; i < TOK_COUNT; i++) { current = TOK_VALIDATORS[i](string + *index, TOKENS[i]); if (current >= record) { record = current; (*this).type = i; } } (*this).end = *index + record; *index += (record) ? record - 1 : 1; return (this); } /* ** @DESCRIPTION ** This function translates the shell.rawinput variable into a token's list. */ void input_parse_tokens(struct sh *shell) { struct node_s *tokens = NULL; struct token_s *new; for (unsigned int i = 0; (*shell).rawinput[i]; i++) { if (ptb_includes((*shell).rawinput[i], WHITESPACE)) continue; new = input_scan((*shell).rawinput, &i); node_insert(&tokens, new); if (!(*shell).rawinput[i]) i--; } node_insert(&tokens, token_new(TOK_EOF)); node_reverse(&tokens); (*shell).tokens = tokens; if (shell->debug_mode) token_print_debug(tokens, shell->rawinput); } <file_sep>/src/prompt/history/destroy.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** destroy */ #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #include "proto/prompt/history.h" void history_destroy(struct history_s *history) { int fd = open(".42sh_history", O_WRONLY | O_TRUNC | O_CREAT, 0666); if (fd == -1) { return; } for (struct dnode_s *curr = dnode_goto_end(history->list); curr; curr = curr->prev) { write(fd, curr->data, strlen(curr->data)); write(fd, "\n", 1); } close(fd); dnode_free(&history->list, &free); } <file_sep>/lib/dnode/include/dnode/find.h /* ** EPITECH PROJECT, 2020 ** dnode ** File description: ** find */ #ifndef DNODE_FIND_H_ #define DNODE_FIND_H_ #include "dnode/type.h" struct dnode_s *dnode_find( struct dnode_s *list, void *data, _Bool (*func)(void *, void *) ); struct dnode_s *dnode_find_after( struct dnode_s *list, void *data, _Bool (*func)(void *, void *) ); struct dnode_s *dnode_find_before( struct dnode_s *list, void *data, _Bool (*func)(void *, void *) ); #endif /* !DNODE_FIND_H_ */ <file_sep>/include/proto/prompt/action/left.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** sh prompt action left */ #ifndef SH_PROTO_PROMPT_ACTION_LEFT_H_ #define SH_PROTO_PROMPT_ACTION_LEFT_H_ #include "types/shell.h" void prompt_action_left(struct sh *shell); #endif /* !SH_PROTO_PROMPT_ACTION_LEFT_H_ */ <file_sep>/lib/builtins/tests/setenv.c /* ** EPITECH PROJECT, 2020 ** builtins ** File description: ** test builtin_setenv */ /* getenv */ #include <stdlib.h> #include <criterion/criterion.h> #include <criterion/redirect.h> #include "builtin/setenv.h" Test(builtin_setenv, simple_setenv) { const char *var = "env_var"; const char *value = "env_var_value"; const char * const argv[] = {var, value, NULL}; const char *getenved_value = NULL; cr_assert_eq(builtin_setenv(argv), SETENV_SUCCESS); getenved_value = getenv(var); cr_assert_str_eq(value, getenved_value); } Test(builtin_setenv, setenv_without_value) { const char *var = "env_var"; const char * const argv[] = {var, NULL}; const char *getenved_value = NULL; cr_assert_eq(builtin_setenv(argv), SETENV_SUCCESS); getenved_value = getenv(var); cr_assert_str_eq("", getenved_value); } Test(builtin_setenv, setenv_too_many_arguments) { const char *arg = "arg"; const char * const argv[] = {arg, arg, arg, NULL}; cr_redirect_stderr(); cr_assert_eq(builtin_setenv(argv), SETENV_TOO_MANY_ARGS); cr_assert_stderr_eq_str("setenv: Too many arguments.\n"); } Test(builtin_setenv, setenv_must_begin_with_a_letter) { const char *arg = "1not_beginning_by_a_letter"; const char * const argv[] = {arg, NULL}; cr_redirect_stderr(); cr_assert_eq(builtin_setenv(argv), SETENV_MUST_BEGIN_WITH_A_LETTER); cr_assert_stderr_eq_str( "setenv: Variable name must begin with a letter.\n" ); } Test(builtin_setenv, setenv_must_contain_only_alphanum_chars) { const char *arg = "containing_non_alph=num chars"; const char * const argv[] = {arg, NULL}; cr_redirect_stderr(); cr_assert_eq(builtin_setenv(argv), SETENV_ALPHANUM_ONLY); cr_assert_stderr_eq_str( "setenv: Variable name must contain alphanumeric characters.\n" ); } <file_sep>/src/expr/foreach_control.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** expr_foreach_control */ #include <stdlib.h> #include <string.h> #include "proto/grammar.h" #include "proto/expr.h" static struct expr_foreach_control_s *expr_foreach_control_n( struct grammar_s *this, struct expr_foreach_control_s *exp, unsigned int save_index ) { if (!grammar_match(this, 1, TOK_NEWLINE)) return (expr_free(exp)); exp->newline = grammar_get_previous(this); save_index = this->index; exp->block = expr_block_w(this); if (!exp->block) this->index = save_index; if (!grammar_match(this, 1, TOK_END)) return (expr_free(exp)); exp->end = grammar_get_previous(this); if (this->tokens[this->index]->type == TOK_EOF) return exp; if (!grammar_match(this, 1, TOK_NEWLINE)) return (expr_free(exp)); exp->newline = grammar_get_previous(this); return exp; } /* ** @DESCRIPTION ** Rule for foreach_control expression. */ static struct expr_foreach_control_s *expr_foreach_control( struct grammar_s *this ) { struct expr_foreach_control_s *exp = calloc(1, sizeof(*exp)); unsigned int save_index = this->index; if (!exp) exit(84); if (!grammar_match(this, 1, TOK_FOREACH)) return (expr_free(exp)); exp->foreach = grammar_get_previous(this); if (!grammar_match(this, 1, TOK_WORD)) return (expr_free(exp)); exp->word = grammar_get_previous(this); exp->wordlist_expression = expr_wordlist_expression_w(this); if (!exp->wordlist_expression) return (expr_free(exp)); return expr_foreach_control_n(this, exp, save_index); } struct expr_foreach_control_s *expr_foreach_control_w(struct grammar_s *this) { struct expr_foreach_control_s *exp; expr_print(this, "Foreach Control"); exp = expr_foreach_control(this); expr_print_debug(this, exp); return exp; } <file_sep>/lib/dnode/tests/append.c /* ** EPITECH PROJECT, 2020 ** dnode ** File description: ** append */ #include <criterion/criterion.h> #include "dnode/append.h" Test(dnode_append, test1) { } <file_sep>/src/exec/rule/redirection.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** exec rule redirection */ #include "proto/exec/rule/debug.h" #include "proto/exec/rule/redirection.h" int exec_rule_redirection( struct sh *shell, __attribute__((unused)) struct expr_redirection_s *rule ) { exec_rule_debug(shell, "redirection", true); exec_rule_debug(shell, "redirection", false); return (0); } <file_sep>/lib/parser_toolbox/include/parser_toolbox/remove_char.h /* ** EPITECH PROJECT, 2020 ** parser_toolbox ** File description: ** parser_toolbox remove_char */ #ifndef PARSER_TOOLBOX_REMOVE_CHAR_H_ #define PARSER_TOOLBOX_REMOVE_CHAR_H_ #include <stddef.h> void ptb_remove_char(char *str, size_t pos); #endif /* !PARSER_TOOLBOX_REMOVE_CHAR_H_ */ <file_sep>/include/constants/prompt/private_bindkey_init.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** Constants private_bindkey_init */ #ifndef SH_CONSTANTS_PROMPT_PRIVATE_BINDKEY_INIT_H_ #define SH_CONSTANTS_PROMPT_PRIVATE_BINDKEY_INIT_H_ #include "proto/prompt/action.h" static const int BINDKEY_COUNT = 19; static const struct { const char *key; struct bindkey_s data; } BINDKEY_DICT[] = { {"kdch1", {&prompt_action_delete, ""}}, {"khome", {&prompt_action_home, ""}}, {"kend", {&prompt_action_end, ""}}, {"\x1b[D", {&prompt_action_left, ""}}, {"\x1b[C", {&prompt_action_right, ""}}, {"\x1b[A", {&prompt_action_up, "up-history"}}, {"\x1b[B", {&prompt_action_down, "down-history"}}, {"\x1b[H", {&prompt_action_home, ""}}, {"\x1b[F", {&prompt_action_end, ""}}, {"\x7f", {&prompt_action_backspace, ""}}, {"\t", {&prompt_action_tab, ""}}, {"\x0C", {&prompt_action_clear_term, "clear-screen"}}, {"\x03", {&prompt_action_interrupt, ""}}, {"\x01", {&prompt_action_home, ""}}, {"\x06", {&prompt_action_right, ""}}, {"\x02", {&prompt_action_left, ""}}, {"\x17", {&prompt_action_cut_line, ""}}, {"\x15", {&prompt_action_clear_line, ""}}, {"\x04", {&prompt_action_end_of_file, ""}}, {"\x1b[5~", {NULL, ""}} }; #endif /* !SH_CONSTANTS_PROMPT_PRIVATE_BINDKEY_INIT_H_ */ <file_sep>/src/expr/program.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** expr_program */ #include <stdlib.h> #include <string.h> #include "proto/constants.h" #include "proto/grammar.h" #include "proto/expr.h" static void set_program_error(struct grammar_s *this) { if (this->tokens[this->index]->type == TOK_OR_IF || this->tokens[this->index]->type == TOK_PIPE) grammar_set_error(this, AST_NULL_COMMAND); else grammar_set_error(this, AST_UNEXPECTED_TOKENS); } /* ** @DESCRIPTION ** Rule for program expression. */ static struct expr_program_s *expr_program(struct grammar_s *this) { struct expr_program_s *exp = malloc(sizeof(struct expr_program_s)); unsigned int save_index = this->index; if (!exp) exit(84); memset(exp, 0, sizeof(struct expr_program_s)); while (grammar_match(this, 2, TOK_NEWLINE, TOK_SEMI)); save_index = this->index; exp->block = expr_block_w(this); if (!exp->block) { this->index = save_index; } if (grammar_match(this, 1, TOK_EOF)) { exp->eof = grammar_get_previous(this); } else if (this->index != this->token_count) { set_program_error(this); free(exp); return NULL; } return exp; } struct expr_program_s *expr_program_w(struct grammar_s *this) { struct expr_program_s *exp; expr_print(this, "Program"); exp = expr_program(this); expr_print_debug(this, exp); return exp; } <file_sep>/include/proto/prompt/input/add_string.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** sh prompt input add_char */ #ifndef SH_PROTO_PROMPT_INPUT_ADD_STRING_H_ #define SH_PROTO_PROMPT_INPUT_ADD_STRING_H_ #include "types/shell.h" void prompt_input_add_string(struct sh *shell, const char *str); #endif /* !SH_PROTO_PROMPT_INPUT_ADD_STRING_H_ */ <file_sep>/lib/parser_toolbox/src/strrep.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** strrep */ #include <stddef.h> #include "parser_toolbox/strrep.h" char *ptb_strrep(char *str, char a, char b) { if (!str) { return (NULL); } for (size_t i = 0; str[i]; ++i) { if (str[i] == a) { str[i] = b; } } return (str); } <file_sep>/include/proto/exec/rule/pipeline.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** shell exec rule pipeline */ #ifndef SH_SHELL_EXEC_RULE_PIPELINE_H_ #define SH_SHELL_EXEC_RULE_PIPELINE_H_ #include "types/shell.h" #include "types/expr.h" int exec_rule_pipeline( struct sh *shell, struct expr_pipeline_s *rule, bool foreground ); #endif /* !SH_SHELL_EXEC_RULE_PIPELINE_H_ */ <file_sep>/include/proto/prompt/action/end.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** sh prompt action end */ #ifndef SH_PROTO_PROMPT_ACTION_END_H_ #define SH_PROTO_PROMPT_ACTION_END_H_ #include "types/shell.h" void prompt_action_end(struct sh *shell); #endif /* !SH_PROTO_PROMPT_ACTION_END_H_ */ <file_sep>/include/proto/prompt/action/interrupt.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** sh prompt action interrupt */ #ifndef SH_PROTO_PROMPT_ACTION_INTERRUPT_H_ #define SH_PROTO_PROMPT_ACTION_INTERRUPT_H_ #include "types/shell.h" void prompt_action_interrupt(struct sh *shell); #endif /* !SH_PROTO_PROMPT_ACTION_INTERRUPT_H_ */ <file_sep>/include/proto/shell/alias.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** shell_alias_hash_create */ #ifndef SH_SHELL_ALIAS_H_ #define SH_SHELL_ALIAS_H_ #include "hasher/type.h" struct hasher_s *shell_alias_hash_create(void); #endif /* !SH_SHELL_ALIAS_H_ */ <file_sep>/lib/hasher/include/hasher/pop.h /* ** EPITECH PROJECT, 2020 ** hasher ** File description: ** hasher pop */ #ifndef HASHER_POP_H_ #define HASHER_POP_H_ #include "hasher/type.h" struct hasher_s *hasher_pop(struct hasher_s **hasher, const char *key); #endif /* !HASHER_POP_H_ */ <file_sep>/lib/builtins/include/builtin/change_directory.h /* ** EPITECH PROJECT, 2020 ** builtins ** File description: ** builtin_change_directory */ #ifndef BUILTIN_CHANGE_DIRECTORY_H_ #define BUILTIN_CHANGE_DIRECTORY_H_ enum change_directory_e { CD_SUCCESS, CD_CHDIR_FAIL, CD_OLDPWD_NOT_SET, CD_GETPWUID_FAIL, CD_ALLOCATION_FAIL, }; enum change_directory_e builtin_change_directory(const char *path); #endif /* !BUILTIN_CHANGE_DIRECTORY_H_ */ <file_sep>/include/proto/exec/rule/control/foreach.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** shell exec rule control foreach */ #ifndef SH_SHELL_EXEC_RULE_CONTROL_FOREACH_H_ #define SH_SHELL_EXEC_RULE_CONTROL_FOREACH_H_ #include "types/shell.h" #include "types/expr.h" int exec_rule_control_foreach( struct sh *shell, struct expr_foreach_control_s *rule ); #endif /* !SH_SHELL_EXEC_RULE_CONTROL_FOREACH_H_ */ <file_sep>/src/expr/wordlist.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** expr_wordlist */ #include <stdlib.h> #include <string.h> #include "proto/grammar.h" #include "proto/expr.h" /* ** @DESCRIPTION ** Rule for wordlist expression. */ static struct expr_wordlist_s *expr_wordlist( struct grammar_s *this ) { struct expr_wordlist_s *exp = malloc( sizeof(struct expr_wordlist_s)); unsigned int save_index __attribute__((unused)) = this->index; if (!exp) exit(84); memset(exp, 0, sizeof(struct expr_wordlist_s)); if (!grammar_match(this, 1, TOK_WORD)) return (expr_free(exp)); exp->wordlist = expr_wordlist_w(this); return exp; } struct expr_wordlist_s *expr_wordlist_w( struct grammar_s *this ) { struct expr_wordlist_s *exp; expr_print(this, "Wordlist"); exp = expr_wordlist(this); expr_print_debug(this, exp); return exp; } <file_sep>/include/proto/prompt/input/read_single_input.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** sh prompt read_single_input */ #ifndef SH_PROTO_READ_SINGLE_INPUT_H_ #define SH_PROTO_READ_SINGLE_INPUT_H_ #include "types/prompt/input.h" enum get_input_e read_single_input(char *c); #endif /* !SH_PROTO_READ_SINGLE_INPUT_H_ */ <file_sep>/src/exec/rule/command.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** exec rule command */ #include "proto/exec/rule/debug.h" #include "types/exec/rule.h" #include "proto/job/process/create.h" #include "proto/job/process/append.h" #include "proto/exec/rule/command/add_word.h" #include "proto/exec/rule/command/add_redirection.h" #include "proto/exec/rule/command.h" #include "proto/exec/magic/parse.h" int exec_rule_command( struct sh *shell, struct expr_command_s *rule, struct job_s *job ) { struct process_s *process = process_create(); exec_rule_debug(shell, "command", true); if (!process) return (EXEC_RULE_ALLOCATION_FAIL); if (do_post_process_command(shell, process, rule)) { return (EXEC_RULE_ALLOCATION_FAIL); } for (; rule; rule = rule->command) { if (!rule->redirection) { continue; } if (exec_rule_command_add_redirection( job, rule->redirection, shell->rawinput)) { return (EXEC_RULE_REDIRECTION_FAIL); } } job_process_append(job, process); exec_rule_debug(shell, "command", false); return (EXEC_RULE_SUCCESS); } <file_sep>/lib/builtins/include/builtin/exit.h /* ** EPITECH PROJECT, 2020 ** builtins ** File description: ** builtin_exit */ #ifndef BUILTIN_EXIT_H_ #define BUILTIN_EXIT_H_ void builtin_exit(const char * const *argv); #endif /* !BUILTIN_EXIT_H_ */ <file_sep>/lib/builtins/tests/exit.c /* ** EPITECH PROJECT, 2020 ** builtins ** File description: ** test builtin_exit */ /* getenv */ #include <stdlib.h> #include <criterion/criterion.h> #include <criterion/redirect.h> #include "builtin/exit.h" Test(builtin_exit, simple_exit, .exit_code = 42) { const char *var = "42"; const char * const argv[] = {var, NULL}; builtin_exit(argv); } Test(builtin_exit, exit_without_argument, .exit_code = 0) { const char * const argv[] = {NULL}; builtin_exit(argv); } Test(builtin_exit, exit_too_many_arguments) { const char *arg = "arg"; const char * const argv[] = {arg, arg, NULL}; cr_redirect_stderr(); builtin_exit(argv); cr_assert_stderr_eq_str("exit: Expression Syntax.\n"); } Test(builtin_exit, exit_with_bad_arg) { const char *arg = "not_a_valid_exit_status"; const char * const argv[] = {arg, NULL}; cr_redirect_stderr(); builtin_exit(argv); cr_assert_stderr_eq_str("exit: Expression Syntax.\n"); } <file_sep>/src/shell/builtin_handlers/too_few_arguments.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** builtins too_many_arguments */ #include <stdio.h> #include "parser_toolbox/argv_length.h" #include "proto/shell/builtin_handlers.h" int builtins_utils_too_few_arguments( const char * const *argv, size_t min_arg_count ) { if (ptb_argv_length(argv) - 1 < min_arg_count) { dprintf(2, "%s: Too few arguments.\n", argv[0]); return (1); } return (0); } <file_sep>/lib/hasher/src/create.c /* ** EPITECH PROJECT, 2020 ** hasher ** File description: ** hasher_create */ #include <stdlib.h> /* */ #include "hasher/create.h" struct hasher_s *hasher_create(char *key, void *data) { struct hasher_s *hasher = NULL; if (key == NULL) { return (NULL); } hasher = (struct hasher_s *) malloc(sizeof(struct hasher_s)); if (hasher == NULL) { return (NULL); } hasher->key = key; hasher->data = data; hasher->next = NULL; return (hasher); } <file_sep>/src/exec/rule/control.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** exec rule control */ #include "proto/exec/rule/debug.h" #include "proto/exec/rule/control/if.h" #include "proto/exec/rule/control/if_inline.h" #include "proto/exec/rule/control/while.h" #include "proto/exec/rule/control/foreach.h" #include "proto/exec/rule/control/repeat.h" #include "proto/exec/rule/control.h" int exec_rule_control( struct sh *shell, struct expr_control_s *rule ) { int ret; exec_rule_debug(shell, "control", true); if (rule->if_inline_control) { ret = exec_rule_control_if_inline(shell, rule->if_inline_control); } if (rule->if_control) { ret = exec_rule_control_if(shell, rule->if_control); } if (rule->while_control) { ret = exec_rule_control_while(shell, rule->while_control); } if (rule->foreach_control) { ret = exec_rule_control_foreach(shell, rule->foreach_control); } if (rule->repeat_control) { ret = exec_rule_control_repeat(shell, rule->repeat_control); } exec_rule_debug(shell, "control", false); return (ret); } <file_sep>/lib/find_binary/include/path_iteration.h /* ** EPITECH PROJECT, 2020 ** find_binary ** File description: ** path_iteration */ #ifndef PATH_ITERATION_H_ #define PATH_ITERATION_H_ const char *path_iteration(const char *path_env); void path_iteration_atexit(void); #endif /* !PATH_ITERATION_H_ */ <file_sep>/include/proto/job/do_notification.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** do_notification job */ #ifndef SH_PROTO_JOB_DO_NOTIFICATION_H_ #define SH_PROTO_JOB_DO_NOTIFICATION_H_ #include "types/job.h" void job_do_notification(struct sh *shell, struct job_s **first_job); #endif /* !SH_PROTO_JOB_DO_NOTIFICATION_H_ */ <file_sep>/src/token/token_validate.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** token_validate */ #include <stdbool.h> #include "parser_toolbox.h" #include "myerror.h" #include "proto/constants.h" #include "proto/token.h" /* ** @DESCRIPTION ** This function skips the inhibitor from the string. ** @TODO ** Raise an advor when the inhibitor is at the end of the line. */ void token_validate_inhibitors(char const *string, unsigned int *i, bool *adv) { if (string[*i] != '\\') { *adv = false; return; } *adv = true; if (!string[*i + 1]) return; else (*i)++; } /* ** @DESCRIPTION ** This function skips the single quotes from the string. ** @TODO ** Raise an error if there is an unmatched quote. */ void token_validate_squotes(char const *string, unsigned int *i, bool *adv) { if (string[*i] != '\'') { *adv = false; return; } *adv = true; (*i)++; for (; string[*i]; (*i)++) { if (string[*i] == '\'') return; } my_error(ERR_WRITE, 84); (*i)--; } /* ** @DESCRIPTION ** This function skips the single quotes from the string. */ void token_validate_bquotes(char const *string, unsigned int *i, bool *adv) { if (string[*i] != '`') { *adv = false; return; } *adv = true; (*i)++; for (; string[*i]; (*i)++) { if (string[*i] == '`') return; } my_error(ERR_WRITE, 84); (*i)--; } /* ** @DESCRIPTION ** This function skips the double quotes from the string. */ void token_validate_dquotes(char const *string, unsigned int *i, bool *adv) { bool self_adv; if (string[*i] != '\"') { *adv = false; return; } *adv = true; (*i)++; for (; string[*i]; (*i)++) { token_validate_inhibitors(string, i, &self_adv); if (self_adv) continue; if (string[*i] == '\"') return; } my_error(ERR_WRITE, 84); (*i)--; } bool token_peek_characters(char const *string, char const *chars) { for (unsigned int i = 0; string[i]; i++) { if (ptb_includes(string[i], WHITESPACE)) continue; if (ptb_includes(string[i], chars)) return (true); } return (false); } <file_sep>/src/expr/command.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** expr_command */ #include <stdlib.h> #include <string.h> #include "proto/grammar.h" #include "proto/expr.h" /* ** @DESCRIPTION ** Rule for command expression. */ static struct expr_command_s *expr_command(struct grammar_s *this) { struct expr_command_s *exp = malloc( sizeof(struct expr_command_s)); unsigned int save_index = this->index; if (!exp) exit(84); memset(exp, 0, sizeof(struct expr_command_s)); if (!grammar_match(this, 1, TOK_WORD)) { exp->redirection = expr_redirection_w(this); if (!exp->redirection) return (expr_free(exp)); } else exp->word = grammar_get_previous(this); save_index = this->index; exp->command = expr_command_w(this); if (!exp->command) this->index = save_index; return (exp); } struct expr_command_s *expr_command_w(struct grammar_s *this) { struct expr_command_s *exp; expr_print(this, "Command"); exp = expr_command(this); expr_print_debug(this, exp); return (exp); } <file_sep>/include/types/prompt/effect.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** sh prompt effect */ #ifndef SH_PROMPT_EFFECT_H_ #define SH_PROMPT_EFFECT_H_ enum prompt_effect_e { PROMPT_EFFECT_CURSOR_BACKWARD, PROMPT_EFFECT_CURSOR_FORWARD, PROMPT_EFFECT_CLEAR, PROMPT_EFFECT_COUNT, }; #endif /* !SH_PROMPT_EFFECT_H_ */ <file_sep>/include/proto/exec/rule/control/if_inline.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** shell exec rule control if_inline */ #ifndef SH_SHELL_EXEC_RULE_CONTROL_IF_INLINE_H_ #define SH_SHELL_EXEC_RULE_CONTROL_IF_INLINE_H_ #include "types/shell.h" #include "types/expr.h" int exec_rule_control_if_inline( struct sh *shell, struct expr_if_inline_control_s *rule ); #endif /* !SH_SHELL_EXEC_RULE_CONTROL_IF_INLINE_H_ */ <file_sep>/tests/input/parser/test_input_parse_tokens_simple.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** input_parse_tokens - test */ #include <criterion/criterion.h> #include <string.h> #include "tests/mock_types.h" #include "proto/input/parser.h" Test(input_parse_tokens, simple_test) { struct sh shell = MOCK_SH; struct node_s *curr; struct token_s *token; enum tokent_e types[] = {TOK_WORD, TOK_EOF}; shell.rawinput = strdup("word"); input_parse_tokens(&shell); curr = shell.tokens; for (unsigned int i = 0; types[i] != TOK_EOF; i++) { if (!curr) { cr_assert(0); return; } token = curr->data; cr_assert_eq(types[i], token->type); curr = curr->next; } } Test(input_parse_tokens, simple_command) { struct sh shell = MOCK_SH; struct node_s *curr; struct token_s *token; enum tokent_e types[] = {TOK_WORD, TOK_IONUMBER, TOK_GREAT, TOK_WORD, TOK_WORD, TOK_EOF}; shell.rawinput = strdup("ls 2 > file -l"); input_parse_tokens(&shell); curr = shell.tokens; for (unsigned int i = 0; types[i] != TOK_EOF; i++) { if (!curr) { cr_assert(0); return; } token = curr->data; cr_assert_eq(types[i], token->type); curr = curr->next; } } Test(input_parse_tokens, advanced_command) { struct sh shell = MOCK_SH; struct node_s *curr; struct token_s *token; enum tokent_e types[] = {TOK_WORD, TOK_AMPERSAND, TOK_OR_IF, TOK_WORD, TOK_PIPE, TOK_WORD, TOK_WORD, TOK_IONUMBER, TOK_GREAT, TOK_WORD, TOK_WORD, TOK_GREAT, TOK_WORD, TOK_EOF}; shell.rawinput = strdup("ls & || ps | cat -e 1 > file 10 > _f_"); input_parse_tokens(&shell); curr = shell.tokens; for (unsigned int i = 0; types[i] != TOK_EOF; i++) { if (!curr) { cr_assert(0); return; } token = curr->data; cr_assert_eq(types[i], token->type); curr = curr->next; } } <file_sep>/src/exec/rule/jobs.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** exec rule grouping */ #include "proto/exec/rule/debug.h" #include "proto/exec/rule/grouping.h" #include "proto/exec/rule/jobs.h" int exec_rule_jobs( struct sh *shell, struct expr_jobs_s *rule, bool foreground ) { exec_rule_debug(shell, "jobs", true); for (; rule->jobs; rule = rule->jobs) { exec_rule_grouping(shell, rule->grouping, !rule->jobs); } exec_rule_grouping(shell, rule->grouping, foreground); exec_rule_debug(shell, "jobs", false); return (0); } <file_sep>/lib/parser_toolbox/src/includes.c /* ** EPITECH PROJECT, 2020 ** parser_toolbox ** File description: ** ptb_characters */ #include <stdbool.h> #include "parser_toolbox/includes.h" /* ** @DESCRIPTION ** Returns true if the c is contained in the values string. ** Returns false otherwise. */ bool ptb_includes(const char c, const char *restrict values) { for (unsigned int i = 0; values[i]; i++) { if (c == values[i]) { return (true); } } return (false); } <file_sep>/src/expr/destroy/jobs.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** expr_jobs */ /* free */ #include <stdlib.h> #include "proto/expr_destroy.h" /* ** @DESCRIPTION ** Rule for jobs expression. */ void expr_jobs_destroy(struct expr_jobs_s *this) { if (!this) { return; } expr_grouping_destroy(this->grouping); free(this); } <file_sep>/lib/mynode/include/mynode.h /* ** EPITECH PROJECT, 2020 ** mynode ** File description: ** Header File | mynode */ #ifndef LIB_MY_NODE_H_ #define LIB_MY_NODE_H_ /* Includes */ #include <stdbool.h> /* Constant Definitions */ typedef void (*fnode_t)(void *); /* Enum Definitions */ /* Structure Definitions */ /* ** @DESCRIPTION ** Holds the global node data for linked lists. */ typedef struct node_s { void *data; struct node_s *next; } node_t; #define NODE struct node_s /* Function Prototypes */ unsigned int node_size(NODE *head); void node_insert(NODE **head, void *data); void node_free(NODE **head, fnode_t function); void node_reverse(NODE **head); void node_append(NODE **head, void *data); void node_filter(NODE **head, bool (*filter)(void *), fnode_t free_func); void node_pop(NODE **head, fnode_t function); void node_remove(NODE **head, void *ptr); void node_apply(NODE *head, fnode_t function); void node_from_table(void **array, NODE **head); void **node_to_table(NODE *const head); /* Dependant Statements */ #endif <file_sep>/lib/parser_toolbox/include/parser_toolbox/sub_str_chr.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** sub_str_chr */ #ifndef PARSER_TOOLBOX_SUB_STR_CHR_H_ #define PARSER_TOOLBOX_SUB_STR_CHR_H_ #include <stdbool.h> #include <stddef.h> bool ptb_sub_str_chr( char *str, size_t start, size_t end, char c ); #endif /* !PARSER_TOOLBOX_SUB_STR_CHR_H_ */ <file_sep>/include/proto/shell/shlvl_update.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** shlvl_update */ #ifndef SH_SHELL_SHLVL_UPDATE_H_ #define SH_SHELL_SHLVL_UPDATE_H_ int shlvl_update(void); #endif /* !SH_SHELL_SHLVL_UPDATE_H_ */ <file_sep>/include/proto/shell/bindkey.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** shell_bindkey_hash_create */ #ifndef SH_SHELL_BINDKEY_H_ #define SH_SHELL_BINDKEY_H_ #include "hasher/type.h" void builtin_bindkey_list(struct sh *shell, const char * const *argv); void builtin_bindkey_help(struct sh *shell, const char * const *argv); struct hasher_s *shell_bindkey_hash_create(void); #endif /* !SH_SHELL_BINDKEY_H_ */ <file_sep>/include/proto/exec/magic/parse.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** parse */ #ifndef PROTO_EXEC_MAGIC_PARSE_H_ #define PROTO_EXEC_MAGIC_PARSE_H_ #include "types/shell.h" #include "types/expr.h" char **do_magic_parse(int fd); void do_subshell(struct sh *shell, char *eval); char **do_subshelled_magic_quote(struct sh *shell, char *eval); int magic_env_var_replace(struct sh *shell, char **str); int do_post_process( struct sh *shell, struct process_s *proc, char **words ); int do_post_process_command( struct sh *shell, struct process_s *proc, struct expr_command_s *command ); #endif /* !PROTO_EXEC_MAGIC_PARSE_H_ */ <file_sep>/src/exec/magic/do_subshelled_magic_quote.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** parse */ #include <stdio.h> #include <stdlib.h> #include <sys/wait.h> #include <unistd.h> #include "proto/exec/magic/parse.h" #include "myerror.h" #include "proto/prompt/input/empty.h" #include "proto/input/parser.h" #include "proto/input/executer.h" #include "proto/exec/rule/program.h" #include "proto/expr_destroy.h" #include "proto/input.h" void do_subshell(struct sh *shell, char *eval) { shell->rawinput = eval; shell->last_status = input_parse(shell); if (shell->expression) { exec_rule_program(shell, shell->expression); } exit(shell->last_status); } char **do_subshelled_magic_quote(struct sh *shell, char *eval) { pid_t pid; int fd[2]; if (pipe(fd) == -1) { exit(1); } pid = fork(); if (pid == -1) { exit(1); } else if (pid == 0) { close(fd[0]); dup2(fd[1], 1); close(fd[1]); do_subshell(shell, eval); } close(fd[1]); waitpid(pid, NULL, 0); return (do_magic_parse(fd[0])); } <file_sep>/lib/mynode/src/node_remove.c /* ** EPITECH PROJECT, 2020 ** mynode ** File description: ** node_remove */ #include <stdlib.h> #include "mynode.h" /* ** @DESCRIPTION ** This function removes the NODE pointed by the ptr. */ void node_remove(NODE **head, void *ptr) { NODE *previous = NULL; NODE *curr = *head; bool found = false; for (; curr; curr = curr->next) { if (curr->data == ptr) { found = true; break; } previous = curr; } if (found) { if (previous) previous->next = curr->next; else *head = curr->next; free(curr); } } <file_sep>/include/types/expr.h /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** program header file. */ #ifndef SH_TYPES_EXPR_PROGRAM_H_ #define SH_TYPES_EXPR_PROGRAM_H_ /**/ /* Includes */ /**/ /**/ /* Constants */ /**/ /**/ /* Structures / Typedef / Enums declarations */ /**/ /* ** @DESCRIPTION ** List of all the expression types for when using unions in expression ** structures. */ enum expr_type_e { EXPR_NULL, EXPR_PROGRAM, EXPR_BLOCK, EXPR_JOBS, EXPR_COMMAND, EXPR_PIPELINE, EXPR_SIMPLE_COMMAND, EXPR_SHELL_COMMAND, EXPR_IF_STATEMENT, EXPR_ELSEIF_STATEMENT, EXPR_ELSE_STATEMENT, EXPR_EXPRESSION, EXPR_COMMAND_SEPARATOR, EXPR_REDIRECTION, EXPR_ELEMENT }; union expr_union_u { struct expr_program_s *program; struct expr_block_s *block; struct expr_jobs_s *jobs; struct expr_command_s *command; struct expr_shell_command_s *shell_command; struct expr_if_statement_s *if_stmt; struct expr_elseif_statement_s *elseif_stmt; struct expr_else_statement_s *else_stmt; struct expr_expression_s *expression; struct expr_command_separator_s *command_separator; struct expr_redirection_s *redirection; }; /* ** @DESCRIPTION ** Rule: WORDLIST */ struct expr_wordlist_s { struct token_s *word; struct expr_wordlist_s *wordlist; }; /* ** @DESCRIPTION ** Rule: WORDLIST CONTROL */ struct expr_wordlist_expression_s { struct token_s *lparanth; struct expr_wordlist_s *wordlist; struct token_s *rparanth; }; /* ** @DESCRIPTION ** Rule: REPEAT CONTROL */ struct expr_repeat_control_s { struct token_s *repeat; struct token_s *word; struct expr_grouping_s *grouping; }; /* ** @DESCRIPTION ** Rule: WHILE CONTROL */ struct expr_while_control_s { struct token_s *while_token; struct expr_wordlist_expression_s *wordlist_expression; struct token_s *wordlist_expression_newline; struct expr_block_s *block; struct token_s *end; struct token_s *end_newline; }; /* ** @DESCRIPTION ** Rule: FOREACH CONTROL */ struct expr_foreach_control_s { struct token_s *foreach; struct token_s *word; struct expr_wordlist_expression_s *wordlist_expression; struct expr_block_s *block; struct token_s *end; struct token_s *newline; }; /* ** @DESCRIPTION ** Rule: ELSE CONTROL */ struct expr_else_control_s { struct token_s *else_token; struct token_s *newline; struct expr_block_s *block; }; /* ** @DESCRIPTION ** Rule: ELSE IF CONTROL */ struct expr_else_if_control_s { struct token_s *else_if_token; struct expr_wordlist_expression_s *wordlist_expression; struct token_s *then; struct token_s *newline; struct expr_block_s *block; struct expr_else_if_control_s *else_if_control; }; /* ** @DESCRIPTION ** Rule: IF CONTROL */ struct expr_if_control_s { struct token_s *if_token; struct expr_wordlist_expression_s *wordlist_expression; struct token_s *then; struct token_s *then_newline; struct expr_block_s *block; struct expr_else_if_control_s *else_if_control; struct expr_else_control_s *else_control; struct token_s *endif; struct token_s *endif_newline; }; /* ** @DESCRIPTION ** Rule: IF CONTROL */ struct expr_if_inline_control_s { struct token_s *if_token; struct expr_wordlist_expression_s *wordlist_expression; struct expr_grouping_s *grouping; struct token_s *endif_newline; }; /* ** @DESCRIPTION ** Rule: CONTROL */ struct expr_control_s { struct expr_if_inline_control_s *if_inline_control; struct expr_if_control_s *if_control; struct expr_while_control_s *while_control; struct expr_foreach_control_s *foreach_control; struct expr_repeat_control_s *repeat_control; }; /* ** @DESCRIPTION ** Rule: SEPARATOR */ struct expr_separator_s { struct token_s *separator; }; /* ** @DESCRIPTION ** Rule: REDIRECTION */ struct expr_redirection_s { struct token_s *io_number; struct token_s *redirection; struct token_s *word; }; /* ** @DESCRIPTION ** Rule: COMMAND */ struct expr_command_s { struct token_s *word; struct expr_redirection_s *redirection; struct expr_command_s *command; }; /* ** @DESCRIPTION ** Rule: PIPELINE */ struct expr_pipeline_s { struct expr_subshell_s *subshell; struct expr_command_s *command; struct token_s *pipe; struct expr_pipeline_s *pipeline; }; /* ** @DESCRIPTION ** Rule: GROUPING */ struct expr_grouping_s { struct expr_pipeline_s *pipeline; struct token_s *conditional; struct expr_grouping_s *grouping; }; /* ** @DESCRIPTION ** Rule: SUBSHELL */ struct expr_subshell_s { struct token_s *lparanth; struct expr_grouping_s *grouping; struct token_s *rparanth; }; /* ** @DESCRIPTION ** Rule: JOBS */ struct expr_jobs_s { struct token_s *ampersand; struct expr_grouping_s *grouping; struct expr_jobs_s *jobs; }; /* ** @DESCRIPTION ** Rule: COMPOUND */ struct expr_compound_s { struct token_s *ampersand_start; struct expr_grouping_s *grouping; struct expr_jobs_s *jobs; struct token_s *ampersand_end; struct expr_separator_s *separator; }; /* ** @DESCRIPTION ** Rule: STATEMENT */ struct expr_statement_s { struct expr_compound_s *compound; struct expr_control_s *control; }; /* ** @DESCRIPTION ** Rule: BLOCK */ struct expr_block_s { struct expr_statement_s *statement; struct expr_block_s *block; }; /* ** @DESCRIPTION ** Rule: PROGRAM */ struct expr_program_s { struct expr_block_s *block; struct token_s *eof; }; /**/ /* Function prototypes */ /**/ #endif <file_sep>/lib/mynode/src/node_apply.c /* ** EPITECH PROJECT, 2020 ** mynode ** File description: ** node_apply */ #include <stdlib.h> #include "mynode.h" void node_apply(NODE *head, fnode_t function) { for (NODE *curr = head; curr; curr = curr->next) { function(curr->data); } } <file_sep>/include/proto/exec/rule/control/else_if.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** shell exec rule control else_if */ #ifndef SH_SHELL_EXEC_RULE_CONTROL_ELSE_IF_H_ #define SH_SHELL_EXEC_RULE_CONTROL_ELSE_IF_H_ #include "types/shell.h" #include "types/expr.h" int exec_rule_control_else_if( struct sh *shell, struct expr_else_if_control_s *rule ); #endif /* !SH_SHELL_EXEC_RULE_CONTROL_ELSE_IF_H_ */ <file_sep>/include/proto/prompt/input/empty.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** sh prompt empty */ #ifndef SH_PROTO_PROMPT_EMPTY_H_ #define SH_PROTO_PROMPT_EMPTY_H_ #include "proto/shell.h" void prompt_input_empty(struct sh *shell); #endif /* !SH_PROTO_PROMPT_EMPTY_H_ */ <file_sep>/lib/builtins/src/setenv.c /* ** EPITECH PROJECT, 2020 ** builtins ** File description: ** builtin_setenv */ /* dprintf */ #include <stdio.h> /* setenv */ #include <stdlib.h> #include "builtin/display_env.h" #include "parser_toolbox/argv_length.h" #include "parser_toolbox/whitelist.h" #include "parser_toolbox/range.h" /* */ #include "builtin/setenv.h" static const char *SETENV_ERROR_MSG[] = { NULL, "setenv: Too many arguments.\n", "setenv: Variable name must contain alphanumeric characters.\n", "setenv: Variable name must begin with a letter.\n", }; enum builtin_setenv_e builtin_setenv(const char * const *argv) { if (!argv[0]) { builtin_display_env(); return (SETENV_SUCCESS); } if (ptb_argv_length(argv) > 2) { dprintf(2, "%s", SETENV_ERROR_MSG[SETENV_TOO_MANY_ARGS]); return (SETENV_TOO_MANY_ARGS); } if (!ptb_whitelist_alphanum(argv[0])) { dprintf(2, "%s", SETENV_ERROR_MSG[SETENV_ALPHANUM_ONLY]); return (SETENV_ALPHANUM_ONLY); } if (ptb_range(argv[0][0], '1', '9')) { dprintf(2, "%s", SETENV_ERROR_MSG[SETENV_MUST_BEGIN_WITH_A_LETTER]); return (SETENV_MUST_BEGIN_WITH_A_LETTER); } return (setenv(argv[0], argv[1] ? argv[1] : "", 1) == -1 ? SETENV_ALLOCATION_FAIL : SETENV_SUCCESS ); } <file_sep>/lib/dnode/include/dnode/type.h /* ** EPITECH PROJECT, 2020 ** dnode ** File description: ** type */ #ifndef DNODE_TYPE_H_ #define DNODE_TYPE_H_ struct dnode_s { void *data; struct dnode_s *next; struct dnode_s *prev; }; #endif /* !DNODE_TYPE_H_ */ <file_sep>/include/proto/job/initialize.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** initialize job */ #ifndef SH_PROTO_JOB_INITIALIZE_H_ #define SH_PROTO_JOB_INITIALIZE_H_ #include "types/shell.h" int job_initialize(struct sh *shell, char **argv); #endif /* !SH_PROTO_JOB_INITIALIZE_H_ */ <file_sep>/include/proto/prompt/action/up.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** sh prompt action up */ #ifndef SH_PROTO_PROMPT_ACTION_UP_H_ #define SH_PROTO_PROMPT_ACTION_UP_H_ #include "types/shell.h" void prompt_action_up(struct sh *shell); #endif /* !SH_PROTO_PROMPT_ACTION_UP_H_ */ <file_sep>/lib/input_postprocessing/include/gnu_source.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** _GNU_SOURCE */ #ifndef PERSONNAL_DEF_GNU_SOURCE_H_ #define PERSONNAL_DEF_GNU_SOURCE_H_ #define _GNU_SOURCE #include <stdio.h> #endif /* !PERSONNAL_DEF_GNU_SOURCE_H_ */ <file_sep>/src/exec/magic/parse.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** parse */ #include <stdio.h> #include <unistd.h> #include "parser_toolbox/string_split.h" #include "parser_toolbox/consts.h" #include "parser_toolbox/unquote.h" #include "proto/exec/magic/parse.h" char **do_magic_parse(int fd) { FILE *stream = fdopen(fd, "r"); char *buffer = NULL; size_t n = 0; if (!stream) { return (NULL); } if (getdelim(&buffer, &n, 0, stream) < 0) { return (NULL); } fclose(stream); close(fd); return (ptb_string_split(buffer, PTB_WHITESPACES)); } <file_sep>/lib/builtins/include/builtin/unsetenv.h /* ** EPITECH PROJECT, 2020 ** builtins ** File description: ** builtin_unsetenv */ #ifndef BUILTIN_UNSETENV_H_ #define BUILTIN_UNSETENV_H_ void builtin_unsetenv(const char * const *argv); #endif /* !BUILTIN_UNSETENV_H_ */ <file_sep>/tests/binaries/src/big_file_gen.c /* ** EPITECH PROJECT, 2020 ** big_file_gen ** File description: ** main */ #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <unistd.h> static void create_file2(int fd, char a, char b) { char temp[5] = {0, 0, 0, 0, '\n'}; for (char c = 'A'; c <= 'z'; ++c) { for (char d = 'A'; d <= 'z'; ++d) { temp[0] = a; temp[1] = b; temp[2] = c; temp[3] = d; write(fd, temp, 5); } } } static void create_file(char const *path) { int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0666); if (fd == -1) { printf("Error when opening file.\n"); return; } for (char a = 'A'; a <= 'z'; ++a) { for (char b = 'A'; b <= 'z'; ++b) { create_file2(fd, a, b); } } close(fd); } int main(int ac, char *av[]) { int fd = -1; struct stat sb; if (ac < 2) { printf("Not enough arguments.\n"); return (84); } if (stat(av[1], &sb) != -1) { return (0); } create_file(av[1]); return (0); } <file_sep>/include/proto/prompt/action/down.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** sh prompt action down */ #ifndef SH_PROTO_PROMPT_ACTION_DOWNH_ #define SH_PROTO_PROMPT_ACTION_DOWNH_ #include "types/shell.h" void prompt_action_down(struct sh *shell); #endif /* !SH_PROTO_PROMPT_ACTION_DOWNH_ */ <file_sep>/lib/Makefile ## ## EPITECH PROJECT, 2020 ## PSU_42sh_2019 ## File description: ## Makefile ## CC ?= gcc LIBNAMES = builtins \ dnode \ mynode \ input_postprocessing \ find_binary \ hasher \ parser_toolbox \ myerror \ all: COMMAND = all all: for lib in $(LIBNAMES) ; do \ $(MAKE) -C ./$$lib/ $(COMMAND) || exit 1 ; \ done \ $(NAME): COMMAND ?= all $(NAME): for lib in $(LIBNAMES) ; do \ $(MAKE) -C ./$$lib/ $(COMMAND) || exit 1 ; \ done \ debug: COMMAND = debug debug: for lib in $(LIBNAMES) ; do \ $(MAKE) -C ./$$lib/ $(COMMAND) || exit 1 ; \ done \ clean: COMMAND = clean clean: for lib in $(LIBNAMES) ; do \ $(MAKE) -C ./$$lib/ $(COMMAND) || exit 1 ; \ done \ fclean: COMMAND = fclean fclean: for lib in $(LIBNAMES) ; do \ $(MAKE) -C ./$$lib/ $(COMMAND) || exit 1 ; \ done \ fcleanlib: COMMAND = fcleanlib fcleanlib: for lib in $(LIBNAMES) ; do \ $(MAKE) -C ./$$lib/ $(COMMAND) || exit 1 ; \ done \ re: COMMAND = fclean all re: for lib in $(LIBNAMES) ; do \ $(MAKE) -C ./$$lib/ $(COMMAND) || exit 1 ; \ done \ relib: COMMAND = fcleanlib all relib: for lib in $(LIBNAMES) ; do \ $(MAKE) -C ./$$lib/ $(COMMAND) || exit 1 ; \ done \ .PHONY: all debug clean fclean fcleanlib re relib <file_sep>/src/shell/builtin_handlers/termname.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** builtins */ #include <stdio.h> #include <stdlib.h> #include "builtins.h" #include "types/shell.h" #include "proto/shell/builtin_handlers.h" int builtin_termname_handler( __attribute__((unused)) struct sh *shell, const char * const *argv ) { const char *term = NULL; if (!argv[1]) { term = getenv("TERM"); if (term) { dprintf(1, "%s\n", term); } } else if (!argv[2]) { } else { dprintf(2, "%s: Too many arguments.\n", argv[0]); return (1); } return (0); } <file_sep>/include/proto/prompt/rewrite_color_command.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** sh prompt rewrite_color_command */ #ifndef SH_PROTO_PROMPT_REWRITE_COLOR_COMMAND_H_ #define SH_PROTO_PROMPT_REWRITE_COLOR_COMMAND_H_ #include "proto/shell.h" void rewrite_color_command(struct sh *shell); #endif /* !SH_PROTO_PROMPT_REWRITE_COLOR_COMMAND_H_ */ <file_sep>/src/job/create.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** exec rule command */ #include <stdlib.h> #include "proto/job/create.h" struct job_s *job_create(int launch_id) { struct job_s *job = malloc(sizeof(struct job_s)); if (job == NULL) { return (NULL); } *job = (struct job_s) { .next = NULL, .command = NULL, .first_process = NULL, .pgid = 0, .notified = false, .tmodes = {0}, .io = {IO_IN, IO_OUT, IO_ERR}, .foreground = true, .launch_id = launch_id }; return (job); } <file_sep>/include/proto/prompt/input/get_extended_input.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** sh input get_extended_input */ #ifndef SH_PROTO_INPUT_GET_EXTENDED_INPUT_H_ #define SH_PROTO_INPUT_GET_EXTENDED_INPUT_H_ #include "types/shell.h" #include "types/prompt/input.h" char *get_extended_input( struct sh *shell, enum get_input_e *status, char character ); #endif /* !SH_PROTO_INPUT_GET_EXTENDED_INPUT_H_ */ <file_sep>/include/types/token.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** token header file. */ #ifndef SH_TYPES_TOKEN_H_ #define SH_TYPES_TOKEN_H_ /**/ /* Includes */ /**/ /**/ /* Structures / Typedef / Enums declarations */ /**/ /* ** @DESCRIPTION ** Defines all of the shell tokens. */ typedef enum tokent_e { TOK_NONE, TOK_EOF, TOK_WORD, TOK_NEWLINE, TOK_IONUMBER, TOK_LESS, TOK_GREAT, TOK_PIPE, TOK_SEMI, TOK_AMPERSAND, TOK_AND_IF, TOK_OR_IF, TOK_DSEMI, TOK_DLESS, TOK_DGREAT, TOK_LESSAND, TOK_GREATAND, TOK_LESSGREAT, TOK_DLESSDASH, TOK_CLOBBER, TOK_LBRACE, TOK_RBRACE, TOK_LPARANTH, TOK_RPARANTH, TOK_BREAK, TOK_SWITCH, TOK_CASE, TOK_BREAKSW, TOK_DEFAULT, TOK_ENDSW, TOK_CONTINUE, TOK_FOREACH, TOK_ENDIF, TOK_END, TOK_GOTO, TOK_IF, TOK_ELSE_IF, TOK_ELSE, TOK_THEN, TOK_REPEAT, TOK_WHILE, TOK_COUNT } tokent_t; /* ** @DESCRIPTION ** Defines the structure for a token once parsed. ** @MEMBERS ** - type: The type of token. ** - start: the beginning of the token in the sh.rawinput string. ** - start: the end of the token in the sh.rawinput string. */ typedef struct token_s { tokent_t type; unsigned int start; unsigned int end; } token_t; /**/ /* Function prototypes */ /**/ #endif <file_sep>/include/proto/exec/rule/command/add_redirection.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** shell exec rule command add_redirection */ #ifndef SH_SHELL_EXEC_RULE_COMMAND_ADD_REDIRECTION_H_ #define SH_SHELL_EXEC_RULE_COMMAND_ADD_REDIRECTION_H_ #include "types/job.h" #include "types/expr.h" int exec_rule_command_add_redirection( struct job_s *job, struct expr_redirection_s *redirection, const char *input ); #endif /* !SH_SHELL_EXEC_RULE_COMMAND_ADD_REDIRECTION_H_ */ <file_sep>/include/types/prompt.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** sh prompt */ #ifndef SH_PROMPT_H_ #define SH_PROMPT_H_ #include <stddef.h> #include <termios.h> #include "types/prompt/action.h" #include "types/prompt/effect.h" struct prompt { char input[8192]; size_t length; size_t cursor; const char *effect[PROMPT_EFFECT_COUNT]; struct termios orig_term; }; #endif /* !SH_PROMPT_H_ */ <file_sep>/lib/parser_toolbox/src/whitelist.c /* ** EPITECH PROJECT, 2020 ** parser_toolbox ** File description: ** ptb_characters */ #include <stdbool.h> #include "parser_toolbox/consts.h" #include "parser_toolbox/includes.h" #include "parser_toolbox/whitelist.h" /* ** @DESCRIPTION ** Returns true string only composed of whitelisted characters ** Returns false otherwise. */ bool ptb_whitelist(const char *string, const char * restrict whitelist) { for (unsigned int i = 0; string[i]; ++i) { if (!ptb_includes(string[i], whitelist)) { return (false); } } return (true); } /* ** @DESCRIPTION ** Returns true string only composed of digit characters ** Returns false otherwise. */ bool ptb_whitelist_digit(const char *string) { return (ptb_whitelist(string, PTB_DIGITS)); } /* ** @DESCRIPTION ** Returns true string only composed of alphanumeric characters ** Returns false otherwise. */ bool ptb_whitelist_alphanum(const char *string) { return (ptb_whitelist(string, PTB_ALPHANUM)); } <file_sep>/include/types/builtins.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** builtins */ #ifndef SH_TYPES_BUILTINS_H_ #define SH_TYPES_BUILTINS_H_ /**/ /* Includes */ /**/ #include "types/shell.h" /**/ /* Constants */ /**/ /**/ /* Structures / Typedef / Enums declarations */ /**/ typedef int (*builtin_handler)(sh_t *sh, const char * const *argv); /**/ /* Function prototypes */ /**/ #endif <file_sep>/include/proto/prompt/action/clear_term.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** sh prompt action clear_term */ #ifndef SH_PROTO_PROMPT_ACTION_CLEAR_TERMH_ #define SH_PROTO_PROMPT_ACTION_CLEAR_TERMH_ #include "types/shell.h" void prompt_action_clear_term(struct sh *shell); #endif /* !SH_PROTO_PROMPT_ACTION_CLEAR_TERMH_ */ <file_sep>/lib/parser_toolbox/include/parser_toolbox/whitelist.h /* ** EPITECH PROJECT, 2020 ** parser_toolbox ** File description: ** parser_toolbox withelist */ #ifndef PARSER_TOOLBOX_WHITELIST_H_ #define PARSER_TOOLBOX_WHITELIST_H_ #include <stdbool.h> bool ptb_whitelist(const char *string, const char * restrict withelist); bool ptb_whitelist_digit(const char *string); bool ptb_whitelist_alphanum(const char *string); #endif /* !PARSER_TOOLBOX_WHITELIST_H_ */ <file_sep>/ftest.sh #!/bin/bash TESTS_PATH=tests/ftests mkdir $TESTS_PATH 2> /dev/null NB_TEST_PASSED=0 NB_TEST_FAILED=0 TOTAL_TESTS_PASSED=0 TOTAL_TESTS_FAILED=0 RED='echo -ne \033[38;2;255;50;50m' GREEN='echo -ne \033[38;2;50;255;50m' YELLOW='echo -ne \033[38;2;255;255;0m' WHITE='echo -ne \033[0m' PURPLE='echo -ne \033[1m\033[038;2;150;150;220m' function display_test_result() { $YELLOW ; echo "$1 result:" ; $WHITE $GREEN echo -ne "\tTest passed: $NB_TEST_PASSED\n" if [ $NB_TEST_FAILED -ne 0 ] then $RED echo -ne "\tTest failed: $NB_TEST_FAILED\n" fi $WHITE TOTAL_TESTS_PASSED=$(($NB_TEST_PASSED + TOTAL_TESTS_PASSED)) TOTAL_TESTS_FAILED=$(($NB_TEST_FAILED + TOTAL_TESTS_FAILED)) NB_TEST_PASSED=0 NB_TEST_FAILED=0 echo } function _test () { echo -ne "$1" | $2 ./42sh 2>&1 | $3 | cat > $TESTS_PATH/$4_42sh.ftest #$RED; echo "status:$?" ; $WHITE echo -ne "$1" | $2 tcsh 2>&1 | $3 | cat > $TESTS_PATH/$4_tcsh.ftest difference=`diff $TESTS_PATH/$4_42sh.ftest $TESTS_PATH/$4_tcsh.ftest` result=$? if [ $result = 0 ] then $GREEN echo $5 OK $WHITE NB_TEST_PASSED=$((NB_TEST_PASSED + 1)) else $RED echo "$5 KO, $TESTS_PATH/$4_42sh.ftest and $TESTS_PATH/$4_tcsh.ftest differ" $WHITE NB_TEST_FAILED=$((NB_TEST_FAILED + 1)) echo $difference > $TESTS_PATH/$4_diff.ftest fi } function basic_test () { $PURPLE ; echo "=----= BASIC TESTS =----=" ; $WHITE _test '\n\n' "" cat empty "Empty" _test '/bin/ls' "" cat run_simple_command "Run simple commands" _test '/bin/ls -l' "" cat simple_exec "Simple exec" _test 'exitt' "" cat wrong_simple_command "Command not found" display_test_result BASIC_TEST } function path_handling () { $PURPLE ; echo "=----= PATH HANDLING =----=" ; $WHITE _test 'unset path\nls' "env -i" cat no_path "No path" _test 'bin/ls' "" cat bin_ls_not_found "Bin/ls not found" display_test_result PATH_HANDLING } function setenv_and_unsetenv () { $PURPLE ; echo "=----= SETENV AND UNSETENV =----=" ; $WHITE _test 'setenv MASHALLA 1000\nenv\n' "" "grep MASHALLA" setenv "Setenv basic" _test 'unsetenv PATH\nenv\n' "" "grep ^PATH=" unsetenv "Unsetenv basic" _test 'setenv MASHALLA ¤1' "" "cat" setenv_alphanum "Setenv alphanum error" _test 'setenv MASHALLA 1 2' "" "cat" setenv_alphanum "Setenv too many arguments" display_test_result SETENV_AND_UNSETENV } function builtin_cd () { $PURPLE ; echo "=----= BUILTIN CD =----=" ; $WHITE _test 'cd\nls' "" "cat" cd_home "Cd" _test 'cd ~\nls' "" "cat" cd_tilde "Cd tilde" _test 'cd -\nls' "" "cat" cd_minus_no_oldpwd "Cd -, no oldpwd" _test 'cd ..\ncd -\nls' "" "cat" cd_minus_with_oldpwd "Cd -, with oldpwd" _test 'cd ftest.sh' "" "cat" cd_not_in_directory "Cd not in directroy" _test 'cd /root' "" "cat" cd_no_permission "Cd no permissions" display_test_result BUILTIN_CD } function line_formatting () { $PURPLE ; echo "=----= LINE FORMATTING =----=" ; $WHITE _test ' ' "" "" "cat" space_1 "Space 1" _test ' \n /bin/echo \n /bin/ls \n' "" "" "cat" space_2 "Space 2" _test ' \t \n /bin/echo\t \n \t /bin/ls \t -l \n ' "" "" "cat" space_and_tab "Space and tab" _test '/bin/ls\t-l\t' "" "" "cat" tab "Tab" display_test_result LINE_FORMATTING } function error_handling () { $PURPLE ; echo "=----= ERROR HANDLING =----=" ; $WHITE gcc tests/binaries/src/bin_not_compatible.c -o tests/binaries/temp tac tests/binaries/temp > tests/binaries/bin_not_compatible chmod +x tests/binaries/bin_not_compatible gcc ./tests/binaries/src/div_zero.c -o ./tests/binaries/div_zero gcc ./tests/binaries/src/segfault.c -o ./tests/binaries/segfault _test './tests/binaries/bin_not_compatible' "" "cat" bin_not_compatible "Bin not compatible" _test './tests/binaries/div_zero' "" "cat" div_zero "DivZero with core dump" _test './tests/binaries/segfault' "" "cat" segfault "SegFault with core dump" _test './src' "" "" "cat" exec_directory "Exec a directory" display_test_result ERROR_HANDLING } function separator () { $PURPLE ; echo "=----= SEPARATOR =----=" ; $WHITE _test '/bin/ls ; /bin/echo' "" "cat" separator_comma "Separator ';'" display_test_result SEPARATOR } function simple_pipe () { $PURPLE ; echo "=----= SIMPLE PIPE =----=" ; $WHITE gcc ./tests/binaries/src/big_file_gen.c -o ./tests/binaries/big_file_gen ./tests/binaries/big_file_gen ./tests/binaries/big_file _test '/bin/ls | /bin/cat -e' "" "cat" simple_pipe "Simple pipe" _test '/bin/cat ./tests/binaries/big_file | wc' "" "cat" pipe_big_input "Pipe with big input" _test '/bin/ls | cd ..\nls' "" "cat" pipe_with_builtin_end "Pipe with builtin end" _test 'cd .. | /bin/ls\n/bin/ls' "" "cat" pipe_with_builtin_start "Pipe with builtin start" _test '/bin/ls | cd .. | /bin/ls\nls' "" "cat" pipe_with_builtin_middle "Pipe with builtin middle" display_test_result SIMPLE_PIPE } function advanced_pipe () { $PURPLE ; echo "=----= ADVANCED PIPE =----=" ; $WHITE lot_of_pipe=`cat ./tests/binaries/lot_of_pipe` _test 'ouesh ouesh | /bin/cat -e' "" "cat" error_and_pipe_1 "Error and pipe 1" _test '/bin/ls | ouesh ouesh' "" "cat" error_and_pipe_2 "Error and pipe 2" _test '/bin/ls | ouesh ouesh | cat -e | defzrg | /ls | /bin/ls' "" "cat" multipipe_error "multipipe error" _test '/bin/ls | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e | /bin/cat -e' "" "cat" multi_pipe "Multi pipe" _test "$lot_of_pipe" "" "cat" fd_max "Pipe fd max" _test '|' "" "cat" only_a_pipe "Only a pipe" display_test_result ADVANCED_PIPE } function redirections () { $PURPLE ; echo "=----= REDIRECTIONS =----=" ; $WHITE _test 'ls > tests/binaries/redirection_test \ncat tests/binaries/redirection_test' "" cat redirections_simple_right "simple right redirection" _test 'ls > tests/binaries/redirection_test\nls >> tests/binaries/redirection_test\nls >> tests/binaries/redirection_test\n \ncat tests/binaries/redirection_test' "" cat redirections_double_right "double right redirection" _test 'cat < tests/binaries/div_zero.c' "" cat redirections_simple_left "simple left redirection" _test 'cat < tests/binaries/div_zero.c > tests/binaries/left_and_right\ncat tests/binaries/left_and_right' "" cat redirections_simple_left_then_right "simple left then right redirection" _test 'cat < MASHALLA' "" "cat" bad_redirection_left "Bad redirection left" _test 'ls > tests/' "" "cat" bad_redirection_right_directory "Bad redirection right (directory)" _test 'ls >' "" "cat" missing_name_redirect "Missing name for redirect" _test 'cat < cat < Makefile' "" "cat" ambiguous_redirect "Ambiguous input redirect" display_test_result REDIRECTIONS } function advanced_manipulations () { $PURPLE ; echo "=----= ADVANCED MANIPULATIONS =----=" ; $WHITE _test './42sh\nls' "" "cat" running_42sh_in_42sh "Running 42sh inside 42sh" display_test_result ADVANCED_MANIPULATIONS } function AND_and_OR_tests () { $PURPLE ; echo "=----= && AND || TESTS =----=" ; $WHITE _test 'ls && ls' "" cat AND_and_OR1 "AND simple test" _test 'ls || ls' "" cat AND_and_OR2 "OR simple test" _test 'ls || ls && ls' "" cat AND_and_OR3 "OR and AND advanced test 1" _test 'ls || ls && ls && jfweiji || cat telpw && grep' "" cat AND_and_OR4 "OR and AND advanced test 2" _test 'ls aerz || echo && ls' "" "cat" AND_and_OR5 "OR and AND 5" _test 'ls && ls && ls && ls || ls || ls && ls' "" "cat" AND_and_OR6 "OR and AND 6" _test 'ls || ls && ls || ls' "" "cat" AND_and_OR7 "OR and AND 7" _test 'ls aef || ls && ls azer' "" "cat" AND_and_OR8 "OR and AND 8" _test 'true && false || true && true' "" "cat" AND_and_OR9 "OR and AND 9" _test 'false || true && true' "" "cat" AND_and_OR10 "OR and AND 10" display_test_result AND_and_OR_TESTS } function globbing () { $PURPLE ; echo "=----= GLOBBING =----=" ; $WHITE _test 'ls ?ests' "" cat globbing1 "? globbing" _test 'ls [a-z]ests' "" cat globbing2 "[] globbing" _test 'ls [a-z]rew' "" cat globbing3 "error globbing" _test 'ls *' "" cat globbing4 "'*' globbing" display_test_result GLOBBING } function var_interpreter () { $PURPLE ; echo "=----= VAR INTERPRETER =----=" ; $WHITE _test 'echo $PATH' "" cat display_path "Display path" _test 'echo $INVALID' "" cat bad_var "Bad var" display_test_result GLOBBING } function inhibitor () { $PURPLE ; echo "=----= INHIBITOR =----=" ; $WHITE _test 'echo \"' "" cat echo_quote1 "Echo quote" _test 'echo \' "" cat echo_quote2 "Echo single \\" display_test_result INHIBITOR } function magic_quote() { $PURPLE ; echo "=----= MAGIC QUOTE =----=" ; $WHITE _test 'echo `python -c "print '"'A'"'*10"`' "" cat python_script "Python script" _test 'echo `echo $PATH`' "" cat variable_in_back_quote "Variable in back quote" _test 'echo `tac src/main.c | cat -e`' "" cat pipe_in_back_quote "Pipe in back quote" display_test_result MAGIC_QUOTE } function _alias () { $PURPLE ; echo "=----= ALIAS =----=" ; $WHITE _test 'alias lol ls \n lol' "" cat _alias1 "basic alias" _test 'alias lol=ls \n lol' "" cat _alias2 "error alias 1" _test 'alias lolle eqwo \n lollle' "" cat _alias3 "error alias 2" _test 'alias a b\nalias b a\nb' "" cat _alias4 "alias loop" display_test_result _ALIAS } function scripting () { $PURPLE ; echo "=----= SCRIPTING =----=" ; $WHITE display_test_result SCRIPTING } function _foreach () { $PURPLE ; echo "=----= FOREACH =----=" ; $WHITE _test 'foreach f (1 543 5) \n echo $f \n end' "" cat _foreach1 "basic foreach" _test 'foreach f (1) \n if($f) ls \n end' "" cat _foreach2 "combined with if foreach" display_test_result _FOREACH } function _which () { $PURPLE ; echo "=----= WHICH =----=" ; $WHITE _test 'unalias ls \n which ls' "" cat _which1 "basic where" _test 'which fewijpfow fpwokefew' "" cat _which2 "where error handling" _test 'unalias ls \n which ls' "" cat _which3 "builtin where" display_test_result _WHICH } function _where () { $PURPLE ; echo "=----= WHERE =----=" ; $WHITE _test 'unalias ls \n where ls' "" cat _where1 "basic where" _test 'where fewijpfow fpwokefew' "" cat _where2 "where error handling" _test 'unalias ls \n where ls' "" cat _where3 "builtin where" display_test_result _WHERE } function _if () { $PURPLE ; echo "=----= IF =----=" ; $WHITE _test 'if(1) ls' "" cat _if1 "basic if" _test 'if ($?) ls' "" cat _if2 "if with variable" _test 'if(0) ls' "" cat _if3 "null if" display_test_result _IF } function _repeat () { $PURPLE ; echo "=----= REPEAT =----=" ; $WHITE _test 'repeat 4 ls' "" cat repeat1 "basic repeat" _test 'repeat -1 ls' "" cat repeat2 "negative repeat" _test 'repeat 0 ls' "" cat repeat3 "null repeat" display_test_result _REPEAT } function parenthesis () { $PURPLE ; echo "=----= PARENTHESIS =----=" ; $WHITE _test '(ls | cat)' "" cat parenthesis1 "basic parenthesis" _test '(ls | cat) | grep test' "" cat parenthesis2 "parenthesis with something after" _test 'ls | (grep toto | cat)' "" cat parenthesis3 "parenthesis at the end" display_test_result PARENTHESIS } function personnals () { $PURPLE ; echo "=----= PERSONNALS =----=" ; $WHITE _test '/bin/ls' "env -i" cat ls "Basic test ls" _test '/bin/cd ..\n/bin/ls' "env -i" cat cd "Basic test cd" _test 'setenv' "env -i" cat env "Basic test env" _test 'setenv MDR 100\nsetenv | /usr/bin/grep MDR' "env -i" cat setenv "Basic test setenv" _test 'unsetenv PATH\nsetenv | /usr/bin/grep PATH' "" cat unsetenv "Basic test unsetenv" _test 'alias this_is_an_alias b && alias | grep this_is_an_alias' "" cat alias "Basic test alias" _test 'repeat 5 /bin/ls' "env -i" cat repeat "Basic test repeat" _test 'if (1) /bin/ls' "env -i" cat if10 "Basic test if" _test 'foreach f (1 2 3)\necho 1 + $f\nend\n' "" cat foreach "Basic test foreach" _test '/bin/ls > ls_output\n/bin/cat ls_output\n/usr/bin/rm ls_output' "" cat simple_right_redir "Basic test simple right redir" _test '/bin/ls >> ls_output\n/bin/ls >> ls_output\n/bin/cat ls_output\n/usr/bin/rm ls_output' "" cat double_right_redir "Basic test double right redir" display_test_result PERSONNALS } function randoms_tests () { $PURPLE ; echo "=----= RANDOMS_TESTS =----=" ; $WHITE _test 'cd ; </etc/hosts od -c | grep xx | wc >> /tmp/z -l ; cd - && echo "OK"' "" cat subject_test "subject test" _test 'jfeaoj && ls || cat test' "" cat big_multiple_test1 "big multiple test1" _test 'ls ; cat < | ls || grep' "" cat big_multiple_test2 "big multiple test2" _test ' ls; ls | grep sr || echo FAILED' "" cat big_multiple_test3 "big multiple test3" _test '|' "" cat big_multiple_test4 "big multiple test4" _test '&' "" cat big_multiple_test5 "big multiple test5" _test '&& ||' "" cat big_multiple_test6 "big multiple test6" _test 'ls&&ls' "" cat big_multiple_test7 "big multiple test7" _test 'zbeub || zbeub || ls | cat | grep sr' "" cat big_multiple_test8 "big multiple test8" _test 'cd test ; ls -a ; ls | cat | wc -c > tutu ; cat tutu' "" cat minishell2_subject_test "minishell 2 subject test" display_test_result RANDOMS_TESTS } function total () { $PURPLE ; echo "TOTAL" ; $WHITE $GREEN echo -ne "\tTest passed: $TOTAL_TESTS_PASSED\n" $RED echo -ne "\tTest failed: $TOTAL_TESTS_FAILED\n" $WHITE nb_test=$((TOTAL_TESTS_PASSED + TOTAL_TESTS_FAILED)) percentage=$((TOTAL_TESTS_PASSED * 100 / nb_test)) for i in {1..10} do if [ $i -lt $((percentage / 10)) ] then $GREEN ; echo -ne '♥ ' ; $WHITE else $PURPLE ; echo -ne '♥ ' ; $WHITE fi done $PURPLE ; echo "$percentage%" ; $WHITE } function all () { basic_test path_handling setenv_and_unsetenv builtin_cd line_formatting error_handling separator simple_pipe advanced_pipe personnals parenthesis _repeat _if _where _which _foreach _alias globbing AND_and_OR_tests redirections randoms_tests total } function clean () { rm -f ./tests/binaries/* rm -f ./tests/ftests/*.ftest } if [ $1 ] then $1 else all fi <file_sep>/lib/dnode/src/free.c /* ** EPITECH PROJECT, 2020 ** dnode ** File description: ** free */ /* free */ #include <stdlib.h> #include "dnode/free.h" void dnode_free(struct dnode_s **head, void (*func)(void *)) { struct dnode_s *prev = NULL; if (!*head) { return; } for (; (*head)->prev; *head = (*head)->prev) {} for (struct dnode_s *curr = *head; curr; curr = curr->next) { if (prev) { free(prev); } if (func) { func(curr->data); } prev = curr; } *head = NULL; } <file_sep>/include/proto/input.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** input header file. */ #ifndef SH_PROTO_INPUT_H_ #define SH_PROTO_INPUT_H_ /**/ /* Includes */ /**/ /**/ /* Constants */ /**/ /**/ /* Structures / Typedef / Enums declarations */ /**/ /**/ /* Function prototypes */ /**/ void input_destroy(struct sh *shell); #endif <file_sep>/include/proto/job/wait_for.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** wait for job */ #ifndef SH_PROTO_JOB_WAIT_FOR_H_ #define SH_PROTO_JOB_WAIT_FOR_H_ #include "types/shell.h" #include "types/job.h" void job_wait_for(struct sh *shell, struct job_s *first_job, struct job_s *job); #endif /* !SH_PROTO_JOB_WAIT_FOR_H_ */ <file_sep>/lib/parser_toolbox/include/parser_toolbox/isdir.h /* ** EPITECH PROJECT, 2020 ** parser_toolbox ** File description: ** parser_toolbox sort_string */ #ifndef PARSER_TOOLBOX_ISDIR_H_ #define PARSER_TOOLBOX_ISDIR_H_ #include "parser_toolbox/enum.h" enum parser_toolbox_e ptb_isdir(const char *path); #endif /* !PARSER_TOOLBOX_ISDIR_H_ */ <file_sep>/src/input/parser/input_parse_grammar.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** input_btree */ #include <stdlib.h> #include "types/grammar.h" #include "proto/expr.h" #include "proto/input/parser.h" static void input_parse_grammar_debug(struct sh *shell, struct grammar_s *this) { struct expr_program_s *expression; if (this->debug) dprintf(2, "\n=============== AST DEBUG MODE ===============\n"); expression = expr_program_w(this); if (this->error && this->debug) { if (this->error_message) { dprintf(2, "\n\033[1m\033[38;2;230;70;100mError: %s.\033[0m\n", this->error_message); } else { dprintf(2, "\n\033[1m\033[38;2;230;70;100mUnreso\ lved Error.\033[0m\n"); } } else if (!this->error && this->debug) { printf("\n\033[1m\033[38;2;150;200;0mTree Clean.\033[0m\n"); } if (this->debug) dprintf(2, "==============================================\n\n"); shell->expression = this->error ? NULL : expression; } /* ** @DESCRIPTION ** This function takes in a token list and populates a binary ** tree to later be executed. ** @TODO ** Find lib / libc implementation for 2d pointer array size getter. */ int input_parse_grammar(struct sh *shell) { struct grammar_s this = {0}; this.rawinput = shell->rawinput; this.debug = shell->debug_mode; this.tokens = (struct token_s **)node_to_table(shell->tokens); if (this.tokens == NULL) { shell->error = ER_MALLOC; return (1); } for (; this.tokens[this.token_count]; this.token_count++); input_parse_grammar_debug(shell, &this); if (this.error_message && !this.debug) dprintf(2, "%s.\n", this.error_message); return (this.error); } <file_sep>/lib/dnode/src/create.c /* ** EPITECH PROJECT, 2020 ** dnode ** File description: ** create */ /* malloc */ #include <stdlib.h> #include "dnode/create.h" /* ** @Description ** Create a new node with send data */ struct dnode_s *dnode_create(void *data) { struct dnode_s *new = malloc(sizeof(struct dnode_s)); if (!new) { return (NULL); } new->data = data; new->next = NULL; new->prev = NULL; return (new); } <file_sep>/src/shell/builtin_handlers/bg.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** builtins */ #include <stdio.h> #include "proto/job/utils.h" #include "builtins.h" #include "types/shell.h" #include "proto/shell/builtin_handlers.h" #include "proto/job/continue.h" int builtin_bg_handler( struct sh *shell, __attribute__((unused)) const char * const *argv ) { for (struct job_s *job = shell->job; job; job = job->next) { if (job_is_stopped(job)) { job->foreground = true; job_continue(shell, job); return (0); } } fprintf(stderr, "bg: No current job.\n"); return (1); } <file_sep>/src/exec/rule/control/else.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** exec rule control else */ #include "proto/exec/rule/debug.h" #include "proto/exec/rule/block.h" #include "proto/exec/rule/control/else.h" int exec_rule_control_else( struct sh *shell, struct expr_else_control_s *rule ) { exec_rule_debug(shell, "else", true); exec_rule_block(shell, rule->block); exec_rule_debug(shell, "else", false); return (0); } <file_sep>/lib/dnode/src/insert.c /* ** EPITECH PROJECT, 2020 ** dnode ** File description: ** insert */ #include <stddef.h> #include "dnode/insert.h" #include "dnode/create.h" /* ** @Description: ** Add a node at the beggining of the list */ void dnode_insert(struct dnode_s **head, struct dnode_s *node) { node->next = *head; node->prev = NULL; if (*head) { (*head)->prev = node; } *head = node; } /* ** @Description: ** Create a node and add it at the beggining of the list */ void dnode_insert_data(struct dnode_s **head, void *data) { struct dnode_s *new = dnode_create(data); if (!new) { return; } dnode_insert(head, new); } <file_sep>/src/shell/builtins_init.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** builtins */ #include <string.h> #include "builtins.h" #include "hasher/insert_data.h" #include "types/shell.h" #include "types/builtins.h" #include "proto/shell/builtin_handlers.h" #include "proto/shell/builtins.h" static const int BUILTIN_COUNT = 23; static const struct { const char *key; builtin_handler func; } BUILTINS_DICT[] = { {"which", &builtin_which_handler}, {"where", &builtin_where_handler}, {"unsetenv", &builtin_unsetenv_handler}, {"unset", &builtin_unset_handler}, {"unalias", &builtin_unalias_handler}, {"termname", &builtin_termname_handler}, {"source", &builtin_source_handler}, {"setenv", &builtin_setenv_handler}, {"set", &builtin_set_handler}, {"pop", &builtin_pop_handler}, {"jobs", &builtin_jobs_handler}, {"history", &builtin_history_handler}, {"fg", &builtin_fg_handler}, {"exit", &builtin_exit_handler}, {"echo", &builtin_echo_handler}, {"debug", &builtin_debug_handler}, {"cd", &builtin_change_directory_handler}, {"builtins", &builtin_builtins_handler}, {"bindkey", &builtin_bindkey_handler}, {"bg", &builtin_bg_handler}, {"alias", &builtin_alias_handler}, {"@", &builtin_at_handler}, {":", &builtin_null_command_handler}, }; struct hasher_s *shell_builtin_hash_create(void) { struct hasher_s *hash = NULL; for (int i = 0; i < BUILTIN_COUNT; ++i) { if (hasher_insert_data( &hash, strdup(BUILTINS_DICT[i].key), (void *) &BUILTINS_DICT[i].func) ) { return (NULL); } } return (hash); } <file_sep>/src/prompt/input/add_string.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** prompt action add_char */ /* isprint */ #include <ctype.h> #include "proto/prompt/input/add_char.h" #include "proto/prompt/input/add_string.h" void prompt_input_add_string(struct sh *shell, const char *str) { for (size_t index = 0; str[index] != '\0'; ++index) { if (isprint(str[index])) { prompt_input_add_char(shell, str[index]); } } } <file_sep>/include/proto/prompt/action/right.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** sh prompt action right */ #ifndef SH_PROTO_PROMPT_ACTION_RIGHT_H_ #define SH_PROTO_PROMPT_ACTION_RIGHT_H_ #include "types/shell.h" void prompt_action_right(struct sh *shell); #endif /* !SH_PROTO_PROMPT_ACTION_RIGHT_H_ */ <file_sep>/src/expr/while_control.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** expr_while_control */ #include <stdlib.h> #include <string.h> #include "proto/grammar.h" #include "proto/expr.h" static int expr_while_control_sub_test( struct grammar_s *this, struct expr_while_control_s *exp, unsigned int save_index ) { exp->while_token = grammar_get_previous(this); exp->wordlist_expression = expr_wordlist_expression_w(this); if (!exp->wordlist_expression) return (1); if (!grammar_match(this, 1, TOK_NEWLINE)) return (1); exp->wordlist_expression_newline = grammar_get_previous(this); save_index = this->index; exp->block = expr_block_w(this); if (!exp->block) this->index = save_index; return (0); } /* ** @DESCRIPTION ** Rule for while_control expression. */ static struct expr_while_control_s *expr_while_control(struct grammar_s *this) { struct expr_while_control_s *exp = malloc( sizeof(struct expr_while_control_s)); unsigned int save_index __attribute__((unused)) = this->index; if (!exp) exit(84); memset(exp, 0, sizeof(struct expr_while_control_s)); if (!grammar_match(this, 1, TOK_WHILE)) return (expr_free(exp)); if (expr_while_control_sub_test(this, exp, save_index)) expr_free(exp); if (!grammar_match(this, 1, TOK_END)) return (expr_free(exp)); exp->end = grammar_get_previous(this); if (this->tokens[this->index]->type == TOK_EOF) return exp; if (!grammar_match(this, 1, TOK_NEWLINE)) return (expr_free(exp)); exp->end_newline = grammar_get_previous(this); return exp; } struct expr_while_control_s *expr_while_control_w(struct grammar_s *this) { struct expr_while_control_s *exp; expr_print(this, "While Control"); exp = expr_while_control(this); expr_print_debug(this, exp); return exp; } <file_sep>/lib/dnode/Makefile ## ## EPITECH PROJECT, 2020 ## PSU_42sh_2019 ## File description: ## Makefile ## CC ?= gcc NAME = libdnode.a TESTNAME = unit_tests SRC = src/append.c \ src/apply.c \ src/create.c \ src/find.c \ src/free.c \ src/goto.c \ src/insert.c \ SRCT = tests/append.c \ tests/apply.c \ tests/create.c \ tests/find.c \ tests/free.c \ tests/goto.c \ tests/insert.c \ OBJ = $(SRC:.c=.o) OBJT = $(SRCT:.c=.o) WARNINGS = -pedantic -Wshadow -Wpointer-arith -Wcast-align \ -Wmissing-prototypes -Wmissing-declarations \ -Wnested-externs -Wwrite-strings -Wredundant-decls \ -Winline -Wno-long-long -Wconversion \ -Wstrict-prototypes \ DEBUG = -g $(WARNINGS) CFLAGS += -Wall -Wextra CPPFLAGS += -I include/ -I ../parser_toolbox/include TFLAGS += -lcriterion LDFLAGS += --coverage \ -L../parser_toolbox -lparser_toolbox \ all: $(NAME) $(NAME): $(OBJ) ar rc $(NAME) $(OBJ) tests_run: make -C ../parser_toolbox/ $(CC) $(SRC) $(SRCT) -o $(TESTNAME) $(TFLAGS) $(LDFLAGS) \ $(CPPFLAGS) $(CFLAGS) ./$(TESTNAME) 2>&1 | (grep -v "profiling") debug: fclean debug: CFLAGS += $(DEBUG) debug: $(NAME) clean: $(RM) $(OBJ) $(OBJT) *.gcno *.gcda fclean: clean $(RM) $(NAME) $(TESTNAME) fcleanlib: fclean make -C ../parser_toolbox/ fclean re: fclean all relib: fcleanlib all .PHONY: all clean fclean re tests_run fcleanlib relib <file_sep>/include/proto/exec/builtins.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** shell shell_builtin_hash_create */ #ifndef SH_SHELL_EXEC_BUILTINS_H_ #define SH_SHELL_EXEC_BUILTINS_H_ #endif /* !SH_SHELL_EXEC_BUILTINS_H_ */ <file_sep>/src/exec/rule/statement.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** exec rule statement */ #include "proto/exec/rule/debug.h" #include "proto/exec/rule/subshell.h" #include "proto/exec/rule/compound.h" #include "proto/exec/rule/control.h" #include "proto/exec/rule/statement.h" int exec_rule_statement( struct sh *shell, struct expr_statement_s *rule ) { exec_rule_debug(shell, "statement", true); if (rule->compound) { return (exec_rule_compound(shell, rule->compound)); } if (rule->control) { return (exec_rule_control(shell, rule->control)); } return (0); } <file_sep>/include/proto/job/process/append.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** append job process */ #ifndef SH_PROTO_JOB_PROCESS_APPEND_H_ #define SH_PROTO_JOB_PROCESS_APPEND_H_ #include "types/job.h" void job_process_append(struct job_s *job, struct process_s *new_process); #endif /* !SH_PROTO_JOB_PROCESS_APPEND_H_ */ <file_sep>/src/job/continue.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** process */ #include "proto/job/put_in.h" #include "proto/job/continue.h" static void mark_job_as_running(struct job_s *job) { struct process_s *process; for (process = job->first_process; process; process = process->next) { process->stopped = false; } job->notified = false; } void job_continue(struct sh *shell, struct job_s *job) { mark_job_as_running(job); if (job->foreground) { job_put_in_foreground(shell, job, true); } else { job_put_in_background(job, true); } } <file_sep>/include/proto/job/launch.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** constants header file. */ #ifndef SH_PROTO_JOB_LAUNCH_H_ #define SH_PROTO_JOB_LAUNCH_H_ #include <stdbool.h> #include "types/shell.h" #include "types/job.h" void job_launch(struct sh *shell, struct job_s *job); #endif /* !SH_PROTO_JOB_LAUNCH_H_ */ <file_sep>/lib/mynode/src/node_to_table.c /* ** EPITECH PROJECT, 2020 ** mynode ** File description: ** node_to_table */ #include <stdlib.h> #include "mynode.h" /* ** @DESCRIPTION ** This function transforms a linked list into a NULL ** terminated 2d array. */ void **node_to_table(NODE *const head) { unsigned int i = 0; void **table = malloc(sizeof(void *) * (node_size(head) + 1)); for (NODE *curr = head; curr; curr = curr->next) { table[i] = curr->data; i++; } table[i] = NULL; return table; } /* ** @DESCRIPTION ** This function transforms a linked list into a NULL ** terminated 2d array. */ void node_from_table(void **array, NODE **head) { for (unsigned int i = 0; array[i]; i++) { node_insert(head, array[i]); } node_reverse(head); }<file_sep>/lib/mynode/src/node_size.c /* ** EPITECH PROJECT, 2020 ** mynode ** File description: ** node_list_size */ #include "mynode.h" /* ** @DESCRIPTION ** Counts the number of nodes in a linked list. ** @RETURN_VALUE ** The number of nodes as an unsigned int. */ unsigned int node_size(NODE *head) { unsigned int size = 0; while (head) { size++; head = head->next; } return size; } <file_sep>/include/proto/exec/rule/separator.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** shell exec rule separator */ #ifndef SH_SHELL_EXEC_RULE_SEPARATOR_H_ #define SH_SHELL_EXEC_RULE_SEPARATOR_H_ #include "types/shell.h" #include "types/expr.h" int exec_rule_separator( struct sh *shell, struct expr_separator_s *rule ); #endif /* !SH_SHELL_EXEC_RULE_SEPARATOR_H_ */ <file_sep>/src/prompt/input/add_char.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** prompt action add_char */ #include <stdio.h> #include "parser_toolbox/add_char.h" #include "types/shell.h" #include "types/prompt/effect.h" #include "proto/prompt/update_cursor_pos.h" #include "proto/prompt/input/add_char.h" void prompt_input_add_char(struct sh *shell, char c) { ptb_add_char(shell->prompt.input, shell->prompt.cursor, c); shell->prompt.length += 1; if (shell->atty) { fputs(shell->prompt.input + shell->prompt.cursor, stdout); shell->prompt.cursor += 1; prompt_update_cursor_pos(&(shell->prompt)); } else { shell->prompt.cursor += 1; } } <file_sep>/src/expr/redirection.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** expr_redirection */ #include <stdlib.h> #include <string.h> #include "proto/constants.h" #include "proto/grammar.h" #include "proto/expr.h" /* ** @DESCRIPTION ** Rule for redirection expression. */ static struct expr_redirection_s *expr_redirection(struct grammar_s *this) { struct expr_redirection_s *exp = malloc( sizeof(struct expr_redirection_s)); unsigned int save_index __attribute__((unused)) = this->index; if (!exp) exit(84); memset(exp, 0, sizeof(struct expr_redirection_s)); if (grammar_match(this, 1, TOK_IONUMBER)) exp->io_number = grammar_get_previous(this); if (!grammar_match(this, 4, TOK_GREAT, TOK_DGREAT, TOK_LESS, TOK_DLESS)) return (expr_free(exp)); exp->redirection = grammar_get_previous(this); if (!grammar_match(this, 1, TOK_WORD)) { grammar_set_error(this, AST_MISSING_REDIRECT_NAME); return (expr_free(exp)); } exp->word = grammar_get_previous(this); return exp; } struct expr_redirection_s *expr_redirection_w(struct grammar_s *this) { struct expr_redirection_s *exp; expr_print(this, "Redirection"); exp = expr_redirection(this); expr_print_debug(this, exp); return exp; } <file_sep>/lib/parser_toolbox/include/parser_toolbox/blacklist.h /* ** EPITECH PROJECT, 2020 ** parser_toolbox ** File description: ** parser_toolbox blacklist */ #ifndef PARSER_TOOLBOX_BLACKLIST_H_ #define PARSER_TOOLBOX_BLACKLIST_H_ #include <stdbool.h> bool ptb_blacklist(const char *string, const char * restrict blacklist); #endif /* !PARSER_TOOLBOX_BLACKLIST_H_ */ <file_sep>/lib/parser_toolbox/src/argv_length.c /* ** EPITECH PROJECT, 2020 ** parser_toolbox ** File description: ** ptb_argv_length */ /* */ #include "parser_toolbox/argv_length.h" size_t ptb_argv_length(const char * const *argv) { size_t len = 0; while (argv[len]) { ++len; } return (len); } <file_sep>/src/main.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** main */ /* This comment is to experiment the CI pipeline */ #include "proto/shell.h" /* ** @DESCRIPTION ** Main. */ int main(int argc, char *const *argv, char * const *envp) { struct sh shell; if (shell_struct_initialise(&shell, argc, argv, envp)) { return (84); } if (shell_start(&shell)) { return (84); } shell_destroy(&shell); return (0); } <file_sep>/tests/input/parser/test_input_parse_tokens_batch_1.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** input_parse_tokens - test */ #include <criterion/criterion.h> #include <string.h> #include "tests/mock_types.h" #include "proto/input/parser.h" Test(input_parse_tokens, subbatch_1) { struct sh shell = MOCK_SH; struct node_s *curr; struct token_s *token; enum tokent_e types[] = {TOK_WORD, TOK_GREAT, TOK_DGREAT, TOK_LESS, TOK_DLESS, TOK_PIPE, TOK_OR_IF, TOK_ENDIF, TOK_WHILE, TOK_IF, TOK_GREAT, TOK_WORD, TOK_EOF}; shell.rawinput = strdup("word> >> < << | || endif while if> whil"); input_parse_tokens(&shell); curr = shell.tokens; for (unsigned int i = 0; types[i] != TOK_EOF; i++) { if (!curr) { cr_assert(0); return; } token = curr->data; cr_assert_eq(types[i], token->type); curr = curr->next; } } Test(input_parse_tokens, subbatch_2) { struct sh shell = MOCK_SH; struct node_s *curr; struct token_s *token; enum tokent_e types[] = {TOK_NEWLINE, TOK_LPARANTH, TOK_WORD, TOK_RPARANTH, TOK_WORD, TOK_IF, TOK_REPEAT, TOK_EOF}; shell.rawinput = strdup("\n({})!break if repeat"); input_parse_tokens(&shell); curr = shell.tokens; for (unsigned int i = 0; types[i] != TOK_EOF; i++) { if (!curr) { cr_assert(0); return; } token = curr->data; cr_assert_eq(types[i], token->type); curr = curr->next; } } <file_sep>/src/expr/destroy/wordlist.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** expr_wordlist */ /* free */ #include <stdlib.h> #include "proto/expr_destroy.h" /* ** @DESCRIPTION ** Rule for wordlist expression. */ void expr_wordlist_destroy(struct expr_wordlist_s *this) { if (!this) { return; } expr_wordlist_destroy(this->wordlist); free(this); } <file_sep>/include/proto/expr.h /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** expr header file. */ #ifndef SH_PROTO_EXPR_H_ #define SH_PROTO_EXPR_H_ /**/ /* Includes */ /**/ #include <stdio.h> #include "types/expr.h" /**/ /* Constants */ /**/ /**/ /* Structures / Typedef / Enums declarations */ /**/ /**/ /* Function prototypes */ /**/ void *expr_free(void *expr); void expr_print_padding(unsigned int depth); void expr_print(struct grammar_s *this, char const *name); void expr_print_debug(struct grammar_s *this, void *ptr); struct expr_program_s *expr_program_w(struct grammar_s *this); struct expr_block_s *expr_block_w(struct grammar_s *this); struct expr_statement_s *expr_statement_w(struct grammar_s *this); struct expr_jobs_s *expr_jobs_w( struct grammar_s *this); struct expr_subshell_s *expr_subshell_w(struct grammar_s *this); struct expr_grouping_s *expr_grouping_w(struct grammar_s *this); struct expr_pipeline_s *expr_pipeline_w(struct grammar_s *this); struct expr_command_s *expr_command_w(struct grammar_s *this); struct expr_redirection_s *expr_redirection_w(struct grammar_s *this); struct expr_separator_s *expr_separator_w(struct grammar_s *this); struct expr_control_s *expr_control_w(struct grammar_s *this); struct expr_if_control_s *expr_if_control_w(struct grammar_s *this); struct expr_else_if_control_s *expr_else_if_control_w(struct grammar_s *this); struct expr_else_control_s *expr_else_control_w(struct grammar_s *this); struct expr_while_control_s *expr_while_control_w(struct grammar_s *this); struct expr_foreach_control_s *expr_foreach_control_w(struct grammar_s *this); struct expr_repeat_control_s *expr_repeat_control_w(struct grammar_s *this); struct expr_wordlist_expression_s *expr_wordlist_expression_w( struct grammar_s *this ); struct expr_wordlist_s *expr_wordlist_w(struct grammar_s *this); struct expr_compound_s *expr_compound_w(struct grammar_s *this); struct expr_if_inline_control_s *expr_if_inline_control_w( struct grammar_s *this); int do_ambiguous_redirection_check( struct grammar_s *grammar, struct expr_pipeline_s *this ); #endif <file_sep>/src/exec/rule/program.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** exec rule program */ #include "proto/exec/rule/debug.h" #include "proto/exec/rule/block.h" #include "proto/exec/rule/program.h" int exec_rule_program( struct sh *shell, struct expr_program_s *rule ) { exec_rule_debug(shell, "program", true); if (rule->block) { exec_rule_block(shell, rule->block); } else { } exec_rule_debug(shell, "program", false); return (0); } <file_sep>/src/exec/rule/compound.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** exec rule block */ #include "proto/exec/rule/debug.h" #include "proto/exec/rule/grouping.h" #include "proto/exec/rule/jobs.h" #include "proto/exec/rule/compound.h" int exec_rule_compound( struct sh *shell, struct expr_compound_s *rule ) { exec_rule_debug(shell, "compound", true); exec_rule_grouping( shell, rule->grouping, rule->jobs ? !rule->jobs->ampersand : true ); if (rule->jobs) { exec_rule_jobs(shell, rule->jobs, !rule->ampersand_end); } exec_rule_debug(shell, "compound", false); return (0); } <file_sep>/lib/parser_toolbox/include/parser_toolbox/add_char.h /* ** EPITECH PROJECT, 2020 ** parser_toolbox ** File description: ** parser_toolbox add_char */ #ifndef PARSER_TOOLBOX_ADD_CHAR_H_ #define PARSER_TOOLBOX_ADD_CHAR_H_ #include <stddef.h> void ptb_add_char(char *str, size_t pos, char c); #endif /* !PARSER_TOOLBOX_ADD_CHAR_H_ */ <file_sep>/lib/parser_toolbox/include/parser_toolbox/strrep.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** strrep */ #ifndef PARSER_TOOLBOX_STRREP_H_ #define PARSER_TOOLBOX_STRREP_H_ char *ptb_strrep(char *str, char a, char b); #endif /* !PARSER_TOOLBOX_STRREP_H_ */ <file_sep>/include/proto/prompt/action/cut_line.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** sh prompt action cut_line */ #ifndef SH_PROTO_PROMPT_ACTION_CUT_LINE_H_ #define SH_PROTO_PROMPT_ACTION_CUT_LINE_H_ #include "types/shell.h" void prompt_action_cut_line(struct sh *shell); #endif /* !SH_PROTO_PROMPT_ACTION_CUT_LINE_H_ */ <file_sep>/include/constants/tokens.h /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** tokens header file. */ #ifndef SH_CONSTANTS_TOKENS_H_ #define SH_CONSTANTS_TOKENS_H_ /**/ /* Includes */ /**/ /**/ /* Constants */ /**/ static const char *TOKENS[] = { "", /* UNKNOW */ "", /* EOF */ 0, /* WORD */ "\n", /* NEWLINE */ 0, /* IO_NUMBER */ "<", /* LESS */ ">", /* GREAT */ "|", /* PIPE */ ";", /* SEMI */ "&", /* AMPERSAND */ "&&", /* AND_IF */ "||", /* OR_IF */ ";;", /* DSEMI */ "<<", /* DLESS */ ">>", /* DGREAT */ "<&", /* LESSAND */ ">&", /* GREATAND */ "<>", /* LESSGREAT */ "<<-", /* DLESSDASH */ ">|", /* CLOBBER */ "{", /* LBRACE */ "}", /* RBRACE */ "(", /* LBRACE */ ")", /* RBRACE */ "break", /* BREAK */ "switch", /* SWITCH */ "case", /* CASE */ "breaksw", /* BREAKSW */ "default:", /* DEFAULT */ "endsw", /* ENDSW */ "continue", /* CONTINUE */ "foreach", /* FOREACH */ "endif", /* ENDIF */ "end", /* END */ "goto", /* GOTO */ "if", /* IF */ "else if", /* ELSE IF */ "else", /* ELSE */ "then", /* THEN */ "repeat", /* REPEAT */ "while" /* WHILE */ }; /**/ /* Structures / Typedef / Enums declarations */ /**/ /**/ /* Function prototypes */ /**/ #endif <file_sep>/lib/hasher/include/hasher/filter.h /* ** EPITECH PROJECT, 2020 ** hasher ** File description: ** hasher filter */ #ifndef HASHER_FILTER_H_ #define HASHER_FILTER_H_ #include "hasher/type.h" struct hasher_s *hasher_filter( struct hasher_s **hasher, const char *key, size_t len ); #endif /* !HASHER_FILTER_H_ */ <file_sep>/include/proto/prompt/action/home.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** sh prompt action home */ #ifndef SH_PROTO_PROMPT_ACTION_HOME_H_ #define SH_PROTO_PROMPT_ACTION_HOME_H_ #include "types/shell.h" void prompt_action_home(struct sh *shell); #endif /* !SH_PROTO_PROMPT_ACTION_HOME_H_ */ <file_sep>/include/proto/job/process/launch.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** constants header file. */ #ifndef SH_PROTO_JOB_PROCESS_LAUNCH_H_ #define SH_PROTO_JOB_PROCESS_LAUNCH_H_ #include <stdbool.h> #include "types/shell.h" #include "types/job.h" void process_launch( struct sh *shell, struct job_s *job, struct process_s *process, int fds[IO_COUNT] ); #endif /* !SH_PROTO_JOB_PROCESS_LAUNCH_H_ */ <file_sep>/lib/find_binary/src/double_array_size.c /* ** EPITECH PROJECT, 2020 ** find_binary ** File description: ** double_array_size */ #include <stdlib.h> /* */ #include "double_array_size.h" int double_array_size(void **array, size_t *allocated) { if (*array != NULL) { free(*array); } *allocated *= 2; *array = malloc(sizeof(char) * (*allocated)); return (*array == NULL); } <file_sep>/lib/parser_toolbox/include/parser_toolbox/word_array_chr.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** word_array_chr */ #ifndef PARSER_TOOLBOX_WORD_ARRAY_CHR_H_ #define PARSER_TOOLBOX_WORD_ARRAY_CHR_H_ #include <stddef.h> char **ptb_word_array_parse( char **word_array, size_t size, char c, char *(*func)(const char *, int) ); char **ptb_word_array_chr(char **word_array, size_t size, char c); char **ptb_word_array_rchr(char **word_array, size_t size, char c); #endif /* !PARSER_TOOLBOX_WORD_ARRAY_CHR_H_ */ <file_sep>/lib/find_binary/src/find_binary_in_path_env.c /* ** EPITECH PROJECT, 2020 ** find_binary ** File description: ** find_binary_in_path_env */ #include <stddef.h> #include "path_iteration.h" #include "find_file_in_path.h" /* */ #include "find_binary_in_path_env.h" char *find_binary_in_path_env(const char *path_env, const char *bin) { char *full_path = NULL; const char *path = path_iteration(path_env); for (; path && !full_path; path = path_iteration(path_env)) { full_path = find_file_in_path(path, bin); } for (; path; path = path_iteration(path_env)); return (full_path); } <file_sep>/include/proto/prompt.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** prompt header file. */ #ifndef SH_PROTO_PROMPT_H_ #define SH_PROTO_PROMPT_H_ /**/ /* Includes */ /**/ #include "types/shell.h" /**/ /* Constants */ /**/ /**/ /* Structures / Typedef / Enums declarations */ /**/ /**/ /* Function prototypes */ /**/ void prompter(struct sh *shell); void prompt_shell(struct sh *shell); #endif <file_sep>/lib/hasher/include/hasher/replace_data.h /* ** EPITECH PROJECT, 2020 ** hasher ** File description: ** hasher replace_data */ #ifndef HASHER_REPLACE_DATA_H_ #define HASHER_REPLACE_DATA_H_ #include "hasher/type.h" void *hasher_replace_data( struct hasher_s *hasher, const char *current_data, char *new_data ); #endif /* !HASHER_REPLACE_DATA_H_ */ <file_sep>/lib/input_postprocessing/tests/quote_cleanup.c /* ** EPITECH PROJECT, 2020 ** input_postprocessing ** File description: ** test builtin_setenv */ #include <string.h> #include <criterion/criterion.h> #include "postprocess/quote_cleanup.h" Test(ipp_quote_cleanup, very_simple_quote_cleanup) { char *dirty_string = strdup("\"I am not so dirty\""); ipp_quote_cleanup(dirty_string); cr_assert_str_eq(dirty_string, "I am not so dirty"); } Test(ipp_quote_cleanup, simple_quote_cleanup) { char *dirty_string = strdup("\"I \"a'm a bit '\"dirty \\\"\"':)\\'"); ipp_quote_cleanup(dirty_string); cr_assert_str_eq(dirty_string, "I am a bit dirty \":)\\"); } Test(ipp_quote_cleanup, medium_quote_cleanup) { char *dirty_string = strdup("I' am 'gen'ui'\"nel\"'y 'dirty"); ipp_quote_cleanup(dirty_string); cr_assert_str_eq(dirty_string, "I am genuinely dirty"); } Test(ipp_quote_cleanup, hard_quote_cleanup) { char *dirty_string = strdup("\"\"\"\"I\" 'a'm \"'s'o\" \\\"dirty\""); ipp_quote_cleanup(dirty_string); cr_assert_str_eq(dirty_string, "I 'a'm so \"dirty"); } Test(ipp_quote_cleanup, tricky_single_quote) { char *dirty_string = strdup("'""\\'\\'"); ipp_quote_cleanup(dirty_string); cr_assert_str_eq(dirty_string, "\\'"); } <file_sep>/include/proto/job/process/update_status.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** job process update status */ #ifndef SH_PROTO_JOB_PROCESS_UPDATE_STATUS_H_ #define SH_PROTO_JOB_PROCESS_UPDATE_STATUS_H_ #include <sys/types.h> #include "types/shell.h" #include "types/job.h" int job_process_update_status( struct sh *shell, struct job_s *first_job, pid_t pid, int status ); #endif /* !SH_PROTO_JOB_PROCESS_UPDATE_STATUS_H_ */ <file_sep>/src/expr/compound.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** expr_compound */ #include <stdlib.h> #include <string.h> #include "proto/grammar.h" #include "proto/expr.h" /* ** @DESCRIPTION ** Rule for compound expression. */ static struct expr_compound_s *expr_compound(struct grammar_s *this) { struct expr_compound_s *exp = calloc(1, sizeof(struct expr_compound_s)); unsigned int save_index = this->index; if (!exp) exit(84); if (grammar_match(this, 1, TOK_AMPERSAND)) exp->ampersand_start = grammar_get_previous(this); exp->grouping = expr_grouping_w(this); if (!exp->grouping) return (expr_free(exp)); save_index = this->index; exp->jobs = expr_jobs_w(this); if (!exp->jobs) this->index = save_index; if (grammar_match(this, 1, TOK_AMPERSAND)) exp->ampersand_start = grammar_get_previous(this); exp->separator = expr_separator_w(this); if (!exp->separator) return (expr_free(exp)); return exp; } struct expr_compound_s *expr_compound_w(struct grammar_s *this) { struct expr_compound_s *exp; expr_print(this, "Compound"); exp = expr_compound(this); expr_print_debug(this, exp); return exp; } <file_sep>/include/types/job.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** job */ #ifndef SH_TYPES_JOB_H_ #define SH_TYPES_JOB_H_ #include <termios.h> #include <stdbool.h> #include <stddef.h> enum process_io_e { IO_NOT = -1, IO_IN, IO_OUT, IO_ERR, IO_COUNT }; struct process_s { struct process_s *next; char **argv; size_t argc; size_t max_argc; pid_t pid; bool completed; bool stopped; char *subshell; int status; }; struct job_s { struct job_s *next; char *command; struct process_s *first_process; pid_t pgid; bool notified; struct termios tmodes; int io[IO_COUNT]; bool foreground; int launch_id; }; #endif /* !SH_TYPES_JOB_H_ */ <file_sep>/src/grammar/grammar_advance.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** grammar_advance */ #include "proto/grammar.h" #include "proto/expr.h" #include "tests/tokens.h" /* ** @DESCRIPTION ** Consumes a pointer if there are tokens remaining in the array. */ struct token_s *grammar_advance(struct grammar_s *this) { if (this->index < this->token_count) { if (this->debug) { expr_print_padding(this->depth); printf("└─ " "\033[1m\033[38;2;230;70;200m%s\033[0m\n", TOK_NAMES[this->tokens[this->index]->type] ); } this->index++; } return this->tokens[this->index]; } <file_sep>/src/expr/destroy/if_control.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** expr_if_control */ /* free */ #include <stdlib.h> #include "proto/expr_destroy.h" /* ** @DESCRIPTION ** Rule for if_control expression. */ void expr_if_control_destroy(struct expr_if_control_s *this) { if (!this) { return; } expr_wordlist_expression_destroy(this->wordlist_expression); expr_block_destroy(this->block); expr_else_if_control_destroy(this->else_if_control); free(this); } <file_sep>/src/shell/builtin_handlers/jobs.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** builtins */ #include <stdio.h> #include <string.h> #include "builtins.h" #include "types/shell.h" #include "proto/shell/builtin_handlers.h" #include "proto/job/continue.h" int builtin_jobs_handler(struct sh *shell, const char * const *argv) { if (builtins_utils_too_many_arguments(argv, 1)) { return (1); } if (argv[1] && strcmp(argv[1], "-l")) { dprintf(2, "Usage: jobs [ -l ].\n"); return (1); } for (struct job_s *job = shell->job; job; job = job->next) { } return (0); } <file_sep>/src/expr/if_control.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** expr_if_control */ #include <stdlib.h> #include <string.h> #include "proto/grammar.h" #include "proto/expr.h" static struct expr_if_control_s *expr_if_control_n( struct grammar_s *this, struct expr_if_control_s *exp, unsigned int save_index ) { exp->block = expr_block_w(this); if (!exp->block) return (expr_free(exp)); save_index = this->index; exp->else_if_control = expr_else_if_control_w(this); if (!exp->else_if_control) this->index = save_index; save_index = this->index; exp->else_control = expr_else_control_w(this); if (!exp->else_control) this->index = save_index; if (!grammar_match(this, 1, TOK_ENDIF)) return (expr_free(exp)); exp->endif = grammar_get_previous(this); if (this->tokens[this->index]->type == TOK_EOF) return exp; if (!grammar_match(this, 1, TOK_NEWLINE)) return (expr_free(exp)); exp->endif_newline = grammar_get_previous(this); return exp; } /* ** @DESCRIPTION ** Rule for if_control expression. */ static struct expr_if_control_s *expr_if_control(struct grammar_s *this) { struct expr_if_control_s *exp = malloc(sizeof(struct expr_if_control_s)); unsigned int save_index = this->index; if (!exp) exit(84); memset(exp, 0, sizeof(struct expr_if_control_s)); if (!grammar_match(this, 1, TOK_IF)) return (expr_free(exp)); exp->if_token = grammar_get_previous(this); exp->wordlist_expression = expr_wordlist_expression_w(this); if (!exp->wordlist_expression) return (expr_free(exp)); if (!grammar_match(this, 1, TOK_THEN)) return (expr_free(exp)); exp->then = grammar_get_previous(this); if (!grammar_match(this, 1, TOK_NEWLINE)) return (expr_free(exp)); exp->then_newline = grammar_get_previous(this); return expr_if_control_n(this, exp, save_index); } struct expr_if_control_s *expr_if_control_w(struct grammar_s *this) { struct expr_if_control_s *exp; expr_print(this, "If Control"); exp = expr_if_control(this); expr_print_debug(this, exp); return exp; } <file_sep>/src/job/process/create.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** exec rule command */ #include <stdlib.h> #include "proto/job/process/create.h" static const size_t PROCESS_ARGV_DEFAULT_SIZE = 32; struct process_s *process_create(void) { struct process_s *process = malloc(sizeof(struct process_s)); if (process == NULL) { return (NULL); } *process = (struct process_s) { .next = NULL, .argv = calloc(PROCESS_ARGV_DEFAULT_SIZE, sizeof(char *)), .argc = 0, .max_argc = PROCESS_ARGV_DEFAULT_SIZE, .pid = 0, .completed = false, .stopped = false, .subshell = NULL, .status = 0 }; return (process); } <file_sep>/src/shell/alias_init.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** alias */ #include <string.h> #include "hasher/insert_data.h" #include "proto/shell/alias.h" /* No more, source .42shrc && .42sh_profile && .42sh_history */ struct hasher_s *shell_alias_hash_create(void) { struct hasher_s *hash = NULL; return (hash); } <file_sep>/lib/parser_toolbox/include/parser_toolbox/consts.h /* ** EPITECH PROJECT, 2020 ** parser_toolbox ** File description: ** parser_toolbox hexdumper */ #ifndef PARSER_TOOLBOX_HEXDUMPER_H_ #define PARSER_TOOLBOX_HEXDUMPER_H_ extern const char PTB_WHITESPACES[]; extern const char PTB_DIGITS[]; extern const char PTB_ALPHANUM[]; #endif /* !PARSER_TOOLBOX_HEXDUMPER_H_ */ <file_sep>/src/exec/rule/control/if.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** exec rule control if */ #include "proto/exec/rule/debug.h" #include "proto/exec/rule/control/check_condition.h" #include "proto/exec/rule/block.h" #include "proto/exec/rule/control/else.h" #include "proto/exec/rule/control/else_if.h" #include "proto/exec/rule/control/if.h" int exec_rule_control_if( struct sh *shell, struct expr_if_control_s *rule ) { int condition = exec_rule_control_check_condition( shell, rule->wordlist_expression ); if (condition == -1) return (1); exec_rule_debug(shell, "if", true); if (condition) { exec_rule_block(shell, rule->block); } else if (rule->else_if_control) { if (exec_rule_control_else_if(shell, rule->else_if_control)) { exec_rule_control_else(shell, rule->else_control); } } else { exec_rule_control_else(shell, rule->else_control); } exec_rule_debug(shell, "if", false); return (0); } <file_sep>/lib/parser_toolbox/src/sub_str_chr.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** sub_str_chr */ #include "parser_toolbox/sub_str_chr.h" bool ptb_sub_str_chr( char *str, size_t start, size_t end, char c ) { if (start > end) { return (false); } for (size_t i = start; i < end; ++i) { if (str[i] == c) { return (true); } } return (false); } <file_sep>/src/expr/destroy/block.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** expr_block */ #include <stdlib.h> #include "proto/expr_destroy.h" /* ** @DESCRIPTION ** Rule for block expression. */ void expr_block_destroy(struct expr_block_s *this) { if (!this) { return; } expr_statement_destroy(this->statement); expr_block_destroy(this->block); free(this); } <file_sep>/src/prompt/actions/arrows.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** prompt action arrows */ /* putp */ #include <curses.h> #include <string.h> #include <term.h> #include "dnode.h" #include "proto/prompt/action/left.h" #include "proto/prompt/action/right.h" #include "proto/prompt/action/down.h" #include "proto/prompt/action/up.h" #include "proto/prompt/action/clear_line.h" #include "proto/prompt/input/add_string.h" #include "proto/prompt/history.h" void prompt_action_left(struct sh *shell) { if (shell->prompt.cursor) { --shell->prompt.cursor; putp(shell->prompt.effect[PROMPT_EFFECT_CURSOR_BACKWARD]); } } void prompt_action_right(struct sh *shell) { if ((shell->prompt.input)[shell->prompt.cursor]) { ++shell->prompt.cursor; putp(shell->prompt.effect[PROMPT_EFFECT_CURSOR_FORWARD]); } } void prompt_action_up(struct sh *shell) { if (!shell->history.curr) { shell->history.curr = shell->history.list; strcpy(shell->history.current_input, shell->prompt.input); } else if (shell->history.curr->next) { shell->history.curr = shell->history.curr->next; } prompt_action_clear_line(shell); if (shell->history.curr) { prompt_input_add_string(shell, (char *) shell->history.curr->data); } else { prompt_input_add_string(shell, shell->history.current_input); } } void prompt_action_down(struct sh *shell) { if (shell->history.curr) { shell->history.curr = shell->history.curr->prev; } prompt_action_clear_line(shell); if (shell->history.curr) { prompt_input_add_string(shell, (char *) shell->history.curr->data); } else { prompt_input_add_string(shell, shell->history.current_input); } } <file_sep>/include/proto/exec/rule/control.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** shell exec rule control */ #ifndef SH_SHELL_EXEC_RULE_CONTROL_H_ #define SH_SHELL_EXEC_RULE_CONTROL_H_ #include "types/shell.h" #include "types/expr.h" int exec_rule_control( struct sh *shell, struct expr_control_s *rule ); #endif /* !SH_SHELL_EXEC_RULE_CONTROL_H_ */ <file_sep>/src/shell/constants.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** constants */ #include "proto/constants.h" /* ** @DESCRIPTION ** Defines the character set to be used as whitespace when parsing */ const char *WHITESPACE = " \t"; /* ** @DESCRIPTION ** Character set used when validating the TOK_WORD. */ const char *TOK_WORD_BLACKLIST = " \n|><&();"; /* ** @DESCRIPTION ** Grammar error messages. */ const char *AST_EMPTY_IF = "Empty if statement"; const char *AST_EMPTY_ELSE = "Empty else statement"; const char *AST_EMPTY_ELSE_IF = "Empty else if statement"; const char *AST_EMPTY_WHILE = "Empty while statement"; const char *AST_EMPTY_FOREACH = "Empty foreach statement"; const char *AST_EMPTY_REPEAT = "Empty repeat statement"; const char *AST_ELSE_IF_MISSING_THEN = "Expected a 'then' after 'else if'"; const char *AST_ELSE_MISSING_NEWLINE = "Expected a 'newline' after 'else'"; const char *AST_THEN_MISSING_NEWLINE = "Expected a 'newline' after 'then'"; const char *AST_INVALID_EXPRESSION = "Invalid expression"; const char *AST_NULL_COMMAND = "Invalid null command"; const char *AST_REPEAT_TOO_FEW_ARGS = "repeat: Too few arguments"; const char *AST_UNEXPECTED_TOKENS = "Invalid null command"; const char *AST_AMBIGUOUS_REDIRECTION1 = "Ambiguous input redirect"; const char *AST_AMBIGUOUS_REDIRECTION2 = "Ambiguous output redirect"; const char *AST_MISSING_REDIRECT_NAME = "Missing name for redirect"; <file_sep>/src/exec/rule/subshell.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** exec rule subshell */ #include "proto/exec/rule/debug.h" #include "proto/exec/rule/block.h" #include "proto/exec/rule/subshell.h" #include "proto/token/get_string.h" #include "proto/job/process/create.h" #include "proto/job/process/append.h" #include "proto/exec/magic/parse.h" int exec_rule_subshell( struct sh *shell, struct expr_subshell_s *rule, struct job_s *job ) { struct process_s *process = process_create(); unsigned int save = rule->lparanth->end; exec_rule_debug(shell, "subshell", true); rule->lparanth->end = rule->rparanth->end - 1; ++rule->lparanth->start; process->subshell = token_get_string(rule->lparanth, shell->rawinput); rule->lparanth->end = save; --rule->lparanth->start; job_process_append(job, process); exec_rule_debug(shell, "subshell", false); return (0); } <file_sep>/lib/builtins/tests/change_directory.c /* ** EPITECH PROJECT, 2020 ** builtins ** File description: ** test change_directory */ /* getcwd */ #include <unistd.h> /* getenv */ #include <stdlib.h> #include <criterion/criterion.h> #include "builtin/change_directory.h" Test(builtin_change_directory, simple_change_directory) { const char *path = "/usr"; const enum change_directory_e return_value = builtin_change_directory(path); char *new_dir = getcwd(NULL, 0); cr_assert_str_eq(path, new_dir); cr_assert_eq(return_value, CD_SUCCESS); free(new_dir); } Test(builtin_change_directory, not_existing_path) { const char *path = "a/real/path/that/doesnt/and/wont/exist/anytime/please"; const enum change_directory_e return_value = builtin_change_directory(path); cr_assert_eq(return_value, CD_CHDIR_FAIL); } Test(builtin_change_directory, cd_old_pwd) { char *old_pwd = getcwd(NULL, 0); const enum change_directory_e return_value = builtin_change_directory("-"); cr_assert_str_eq(old_pwd, getenv("OLDPWD")); cr_assert_eq(return_value, CD_SUCCESS); free(old_pwd); } <file_sep>/lib/builtins/Makefile ## ## EPITECH PROJECT, 2020 ## PSU_42sh_2019 ## File description: ## Makefile ## CC ?= gcc NAME = libbuiltins.a TESTNAME = unit_tests SRC = src/change_directory.c \ src/display_env.c \ src/echo.c \ src/exit.c \ src/get_user_home.c \ src/setenv.c \ src/unsetenv.c \ SRCT = tests/change_directory.c \ tests/echo.c \ tests/exit.c \ tests/setenv.c \ tests/unsetenv.c \ OBJ = $(SRC:.c=.o) OBJT = $(SRCT:.c=.o) WARNINGS = -pedantic -Wshadow -Wpointer-arith -Wcast-align \ -Wmissing-prototypes -Wmissing-declarations \ -Wnested-externs -Wwrite-strings -Wredundant-decls \ -Winline -Wno-long-long -Wconversion \ -Wstrict-prototypes \ DEBUG = -g $(WARNINGS) CFLAGS += -Wall -Wextra CPPFLAGS += -I include/ -I ../parser_toolbox/include TFLAGS += -lcriterion LDFLAGS += --coverage \ -L../parser_toolbox -lparser_toolbox \ all: $(NAME) $(NAME): $(OBJ) ar rc $(NAME) $(OBJ) tests_run: make -C ../parser_toolbox/ $(CC) $(SRC) $(SRCT) -o $(TESTNAME) $(TFLAGS) $(LDFLAGS) \ $(CPPFLAGS) $(CFLAGS) ./$(TESTNAME) 2>&1 | (grep -v "profiling") debug: fclean debug: CFLAGS += $(DEBUG) debug: $(NAME) clean: $(RM) $(OBJ) $(OBJT) *.gcno *.gcda fclean: clean $(RM) $(NAME) $(TESTNAME) fcleanlib: fclean make -C ../parser_toolbox/ fclean re: fclean all relib: fcleanlib all .PHONY: all clean fclean re tests_run fcleanlib relib <file_sep>/src/expr/else_control.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** expr_else_control */ #include <stdlib.h> #include <string.h> #include "proto/constants.h" #include "proto/grammar.h" #include "proto/expr.h" /* ** @DESCRIPTION ** Rule for else_control expression. */ static struct expr_else_control_s *expr_else_control(struct grammar_s *this) { struct expr_else_control_s *exp = malloc( sizeof(struct expr_else_control_s)); if (!exp) exit(84); memset(exp, 0, sizeof(struct expr_else_control_s)); if (!grammar_match(this, 1, TOK_ELSE)) return (expr_free(exp)); exp->else_token = grammar_get_previous(this); if (!grammar_match(this, 1, TOK_NEWLINE)) { grammar_set_error(this, AST_ELSE_MISSING_NEWLINE); return (expr_free(exp)); } exp->newline = grammar_get_previous(this); exp->block = expr_block_w(this); if (!exp->block) { grammar_set_error(this, AST_EMPTY_ELSE); return (expr_free(exp)); } return exp; } struct expr_else_control_s *expr_else_control_w(struct grammar_s *this) { struct expr_else_control_s *exp; expr_print(this, "Else Control"); exp = expr_else_control(this); expr_print_debug(this, exp); return exp; } <file_sep>/lib/dnode/src/apply.c /* ** EPITECH PROJECT, 2020 ** dnode ** File description: ** apply */ #include <stddef.h> #include "dnode/apply.h" #include "dnode/goto.h" void dnode_apply(struct dnode_s *list, void (*func)(void *)) { struct dnode_s *curr = NULL; if (!func) { return; } curr = dnode_goto_start(list); for (; curr; curr = curr->next) { func(curr->data); } } <file_sep>/src/shell/builtin_handlers/source.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** builtins */ #include "builtins.h" #include "types/shell.h" #include "proto/shell/builtin_handlers.h" /* int fd_save = shell->fd; */ /* get fd() */ /* shell->fd = 0; */ /* shell_loop() */ int builtin_source_handler( struct sh *shell, const char * const *argv ) { int tmp = shell->atty; if (argv[1] == NULL) { return (1); } shell->atty = 0; for (size_t i = 1; argv[i]; ++i) { } shell->atty = tmp; return (0); } <file_sep>/lib/mynode/Makefile ## ## EPITECH PROJECT, 2020 ## my_printf ## File description: ## Makefile ## CC ?= gcc NAME = libmynode.a SRC = src/node_append.c \ src/node_insert.c \ src/node_apply.c \ src/node_filter.c \ src/node_free.c \ src/node_pop.c \ src/node_remove.c \ src/node_reverse.c \ src/node_size.c \ src/node_to_table.c \ OBJ = $(SRC:.c=.o) CFLAGS = -Wall -Wextra CPPFLAGS = -I ./include/ TFLAGS = --coverage -lcriterion all: $(NAME) $(NAME): $(OBJ) ar rc $(NAME) $(OBJ) ranlib $(NAME) clean: $(RM) $(OBJ) fclean: clean $(RM) $(NAME) $(TEST) re: fclean all .PHONY: all clean fclean re <file_sep>/src/shell/builtin_handlers/unset.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** builtins */ /* free */ #include <stdlib.h> #include "builtins.h" #include "types/shell.h" #include "proto/shell/builtin_handlers.h" #include "hasher/pop.h" #include "types/local_variables.h" int builtin_unset_handler(struct sh *shell, const char * const *argv) { struct hasher_s *node = NULL; struct local_var_s *var = NULL; for (size_t i = 1; argv[i]; ++i) { node = hasher_pop(&shell->local_var, argv[i]); if (!node) { continue; } var = node->data; if (var->type == STRING) { free(var->data.string); } free(var); free(node->key); free(node); } return (0); } <file_sep>/include/tests/mock_types.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** shell header file. */ #ifndef SH_TEST_SHELL_H_ #define SH_TEST_SHELL_H_ /**/ /* Includes */ /**/ #include <stddef.h> #include "types/shell.h" /**/ /* Constants */ /**/ static const char *const MOCK_ENV[] = { "PATH=", "SHELL=/usr/bin/zsh", "PATH=/usr/bin:/usr/local/sbin:/usr/local/bin", "OLDPWD=/home" }; static const struct sh MOCK_SH = { .active = true, .rawinput = NULL, .tokens = NULL, .envp = (char **) MOCK_ENV }; /**/ /* Structures / Typedef / Enums declarations */ /**/ /**/ /* Function prototypes */ /**/ #endif <file_sep>/lib/dnode/src/goto.c /* ** EPITECH PROJECT, 2020 ** dnode ** File description: ** goto */ #include <stddef.h> #include "dnode/goto.h" struct dnode_s *dnode_goto_end(struct dnode_s *list) { struct dnode_s *curr = list; if (!curr) { return (NULL); } for (; curr->next; curr = curr->next) {} return (curr); } struct dnode_s *dnode_goto_start(struct dnode_s *list) { struct dnode_s *curr = list; if (!curr) { return (NULL); } for (; curr->prev; curr = curr->prev) {} return (curr); } <file_sep>/include/proto/exec/rule/command.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** shell exec rule command */ #ifndef SH_SHELL_EXEC_RULE_COMMAND_H_ #define SH_SHELL_EXEC_RULE_COMMAND_H_ #include "types/shell.h" #include "types/expr.h" #include "types/job.h" int exec_rule_command( struct sh *shell, struct expr_command_s *rule, struct job_s *job ); #endif /* !SH_SHELL_EXEC_RULE_COMMAND_H_ */ <file_sep>/lib/builtins/src/echo.c /* ** EPITECH PROJECT, 2020 ** builtins ** File description: ** builtin_echo */ /* dprintf */ #include <stdio.h> /* strcmp */ #include <string.h> /* bool */ #include <stdbool.h> /* */ #include "builtin/exit.h" void builtin_echo(const char * const *argv) { bool is_flag = (argv[0] && !strcmp(argv[0], "-n")); for (int i = is_flag; argv[i]; ++i) { dprintf(1, "%s%s", (i - is_flag) ? " " : "", argv[i]); } if (!is_flag) { dprintf(1, "\n"); } } <file_sep>/src/shell/check_debug_mode.c /* ** EPITECH PROJECT, 2020 ** 42sh ** File description: ** check debug mode */ #include <stdbool.h> #include <string.h> #include "proto/shell/check_debug_mode.h" bool check_debug_mode(char *const *av) { if (!av[1]) return (false); else if (!strcmp(av[1], "--debug-mode")) return (true); else return (false); } <file_sep>/src/expr/block.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** expr_block */ #include <stdlib.h> #include <string.h> #include "proto/grammar.h" #include "proto/expr.h" /* ** @DESCRIPTION ** Rule for block expression. */ static struct expr_block_s *expr_block(struct grammar_s *this) { struct expr_block_s *exp = malloc(sizeof(struct expr_block_s)); unsigned int save_index = this->index; if (!exp) exit(84); memset(exp, 0, sizeof(struct expr_block_s)); save_index = this->index; exp->statement = expr_statement_w(this); if (!exp->statement) { this->index = save_index; return (expr_free(exp)); } while (grammar_match(this, 2, TOK_NEWLINE, TOK_SEMI)); save_index = this->index; exp->block = expr_block_w(this); if (!exp->block) this->index = save_index; return (exp); } struct expr_block_s *expr_block_w(struct grammar_s *this) { struct expr_block_s *exp; expr_print(this, "Block"); exp = expr_block(this); expr_print_debug(this, exp); return (exp); } <file_sep>/src/exec/rule/control/while.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** exec rule control while */ #include "proto/exec/rule/debug.h" #include "proto/exec/rule/control/check_condition.h" #include "proto/exec/rule/block.h" #include "proto/exec/rule/control/while.h" int exec_rule_control_while( struct sh *shell, struct expr_while_control_s *rule ) { exec_rule_debug(shell, "while", true); while (exec_rule_control_check_condition( shell, rule->wordlist_expression)) { if (rule->block) { exec_rule_block(shell, rule->block); } } exec_rule_debug(shell, "while", false); return (0); } <file_sep>/src/shell/builtin_handlers/builtins.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** builtins */ #include <stdio.h> #include "hasher/type.h" #include "builtins.h" #include "types/shell.h" #include "proto/shell/builtin_handlers.h" int builtin_builtins_handler(struct sh *shell, const char * const *argv) { if (builtins_utils_too_many_arguments(argv, 0)) { return (1); } for (struct hasher_s *builtin = shell->builtin; builtin != NULL; builtin = builtin->next) { dprintf(1, "%s\n", builtin->key); } return (0); } <file_sep>/src/input/input_destroy.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** input_destroy */ #include <stdlib.h> #include "types/shell.h" #include "proto/input.h" /* ** @DESCRIPTION ** This function is called at the end of the command's execution in order to ** free all of the malloc'ed variables. */ void input_destroy(struct sh *shell) { free(shell->rawinput); shell->rawinput = NULL; node_free(&(*shell).tokens, &free); } <file_sep>/src/prompt/set_raw_mode.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** set_raw_mode */ /* STDIN_FILENO */ #include <unistd.h> #include "proto/prompt/set_raw_mode.h" void term_set_raw_mode(const struct termios *orig_term) { struct termios new_term; new_term = *orig_term; new_term.c_cc[VTIME] = 0; new_term.c_cc[VMIN] = 0; new_term.c_lflag &= (tcflag_t) ~(ECHO | ICANON | ISIG); if (tcsetattr(STDIN_FILENO, TCSANOW, &new_term) == -1) { } } <file_sep>/lib/find_binary/include/extend_path.h /* ** EPITECH PROJECT, 2020 ** find_binary ** File description: ** extend_path */ #ifndef EXTEND_PATH_H_ #define EXTEND_PATH_H_ char *extend_path(const char *path, const char *extend); #endif /* !EXTEND_PATH_H_ */ <file_sep>/src/shell/shell_start.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** start */ #include "proto/shell.h" #include "proto/prompt.h" /* ** @DESCRIPTION ** Starts the 42sh. ** Initialises all the 'dependencies' such as aliases etc... */ int shell_start(struct sh *shell) { prompter(shell); return (0); } <file_sep>/src/exec/rule/control/repeat.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** exec rule control repeat */ #include <stdlib.h> #include "parser_toolbox/whitelist.h" #include "proto/token/get_string.h" #include "proto/exec/rule/debug.h" #include "types/exec/rule.h" #include "proto/exec/rule/grouping.h" #include "proto/exec/rule/control/repeat.h" int exec_rule_control_repeat( struct sh *shell, struct expr_repeat_control_s *rule ) { char *substr = token_get_string(rule->word, shell->rawinput); long repeat = 0; if (substr == NULL) { return (EXEC_RULE_ALLOCATION_FAIL); } if (!ptb_whitelist_digit(substr + (*substr == '-'))) { dprintf(2, "repeat: Badly formed number.\n"); return (EXEC_RULE_REPEAT_BADLY_FORMED_NUMBER); } repeat = strtol(substr, (char **) 0, 10); free(substr); exec_rule_debug(shell, "repeat", true); for (long i = 0; i < repeat; ++i) { exec_rule_grouping(shell, rule->grouping, true); } exec_rule_debug(shell, "repeat", false); return (EXEC_RULE_SUCCESS); } <file_sep>/src/prompt/actions/clear_term.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** prompt action prompt_action_clear_term */ /* putp */ #include <curses.h> #include <term.h> #include "proto/prompt/update_cursor_pos.h" #include "proto/prompt/display.h" #include "proto/prompt/action/clear_term.h" void prompt_action_clear_term(struct sh *shell) { if (shell->atty) { putp(shell->prompt.effect[PROMPT_EFFECT_CLEAR]); prompt_display(shell); fputs(shell->prompt.input, stdout); prompt_update_cursor_pos(&(shell->prompt)); } } <file_sep>/lib/hasher/include/hasher/destroy.h /* ** EPITECH PROJECT, 2020 ** hasher ** File description: ** hasher destroy */ #ifndef HASHER_DESTROY_H_ #define HASHER_DESTROY_H_ #include "hasher/type.h" void hasher_destroy( struct hasher_s *hasher, _Bool destroy_key, _Bool destroy_data ); #endif /* !HASHER_DESTROY_H_ */ <file_sep>/lib/hasher/src/get_data.c /* ** EPITECH PROJECT, 2020 ** hasher ** File description: ** hasher_get_data */ #include <string.h> #include "hasher/get.h" /* */ #include "hasher/get_data.h" void *hasher_get_data(struct hasher_s *hasher, const char *key) { struct hasher_s *match = hasher_get(hasher, key); return (match ? match->data : NULL); } <file_sep>/src/expr/destroy/expr_free.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** expr_else_if_control */ /* free */ #include <stdlib.h> void *expr_free(void *expr) { free(expr); return (NULL); } <file_sep>/src/expr/grouping.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** expr_grouping */ #include <stdlib.h> #include <string.h> #include "proto/constants.h" #include "proto/grammar.h" #include "proto/expr.h" static int check_pipeline( struct grammar_s *this, struct expr_grouping_s *exp ) { int ret = do_ambiguous_redirection_check(this, exp->pipeline); if (ret == 1) { grammar_set_error(this, AST_AMBIGUOUS_REDIRECTION1); return (1); } else if (ret == 2) { grammar_set_error(this, AST_AMBIGUOUS_REDIRECTION2); return (1); } return (0); } /* ** @DESCRIPTION ** Rule for grouping expression. */ static struct expr_grouping_s *expr_grouping(struct grammar_s *this) { struct expr_grouping_s *exp = malloc( sizeof(struct expr_grouping_s)); unsigned int save_index __attribute__((unused)) = this->index; if (!exp) exit(84); memset(exp, 0, sizeof(struct expr_grouping_s)); exp->pipeline = expr_pipeline_w(this); if (!exp->pipeline || check_pipeline(this, exp)) return (expr_free(exp)); if (!grammar_match(this, 2, TOK_AND_IF, TOK_OR_IF)) return exp; exp->conditional = grammar_get_previous(this); exp->grouping = expr_grouping_w(this); if (!exp->grouping) { grammar_set_error(this, AST_NULL_COMMAND); return (expr_free(exp)); } return exp; } struct expr_grouping_s *expr_grouping_w(struct grammar_s *this) { struct expr_grouping_s *exp; expr_print(this, "Grouping"); exp = expr_grouping(this); expr_print_debug(this, exp); return exp; } <file_sep>/src/shell/shlvl_update.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** start */ #include <stdio.h> #include <stdlib.h> #include "proto/shell/shlvl_update.h" /* ** @DESCRIPTION ** Increase SHLVL env var by one if it exists, ** Otherwise, it initialises it to 1 */ int shlvl_update(void) { const char *shlvl = getenv("SHLVL"); char nb_stringified[16] = {'\0'}; if (shlvl) { snprintf(nb_stringified, 16, "%d", atoi(shlvl) + 1); } else { nb_stringified[0] = '1'; } return (setenv("SHLVL", nb_stringified, 1)); } <file_sep>/lib/builtins/include/builtin/setenv.h /* ** EPITECH PROJECT, 2020 ** builtins ** File description: ** builtin_setenv */ #ifndef BUILTIN_SETENV_H_ #define BUILTIN_SETENV_H_ enum builtin_setenv_e { SETENV_SUCCESS = 0, SETENV_TOO_MANY_ARGS = 1, SETENV_ALPHANUM_ONLY = 2, SETENV_MUST_BEGIN_WITH_A_LETTER = 3, SETENV_ALLOCATION_FAIL }; enum builtin_setenv_e builtin_setenv(const char * const *argv); #endif /* !BUILTIN_SETENV_H_ */ <file_sep>/include/proto/exec/rule/debug.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** shell exec rule debug */ #ifndef SH_SHELL_EXEC_RULE_DEEBUG_H_ #define SH_SHELL_EXEC_RULE_DEEBUG_H_ #include "types/shell.h" void exec_rule_debug(struct sh *shell, const char *rule, bool entering); void exec_rule_job_display(struct sh *shell, struct job_s *job); #endif /* !SH_SHELL_EXEC_RULE_DEEBUG_H_ */ <file_sep>/src/shell/shell_init.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** init */ #include <unistd.h> #include <string.h> #include <fcntl.h> #include "proto/shell.h" #include "proto/shell/builtins.h" #include "proto/shell/alias.h" #include "proto/shell/term_init.h" #include "proto/shell/bindkey.h" #include "proto/shell/check_debug_mode.h" #include "proto/shell/local_variables.h" #include "proto/prompt/history.h" #include "proto/shell/shlvl_update.h" /* TODO: parse av: if fd replace STDIN_FILENO in isatty by fildes */ static int shell_get_fildes(int ac, char * const *av) { int fd_start = 1; int fd; for (; fd_start < ac && av[fd_start][0] == '-'; ++fd_start); if (fd_start >= ac) { return (STDIN_FILENO); } fd = open(av[fd_start], O_RDONLY); return (fd); } /* ** @DESCRIPTION ** Initialises a local `struct sh` and inits all of its members. */ int shell_struct_initialise( struct sh *this, int ac, char *const *av, char *const *ep ) { int fd = shell_get_fildes(ac, av); if (fd == -1) return (1); *this = (struct sh) { .debug_mode = check_debug_mode(av), .active = true, .rawinput = NULL, .tokens = NULL, .pgid = 0, .envp = ep, .prompt = {{0}}, .atty = isatty(fd), .history = {0}, .builtin = shell_builtin_hash_create(), .alias = NULL, .bindkey = NULL, .local_var = local_variables_init(), .error = ER_NONE, .job = NULL, .fd = fd, .stream = fdopen(fd, "r"), .expression = NULL, .debug = {.depth = 0} }; if (!this->stream || term_init(this) || shlvl_update()) return (1); history_init(&this->history); this->bindkey = shell_bindkey_hash_create(); return ( !this->builtin || (this->atty && !this->bindkey) ); } <file_sep>/include/proto/sighandler.h /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** sig handler */ #ifndef SH_SIG_HANDLER_H_ #define SH_SIG_HANDLER_H_ #include <signal.h> typedef void (*sighandler_t)(int); void term_set_signal_handling(sighandler_t action); #endif /* !SH_SIG_HANDLER_H_ */ <file_sep>/lib/hasher/src/get.c /* ** EPITECH PROJECT, 2020 ** hasher ** File description: ** hasher_get */ #include <string.h> /* */ #include "hasher/get.h" struct hasher_s *hasher_get(struct hasher_s *hasher, const char *key) { if (key == NULL) { return (NULL); } for (; hasher != NULL; hasher = hasher->next) { if (!strcmp(hasher->key, key)) { return (hasher); } } return (NULL); } <file_sep>/include/proto/exec/rule/jobs.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** shell exec rule jobs */ #ifndef SH_SHELL_EXEC_RULE_JOBS_H_ #define SH_SHELL_EXEC_RULE_JOBS_H_ #include "types/shell.h" #include "types/expr.h" int exec_rule_jobs( struct sh *shell, struct expr_jobs_s *rule, bool foreground ); #endif /* !SH_SHELL_EXEC_RULE_JOBS_H_ */ <file_sep>/src/expr/destroy/redirection.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** expr_redirection */ /* free */ #include <stdlib.h> #include "proto/expr_destroy.h" /* ** @DESCRIPTION ** Rule for redirection expression. */ void expr_redirection_destroy(struct expr_redirection_s *this) { if (!this) { return; } free(this); } <file_sep>/src/exec/rule/separator.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** exec rule separator */ #include "proto/exec/rule/debug.h" #include "proto/exec/rule/separator.h" int exec_rule_separator( struct sh *shell, __attribute__((unused)) struct expr_separator_s *rule ) { exec_rule_debug(shell, "separator", true); exec_rule_debug(shell, "separator", false); return (0); } <file_sep>/src/expr/else_if_control.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** expr_else_if_control */ #include <stdlib.h> #include <string.h> #include "proto/constants.h" #include "proto/grammar.h" #include "proto/expr.h" static struct expr_else_if_control_s *expr_else_if_control_n( struct grammar_s *this, struct expr_else_if_control_s *exp, unsigned int save_index ) { if (!grammar_match(this, 1, TOK_THEN)) { grammar_set_error(this, AST_ELSE_IF_MISSING_THEN); return (expr_free(exp)); } exp->then = grammar_get_previous(this); if (!grammar_match(this, 1, TOK_NEWLINE)) { grammar_set_error(this, AST_THEN_MISSING_NEWLINE); return (expr_free(exp)); } exp->newline = grammar_get_previous(this); exp->block = expr_block_w(this); if (!exp->block) { grammar_set_error(this, AST_EMPTY_ELSE_IF); return (expr_free(exp)); } save_index = this->index; exp->else_if_control = expr_else_if_control_w(this); if (!exp->else_if_control) this->index = save_index; return exp; } /* ** @DESCRIPTION ** Rule for else_if_control expression. */ static struct expr_else_if_control_s *expr_else_if_control( struct grammar_s *this ) { struct expr_else_if_control_s *exp = malloc( sizeof(struct expr_else_if_control_s)); unsigned int save_index = this->index; if (!exp) exit(84); memset(exp, 0, sizeof(struct expr_else_if_control_s)); if (!grammar_match(this, 1, TOK_ELSE_IF)) return (expr_free(exp)); exp->else_if_token = grammar_get_previous(this); exp->wordlist_expression = expr_wordlist_expression_w(this); if (!exp->wordlist_expression) { grammar_set_error(this, AST_INVALID_EXPRESSION); return (expr_free(exp)); } return expr_else_if_control_n(this, exp, save_index); } struct expr_else_if_control_s *expr_else_if_control_w(struct grammar_s *this) { struct expr_else_if_control_s *exp; expr_print(this, "Else If Control"); exp = expr_else_if_control(this); expr_print_debug(this, exp); return exp; } <file_sep>/include/proto/prompt/update_cursor_pos.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** sh prompt update_cursor_pos */ #ifndef SH_PROTO_PROMPT_UPDATE_CURSOR_POS_H_ #define SH_PROTO_PROMPT_UPDATE_CURSOR_POS_H_ #include "types/prompt.h" void prompt_update_cursor_pos(struct prompt *prompt); #endif /* !SH_PROTO_PROMPT_UPDATE_CURSOR_POS_H_ */ <file_sep>/include/proto/exec/rule/block.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** shell exec rule block */ #ifndef SH_SHELL_EXEC_RULE_BLOCK_H_ #define SH_SHELL_EXEC_RULE_BLOCK_H_ #include "types/shell.h" #include "types/expr.h" int exec_rule_block( struct sh *shell, struct expr_block_s *rule ); #endif /* !SH_SHELL_EXEC_RULE_BLOCK_H_ */ <file_sep>/lib/find_binary/src/find_file_in_path.c /* ** EPITECH PROJECT, 2020 ** find_binary ** File description: ** find_file_in_path */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "extend_path.h" #include "find_file_in_path.h" char *find_file_in_path(const char *path, const char *bin) { char *current_path = extend_path(path, bin); if (access(current_path, F_OK) == 0) return (current_path); free(current_path); return (NULL); } <file_sep>/src/expr/destroy/repeat_control.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** expr_repeat_control */ /* free */ #include <stdlib.h> #include "proto/expr_destroy.h" /* ** @DESCRIPTION ** Rule for repeat_control expression. */ void expr_repeat_control_destroy(struct expr_repeat_control_s *this) { if (!this) { return; } expr_grouping_destroy(this->grouping); free(this); } <file_sep>/src/shell/bindkey_init.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** bindkey */ #include <string.h> #include <curses.h> /* setupterm */ #include <term.h> #include "hasher/insert_data.h" #include "proto/shell/term_init.h" #include "proto/shell/bindkey.h" #include "types/builtins/bindkey.h" #include "constants/prompt/private_bindkey_init.h" struct hasher_s *shell_bindkey_hash_create(void) { struct hasher_s *hash = NULL; char *key = NULL; for (int i = 0; i < BINDKEY_COUNT; ++i) { key = i > 2 ? strdup(BINDKEY_DICT[i].key) : tigetstr(BINDKEY_DICT[i].key); if ((i < 3 && key == (char *) -1) || key == NULL) { return (NULL); } if (i < 3) key = strdup(key); if (hasher_insert_data( &hash, key, (void *) &BINDKEY_DICT[i].data )) { return (NULL); } } return (hash); } <file_sep>/tests/binaries/src/bin_not_compatible.c /* ** EPITECH PROJECT, 2020 ** bin_not_compatible ** File description: ** main */ int main(void) { return (0); } <file_sep>/src/shell/autocomplete_init.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** autocomplete */ #include <stdlib.h> #include "path_iteration.h" #include "proto/shell/autocomplete.h" void shell_autocomplete_hash_create(void) { atexit(&path_iteration_atexit); } <file_sep>/include/proto/input/executer.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** executer header file. */ #ifndef SH_PROTO_INPUT_EXECUTER_H_ #define SH_PROTO_INPUT_EXECUTER_H_ /**/ /* Includes */ /**/ #include "types/shell.h" /**/ /* Constants */ /**/ /**/ /* Structures / Typedef / Enums declarations */ /**/ /**/ /* Function prototypes */ /**/ void input_execute(struct sh *shell); #endif <file_sep>/include/tests/tokens.h /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** tokens header file. */ #ifndef SH_TESTS_INPUT_TOKENS_H_ #define SH_TESTS_INPUT_TOKENS_H_ /**/ /* Includes */ /**/ /**/ /* Constants */ /**/ /* ** @DESCRIPTION ** Provides a name description for each token type. ** This structure is mainly used for debugging. */ static const char *TOK_NAMES[] = { "(Unknown)", "EOF", "Word", "Newline", "IO Number", "Less", "Great", "Pipe", "Semicolon", "Ampersand", "And If", "Or If", "Double Semi", "Double Less", "Double Great", "Less And", "Great And", "Less Great", "Double Less Dash", "Clobber", "Left Brace", "Right Brace", "Left Paranthesis", "Right Paranthesis", "Break", "Switch", "Case", "Breaksw", "Default:", "Endsw", "Continue", "Foreach", "Endif", "End", "Goto", "If", "Else if", "Else", "Then", "Repeat", "While"}; /**/ /* Structures / Typedef / Enums declarations */ /**/ /**/ /* Function prototypes */ /**/ #endif <file_sep>/lib/dnode/include/dnode/goto.h /* ** EPITECH PROJECT, 2020 ** dnode ** File description: ** goto */ #ifndef DNODE_GOTO_H_ #define DNODE_GOTO_H_ #include "dnode/type.h" struct dnode_s *dnode_goto_end(struct dnode_s *list); struct dnode_s *dnode_goto_start(struct dnode_s *list); #endif /* !DNODE_GOTO_H_ */ <file_sep>/lib/parser_toolbox/src/sort_string.c /* ** EPITECH PROJECT, 2020 ** parser_toolbox ** File description: ** ptb_characters */ #include <stdlib.h> #include <string.h> #include "parser_toolbox/sort_string.h" static int sort_string_cmp(const void *a, const void *b) { return (strcmp(*((char * const *) a), *((char * const *) b))); } void ptb_sort_string(char * const *strings, size_t length) { qsort((void *) strings, length, sizeof(char *), sort_string_cmp); } <file_sep>/lib/find_binary/include/double_array_size.h /* ** EPITECH PROJECT, 2020 ** find_binary ** File description: ** double_array_size */ #ifndef DOUBLE_ARRAY_SIZE_H_ #define DOUBLE_ARRAY_SIZE_H_ int double_array_size(void **array, size_t *allocated); #endif /* !DOUBLE_ARRAY_SIZE_H_ */ <file_sep>/lib/builtins/src/display_env.c /* ** EPITECH PROJECT, 2020 ** builtins ** File description: ** builtin_setenv */ #include <stdio.h> extern char **environ; /* */ #include "builtin/display_env.h" void builtin_display_env(void) { for (int i = 0; environ[i]; ++i) { dprintf(1, "%s\n", environ[i]); } } <file_sep>/src/expr/destroy/subshell.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** expr_subshell */ /* free */ #include <stdlib.h> #include "proto/expr_destroy.h" /* ** @DESCRIPTION ** Rule for subshell expression. */ void expr_subshell_destroy(struct expr_subshell_s *this) { if (!this) { return; } expr_grouping_destroy(this->grouping); free(this); } <file_sep>/src/exec/rule/sub_pipeline.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** exec rule pipeline */ #include <stdlib.h> #include <string.h> #include <stdio.h> #include <unistd.h> #include "proto/exec/rule/debug.h" #include "types/exec/rule.h" #include "proto/job/create.h" #include "proto/job/destroy.h" #include "proto/job/launch.h" #include "proto/exec/rule/command.h" #include "proto/exec/rule/subshell.h" #include "proto/exec/rule/pipeline.h" #include "parser_toolbox/string_split.h" #include "parser_toolbox/argv_length.h" #include "hasher/get_data.h" #include "types/builtins.h" void replace_add_data(struct process_s *process, char *data); void follow_alias( struct process_s **process, struct process_s **save, char *data ) { if (data != (*process)->argv[0]) { replace_add_data(*process, data); *process = *save; } else { *save = *process; *process = (*process)->next; } } <file_sep>/include/proto/exec/rule/control/while.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** shell exec rule control while */ #ifndef SH_SHELL_EXEC_RULE_CONTROL_WHILE_H_ #define SH_SHELL_EXEC_RULE_CONTROL_WHILE_H_ #include "types/shell.h" #include "types/expr.h" int exec_rule_control_while( struct sh *shell, struct expr_while_control_s *rule ); #endif /* !SH_SHELL_EXEC_RULE_CONTROL_WHILE_H_ */ <file_sep>/lib/parser_toolbox/include/parser_toolbox/display_strings_equalize.h /* ** EPITECH PROJECT, 2020 ** parser_toolbox ** File description: ** parser_toolbox display_strings_equalize */ #ifndef PARSER_TOOLBOX_DISPLAY_STRING_EQUALIZE_H_ #define PARSER_TOOLBOX_DISPLAY_STRING_EQUALIZE_H_ #include <stddef.h> void ptb_display_strings_equalize( char * const *strings, size_t length, size_t win_width ); void ptb_display_sorted_strings_equalize( char * const *strings, size_t length, size_t win_width ); #endif /* !PARSER_TOOLBOX_DISPLAY_STRING_EQUALIZE_H_ */ <file_sep>/src/expr/pipeline.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** expr_pipeline */ #include <stdlib.h> #include <string.h> #include "proto/constants.h" #include "proto/grammar.h" #include "proto/expr.h" static int expr_pipeline_sub_test( struct grammar_s *this, struct expr_pipeline_s *exp, unsigned int save_index ) { this->index = save_index; exp->command = expr_command_w(this); if (!exp->command) return (1); return (0); } /* ** @DESCRIPTION ** Rule for pipeline expression. */ static struct expr_pipeline_s *expr_pipeline(struct grammar_s *this) { struct expr_pipeline_s *exp = malloc( sizeof(struct expr_pipeline_s)); unsigned int save_index __attribute__((unused)) = this->index; if (!exp) exit(84); memset(exp, 0, sizeof(struct expr_pipeline_s)); exp->subshell = expr_subshell_w(this); if (!exp->subshell && expr_pipeline_sub_test(this, exp, save_index)) return (expr_free(exp)); if (!grammar_match(this, 1, TOK_PIPE)) return exp; exp->pipe = grammar_get_previous(this); exp->pipeline = expr_pipeline(this); if (!exp->pipeline) { grammar_set_error(this, AST_NULL_COMMAND); return (expr_free(exp)); } return exp; } struct expr_pipeline_s *expr_pipeline_w(struct grammar_s *this) { struct expr_pipeline_s *exp; expr_print(this, "Pipeline"); exp = expr_pipeline(this); expr_print_debug(this, exp); return exp; } <file_sep>/include/types/builtins/bindkey.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** builtins */ #ifndef SH_TYPES_BUILTINS_BINDKEY_H_ #define SH_TYPES_BUILTINS_BINDKEY_H_ #include "types/shell.h" struct bindkey_s { void (*func)(struct sh *shell); const char *name; }; #endif /* !SH_TYPES_BUILTINS_BINDKEY_H_ */ <file_sep>/src/shell/local_variables/from_data.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** from_data */ /* malloc */ #include <stdlib.h> #include "hasher/get_data.h" #include "types/local_variables.h" #include "proto/shell/local_variables.h" struct local_var_s *local_variable_from_data( struct hasher_s *hasher, char const *key, char const *data ) { struct local_var_s *var = hasher_get_data(hasher, key); if (var) { local_variable_assign_value(var, data); return (NULL); } var = malloc(sizeof(struct local_var_s)); if (!var) { return (NULL); } local_variable_assign_value(var, data); return (var); } <file_sep>/lib/parser_toolbox/src/display_strings.c /* ** EPITECH PROJECT, 2020 ** parser_toolbox ** File description: ** ptb_display_strings */ #include <stdio.h> #include "parser_toolbox/sort_string.h" #include "parser_toolbox/display_strings.h" void ptb_display_strings(char * const *strings, size_t length) { for (size_t i = 0; i < length; ++i) { puts(strings[i]); } } void ptb_display_sorted_strings(char * const *strings, size_t length) { ptb_sort_string(strings, length); ptb_display_strings(strings, length); } <file_sep>/include/types/grammar.h /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** grammar header file. */ #ifndef SH_TYPES_GRAMMAR_H_ #define SH_TYPES_GRAMMAR_H_ /**/ /* Includes */ /**/ #include <stdbool.h> #include "types/token.h" /**/ /* Constants */ /**/ /**/ /* Structures / Typedef / Enums declarations */ /**/ /* ** @DESCRIPTION ** Grammar wrapper structure. ** @MEMBERS ** - tokens: a 2d array of the parsed tokens. ** - index: the current index of the tokens table. */ struct grammar_s { struct token_s **tokens; unsigned int index; unsigned int token_count; bool error; bool debug; unsigned int depth; char const *error_message; unsigned int callindex; char *rawinput; }; /**/ /* Function prototypes */ /**/ #endif <file_sep>/include/proto/exec/rule/control/repeat.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** shell exec rule control repeat */ #ifndef SH_SHELL_EXEC_RULE_CONTROL_REPEAT_H_ #define SH_SHELL_EXEC_RULE_CONTROL_REPEAT_H_ #include "types/shell.h" #include "types/expr.h" int exec_rule_control_repeat( struct sh *shell, struct expr_repeat_control_s *rule ); #endif /* !SH_SHELL_EXEC_RULE_CONTROL_REPEAT_H_ */ <file_sep>/lib/parser_toolbox/src/add_char.c /* ** EPITECH PROJECT, 2020 ** parser_toolbox ** File description: ** string */ /* strlen */ #include <string.h> #include "parser_toolbox/add_char.h" void ptb_add_char(char *str, size_t pos, char c) { size_t size = strlen(str); for (; size > pos; --size) { str[size] = str[size - 1]; } str[size] = c; } <file_sep>/lib/dnode/tests/goto.c /* ** EPITECH PROJECT, 2020 ** dnode ** File description: ** goto */ #include <criterion/criterion.h> #include "dnode/goto.h" #include "dnode/insert.h" Test(dnode_goto, basic_test) { struct dnode_s *list = NULL; dnode_insert_data(&list, "salut"); dnode_insert_data(&list, "comment"); dnode_insert_data(&list, "ça va ?"); list = dnode_goto_end(list); cr_assert_str_eq(list->data, "salut"); cr_assert_str_eq(list->prev->data, "comment"); cr_assert_str_eq(list->prev->prev->data, "ça va ?"); cr_assert_null(list->prev->prev->prev); } <file_sep>/src/shell/builtin_handlers/wait.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** builtins */ #include <stdio.h> #include <stdlib.h> #include "builtins.h" #include "proto/shell/builtin_handlers.h" int builtin_wait_handler( __attribute__((unused)) struct sh *shell, const char * const *argv ) { if (builtins_utils_too_many_arguments(argv, 1)) { return (1); } return (0); } <file_sep>/include/proto/prompt/move_cursor_pos.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** sh prompt move_cursor_pos */ #ifndef SH_PROTO_PROMPT_MOVE_CURSOR_POS_H_ #define SH_PROTO_PROMPT_MOVE_CURSOR_POS_H_ #include "types/prompt.h" void prompt_move_cursor_pos(struct prompt *prompt, size_t new_pos); #endif /* !SH_PROTO_PROMPT_MOVE_CURSOR_POS_H_ */ <file_sep>/include/types/exec/rule.h /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** program header file. */ #ifndef SH_TYPES_EXEC_RULE_H_ #define SH_TYPES_EXEC_RULE_H_ enum exec_rule_e { EXEC_RULE_SUCCESS, EXEC_RULE_ALLOCATION_FAIL, EXEC_RULE_AMBIGUOUS_REDIRECTION, EXEC_RULE_REDIRECTION_FAIL, EXEC_RULE_REPEAT_BADLY_FORMED_NUMBER, EXEC_RULE_ALIAS_LOOP, }; #endif /* !SH_TYPES_EXEC_RULE_H_ */ <file_sep>/lib/find_binary/tests/double_array_size.c /* ** EPITECH PROJECT, 2020 ** find_binary ** File description: ** test double_array_size */ #include <stddef.h> #include <criterion/criterion.h> #include "double_array_size.h" Test(double_array_size, simple_array_doubling) { size_t size = 8; void *array = malloc(size); double_array_size(&array, &size); cr_assert_eq(size, 8 * 2); cr_assert_not_null(array); free(array); } <file_sep>/src/prompt/actions/clear_line.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** prompt action prompt_action_clear_line */ #include <stdio.h> #include "proto/prompt/move_cursor_pos.h" #include "proto/prompt/input/empty.h" #include "proto/prompt/action/clear_line.h" void prompt_action_clear_line(struct sh *shell) { if (shell->atty) { prompt_move_cursor_pos(&(shell->prompt), 0); printf("%*s", (int) shell->prompt.length, ""); shell->prompt.cursor = shell->prompt.length; prompt_move_cursor_pos(&(shell->prompt), 0); } prompt_input_empty(shell); } <file_sep>/include/constants/prompt/builtins/private_bindkey.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** Constants private_bindkey */ #ifndef SH_CONSTANTS_PROMPT_BUILTINS_PRIVATE_BINDKEY_H_ #define SH_CONSTANTS_PROMPT_BUILTINS_PRIVATE_BINDKEY_H_ #include "types/builtins.h" #include "proto/shell/bindkey.h" static const struct { const char *flag; void (*function)(struct sh *shell, const char * const *argv); } BINDKEY_FLAG[] = { {"-h", &builtin_bindkey_help}, {"-l", &builtin_bindkey_list}, {NULL, NULL} }; static const char BUILTIN_BINDKEY_HELP[] = "Usage: bindkey [options] [--] [KEY [COMMAND]]\n" " -a list or bind KEY in alternative key map\n" " -b interpret KEY as a C-, M-, F- or X- key name\n" " -s interpret COMMAND as a literal string to be output\n" " -c interpret COMMAND as a builtin or external command\n" " -v bind all keys to vi bindings\n" " -e bind all keys to emacs bindings\n" " -d bind all keys to default editor's bindings (emacs)\n" " -l list editor commands with descriptions\n" " -r remove KEY's binding\n" " -k interpret KEY as a symbolic arrow-key name\n" " -- force a break from option processing\n" " -u (or any invalid option) this message\n\n" " Without KEY or COMMAND, prints all bindings\n" " Without COMMAND, prints the binding for KEY.\n"; static const char BUILTIN_BINDKEY_EDITOR_COMMANDS_WITH_DESCRIPTIONS[] = "backward-char\n" " Move back a character\n" "backward-delete-char\n" " Delete the character behind cursor\n" "backward-delete-word\n" " Cut from beginning of current word to cursor - saved in cut " "buffer\n" "backward-kill-line\n" " Cut from beginning of line to cursor - save in cut buffer\n" "backward-word\n" " Move to beginning of current word\n" "beginning-of-line\n" " Move to beginning of line\n" "capitalize-word\n" " Capitalize the characters from cursor to end of current word\n" "change-case\n" " Vi change case of character under cursor and advance one " "character\n" "change-till-end-of-line\n" " Vi change to end of line\n" "clear-screen\n" " Clear screen leaving current line on top\n" "complete-word\n" " Complete current word\n" "complete-word-fwd\n" " Tab forward through files\n" "complete-word-back\n" " Tab backward through files\n" "complete-word-raw\n" " Complete current word ignoring programmable completions\n" "copy-prev-word\n" " Copy current word to cursor\n" "copy-region-as-kill\n" " Copy area between mark and cursor to cut buffer\n" "dabbrev-expand\n" " Expand to preceding word for which this is a prefix\n" "delete-char\n" " Delete character under cursor\n" "delete-char-or-eof\n" " Delete character under cursor or signal end of file on an empty " "line\n" "delete-char-or-list\n" " Delete character under cursor or list completions if at end of " "line\n" "delete-char-or-list-or-eof\n" " Delete character under cursor, list completions or signal end " "of file\n" "delete-word\n" " Cut from cursor to end of current word - save in cut buffer\n" "digit\n" " Adds to argument if started or enters digit\n" "digit-argument\n" " Digit that starts argument\n" "down-history\n" " Move to next history line\n" "downcase-word\n" " Lowercase the characters from cursor to end of current word\n" "end-of-file\n" " Indicate end of file\n" "end-of-line\n" " Move cursor to end of line\n" "exchange-point-and-mark\n" " Exchange the cursor and mark\n" "expand-glob\n" " Expand file name wildcards\n" "expand-history\n" " Expand history escapes\n" "expand-line\n" " Expand the history escapes in a line\n" "expand-variables\n" " Expand variables\n" "forward-char\n" " Move forward one character\n" "forward-word\n" " Move forward to end of current word\n" "gosmacs-transpose-chars\n" " Exchange the two characters before the cursor\n" "history-search-backward\n" " Search in history backward for line beginning as current\n" "history-search-forward\n" " Search in history forward for line beginning as current\n" "insert-last-word\n" " Insert last item of previous command\n" "i-search-fwd\n" " Incremental search forward\n" "i-search-back\n" " Incremental search backward\n" "keyboard-quit\n" " Clear line\n" "kill-line\n" " Cut to end of line and save in cut buffer\n" "kill-region\n" " Cut area between mark and cursor and save in cut buffer\n" "kill-whole-line\n" " Cut the entire line and save in cut buffer\n" "list-choices\n" " List choices for completion\n" "list-choices-raw\n" " List choices for completion overriding programmable completion\n" "list-glob\n" " List file name wildcard matches\n" "list-or-eof\n" " List choices for completion or indicate end of file if empty " "line\n" "load-average\n" " Display load average and current process status\n" "magic-space\n" " Expand history escapes and insert a space\n" "newline\n" " Execute command\n" "newline-and-hold\n" " Execute command and keep current line\n" "newline-and-down-history\n" " Execute command and move to next history line\n" "normalize-path\n" " Expand pathnames, eliminating leading .'s and ..'s\n" "normalize-command\n" " Expand commands to the resulting pathname or alias\n" "overwrite-mode\n" " Switch from insert to overwrite mode or vice versa\n" "prefix-meta\n" " Add 8th bit to next character typed\n" "quoted-insert\n" " Add the next character typed to the line verbatim\n" "redisplay\n" " Redisplay everything\n" "run-fg-editor\n" " Restart stopped editor\n"; static const char BUILTIN_BINDKEY_HELP_PART_2[] = "run-help\n" " Look for help on current command\n" "self-insert-command\n" " This character is added to the line\n" "sequence-lead-in\n" " This character is the first in a character sequence\n" "set-mark-command\n" " Set the mark at cursor\n" "spell-word\n" " Correct the spelling of current word\n" "spell-line\n" " Correct the spelling of entire line\n" "stuff-char\n" " Send character to tty in cooked mode\n" "toggle-literal-history\n" " Toggle between literal and lexical current history line\n" "transpose-chars\n" " Exchange the character to the left of the cursor with the one " "under\n" "transpose-gosling\n" " Exchange the two characters before the cursor\n" "tty-dsusp\n" " Tty delayed suspend character\n" "tty-flush-output\n" " Tty flush output character\n" "tty-sigintr\n" " Tty interrupt character\n" "tty-sigquit\n" " Tty quit character\n" "tty-sigtsusp\n" " Tty suspend character\n" "tty-start-output\n" " Tty allow output character\n" "tty-stop-output\n" " Tty disallow output character\n" "undefined-key\n" " Indicates unbound character\n" "universal-argument\n" " Emacs universal argument (argument times 4)\n" "up-history\n" " Move to previous history line\n" "upcase-word\n" " Uppercase the characters from cursor to end of current word\n" "vi-beginning-of-next-word\n" " Vi goto the beginning of next word\n" "vi-add\n" " Vi enter insert mode after the cursor\n" "vi-add-at-eol\n" " Vi enter insert mode at end of line\n" "vi-chg-case\n" " Vi change case of character under cursor and advance one " "character\n" "vi-chg-meta\n" " Vi change prefix command\n" "vi-chg-to-eol\n" " Vi change to end of line\n" "vi-cmd-mode\n" " Enter vi command mode (use alternative key bindings)\n" "vi-cmd-mode-complete\n" " Vi command mode complete current word\n" "vi-delprev\n" " Vi move to previous character (backspace)\n" "vi-delmeta\n" " Vi delete prefix command\n" "vi-endword\n" " Vi move to the end of the current space delimited word\n" "vi-eword\n" " Vi move to the end of the current word\n" "vi-char-back\n" " Vi move to the character specified backward\n" "vi-char-fwd\n" " Vi move to the character specified forward\n" "vi-charto-back\n" " Vi move up to the character specified backward\n" "vi-charto-fwd\n" " Vi move up to the character specified forward\n" "vi-insert\n" " Enter vi insert mode\n" "vi-insert-at-bol\n" " Enter vi insert mode at beginning of line\n" "vi-repeat-char-fwd\n" " Vi repeat current character search in the same search " "direction\n" "vi-repeat-char-back\n" " Vi repeat current character search in the opposite search " "direction\n" "vi-repeat-search-fwd\n" " Vi repeat current search in the same search direction\n" "vi-repeat-search-back\n" " Vi repeat current search in the opposite search direction\n" "vi-replace-char\n" " Vi replace character under the cursor with the next character " "typed\n" "vi-replace-mode\n" " Vi replace mode\n" "vi-search-back\n" " Vi search history backward\n" "vi-search-fwd\n" " Vi search history forward\n" "vi-substitute-char\n" " Vi replace character under the cursor and enter insert mode\n" "vi-substitute-line\n" " Vi replace entire line\n" "vi-word-back\n" " Vi move to the previous word\n" "vi-word-fwd\n" " Vi move to the next word\n" "vi-undo\n" " Vi undo last change\n" "vi-zero\n" " Vi goto the beginning of line\n" "which-command\n" " Perform which of current command\n" "yank\n" " Paste cut buffer at cursor position\n" "yank-pop\n" " Replace just-yanked text with yank from earlier kill\n" "e_copy_to_clipboard\n" " (WIN32 only) Copy cut buffer to system clipboard\n" "e_paste_from_clipboard\n" " (WIN32 only) Paste clipboard buffer at cursor position\n" "e_dosify_next\n" " (WIN32 only) Convert each '/' in next word to '\\'\n" "e_dosify_prev\n" " (WIN32 only) Convert each '/' in previous word to '\\'\n" "e_page_up\n" " (WIN32 only) Page visible console window up\n" "e_page_down\n" " (WIN32 only) Page visible console window down\n"; #endif /* !SH_CONSTANTS_PROMPT_BUILTINS_PRIVATE_BINDKEY_H_ */ <file_sep>/tests/binaries/src/div_zero.c /* ** EPITECH PROJECT, 2020 ** div_zero ** File description: ** main */ #include <signal.h> int main(void) { raise(SIGFPE); return (0); } <file_sep>/lib/parser_toolbox/include/parser_toolbox/unquote.h /* ** EPITECH PROJECT, 2020 ** parser_toolbox ** File description: ** parser_toolbox unquote */ #ifndef PARSER_TOOLBOX_UNQUOTE_H_ #define PARSER_TOOLBOX_UNQUOTE_H_ void ptb_unquote(char *str); #endif /* !PARSER_TOOLBOX_UNQUOTE_H_ */ <file_sep>/src/expr/wordlist_expression.c /* ** EPITECH PROJECT, 2019 ** PSU_42sh_2019 ** File description: ** expr_wordlist_expression */ #include <stdlib.h> #include <string.h> #include "proto/grammar.h" #include "proto/expr.h" /* ** @DESCRIPTION ** Rule for wordlist_expression expression. */ static struct expr_wordlist_expression_s *expr_wordlist_expression( struct grammar_s *this ) { struct expr_wordlist_expression_s *exp = malloc( sizeof(struct expr_wordlist_expression_s)); unsigned int save_index __attribute__((unused)) = this->index; if (!exp) exit(84); memset(exp, 0, sizeof(struct expr_wordlist_expression_s)); if (!grammar_match(this, 1, TOK_LPARANTH)) return (expr_free(exp)); exp->lparanth = grammar_get_previous(this); exp->wordlist = expr_wordlist_w(this); if (!exp->wordlist) return (expr_free(exp)); while (!grammar_match(this, 2, TOK_RPARANTH, TOK_EOF)) grammar_advance(this); exp->rparanth = grammar_get_previous(this); return exp; } struct expr_wordlist_expression_s *expr_wordlist_expression_w( struct grammar_s *this ) { struct expr_wordlist_expression_s *exp; expr_print(this, "Wordlist Expression"); exp = expr_wordlist_expression(this); expr_print_debug(this, exp); return exp; } <file_sep>/include/proto/prompt/set_raw_mode.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** sh prompt term_set_raw_mode */ #ifndef SH_PROTO_PROMPT_SET_RAW_H_ #define SH_PROTO_PROMPT_SET_RAW_H_ #include <termios.h> void term_set_raw_mode(const struct termios *orig_term); #endif /* !SH_PROTO_PROMPT_SET_RAW_H_ */ <file_sep>/include/proto/prompt/input/get_input.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** sh input get_input */ #ifndef SH_PROTO_INPUT_GET_INPUT_H_ #define SH_PROTO_INPUT_GET_INPUT_H_ #include "types/shell.h" #include "types/prompt/input.h" enum get_input_e get_input(struct sh *shell); #endif /* !SH_PROTO_INPUT_GET_INPUT_H_ */ <file_sep>/tests/input/parser/test_input_parse_tokens_quotes.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** input_parse_tokens - test */ #include <criterion/criterion.h> #include <string.h> #include "myerror.h" #include "tests/mock_types.h" #include "proto/input/parser.h" Test(input_parse_tokens, simple_quotes) { struct sh shell = MOCK_SH; struct node_s *curr; struct token_s *token; enum tokent_e types[] = {TOK_WORD, TOK_WORD, TOK_WORD, TOK_EOF}; shell.rawinput = strdup("ls \"This is inside a word\" 'and this as wel'"); input_parse_tokens(&shell); curr = shell.tokens; for (unsigned int i = 0; types[i] != TOK_EOF; i++) { if (!curr) { cr_assert(0); return; } token = curr->data; cr_assert_eq(types[i], token->type); curr = curr->next; } } Test(input_parse_tokens, backticks) { struct sh shell = MOCK_SH; struct node_s *curr; struct token_s *token; enum tokent_e types[] = {TOK_WORD, TOK_WORD, TOK_WORD, TOK_EOF}; shell.rawinput = strdup("ls `This is inside a word` `and this as wel`"); input_parse_tokens(&shell); curr = shell.tokens; for (unsigned int i = 0; types[i] != TOK_EOF; i++) { if (!curr) { cr_assert(0); return; } token = curr->data; cr_assert_eq(types[i], token->type); curr = curr->next; } } Test(input_parse_tokens, unmatched_simple) { struct sh shell = MOCK_SH; shell.rawinput = strdup("ls 'This is inside a word"); input_parse_tokens(&shell); cr_assert_eq(my_error(ERR_READ, 0), 84); } Test(input_parse_tokens, unmatched_double) { struct sh shell = MOCK_SH; shell.rawinput = strdup("ls \"This is inside a word"); input_parse_tokens(&shell); cr_assert_eq(my_error(ERR_READ, 0), 84); } Test(input_parse_tokens, unmatched_backticks) { struct sh shell = MOCK_SH; shell.rawinput = strdup("ls `This is inside a word"); input_parse_tokens(&shell); cr_assert_eq(my_error(ERR_READ, 0), 84); } <file_sep>/lib/builtins/src/unsetenv.c /* ** EPITECH PROJECT, 2020 ** builtins ** File description: ** builtin_setenv */ /* dprintf */ #include <stdio.h> /* unsetenv */ #include <stdlib.h> #include "parser_toolbox/argv_length.h" /* */ #include "builtin/setenv.h" void builtin_unsetenv(const char * const *argv) { if (!argv[0]) { dprintf(2, "unsetenv: Too few arguments.\n"); return; } for (int i = 0; argv[i]; ++i) { if (unsetenv(argv[i]) == -1) { dprintf(2, "ENOMEM\n"); return; } } return; } <file_sep>/src/shell/builtin_handlers/set.c /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** builtins */ #include <string.h> #include <stdlib.h> #include <ctype.h> #include "builtins.h" #include "types/shell.h" #include "proto/shell/builtin_handlers.h" #include "hasher/type.h" #include "hasher/insert_data.h" #include "hasher/get_data.h" #include "parser_toolbox/argv_length.h" #include "proto/shell/local_variables.h" #include "types/local_variables.h" #include "parser_toolbox/str_join.h" static _Bool builtin_set_variable( struct hasher_s **hasher, const char *arg ) { char *key = strdup(arg); char *data = NULL; struct local_var_s *var = NULL; if (!key) { return (1); } data = strchr(key, '='); if (data) { *data = 0; var = local_variable_from_data(*hasher, key, &data[1]); if (!var) { return (0); } hasher_insert_data_ordered(hasher, key, var); } return (0); } static _Bool builtin_set_error_handling( struct hasher_s **hasher, const char *arg ) { if (!isalpha(arg[0])) { dprintf(2, "set: Variable name must begin with a letter.\n"); return (1); } for (size_t j = 0; arg[j] && arg[j] != '='; ++j) { if (!isalnum(arg[j])) { dprintf(2, "set: Variable name must" " contain alphanumeric characters.\n"); return (1); } } return (builtin_set_variable(hasher, arg)); } int builtin_set_handler(struct sh *shell, const char * const *argv) { size_t argc = ptb_argv_length(argv); if (argc == 1) { local_variables_display( shell->local_var, shell->history.list ); return (0); } if (argc == 2) { return (builtin_set_error_handling(&shell->local_var, argv[1])); } else if (argc == 4) { return (builtin_set_error_handling(&shell->local_var, ptb_str_join(&argv[1], NULL))); } return (0); } <file_sep>/include/proto/prompt/action/backspace.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** sh prompt action backspace */ #ifndef SH_PROTO_PROMPT_ACTION_BACKSPACEH_ #define SH_PROTO_PROMPT_ACTION_BACKSPACEH_ #include "types/shell.h" void prompt_action_backspace(struct sh *shell); #endif /* !SH_PROTO_PROMPT_ACTION_BACKSPACEH_ */ <file_sep>/include/proto/shell/check_debug_mode.h /* ** EPITECH PROJECT, 2020 ** 42sh ** File description: ** check debug mode header */ #ifndef SH_PROTO_CHECK_DEBUG_MODE #define SH_PROTO_CHECK_DEBUG_MODE bool check_debug_mode(char *const *av); #endif /* !SH_PROTO_CHECK_DEBUG_MODE */ <file_sep>/lib/parser_toolbox/include/parser_toolbox/str_join.h /* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** str_join */ #ifndef PARSER_TOOLBOX_STR_JOIN_H_ #define PARSER_TOOLBOX_STR_JOIN_H_ char *ptb_str_join(const char *const *word_array, char const *str); #endif /* !PARSER_TOOLBOX_STR_JOIN_H_ */
7178a389b725065d08740f35911ff0a7fbb07307
[ "Markdown", "C", "Makefile", "Shell" ]
451
C
rojas-diego/epitech-42sh
07afd6c16abbd9de3fb4aa037533f1505bc0f948
6c202f82c3f2e5696ad46b6a9be2639096939701
refs/heads/main
<repo_name>tnakamura0314/codesandbox-test<file_sep>/src/index.js import "./styles.css"; /** * const,let等の変数宣言 * */ /** // var val1 = "var変数"; console.log(val1); // var変数は上書き可能 val1 = "var変数を上書き"; console.log(val1); // var変数は再宣言可能 var val1 = "var変数を再宣言"; console.log(val1); */ /** let val2 = "let変数"; console.log(val2); //letは上書きが可能 val2 = "let変数を上書き"; console.log(val2); //letは再宣言不可能 let val2 = "let変数を再宣言"; */ /** const val3 = "const変数"; console.log(val3); //const変数は上書き不可 val3 = "const変数を上書き"; //constは再宣言不可 const val3 = "const変数を再宣言"; */ //constで定義したオブジェクトはプロパティの変更が可能 /** const val4 = { name: "じゃけぇ", age: 28 }; val4.name = "jake"; val4.address = "Hiroshima"; console.log(val4); */ //constで定義した配列もプロパティの変更が可能 /** const val5 = ["dog", "cat"]; val5[0] = "bird"; val5.push("monkey"); console.log(val5); */ /** *  テンプレート文字列 * */ // const name = "じゃけぇ"; // const age = 25; //「私の名前はじゃけぇです。年齢は25歳です。」 //従来の方法 // const message1 = "私の名前は" + name + "です。年齢は" + age + "です。"; // console.log(message1); //テンプレート文字列を用いた方法 // const message2 = `私の名前は${name}です。年齢は${age}です。`; // console.log(message2); /** * アロー関数について * */ //従来の関数 // function func1(str) { // return str; // } // const func1 = function (str) { // return str; // }; // console.log(func1("func1です")); //アロー関数(function書かなくていい!) // const func2 = (str) => { // return str; // }; //{}とreturnを省略してもOK! // const func2 = (str) => str; // console.log(func2("func2です")); //2つの引数を渡す // const func3 = (num1, num2) => { // return num1 + num2; // }; //{}とreturnを省略してもOK! // const func3 = (num1, num2) => num1 + num2; // console.log(func3(2, 3)); /** * 分割代入(オブジェクト) * */ // const myProfile = { // name: "じゃけぇ", // age: 25 // }; //従来(オブジェクト) // const message1 = `名前は${myProfile.name}です。年齢は${myProfile.age}です。`; // console.log(message1); //分割代入(オブジェクト) // const { name, age } = myProfile; // const message1 = `名前は${name}です。年齢は${age}です。`; // console.log(message1); /** * 分割代入(配列) * */ // const myProfile = ["じゃけぇ", 25]; //従来(配列) // const message3 = `名前は${myProfile[0]}です。年齢は${myProfile[1]}歳です。`; // console.log(message3); //分割代入(配列) 132行目では配列の順番順に引数を指定 // const [name, age] = myProfile; // const message3 = `名前は${name}です。年齢は${age}歳です。`; // console.log(message3); /** *  デフォルト値、引数などについて */ //引数を(name = "ゲスト")と書くことで初期値(デフォルト値)を設定できる! // const sayHello = (name = "ゲスト") => console.log(`こんにちは!${name}さん!`); // sayHello(); /** * スプレッド構文 ... */ // //配列の展開 // const array = [1, 2]; // // console.log(array); // //配列の中身を順番に処理してくれる ... // // console.log(...array); // const sumFunc = (num1, num2) => console.log(num1 + num2); // // sumFunc(array[0], array[1]); // //上の記述と同じ配列の中身を順番に処理してくれる ... // sumFunc(...array); //まとめる // const array2 = [1, 2, 3, 4, 5]; // const [num1, num2, ...num3] = array2; // console.log(num1); // console.log(num2); // console.log(num3); //配列のコピー、結合 // const array4 = [10, 20]; // const array5 = [30, 40]; // //配列をスプレット構文で代入(参照を引き継がずにarray6[0]の値だけ変更できる) // const array6 = [...array4]; // console.log(array6); // array6[0] = 100; // console.log(array4); // //2つの配列を結合する!スプレット構文で // const array7 = [...array4, ...array5]; // console.log(array7); //普通にイコールで代入してしまうと、同じ参照となるため、array4の値も変更されてしまう。 // const array8 = array4; // array8[0] = 100; // console.log(array8); // console.log(array4); /** * mapやfilterを使用した配列処理について */ const nameArr = ["田中", "山田", "じゃけぇ"]; // for (let index = 0; index < nameArr.length; index++) { // console.log(nameArr[index]); // } // for (let index = 0; index < nameArr.length; index++) { // console.log(`${index}番目は${nameArr[index]}です。`); // } // const nameArr2 = nameArr.map((name) => { // return name; // }); // console.log(nameArr2); //mapを使用してループ処理(206行目と同じ処理) // nameArr.map((name, index) => console.log(`${index + 1}番目は${name}です。`)); const numArr = [1, 2, 3, 4, 5]; //filterは条件分岐で該当のもののみをとってきて新しい配列作れる // const newNumArr = numArr.filter((num) => { // //2で割った余りが1になる奇数のみ返す // return num % 2 === 1; // }); // console.log(newNumArr); // const newNameArr = nameArr.map((name) => { // if (name === "じゃけぇ") { // return name; // } else { // return `${name}さん`; // } // }); // console.log(newNameArr); /** * 三項演算子について */ // 【構文】  条件 ? 条件がtrueの時 : 条件がfalseの時 // const val1 = 1 > 0 ? 'trueです' : 'falseです'; // console.log(val1); // const num = 1300; // //toLocaleString()はカンマ区切りにできるメソッド // // console.log(num.toLocaleString()); // //typeof その変数の型を判定してくれるもの // //三項演算子 numが数値ならカンマ区切りで表示。 数値以外なら'数値を入力してください'と表示 // const formattedNum = // typeof num === "number" ? num.toLocaleString() : "数値を入力してください。"; // console.log(formattedNum); //num1 + num2が100を超えるかを三項演算子で判定して、返す値を変える関数 // const checkSum = (num1, num2) => { // return num1 + num2 > 100 ? '100を超えています!!' : '許容範囲内です。'; // } // console.log(checkSum(50,60)); // console.log(checkSum(50,40)); /** * 論理演算子の本当の意味を知ろう  (&&アンパサンド ||パイプライン) */ // const flag1 = true; // const flag2 = false; // if(flag1 || flag2){ // console.log("1か2はtrueになります"); // } // if(flag1 && flag2){ // console.log("1も2もtrueになります"); // } // || は283行目の左側がfalseなら右側を返す。左側がtrueなら左側を返す。 // const num = null; // const fee = num || "金額未設定です"; // console.log(fee); // && は左側がtrueなら右側を返す // const num2 = 100; // const fee2 = num2 && "何か設定されました。" // console.log(fee2); document.getElementById("app").innerHTML = ` <h1>Hello Vanilla!</h1> <div> We use the same configuration as Parcel to bundle this sandbox, you can find more info about Parcel <a href="https://parceljs.org" target="_blank" rel="noopener noreferrer">here</a>. </div> `;
40aebefd46aa15b1fa1a2a4e9098c7ead89913ea
[ "JavaScript" ]
1
JavaScript
tnakamura0314/codesandbox-test
e95ad9fdfd14e425faca9e17de6a618fcc0c8635
e512259c5b855a8d76b0c75fb16280ec307acadd
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.Content.PM; using Android.Content.Res; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace PigGame { [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)] public class IntroActivity : Activity { protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); if ((Application.ApplicationContext.Resources.Configuration.ScreenLayout & ScreenLayout.SizeMask) == ScreenLayout.SizeSmall) { RequestedOrientation = ScreenOrientation.Portrait; } if ((Application.ApplicationContext.Resources.Configuration.ScreenLayout & ScreenLayout.SizeMask) == ScreenLayout.SizeNormal) { RequestedOrientation = ScreenOrientation.Portrait; } if ((Application.ApplicationContext.Resources.Configuration.ScreenLayout & ScreenLayout.SizeMask) == ScreenLayout.SizeLarge) { RequestedOrientation = ScreenOrientation.Landscape; } SetContentView(Resource.Layout.IntroActivity); // Create your application here var startGameButton = FindViewById<Button>(Resource.Id.startGameButton); var nameEditText1 = FindViewById<EditText>(Resource.Id.textInputEditText1); var nameEditText2 = FindViewById<EditText>(Resource.Id.textInputEditText2); var score1Label = FindViewById<TextView>(Resource.Id.introPlayer1Label); var score2Label = FindViewById<TextView>(Resource.Id.introPlayer2Label); var messageLabel = FindViewById<TextView>(Resource.Id.introMessageLabel); startGameButton.Click += (sender, e) => { Intent intent = new Intent(this, typeof(GameActivity)); if(nameEditText1.Text == "" || nameEditText2.Text == "") { messageLabel.Text = "Enter a name for each player"; } else { intent.PutExtra("name1", nameEditText1.Text); intent.PutExtra("name2", nameEditText2.Text); nameEditText1.Enabled = false; nameEditText2.Enabled = false; StartActivity(intent); } }; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace PigGame { class PigGameLogic { public PigGameLogic() { } public PigGameLogic(string name1, string name2, int score1, int score2, Boolean turn, int turnPoints, int lastRoll) { Player1Name = name1; Player2Name = name2; Player1Score = score1; Player2Score = score2; Player1Turn = turn; PointsForTurn = turnPoints; RollValue = lastRoll; } public Boolean Player1Turn = true; public string Player1Name { get; set; } public string Player2Name { get; set; } public int Player1Score { get; set; } public int Player2Score { get; set; } public int PointsForTurn { get; set; } public int RollValue { get; set; } public string RollDie() { Random random = new Random(); RollValue = random.Next(1, 6); if (RollValue == 1) PointsForTurn = 0; else PointsForTurn += RollValue; return PointsForTurn.ToString(); } public void EndTurn() { if (Player1Turn == true) { if (Player1Score + PointsForTurn <= 100) { Player1Score += PointsForTurn; Player1Turn = false; } else Player1Turn = false; PointsForTurn = 0; } else { if(Player2Score + PointsForTurn <= 100) { Player2Score += PointsForTurn; Player1Turn = true; } else Player1Turn = true; PointsForTurn = 0; } CheckForWinner(); } public void GetPlayerNames(string name1, string name2) { Player1Name = name1; Player2Name = name2; } public string CheckForWinner() { if(Player1Turn == true) { if (Player1Score == 100) return Player2Name + " wins the game"; if (Player2Score == 100) return Player2Name + " wins the game!"; else return ""; } else return ""; } public int SetDiceImage() { if (RollValue == 0) return Resource.Drawable.pig; int[] diceImages = new int[6] { Resource.Drawable.Die1, Resource.Drawable.Die2, Resource.Drawable.Die3, Resource.Drawable.Die4, Resource.Drawable.Die5, Resource.Drawable.Die6 }; return diceImages[RollValue - 1]; } } }<file_sep>using Android.App; using Android.Widget; using Android.OS; using Android.Support.V7.App; using System; using Newtonsoft.Json; using System.IO; using System.Xml.Serialization; using Android.Content; using Android.Runtime; using Android.Views; using Android.Content.PM; using Android.Content.Res; namespace PigGame { [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = false)] public class GameActivity : AppCompatActivity { PigGameLogic gameLogic; string player1Name; string player2Name; int player1Score; int player2Score; int pointsForTurn; int lastRollValue; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); if ((Application.ApplicationContext.Resources.Configuration.ScreenLayout & ScreenLayout.SizeMask) == ScreenLayout.SizeSmall) { RequestedOrientation = ScreenOrientation.Portrait; } if ((Application.ApplicationContext.Resources.Configuration.ScreenLayout & ScreenLayout.SizeMask) == ScreenLayout.SizeNormal) { RequestedOrientation = ScreenOrientation.Portrait; } if ((Application.ApplicationContext.Resources.Configuration.ScreenLayout & ScreenLayout.SizeMask) == ScreenLayout.SizeLarge) { RequestedOrientation = ScreenOrientation.Landscape; } // Set our view from the "main" layout resource SetContentView(Resource.Layout.GameActivity); // create all of the views var newGameButton = FindViewById<Button>(Resource.Id.newGameButton); var rollButton = FindViewById<Button>(Resource.Id.rollButton); var newPlayersButton = FindViewById<Button>(Resource.Id.newPlayersPuttonButton); var endTurnButton = FindViewById<Button>(Resource.Id.endTurnButton); var score1Label = FindViewById<TextView>(Resource.Id.scoreLabel1); var score2Label = FindViewById<TextView>(Resource.Id.scoreLabel2); var scoreTextView1 = FindViewById<TextView>(Resource.Id.scoreTextView1); var scoreTextView2 = FindViewById<TextView>(Resource.Id.scoreTextView2); var whosTurnLabel = FindViewById<TextView>(Resource.Id.whosTurnLabel); var pointsForTurnTextView = FindViewById<TextView>(Resource.Id.pointsForTurnTextView); var diceImageView = FindViewById<ImageView>(Resource.Id.diceImageView); //if the game has been saved get the page out of the json if (savedInstanceState != null) { gameLogic = new PigGameLogic(); string jsonGame = savedInstanceState.GetString("pageInJson"); gameLogic = JsonConvert.DeserializeObject<PigGameLogic>(jsonGame); score1Label.Text = gameLogic.Player1Name + "'s Score"; score2Label.Text = gameLogic.Player2Name + "'s Score"; scoreTextView1.Text = gameLogic.Player1Score.ToString(); scoreTextView2.Text = gameLogic.Player2Score.ToString(); pointsForTurnTextView.Text = gameLogic.PointsForTurn.ToString(); diceImageView.SetImageResource(gameLogic.SetDiceImage()); if (gameLogic.Player1Turn == true) whosTurnLabel.Text = gameLogic.Player1Name + "'s Turn"; else whosTurnLabel.Text = gameLogic.Player2Name + "'s Turn"; } else { //Create a new game logic gameLogic = new PigGameLogic(); player1Name = Intent.GetStringExtra("name1"); player2Name = Intent.GetStringExtra("name2"); score1Label.Text = player1Name + "'s Score"; score2Label.Text = player2Name + "'s Score"; gameLogic.GetPlayerNames(player1Name, player2Name); whosTurnLabel.Text = player1Name + "'s Turn"; player1Score = 0; player2Score = 0; diceImageView.SetImageResource(Resource.Drawable.pig); } newGameButton.Click += (sender, e) => { diceImageView.SetImageResource(Resource.Drawable.pig); gameLogic = new PigGameLogic(); player1Name = Intent.GetStringExtra("name1"); player2Name = Intent.GetStringExtra("name2"); gameLogic.GetPlayerNames(player1Name,player2Name); scoreTextView1.Text = gameLogic.Player1Score.ToString(); scoreTextView2.Text = gameLogic.Player2Score.ToString(); whosTurnLabel.Text = player1Name + "'s Turn"; pointsForTurnTextView.Text = "0"; }; rollButton.Click += (sender, e) => { string roll = gameLogic.RollDie(); if (roll != "0") pointsForTurnTextView.Text = roll; else { rollButton.Enabled = false; whosTurnLabel.Text = "You rolled a 1"; pointsForTurnTextView.Text = roll; } diceImageView.SetImageResource(gameLogic.SetDiceImage()); }; endTurnButton.Click += (sender, e) => { gameLogic.EndTurn(); rollButton.Enabled = true; if (gameLogic.CheckForWinner() != "") { whosTurnLabel.Text = gameLogic.CheckForWinner(); rollButton.Enabled = false; endTurnButton.Enabled = false; } else { scoreTextView1.Text = gameLogic.Player1Score.ToString(); scoreTextView2.Text = gameLogic.Player2Score.ToString(); pointsForTurnTextView.Text = gameLogic.PointsForTurn.ToString(); if (gameLogic.Player1Turn == false) whosTurnLabel.Text = gameLogic.Player2Name + "'s Turn"; else whosTurnLabel.Text = gameLogic.Player1Name + "'s Turn"; } }; newPlayersButton.Click += (sender, e) => { diceImageView.SetImageResource(Resource.Drawable.pig); Intent intent = new Intent(this, typeof(IntroActivity)); StartActivity(intent); }; } protected override void OnSaveInstanceState(Bundle outState) { string pageInJson = JsonConvert.SerializeObject(this.gameLogic, Formatting.Indented); outState.PutString("pageInJson",pageInJson); base.OnSaveInstanceState(outState); } } } // EXPERIMENTAL STUFF(DETECTING ORIENTATION) //var windowManager = ApplicationContext.GetSystemService(Context.WindowService).JavaCast<IWindowManager>(); //var orientation = windowManager.DefaultDisplay.Rotation; //if (orientation != Android.Views.SurfaceOrientation.Rotation0) //Android.Views.SurfaceOrientation.Rotation270
ad91382a045b9f6f1611069460a8c738728d1117
[ "C#" ]
3
C#
trevoruehlinx1/AndLab5
94501080ef9cb06512842632d528d48863303d4b
d65b1a4a78b16505b714d3e0f207a22fa2e931d1
refs/heads/master
<file_sep>#!/bin/bash -e # K8S_HOST = Kubernetes Hostname # K8S_TOKEN = Kubernetes Service Account Token # K8S_DEPLOYMENT = Kubernetes Deployment Name # K8S_CONTAINER = Container name to update in deployment # K8S_IMAGE = Docker image name (without the version) # K8S_TAG = Docker tag to install # K8S_ENV_KEY = Environment key to update (optional) # K8S_ENV_VALUE = Environment value to update (optional) if [ -z "$K8S_TOKEN" ] || [ -z "$K8S_TAG" ] || [ -z "$K8S_DEPLOYMENT" ] || [ -z "$K8S_CONTAINER" ] || [ -z "$K8S_IMAGE" ] || [ -z "$K8S_HOST" ]; then echo Unable to kubernetes trigger, missing environment variables exit 2 fi if [ ! -z "$K8S_ENV_KEY" ] && [ ! -z "$K8S_ENV_VALUE" ]; then echo Overriding an Environment key ${K8S_ENV_KEY} with ${K8S_ENV_VALUE} ENVIRO_MOD=",\"env\":[{\"name\":\"${K8S_ENV_KEY}\",\"value\":\"${K8S_ENV_VALUE}\"}]" fi echo "Triggering Kubernetes deployment" URL=https://${K8S_HOST}/apis/extensions/v1beta1/namespaces/default/deployments/${K8S_DEPLOYMENT} BODY="{\"spec\":{\"template\":{\"spec\":{\"containers\":[{\"name\":\"${K8S_CONTAINER}\",\"image\":\"${K8S_IMAGE}:${K8S_TAG}\"${ENVIRO_MOD}}]}}}}" curl -k -i \ -XPATCH \ -H "Accept: application/json, */*" \ -H "Authorization: Bearer ${K8S_TOKEN}" \ -H "Content-Type: application/strategic-merge-patch+json" \ -d $BODY \ $URL > /tmp/k8s_out head -1 /tmp/k8s_out | grep "200" || (echo "Failed deployment" && cat /tmp/k8s_out && exit 1) <file_sep>#!/bin/bash -e # DOCKER_TAG = Tag to check for # DOCKER_REPO = Org/Repo name if [ -z "$DOCKER_TAG" ] || [ -z "$DOCKER_REPO" ]; then echo Unable to docker wait, missing environment variables exit 2 fi function check_status { TOKEN=`wget -q -O - "https://auth.docker.io/token?service=registry.docker.io&scope=repository:$DOCKER_REPO:pull" | python -c "import sys, json; print(json.load(sys.stdin))['token']"` wget -S --spider -q --header="Authorization: Bearer $TOKEN" https://index.docker.io/v2/$DOCKER_REPO/manifests/$DOCKER_TAG > /dev/null 2>&1 } echo Looking for image $DOCKER_REPO:$DOCKER_TAG MINUTES=0 until check_status do if [ $MINUTES -gt 20 ] ; then echo "Timed out after 20 minutes" exit 1 fi echo "Not available yet ($MINUTES minutes elapsed)" sleep 60 ((MINUTES+=1)) done echo Image found <file_sep>#!/bin/bash -e # GITHUB_TOKEN = Token for updating your git repo # RELEASE_FILE = File to release if [ -z "$GITHUB_TOKEN" ] || [ -z "$RELEASE_FILE" ]; then echo Unable to release, missing environment variables exit 2 fi GITHUB_RELEASE=/tmp/linux-amd64-github-release if [ ! -f "$GITHUB_RELEASE" ] ; then echo Downloading github-release wget -q -O - https://github.com/github-release/github-release/releases/latest \ | egrep -o '/github-release/github-release/releases/download/v[0-9.]*/linux-amd64-github-release.bz2' \ | wget --base=http://github.com/ -i - -O /tmp/linux-amd64-github-release.bz2 bzip2 -dv /tmp/linux-amd64-github-release.bz2 chmod +x $GITHUB_RELEASE fi GIT_VERSION=/tmp/gitversion if [ ! -f "$GIT_VERSION" ] ; then echo Downloading gitversion wget -q -O - https://github.com/screwdriver-cd/gitversion/releases/latest \ | egrep -o '/screwdriver-cd/gitversion/releases/download/v[0-9.]*/gitversion_linux_amd64' \ | wget --base=http://github.com/ -i - -O /tmp/gitversion chmod +x $GIT_VERSION fi GIT_ORG=`git remote -v | grep fetch | sed 's/ (fetch)//' | cut -d'/' -f4` GIT_REPO=`git remote -v | grep fetch | sed 's/ (fetch)//' | cut -d'/' -f5` if [ -f VERSION ] ; then GIT_TAG=$(<VERSION) else GIT_TAG=`$GIT_VERSION --prefix v show` fi echo "Creating release $GIT_TAG for $GIT_ORG / $GIT_REPO" $GITHUB_RELEASE --version $GITHUB_RELEASE release --user $GIT_ORG --repo $GIT_REPO --tag $GIT_TAG --name $GIT_TAG $GITHUB_RELEASE upload --user $GIT_ORG --repo $GIT_REPO --tag $GIT_TAG --name $RELEASE_FILE --file $RELEASE_FILE <file_sep>#!/bin/bash -e GIT_VERSION=/tmp/gitversion if [ ! -f "$GIT_VERSION" ] ; then echo Downloading gitversion wget -q -O - https://github.com/screwdriver-cd/gitversion/releases/latest \ | egrep -o '/screwdriver-cd/gitversion/releases/download/v[0-9.]*/gitversion_linux_amd64' \ | wget --base=http://github.com/ -i - -O /tmp/gitversion chmod +x $GIT_VERSION fi echo Finding version $GIT_VERSION --prefix v show | tee VERSION
50365e4e3f01b231d624c3d53ad715d8038f543c
[ "Shell" ]
4
Shell
ibu1224/toolbox
90327ac84b3920f4b1819d70c6d4a70b01037aa9
36f55ae40de3a29c392c3d6d61449c9dcd3c1033
refs/heads/master
<repo_name>ermolaevp/webpack-redux<file_sep>/src/modules/endpoints/reducers/data.js const initalState = { _items: [], _meta: { choices: { priority: [1, 2, 3], proto: ["TCP", "UDP", "ICMP"], group: ["info","scan","auth","policy","malware","ddos","attacks","other"] } }, _links: {}, } const data = (state = initalState, action = {}) => { switch (action.type) { case 'RECEIVE_DATA': return { ...state, ...action.payload } default: return state } } export default data <file_sep>/src/modules/app_state/actions/app_state_set.js const appStateSet = (state) => { return { type: 'SET_APP_STATE', state } } export default appStateSet;<file_sep>/src/widgets/DateTimePicker/date_time_picker.js import './style.css' import React, { Component, PropTypes } from "react" import { connect } from 'react-redux' import moment from "moment" import "moment/locale/ru" import { dateTimeFormat } from '../../constants' import classnames from 'classnames' import DayPicker, { DateUtils } from "react-day-picker" import LocaleUtils from "react-day-picker/moment" const TimePicker = ({ handleClick }) => { const timeArray = [] for (let i = 0; i < 24; i++) { timeArray[i] = i } return( <div className="time-picker"> {timeArray.map(i => <div key={i}> <div className="time-picker-item" onClick={e => handleClick(i, 0)}>{i}:00</div> <div className="time-picker-item" onClick={e => handleClick(i, 30)}>{i}:30</div> </div> )} <div className="time-picker-item" onClick={e => handleClick(23, 59)}>23:59</div> </div> ) } export default class DateTimePicker extends Component { static propTypes = { handleChange: PropTypes.func.isRequired } constructor(props) { super(props) this.state = { selectedDay: null, pickerVisible: false } } componentWillReceiveProps(nextProps) { if (nextProps.date === null) { this.timeInp.value = '' return } if (this.props.date === null || nextProps.date.toString() !== this.props.date.toString()) { this.timeInp.value = moment(nextProps.date).format(dateTimeFormat) } } render() { let pickerDate, pickerTime const setTime = (h, m) => { let prevTime = new Date(this.timeInp.value) if (prevTime.toString() === 'Invalid Date') { prevTime = new Date } const currentTime = moment(prevTime) currentTime.hour(h) currentTime.minute(m) this.timeInp.value = currentTime.format(dateTimeFormat) this.props.handleChange(currentTime.toDate()) } const setDate = (e, day, { selected }) => { this.setState({ selectedDay: selected ? null : day }) let prevTime = new Date(this.timeInp.value) const currentTime = moment(new Date(day)) if (prevTime.toString() !== 'Invalid Date') { prevTime = moment(prevTime) currentTime.hour(prevTime.hour()) currentTime.minute(prevTime.minute()) } this.timeInp.value = currentTime.startOf('day').format(dateTimeFormat) this.props.handleChange(currentTime.toDate()) } const getDefaultValue = (date) => { if (date === null) return '' let d = new Date(date) if (d.toString() === 'Invalid Date') return '' return moment(date).format(dateTimeFormat) } return ( <div className={classnames(['date-time-picker', { 'dtp--visible': this.props.visibility }])} onClick={e => e.stopPropagation()} > <input type="text" ref={node => this.timeInp = node} defaultValue={getDefaultValue(this.props.date)} onBlur={e =>{ if (e.currentTarget.value !== '') { this.props.handleChange(new Date(e.currentTarget.value)) } }} onClick={this.props.handleChangeVisibility} /> <div className="picker-wrapper"> <div className="picker-tabs"> <span className="picker-tab-date" onClick={e => { pickerDate.style.display = 'block' pickerTime.style.display = 'none' }} > <i className="material-icons">date_range</i> </span> <span className="picker-tab-time" onClick={e => { pickerDate.style.display = 'none' pickerTime.style.display = 'block' }} > <i className="material-icons">av_timer</i> </span> </div> <div className="picker-date" ref={node => pickerDate = node}> <DayPicker ref="daypicker" localeUtils={ LocaleUtils } locale="ru" numberOfMonths={ 1 } onDayClick={ setDate } selectedDays={day => DateUtils.isSameDay(this.state.selectedDay, day)} /> </div> <div className="picker-time" ref={node => pickerTime = node}> <TimePicker handleClick={ setTime }/> </div> </div> </div> ) } } <file_sep>/src/widgets/FilterForm/index.js import React, { Component, PropTypes } from 'react'; import classnames from 'classnames'; import StringFilterForm from './string_filter_form'; import NumberFilterForm from './number_filter_form'; import DatetimeFilterForm from './datetime_filter_form'; import SubsetFilterForm from './subset_filter_form'; export default class FilterForm extends Component { render() { return ( <div> {(() => { switch (this.props.filterType) { case 'number': return <NumberFilterForm {...this.props}/> case 'datetime': return <DatetimeFilterForm {...this.props}/> case 'subset': return <SubsetFilterForm {...this.props}/> case 'mongo_id': case 'string': return <StringFilterForm {...this.props}/> default: return <div></div> } })()} </div> ) } } <file_sep>/src/widgets/IncidentCard/utils.js export const RenderList = (item, key) => { if (typeof item === 'string') return <li key={key}>{item}</li>; if (Array.isArray(item)) return item.map((i, j) => RenderList(i, j)); if (typeof item === 'object') { return Object.keys(item).map(subitem => { return ( <li key={subitem}>{_t(subitem)} <ul>{RenderList(item[subitem])}</ul> </li> ) }); } } <file_sep>/src/modules/endpoints/actions/set_fetching.js const setFetching = (endpoint, isFetching = true) => { return { type: 'SET_FETCHING', endpoint, isFetching } } export default setFetching; <file_sep>/src/modules/charts/actions/incidents_chart_set_data.js export default function incidentsChartSetData(payload) { return { type: 'INCIDENTS_CHART_SET_DATA', payload } } <file_sep>/src/containers/Tables/Events.js import React, { Component } from 'react'; import { connect } from 'react-redux'; import classnames from 'classnames'; import moment from 'moment'; import { InitalConstants } from '../../constants'; import { mapEndpointStateToProps, mapEndpointDispatchToProps } from './utils' // Widgets import Table from '../../widgets/Table/table'; // Actions import filterSet from '../../modules/endpoints/actions/filter_set'; import filterReplace from '../../modules/endpoints/actions/filter_replace'; const ENDPOINT = 'events'; const mapStateToProps = (state) => { return { ...mapEndpointStateToProps(ENDPOINT, state) } } const mapDispatchToProps = (dispatch) => { return { ...mapEndpointDispatchToProps(ENDPOINT, dispatch), handleDateRangeChange(date_range) { return dispatch(filterSet('events', 'logdate', { $gte: date_range.from, $lte: date_range.to })) }, handleRowClick(e, data) { const logdate = new Date(data.logdate); const logTime = { '$gte': moment(logdate).subtract(300, 'seconds').toDate(), '$lte': moment(logdate).add(300, 'seconds').toDate() } if (data.homenet_address.indexOf(data.src) === -1) { dispatch(filterReplace('firewall', {logTime, SourceIP: data.src})); dispatch(filterReplace('webproxy', {logTime, ClientIP: data.src})); } else if (data.homenet_address.indexOf(data.dst) === -1) { dispatch(filterReplace('firewall', {logTime, DestanationIP: data.dst})); dispatch(filterReplace('webproxy', {logTime, DestHostIP: data.dst})); } } } } export default connect(mapStateToProps, mapDispatchToProps)(Table); <file_sep>/src/modules/date_range/reducers/date_range.js import moment from 'moment' import { InitalConstants } from '../../../constants' const initalState = { from: InitalConstants.DATE_RANGE.from, to: InitalConstants.DATE_RANGE.to } export default function date_range(state=initalState, action={}) { switch (action.type) { case 'DATE_RANGE_SET': return { ...state, ...action.payload } case 'DATE_RANGE_SET_BY_PERIOD': const { period, unit } = action.payload return { from: moment().subtract(period, unit).startOf('minute').toDate(), to: new Date, } default: return state } } <file_sep>/Dockerfile FROM node:4.4.1 RUN mkdir -p /var/www WORKDIR /var/www COPY package.json . COPY webpack.production.config.js . COPY server-prod.js . RUN npm install COPY . /var/www RUN npm run build ENTRYPOINT ["npm", "run", "serve"] <file_sep>/src/widgets/Header/header.js import './header.css' import React from 'react' import logo from './logo.svg' const Header = () => ( <div className="header"> <div className="header-brand clearfix"> <img src={logo} alt="logo" /> <span>Threat Intelligence</span><br/> <span className="header-brand--small">analytics system</span> </div> <a style={{ position: 'absolute', top: 0, right: 0, color: '#0288d1', cursor: 'default', }} href="javascript:localStorage.clear();window.location.href='/'" title="clear localStorage" > clear localStorage </a> </div> ) export default Header <file_sep>/src/modules/filters/reducers/filters.js const initalState = { sensors: [] } export default function filters(state=initalState, action){ switch (action.type) { case 'SET_FILTERS': return { ...state, ...action.payload } default: return state } } <file_sep>/src/modules/endpoints/reducers/endpoints.js import params from './params'; import data from './data'; import date_range from '../../date_range/reducers/date_range' import moment from 'moment' const initalEndpointState = { isFetching: false, data: data(), params: params() } const initalState = { events: { ...initalEndpointState, params: { ...initalEndpointState.params, filter: { ...initalEndpointState.params.filter, logdate: { $gte: date_range().from, $lte: date_range().to }, } } }, incidents: { ...initalEndpointState, selectedId: null, params: { ...initalEndpointState.params, filter: { ...initalEndpointState.params.filter, created: { $gte: moment(date_range().to).subtract(1, 'days').toDate(), $lte: date_range().to }, } } }, webproxy: { ...initalEndpointState }, firewall: { ...initalEndpointState } } const endpoints = (state = initalState, action) => { switch (action.type) { case 'SET_STATE': return { ...state, ...action.payload } case 'SET_FETCHING': return { ...state, [action.endpoint]: { ...state[action.endpoint], isFetching: action.isFetching } } case 'RECEIVE_DATA': return { ...state, [action.endpoint]: { ...state[action.endpoint], data: data(state[action.endpoint].data, action) } } case 'INCIDENT_SELECT': return { ...state, [action.endpoint]: { ...state[action.endpoint], selectedId: action.payload } } case 'SET_FILTER': case 'REMOVE_FILTER': case 'SET_PAGE': case 'SET_MAX_RESULTS': case 'SORT_ASC': case 'SORT_DESC': case 'SORT_REMOVE': case 'TOGGLE_GROUP_FILTER': case 'REPLACE_FILTER': return { ...state, [action.endpoint]: { ...state[action.endpoint], params: params(state[action.endpoint].params, action) } } default: return state } } export default endpoints; <file_sep>/src/widgets/TreeMenu/tree_branch.js import React, { Component, PropTypes } from 'react' import classnames from 'classnames' export default class TreeBranch extends Component { constructor(props) { super(props) this.state = { collapsed: true } this.collapse = this.collapse.bind(this) } collapse(e) { this.setState({ collapsed: !this.state.collapsed }) } render(){ const { collapsed } = this.state const { id, title, handleChange, isChecked } = this.props return ( <li className={classnames(["tree-branch", { collapsed }])}> <i className="material-icons collapse-branch" onClick={this.collapse} > { this.state.collapsed ? 'add' : 'remove' } </i> <input type="checkbox" id={id} onChange={handleChange} checked={isChecked} /> <label htmlFor={id}> {title} </label> <ul> {this.props.children} </ul> </li> ) } } <file_sep>/src/containers/Tables/utils.js // Actions import filterSet from '../../modules/endpoints/actions/filter_set'; import filterReplace from '../../modules/endpoints/actions/filter_replace'; import filterRemove from '../../modules/endpoints/actions/filter_remove'; import setFetching from '../../modules/endpoints/actions/set_fetching'; import dataFetch from '../../modules/endpoints/actions/data_fetch'; import attributePlaceAfter from '../../modules/attributes/actions/attribute_place_after'; import attributeToggle from '../../modules/attributes/actions/attribute_toggle'; import attributeSetNewSize from '../../modules/attributes/actions/attribute_set_new_size'; import sortRemove from '../../modules/endpoints/actions/sort_remove'; import sortAscending from '../../modules/endpoints/actions/sort_ascending'; import sortDescending from '../../modules/endpoints/actions/sort_descending'; import pageSet from '../../modules/endpoints/actions/page_set'; import maxResultsSet from '../../modules/endpoints/actions/max_results_set'; const paginationParams = (links={}) => { const { prev={}, next={}, last={} } = links const findPage = (href='') => { const [ page ] = /\d+$/.exec(href) || [] return parseInt(page, 10); }; return { prev: findPage(prev.href) || 1, next: findPage(next.href), last: findPage(last.href), } } export const mapEndpointStateToProps = (endp, state) => { const ENDPOINT = endp const { endpoints, attributes } = state const endpoint = endpoints[ENDPOINT] const attrs = attributes[ENDPOINT] return { prefix: ENDPOINT, date_range: state.date_range, attributes: attrs, columns: _(attrs).select(attr => attr.visibility === true), items: endpoint.data._items, params: endpoint.params, isFetching: endpoint.isFetching, isSortedAsc(column) { return endpoint.params.sort[column.id] === 1; }, isSortedDesc(column) { return endpoint.params.sort[column.id] === -1; }, isFiltered(column) { const { filter } = endpoint.params if (column.id === 'group') { return filter.group.$in.length > 0; } return ((typeof filter[column.id] !== 'undefined') && filter[column.id] !== null) }, getFilter(column) { return endpoint.params.filter[column.id]; }, getChoices(column) { if (column.filter_type !== 'subset') return false return endpoint.data._meta.choices[column.id] }, pagination: { total: endpoint.data._meta.total || 0, max_results: endpoint.params.max_results, page: endpoint.params.page, ...paginationParams(endpoint.data._links) } } } export const mapEndpointDispatchToProps = (endpoint, dispatch) => { return { handleRowClick(e, data) { }, handleDateRangeChange(date_range) { }, dataFetch(params = {}) { dispatch(dataFetch(endpoint, params)); }, moveColumn(source, target) { dispatch(attributePlaceAfter(endpoint, source, target)); }, resizeColumn(id, newSize) { dispatch(attributeSetNewSize(endpoint, id, newSize)) }, sortAscending(column, isSortedAsc=false) { if (isSortedAsc) return dispatch(sortRemove(endpoint, column.id)) return dispatch(sortAscending(endpoint, column.id)) }, sortDescending(column, isSortedDesc=false) { if (isSortedDesc) return dispatch(sortRemove(endpoint, column.id)) return dispatch(sortDescending(endpoint, column.id)) }, removeSorting(column) { return dispatch(sortRemove(endpoint, column.id)) }, attrVisibilityToggle(e, id) { dispatch(attributeToggle(endpoint, id)); }, setPage(page) { if(isNaN(page)) return false; dispatch(pageSet(endpoint, page)); }, setMaxResults(maxResults) { dispatch(maxResultsSet(endpoint, maxResults)); }, handleFilterForm(column, data) { dispatch(pageSet(endpoint, 1)); dispatch(filterSet(endpoint, column.id, data)) }, handleResetFilterForm(column) { dispatch(pageSet(endpoint, 1)); dispatch(filterRemove(endpoint, column.id)) }, } } <file_sep>/README.md IDS Frontend ============ Dockerfile FROM node:4.4.1 RUN mkdir -p /var/www WORKDIR /var/www COPY package.json . COPY webpack.production.config.js . COPY server-prod.js . ADD entrypoint.sh /sbin/entrypoint.sh RUN chmod 755 /sbin/entrypoint.sh ENTRYPOINT ["/sbin/entrypoint.sh"] entrypoint.sh #!/bin/bash echo echo "Installing packages..." npm install if [ "$NODE_ENV" = "production" ] then echo echo "Building app..." npm run build echo echo "Serving app in production mode..." npm run serve else echo echo "Running app..." npm start fi docker-compose.yml version: '2' services: ids_frontend: build: context: . volumes: - node_modules:/var/www/node_modules - ./src:/var/www/src ports: - "9001:9001" environment: - NODE_ENV=development - EVE_BACKEND_HOST=10.0.9.118 - EVE_BACKEND_PORT=8000 - NPM_CONFIG_LOGLEVEL=warn - NPM_CONFIG_SAVE=true - NPM_CONFIG_SAVE_EXACT=true - NPM_CONFIG_REGISTRY=http://registry.npmjs.org/ - NPM_CONFIG_PROXY=http://10.0.9.23:3143 - PORT=9001 volumes: node_modules: driver: local <file_sep>/src/modules/sensors/actions/sensors_toggle.js export default function sensorsToggle(payload) { return { type: 'SENSORS_TOGGLE', payload } } <file_sep>/src/modules/fired_signatures/actions/fs_set_sort.js const fsSetSort = (payload) => { return { type: 'FS_SET_SORT', payload } } export default fsSetSort <file_sep>/src/modules/app_state/reducers/app_state.js import { InitalConstants } from '../../../constants' const initalState = { status: 200, error: undefined, } const app_state = (state = initalState, action) => { switch (action.type) { case 'SET_APP_STATE': return { ...state, ...action.state } case 'SET_APP_STATE_OK': return { ...state, status: 200, error: undefined } case 'SET_APP_STATE_ERROR': const { error } = action; return { ...state, status: error.status || 500, error } default: return state; } } export default app_state; <file_sep>/src/modules/endpoints/actions/sort_ascending.js const sortAscending = (endpoint, column) => { return { type: 'SORT_ASC', endpoint, column } } export default sortAscending; <file_sep>/src/modules/endpoints/actions/filter_remove.js const filterRemove = (endpoint, column) => { return { type: 'REMOVE_FILTER', endpoint, column } } export default filterRemove; <file_sep>/src/containers/DatePicker.js import "react-day-picker/lib/style.css"; import '../public/assets/css/date-range-picker.css'; import React, { Component, PropTypes } from "react"; import { connect } from 'react-redux'; import moment from "moment"; import DayPicker, { DateUtils } from "react-day-picker"; import LocaleUtils from "react-day-picker/moment"; import classnames from 'classnames'; import "moment/locale/ru"; import { dateTimeFormat } from '../constants'; // Actions import dateRangeSet from '../modules/date_range/actions/date_range_set' import dateRangeSetByPeriod from '../modules/date_range/actions/date_range_set_by_period' const mapStateToProps = ({ date_range }) => { return { date_range } } const mapDispatchToProps = (dispatch) => { return { setDateRange(date_range) { dispatch(dateRangeSet(date_range)) }, setDateRangeByPeriod(period, unit='minutes') { dispatch(dateRangeSetByPeriod({ period, unit })) } } } class DatePickerContainer extends Component { constructor(props) { super(props); this.state = { period: 15, from: null, to: null, } } componentDidMount() { const fn = () => { if (this.state.period !== null) { this.props.setDateRangeByPeriod(this.state.period) } } this.timerID = setInterval(fn, 60000) } componentWillUnmount() { clearInterval(this.timerID) } handleDayClick(e, day) { const range = DateUtils.addDayToRange(day, this.state) if (range.from === null && range.to === null) { range.from = new Date(day) range.to = new Date(day) } if (range.from && range.to === null) range.to = new Date(range.from) if (range.from) range.from = moment(range.from).startOf('day').toDate() if (range.to) range.to = moment(range.to).endOf('day').toDate() this.props.setDateRange(range) this.setState({ period: null, ...range }) } handlePeriodClick(period) { this.setState({ period }); this.props.setDateRangeByPeriod(period) this.setState({ from: null, to: null }); } render() { const modifiers = { selected: day => DateUtils.isDayInRange(day, this.state) } return ( <div className="DatePickerContainer"> <DayPicker ref="daypicker" localeUtils={ LocaleUtils } locale="ru" numberOfMonths={ 2 } modifiers={ modifiers } onDayClick={ this.handleDayClick.bind(this) } /> <div className="DatePickerContainer-periods"> <span className={classnames({'dpc-period--active': this.state.period === 15})} onClick={() => this.handlePeriodClick(15)}>15 минут</span> <span className={classnames({'dpc-period--active': this.state.period === 60})} onClick={() => this.handlePeriodClick(60)}>60 минут</span> <span className={classnames({'dpc-period--active': this.state.period === 24*60})} onClick={() => this.handlePeriodClick(24*60)}>24 часа</span> </div> </div> ); } } export default connect(mapStateToProps, mapDispatchToProps)(DatePickerContainer); <file_sep>/src/modules/endpoints/actions/max_results_set.js // max_results_set.js const maxResultsSet = (endpoint, payload) => { return { type: 'SET_MAX_RESULTS', endpoint, payload } } export default maxResultsSet; <file_sep>/src/widgets/TreeMenu/tree_leaf.js import React from 'react' const TreeLeaf = ({ id, title, handleChange, isChecked }) => ( <li className="tree-leaf"> <input id={id} type="checkbox" onChange={handleChange} checked={isChecked} /> <label htmlFor={id}>{title}</label> </li> ) export default TreeLeaf <file_sep>/src/containers/Titles/titles.js import './titles.css' import React, { Component, PropTypes } from 'react' import { connect } from 'react-redux' import moment from 'moment' // Widgets import Title from './title' // Actions import countersFetch from '../../modules/counters/actions/counters_fetch' import counters1Fetch from '../../modules/counters/actions/counters1_fetch' const mapStateToProps = ({ date_range }) => { return { date_range } } const mapDispatchToProps = (dispatch) => { return { fetchCounters(date_range) { const i = date_range.to - date_range.from const date_range_before = { from: moment(date_range.from).subtract(i, 'milliseconds').toDate(), to: new Date(date_range.from) } dispatch(countersFetch(date_range)) return dispatch(counters1Fetch(date_range_before)) } } } class TitlesContainer extends Component { componentDidMount() { const { fetchCounters, date_range } = this.props return fetchCounters(date_range) } componentWillReceiveProps(nextProps) { if (JSON.stringify(nextProps.date_range) !== JSON.stringify(this.props.date_range)) { const { fetchCounters, date_range } = nextProps return fetchCounters(date_range) } } render() { return ( <div className="titles"> <div className="titles-row clearfix"> <Title group="info" /> <Title group="scan" /> <Title group="auth" /> <Title group="policy" /> <Title group="malware" /> <Title group="ddos" /> <Title group="attacks" /> <Title group="other" /> </div> </div> ) } } export default connect(mapStateToProps, mapDispatchToProps)(TitlesContainer) <file_sep>/server-prod.js var http = require('http'); var express = require('express'); var bodyParser = require('body-parser'); var app = express(); app.use(require('morgan')('short')); // Serve static files app.use(express.static(__dirname + '/dist/public/')); // Register API middleware app.use('/api/endpoints', require(__dirname + '/src/api/endpoints')); app.use('/api/counters', require(__dirname + '/src/api/counters')); app.use('/api/groups', require(__dirname + '/src/api/groups')); app.use('/api/organizations', require(__dirname + '/src/api/organizations')); app.use('/api/fired_signatures', require(__dirname + '/src/api/fired_signatures')); app.use('/api/events_histogram', require(__dirname + '/src/api/events_histogram')); app.use('/api/incidents_histogram', require(__dirname + '/src/api/incidents_histogram')); // Root route app.get("/", function(req, res) { res.sendFile(__dirname + '/dist/public/index.html'); }); if (require.main === module) { var server = http.createServer(app); server.listen(process.env.PORT || 9000, function() { console.log("Listening on %j", server.address()); }); } <file_sep>/src/containers/Organizations.js import React, { Component, PropTypes } from 'react' import { connect } from 'react-redux' import { getSensors } from '../modules/utils' import { _t } from '../constants' // Widgets import TreeMenu from '../widgets/TreeMenu/tree_menu' import TreeBranch from '../widgets/TreeMenu/tree_branch' import TreeLeaf from '../widgets/TreeMenu/tree_leaf' // Actions import organizationsFetch from '../modules/organizations/actions/organizations_fetch' import sensorToggle from '../modules/sensors/actions/sensor_toggle' import sensorsToggle from '../modules/sensors/actions/sensors_toggle' import filterSet from '../modules/endpoints/actions/filter_set' const mapStateToProps = ({ organizations, sensors }) => { return { sensors, organizations: organizations._items, relatedSensors(obj) { return getSensors(obj) }, isChecked(address) { if (Array.isArray(address)) { const address_string = address.sort().join(',') const sensors_string = _(sensors).intersection(address).sort().join(',') return sensors_string === address_string } return sensors.indexOf(address) !== -1 } } } const mapDispatchToProps = (dispatch) => { return { fetchOrganizations() { dispatch(organizationsFetch()) }, toggleSensor(sensor) { if (Array.isArray(sensor)) { return dispatch(sensorsToggle(sensor)) } dispatch(sensorToggle(sensor)) }, setFilter(sensors) { return dispatch(filterSet('events', 'sensor_ip', { $in: sensors })) } } } class Organizations extends Component { componentDidMount() { this.props.fetchOrganizations() } render() { const { sensors, organizations, toggleSensor, relatedSensors, isChecked, setFilter } = this.props return ( <TreeMenu> {organizations.map((org, orgIndex) => <TreeBranch key={orgIndex} id={`${orgIndex}-tree-branch`} title={`${org.name} (${org.branches.length})`} handleChange={(e) => toggleSensor(relatedSensors(org))} isChecked={isChecked(relatedSensors(org))} > {org.branches.map((branch, branchIndex) => <TreeBranch key={branchIndex} id={`${orgIndex}-${branchIndex}-tree-branch`} title={`${branch.name} (${branch.segments.length})`} handleChange={(e) => toggleSensor(relatedSensors(branch))} isChecked={isChecked(relatedSensors(branch))} > {branch.segments.map((segment, segmentIndex) => <TreeBranch key={segmentIndex} id={`${orgIndex}-${branchIndex}-${segmentIndex}-tree-branch`} title={`${segment.name} (${segment.sensors.length})`} handleChange={(e) => toggleSensor(relatedSensors(segment))} isChecked={isChecked(relatedSensors(segment))} > {segment.sensors.map((sensor, sensorIndex) => <TreeLeaf key={sensorIndex} id={`${orgIndex}-${branchIndex}-${segmentIndex}-${sensorIndex}-tree-leaf`} title={`${sensor.type} - ${sensor.address} / ${sensor.address}`} handleChange={(e) => toggleSensor(sensor.address)} isChecked={isChecked(sensor.address)} /> )} </TreeBranch> )} </TreeBranch> )} </TreeBranch> )} <li style={{textAlign: 'center', paddingTop: '16px'}}> <a href="javascript:void(0)" onClick={() => setFilter(sensors)}> {_t('Apply filter')} </a> </li> </TreeMenu> ) } } export default connect(mapStateToProps, mapDispatchToProps)(Organizations) <file_sep>/src/api/groups.js var Router = require('express/lib/router'); var bodyParser = require('body-parser'); var axios = require('axios'); var router = new Router(); var EVE_BACKEND_URL = `http://${process.env.EVE_BACKEND_HOST}:${process.env.EVE_BACKEND_PORT}`; router.post('/', bodyParser.json(), (req, res) => { var url = `${EVE_BACKEND_URL}/groups/group-list`; if (process.env.NODE_ENV === 'development') { console.log(url); } axios.get(url) .then(result => res.status(200).send(result.data.groups)) .catch(err => { return res.status(err.status).send({ status: err.status, statusText: err.statusText, message: err.data._error.message }); }); }); module.exports = router; <file_sep>/src/modules/endpoints/reducers/filter.js import moment from 'moment' import group from './group'; const initalState = { group: group(), } const filter = (state = initalState, action = {}) => { switch (action.type) { case 'SET_FILTER': return { ...state, [action.column]: action.filter } case 'REMOVE_FILTER': const nextState = { ...state }; delete nextState[action.column]; return nextState; case 'TOGGLE_GROUP_FILTER': return { ...state, group: group(state.group, action) } case 'REPLACE_FILTER': return { ...initalState, ...action.payload } default: return state; } }; export default filter; <file_sep>/src/modules/sensors/actions/sensor_toggle.js export default function sensorToggle(payload) { return { type: 'SENSOR_TOGGLE', payload } } <file_sep>/src/modules/sensors/reducers/sensors.js import organizations from '../../organizations/reducers/organizations' import { toggleArray, getSensors } from '../../utils' const initalState = getSensors(organizations()) export default function sensors(state = initalState, action = {}) { switch (action.type) { case 'SENSORS_SET': return [ ...state, ...action.payload ] case 'SENSOR_TOGGLE': return toggleArray(state, action.payload) case 'SENSORS_TOGGLE': // console.log(action.payload); // console.log(_(state).intersection(action.payload)); if (_(state).intersection(action.payload).length > 0) { return _(state).difference(action.payload) } else { return _(state).union(action.payload) } return state default: return state } } <file_sep>/src/modules/endpoints/reducers/group.js const initalState = { $in: [] } const toggleGroup = (groups, group) => { const nextState = groups.filter(i => i !== group); if (nextState.length < groups.length) return nextState; // remove item return [ // add item ...groups, group ] } const group = (state = initalState, action = {}) => { switch (action.type) { case 'TOGGLE_GROUP_FILTER': case 'FS_TOGGLE_GROUP': return { ...state, $in: toggleGroup(state.$in, action.group) } default: return state; } } export default group; <file_sep>/src/widgets/Tabs/tabs.js import './styles.css' import React from 'react' import classnames from 'classnames' const Tabs = ({ tabs, active_tab, setTab, children }) => ( <div className='tabs'> <div className='tabs-buttons'> {tabs.map((tab, tabIndex) => <div key={tabIndex} className={classnames(['tabs-button', {active: active_tab === tabIndex}])} onClick={() => setTab(tabIndex)} > <span>{tab}</span> </div> )} </div> <div className='tabs-body'> {children.map((child, childIndex) => <div className={classnames(['tab', {hidden: active_tab !== childIndex}])} key={childIndex} > {child} </div> )} </div> </div> ) export default Tabs <file_sep>/src/widgets/FilterForm/string_filter_form.js import React, { Component, PropTypes } from 'react' import ActionButtons from './action_buttons' import { parseFormValues, clearForm } from './utils' import { _t } from '../../constants' class StringFilterForm extends Component { constructor(props){ super(props) this.state = { lastModified: 'regex', } this.onSubmit = this.onSubmit.bind(this) this.onReset = this.onReset.bind(this) } fillForm(filter) { if (typeof filter !== 'undefined') { if (typeof filter['$regex'] !== 'undefined') { this.form.regex.value = filter['$regex'] this.setState({ lastModified: 'regex' }) } else { this.form.substring.value = filter this.setState({ lastModified: 'substring'}) } } } componentDidMount() { this.fillForm(this.props.filter) } componentWillReceiveProps(nextProps) { if(JSON.stringify(nextProps.filter) !== JSON.stringify(this.props.filter)) { this.fillForm(nextProps.filter) } } onSubmit(e) { e.preventDefault(); const values = parseFormValues(this.form, val => val.trim()) const { lastModified } = this.state; if ('regex' === lastModified && 'undefined' !== typeof values.regex && '' !== values.regex) { this.form.substring.value = '' return this.props.onSubmit({ '$regex': values.regex, '$options': 'i' }) } if ('substring' === lastModified && 'undefined' !== typeof values.substring && '' !== values.substring) { this.form.regex.value = '' return this.props.onSubmit(values.substring) } return false; } onReset() { clearForm(this.form) this.props.onReset() } render() { return ( <form ref={node => this.form = node} onSubmit={this.onSubmit} > <div className="dd-menu-item--filter"> <input type="text" name="regex" placeholder={_t("Regex")} onChange={() => this.setState({lastModified: 'regex'})} /> </div> <div className="separator"/> <div className="dd-menu-item--filter"> <input type="text" name="substring" placeholder={_t("Substring")} onChange={() => this.setState({lastModified: 'substring'})} /> </div> <ActionButtons onSubmit={this.onSubmit} onReset={this.onReset} /> </form> ) } } export default StringFilterForm; <file_sep>/src/containers/Tables/FiredSignatures.js import React, { Component } from 'react'; import { connect } from 'react-redux'; import classnames from 'classnames'; import { InitalConstants } from '../../constants'; // Widgets import Table from '../../widgets/Table/table'; // Actions import attributeToggle from '../../modules/attributes/actions/attribute_toggle'; import attributePlaceAfter from '../../modules/attributes/actions/attribute_place_after'; import attributeSetNewSize from '../../modules/attributes/actions/attribute_set_new_size'; import fsSetMaxResults from '../../modules/fired_signatures/actions/fs_set_max_results'; import fsSetPage from '../../modules/fired_signatures/actions/fs_set_page' import fsFetchData from '../../modules/fired_signatures/actions/fs_fetch_data'; import fsSetAggregate from '../../modules/fired_signatures/actions/fs_set_aggregate'; import fsRemoveAggregate from '../../modules/fired_signatures/actions/fs_remove_aggregate'; import fsSetSort from '../../modules/fired_signatures/actions/fs_set_sort'; import fsRemoveSort from '../../modules/fired_signatures/actions/fs_remove_sort'; import filterSet from '../../modules/endpoints/actions/filter_set'; import filterRemove from '../../modules/endpoints/actions/filter_remove'; const ENDPOINT = 'fired_signatures'; const mapStateToProps = ({ date_range, fired_signatures, attributes }) => { return { prefix: 'fired_signatures', date_range, attributes: attributes.fired_signatures, columns: _(attributes.fired_signatures).select(attr => attr.visibility === true), items: fired_signatures._items, params: { aggregate: { ...fired_signatures.aggregate, $from: date_range.from, $to: date_range.to, }, max_results: fired_signatures.max_results, page: fired_signatures.page, }, isSortedAsc(column) { if (typeof fired_signatures.aggregate["$sort"] === 'undefined') return false return fired_signatures.aggregate["$sort"][column.id] === 1 }, isSortedDesc(column) { if (typeof fired_signatures.aggregate["$sort"] === 'undefined') return false return fired_signatures.aggregate["$sort"][column.id] === -1 }, isFiltered(column) { if (column.id === 'group') { return fired_signatures.aggregate.group.$in.length > 0 } return typeof fired_signatures.aggregate[column.id] !== 'undefined' }, getFilter(column) { return fired_signatures.aggregate[column.id] }, getChoices(column) { if (column.filter_type !== 'subset') return false return fired_signatures._meta.choices[column.id] }, pagination: { total: NaN, max_results: fired_signatures.max_results, page: fired_signatures.page, next: fired_signatures.page+1, prev: ((fired_signatures.page - 1) <= 1 ? 1 : (fired_signatures.page - 1)), last: NaN, } } } const mapDispatchToProps = (dispatch) => { return { handleRowClick(e, data, isSameRow) { if (isSameRow) return dispatch(filterRemove('events', 'rule')); return dispatch(filterSet('events', 'rule', data.rule)); }, handleDateRangeChange(date_range) { return dispatch(fsSetAggregate({ $from: date_range.from, $to: date_range.to })) }, handleFilterForm(column, data) { dispatch(fsSetPage(1)) return dispatch(fsSetAggregate({[column.id]: data})) }, handleResetFilterForm(column) { dispatch(fsSetPage(1)) return dispatch(fsRemoveAggregate(column.id)) }, dataFetch(params = { aggregate: { $from: InitalConstants.DATE_RANGE.from, $to: InitalConstants.DATE_RANGE.to } }) { dispatch(fsFetchData(params)); }, moveColumn(source, target) { dispatch(attributePlaceAfter(ENDPOINT, source, target)); }, resizeColumn(id, newSize) { dispatch(attributeSetNewSize(ENDPOINT, id, newSize)) }, sortAscending(column, isSortedAsc=false) { if (isSortedAsc) return dispatch(fsRemoveSort(column.id)) return dispatch(fsSetSort({[column.id]: 1})) }, sortDescending(column, isSortedDesc=false) { if (isSortedDesc) return dispatch(fsRemoveSort(column.id)) return dispatch(fsSetSort({[column.id]: -1})) }, removeSorting(column) { return dispatch(fsRemoveSort(column.id)) }, attrVisibilityToggle(e, id) { dispatch(attributeToggle(ENDPOINT, id)); }, setPage(page) { if(isNaN(page)) return false; dispatch(fsSetPage(page)) }, setMaxResults(maxResults) { dispatch(fsSetMaxResults(maxResults)); } } } export default connect(mapStateToProps, mapDispatchToProps)(Table); <file_sep>/src/modules/endpoints/reducers/params.js import filter from './filter'; import sort from './sort'; const initalState = { page: 1, max_results: 10, sort: sort(), filter: filter() } const params = (state = initalState, action = {}) => { switch (action.type) { case 'SET_PAGE': return { ...state, page: action.payload } case 'SET_MAX_RESULTS': return { ...state, max_results: action.payload } case 'SET_FILTER': case 'REMOVE_FILTER': case 'TOGGLE_GROUP_FILTER': case 'REPLACE_FILTER': return { ...state, filter: filter(state.filter, action) } case 'SORT_ASC': case 'SORT_DESC': case 'SORT_REMOVE': return { ...state, sort: sort(state.sort, action) } default: return state } } export default params <file_sep>/src/api/endpoints.js var Router = require('express/lib/router'); var bodyParser = require('body-parser'); var url = require('url'); var _ = require('underscore'); var axios = require('axios'); var router = new Router(); var EVE_BACKEND_URL = `http://${process.env.EVE_BACKEND_HOST}:${process.env.EVE_BACKEND_PORT}`; router.param('endpoint', (req, res, next, endpoint) => { req.endpoint_url = `${EVE_BACKEND_URL}/${endpoint}`; next(); }); router.post('/:endpoint', bodyParser.json(), (req, res) => { var page = req.body.page; var max_results = req.body.max_results; var sort = req.body.sort; var filter = req.body.filter; var params = { page: parseInt(page, 10), max_results: parseInt(max_results, 10) } if (undefined !== sort) { params.sort = '[' + _.pairs(sort).map(chunk => `("${chunk[0]}", ${chunk[1]})`).join(',') + ']'; } if (undefined !== filter) { if (filter.group && filter.group.$in && filter.group.$in.length === 0) { delete filter.group; } if (filter.sensor_ip && filter.sensor_ip.$in && filter.sensor_ip.$in.length === 0) { delete filter.sensor_ip; } params.where = JSON.stringify(filter); } var paramsString = _.pairs(params).map(p => `${p[0]}=${p[1]}`).join('&'); var url = `${req.endpoint_url}?${paramsString}`; if (process.env.NODE_ENV === 'development') { console.log(url); } axios.get(url) .then(result => { return res.status(200).send(result.data) }) .catch(err => { return res.status(err.status).send({ status: err.status, statusText: err.statusText, message: err.data._error.message }); }); }); module.exports = router; <file_sep>/src/modules/endpoints/actions/incident_select.js export default function incidentSelect(payload) { return { type: 'INCIDENT_SELECT', endpoint: 'incidents', payload } } <file_sep>/src/modules/fired_signatures/actions/fs_set_state.js const fs_set_state = (payload) => { return { type: 'FS_SET_STATE', payload } } export default fs_set_state; <file_sep>/src/modules/attributes/actions/attribute_place_after.js const attributePlaceAfter = (endpoint, source, target) => { return { type: 'PLACE_ATTRIBUTE_AFTER', endpoint, source, target } } export default attributePlaceAfter; <file_sep>/src/modules/endpoints/actions/filter_set.js const filterSet = (endpoint, column, filter = {}) => { return { type: 'SET_FILTER', endpoint, column, filter } } export default filterSet; <file_sep>/src/containers/App.js import React from 'react' import { createStore, applyMiddleware } from 'redux' import { Provider } from 'react-redux' import thunk from 'redux-thunk' import { _t } from '../constants' // Widgets import Collapsible from '../widgets/Collapsible' import Header from '../widgets/Header/header' import TopScrollButton from '../widgets/TopScrollButton' // Containers import AppStatus from './AppStatus' import AppFilters from './AppFilters' import Titles from './Titles' import PeriodToText from './PeriodToText' import Incident from './Incident' import TabsSelector from './TabsSelector' // Endpoint Table Containers import FiredSignatures from './Tables/FiredSignatures' import EventsChart from './EventsChart' import IncidentsChart from './IncidentsChart' import Events from './Tables/Events' import Webproxy from './Tables/Webproxy' import Firewall from './Tables/Firewall' import Incidents from './Tables/Incidents' import reducers from '../modules/reducers' const store = applyMiddleware(thunk)(createStore)(reducers) const AppContainer = () => { return ( <Provider store={store}> <div id='app'> <AppStatus /> <Header /> <AppFilters/> <div className="container"> <PeriodToText /> <Collapsible title={_t("Event classes")} collapsed={false}> <Titles /> </Collapsible> <Collapsible title={_t("Events chart")} collapsed={false}> <EventsChart /> </Collapsible> <Collapsible title={_t("Incidents chart")} collapsed={false}> <IncidentsChart /> </Collapsible> <TabsSelector tabs={[_t('fired_signatures'), _t('incidents')]}> <FiredSignatures /> <Incidents /> <Incident /> </TabsSelector> <Events /> <Webproxy /> <Firewall /> <TopScrollButton /> </div> </div> </Provider> ) } export default AppContainer; <file_sep>/webpack.production.config.js 'use strict'; var path = require('path'); var webpack = require('webpack'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var StatsPlugin = require('stats-webpack-plugin'); module.exports = { context: __dirname, entry: [ __dirname + '/src/main.js' ], target: 'web', output: { path: __dirname + '/dist/public/', filename: '[name]-[hash].min.js', }, module: { loaders: [ { test: /\.css$/, loader: ExtractTextPlugin.extract('style', 'css!postcss') // loader: ExtractTextPlugin.extract('style', 'css?modules&localIdentName=[name]---[local]---[hash:base64:5]!postcss') }, { test: /\.jsx?$/, exclude: /(node_modules|bower_components)/, loader: 'babel', // 'babel-loader' is also a legal name to reference query: { babelrc: false, presets: ["react", "es2015", "stage-0"], // plugins: ["transform-runtime"] } }, { test: /\.json$/, loader: 'json', }, { test: /\.(png|jpg|jpeg|gif|svg|woff2?)$/, loader: 'url-loader', query: { name: '[path][name].[ext]', limit: 10000, }, }, { test: /\.(eot|ttf|wav|mp3)$/, loader: 'file-loader', query: { name: '[path][name].[ext]', }, }, ] }, postcss: function () { return [require('autoprefixer'), require('precss')]; }, plugins: [ new webpack.optimize.OccurenceOrderPlugin(), new ExtractTextPlugin('[name]-[hash].min.css'), new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false, screw_ie8: true } }), new StatsPlugin('webpack.stats.json', { source: false, modules: false }), new HtmlWebpackPlugin({ template: 'src/index.tpl.html', inject: 'body', filename: 'index.html' }), new webpack.ProvidePlugin({ _: "underscore", }), new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': '"production"' } }) ], devtool: '#source-map', }; <file_sep>/src/modules/date_range/actions/date_range_set.js export default function dateRangeSet(payload) { return { type: 'DATE_RANGE_SET', payload } } <file_sep>/src/containers/PeriodToText.js import React from 'react' import { connect } from 'react-redux' import moment from 'moment' import { dateTimeFormat } from '../constants' moment.locale('ru') // const toText = (date_range) => { // if (period > 0) return 'за ' + moment().subtract(period, 'milliseconds').fromNow(true); // const dateToString = (d) => moment(d).format('YYYY-MM-DD HH:mm:ss'); // return `с ${dateToString(date_range.from)} по ${dateToString(date_range.to)}`; // } const mapStateToProps = ({ date_range }) => { return { date_range } } const PeriodToText = ({ date_range }) => ( <div className="period-to-text"> с {moment(date_range.from).format(dateTimeFormat)} по {moment(date_range.to).format(dateTimeFormat)} </div> ) export default connect(mapStateToProps)(PeriodToText); <file_sep>/src/containers/EventsChart.js import 'chartist/dist/chartist.min.css' import React, { Component, PropTypes } from 'react' import { connect } from 'react-redux' import moment from 'moment' import Chartist from 'chartist' import { dateTimeFormat } from '../constants' // Actions import eventsChartFetchData from '../modules/charts/actions/events_chart_fetch_data' import eventsChartSetData from '../modules/charts/actions/events_chart_set_data' const calcStep = (params) => { const i = params.to - params.from if (i <= 60*61*1000 ) return 1 return 30 // const k = 100 // return Math.ceil(i / 1000 / 60 / k) } const makeTimeLine = (date_from, date_to, step=30) => { if (date_to > new Date) date_to = new Date const timelineValuesQty = Math.ceil((date_to - date_from) / 1000 / 60 / step) const _res = [] let slider = date_from let i = 0 const r = 15 // Visible values on the timeline while(slider <= date_to) { if (i % (Math.ceil(timelineValuesQty / r)) === 0) { _res.push(moment(slider).format(dateTimeFormat)) } else { _res.push('') } slider = moment(slider).add(step, 'minutes').toDate() i++ } return _res } const mapStateToProps = ({ filters, groups, date_range, eventsChart }) => { return { data: eventsChart.data, params: { groups, sensor_ips: filters.sensors, ...date_range } } } const mapDispatchToProps = (dispatch) => { return { fetchEventsChartData(params) { dispatch(eventsChartFetchData(params)) }, setEventsChartData(data) { dispatch(eventsChartSetData(data)) } } } class EventsChart extends Component { constructor(props) { super(props); this.state = { }; } componentWillReceiveProps(nextProps) { if (JSON.stringify(nextProps.params) !== JSON.stringify(this.props.params)) { if (this.canPlot(nextProps.params)) { this.setStep(calcStep(nextProps.params)) this.props.fetchEventsChartData({ ...nextProps.params, // to: moment(nextProps.params.to).add(1, 'minutes').toDate(), step: this.getStep() }) } else { this.props.setEventsChartData() } } if (JSON.stringify(nextProps.data) !== JSON.stringify(this.props.data)) { const timeLine = makeTimeLine(nextProps.params.from, nextProps.params.to, this.getStep()) this.chart.update({ labels: timeLine, series: [nextProps.data], }) } } canPlot(params) { return params.to - params.from < 1000*60*60*24*7 // week } setStep(step) { this.step = step } getStep() { return this.step } componentDidMount() { this.chart = new Chartist.Line('#events-chart', { labels: [], series: [[]], }, { fullWidth: true, chartPadding: { right: 90 } }); this.setStep(calcStep(this.props.params)) this.props.fetchEventsChartData({...this.props.params, step: this.getStep()}) } render() { return ( <div id="events-chart"></div> ) } } export default connect(mapStateToProps, mapDispatchToProps)(EventsChart); <file_sep>/src/modules/endpoints/actions/set_total_results.js const setTotalResults = (totalResults = 0) => { return { type: 'SET_TOTAL_RESULTS', totalResults } } export default setTotalResults;<file_sep>/src/constants.js 'use strict' import moment from 'moment'; const period = 15 * 60 * 1000 // 15 min export const dateTimeFormat = 'YYYY-MM-DD HH:mm:ss' export const InitalConstants = { PERIOD: period, DATE_RANGE: { from: moment().subtract(period, 'milliseconds').startOf('minute').toDate(), to: moment().toDate(), } } export const ItemTypes = { COLUMN_TITLE: 'column_title', COLUMN_RESIZER: 'column_resizer' }; export const _t = (term) => { const dict = { title: 'Наименование', attribute_incident: 'Признаки инцидента', threats: 'Угрозы ИБ', type_class_descr: 'Класс инцидента', date_fact: 'Время', affected_actives: 'Пораженные активы', recommendations: 'Рекомендации', sensor: 'Сенсор', src_addrs: 'IP источника', src_mac: 'MAC источника', dst_addrs: 'IP получателя', dst_mac: 'MAC получателя', event_id: 'ID события', pcap_link: 'Pcap', description: 'Описание', correlated_event: 'Коррелированные событие', status: 'Статус', sig_text: 'Правило', class: 'Класс', methods: 'Методы', symptoms: 'Симптомы', main_events: 'Главные события', correlated_events: 'Связанные события', message: 'Сообщение', dst_address: 'IP получателя', src_address: 'IP источника', info: "Информация", scan: "Сканирования", auth: "Подбор паролей", policy: "Политики ИБ", malware: "Трояны и вирусы", ddos: "DDoS", attacks: "Атаки", other: "Другие", attribute_incident: 'Признаки инцидента', threats: 'Угрозы ИБ', type_class_descr: 'Класс инцидента', date_fact: 'Время', affected_actives: 'Пораженные активы', recommendations: 'Рекомендации', sensor: 'Сенсор', src_addrs: 'IP источника', src_mac: 'MAC источника', dst_addrs: 'IP получателя', dst_mac: 'MAC получателя', event_id: 'ID события', pcap_link: 'Pcap', description: 'Описание', correlated_event: 'Коррелированные событие', status: 'Статус', sig_text: 'Правило', class: 'Класс', methods: 'Методы', symptoms: 'Симптомы', main_events: 'Главные события', correlated_events: 'Связанные события', message: 'Сообщение', dst_address: 'IP получателя', src_address: 'IP источника', processingtime: 'Время обработки (миллисекунды)', bytesrecvd: 'Принято (байт)', bytessent: 'Отправлено (байт)', protocol: 'Протокол', transport: 'Транспорт', operation: 'Операция', uri: 'URI', ClientUserName: 'Имя пользователя', FwcAppPath: 'Путь к приложению', mimetype: 'Тип данных', resultcode: 'Ответ сервера', SrcPort: 'Порт пользователя', logTime: 'Дата', SourceIP: 'IP пользователя', servername: 'Имя proxy', SourcePort: 'Порт пользователя', DestinationIP: 'IP получателя', DestinationPort: 'Порт получателя', OriginalClientIP: 'IP пользователя (Оригинальный)', Action: 'Действие', ApplicationProtocol: 'Протокол приложения', connectiontime: 'Время соединения (миллисекунды)', DestinationName: 'Имя получателя', ClientAgent: 'Агент пользователя', sessionid: 'ID сессии', NATAddress: 'NAT Адрес', created: 'Дата', summary: 'Описание', priority: 'Критичность', count: 'Количество', homenet_address: '', rule: 'Код правила', direction: 'Направление', group: 'Класс', _id: 'ID', _created: 'Создано', _updated: 'Обновлено', logdate: 'Дата', sensor_ip: 'IP сенсора', dst: 'IP получателя', dpt: 'Порт получателя', pcap: 'Пакет', proto: 'Протокол', spt: 'Порт источника', src: 'IP источника', ClientIP: 'IP пользователя', DestHostIP: 'IP получателя', referredserver: 'Перенаправлен с сервера', DestHost: 'Хост получателя', DestHostPort: 'Порт получателя', Filter: 'Фильтр', Filters: 'Фильтры', "Sort Ascending": "Сортировать по возрастанию", "Sort Descending": "Сортировать по убыванию", Columns: 'Колонки', mode: "Метод", homenet_address: "IP-адрес", "No results found": "0 результатов найдено", "Rows per page": "Строк на страницу", "of": "из", "Reset": "Сброс", "Ok": "Ок", "Regex": "Регулярное выражение", "Substring": "Подстрока", after: "после", before: "до", "on": "в", external_id: 'Внешний ID', ip: 'IP', Fetching: 'Загрузка', level: 'Рейтинг', delivery_status: "Статус доставки", incidents: 'Инциденты', fired_signatures: 'Группы событий', events: 'События', webproxy: 'Proxy', firewall: 'Firewall', "Apply filter": 'Применить фильтр', "Sort": 'Сортировать', "Collapse/Expand": 'Свернуть/Развернуть', "Select columns": 'Выбрать колонки', "Event classes": 'Классы событий', "Copy": "Копировать", "Go to page": "На страницу", "page": "cтраница", "Go to first page": "На первую страницу", 1: 'Высокая', 2: 'Средняя', 3: 'Низкая', 'TCP': 'TCP', 'UDP': 'UDP', 'ICMP': 'ICMP', 'Events chart': 'Диаграмма событий', 'Incidents chart': 'Диаграмма инцидентов', impact: 'Воздействие', 'detecting date': 'Дата фиксации', 'impact methods': 'Методы воздействия', 'additional information': 'Дополнительная информация', sensor_name: 'Им<NAME>', Incident: 'Инцидент', 'Scroll to top': 'На верх', 'Show filters': 'Показать фильтры', 'Apply filters': 'Применить фильтры' } if (typeof dict[term] === 'undefined') console.log('term not found', term) return dict[term] || term; } export const _t_for_tables = (term) => { const dict = { 'dst': 'Получатель', 'src': "Источник", 1: 'Высокая', 2: 'Средняя', 3: 'Низкая', 'dst(h)': 'Получатель (h)', 'src(h)': 'Источник (h)', } if (typeof dict[term] === 'undefined') { return _t(term) } return dict[term] || term; } export const InitalAttributes = { EVENT_ATTRIBUTES: [ // {id: '_id', name: 'id', type: 'mongo_id', filter_type: 'string', width: '70px', visibility: false }, // {id: '_created', name: 'created', type: 'datetime', filter_type: 'datetime', width: '130px', visibility: false }, // {id: '_updated', name: 'updated', type: 'datetime', filter_type: 'datetime', width: '130px', visibility: false }, {id: 'logdate', name: 'logdate', type: 'datetime', filter_type: 'datetime', width: '130px', visibility: true }, {id: 'rule', name: 'rule', type: 'string', filter_type: 'string', width: '100px', visibility: false }, {id: 'sensor_ip', name: 'sensor_ip', type: 'string', filter_type: 'subset', width: '100px', visibility: true }, {id: 'dst', name: 'dst', type: 'string', filter_type: 'string', width: '100px', visibility: true }, {id: 'dpt', name: 'dpt', type: 'number', filter_type: 'number', width: '40px', visibility: true }, {id: 'event_id', name: 'event_id', type: 'string', filter_type: 'string', width: '100px', visibility: true }, {id: 'pcap', name: 'pcap', type: 'link', filter_type: 'string', visibility: true }, {id: 'priority', name: 'priority', type: 'string', filter_type: 'subset', width: '50px', visibility: true }, {id: 'proto', name: 'proto', type: 'string', filter_type: 'subset', width: '50px', visibility: true }, {id: 'sig_text', name: 'sig_text', type: 'string', filter_type: 'string', visibility: true }, {id: 'spt', name: 'spt', type: 'number', filter_type: 'number', width: '40px', visibility: true }, {id: 'src', name: 'src', type: 'string', filter_type: 'string', width: '100px', visibility: true }, {id: 'group', name: 'group', type: 'string', filter_type: 'subset', width: '136px', visibility: true }, ], INCIDENT_ATTRIBUTES: [ // { id: '_id', name: 'id', type: 'mongo_id', filter_type: 'string', width: '70px', visibility: false }, // { id: '_created', name: 'created', type: 'datetime', filter_type: 'datetime', width: '130px', visibility: false }, // { id: '_updated', name: 'updated', type: 'datetime', filter_type: 'datetime', width: '130px', visibility: false }, { id: 'created', name: 'created', type: 'datetime', filter_type: 'datetime', width: '130px', visibility: true }, { id: 'level', name: 'level', type: 'number', filter_type: 'number', width: '70px', visibility: true }, { id: 'affected_actives', type: 'array', filter_type: 'string', width: '200px', visibility: true }, { id: 'mode', name: 'mode', type: 'string', filter_type: 'string', width: '100px', visibility: true }, { id: 'title', name: 'title', type: 'string', filter_type: 'string', width: '280px', visibility: true }, { id: 'summary', name: 'summary', type: 'string', filter_type: 'string', visibility: true }, // { id: 'date_fact', name: 'date', type: 'datetime', filter_type: 'datetime', width: 0, visibility: true }, // { id: 'event_id', name: 'event id', type: 'number', filter_type: 'number', width: 0, visibility: true }, // { id: 'sensor', name: 'sensor', type: 'string', filter_type: 'string', width: 0, visibility: true }, // { id: 'pcap_link', name: 'pcap link', type: 'link', filter_type: 'string', width: 0, visibility: true }, // { id: '_etag', name: 'etag', type: 'string', filter_type: 'string', width: 0, visibility: true }, ], FIRED_SIGNATURES_ATTRIBUTES: [ { id: 'priority', name: 'priority', type: 'string', filter_type: 'subset', visibility: true }, { id: 'sig_text', name: 'sig_text', type: 'string', filter_type: 'string', visibility: true }, { id: 'count', name: 'count', type: 'number', filter_type: 'number', visibility: true }, { id: 'homenet_address', name: 'homenet_address', type: 'string', filter_type: 'string', visibility: true }, { id: 'rule', name: 'rule', type: 'string', filter_type: 'string', visibility: true }, { id: 'direction', name: 'direction', type: 'string', filter_type: 'string', visibility: true }, { id: 'group', name: 'group', type: 'string', filter_type: 'subset', visibility: true }, ], FIREWALL_ATTRIBUTES: [ // { id: '_id', type: 'mongo_id', filter_type: 'string', visibility: false }, { id: "logTime", type: "datetime", filter_type: 'datetime', visibility: true }, { id: "servername", type: "string", filter_type: 'string', visibility: true }, { id: "protocol", type: "string", filter_type: 'string', visibility: true }, { id: "SourceIP", type: "string", filter_type: 'string', visibility: true }, { id: "SourcePort", type: "number", filter_type: 'number', visibility: true }, { id: "DestinationIP", type: "string", filter_type: 'string', visibility: true }, { id: "DestinationPort", type: "number", filter_type: 'number', visibility: true }, { id: "OriginalClientIP", type: "string", filter_type: 'string', visibility: true }, { id: "Action", type: "number", filter_type: 'number', visibility: true }, { id: "resultcode", type: "number", filter_type: 'number', visibility: true }, { id: "ApplicationProtocol", type: "string", filter_type: 'string', visibility: true }, { id: "bytessent", type: "number", filter_type: 'number', visibility: true }, { id: "bytesrecvd", type: "number", filter_type: 'number', visibility: true }, { id: "connectiontime", type: "number", filter_type: 'number', visibility: true }, { id: "DestinationName", type: "string", filter_type: 'string', visibility: true }, { id: "ClientUserName", type: "string", filter_type: 'string', visibility: true }, { id: "ClientAgent", type: "string", filter_type: 'string', visibility: true }, { id: "sessionid", type: "number", filter_type: 'number', visibility: true }, { id: "NATAddress", type: "string", filter_type: 'string', visibility: true }, { id: "FwcAppPath", type: "string", filter_type: 'string', visibility: true }, ], WEBPROXY_ATTRIBUTES: [ // { id: '_id', type: 'mongo_id', filter_type: 'string', visibility: false }, { id: 'logTime', type: 'datetime', filter_type: 'datetime', visibility: true }, { id: 'ClientIP', type: 'string', filter_type: 'string', visibility: true }, { id: 'ClientUserName', type: 'string', filter_type: 'string', visibility: true }, { id: 'ClientAgent', type: 'string', filter_type: 'string', visibility: true }, { id: 'servername', type: 'string', filter_type: 'string', visibility: true }, { id: 'referredserver', type: 'string', filter_type: 'string', visibility: true }, { id: 'DestHost', type: 'string', filter_type: 'string', visibility: true }, { id: 'DestHostIP', type: 'string', filter_type: 'string', visibility: true }, { id: 'DestHostPort', type: 'number', filter_type: 'number', visibility: true }, { id: 'processingtime', type: 'number', filter_type: 'number', visibility: true }, { id: 'bytesrecvd', type: 'number', filter_type: 'number', visibility: true }, { id: 'bytessent', type: 'number', filter_type: 'number', visibility: true }, { id: 'protocol', type: 'string', filter_type: 'string', visibility: true }, { id: 'transport', type: 'string', filter_type: 'string', visibility: true }, { id: 'operation', type: 'string', filter_type: 'string', visibility: true }, { id: 'uri', type: 'string', filter_type: 'string', visibility: true }, { id: 'mimetype', type: 'string', filter_type: 'string', visibility: true }, { id: 'resultcode', type: 'number', filter_type: 'number', visibility: true }, { id: 'SrcPort', type: 'number', filter_type: 'number', visibility: true }, ] }; <file_sep>/src/api/fired_signatures.js var Router = require('express/lib/router'); var bodyParser = require('body-parser'); var url = require('url'); var _ = require('underscore'); var axios = require('axios'); var moment = require('moment'); var router = new Router(); var EVE_BACKEND_URL = `http://${process.env.EVE_BACKEND_HOST}:${process.env.EVE_BACKEND_PORT}`; router.post('/', bodyParser.json(), (req, res) => { var page = req.body.page || 1; var max_results = req.body.max_results || 25; var aggregate = req.body.aggregate; var params = { page: parseInt(page, 10), max_results: parseInt(max_results, 10), } if (undefined !== aggregate) { if (aggregate.group && aggregate.group.$in && aggregate.group.$in.length === 0) { delete aggregate.group; } params.aggregate = JSON.stringify(aggregate); } var paramsString = _.pairs(params).map(p => `${p[0]}=${p[1]}`).join('&'); var url = `${EVE_BACKEND_URL}/fired_signatures?${paramsString}`; if (process.env.NODE_ENV === 'development') { console.log(url); } axios.get(url) .then(result => res.status(200).send(result.data)) .catch(err => { return res.status(err.status).send({ status: err.status, statusText: err.statusText, message: err.data._error.message }); }); }); module.exports = router; <file_sep>/src/widgets/FilterForm/action_buttons.js import React from 'react' import { _t } from '../../constants' const ActionButtons = ({ onSubmit, onReset }) => ( <div className="action-buttons"> <button className="hidden">submit</button> <div className="dd-menu-item text-right"> <a className="action-link" href="javascript:void(0)" onClick={onReset}>{_t('Reset')}</a> <a className="action-link" href="javascript:void(0)" onClick={onSubmit}>{_t('Ok')}</a> </div> </div> ) export default ActionButtons <file_sep>/src/modules/endpoints/actions/page_set.js const pageSet = (endpoint, payload = 1) => { return { type: 'SET_PAGE', endpoint, payload } } export default pageSet; <file_sep>/src/widgets/AppFilters/organizations_filter.js import React from 'react' // Widgets import TreeMenu from '../TreeMenu/tree_menu' import TreeBranch from '../TreeMenu/tree_branch' import TreeLeaf from '../TreeMenu/tree_leaf' const OrganizationsFilter = ({ sensors, organizations, toggleSensor, relatedSensors, isChecked }) => ( <TreeMenu> {organizations.map((org, orgIndex) => <TreeBranch key={orgIndex} id={`${orgIndex}-tree-branch`} title={`${org.name} (${org.branches.length})`} handleChange={(e) => toggleSensor(relatedSensors(org))} isChecked={isChecked(relatedSensors(org))} > {org.branches.map((branch, branchIndex) => <TreeBranch key={branchIndex} id={`${orgIndex}-${branchIndex}-tree-branch`} title={`${branch.name} (${branch.segments.length})`} handleChange={(e) => toggleSensor(relatedSensors(branch))} isChecked={isChecked(relatedSensors(branch))} > {branch.segments.map((segment, segmentIndex) => <TreeBranch key={segmentIndex} id={`${orgIndex}-${branchIndex}-${segmentIndex}-tree-branch`} title={`${segment.name} (${segment.sensors.length})`} handleChange={(e) => toggleSensor(relatedSensors(segment))} isChecked={isChecked(relatedSensors(segment))} > {segment.sensors.map((sensor, sensorIndex) => <TreeLeaf key={sensorIndex} id={`${orgIndex}-${branchIndex}-${segmentIndex}-${sensorIndex}-tree-leaf`} title={`${sensor.type} - ${sensor.address} / ${sensor.address}`} handleChange={(e) => toggleSensor(sensor.address)} isChecked={isChecked(sensor.address)} /> )} </TreeBranch> )} </TreeBranch> )} </TreeBranch> )} </TreeMenu> ) export default OrganizationsFilter <file_sep>/src/widgets/Table/table_head_row_drop_target.js import React, { Component, PropTypes } from 'react' import { findDOMNode } from 'react-dom'; import { DropTarget } from 'react-dnd'; import { ItemTypes } from '../../constants'; import classnames from 'classnames' const columnResizerTarget = { hover(props, monitor, component) { const resizer = monitor.getItem() const positionX = monitor.getClientOffset().x //; console.log(positionX); // current x position const minPositionX = resizer.headColumnRect.x + 10 const newSize = (positionX > minPositionX ? positionX : minPositionX) - resizer.headColumnRect.x console.log(newSize); // console.log(component); // console.log('getBoundingClientRect', findDOMNode(component).getBoundingClientRect()) props.resizeColumn(resizer.id, newSize); }, drop(props, monitor, component) { const newSize = monitor.getItem().newSize; const id = props.id; // console.log(props); // console.log(monitor.getItem()); // console.log(monitor.didDrop()); // console.log(monitor.getDropResult()); //props.resizeColumn(id, newSize); } }; function collect(connect, monitor) { return { connectDropTarget: connect.dropTarget(), isOver: monitor.isOver() }; } class TableHeadRowDropTarget extends Component { static propTypes = { connectDropTarget: PropTypes.func.isRequired, isOver: PropTypes.bool.isRequired, } render() { const { isOver } = this.props return this.props.connectDropTarget( <tr className={classnames(["column-row-drop-target", { isOver }])}> {this.props.children} </tr> ) } } export default DropTarget(ItemTypes.COLUMN_RESIZER, columnResizerTarget, collect)(TableHeadRowDropTarget) <file_sep>/src/modules/counters/actions/counters1_fetch.js import axios from 'axios' import counters1Receive from './counters1_receive' import appStateSetError from '../../app_state/actions/app_state_set_error' const counters1Fetch = (date_range) => { return (dispatch) => { axios.post('/api/counters', date_range) .then(response => { const { data } = response dispatch(counters1Receive({ isFetching: false, ...data })) }) .catch(err => { dispatch(counters1Receive({ isFetching: false, _items: [] })) dispatch(appStateSetError(err)); }); } } export default counters1Fetch; <file_sep>/src/widgets/AppFilters/app_filters.js import './filters.css'; import React, { Component } from 'react'; import classnames from 'classnames'; import { _t } from '../../constants'; import moment from 'moment' import { toggleArray } from '../../modules/utils' // widgets import DateTimePeriodFilter from './date_time_period_filter' import OrganizationsFilter from './organizations_filter' class AppFilters extends Component { constructor(props) { super(props) this.state = { period: 15, from: null, to: null, scrolled: false, collapsed: true } this.applyFilters = this.applyFilters.bind(this) this.toggleCollapse = this.toggleCollapse.bind(this) this.handleScroll = this.handleScroll.bind(this) } componentDidMount() { this.props.fetchOrganizations() window.addEventListener('scroll', this.handleScroll) this.startLiveUpdate(this.state.period) } componentWillUnmount() { window.removeEventListener('scroll', this.handleScroll) clearInterval(this.timerID) } startLiveUpdate(period) { clearInterval(this.timerID) if (period === null) return false const fn = () => { this.props.setDateRangeByPeriod(period) } this.timerID = setInterval(fn, 60000) this.props.setDateRangeByPeriod(period) } stopLiveUpdate() { clearInterval(this.timerID) } toggleCollapse() { this.setState({ collapsed: !this.state.collapsed }); } handleScroll(e) { // this.setState({ scrolled: (window.pageYOffset >= 88) }) } applyFilters() { this.props.setSensors(this.props.sensors) this.props.setFilters({ sensors: this.props.sensors }) this.startLiveUpdate(this.state.period) if (this.state.period === null) { this.props.setDateRange({ from: this.state.from, to: this.state.to }) } this.toggleCollapse() } render() { return ( <div className={classnames([ "filters", { "filters--fixed": this.state.scrolled }, { 'filters--collapsed': this.state.collapsed }, ])}> <div className='filters-body clearfix'> <div className="filter-items-row"> <div className="filter-item"> <OrganizationsFilter sensors={this.props.sensors} organizations={this.props.organizations} toggleSensor={this.props.toggleSensor} relatedSensors={this.props.relatedSensors} isChecked={this.props.isChecked} /> </div> <div className="filter-item"> <DateTimePeriodFilter period={this.state.period} from={this.state.from} to={this.state.to} setPeriod={p => this.setState({ from: null, to: null, period: p })} setFrom={f => this.setState({ from: f, period: null })} setTo={t => this.setState({ to: t, period: null })} /> </div> </div> </div> <div className="filters-control"> <a href="javascript:void(0)" className={classnames({ hidden: this.state.collapsed })} onClick={this.applyFilters} > {_t('Apply filters')}{' '} <i className="material-icons rotate-90">chevron_left</i> </a> <a href="javascript:void(0)" className={classnames({ hidden: !this.state.collapsed })} onClick={this.toggleCollapse} > {_t('Show filters')}{' '} <i className="material-icons rotate-90">chevron_right</i> </a> </div> </div> ) } } export default AppFilters <file_sep>/src/modules/date_range/actions/date_range_set_by_period.js export default function dateRangeSetByPeriod(payload) { return { type: 'DATE_RANGE_SET_BY_PERIOD', payload } } <file_sep>/src/widgets/AppFilters/date_time_period_filter.js import React, { Component } from "react" import moment from 'moment' // Widgets import DateTimePicker from '../DateTimePicker' import Button from '../Button' export default class DateTimePeriodFilter extends Component { constructor(props) { super(props) this.state = { fromPickerVisibility: false, toPickerVisibility: false, } this.handleChangeFromPickerVisibility = this.handleChangeFromPickerVisibility.bind(this) this.handleChangeToPickerVisibility = this.handleChangeToPickerVisibility.bind(this) this.closeAllPickers = this.closeAllPickers.bind(this) } componentDidMount() { window.addEventListener('click', this.closeAllPickers) } componentWillUnmount() { window.removeEventListener('click', this.closeAllPickers) } handleChangeFromPickerVisibility(e) { this.setState({ fromPickerVisibility: !this.state.fromPickerVisibility, toPickerVisibility: false }) } handleChangeToPickerVisibility(e) { this.setState({ toPickerVisibility: !this.state.toPickerVisibility, fromPickerVisibility: false, }) } closeAllPickers() { this.setState({ fromPickerVisibility: false, toPickerVisibility: false, }) } render() { const { period, from, to, setPeriod, setFrom, setTo } = this.props const { fromPickerVisibility, toPickerVisibility } = this.state const { handleChangeFromPickerVisibility, handleChangeToPickerVisibility } = this return( <div className="date-time-period-filter"> <div>Выберите интервал</div> <div className="sep">с</div> <DateTimePicker date={from} handleChange={setFrom} visibility={fromPickerVisibility} handleChangeVisibility={handleChangeFromPickerVisibility} /> <div className="sep">по</div> <DateTimePicker date={to} handleChange={setTo} visibility={toPickerVisibility} handleChangeVisibility={handleChangeToPickerVisibility} /> <div className="sep">или за период</div> <div> <Button onClick={(e) => { setTo(new Date) setFrom(moment().subtract(15, 'minutes').toDate()) }}> 15 м </Button>{' '} <Button onClick={(e) => { setTo(new Date) setFrom(moment().subtract(60, 'minutes').toDate()) }}> 60 м </Button>{' '} <Button onClick={(e) => { setTo(new Date) setFrom(moment().subtract(24, 'hours').toDate()) }}> 24 ч </Button> </div> <div className="sep">или за период (автообновление)</div> <div> <Button isActive={period === 15} onClick={(e) => setPeriod(15)}>15 м <i className="material-icons">update</i></Button>{' '} <Button isActive={period === 60} onClick={(e) => setPeriod(60)}>60 м <i className="material-icons">update</i></Button>{' '} <Button isActive={period === 60*24} onClick={(e) => setPeriod(60*24)}>24 ч <i className="material-icons">update</i></Button> </div> </div> ) } } <file_sep>/src/modules/reducers.js import { combineReducers } from 'redux' import endpoints from './endpoints/reducers/endpoints' import attributes from './attributes/reducers/attributes' import app_state from './app_state/reducers/app_state' import counters from './counters/reducers/counters' import counters1 from './counters/reducers/counters1' import groups from './groups/reducers/groups' import fired_signatures from './fired_signatures/reducers/fired_signatures' import organizations from './organizations/reducers/organizations' import sensors from './sensors/reducers/sensors' import eventsChart from './charts/reducers/events_chart' import incidentsChart from './charts/reducers/incidents_chart' import date_range from './date_range/reducers/date_range' import active_tab from './active_tab/reducers/active_tab' import filters from './filters/reducers/filters' const reducers = combineReducers({ endpoints, attributes, app_state, counters, counters1, groups, fired_signatures, organizations, sensors, eventsChart, incidentsChart, date_range, active_tab, filters }); export default reducers; <file_sep>/src/modules/endpoints/reducers/sort.js const sort = (state = {}, action = {}) => { const next_state = {...state}; switch (action.type) { case 'SORT_ASC': next_state[action.column] = 1; return next_state; case 'SORT_DESC': next_state[action.column] = -1; return next_state; case 'SORT_REMOVE': delete next_state[action.column]; return next_state; default: return state; } }; export default sort; <file_sep>/src/widgets/Table/table_body_row.js import React from 'react'; import classnames from 'classnames'; const TableBodyRow = ({ columns, row, onRowClick }) => { return ( <tr onClick={() => onRowClick(row)} className={classnames({ active: rowIndex === this.state.activeRowIndex })} > {columns.map((column, colIndex) => { if (row[column.id] === undefined || row[column.id] === null) return <td key={colIndex}></td>; return ( <Cell key={colIndex} type={column.type} width={column.width} > {row[column.id]} </Cell> ) })} </tr> ) } <file_sep>/src/modules/charts/actions/events_chart_fetch_data.js import axios from 'axios' import eventsChartSetData from './events_chart_set_data' import appStateSetError from '../../app_state/actions/app_state_set_error' const eventsChartFetchData = (params) => { return (dispatch) => { axios.post('/api/events_histogram', params) .then(response => { const { data } = response; dispatch(eventsChartSetData(data)) }) .catch(err => { dispatch(eventsChartSetData()) dispatch(appStateSetError(err)) }); } } export default eventsChartFetchData <file_sep>/src/modules/charts/actions/incidents_chart_fetch_data.js import axios from 'axios' import incidentsChartSetData from './incidents_chart_set_data' import appStateSetError from '../../app_state/actions/app_state_set_error' const incidentsChartFetchData = (params) => { return (dispatch) => { axios.post('/api/incidents_histogram', params) .then(response => { const { data } = response; dispatch(incidentsChartSetData(data)) }) .catch(err => { dispatch(incidentsChartSetData()) dispatch(appStateSetError(err)) }); } } export default incidentsChartFetchData <file_sep>/src/modules/attributes/actions/attribute_toggle.js const attributeToggle = (endpoint, id) => { // console.log(id); return { type: 'TOGGLE_VISIBILITY', endpoint, id } }; export default attributeToggle; <file_sep>/src/modules/counters/actions/counters_fetch.js import axios from 'axios' import countersReceive from './counters_receive' import appStateSetError from '../../app_state/actions/app_state_set_error' const countersFetch = (date_range) => { return (dispatch) => { axios.post('/api/counters', date_range) .then(response => { const { data } = response dispatch(countersReceive({ isFetching: false, ...data })) }) .catch(err => { dispatch(countersReceive({ isFetching: false, _items: [] })) dispatch(appStateSetError(err)); }); } } export default countersFetch; <file_sep>/src/modules/attributes/actions/attributes_set.js const attributesSet = (endpoint, payload = []) => { return { type: 'SET_ATTRIBUTES', endpoint, payload } }; export default attributesSet; <file_sep>/src/widgets/Table/ColumnMenu/column_menu.js import './dd-menu.css' import React from 'react' import classnames from 'classnames' const ColumnMenu = ({ children, isVisible }) => ( <div className={classnames(["dd-menu", {"hidden": !isVisible}])} > {children} </div> ) export default ColumnMenu <file_sep>/entrypoint.sh #!/bin/bash echo echo "Installing packages..." npm install if [ "$NODE_ENV" = "production" ] then echo echo "Building app..." npm run build echo echo "Serving app in production mode..." npm run serve else echo echo "Running app..." npm start fi <file_sep>/src/modules/endpoints/actions/filter_replace.js const filterReplace = (endpoint, payload) => { return { type: 'REPLACE_FILTER', endpoint, payload } } export default filterReplace; <file_sep>/src/widgets/Table/ColumnMenu/checkbox_item.js import React from 'react' const CheckboxItem = ({ prefix, checked, label, id, onChange }) => ( <div className="dd-menu-item dd-menu-item--highlight" > <input checked={checked} type="checkbox" id={`dd-${prefix}-item-${id}`} onChange={(e) => onChange(e, id)} /> <label htmlFor={`dd-${prefix}-item-${id}`}>{label}</label> </div> ) export default CheckboxItem <file_sep>/src/widgets/Table/table_body.js import React, { Component } from 'react'; import Cell from './cell'; import classnames from 'classnames'; import { _t } from '../../constants'; class TableBody extends Component { constructor(props) { super(props); this.state = { rowIndex: null } } componentWillReceiveProps(nextProps) { if (JSON.stringify(nextProps.data) !== JSON.stringify(this.props.data)) { this.state.rowIndex = null; } } render() { const { isFetching, columns, data, onRowClick, prefix } = this.props; let ids = [] if (prefix === 'incidents' && localStorage.hasOwnProperty('viewed_incidents_ids')) { ids = JSON.parse(localStorage.getItem('viewed_incidents_ids')) } if (isFetching) return <tbody><tr><td colSpan={columns.length}>{_t('Fetching')}...</td></tr></tbody>; if (data.length === 0) return <tbody><tr><td colSpan={columns.length}>{_t('No results found')}.</td></tr></tbody>; const rows = data.map((row, rowIndex) => { const colElems = columns.map((column, colIndex) => { if (row[column.id] === undefined || row[column.id] === null) return <td key={colIndex}></td>; return ( <Cell key={colIndex} id={column.id} type={column.type} width={column.width} > {row[column.id]} </Cell> ) }) return ( <tr key={rowIndex} onMouseDown={ e => this.coursorPositionX = e.clientX } onMouseUp={ e => { if (this.coursorPositionX !== e.clientX) { this.coursorPositionX = null return } const isSameRow = this.state.rowIndex === rowIndex; onRowClick(e, row, isSameRow) if (isSameRow) { this.setState({ rowIndex: null }) } else { this.setState({ rowIndex }) } }} className={classnames({ active: rowIndex === this.state.rowIndex, viewed: prefix === 'incidents' && ids.indexOf(row._id) !== -1 })} > {colElems} </tr> )}); return <tbody className={`tbody-endpoint-${prefix}`}>{rows}</tbody>; } } export default TableBody; <file_sep>/src/modules/fired_signatures/reducers/fired_signatures.js import group from '../../endpoints/reducers/group' const initalState = { _items: [], _meta: { choices: { direction: ["src", "dst", "both"], proto: ["TCP", "UDP", "ICMP"], priority: [1, 2, 3], group: ["info","scan","auth","policy","malware","ddos","attacks","other"] } }, page: 1, max_results: 10, aggregate: { group: group() } } const fired_signatures = (state=initalState, action) => { const nextAggr = { ...state.aggregate } switch (action.type) { case 'FS_SET_PAGE': return { ...state, page: action.payload } case 'FS_SET_AGGREGATE': return { ...state, aggregate: { ...state.aggregate, ...action.payload } } case 'FS_REMOVE_AGGREGATE': if (action.payload === 'group') { nextAggr.group = group() } else { delete nextAggr[action.payload] } return { ...state, aggregate: nextAggr } case 'FS_SET_STATE': action.payload = action.payload || initalState return { ...state, _items: action.payload._items, _meta: { ...state._meta, choices: { ...state._meta.choices, ...action.payload._meta.choices } } } case 'FS_SET_SORT': return { ...state, aggregate: { ...state.aggregate, "$sort": action.payload } } case 'FS_REMOVE_SORT': delete nextAggr["$sort"] return { ...state, aggregate: nextAggr } case 'FS_SET_MAX_RESULTS': return { ...state, max_results: action.payload } case 'FS_TOGGLE_GROUP': return { ...state, aggregate: { ...state.aggregate, group: group(state.aggregate.group, action) } } default: return state; } } export default fired_signatures; <file_sep>/src/modules/groups/actions/group_toggle.js export default function groupToggle(payload) { return { type: 'GROUP_TOGGLE', payload } } <file_sep>/src/widgets/FilterForm/datetime_filter_form.js import "react-day-picker/lib/style.css"; import React, { Component } from 'react'; import DayPicker from "react-day-picker"; import moment from 'moment'; import ActionButtons from './action_buttons' import { parseFormValues, clearForm, getRangeFilter } from './utils' import { dateTimeFormat, _t } from '../../constants' const getAfter = (m) => m.startOf('second').toJSON(); const getBefore = (m) => m.endOf('second').toJSON(); const momentFormat = (d) => moment(d).format(dateTimeFormat); const FilterItem = ({ name, onChange, onClick, onSelectDay, currentActive }) => { return ( <div className="dd-menu-item--filter"> <input type="datetime" name={name} placeholder={_t(name)} onClick={() => onClick(name)} onChange={() => onChange(name)} /> <div className="calendar-wrapper menu-shadow" style={{ display: currentActive === name ? 'block' : 'none' }} > <DayPicker onDayClick={ (e, day) => onSelectDay(name, day) } /> </div> </div> ) } class DatetimeFilterForm extends Component { constructor(props) { super(props); this.state = { lastModified: 'after', currentActive: undefined } this.onSubmit = this.onSubmit.bind(this); this.onReset = this.onReset.bind(this); this.setLastModified = this.setLastModified.bind(this); this.setInputValue = this.setInputValue.bind(this); this.onClick = this.onClick.bind(this); } fillForm(filter) { if (typeof filter !== 'undefined') { if (typeof filter['$gte'] !== 'undefined') this.form.after.value = momentFormat(new Date(filter['$gte'])) if (typeof filter['$lte'] !== 'undefined') this.form.before.value = momentFormat(new Date(filter['$lte'])) } } componentDidMount() { this.fillForm(this.props.filter) } componentWillReceiveProps(nextProps) { if(JSON.stringify(nextProps.filter) !== JSON.stringify(this.props.filter)) { this.fillForm(nextProps.filter) } } onSubmit(e) { e.preventDefault(); const { lastModified } = this.state; const values = parseFormValues(this.form, val => moment(val.trim(), dateTimeFormat)); if ('on' === lastModified && values.on.isValid()) { const after = getAfter(values.on); const before = getBefore(values.on); const filter = getRangeFilter(after, before); return this.props.onSubmit(filter); } if ('after' === lastModified || 'before' === lastModified) { const filter = getRangeFilter(getAfter(values.after), getBefore(values.before)); return this.props.onSubmit(filter); } return false; } onClick(inputName) { this.setState({ currentActive: inputName }); } setLastModified(lastModified) { this.setState({ lastModified }); this.updateForm(lastModified); } setInputValue(inputName, day) { let d = new Date(day); switch(inputName){ case 'after': d = moment(d).startOf('day'); break; case 'before': d = moment(d).endOf('day'); break; default: d = moment(d); } this.setState({ lastModified: inputName }); this.form[inputName].value = d.format(dateTimeFormat); this.updateForm(inputName); } updateForm(lastModified) { lastModified === 'on' ? this.form.after.value = this.form.before.value = '' : this.form.on.value = '' } onReset() { clearForm(this.form) this.props.onReset() } render() { const props = { onChange: this.setLastModified, onSelectDay: this.setInputValue, onClick: this.onClick, currentActive: this.state.currentActive } return ( <form ref={node => this.form = node} onSubmit={this.onSubmit} > <FilterItem name="after" {...props}/> <FilterItem name="before" {...props}/> <div className="separator"/> <FilterItem name="on" {...props}/> <button className="hidden">submit</button> <ActionButtons onSubmit={this.onSubmit} onReset={this.onReset} /> </form> ) } } export default DatetimeFilterForm; <file_sep>/src/modules/app_state/actions/app_state_set_ok.js const appSetStateOk = () => { return { type: 'SET_APP_STATE_OK' } } export default appSetStateOk;<file_sep>/src/widgets/Table/cell.js import React from 'react' import moment from 'moment' import { _t, _t_for_tables, dateTimeFormat } from '../../constants' const style = {} const Cell = ({ id, type, width, children }) => { if ('priority,direction,group'.split(',').indexOf(id) !== -1) children = _t_for_tables(children) if (type === 'datetime') children = moment(new Date(children)).format(dateTimeFormat) if (id === 'affected_actives' && Array.isArray(children)) children = children.map(a => a.ip) if (Array.isArray(children)) children = children.join(', ') return ( <td className={type} style={{ ...style, maxWidth: width }}> {(() => { switch (type) { case 'datetime': return <span title={children}>{children}</span> case 'link': return <a href={children} title={children} target="_blank"><i className="material-icons">file_download</i></a> default: return <span title={children}>{children}</span> } })()} <i className="material-icons copy-to-clipboard" title={_t("Copy")} onClick={(e) =>{ e.stopPropagation() window.prompt(_t("Ctrl+C, Enter"), children) }} >content_copy</i> </td> ) } export default Cell <file_sep>/src/modules/fired_signatures/actions/fs_set_max_results.js const fsSetMaxResults = (payload) => { return { type: 'FS_SET_MAX_RESULTS', payload } } export default fsSetMaxResults <file_sep>/src/widgets/Table/table.js import './css/table.css'; import './css/table-collapsible.css'; import './css/column-title-dnd.css'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import { findDOMNode } from 'react-dom'; import classnames from 'classnames'; import { _t } from '../../constants'; // Widgets import TableHead from './table_head'; import TableHeadRowDropTarget from './table_head_row_drop_target' import TableHeadColumn from './table_head_column'; import TableHeadColumnTitleDnD from './table_head_column_title_dnd' import TableBody from './table_body'; import Pagination from './Pagination'; import ColumnMenu from './ColumnMenu/column_menu'; import MenuItem from './ColumnMenu/menu_item'; import CheckboxItem from './ColumnMenu/checkbox_item'; import FilterForm from '../FilterForm'; class Table extends Component { constructor(props) { super(props) this.state = { collapsed: true, columnsMenuVisibility: false, openedfilterMenuId: null, column: {} } this.closeAllMenus = this.closeAllMenus.bind(this) this.toggleColumnsMenu = this.toggleColumnsMenu.bind(this) this.toggleFilterMenu = this.toggleFilterMenu.bind(this) this.toggleTable = this.toggleTable.bind(this) this.moveFilterMenuContainer = this.moveFilterMenuContainer.bind(this) } componentDidMount() { if (['webproxy', 'firewall'].indexOf(this.props.prefix) === -1) { this.props.dataFetch(this.props.params) } if (['incidents', 'fired_signatures'].indexOf(this.props.prefix) !== -1) { this.setState({ collapsed: false }) } //window.addEventListener('click', this.closeAllMenus); } componentWillReceiveProps(nextProps) { if (JSON.stringify(nextProps.params) !== JSON.stringify(this.props.params)) { return this.props.dataFetch(nextProps.params); } if (JSON.stringify(nextProps.date_range) !== JSON.stringify(this.props.date_range)) { return this.props.handleDateRangeChange(nextProps.date_range) } } componentWillUnmount() { //window.removeEventListener('click', this.closeAllMenus); } toggleColumnsMenu() { this.setState({ columnsMenuVisibility: !this.state.columnsMenuVisibility }) } toggleFilterMenu(id) { if (id === this.state.openedfilterMenuId) { return this.setState({ openedfilterMenuId: null }) } this.setState({ openedfilterMenuId: id }) } toggleTable() { this.setState({ collapsed: !this.state.collapsed }) if (!this.state.collapsed) { this.setState({ columnsMenuVisibility: false, openedfilterMenuId: null }) } } closeAllMenus() { this.setState({ columnsMenuVisibility: false, openedfilterMenuId: null }) } moveFilterMenuContainer(e) { const w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; const mostLeftX = w - 356; const positionX = e.currentTarget.getBoundingClientRect().left - 50; //console.log(positionX); // console.log(e.currentTarget.getBoundingClientRect()); const resPositionX = positionX < mostLeftX ? positionX : mostLeftX; this.filterMenuContainer.style.left = `${resPositionX}px`; } render() { const { sortAscending, isSortedAsc, sortDescending, isSortedDesc, removeSorting } = this.props; return ( <div className={classnames(["table-collapsible card", `${this.props.prefix}-table-collapsible`,{collapsed: this.state.collapsed}])}> <div className="table-bar clearfix" onClick={this.toggleTable}> <div className="table-title"> { _t(this.props.prefix) } </div> <div className={classnames([ "table-culumn-filter menu", { hidden: this.state.openedfilterMenuId === null } ])} onClick={e => e.stopPropagation()} ref={node => this.filterMenuContainer = node} > <FilterForm prefix={`${this.props.prefix}_${this.state.column.filter_type}`} filterType={this.state.column.filter_type} filter={this.props.getFilter(this.state.column)} choices={this.props.getChoices(this.state.column)} onSubmit={(data) => { this.props.handleFilterForm(this.state.column, data) this.setState({ openedfilterMenuId: null }) }} onReset={() => { this.props.handleResetFilterForm(this.state.column) this.setState({ openedfilterMenuId: null }) }} /> </div> <div className="table-menu"> <div className="table-menu-columns"> <i className={classnames(["material-icons", {hidden: this.state.collapsed}])} title={_t("Select columns")} onClick={e => { e.stopPropagation() this.toggleColumnsMenu() }} >more_vert</i> <div className={classnames(["columns-menu menu", {hidden: !this.state.columnsMenuVisibility}])} onClick={e => e.stopPropagation()} > {this.props.attributes.map((attr, attrIndex) => <CheckboxItem key={attrIndex} prefix={this.props.prefix} checked={attr.visibility} label={_t(attr.id)} id={attr.id} onChange={this.props.attrVisibilityToggle} /> )} </div> </div> <i className="table-menu-collapse material-icons" title={_t("Collapse/Expand")} >chevron_left</i> </div> </div> <div className="table-main" onScroll={() => this.setState({ openedfilterMenuId: null })} > <table className={`${this.props.prefix}-table`}> <TableHead> <TableHeadRowDropTarget resizeColumn={this.props.resizeColumn}> {this.props.columns.map((column, colIndex) => <TableHeadColumn key={colIndex} id={column.id} width={column.width || 0} > <TableHeadColumnTitleDnD id={column.id} filtered={this.props.isFiltered(column)} menuOpened={this.state.openedfilterMenuId === column.id} sortedAsc={isSortedAsc(column)} sortedDesc={isSortedDesc(column)} moveColumn={this.props.moveColumn} > <i className="material-icons filter-icon" title={_t("Apply filter")} onClick={(e) => { this.setState({ column }) this.moveFilterMenuContainer(e) this.toggleFilterMenu(column.id) }} >filter_list</i> <span className="column-title" title={_t("Sort")} onClick={() => { if (isSortedAsc(column) + isSortedDesc(column) === 0) { return sortAscending(column) } if (isSortedAsc(column)) { return sortDescending(column) } if (isSortedDesc(column)) { return removeSorting(column) } }} >{_t(column.id)}</span> <span className="html-icon sort-asc-icon">&uarr;</span> <span className="html-icon sort-desc-icon">&darr;</span> </TableHeadColumnTitleDnD> </TableHeadColumn> )} </TableHeadRowDropTarget> </TableHead> <TableBody prefix={this.props.prefix} isFetching={this.props.isFetching} columns={this.props.columns} data={this.props.items} onRowClick={this.props.handleRowClick} /> </table> </div> <div className="table-pagination"> <Pagination {...this.props.pagination} setMaxResults={this.props.setMaxResults} setPage={this.props.setPage} /> </div> <div className="incident-wrapper"></div> </div> ) } } export default Table <file_sep>/src/modules/organizations/actions/organizations_set.js export default function organizationsSet(payload) { return { type: 'SET_ORGANIZATIONS', payload } } <file_sep>/src/modules/endpoints/actions/sort_remove.js const sortRemove = (endpoint, column) => { return { type: 'SORT_REMOVE', endpoint, column } } export default sortRemove; <file_sep>/src/modules/fired_signatures/actions/fs_toggle_group.js const fsToggleGroup = (group) => { return { type: 'FS_TOGGLE_GROUP', group } } export default fsToggleGroup; <file_sep>/src/widgets/Button/button.js import './style.css' import React, { Component, PropTypes } from "react" import classnames from 'classnames' const Button = ({ isActive=false, children, onClick }) => ( <span className={classnames([ 'button', { active: isActive } ])} onClick={onClick}> {children} </span> ) export default Button <file_sep>/src/main.js // import injectTapEventPlugin from 'react-tap-event-plugin'; import styles from './public/assets/css/index.css'; import React from 'react'; import ReactDOM from 'react-dom'; import AppContainer from './containers/App.js'; // injectTapEventPlugin(); ReactDOM.render( <AppContainer />, document.getElementById('root') ); <file_sep>/src/containers/Tables/Incidents.js import React, { Component } from 'react' import ReactDOM from 'react-dom' import { connect } from 'react-redux' import classnames from 'classnames' import moment from 'moment' import { InitalConstants } from '../../constants' import { mapEndpointStateToProps, mapEndpointDispatchToProps } from './utils' // Widgets import Table from '../../widgets/Table/table' import Card from '../../widgets/IncidentCard/card' // Actions import filterSet from '../../modules/endpoints/actions/filter_set' import incidentSelect from '../../modules/endpoints/actions/incident_select' import activeTabSet from '../../modules/active_tab/actions/active_tab_set' const saveIdToLocalStorage = (id) => { let ids = [] if (localStorage.hasOwnProperty('viewed_incidents_ids')) { ids = JSON.parse(localStorage.getItem('viewed_incidents_ids')) } if (ids.indexOf(id) !== -1) return // there is already one if (ids.length > 1000) ids.shift() // ids list length limited to 1000 ids.push(id) localStorage.setItem('viewed_incidents_ids', JSON.stringify(ids)); } const ENDPOINT = 'incidents'; const mapStateToProps = (state) => { return { ...mapEndpointStateToProps(ENDPOINT, state) } } const mapDispatchToProps = (dispatch) => { return { ...mapEndpointDispatchToProps(ENDPOINT, dispatch), handleDateRangeChange(date_range) { let dr = { $gte: date_range.from, $lte: date_range.to } // if current period < 1 day, show all day incidents if (date_range.to - date_range.from < 1000*60*60*24) { dr = { $gte: moment(date_range.to).subtract(1, 'days').toDate(), $lte: date_range.to } } return dispatch(filterSet('incidents', 'created', dr)) }, handleRowClick(e, data) { saveIdToLocalStorage(data._id) dispatch(incidentSelect(data._id)) dispatch(activeTabSet(2)) // go to the incident tab }, } } export default connect(mapStateToProps, mapDispatchToProps)(Table); <file_sep>/src/modules/filters/actions/filters_set.js export default function filtersSet(payload){ return { type: 'SET_FILTERS', payload } } <file_sep>/src/containers/Titles/title.js import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import classnames from 'classnames'; import ajaxLoader from '../../public/assets/images/ajax-loader.gif'; import { getTitleIcon } from './utils'; import { _t } from '../../constants'; // Actions import grpToggle from '../../modules/groups/actions/group_toggle' import groupToggle from '../../modules/endpoints/actions/group_toggle' import fsToggleGroup from '../../modules/fired_signatures/actions/fs_toggle_group' const calcPercent = (current=0, previous) => { if (typeof previous === 'undefined') return return Math.ceil(current * 100 / previous - 100) } const mapStateToProps = ({ counters, counters1, date_range }, { group }) => { // if (counters1._items.length > 0) console.log(counters1); let { count: item_count } = _(counters._items).findWhere({ group }) || {}; let { count: item1_count } = _(counters1._items).findWhere({ group }) || {}; return { group, coefficient: Math.floor((date_range.to - date_range.from ) / 1000*60*15), qty: typeof item_count === 'undefined' ? 0 : item_count, isFetching: counters.isFetching, ratio: calcPercent(item_count, item1_count) } } const mapDispatchToProps = (dispatch) => { return { toggleGroupFilter(group) { dispatch(grpToggle(group)) dispatch(groupToggle(group)); dispatch(fsToggleGroup(group)); } } } const IconDecrease = <i className="material-icons good">arrow_drop_down</i> const IconIncrease = <i className="material-icons error">arrow_drop_up</i> const Ratio = ({ value }) => ( <div className="title-ratio"> { value <= 0 ? IconDecrease : IconIncrease } {Math.abs(value)}% </div> ) const NoRatio = () => ( <div className="title-ratio"> <i className="material-icons">remove</i> </div> ) class Title extends Component { constructor(props) { super(props); this.state = { isSelected: false }; this.handleClick = this.handleClick.bind(this); } static propTypes = { group: PropTypes.string.isRequired, qty: PropTypes.number.isRequired, isFetching: PropTypes.bool.isRequired, toggleGroupFilter: PropTypes.func.isRequired } handleClick(e) { // if (this.props.qty < 0) return false; this.setState({ isSelected: !this.state.isSelected }); this.props.toggleGroupFilter(this.props.group); } render() { const { group, qty, isFetching, ratio, coefficient } = this.props; const { isSelected } = this.state; const loader = <img src={ajaxLoader} /> return ( <div className="titles-item"> <div className={classnames(['titles-title', { 'title--selected': isSelected }])} onClick={this.handleClick} > <div className="title-group"> {_t(group)} </div> <div className="title-main"> { isFetching ? loader : getTitleIcon(group, qty, coefficient) } { qty >= 0 ? qty : 'N/A' } </div> { ratio ? <Ratio value={ratio}/> : <NoRatio /> } </div> </div> ) } } export default connect(mapStateToProps, mapDispatchToProps)(Title); <file_sep>/src/containers/TabsSelector.js import React from 'react' import { connect } from 'react-redux' // Widgets import Tabs from '../widgets/Tabs' // Actions import activeTabSet from '../modules/active_tab/actions/active_tab_set' const mapStateToProps = ({ active_tab }, { tabs }) => { return { active_tab, tabs } } const mapDispatchToProps = (dispatch) => { return { setTab(tabIndex){ dispatch(activeTabSet(tabIndex)) } } } export default connect(mapStateToProps, mapDispatchToProps)(Tabs)
e216dc7384094c8e2bc3448ae4a1291f2e534f4c
[ "JavaScript", "Dockerfile", "Markdown", "Shell" ]
86
JavaScript
ermolaevp/webpack-redux
63adc97f1de89b54599f11e918cd451f36e891c2
73c77302225a97d2b95837f4a7f828025c516f74
refs/heads/master
<file_sep>package com.edii.tools; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.RandomAccessFile; import java.io.StringWriter; import java.text.SimpleDateFormat; import java.util.Date; public class Utils { static int prevNumber = 0; public static String readFileAsString(String filePath) throws java.io.IOException { byte[] buffer = new byte[(int) new File(filePath).length()]; BufferedInputStream f = null; try { f = new BufferedInputStream(new FileInputStream(filePath)); f.read(buffer); } finally { if (f != null) { try { f.close(); } catch (IOException ignored) { } } } return new String(buffer); } public static boolean writeStringtoFile(String filename, String content) throws Exception { boolean success = false; File f = null; RandomAccessFile rf = null; try { f = new File(filename); rf = new RandomAccessFile(f, "rwd"); rf.writeBytes(content); rf.close(); success = true; } catch (Exception e) { System.err.println(e.getMessage()); success = false; } finally { f = null; rf = null; return success; } } public static String getStackTrace(Throwable t) { String stackTrace = null; try { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); pw.close(); sw.close(); stackTrace = sw.getBuffer().toString(); } catch (Exception ex) { } return stackTrace; } public static String getNow() { return new SimpleDateFormat("ddMMyyyyHHmmss").format(new Date()); } public static boolean isFileExist(String filename) { //filename is full with filepath File file = new File(filename); return file.isFile(); } public static String addXmlHeader() { return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; } public static String getUniqueString() { long currentTime = System.currentTimeMillis(); int threadID = Thread.currentThread().hashCode(); StringBuffer strBuf = new StringBuffer(); int num = 0; do { num = (int) (Math.round(Math.random() * 36.0D) % 36L); } while (num == prevNumber); prevNumber = num; convertToRadix(strBuf, num, 36); convertToRadix(strBuf, currentTime, 36); convertToRadix(strBuf, threadID, 36); strBuf.reverse(); return strBuf.toString(); } public static void convertToRadix(StringBuffer strBuf, long num, int radix) { while (num > 0L) { int n = (int) (num % radix); char ch = Character.forDigit(n, radix); strBuf.append(Character.toUpperCase(ch)); num /= radix; } } } <file_sep>/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.edii.tools; import com.nsw.db.Db; import java.sql.PreparedStatement; import java.sql.SQLException; /** * * @author <NAME> */ public class Log { public void logSucces(String TIPE_JOB, String NAMA_JOB, String SQL_CODE, String SQL_ERRM, String KETERANGAN) throws Exception { Db mydb = null; Integer ID = null; String query = null; PreparedStatement preparedStatement = null; query = "INSERT INTO LOG_JOB(ID,TIPE_JOB,NAMA_JOB,SQL_CODE,SQL_ERRM,STATUS,KETERANGAN,WK_REKAM) VALUES (?,?,?,?,?,?,?,?)"; try { mydb = new Db("SHL.properties"); mydb.execute("SELECT SEQ_LOG_JOB.NEXTVAL as ID FROM DUAL");// fungsi untuk mengambil data terakhir if (mydb.next()) { ID = mydb.getInt("ID"); } preparedStatement = mydb.preparedstmt(query); preparedStatement.setInt(1, ID); preparedStatement.setString(2, TIPE_JOB); preparedStatement.setString(3, NAMA_JOB); preparedStatement.setString(4, SQL_CODE); preparedStatement.setString(5, SQL_ERRM); preparedStatement.setString(6, "TRUE"); preparedStatement.setString(7, KETERANGAN); preparedStatement.setTimestamp(8, getCurrentTimeStamp()); preparedStatement.executeUpdate(); mydb.execute("commit"); } catch (SQLException e) { } finally { if (preparedStatement != null) { preparedStatement.close(); } if (mydb != null) { mydb.close(); } } } public void logError(String TIPE_JOB, String NAMA_JOB, String SQL_CODE, String SQL_ERRM, String KETERANGAN) throws Exception { Db mydb = null; Integer ID = null; String query = null; PreparedStatement preparedStatement = null; query = "INSERT INTO LOG_JOB(ID,TIPE_JOB,NAMA_JOB,SQL_CODE,SQL_ERRM,STATUS,KETERANGAN,WK_REKAM) VALUES (?,?,?,?,?,?,?,?)"; try { mydb = new Db("SHL.properties"); mydb.execute("SELECT SEQ_LOG_JOB.NEXTVAL as ID FROM DUAL");// fungsi untuk mengambil data terakhir if (mydb.next()) { ID = mydb.getInt("ID"); } preparedStatement = mydb.preparedstmt(query); preparedStatement.setInt(1, ID); preparedStatement.setString(2, TIPE_JOB); preparedStatement.setString(3, NAMA_JOB); preparedStatement.setString(4, SQL_CODE); preparedStatement.setString(5, SQL_ERRM); preparedStatement.setString(6, "FALSE"); preparedStatement.setString(7, KETERANGAN); preparedStatement.setTimestamp(8, getCurrentTimeStamp()); preparedStatement.executeUpdate(); mydb.execute("commit"); } catch (SQLException e) { } finally { if (preparedStatement != null) { preparedStatement.close(); } if (mydb != null) { mydb.close(); } } } private static java.sql.Timestamp getCurrentTimeStamp() { java.util.Date today = new java.util.Date(); return new java.sql.Timestamp(today.getTime()); } public static void main(String[] args) throws Exception { Log l = new Log(); //l.logError("COARRI_CODECO_SHL", "INSERT DB", "", "", ""); l.logSucces("COARRI_CODECO_SHL", "INSERT DB", "", "SUCCESS", "001"); } } <file_sep>/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.edii.generatefile; import DatabaseGenerator.DatabaseOracle; import XMLGenerator.GeneratorXML; import com.edii.db.Db; import com.edii.operation.db.operation; import File.TXT.CreateFile; import com.edii.tools.Tanggalan; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.logging.LogFactory; /** * * @author <NAME> */ public class GenerateXMLCFS { String table = ""; String colomn = ""; String value = ""; String query = ""; GeneratorXML gx = null; static org.apache.commons.logging.Log logger = LogFactory.getLog(Db.class); private static final String PROPERTIES_FILE = "db.properties"; private static final Properties PROPERTIES = new Properties(); DatabaseOracle dbO = null; static { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream propertiesFile = classLoader.getResourceAsStream(PROPERTIES_FILE); if (propertiesFile == null) { logger.debug("Properties file '" + PROPERTIES_FILE + "' is missing in classpath."); } try { PROPERTIES.load(propertiesFile); } catch (IOException e) { logger.debug("Cannot load properties file '" + PROPERTIES_FILE + "'." + e.getMessage()); } } private void OpenConnection() throws ClassNotFoundException { dbO = new DatabaseOracle(); dbO.connectDatabase(PROPERTIES.getProperty("db.host"), PROPERTIES.getProperty("db.SID"), PROPERTIES.getProperty("db.username"), PROPERTIES.getProperty("db.password")); } public String execute(String outboxDir, String kdAsp) throws Exception { CreateFile cf = null; Tanggalan tg = null; String REF_NUMBER = null; String filename = null; String result = null; ArrayList<String> list = new ArrayList<>(); try { OpenConnection(); } catch (ClassNotFoundException ex) { Logger.getLogger(operation.class.getName()).log(Level.SEVERE, null, ex); } colomn = "KODE_KANTOR,TIPE_DATA,KODE_TPS_ASAL,REF_NUMBER,NO_PLP," + "TGL_SURAT_PLP,KODE_GUDANG_ASAL,KODE_TPS_TUJUAN,KODE_GUDANG_TUJUAN," + "KODE_ALASAN_PLP,YOR_ASAL,YOR_TUJUAN,CALL_SIGN,NAMA_KAPAL,NO_VOYAGE," + "TGL_TIBA,NO_BC11,TGL_BC11,NAMA_PEMOHON"; query = "SELECT KODE_KANTOR,TIPE_DATA,KODE_TPS_ASAL,REF_NUMBER,NO_PLP," + "TO_CHAR(TGL_PLP,'YYYYMMDD'),KODE_GUDANG_ASAL,KODE_TPS_TUJUAN,KODE_GUDANG_TUJUAN," + "KODE_ALASAN_PLP,YOR_ASAL,YOR_TUJUAN,CALL_SIGN,NAMA_KAPAL,NO_VOYAGE," + "TO_CHAR(TGL_TIBA,'YYYYMMDD'),NO_BC11,TO_CHAR(TGL_BC11,'YYYYMMDD')," + "NAMA_PEMOHON FROM T_REQ_UBAH_STATUS WHERE STATUS = '300' AND FL_SEND = '0' AND " + "KODE_TPS_ASAL = '" + kdAsp + "'"; try { cf = new CreateFile(); tg = new Tanggalan(); gx = new GeneratorXML("DOCUMENT", "loadplp.xsd"); gx.addXML("DOCUMENT", "LOADPLP", ""); list = dbO.query_select_raw(colomn, query); try { if (!list.isEmpty()) { REF_NUMBER = list.get(0).split("#")[3].split(":")[1]; gx.addXML("LOADPLP", "HEADER", list.get(0).replace("#", ",")); gx.addXML("LOADPLP", "DETIL", ""); //GET CONT table = "T_REQ_UBAH_STATUS_CONT"; colomn = "NO_CONT,UKURAN_CONT "; String colwhere = "REF_NUMBER"; String valwhere = REF_NUMBER; list = dbO.query_select_with_where(table, colomn, colwhere, valwhere, ""); for (String isi_list : list) { gx.addXML("DETIL", "CONT", isi_list.replace("#", ",")); } //GET KMS colomn = "KODE_KEMASAN,JUMLAH_KEMASAN,NO_BL,TGL_BL_AWB"; query = "SELECT KODE_KEMASAN,JUMLAH_KEMASAN,NO_BL,TO_CHAR(TGL_BL,'YYYYMMDD') FROM T_REQ_UBAH_STATUS_KMS WHERE REF_NUMBER = '" + REF_NUMBER + "'"; list = dbO.query_select_raw(colomn, query); for (String isi_list : list) { gx.addXML("DETIL", "KMS", isi_list.replace("#", ",")); } } if (gx.getStringxml().length() > 100) { table = "T_REQ_UBAH_STATUS"; colomn = "STATUS,DATE_SEND,FL_SEND"; value = "400," + getCurrentTimeStamp()+",1"; String colwhere = "REF_NUMBER = ,FL_SEND ="; String valwhere = REF_NUMBER + ",0"; if (dbO.query_update_with_where(table, colomn, value, colwhere, valwhere, "AND")) { filename = REF_NUMBER + "_GET_UBAH_STATUS_" + tg.UNIXNUMBER() + ".xml"; if (cf.newFile(outboxDir + File.separator, filename, gx.getStringxml())) { result = gx.getStringxml(); } } // query = "UPDATE T_REQ_UBAH_STATUS SET STATUS = ?, DATE_SEND = ? , FL_SEND = ? WHERE REF_NUMBER = ? AND FL_SEND = ?"; // preparedStatement = mydb.preparedstmt(query); // preparedStatement.setString(1, "400"); // preparedStatement.setTimestamp(2, getCurrentTimeStamp()); // preparedStatement.setString(3, "1"); // preparedStatement.setString(4, REF_NUMBER); // preparedStatement.setString(5, "0"); // mydb.execute("commit"); } } catch (Exception e) { System.out.println("message" + e.getMessage()); } return result; } catch (Exception e) { System.out.println("message nian" + e.getMessage()); return result; } finally { list.clear(); } } public static void main(String[] args) throws Exception { GenerateResponPLP_Tujuan_Tes tes = new GenerateResponPLP_Tujuan_Tes(); String r = tes.excute("D://DATA", "KOJA"); System.out.println(r); } private static java.sql.Timestamp getCurrentTimeStamp() { java.util.Date today = new java.util.Date(); return new java.sql.Timestamp(today.getTime()); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.edii.model; /** * * @author <NAME> */ public class ModelGetSPJM { String CAR = null; String KD_KANTOR = null; String NO_PIB = null; String TGL_PIB = null; String NPWP_IMP = null; String NAMA_IMP = null; String NPWP_PPJK = null; String NAMA_PPJK = null; String GUDANG = null; String JML_CONT = null; String NO_BC11 = null; String TGL_BC11 = null; String NO_POS_BC11 = null; String FL_KARANTINA = null; String NM_ANGKUT = null; String NO_VOY_FLIGHT = null; //DOK PLP Element Dtl KMS String JNS_KMS = null; String MERK_KMS = null; String JML_KMS = null; //DOK SPJM Element Dtl CONT String NO_CONT = null; public String getNO_DOK() { return NO_DOK; } public void setNO_DOK(String NO_DOK) { this.NO_DOK = NO_DOK; } public String getTGL_DOK() { return TGL_DOK; } public void setTGL_DOK(String TGL_DOK) { this.TGL_DOK = TGL_DOK; } public String getJNS_DOK() { return JNS_DOK; } public void setJNS_DOK(String JNS_DOK) { this.JNS_DOK = JNS_DOK; } String SIZE = null; //DOK String NO_DOK = null; String TGL_DOK =null; String JNS_DOK = null; public String getCAR() { return CAR; } public void setCAR(String CAR) { this.CAR = CAR; } public String getKD_KANTOR() { return KD_KANTOR; } public void setKD_KANTOR(String KD_KANTOR) { this.KD_KANTOR = KD_KANTOR; } public String getNO_PIB() { return NO_PIB; } public void setNO_PIB(String NO_PIB) { this.NO_PIB = NO_PIB; } public String getTGL_PIB() { return TGL_PIB; } public void setTGL_PIB(String TGL_PIB) { this.TGL_PIB = TGL_PIB; } public String getNPWP_IMP() { return NPWP_IMP; } public void setNPWP_IMP(String NPWP_IMP) { this.NPWP_IMP = NPWP_IMP; } public String getNAMA_IMP() { return NAMA_IMP; } public void setNAMA_IMP(String NAMA_IMP) { this.NAMA_IMP = NAMA_IMP; } public String getNPWP_PPJK() { return NPWP_PPJK; } public void setNPWP_PPJK(String NPWP_PPJK) { this.NPWP_PPJK = NPWP_PPJK; } public String getNAMA_PPJK() { return NAMA_PPJK; } public void setNAMA_PPJK(String NAMA_PPJK) { this.NAMA_PPJK = NAMA_PPJK; } public String getGUDANG() { return GUDANG; } public void setGUDANG(String GUDANG) { this.GUDANG = GUDANG; } public String getJML_CONT() { return JML_CONT; } public void setJML_CONT(String JML_CONT) { this.JML_CONT = JML_CONT; } public String getNO_BC11() { return NO_BC11; } public void setNO_BC11(String NO_BC11) { this.NO_BC11 = NO_BC11; } public String getTGL_BC11() { return TGL_BC11; } public void setTGL_BC11(String TGL_BC11) { this.TGL_BC11 = TGL_BC11; } public String getNO_POS_BC11() { return NO_POS_BC11; } public void setNO_POS_BC11(String NO_POS_BC11) { this.NO_POS_BC11 = NO_POS_BC11; } public String getFL_KARANTINA() { return FL_KARANTINA; } public void setFL_KARANTINA(String FL_KARANTINA) { this.FL_KARANTINA = FL_KARANTINA; } public String getNM_ANGKUT() { return NM_ANGKUT; } public void setNM_ANGKUT(String NM_ANGKUT) { this.NM_ANGKUT = NM_ANGKUT; } public String getNO_VOY_FLIGHT() { return NO_VOY_FLIGHT; } public void setNO_VOY_FLIGHT(String NO_VOY_FLIGHT) { this.NO_VOY_FLIGHT = NO_VOY_FLIGHT; } public String getJNS_KMS() { return JNS_KMS; } public void setJNS_KMS(String JNS_KMS) { this.JNS_KMS = JNS_KMS; } public String getMERK_KMS() { return MERK_KMS; } public void setMERK_KMS(String MERK_KMS) { this.MERK_KMS = MERK_KMS; } public String getJML_KMS() { return JML_KMS; } public void setJML_KMS(String JML_KMS) { this.JML_KMS = JML_KMS; } public String getNO_CONT() { return NO_CONT; } public void setNO_CONT(String NO_CONT) { this.NO_CONT = NO_CONT; } public String getSIZE() { return SIZE; } public void setSIZE(String SIZE) { this.SIZE = SIZE; } } <file_sep>/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.edii.xml; /** * * @author aldi */ public class Reqsppb { private String TYPE; private String NO_SPPB; private String TGL_SPPB; private String NPWP_IMP; /** * @return the NO_SPPB */ public String getNO_SPPB() { return NO_SPPB; } /** * @param NO_SPPB the NO_SPPB to set */ public void setNO_SPPB(String NO_SPPB) { this.NO_SPPB = NO_SPPB; } /** * @return the TGL_SPPB */ public String getTGL_SPPB() { return TGL_SPPB; } /** * @param TGL_SPPB the TGL_SPPB to set */ public void setTGL_SPPB(String TGL_SPPB) { this.TGL_SPPB = TGL_SPPB; } /** * @return the NPWP_IMP */ public String getNPWP_IMP() { return NPWP_IMP; } /** * @param NPWP_IMP the NPWP_IMP to set */ public void setNPWP_IMP(String NPWP_IMP) { this.NPWP_IMP = NPWP_IMP; } /** * @return the TYPE */ public String getTYPE() { return TYPE; } /** * @param TYPE the TYPE to set */ public void setTYPE(String TYPE) { this.TYPE = TYPE; } } <file_sep> package id.go.beacukai.services; import javax.xml.bind.annotation.XmlRegistry; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the id.go.beacukai.services package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: id.go.beacukai.services * */ public ObjectFactory() { } /** * Create an instance of {@link GetNPEResponse } * */ public GetNPEResponse createGetNPEResponse() { return new GetNPEResponse(); } /** * Create an instance of {@link GetImporPermit } * */ public GetImporPermit createGetImporPermit() { return new GetImporPermit(); } /** * Create an instance of {@link CekDataTerkirim } * */ public CekDataTerkirim createCekDataTerkirim() { return new CekDataTerkirim(); } /** * Create an instance of {@link CekDataGagalKirimResponse } * */ public CekDataGagalKirimResponse createCekDataGagalKirimResponse() { return new CekDataGagalKirimResponse(); } /** * Create an instance of {@link GetRejectData } * */ public GetRejectData createGetRejectData() { return new GetRejectData(); } /** * Create an instance of {@link GetImpor_SppbResponse } * */ public GetImpor_SppbResponse createGetImpor_SppbResponse() { return new GetImpor_SppbResponse(); } /** * Create an instance of {@link PermohonanBC12 } * */ public PermohonanBC12 createPermohonanBC12() { return new PermohonanBC12(); } /** * Create an instance of {@link GetSPPB12_TPSTujuan } * */ public GetSPPB12_TPSTujuan createGetSPPB12_TPSTujuan() { return new GetSPPB12_TPSTujuan(); } /** * Create an instance of {@link CoCoCarTer } * */ public CoCoCarTer createCoCoCarTer() { return new CoCoCarTer(); } /** * Create an instance of {@link GetNPE } * */ public GetNPE createGetNPE() { return new GetNPE(); } /** * Create an instance of {@link GetResponPLPResponse } * */ public GetResponPLPResponse createGetResponPLPResponse() { return new GetResponPLPResponse(); } /** * Create an instance of {@link PermohonanBC12Response } * */ public PermohonanBC12Response createPermohonanBC12Response() { return new PermohonanBC12Response(); } /** * Create an instance of {@link CekDataSPPBResponse } * */ public CekDataSPPBResponse createCekDataSPPBResponse() { return new CekDataSPPBResponse(); } /** * Create an instance of {@link GetPendukungPLP } * */ public GetPendukungPLP createGetPendukungPLP() { return new GetPendukungPLP(); } /** * Create an instance of {@link GetPendukungPLP_BL } * */ public GetPendukungPLP_BL createGetPendukungPLP_BL() { return new GetPendukungPLP_BL(); } /** * Create an instance of {@link GetEkspor_NPE } * */ public GetEkspor_NPE createGetEkspor_NPE() { return new GetEkspor_NPE(); } /** * Create an instance of {@link GetEksporPermit_FNPE } * */ public GetEksporPermit_FNPE createGetEksporPermit_FNPE() { return new GetEksporPermit_FNPE(); } /** * Create an instance of {@link CekNPEResponse } * */ public CekNPEResponse createCekNPEResponse() { return new CekNPEResponse(); } /** * Create an instance of {@link GetBC23Permit_FASPResponse } * */ public GetBC23Permit_FASPResponse createGetBC23Permit_FASPResponse() { return new GetBC23Permit_FASPResponse(); } /** * Create an instance of {@link GetImporPermitResponse } * */ public GetImporPermitResponse createGetImporPermitResponse() { return new GetImporPermitResponse(); } /** * Create an instance of {@link CoarriCodeco_ContainerResponse } * */ public CoarriCodeco_ContainerResponse createCoarriCodeco_ContainerResponse() { return new CoarriCodeco_ContainerResponse(); } /** * Create an instance of {@link GantiPassword } * */ public GantiPassword createGantiPassword() { return new GantiPassword(); } /** * Create an instance of {@link CoCoTangki } * */ public CoCoTangki createCoCoTangki() { return new CoCoTangki(); } /** * Create an instance of {@link GetImpor_Bc11Response } * */ public GetImpor_Bc11Response createGetImpor_Bc11Response() { return new GetImpor_Bc11Response(); } /** * Create an instance of {@link GetResponPLPTujuan } * */ public GetResponPLPTujuan createGetResponPLPTujuan() { return new GetResponPLPTujuan(); } /** * Create an instance of {@link UploadBatalPLP } * */ public UploadBatalPLP createUploadBatalPLP() { return new UploadBatalPLP(); } /** * Create an instance of {@link GetDokumenManual_OnDemandResponse } * */ public GetDokumenManual_OnDemandResponse createGetDokumenManual_OnDemandResponse() { return new GetDokumenManual_OnDemandResponse(); } /** * Create an instance of {@link GetResponPenolakanBC12Response } * */ public GetResponPenolakanBC12Response createGetResponPenolakanBC12Response() { return new GetResponPenolakanBC12Response(); } /** * Create an instance of {@link GetImpor_Bc11 } * */ public GetImpor_Bc11 createGetImpor_Bc11() { return new GetImpor_Bc11(); } /** * Create an instance of {@link CoCoCont_TesResponse } * */ public CoCoCont_TesResponse createCoCoCont_TesResponse() { return new CoCoCont_TesResponse(); } /** * Create an instance of {@link GetDokumenManual } * */ public GetDokumenManual createGetDokumenManual() { return new GetDokumenManual(); } /** * Create an instance of {@link GetDokumenManualResponse } * */ public GetDokumenManualResponse createGetDokumenManualResponse() { return new GetDokumenManualResponse(); } /** * Create an instance of {@link GetSPJM } * */ public GetSPJM createGetSPJM() { return new GetSPJM(); } /** * Create an instance of {@link CoCoCarTerResponse } * */ public CoCoCarTerResponse createCoCoCarTerResponse() { return new CoCoCarTerResponse(); } /** * Create an instance of {@link GetSPJMResponse } * */ public GetSPJMResponse createGetSPJMResponse() { return new GetSPJMResponse(); } /** * Create an instance of {@link GetBC23Permit } * */ public GetBC23Permit createGetBC23Permit() { return new GetBC23Permit(); } /** * Create an instance of {@link GetPendukungPLP_BLResponse } * */ public GetPendukungPLP_BLResponse createGetPendukungPLP_BLResponse() { return new GetPendukungPLP_BLResponse(); } /** * Create an instance of {@link UploadBatalPLPResponse } * */ public UploadBatalPLPResponse createUploadBatalPLPResponse() { return new UploadBatalPLPResponse(); } /** * Create an instance of {@link GetResponPLPTujuanResponse } * */ public GetResponPLPTujuanResponse createGetResponPLPTujuanResponse() { return new GetResponPLPTujuanResponse(); } /** * Create an instance of {@link GetPendukungPLPResponse } * */ public GetPendukungPLPResponse createGetPendukungPLPResponse() { return new GetPendukungPLPResponse(); } /** * Create an instance of {@link GetResponBatalPLPTujuan } * */ public GetResponBatalPLPTujuan createGetResponBatalPLPTujuan() { return new GetResponBatalPLPTujuan(); } /** * Create an instance of {@link GetEkspor_NPEResponse } * */ public GetEkspor_NPEResponse createGetEkspor_NPEResponse() { return new GetEkspor_NPEResponse(); } /** * Create an instance of {@link GetEksporPermit_FNPEResponse } * */ public GetEksporPermit_FNPEResponse createGetEksporPermit_FNPEResponse() { return new GetEksporPermit_FNPEResponse(); } /** * Create an instance of {@link CoCoKms_TesResponse } * */ public CoCoKms_TesResponse createCoCoKms_TesResponse() { return new CoCoKms_TesResponse(); } /** * Create an instance of {@link GetImporPermit_FASP } * */ public GetImporPermit_FASP createGetImporPermit_FASP() { return new GetImporPermit_FASP(); } /** * Create an instance of {@link GetBC23Permit_FASP } * */ public GetBC23Permit_FASP createGetBC23Permit_FASP() { return new GetBC23Permit_FASP(); } /** * Create an instance of {@link CekDataTerkirimResponse } * */ public CekDataTerkirimResponse createCekDataTerkirimResponse() { return new CekDataTerkirimResponse(); } /** * Create an instance of {@link CoCoKms_Tes } * */ public CoCoKms_Tes createCoCoKms_Tes() { return new CoCoKms_Tes(); } /** * Create an instance of {@link GetEkspor_PEB } * */ public GetEkspor_PEB createGetEkspor_PEB() { return new GetEkspor_PEB(); } /** * Create an instance of {@link CekDataGagalKirim } * */ public CekDataGagalKirim createCekDataGagalKirim() { return new CekDataGagalKirim(); } /** * Create an instance of {@link GetEkspor_PKBEResponse } * */ public GetEkspor_PKBEResponse createGetEkspor_PKBEResponse() { return new GetEkspor_PKBEResponse(); } /** * Create an instance of {@link GetSPPB12_TPSAsalResponse } * */ public GetSPPB12_TPSAsalResponse createGetSPPB12_TPSAsalResponse() { return new GetSPPB12_TPSAsalResponse(); } /** * Create an instance of {@link CoarriCodeco_Kemasan } * */ public CoarriCodeco_Kemasan createCoarriCodeco_Kemasan() { return new CoarriCodeco_Kemasan(); } /** * Create an instance of {@link CoCoTangkiResponse } * */ public CoCoTangkiResponse createCoCoTangkiResponse() { return new CoCoTangkiResponse(); } /** * Create an instance of {@link CekNPE } * */ public CekNPE createCekNPE() { return new CekNPE(); } /** * Create an instance of {@link CoarriCodeco_KemasanResponse } * */ public CoarriCodeco_KemasanResponse createCoarriCodeco_KemasanResponse() { return new CoarriCodeco_KemasanResponse(); } /** * Create an instance of {@link GantiPasswordResponse } * */ public GantiPasswordResponse createGantiPasswordResponse() { return new GantiPasswordResponse(); } /** * Create an instance of {@link GetResponPenolakanBC12 } * */ public GetResponPenolakanBC12 createGetResponPenolakanBC12() { return new GetResponPenolakanBC12(); } /** * Create an instance of {@link PermohonanPLPResponse } * */ public PermohonanPLPResponse createPermohonanPLPResponse() { return new PermohonanPLPResponse(); } /** * Create an instance of {@link PermohonanPLP } * */ public PermohonanPLP createPermohonanPLP() { return new PermohonanPLP(); } /** * Create an instance of {@link UploadMohonPLPResponse } * */ public UploadMohonPLPResponse createUploadMohonPLPResponse() { return new UploadMohonPLPResponse(); } /** * Create an instance of {@link GetImporPermit_FASPResponse } * */ public GetImporPermit_FASPResponse createGetImporPermit_FASPResponse() { return new GetImporPermit_FASPResponse(); } /** * Create an instance of {@link GetDataOBResponse } * */ public GetDataOBResponse createGetDataOBResponse() { return new GetDataOBResponse(); } /** * Create an instance of {@link GetResponPLP_TujuanResponse } * */ public GetResponPLP_TujuanResponse createGetResponPLP_TujuanResponse() { return new GetResponPLP_TujuanResponse(); } /** * Create an instance of {@link GetDokumenManual_OnDemand } * */ public GetDokumenManual_OnDemand createGetDokumenManual_OnDemand() { return new GetDokumenManual_OnDemand(); } /** * Create an instance of {@link GetResponBatalPLPResponse } * */ public GetResponBatalPLPResponse createGetResponBatalPLPResponse() { return new GetResponBatalPLPResponse(); } /** * Create an instance of {@link CekDataSPPB } * */ public CekDataSPPB createCekDataSPPB() { return new CekDataSPPB(); } /** * Create an instance of {@link GetSPPB12_TPSTujuanResponse } * */ public GetSPPB12_TPSTujuanResponse createGetSPPB12_TPSTujuanResponse() { return new GetSPPB12_TPSTujuanResponse(); } /** * Create an instance of {@link GetImpor_Sppb } * */ public GetImpor_Sppb createGetImpor_Sppb() { return new GetImpor_Sppb(); } /** * Create an instance of {@link GetEkspor_PKBE } * */ public GetEkspor_PKBE createGetEkspor_PKBE() { return new GetEkspor_PKBE(); } /** * Create an instance of {@link GetImporPermit200 } * */ public GetImporPermit200 createGetImporPermit200() { return new GetImporPermit200(); } /** * Create an instance of {@link GetImporPermit200Response } * */ public GetImporPermit200Response createGetImporPermit200Response() { return new GetImporPermit200Response(); } /** * Create an instance of {@link GetDataOB } * */ public GetDataOB createGetDataOB() { return new GetDataOB(); } /** * Create an instance of {@link CoCoCont_Tes } * */ public CoCoCont_Tes createCoCoCont_Tes() { return new CoCoCont_Tes(); } /** * Create an instance of {@link GetResponPLP_Tujuan } * */ public GetResponPLP_Tujuan createGetResponPLP_Tujuan() { return new GetResponPLP_Tujuan(); } /** * Create an instance of {@link GetResponPLP } * */ public GetResponPLP createGetResponPLP() { return new GetResponPLP(); } /** * Create an instance of {@link GetSPPB12_TPSAsal } * */ public GetSPPB12_TPSAsal createGetSPPB12_TPSAsal() { return new GetSPPB12_TPSAsal(); } /** * Create an instance of {@link GetSppb_Bc23Response } * */ public GetSppb_Bc23Response createGetSppb_Bc23Response() { return new GetSppb_Bc23Response(); } /** * Create an instance of {@link GetSppb_Bc23 } * */ public GetSppb_Bc23 createGetSppb_Bc23() { return new GetSppb_Bc23(); } /** * Create an instance of {@link GetResponBatalPLP } * */ public GetResponBatalPLP createGetResponBatalPLP() { return new GetResponBatalPLP(); } /** * Create an instance of {@link GetEkspor_PEBResponse } * */ public GetEkspor_PEBResponse createGetEkspor_PEBResponse() { return new GetEkspor_PEBResponse(); } /** * Create an instance of {@link GetSPJM_OnDemandResponse } * */ public GetSPJM_OnDemandResponse createGetSPJM_OnDemandResponse() { return new GetSPJM_OnDemandResponse(); } /** * Create an instance of {@link GetResponBatalPLPTujuanResponse } * */ public GetResponBatalPLPTujuanResponse createGetResponBatalPLPTujuanResponse() { return new GetResponBatalPLPTujuanResponse(); } /** * Create an instance of {@link UploadMohonPLP } * */ public UploadMohonPLP createUploadMohonPLP() { return new UploadMohonPLP(); } /** * Create an instance of {@link CoarriCodeco_Container } * */ public CoarriCodeco_Container createCoarriCodeco_Container() { return new CoarriCodeco_Container(); } /** * Create an instance of {@link GetSPJM_OnDemand } * */ public GetSPJM_OnDemand createGetSPJM_OnDemand() { return new GetSPJM_OnDemand(); } /** * Create an instance of {@link GetRejectDataResponse } * */ public GetRejectDataResponse createGetRejectDataResponse() { return new GetRejectDataResponse(); } /** * Create an instance of {@link GetBC23PermitResponse } * */ public GetBC23PermitResponse createGetBC23PermitResponse() { return new GetBC23PermitResponse(); } } <file_sep> package id.go.beacukai.services; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.ws.RequestWrapper; import javax.xml.ws.ResponseWrapper; /** * This class was generated by the JAX-WS RI. * JAX-WS RI 2.2.10-b140803.1500 * Generated source version: 2.1 * */ @WebService(name = "TPSServicesSoap", targetNamespace = "http://services.beacukai.go.id/") @XmlSeeAlso({ ObjectFactory.class }) public interface TPSServicesSoap { /** * Fungsi untuk konfirmasi ganti user password * * @param userName * @param password<PASSWORD> * @param password * @param passwordBaru * @return * returns java.lang.String */ @WebMethod(operationName = "GantiPassword", action = "http://services.beacukai.go.id/GantiPassword") @WebResult(name = "GantiPasswordResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "GantiPassword", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GantiPassword") @ResponseWrapper(localName = "GantiPasswordResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GantiPasswordResponse") public String gantiPassword( @WebParam(name = "UserName", targetNamespace = "http://services.beacukai.go.id/") String userName, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password, @WebParam(name = "PasswordBaru", targetNamespace = "http://services.beacukai.go.id/") String passwordBaru, @WebParam(name = "PasswordKonfirmasi", targetNamespace = "http://services.beacukai.go.id/") String passwordKonfirmasi); /** * Fungsi untuk insert data Coarri-Codeco Container(Baru, dengan penambahan kolom pada detil container) * * @param username * @param fStream * @param password * @return * returns java.lang.String */ @WebMethod(operationName = "CoarriCodeco_Container", action = "http://services.beacukai.go.id/CoarriCodeco_Container") @WebResult(name = "CoarriCodeco_ContainerResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "CoarriCodeco_Container", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.CoarriCodeco_Container") @ResponseWrapper(localName = "CoarriCodeco_ContainerResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.CoarriCodeco_ContainerResponse") public String coarriCodecoContainer( @WebParam(name = "fStream", targetNamespace = "http://services.beacukai.go.id/") String fStream, @WebParam(name = "Username", targetNamespace = "http://services.beacukai.go.id/") String username, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password); /** * Fungsi untuk insert data Coarri Kemasan (Baru, dengan penambahan kolom pada detil kemasan) * * @param username * @param fStream * @param password * @return * returns java.lang.String */ @WebMethod(operationName = "CoarriCodeco_Kemasan", action = "http://services.beacukai.go.id/CoarriCodeco_Kemasan") @WebResult(name = "CoarriCodeco_KemasanResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "CoarriCodeco_Kemasan", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.CoarriCodeco_Kemasan") @ResponseWrapper(localName = "CoarriCodeco_KemasanResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.CoarriCodeco_KemasanResponse") public String coarriCodecoKemasan( @WebParam(name = "fStream", targetNamespace = "http://services.beacukai.go.id/") String fStream, @WebParam(name = "Username", targetNamespace = "http://services.beacukai.go.id/") String username, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password); /** * Fungsi untuk melakukan uji coba insert data Coarri berdasarkan container, dengan username = 'TES' dan password = '<PASSWORD>' * * @param username * @param fStream * @param password * @return * returns java.lang.String */ @WebMethod(operationName = "CoCoCont_Tes", action = "http://services.beacukai.go.id/CoCoCont_Tes") @WebResult(name = "CoCoCont_TesResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "CoCoCont_Tes", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.CoCoCont_Tes") @ResponseWrapper(localName = "CoCoCont_TesResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.CoCoCont_TesResponse") public String coCoContTes( @WebParam(name = "fStream", targetNamespace = "http://services.beacukai.go.id/") String fStream, @WebParam(name = "Username", targetNamespace = "http://services.beacukai.go.id/") String username, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password); /** * Fungsi untuk melakukan uji coba insert data Coarri berdasarkan kemasan, dengan username = 'TES' dan password = '<PASSWORD>' * * @param username * @param fStream * @param password * @return * returns java.lang.String */ @WebMethod(operationName = "CoCoKms_Tes", action = "http://services.beacukai.go.id/CoCoKms_Tes") @WebResult(name = "CoCoKms_TesResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "CoCoKms_Tes", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.CoCoKms_Tes") @ResponseWrapper(localName = "CoCoKms_TesResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.CoCoKms_TesResponse") public String coCoKmsTes( @WebParam(name = "fStream", targetNamespace = "http://services.beacukai.go.id/") String fStream, @WebParam(name = "Username", targetNamespace = "http://services.beacukai.go.id/") String username, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password); /** * Fungsi untuk melakukan uji coba insert data Coarri Tangki-tangki penimbunan * * @param username * @param fStream * @param password * @return * returns java.lang.String */ @WebMethod(operationName = "CoCoTangki", action = "http://services.beacukai.go.id/CoCoTangki") @WebResult(name = "CoCoTangkiResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "CoCoTangki", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.CoCoTangki") @ResponseWrapper(localName = "CoCoTangkiResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.CoCoTangkiResponse") public String coCoTangki( @WebParam(name = "fStream", targetNamespace = "http://services.beacukai.go.id/") String fStream, @WebParam(name = "Username", targetNamespace = "http://services.beacukai.go.id/") String username, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password); /** * Fungsi untuk melakukan insert data Coarri Car Terminal * * @param username * @param fStream * @param password * @return * returns java.lang.String */ @WebMethod(operationName = "CoCoCarTer", action = "http://services.beacukai.go.id/CoCoCarTer") @WebResult(name = "CoCoCarTerResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "CoCoCarTer", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.CoCoCarTer") @ResponseWrapper(localName = "CoCoCarTerResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.CoCoCarTerResponse") public String coCoCarTer( @WebParam(name = "fStream", targetNamespace = "http://services.beacukai.go.id/") String fStream, @WebParam(name = "Username", targetNamespace = "http://services.beacukai.go.id/") String username, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password); /** * Fungsi untuk mendownload data Pendukung PLP dengan data BL, filter yang digunakan adalah nomor BC11, tanggal BC11 dengan format tanggal #ddmmyyyy#, dan nomor Kontainer * * @param noCont * @param noBc11 * @param userName * @param tglBc11 * @param password * @return * returns java.lang.String */ @WebMethod(operationName = "GetPendukungPLP_BL", action = "http://services.beacukai.go.id/GetPendukungPLP_BL") @WebResult(name = "GetPendukungPLP_BLResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "GetPendukungPLP_BL", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetPendukungPLP_BL") @ResponseWrapper(localName = "GetPendukungPLP_BLResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetPendukungPLP_BLResponse") public String getPendukungPLPBL( @WebParam(name = "UserName", targetNamespace = "http://services.beacukai.go.id/") String userName, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password, @WebParam(name = "noBc11", targetNamespace = "http://services.beacukai.go.id/") String noBc11, @WebParam(name = "tglBc11", targetNamespace = "http://services.beacukai.go.id/") String tglBc11, @WebParam(name = "noCont", targetNamespace = "http://services.beacukai.go.id/") String noCont); /** * Fungsi untuk mendownload data Pendukung PLP, filter yang digunakan adalah nomor BC11, tanggal BC11 dengan format tanggal #ddmmyyyy#, dan nomor Kontainer * * @param noCont * @param noBc11 * @param userName * @param tglBc11 * @param password * @return * returns java.lang.String */ @WebMethod(operationName = "GetPendukungPLP", action = "http://services.beacukai.go.id/GetPendukungPLP") @WebResult(name = "GetPendukungPLPResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "GetPendukungPLP", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetPendukungPLP") @ResponseWrapper(localName = "GetPendukungPLPResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetPendukungPLPResponse") public String getPendukungPLP( @WebParam(name = "UserName", targetNamespace = "http://services.beacukai.go.id/") String userName, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password, @WebParam(name = "noBc11", targetNamespace = "http://services.beacukai.go.id/") String noBc11, @WebParam(name = "tglBc11", targetNamespace = "http://services.beacukai.go.id/") String tglBc11, @WebParam(name = "noCont", targetNamespace = "http://services.beacukai.go.id/") String noCont); /** * Fungsi untuk mendownload data SPPB, filter yang digunakan adalah nomor BC11 dan tanggal BC11 format tanggal #ddmmyyyy# * * @param noBc11 * @param userName * @param tglBc11 * @param password * @return * returns java.lang.String */ @WebMethod(operationName = "GetImpor_Bc11", action = "http://services.beacukai.go.id/GetImpor_Bc11") @WebResult(name = "GetImpor_Bc11Result", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "GetImpor_Bc11", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetImpor_Bc11") @ResponseWrapper(localName = "GetImpor_Bc11Response", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetImpor_Bc11Response") public String getImporBc11( @WebParam(name = "UserName", targetNamespace = "http://services.beacukai.go.id/") String userName, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password, @WebParam(name = "No_Bc11", targetNamespace = "http://services.beacukai.go.id/") String noBc11, @WebParam(name = "Tgl_Bc11", targetNamespace = "http://services.beacukai.go.id/") String tglBc11); /** * Fungsi untuk mendownload data SPPB, filter yang digunakan adalah tanggal SPPB, nomor SPPB dan NPWP, format tanggal #ddmmyyyy# * * @param npwpImp * @param noSppb * @param userName * @param tglSppb * @param password * @return * returns java.lang.String */ @WebMethod(operationName = "GetImpor_Sppb", action = "http://services.beacukai.go.id/GetImpor_Sppb") @WebResult(name = "GetImpor_SppbResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "GetImpor_Sppb", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetImpor_Sppb") @ResponseWrapper(localName = "GetImpor_SppbResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetImpor_SppbResponse") public String getImporSppb( @WebParam(name = "UserName", targetNamespace = "http://services.beacukai.go.id/") String userName, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password, @WebParam(name = "No_Sppb", targetNamespace = "http://services.beacukai.go.id/") String noSppb, @WebParam(name = "Tgl_Sppb", targetNamespace = "http://services.beacukai.go.id/") String tglSppb, @WebParam(name = "NPWP_Imp", targetNamespace = "http://services.beacukai.go.id/") String npwpImp); /** * Fungsi untuk mendownload data SPPB, filter yang digunakan adalah kode Gudang * * @param kdGudang * @param userName * @param password * @return * returns java.lang.String */ @WebMethod(operationName = "GetImporPermit", action = "http://services.beacukai.go.id/GetImporPermit") @WebResult(name = "GetImporPermitResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "GetImporPermit", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetImporPermit") @ResponseWrapper(localName = "GetImporPermitResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetImporPermitResponse") public String getImporPermit( @WebParam(name = "UserName", targetNamespace = "http://services.beacukai.go.id/") String userName, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password, @WebParam(name = "Kd_Gudang", targetNamespace = "http://services.beacukai.go.id/") String kdGudang); /** * Fungsi untuk mendownload data SPPB, filter yang digunakan adalah kode Gudang (hasil 200 rows) * * @param kdGudang * @param userName * @param password * @return * returns java.lang.String */ @WebMethod(operationName = "GetImporPermit200", action = "http://services.beacukai.go.id/GetImporPermit200") @WebResult(name = "GetImporPermit200Result", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "GetImporPermit200", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetImporPermit200") @ResponseWrapper(localName = "GetImporPermit200Response", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetImporPermit200Response") public String getImporPermit200( @WebParam(name = "UserName", targetNamespace = "http://services.beacukai.go.id/") String userName, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password, @WebParam(name = "Kd_Gudang", targetNamespace = "http://services.beacukai.go.id/") String kdGudang); /** * Fungsi untuk mendownload data SPPB, filter yang digunakan adalah kode ASP * * @param userName * @param kdASP * @param password * @return * returns java.lang.String */ @WebMethod(operationName = "GetImporPermit_FASP", action = "http://services.beacukai.go.id/GetImporPermit_FASP") @WebResult(name = "GetImporPermit_FASPResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "GetImporPermit_FASP", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetImporPermit_FASP") @ResponseWrapper(localName = "GetImporPermit_FASPResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetImporPermit_FASPResponse") public String getImporPermitFASP( @WebParam(name = "UserName", targetNamespace = "http://services.beacukai.go.id/") String userName, @WebParam(name = "<PASSWORD>", targetNamespace = "http://services.beacukai.go.id/") String password, @WebParam(name = "Kd_ASP", targetNamespace = "http://services.beacukai.go.id/") String kdASP); /** * Fungsi untuk mendownload data NPE, filter yang digunakan adalah No PEB, Tgl PEB format #ddmmyyyy#, NPWP * * @param noPEB * @param userName * @param password * @param tglPEB * @param npwp * @return * returns java.lang.String */ @WebMethod(operationName = "GetEkspor_PEB", action = "http://services.beacukai.go.id/GetEkspor_PEB") @WebResult(name = "GetEkspor_PEBResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "GetEkspor_PEB", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetEkspor_PEB") @ResponseWrapper(localName = "GetEkspor_PEBResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetEkspor_PEBResponse") public String getEksporPEB( @WebParam(name = "UserName", targetNamespace = "http://services.beacukai.go.id/") String userName, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password, @WebParam(name = "No_PEB", targetNamespace = "http://services.beacukai.go.id/") String noPEB, @WebParam(name = "Tgl_PEB", targetNamespace = "http://services.beacukai.go.id/") String tglPEB, @WebParam(name = "npwp", targetNamespace = "http://services.beacukai.go.id/") String npwp); /** * Fungsi untuk mendownload data NPE, filter yang digunakan adalah No NPE, NPWP, Kode Kantor * * @param kdKantor * @param userName * @param noPE * @param password * @param npwp * @return * returns java.lang.String */ @WebMethod(operationName = "GetEkspor_NPE", action = "http://services.beacukai.go.id/GetEkspor_NPE") @WebResult(name = "GetEkspor_NPEResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "GetEkspor_NPE", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetEkspor_NPE") @ResponseWrapper(localName = "GetEkspor_NPEResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetEkspor_NPEResponse") public String getEksporNPE( @WebParam(name = "UserName", targetNamespace = "http://services.beacukai.go.id/") String userName, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password, @WebParam(name = "No_PE", targetNamespace = "http://services.beacukai.go.id/") String noPE, @WebParam(name = "npwp", targetNamespace = "http://services.beacukai.go.id/") String npwp, @WebParam(name = "kdKantor", targetNamespace = "http://services.beacukai.go.id/") String kdKantor); /** * Fungsi untuk mendownload data NPE, filter yang digunakan adalah No PKBE, Tanggal PKBE, Kode Kantor * * @param tglPKBE * @param kdKantor * @param userName * @param password * @param noPKBE * @return * returns java.lang.String */ @WebMethod(operationName = "GetEkspor_PKBE", action = "http://services.beacukai.go.id/GetEkspor_PKBE") @WebResult(name = "GetEkspor_PKBEResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "GetEkspor_PKBE", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetEkspor_PKBE") @ResponseWrapper(localName = "GetEkspor_PKBEResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetEkspor_PKBEResponse") public String getEksporPKBE( @WebParam(name = "UserName", targetNamespace = "http://services.beacukai.go.id/") String userName, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password, @WebParam(name = "No_PKBE", targetNamespace = "http://services.beacukai.go.id/") String noPKBE, @WebParam(name = "TGL_PKBE", targetNamespace = "http://services.beacukai.go.id/") String tglPKBE, @WebParam(name = "kdKantor", targetNamespace = "http://services.beacukai.go.id/") String kdKantor); /** * Fungsi untuk mendownload data OB/Pindah TPS, filter yang digunakan adalah kode ASP * * @param userName * @param kdASP * @param password * @return * returns java.lang.String */ @WebMethod(operationName = "GetDataOB", action = "http://services.beacukai.go.id/GetDataOB") @WebResult(name = "GetDataOBResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "GetDataOB", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetDataOB") @ResponseWrapper(localName = "GetDataOBResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetDataOBResponse") public String getDataOB( @WebParam(name = "UserName", targetNamespace = "http://services.beacukai.go.id/") String userName, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password, @WebParam(name = "Kd_ASP", targetNamespace = "http://services.beacukai.go.id/") String kdASP); /** * Fungsi untuk mendapatkan nomor dan tanggal NPE, filter yang digunakan adalah NPWP Eksportir, nomor NPE (6 digit)dan Kode Kantor Penerbit NPE * * @param kdKtr * @param noNpe * @param userName * @param npwpEks * @param password * @return * returns java.lang.String */ @WebMethod(operationName = "GetNPE", action = "http://services.beacukai.go.id/GetNPE") @WebResult(name = "GetNPEResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "GetNPE", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetNPE") @ResponseWrapper(localName = "GetNPEResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetNPEResponse") public String getNPE( @WebParam(name = "UserName", targetNamespace = "http://services.beacukai.go.id/") String userName, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password, @WebParam(name = "NPWP_Eks", targetNamespace = "http://services.beacukai.go.id/") String npwpEks, @WebParam(name = "No_Npe", targetNamespace = "http://services.beacukai.go.id/") String noNpe, @WebParam(name = "Kd_Ktr", targetNamespace = "http://services.beacukai.go.id/") String kdKtr); /** * Fungsi untuk mendownload data REJECT hasil validasi konten * * @param kdTps * @param userName * @param password * @return * returns java.lang.String */ @WebMethod(operationName = "GetRejectData", action = "http://services.beacukai.go.id/GetRejectData") @WebResult(name = "GetRejectDataResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "GetRejectData", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetRejectData") @ResponseWrapper(localName = "GetRejectDataResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetRejectDataResponse") public String getRejectData( @WebParam(name = "UserName", targetNamespace = "http://services.beacukai.go.id/") String userName, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password, @WebParam(name = "Kd_Tps", targetNamespace = "http://services.beacukai.go.id/") String kdTps); /** * Fungsi untuk mendownload data dokumen manual * * @param kdTps * @param userName * @param password * @return * returns java.lang.String */ @WebMethod(operationName = "GetDokumenManual", action = "http://services.beacukai.go.id/GetDokumenManual") @WebResult(name = "GetDokumenManualResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "GetDokumenManual", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetDokumenManual") @ResponseWrapper(localName = "GetDokumenManualResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetDokumenManualResponse") public String getDokumenManual( @WebParam(name = "UserName", targetNamespace = "http://services.beacukai.go.id/") String userName, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password, @WebParam(name = "Kd_Tps", targetNamespace = "http://services.beacukai.go.id/") String kdTps); /** * Fungsi untuk mendownload data dokumen manual on demand, parameter Kode Dokumen, Nomor Dokumen dan Tanggal Dokumen (ddMMyyyy) * * @param noDok * @param tglDok * @param userName * @param kdDok * @param password * @return * returns java.lang.String */ @WebMethod(operationName = "GetDokumenManual_OnDemand", action = "http://services.beacukai.go.id/GetDokumenManual_OnDemand") @WebResult(name = "GetDokumenManual_OnDemandResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "GetDokumenManual_OnDemand", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetDokumenManual_OnDemand") @ResponseWrapper(localName = "GetDokumenManual_OnDemandResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetDokumenManual_OnDemandResponse") public String getDokumenManualOnDemand( @WebParam(name = "UserName", targetNamespace = "http://services.beacukai.go.id/") String userName, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password, @WebParam(name = "KdDok", targetNamespace = "http://services.beacukai.go.id/") String kdDok, @WebParam(name = "NoDok", targetNamespace = "http://services.beacukai.go.id/") String noDok, @WebParam(name = "TglDok", targetNamespace = "http://services.beacukai.go.id/") String tglDok); /** * Fungsi untuk mendownload data barang yang terkena SPJM dengan parameter KD TPS * * @param kdTps * @param userName * @param password * @return * returns java.lang.String */ @WebMethod(operationName = "GetSPJM", action = "http://services.beacukai.go.id/GetSPJM") @WebResult(name = "GetSPJMResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "GetSPJM", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetSPJM") @ResponseWrapper(localName = "GetSPJMResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetSPJMResponse") public String getSPJM( @WebParam(name = "UserName", targetNamespace = "http://services.beacukai.go.id/") String userName, @WebParam(name = "<PASSWORD>", targetNamespace = "http://services.beacukai.go.id/") String password, @WebParam(name = "Kd_Tps", targetNamespace = "http://services.beacukai.go.id/") String kdTps); /** * Fungsi untuk mendownload data barang yang terkena SPJM dengan filter No.PIB dan Tgl. PIB format ddmmyyyy * * @param userName * @param tglPib * @param password * @param noPib * @return * returns java.lang.String */ @WebMethod(operationName = "GetSPJM_onDemand", action = "http://services.beacukai.go.id/GetSPJM_onDemand") @WebResult(name = "GetSPJM_onDemandResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "GetSPJM_onDemand", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetSPJM_OnDemand") @ResponseWrapper(localName = "GetSPJM_onDemandResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetSPJM_OnDemandResponse") public String getSPJMOnDemand( @WebParam(name = "UserName", targetNamespace = "http://services.beacukai.go.id/") String userName, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password, @WebParam(name = "noPib", targetNamespace = "http://services.beacukai.go.id/") String noPib, @WebParam(name = "tglPib", targetNamespace = "http://services.beacukai.go.id/") String tglPib); /** * Fungsi untuk cek jumlah data yang terkirim (Format tanggal : dd-mm-yyyy) * * @param userName * @param tglAwal * @param password * @param tglAkhir * @return * returns java.lang.String */ @WebMethod(operationName = "CekDataTerkirim", action = "http://services.beacukai.go.id/CekDataTerkirim") @WebResult(name = "CekDataTerkirimResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "CekDataTerkirim", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.CekDataTerkirim") @ResponseWrapper(localName = "CekDataTerkirimResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.CekDataTerkirimResponse") public String cekDataTerkirim( @WebParam(name = "UserName", targetNamespace = "http://services.beacukai.go.id/") String userName, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password, @WebParam(name = "Tgl_Awal", targetNamespace = "http://services.beacukai.go.id/") String tglAwal, @WebParam(name = "Tgl_Akhir", targetNamespace = "http://services.beacukai.go.id/") String tglAkhir); /** * Fungsi untuk cek jumlah data SPPB berdasarkan tanggal sppb tertentu (Format tanggal : dd-mm-yyyy) * * @param tglSPPB * @param userName * @param <PASSWORD> * @return * returns java.lang.String */ @WebMethod(operationName = "CekDataSPPB", action = "http://services.beacukai.go.id/CekDataSPPB") @WebResult(name = "CekDataSPPBResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "CekDataSPPB", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.CekDataSPPB") @ResponseWrapper(localName = "CekDataSPPBResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.CekDataSPPBResponse") public String cekDataSPPB( @WebParam(name = "UserName", targetNamespace = "http://services.beacukai.go.id/") String userName, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password, @WebParam(name = "Tgl_SPPB", targetNamespace = "http://services.beacukai.go.id/") String tglSPPB); /** * Fungsi untuk cek jumlah data yang gagal terkirim (Format tanggal : dd-mm-yyyy) * * @param userName * @param tglAwal * @param password * @param tglAkhir * @return * returns java.lang.String */ @WebMethod(operationName = "CekDataGagalKirim", action = "http://services.beacukai.go.id/CekDataGagalKirim") @WebResult(name = "CekDataGagalKirimResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "CekDataGagalKirim", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.CekDataGagalKirim") @ResponseWrapper(localName = "CekDataGagalKirimResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.CekDataGagalKirimResponse") public String cekDataGagalKirim( @WebParam(name = "UserName", targetNamespace = "http://services.beacukai.go.id/") String userName, @WebParam(name = "<PASSWORD>", targetNamespace = "http://services.beacukai.go.id/") String password, @WebParam(name = "Tgl_Awal", targetNamespace = "http://services.beacukai.go.id/") String tglAwal, @WebParam(name = "Tgl_Akhir", targetNamespace = "http://services.beacukai.go.id/") String tglAkhir); /** * Fungsi untuk cek data NPE, filter yang digunakan adalah NPWP Eksportir, nomor NPE dan tanggal NPE, format tanggal #ddmmyyyy# * * @param noNpe * @param userName * @param npwpEks * @param password * @param tglNpe * @return * returns java.lang.String */ @WebMethod(operationName = "CekNPE", action = "http://services.beacukai.go.id/CekNPE") @WebResult(name = "CekNPEResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "CekNPE", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.CekNPE") @ResponseWrapper(localName = "CekNPEResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.CekNPEResponse") public String cekNPE( @WebParam(name = "UserName", targetNamespace = "http://services.beacukai.go.id/") String userName, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password, @WebParam(name = "NPWP_Eks", targetNamespace = "http://services.beacukai.go.id/") String npwpEks, @WebParam(name = "No_Npe", targetNamespace = "http://services.beacukai.go.id/") String noNpe, @WebParam(name = "Tgl_Npe", targetNamespace = "http://services.beacukai.go.id/") String tglNpe); /** * Fungsi untuk mendownload data SPPB BC23, filter yang digunakan adalah tanggal SPPB, nomor SPPB dan NPWP, format tanggal #ddmmyyyy# * * @param npwpImp * @param noSppb * @param userName * @param tglSppb * @param password * @return * returns java.lang.String */ @WebMethod(operationName = "GetSppb_Bc23", action = "http://services.beacukai.go.id/GetSppb_Bc23") @WebResult(name = "GetSppb_Bc23Result", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "GetSppb_Bc23", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetSppb_Bc23") @ResponseWrapper(localName = "GetSppb_Bc23Response", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetSppb_Bc23Response") public String getSppbBc23( @WebParam(name = "UserName", targetNamespace = "http://services.beacukai.go.id/") String userName, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password, @WebParam(name = "No_Sppb", targetNamespace = "http://services.beacukai.go.id/") String noSppb, @WebParam(name = "Tgl_Sppb", targetNamespace = "http://services.beacukai.go.id/") String tglSppb, @WebParam(name = "NPWP_Imp", targetNamespace = "http://services.beacukai.go.id/") String npwpImp); /** * Fungsi untuk mendownload data SPPB, filter yang digunakan adalah kode Gudang * * @param kdGudang * @param userName * @param password * @return * returns java.lang.String */ @WebMethod(operationName = "GetBC23Permit", action = "http://services.beacukai.go.id/GetBC23Permit") @WebResult(name = "GetBC23PermitResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "GetBC23Permit", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetBC23Permit") @ResponseWrapper(localName = "GetBC23PermitResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetBC23PermitResponse") public String getBC23Permit( @WebParam(name = "UserName", targetNamespace = "http://services.beacukai.go.id/") String userName, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password, @WebParam(name = "Kd_Gudang", targetNamespace = "http://services.beacukai.go.id/") String kdGudang); /** * Fungsi untuk mendownload data SPPB, filter yang digunakan adalah kode ASP * * @param userName * @param kdASP * @param password * @return * returns java.lang.String */ @WebMethod(operationName = "GetBC23Permit_FASP", action = "http://services.beacukai.go.id/GetBC23Permit_FASP") @WebResult(name = "GetBC23Permit_FASPResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "GetBC23Permit_FASP", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetBC23Permit_FASP") @ResponseWrapper(localName = "GetBC23Permit_FASPResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetBC23Permit_FASPResponse") public String getBC23PermitFASP( @WebParam(name = "UserName", targetNamespace = "http://services.beacukai.go.id/") String userName, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password, @WebParam(name = "Kd_ASP", targetNamespace = "http://services.beacukai.go.id/") String kdASP); /** * Fungsi untuk mendownload data SPPB BC12, filter yang digunakan adalah kode TPS ASAL * * @param kdAsp * @param userName * @param password * @return * returns java.lang.String */ @WebMethod(operationName = "GetSPPB12_TPSAsal", action = "http://services.beacukai.go.id/GetSPPB12_TPSAsal") @WebResult(name = "GetSPPB12_TPSAsalResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "GetSPPB12_TPSAsal", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetSPPB12_TPSAsal") @ResponseWrapper(localName = "GetSPPB12_TPSAsalResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetSPPB12_TPSAsalResponse") public String getSPPB12TPSAsal( @WebParam(name = "UserName", targetNamespace = "http://services.beacukai.go.id/") String userName, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password, @WebParam(name = "Kd_asp", targetNamespace = "http://services.beacukai.go.id/") String kdAsp); /** * Fungsi untuk mendownload data SPPB BC12, filter yang digunakan adalah kode TPS Tujuan * * @param kdAsp * @param userName * @param password * @return * returns java.lang.String */ @WebMethod(operationName = "GetSPPB12_TPSTujuan", action = "http://services.beacukai.go.id/GetSPPB12_TPSTujuan") @WebResult(name = "GetSPPB12_TPSTujuanResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "GetSPPB12_TPSTujuan", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetSPPB12_TPSTujuan") @ResponseWrapper(localName = "GetSPPB12_TPSTujuanResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetSPPB12_TPSTujuanResponse") public String getSPPB12TPSTujuan( @WebParam(name = "UserName", targetNamespace = "http://services.beacukai.go.id/") String userName, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password, @WebParam(name = "Kd_asp", targetNamespace = "http://services.beacukai.go.id/") String kdAsp); /** * Fungsi untuk Upload data permohonan BC12 * * @param username * @param fStream * @param password * @return * returns java.lang.String */ @WebMethod(operationName = "PermohonanBC12", action = "http://services.beacukai.go.id/PermohonanBC12") @WebResult(name = "PermohonanBC12Result", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "PermohonanBC12", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.PermohonanBC12") @ResponseWrapper(localName = "PermohonanBC12Response", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.PermohonanBC12Response") public String permohonanBC12( @WebParam(name = "fStream", targetNamespace = "http://services.beacukai.go.id/") String fStream, @WebParam(name = "Username", targetNamespace = "http://services.beacukai.go.id/") String username, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password); /** * Fungsi untuk mendownload data Respon NP4 Bc12 yang sudah diproses, filter yang digunakan adalah kode TPS * * @param kdAsp * @param userName * @param password * @return * returns java.lang.String */ @WebMethod(operationName = "GetResponPenolakanBC12", action = "http://services.beacukai.go.id/GetResponPenolakanBC12") @WebResult(name = "GetResponPenolakanBC12Result", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "GetResponPenolakanBC12", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetResponPenolakanBC12") @ResponseWrapper(localName = "GetResponPenolakanBC12Response", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetResponPenolakanBC12Response") public String getResponPenolakanBC12( @WebParam(name = "UserName", targetNamespace = "http://services.beacukai.go.id/") String userName, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password, @WebParam(name = "Kd_asp", targetNamespace = "http://services.beacukai.go.id/") String kdAsp); /** * Fungsi untuk Upload data permohonan PLP * * @param username * @param fStream * @param password * @return * returns java.lang.String */ @WebMethod(operationName = "PermohonanPLP", action = "http://services.beacukai.go.id/PermohonanPLP") @WebResult(name = "PermohonanPLPResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "PermohonanPLP", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.PermohonanPLP") @ResponseWrapper(localName = "PermohonanPLPResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.PermohonanPLPResponse") public String permohonanPLP( @WebParam(name = "fStream", targetNamespace = "http://services.beacukai.go.id/") String fStream, @WebParam(name = "Username", targetNamespace = "http://services.beacukai.go.id/") String username, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password); /** * Fungsi untuk Upload data permohonan PLP * * @param username * @param fStream * @param password * @return * returns java.lang.String */ @WebMethod(operationName = "UploadMohonPLP", action = "http://services.beacukai.go.id/UploadMohonPLP") @WebResult(name = "UploadMohonPLPResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "UploadMohonPLP", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.UploadMohonPLP") @ResponseWrapper(localName = "UploadMohonPLPResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.UploadMohonPLPResponse") public String uploadMohonPLP( @WebParam(name = "fStream", targetNamespace = "http://services.beacukai.go.id/") String fStream, @WebParam(name = "Username", targetNamespace = "http://services.beacukai.go.id/") String username, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password); /** * Fungsi untuk Upload data pembatalan PLP * * @param username * @param fStream * @param password * @return * returns java.lang.String */ @WebMethod(operationName = "UploadBatalPLP", action = "http://services.beacukai.go.id/UploadBatalPLP") @WebResult(name = "UploadBatalPLPResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "UploadBatalPLP", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.UploadBatalPLP") @ResponseWrapper(localName = "UploadBatalPLPResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.UploadBatalPLPResponse") public String uploadBatalPLP( @WebParam(name = "fStream", targetNamespace = "http://services.beacukai.go.id/") String fStream, @WebParam(name = "Username", targetNamespace = "http://services.beacukai.go.id/") String username, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password); /** * Fungsi untuk mendownload data Respon PLP yang sudah diproses, filter yang digunakan adalah kode TPS * * @param kdAsp * @param userName * @param password * @return * returns java.lang.String */ @WebMethod(operationName = "GetResponPLP", action = "http://services.beacukai.go.id/GetResponPLP") @WebResult(name = "GetResponPLPResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "GetResponPLP", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetResponPLP") @ResponseWrapper(localName = "GetResponPLPResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetResponPLPResponse") public String getResponPLP( @WebParam(name = "UserName", targetNamespace = "http://services.beacukai.go.id/") String userName, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password, @WebParam(name = "Kd_asp", targetNamespace = "http://services.beacukai.go.id/") String kdAsp); /** * Fungsi untuk mendownload data Respon PLP yang sudah disetujui, oleh TPS Tujuan, filter yang digunakan adalah kode TPS * * @param kdAsp * @param userName * @param password * @return * returns java.lang.String */ @WebMethod(operationName = "GetResponPLPTujuan", action = "http://services.beacukai.go.id/GetResponPLPTujuan") @WebResult(name = "GetResponPLPTujuanResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "GetResponPLPTujuan", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetResponPLPTujuan") @ResponseWrapper(localName = "GetResponPLPTujuanResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetResponPLPTujuanResponse") public String getResponPLPTujuan( @WebParam(name = "UserName", targetNamespace = "http://services.beacukai.go.id/") String userName, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password, @WebParam(name = "Kd_asp", targetNamespace = "http://services.beacukai.go.id/") String kdAsp); /** * Fungsi untuk mendownload data Respon PLP yang sudah disetujui, oleh TPS Tujuan, filter yang digunakan adalah kode TPS * * @param kdAsp * @param userName * @param password * @return * returns java.lang.String */ @WebMethod(operationName = "GetResponPLP_Tujuan", action = "http://services.beacukai.go.id/GetResponPLP_Tujuan") @WebResult(name = "GetResponPLP_TujuanResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "GetResponPLP_Tujuan", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetResponPLP_Tujuan") @ResponseWrapper(localName = "GetResponPLP_TujuanResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetResponPLP_TujuanResponse") public String getResponPLP_Tujuan( @WebParam(name = "UserName", targetNamespace = "http://services.beacukai.go.id/") String userName, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password, @WebParam(name = "Kd_asp", targetNamespace = "http://services.beacukai.go.id/") String kdAsp); /** * Fungsi untuk mengambil data persetujuan pembatalan PLP * * @param username * @param kdAsp * @param password * @return * returns java.lang.String */ @WebMethod(operationName = "GetResponBatalPLP", action = "http://services.beacukai.go.id/GetResponBatalPLP") @WebResult(name = "GetResponBatalPLPResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "GetResponBatalPLP", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetResponBatalPLP") @ResponseWrapper(localName = "GetResponBatalPLPResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetResponBatalPLPResponse") public String getResponBatalPLP( @WebParam(name = "Username", targetNamespace = "http://services.beacukai.go.id/") String username, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password, @WebParam(name = "Kd_asp", targetNamespace = "http://services.beacukai.go.id/") String kdAsp); /** * Fungsi untuk mengambil data persetujuan pembatalan PLP * * @param username * @param kdAsp * @param password * @return * returns java.lang.String */ @WebMethod(operationName = "GetResponBatalPLPTujuan", action = "http://services.beacukai.go.id/GetResponBatalPLPTujuan") @WebResult(name = "GetResponBatalPLPTujuanResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "GetResponBatalPLPTujuan", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetResponBatalPLPTujuan") @ResponseWrapper(localName = "GetResponBatalPLPTujuanResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetResponBatalPLPTujuanResponse") public String getResponBatalPLPTujuan( @WebParam(name = "Username", targetNamespace = "http://services.beacukai.go.id/") String username, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password, @WebParam(name = "Kd_asp", targetNamespace = "http://services.beacukai.go.id/") String kdAsp); /** * Fungsi untuk mendownload data NPE berdasarkan No.NPE, NPWP Eksportir dan Kode Kantor * * @param kdKantor * @param userName * @param noPE * @param password * @param npwp * @return * returns java.lang.String */ @WebMethod(operationName = "GetEksporPermit_FNPE", action = "http://services.beacukai.go.id/GetEksporPermit_FNPE") @WebResult(name = "GetEksporPermit_FNPEResult", targetNamespace = "http://services.beacukai.go.id/") @RequestWrapper(localName = "GetEksporPermit_FNPE", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetEksporPermit_FNPE") @ResponseWrapper(localName = "GetEksporPermit_FNPEResponse", targetNamespace = "http://services.beacukai.go.id/", className = "id.go.beacukai.services.GetEksporPermit_FNPEResponse") public String getEksporPermitFNPE( @WebParam(name = "UserName", targetNamespace = "http://services.beacukai.go.id/") String userName, @WebParam(name = "Password", targetNamespace = "http://services.beacukai.go.id/") String password, @WebParam(name = "No_PE", targetNamespace = "http://services.beacukai.go.id/") String noPE, @WebParam(name = "npwp", targetNamespace = "http://services.beacukai.go.id/") String npwp, @WebParam(name = "kdKantor", targetNamespace = "http://services.beacukai.go.id/") String kdKantor); } <file_sep>/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.edii.generatefile; import com.edii.db.Db; import com.edii.tools.Tanggalan; import DatabaseGenerator.DatabaseOracle; import XMLGenerator.GeneratorXML; import com.edii.operation.db.operation; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.logging.LogFactory; import File.TXT.CreateFile; import java.io.File; /** * * @author <NAME> */ public class GenerateResponPLP_Tujuan_Tes { String table = ""; String colomn = ""; String value = ""; String query = ""; GeneratorXML gx = null; static org.apache.commons.logging.Log logger = LogFactory.getLog(Db.class); private static final String PROPERTIES_FILE = "db.properties"; private static final Properties PROPERTIES = new Properties(); DatabaseOracle dbO = null; static { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream propertiesFile = classLoader.getResourceAsStream(PROPERTIES_FILE); if (propertiesFile == null) { logger.debug("Properties file '" + PROPERTIES_FILE + "' is missing in classpath."); } try { PROPERTIES.load(propertiesFile); } catch (IOException e) { logger.debug("Cannot load properties file '" + PROPERTIES_FILE + "'." + e.getMessage()); } } private void OpenConnection() throws ClassNotFoundException { dbO = new DatabaseOracle(); dbO.connectDatabase(PROPERTIES.getProperty("db.host"), PROPERTIES.getProperty("db.SID"), PROPERTIES.getProperty("db.username"), PROPERTIES.getProperty("db.password")); } public String excute(String outboxDir, String kdAsp) throws Exception { CreateFile cf = null; Tanggalan tg = null; //DOK PLP Element Header String RESPONID = null; String result = null; ArrayList<String> list = new ArrayList<>(); try { OpenConnection(); } catch (ClassNotFoundException ex) { Logger.getLogger(operation.class.getName()).log(Level.SEVERE, null, ex); } //GET HEADER colomn = "RESPONID,KD_KANTOR,KD_TPS,KD_TPS_ASAL,NO_PLP,TGL_PLP," + "NAMA_KAPAL,NO_VOYAGE,CALL_SIGN, TGL_TIBA , GUDANG_TUJUAN,NO_BC11, " + "TGL_BC11, NO_SURAT,TGL_SURAT "; query = "SELECT RESPONID,KD_KANTOR,KD_TPS,KD_TPS_ASAL,NO_PLP,TO_CHAR(TGL_PLP,'YYYYMMDD') AS TGL_PLP," + "NAMA_KAPAL,NO_VOYAGE,CALL_SIGN,TO_CHAR(TGL_TIBA,'YYYYMMDD') AS TGL_TIBA , GUDANG_TUJUAN,NO_BC11, " + "TO_CHAR(TGL_BC11,'YYYYMMDD') AS TGL_BC11, NO_SURAT, TO_CHAR(TGL_SURAT,'YYYYMMDD') AS TGL_SURAT " + "FROM T_PLP_TES WHERE FL_SEND = '0' AND KD_TPS = '" + kdAsp + "'"; try { cf = new CreateFile(); tg = new Tanggalan(); gx = new GeneratorXML("DOCUMENT", ""); gx.addXML("DOCUMENT", "RESPONPLP", ""); list = dbO.query_select_raw(colomn, query); try { if (!list.isEmpty()) { RESPONID = list.get(0).split("#")[0].split(":")[1]; gx.addXML("RESPONPLP", "HEADER", list.get(0).replace("#", ",")); gx.addXML("RESPONPLP", "DETIL", ""); //GET CONT colomn = "NO_CONT,UK_CONT,JNS_CONT,NO_POS_BC11,CONSIGNEE, NO_BL_AWB, TGL_BL_AWB"; query = "SELECT NO_CONT,UK_CONT,JNS_CONT,NO_POS_BC11,CONSIGNEE, NO_BL_AWB, TO_CHAR(TGL_BL_AWB,'YYYYMMDD') AS TGL_BL_AWB FROM T_PLP_CONT_TES WHERE RESPONID = '" + RESPONID + "'"; list = dbO.query_select_raw(colomn, query); for (String isi_list : list) { gx.addXML("DETIL", "CONT", isi_list.replace("#", ",")); } //GET KMS colomn = "JNS_KMS,JML_KMS,NO_BL,TGL_BL_AWB"; query = "SELECT JNS_KMS,JML_KMS,NO_BL,TO_CHAR(TGL_BL,'YYYYMMDD') FROM T_PLP_KMS WHERE RESPONID = '" + RESPONID + "'"; list = dbO.query_select_raw(colomn, query); for (String isi_list : list) { gx.addXML("DETIL", "KMS", isi_list.replace("#", ",")); } } if (!gx.getStringxml().isEmpty()) { table = "T_PLP_TES"; colomn = "FL_SEND,DATE_SEND"; value = "1,"+getCurrentTimeStamp(); String colwhere = "RESPONID = ,FL_SEND ="; String valwhere = RESPONID+",0"; if (dbO.query_update_with_where(table, colomn, value, colwhere, valwhere, "AND")) { String filename = RESPONID + "_T_PLP_TES_" + tg.UNIXNUMBER() + ".xml"; if (cf.newFile(outboxDir + File.separator, filename, gx.getStringxml())) { result = gx.getStringxml(); } } // query = "UPDATE T_PLP_TES SET FL_SEND = ? , DATE_SEND = ? WHERE RESPONID = ? AND FL_SEND = ?"; // preparedStatement = mydb.preparedstmt(query); // preparedStatement.setString(1, "1"); // preparedStatement.setDate(2, getCurrentTimeStamp()); // preparedStatement.setString(3, RESPONID); // preparedStatement.setString(4, "0"); // mydb.execute("commit"); } } catch (Exception e) { System.out.println("message" + e.getMessage()); } return result; } catch (Exception e) { System.out.println("message nian" + e.getMessage()); return result; } finally { list.clear(); } } private static java.sql.Date getCurrentTimeStamp() { java.util.Date today = new java.util.Date(); return new java.sql.Date(today.getTime()); } public static void main(String[] args) throws Exception { GenerateResponPLP_Tujuan_Tes tes = new GenerateResponPLP_Tujuan_Tes(); String r = tes.excute("D://DATA", "KOJA"); System.out.println(r); } } <file_sep> package id.go.beacukai.services; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="GantiPasswordResult" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "gantiPasswordResult" }) @XmlRootElement(name = "GantiPasswordResponse") public class GantiPasswordResponse { @XmlElement(name = "GantiPasswordResult") protected String gantiPasswordResult; /** * Gets the value of the gantiPasswordResult property. * * @return * possible object is * {@link String } * */ public String getGantiPasswordResult() { return gantiPasswordResult; } /** * Sets the value of the gantiPasswordResult property. * * @param value * allowed object is * {@link String } * */ public void setGantiPasswordResult(String value) { this.gantiPasswordResult = value; } } <file_sep> package id.go.beacukai.services; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="GetImporPermit_FASPResult" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "getImporPermit_FASPResult" }) @XmlRootElement(name = "GetImporPermit_FASPResponse") public class GetImporPermit_FASPResponse { @XmlElement(name = "GetImporPermit_FASPResult") protected String getImporPermit_FASPResult; /** * Gets the value of the getImporPermit_FASPResult property. * * @return * possible object is * {@link String } * */ public String getGetImporPermit_FASPResult() { return getImporPermit_FASPResult; } /** * Sets the value of the getImporPermit_FASPResult property. * * @param value * allowed object is * {@link String } * */ public void setGetImporPermit_FASPResult(String value) { this.getImporPermit_FASPResult = value; } } <file_sep> package id.go.beacukai.services; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="CoCoKms_TesResult" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "coCoKms_TesResult" }) @XmlRootElement(name = "CoCoKms_TesResponse") public class CoCoKms_TesResponse { @XmlElement(name = "CoCoKms_TesResult") protected String coCoKms_TesResult; /** * Gets the value of the coCoKms_TesResult property. * * @return * possible object is * {@link String } * */ public String getCoCoKms_TesResult() { return coCoKms_TesResult; } /** * Sets the value of the coCoKms_TesResult property. * * @param value * allowed object is * {@link String } * */ public void setCoCoKms_TesResult(String value) { this.coCoKms_TesResult = value; } } <file_sep>/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.edii.model; /** * * @author <NAME> */ public class ModelLog { private String user; private String nama_class; private String refNumber; private String jnsDok; private String Dok; public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getNama_class() { return nama_class; } public void setNama_class(String nama_class) { this.nama_class = nama_class; } public String getRefNumber() { return refNumber; } public void setRefNumber(String refNumber) { this.refNumber = refNumber; } public String getJnsDok() { return jnsDok; } public void setJnsDok(String jnsDok) { this.jnsDok = jnsDok; } public String getDok() { return Dok; } public void setDok(String Dok) { this.Dok = Dok; } } <file_sep>/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.edii.db; //import com.edii.tools.ExcuteProses; import java.sql.Connection; import java.sql.ResultSet; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.Clob; import java.sql.Statement; import java.sql.CallableStatement; import java.util.Calendar; import java.io.OutputStream; import java.io.InputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.ByteArrayInputStream; import javax.sql.DataSource; import javax.naming.InitialContext; import javax.naming.Context; import oracle.sql.BLOB; import oracle.sql.CLOB; import oracle.jdbc.OracleResultSet; import oracle.jdbc.driver.OracleDriver; public class ConnDbOrcl { private boolean process = true; public boolean getProcessValue() { return this.process; } public Connection connect(String host, String port, String sid, String user, String pswd, boolean autoCommit) throws Exception { Connection conn = null; boolean stsconn = false; int maxtry = 0; try { while ((!stsconn) && (maxtry < 5)) { try { Thread.currentThread().sleep(100); DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); conn = DriverManager.getConnection("jdbc:oracle:thin:@" + host + ":" + port + ":" + sid, user, pswd); conn.setAutoCommit(autoCommit); stsconn = true; maxtry = 777; } catch (Exception e) { stsconn = false; close(conn); conn = null; } maxtry += 1; } } catch (Exception e) { conn = null; } finally { stsconn = false; maxtry = 0; } return conn; } public Connection jndiconnect(String jndi, boolean autoCommit) throws Exception { Connection conn = null; try { conn = getDataSource(jndi).getConnection(); conn.setAutoCommit(autoCommit); } catch (Exception e) { conn = null; } return conn; } private DataSource getDataSource(String jndi) throws Exception { DataSource ds = null; Context ic = null; try { ic = new InitialContext(); ds = (DataSource) ic.lookup(jndi); } catch (Exception e) { ds = null; } finally { ic = null; } return ds; } public ResultSet execute(Connection conn, String sql) throws Exception { // ExcuteProses exc = new ExcuteProses(); ResultSet rs = null; try { rs = conn.createStatement().executeQuery(sql); } catch (Exception e) { //err.mailError("SQL: " + sql, e.getStackTrace()); System.out.println("SQL: " + sql); e.printStackTrace(); // exc.ExcuteError(e.getMessage(), "SQL", ""); this.process = false; rs = null; } return rs; } public String getString(ResultSet rs, int s) throws Exception { String temp = null; try { temp = ""; temp = rs.getString(s); } catch (Exception e) { temp = null; } return (temp == null) ? "" : temp; } public String getString(ResultSet rs, int s, String d) throws Exception { String temp = null; try { temp = ""; temp = rs.getString(s); } catch (Exception e) { temp = null; } return (temp == null) ? d : temp; } public String getString(ResultSet rs, String s) throws Exception { String temp = null; try { temp = ""; temp = rs.getString(s); } catch (Exception e) { temp = null; } return (temp == null) ? "" : temp; } public String getString(ResultSet rs, String s, String d) throws Exception { String temp = null; try { temp = rs.getString(s); } catch (Exception e) { temp = null; } return (temp == null) ? d : temp; } public PreparedStatement preparedstmt(Connection conn, String stmt) { PreparedStatement tmpstmt = null; try { tmpstmt = conn.prepareStatement(stmt); } catch (Exception e) { tmpstmt = null; } return tmpstmt; } public CLOB createCLOB(Connection conn) { CLOB tempCLOB = null; try { conn.setAutoCommit(false); tempCLOB = CLOB.createTemporary(conn, true, CLOB.DURATION_SESSION); tempCLOB.open(CLOB.MODE_READWRITE); } catch (Exception e) { tempCLOB = null; } return tempCLOB; } public boolean insertBLOB(Connection conn, String sqlCommand, String filePath) throws IOException { boolean retVal = true; Statement stmt = null; ResultSet rs = null; BLOB blob = null; OutputStream os = null; InputStream is = null; File file = null; byte[] buffer = null; try { stmt = conn.createStatement(); rs = stmt.executeQuery(sqlCommand + " FOR UPDATE"); if (rs.next()) { blob = ((OracleResultSet) rs).getBLOB(1); os = blob.getBinaryOutputStream(); file = new File(filePath); is = new FileInputStream(file); buffer = new byte[blob.getBufferSize()]; int bytesRead = 0; while ((bytesRead = is.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } } else { retVal = false; } } catch (Exception e) { retVal = false; } finally { try { rs.close(); stmt.close(); } catch (Exception e) { } finally { os.flush(); rs = null; stmt = null; blob = null; os = null; is = null; file = null; buffer = null; } } return retVal; } public boolean insertBLOBString(Connection conn, String sqlCommand, String tempString) throws IOException { boolean retVal = true; Statement stmt = null; ResultSet rs = null; BLOB blob = null; OutputStream os = null; ByteArrayInputStream is = null; byte[] tempByte = null; byte[] buffer = null; try { stmt = conn.createStatement(); rs = stmt.executeQuery(sqlCommand + " FOR UPDATE"); if (rs.next()) { blob = ((OracleResultSet) rs).getBLOB(1); os = blob.getBinaryOutputStream(); tempByte = tempString.getBytes(); is = new ByteArrayInputStream(tempByte); buffer = new byte[blob.getBufferSize()]; int bytesRead = 0; while ((bytesRead = is.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } } else { retVal = false; } } catch (Exception e) { retVal = false; } finally { try { rs.close(); stmt.close(); os.flush(); } catch (Exception e) { } finally { rs = null; stmt = null; blob = null; os = null; is = null; buffer = null; } } return retVal; } public BLOB getBLOB(ResultSet rs, String s) throws Exception { BLOB temp = null; try { temp = ((OracleResultSet) rs).getBLOB(s); } catch (Exception e) { temp = null; } return (temp == null) ? null : temp; } public BLOB getBLOB(ResultSet rs, int s) throws Exception { BLOB temp = null; try { temp = ((OracleResultSet) rs).getBLOB(s); } catch (Exception e) { temp = null; } return (temp == null) ? null : temp; } public Clob getClob(ResultSet rs, String s) throws Exception { Clob temp = null; try { temp = rs.getClob(s); } catch (Exception e) { temp = null; } return (temp == null) ? null : temp; } public Clob getClob(ResultSet rs, int s) throws Exception { Clob temp = null; try { temp = rs.getClob(s); } catch (Exception e) { temp = null; } return (temp == null) ? null : temp; } public int getInt(ResultSet rs, int s) throws Exception { int temp = 0; try { temp = rs.getInt(s); } catch (Exception e) { temp = 0; } return temp; } public int getInt(ResultSet rs, String s) throws Exception { int temp = 0; try { temp = rs.getInt(s); } catch (Exception e) { temp = 0; } return temp; } public long getLong(ResultSet rs, int s) throws Exception { long temp = 0; try { temp = rs.getLong(s); } catch (Exception e) { temp = 0; } return temp; } public long getLong(ResultSet rs, String s) throws Exception { long temp = 0; try { temp = rs.getLong(s); } catch (Exception e) { temp = 0; } return temp; } public java.util.Date getDate(ResultSet rs, int s) throws Exception { java.util.Date temp = null; try { temp = rs.getDate(s); if (temp.equals(null)) { temp = Calendar.getInstance().getTime(); } } catch (Exception e) { temp = null; } return temp; } public java.util.Date getDate(ResultSet rs, String s) throws Exception { java.util.Date temp = null; try { temp = rs.getTimestamp(s); if (temp == null) { temp = Calendar.getInstance().getTime(); } } catch (Exception e) { temp = null; } return temp; } public void commit(Connection conn) throws Exception { try { conn.commit(); } catch (Exception e) { // } } public void rollback(Connection conn) throws Exception { try { conn.rollback(); } catch (Exception e) { // } } public void close(Connection conn) throws Exception { try { conn.close(); } catch (Exception e) { conn = null; } finally { conn = null; } } public boolean next(ResultSet rs) throws Exception { return rs.next(); } public boolean previous(ResultSet rs) throws Exception { return rs.previous(); } public boolean absolute(ResultSet rs, int row) throws Exception { return rs.absolute(row); } public double getDouble(ResultSet rs, int s) throws Exception { double temp = 0; try { temp = rs.getDouble(s); } catch (Exception e) { temp = 0; } return temp; } public double getDouble(ResultSet rs, String s) throws Exception { double temp = 0; try { temp = rs.getDouble(s); } catch (Exception e) { temp = 0; } return temp; } public CallableStatement getCallableStatement(Connection conn, String s) throws Exception { CallableStatement temp = null; try { temp = conn.prepareCall(s); } catch (Exception e) { temp = null; } return temp; } public String executeError(Connection conn, String sql) throws Exception { ResultSet rs = null; String error = null; try { rs = conn.createStatement().executeQuery(sql); } catch (Exception e) { //err.mailError("SQL: " + sql, e.getStackTrace()); System.out.println("SQL: " + sql); e.printStackTrace(); this.process = false; rs = null; error = e.getMessage().toString(); } return error; } } <file_sep>/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.edii.model; /** * * @author <NAME> */ public class ModelGetResponPLP { //DOK RESPON PLP Element Header String kd_kantor = null; String kd_tps = null; String ref_number = null; String no_plp = null; String tgl_plp = null; String alasan_reject = null; //DOK RESPON Element Dtl KMS String jns_kms = null; String jml_kms = null; String no_bl_awb = null; String tgl_bl_awb = null; String fl_setuju_kms = null; //DOK RESPON Element Dtl CONT String no_cont = null; String uk_cont = null; String fl_setuju_cont = null; String jns_cont = null; public String getKd_kantor() { return kd_kantor; } public void setKd_kantor(String kd_kantor) { this.kd_kantor = kd_kantor; } public String getKd_tps() { return kd_tps; } public void setKd_tps(String kd_tps) { this.kd_tps = kd_tps; } public String getRef_number() { return ref_number; } public void setRef_number(String ref_number) { this.ref_number = ref_number; } public String getNo_plp() { return no_plp; } public void setNo_plp(String no_plp) { this.no_plp = no_plp; } public String getTgl_plp() { return tgl_plp; } public void setTgl_plp(String tgl_plp) { this.tgl_plp = tgl_plp; } public String getAlasan_reject() { return alasan_reject; } public void setAlasan_reject(String alasan_reject) { this.alasan_reject = alasan_reject; } public String getJns_kms() { return jns_kms; } public void setJns_kms(String jns_kms) { this.jns_kms = jns_kms; } public String getJml_kms() { return jml_kms; } public void setJml_kms(String jml_kms) { this.jml_kms = jml_kms; } public String getNo_bl_awb() { return no_bl_awb; } public void setNo_bl_awb(String no_bl_awb) { this.no_bl_awb = no_bl_awb; } public String getTgl_bl_awb() { return tgl_bl_awb; } public void setTgl_bl_awb(String tgl_bl_awb) { this.tgl_bl_awb = tgl_bl_awb; } public String getFl_setuju_kms() { return fl_setuju_kms; } public void setFl_setuju_kms(String fl_setuju_kms) { this.fl_setuju_kms = fl_setuju_kms; } public String getNo_cont() { return no_cont; } public void setNo_cont(String no_cont) { this.no_cont = no_cont; } public String getUk_cont() { return uk_cont; } public void setUk_cont(String uk_cont) { this.uk_cont = uk_cont; } public String getFl_setuju_cont() { return fl_setuju_cont; } public void setFl_setuju_cont(String fl_setuju_cont) { this.fl_setuju_cont = fl_setuju_cont; } public String getJns_cont() { return jns_cont; } public void setJns_cont(String jns_cont) { this.jns_cont = jns_cont; } } <file_sep> package id.go.beacukai.services; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="UserName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="Password" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="KdDok" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="NoDok" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="TglDok" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "userName", "password", "kdDok", "noDok", "tglDok" }) @XmlRootElement(name = "GetDokumenManual_OnDemand") public class GetDokumenManual_OnDemand { @XmlElement(name = "UserName") protected String userName; @XmlElement(name = "Password") protected String password; @XmlElement(name = "KdDok") protected String kdDok; @XmlElement(name = "NoDok") protected String noDok; @XmlElement(name = "TglDok") protected String tglDok; /** * Gets the value of the userName property. * * @return * possible object is * {@link String } * */ public String getUserName() { return userName; } /** * Sets the value of the userName property. * * @param value * allowed object is * {@link String } * */ public void setUserName(String value) { this.userName = value; } /** * Gets the value of the password property. * * @return * possible object is * {@link String } * */ public String getPassword() { return password; } /** * Sets the value of the password property. * * @param value * allowed object is * {@link String } * */ public void setPassword(String value) { this.password = value; } /** * Gets the value of the kdDok property. * * @return * possible object is * {@link String } * */ public String getKdDok() { return kdDok; } /** * Sets the value of the kdDok property. * * @param value * allowed object is * {@link String } * */ public void setKdDok(String value) { this.kdDok = value; } /** * Gets the value of the noDok property. * * @return * possible object is * {@link String } * */ public String getNoDok() { return noDok; } /** * Sets the value of the noDok property. * * @param value * allowed object is * {@link String } * */ public void setNoDok(String value) { this.noDok = value; } /** * Gets the value of the tglDok property. * * @return * possible object is * {@link String } * */ public String getTglDok() { return tglDok; } /** * Sets the value of the tglDok property. * * @param value * allowed object is * {@link String } * */ public void setTglDok(String value) { this.tglDok = value; } } <file_sep>/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.edii.xml; import java.io.File; import java.util.ArrayList; import java.util.List; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author aldi */ public class XmlReqsppb { private static final Logger logger = LoggerFactory.getLogger(XmlReqsppb.class); public List<Reqsppb> parseFile(String pathfile) { Document document; String varxml = "/DOCUMENT/"; String varLoop = "/DOCUMENT/SPPB"; SAXReader saxreader; List<Reqsppb> listSppb = new ArrayList<Reqsppb>(); try { saxreader = new SAXReader(); document = saxreader.read(new File(pathfile)); Element root = document.getRootElement(); //System.out.println(root.asXML()); List listLoop = root.selectNodes(varLoop); for (int i = 0; i < listLoop.size(); i++) { Element eloop = (Element) listLoop.get(i); Reqsppb sppb = new Reqsppb(); sppb.setTYPE(getString(eloop, "@tipe")); sppb.setNO_SPPB(getString(eloop, "NO_SPPB")); //2011-07-28 00:00:00.0 String tempTgl = getString(eloop, "TGL_SPPB"); if (tempTgl.length() > 9) { tempTgl = tempTgl.substring(0, 10); tempTgl = tempTgl.replaceAll("-", ""); sppb.setTGL_SPPB(tempTgl.substring(6, 8) + "-" + tempTgl.substring(4, 6) + "-" + tempTgl.substring(0, 4)); } else { sppb.setTGL_SPPB(tempTgl); } sppb.setNPWP_IMP(getString(eloop, "NPWP_IMP")); listSppb.add(sppb); } } catch (Exception e) { logger.error("on method : parseFile(file) " + e.getMessage()); } return listSppb; } public String getString(Element el, String tag) { String result = ""; try { result = el.selectSingleNode(tag).getText(); } catch (NullPointerException npe) { logger.error(" on method : getString(el, tag) " + npe.getMessage()); logger.error(" Check xml tag fot tag " + tag + "in element " + el.asXML()); } catch (Exception e) { logger.error(" on method : getString(el, tag) " + e.getMessage()); } return result; } /* public static void main(String[] args) { // XmlReqsppb req = new XmlReqsppb(); // List<Reqsppb> listsppb = req.parseFile("REQSPPB_07212011105617265.xml"); // System.out.println(listsppb.size()); // for (int i = 0; i < listsppb.size(); i++) { // Reqsppb sppb = listsppb.get(i); // System.out.println(sppb.getTYPE()); // System.out.println(sppb.getNO_SPPB()); // System.out.println(sppb.getTGL_SPPB()); // System.out.println(sppb.getNPWP_IMP()); // } // File files = new File("."); // // String file[] = files.list(); // // for (String File : file) { // System.out.println(File); // logger.info(File); //logger.error(File); //} String tempTgl = "20110728"; System.out.println(tempTgl.substring(6,8)+"-"+tempTgl.substring(4,6)+"-"+tempTgl.substring(0,4)); System.out.println("2011-07-28".replaceAll("-", "")); } */ } <file_sep>/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.edii.tools; import com.edii.db.Db; import java.io.File; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.jdom2.Attribute; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.output.XMLOutputter; /** * * @author <NAME> */ public class GenerateXMLCFS { public String execute(String outboxDir, String kdAsp) throws Exception { Db mydb = null; CreateFile cf = null; Tanggalan tg = null; Document doc = null; Document doc1 = null; Element root = null; Element row = null; Element doclist = null; Element detil = null; // element Header String KD_KANTOR = null; String KD_TPS_ASAL = null; String REF_NUMBER = null; String NO_SURAT_PLP = null; String TGL_SURAT_PLP = null; String GUDANG_ASAL = null; String KD_TPS_TUJUAN = null; String GUDANG_TUJUAN = null; String KD_ALASAN_PLP = null; String CALL_SIGN = null; String NM_ANGKUT = null; String NO_VOY_FLIGHT = null; String TGL_TIBA = null; String NO_BC11 = null; String filename = null; String YOR_ASAL = null; String YOR_TUJUAN = null; String TGL_BC11 = null; String NM_PEMOHON = null; String TIPE_DATA = null; String NO_BATAL_PLP = null; String TGL_BATAL_PLP = null; String ALASAN = null; String filename1 = null; // element Detail Permohonan String NO_CONT = null; String UK_CONT = null; String JNS_KMS = null; String JML_KMS = null; String NO_BL_AWB = null; String TGL_BL_AWB = null; String result = null; String query = null; String ID = null; PreparedStatement preparedStatement = null; query = "SELECT KODE_KANTOR,TIPE_DATA,KODE_TPS_ASAL,REF_NUMBER,NO_PLP," + "TO_CHAR(TGL_PLP,'YYYYMMDD'),KODE_GUDANG_ASAL,KODE_TPS_TUJUAN,KODE_GUDANG_TUJUAN," + "KODE_ALASAN_PLP,YOR_ASAL,YOR_TUJUAN,CALL_SIGN,NAMA_KAPAL,NO_VOYAGE," + "TO_CHAR(TGL_TIBA,'YYYYMMDD'),NO_BC11,TO_CHAR(TGL_BC11,'YYYYMMDD')," + "NAMA_PEMOHON FROM T_REQ_UBAH_STATUS WHERE STATUS = ? AND FL_SEND = ? AND " + "KODE_TPS_ASAL = ?"; ResultSet rs = null; try { mydb = new Db(); cf = new CreateFile(); tg = new Tanggalan(); //Create PLP AJU root = new Element("DOCUMENT","loadplp.xsd"); doc = new Document(root); doclist = new Element("LOADPLP"); // doc = DocumentHelper.createDocument(); // root = doc.addElement("DOCUMENT").addAttribute("xmlns", "loadplp.xsd"); // doclist = root.addElement("LOADPLP"); preparedStatement = mydb.preparedstmt(query); preparedStatement.setString(1, "300"); preparedStatement.setString(2, "0"); preparedStatement.setString(3, kdAsp); rs = preparedStatement.executeQuery(); try { if (rs.next()) { KD_KANTOR = null == rs.getString("KODE_KANTOR") ? "" : rs.getString("KODE_KANTOR"); TIPE_DATA = null == rs.getString("TIPE_DATA") ? "" : rs.getString("TIPE_DATA"); KD_TPS_ASAL = null == rs.getString("KODE_TPS_ASAL") ? "" : rs.getString("KODE_TPS_ASAL"); REF_NUMBER = null == rs.getString("REF_NUMBER") ? "" : rs.getString("REF_NUMBER"); NO_SURAT_PLP = null == rs.getString("NO_PLP") ? "" : rs.getString("NO_PLP"); TGL_SURAT_PLP = null == rs.getString("TO_CHAR(TGL_PLP,'YYYYMMDD')") ? "" : rs.getString("TO_CHAR(TGL_PLP,'YYYYMMDD')"); GUDANG_ASAL = null == rs.getString("KODE_GUDANG_ASAL") ? "" : rs.getString("KODE_GUDANG_ASAL"); KD_TPS_TUJUAN = null == rs.getString("KODE_TPS_TUJUAN") ? "" : rs.getString("KODE_TPS_TUJUAN"); GUDANG_TUJUAN = null == rs.getString("KODE_GUDANG_TUJUAN") ? "" : rs.getString("KODE_GUDANG_TUJUAN"); KD_ALASAN_PLP = null == rs.getString("KODE_ALASAN_PLP") ? "" : rs.getString("KODE_ALASAN_PLP"); YOR_ASAL = null == rs.getString("YOR_ASAL") ? "" : rs.getString("YOR_ASAL"); YOR_TUJUAN = null == rs.getString("YOR_TUJUAN") ? "" : rs.getString("YOR_TUJUAN"); CALL_SIGN = null == rs.getString("CALL_SIGN") ? "" : rs.getString("CALL_SIGN"); NM_ANGKUT = null == rs.getString("NAMA_KAPAL") ? "" : rs.getString("NAMA_KAPAL"); NO_VOY_FLIGHT = null == rs.getString("NO_VOYAGE") ? "" : rs.getString("NO_VOYAGE"); TGL_TIBA = null == rs.getString("TO_CHAR(TGL_TIBA,'YYYYMMDD')") ? "" : rs.getString("TO_CHAR(TGL_TIBA,'YYYYMMDD')"); NO_BC11 = null == rs.getString("NO_BC11") ? "" : rs.getString("NO_BC11"); TGL_BC11 = null == rs.getString("TO_CHAR(TGL_BC11,'YYYYMMDD')") ? "" : rs.getString("TO_CHAR(TGL_BC11,'YYYYMMDD')"); NM_PEMOHON = null == rs.getString("NAMA_PEMOHON") ? "" : rs.getString("NAMA_PEMOHON"); row = new Element("HEADER"); row.addContent(new Element("KD_KANTOR").setText(KD_KANTOR)); row.addContent(new Element("TIPE_DATA").setText(TIPE_DATA)); row.addContent(new Element("KD_TPS_ASAL").setText(KD_TPS_ASAL)); row.addContent(new Element("REF_NUMBER").setText(REF_NUMBER)); row.addContent(new Element("NO_SURAT_PLP").setText(NO_SURAT_PLP)); row.addContent(new Element("TGL_SURAT_PLP").setText(TGL_SURAT_PLP)); row.addContent(new Element("GUDANG_ASAL").setText(GUDANG_ASAL)); row.addContent(new Element("KD_TPS_TUJUAN").setText(KD_TPS_TUJUAN)); row.addContent(new Element("GUDANG_TUJUAN").setText(GUDANG_TUJUAN)); row.addContent(new Element("KD_ALASAN_PLP").setText(KD_ALASAN_PLP)); row.addContent(new Element("YOR_ASAL").setText(YOR_ASAL)); row.addContent(new Element("YOR_TUJUAN").setText(YOR_TUJUAN)); row.addContent(new Element("CALL_SIGN").setText(CALL_SIGN)); row.addContent(new Element("NM_ANGKUT").setText(NM_ANGKUT)); row.addContent(new Element("NO_VOY_FLIGHT").setText(NO_VOY_FLIGHT)); row.addContent(new Element("TGL_TIBA").setText(TGL_TIBA)); row.addContent(new Element("NO_BC11").setText(NO_BC11)); row.addContent(new Element("TGL_BC11").setText(TGL_BC11)); row.addContent(new Element("NM_PEMOHON").setText(NM_PEMOHON)); doclist.addContent(row); //detil = doclist.addElement("DETIL"); detil = new Element("DETIL"); query = "SELECT * FROM T_REQ_UBAH_STATUS_CONT WHERE REF_NUMBER = ?"; preparedStatement = mydb.preparedstmt(query); preparedStatement.setString(1, REF_NUMBER); rs = preparedStatement.executeQuery(); while (rs.next()) { NO_CONT = null == rs.getString("NO_CONT") ? "" : rs.getString("NO_CONT"); UK_CONT = null == rs.getString("UKURAN_CONT") ? "" : rs.getString("UKURAN_CONT"); row = new Element("CONT"); row.addContent(new Element("NO_CONT").setText(NO_CONT)); row.addContent(new Element("UK_CONT").setText(UK_CONT)); detil.addContent(row); } query = "SELECT KODE_KEMASAN,JUMLAH_KEMASAN,NO_BL,TO_CHAR(TGL_BL,'YYYYMMDD') FROM T_REQ_UBAH_STATUS_KMS WHERE REF_NUMBER = ?"; preparedStatement = mydb.preparedstmt(query); preparedStatement.setString(1, REF_NUMBER); rs = preparedStatement.executeQuery(); while (rs.next()) { JNS_KMS = null == rs.getString("KODE_KEMASAN") ? "" : rs.getString("KODE_KEMASAN"); JML_KMS = null == rs.getString("JUMLAH_KEMASAN") ? "" : rs.getString("JUMLAH_KEMASAN"); NO_BL_AWB = null == rs.getString("NO_BL") ? "" : rs.getString("NO_BL"); TGL_BL_AWB = null == rs.getString("TO_CHAR(TGL_BL,'YYYYMMDD')") ? "" : rs.getString("TO_CHAR(TGL_BL,'YYYYMMDD')"); row = new Element("KMS"); row.addContent(new Element("JNS_KMS").setText(JNS_KMS)); row.addContent(new Element("JML_KMS").setText(JML_KMS)); row.addContent(new Element("NO_BL_AWB").setText(NO_BL_AWB)); row.addContent(new Element("TGL_BL_AWB").setText(TGL_BL_AWB)); detil.addContent(row); } } //JDOM2 doclist.addContent(detil); doc.getRootElement().addContent(doclist); String docasXML = new XMLOutputter().outputString(doc); //convert to string if (docasXML.length() > 100) { query = "UPDATE T_REQ_UBAH_STATUS SET STATUS = ?, DATE_SEND = ? , FL_SEND = ? WHERE REF_NUMBER = ? AND FL_SEND = ?"; preparedStatement = mydb.preparedstmt(query); preparedStatement.setString(1, "400"); preparedStatement.setTimestamp(2, getCurrentTimeStamp()); preparedStatement.setString(3, "1"); preparedStatement.setString(4, REF_NUMBER); preparedStatement.setString(5, "0"); mydb.execute("commit"); filename = REF_NUMBER + "_GET_UBAH_STATUS_" + tg.UNIXNUMBER() + ".xml"; if (cf.execute(outboxDir + File.separator + filename)) { cf.content(outboxDir + File.separator + filename, docasXML); result = docasXML; } } } catch (SQLException e) { exc.ExcuteError(e.getMessage(), "execute_class_GenerateXMLCFS", REF_NUMBER); System.out.println("message" + e.getMessage()); } } catch (Exception e) { exc.ExcuteError(e.getMessage(), "execute_class_GenerateXMLCFS", REF_NUMBER); System.out.println("message nian" + e.getMessage()); } finally { tg = null; cf = null; doc = null; doc1 = null; root = null; row = null; doclist = null; detil = null; if (preparedStatement != null) { preparedStatement.close(); } if (mydb != null) { mydb.close(); } if (rs != null) { rs.close(); } return result; } } private static java.sql.Timestamp getCurrentTimeStamp() { java.util.Date today = new java.util.Date(); return new java.sql.Timestamp(today.getTime()); } } <file_sep>package com.edii.tools; import java.io.File; import java.io.RandomAccessFile; public class CreateFile { public boolean execute(String filename) throws Exception { boolean success = false; File f = null; try { f = new File(filename); try{ f.delete(); success = true; }catch(Exception e){ } f.createNewFile(); }catch(Exception e){ success = false; } finally { f = null; return success; } } public boolean content(String filename,String content) throws Exception { boolean success = false; File f = null; RandomAccessFile rf = null; try { f = new File(filename); rf = new RandomAccessFile(f, "rwd"); rf.writeBytes(content); rf.close(); success = true; }catch(Exception e){success = false;} finally { f = null; rf = null; return success; } } public synchronized boolean content(String filename,byte[] content) throws Exception { boolean success = false; File f = null; RandomAccessFile rf = null; try { f = new File(filename); rf = new RandomAccessFile(f, "rwd"); rf.write(content); rf.close(); success = true; }catch(Exception e){success = false;} finally { f = null; rf = null; return success; } } public boolean content(String filename,byte[] content,int start,int end) throws Exception { boolean success = false; File f = null; RandomAccessFile rf = null; try { f = new File(filename); rf = new RandomAccessFile(f, "rwd"); rf.write(content,start,end); rf.close(); success = true; }catch(Exception e){success = false;} finally { f = null; rf = null; return success; } } } <file_sep> package id.go.beacukai.services; import java.net.MalformedURLException; import java.net.URL; import javax.xml.namespace.QName; import javax.xml.ws.Service; import javax.xml.ws.WebEndpoint; import javax.xml.ws.WebServiceClient; import javax.xml.ws.WebServiceException; import javax.xml.ws.WebServiceFeature; /** * This class was generated by the JAX-WS RI. * JAX-WS RI 2.2.10-b140803.1500 * Generated source version: 2.1 * */ @WebServiceClient(name = "TPSServices", targetNamespace = "http://services.beacukai.go.id/", wsdlLocation = "file:/E:/services/service.asmx.wsdl") public class TPSServices extends Service { private final static URL TPSSERVICES_WSDL_LOCATION; private final static WebServiceException TPSSERVICES_EXCEPTION; private final static QName TPSSERVICES_QNAME = new QName("http://services.beacukai.go.id/", "TPSServices"); static { URL url = null; WebServiceException e = null; try { url = new URL("file:/E:/services/service.asmx.wsdl"); } catch (MalformedURLException ex) { e = new WebServiceException(ex); } TPSSERVICES_WSDL_LOCATION = url; TPSSERVICES_EXCEPTION = e; } public TPSServices() { super(__getWsdlLocation(), TPSSERVICES_QNAME); } public TPSServices(URL wsdlLocation, QName serviceName) { super(wsdlLocation, serviceName); } /** * * @return * returns TPSServicesSoap */ @WebEndpoint(name = "TPSServicesSoap") public TPSServicesSoap getTPSServicesSoap() { return super.getPort(new QName("http://services.beacukai.go.id/", "TPSServicesSoap"), TPSServicesSoap.class); } /** * * @param features * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values. * @return * returns TPSServicesSoap */ @WebEndpoint(name = "TPSServicesSoap") public TPSServicesSoap getTPSServicesSoap(WebServiceFeature... features) { return super.getPort(new QName("http://services.beacukai.go.id/", "TPSServicesSoap"), TPSServicesSoap.class, features); } /** * * @return * returns TPSServicesSoap */ @WebEndpoint(name = "TPSServicesSoap12") public TPSServicesSoap getTPSServicesSoap12() { return super.getPort(new QName("http://services.beacukai.go.id/", "TPSServicesSoap12"), TPSServicesSoap.class); } /** * * @param features * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values. * @return * returns TPSServicesSoap */ @WebEndpoint(name = "TPSServicesSoap12") public TPSServicesSoap getTPSServicesSoap12(WebServiceFeature... features) { return super.getPort(new QName("http://services.beacukai.go.id/", "TPSServicesSoap12"), TPSServicesSoap.class, features); } private static URL __getWsdlLocation() { if (TPSSERVICES_EXCEPTION!= null) { throw TPSSERVICES_EXCEPTION; } return TPSSERVICES_WSDL_LOCATION; } } <file_sep><<<<<<< HEAD deploy.ant.properties.file=C:\\Users\\<NAME>\\AppData\\Roaming\\NetBeans\\7.3.1\\config\\GlassFishEE6\\Properties\\gfv31034388319.properties j2ee.platform.is.jsr109=true j2ee.server.domain=C:/Users/<NAME>/AppData/Roaming/NetBeans/7.3.1/config/GF3/domain1 j2ee.server.home=C:/Program Files/Apache Software Foundation/Apache Tomcat 7.0.34 j2ee.server.instance=[C:\\Program Files\\glassfish-4.0\\glassfish;C:\\Program Files\\glassfish-4.0\\glassfish\\domains\\domain1]deployer:gfv3ee6wc:localhost:4848 j2ee.server.middleware=C:/Program Files/glassfish-4.0 ======= deploy.ant.properties.file=C:\\Users\\<NAME>\\AppData\\Roaming\\NetBeans\\7.3.1\\tomcat70.properties j2ee.platform.is.jsr109=true j2ee.server.domain=C:/Users/<NAME>/AppData/Roaming/NetBeans/7.3.1/apache-tomcat-7.0.34.0_base j2ee.server.home=C:/Program Files/glassfish-4.1/glassfish j2ee.server.instance=tomcat70:home=C:\\Program Files\\Apache Software Foundation\\Apache Tomcat 7.0.34:base=apache-tomcat-7.0.34.0_base j2ee.server.middleware=C:/Program Files/glassfish-4.1 >>>>>>> origin/master javac.debug=true javadoc.preview=true jaxbwiz.endorsed.dirs=C:\\Program Files\\NetBeans 6.8\\ide12\\modules\\ext\\jaxb\\api selected.browser=default <<<<<<< HEAD user.properties.file=C:\\Users\\<NAME>\\AppData\\Roaming\\NetBeans\\7.3.1\\build.properties ======= user.properties.file=C:\\Users\\<NAME>\\AppData\\Roaming\\NetBeans\\7.3.1\\build.properties >>>>>>> origin/master <file_sep> package id.go.beacukai.services; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="CoCoTangkiResult" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "coCoTangkiResult" }) @XmlRootElement(name = "CoCoTangkiResponse") public class CoCoTangkiResponse { @XmlElement(name = "CoCoTangkiResult") protected String coCoTangkiResult; /** * Gets the value of the coCoTangkiResult property. * * @return * possible object is * {@link String } * */ public String getCoCoTangkiResult() { return coCoTangkiResult; } /** * Sets the value of the coCoTangkiResult property. * * @param value * allowed object is * {@link String } * */ public void setCoCoTangkiResult(String value) { this.coCoTangkiResult = value; } } <file_sep>package com.edii.tools; import java.security.Key; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author <NAME> */ public class Encrypt { MessageDigest messageDigest; private static final String ALGO = "AES"; private static final byte[] keyValue = new byte[]{'T', 'h', 'e', 'B', 'e', 's', 't', 'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y'}; public String encrypt(String plaintext) throws NoSuchAlgorithmException { messageDigest = MessageDigest.getInstance("MD5"); //System.out.println("Metode Enkripsi : " + messageDigest.getAlgorithm()); String input = plaintext; messageDigest.update(input.getBytes()); byte[] output = messageDigest.digest(); return convert(output); } private int byte2int(byte data) { return data < 0 ? 256 + data : data; } public String convert(byte[] data) { StringBuffer buffer = new StringBuffer(); for (byte b : data) { String s = Integer.toHexString(byte2int(b)); if (s.length() < 2) { buffer.append("0" + s); } else { buffer.append(s); } } return buffer.toString(); } public static String encrypt_AES(String Data) throws Exception { Key key = generateKey(); Cipher c = Cipher.getInstance(ALGO); c.init(Cipher.ENCRYPT_MODE, key); byte[] encVal = c.doFinal(Data.getBytes()); String encryptedValue = new BASE64Encoder().encode(encVal); return encryptedValue; } public static String decrypt_AES(String encryptedData) throws Exception { Key key = generateKey(); Cipher c = Cipher.getInstance(ALGO); c.init(Cipher.DECRYPT_MODE, key); byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData); byte[] decValue = c.doFinal(decordedValue); String decryptedValue = new String(decValue); return decryptedValue; } private static Key generateKey() throws Exception { Key key = new SecretKeySpec(keyValue, ALGO); return key; } public static void main(String[] args) throws Exception { String password = "cd"; String passwordEnc = Encrypt.encrypt_AES(password); String passwordDec = Encrypt.decrypt_AES(passwordEnc); System.out.println("Plain Text : " + password); System.out.println("Encrypted Text : " + passwordEnc); System.out.println("Decrypted Text : " + passwordDec); } // public static void main(String[] args) throws NoSuchAlgorithmException { // String input = "IPC0"; // Encrypt mde = new Encrypt(); // System.out.println("(" + input + ") = " + mde.encrypt(input)); // } } <file_sep> package id.go.beacukai.services; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="UserName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="Password" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="No_PKBE" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="TGL_PKBE" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="kdKantor" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "userName", "password", "no_PKBE", "tgl_PKBE", "kdKantor" }) @XmlRootElement(name = "GetEkspor_PKBE") public class GetEkspor_PKBE { @XmlElement(name = "UserName") protected String userName; @XmlElement(name = "Password") protected String password; @XmlElement(name = "No_PKBE") protected String no_PKBE; @XmlElement(name = "TGL_PKBE") protected String tgl_PKBE; protected String kdKantor; /** * Gets the value of the userName property. * * @return * possible object is * {@link String } * */ public String getUserName() { return userName; } /** * Sets the value of the userName property. * * @param value * allowed object is * {@link String } * */ public void setUserName(String value) { this.userName = value; } /** * Gets the value of the password property. * * @return * possible object is * {@link String } * */ public String getPassword() { return password; } /** * Sets the value of the password property. * * @param value * allowed object is * {@link String } * */ public void setPassword(String value) { this.password = value; } /** * Gets the value of the no_PKBE property. * * @return * possible object is * {@link String } * */ public String getNo_PKBE() { return no_PKBE; } /** * Sets the value of the no_PKBE property. * * @param value * allowed object is * {@link String } * */ public void setNo_PKBE(String value) { this.no_PKBE = value; } /** * Gets the value of the tgl_PKBE property. * * @return * possible object is * {@link String } * */ public String getTGL_PKBE() { return tgl_PKBE; } /** * Sets the value of the tgl_PKBE property. * * @param value * allowed object is * {@link String } * */ public void setTGL_PKBE(String value) { this.tgl_PKBE = value; } /** * Gets the value of the kdKantor property. * * @return * possible object is * {@link String } * */ public String getKdKantor() { return kdKantor; } /** * Sets the value of the kdKantor property. * * @param value * allowed object is * {@link String } * */ public void setKdKantor(String value) { this.kdKantor = value; } } <file_sep>/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.edii.generatefile; import DatabaseGenerator.DatabaseOracle; import XMLGenerator.GeneratorXML; import com.edii.db.Db; import com.edii.operation.db.operation; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.logging.LogFactory; /** * * @author <NAME> */ public class GenerateDW { String table = ""; String colomn = ""; String value = ""; String query = ""; GeneratorXML gx = null; static org.apache.commons.logging.Log logger = LogFactory.getLog(Db.class); private static final String PROPERTIES_FILE = "db.properties"; private static final Properties PROPERTIES = new Properties(); DatabaseOracle dbO = null; static { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream propertiesFile = classLoader.getResourceAsStream(PROPERTIES_FILE); if (propertiesFile == null) { logger.debug("Properties file '" + PROPERTIES_FILE + "' is missing in classpath."); } try { PROPERTIES.load(propertiesFile); } catch (IOException e) { logger.debug("Cannot load properties file '" + PROPERTIES_FILE + "'." + e.getMessage()); } } private void OpenConnection() throws ClassNotFoundException { dbO = new DatabaseOracle(); dbO.connectDatabase(PROPERTIES.getProperty("db.host"), PROPERTIES.getProperty("db.SID"), PROPERTIES.getProperty("db.username"), PROPERTIES.getProperty("db.password")); } public String excute(String RefNumber, String responId) throws Exception { String RESPONID = null; String result = null; ArrayList<String> list = new ArrayList<>(); try { OpenConnection(); } catch (ClassNotFoundException ex) { Logger.getLogger(operation.class.getName()).log(Level.SEVERE, null, ex); } colomn = "KODE_TPS_ASAL , KODE_GUDANG_ASAL , CALL_SIGN, NAMA_KAPAL, " + "NO_VOYAGE, KODE_TPS_TUJUAN, KODE_GUDANG_TUJUAN, REF_NUMBER, RESPONID"; query = "SELECT A.KODE_TPS_ASAL , A.KODE_GUDANG_ASAL , A.CALL_SIGN, A.NAMA_KAPAL, " + "A.NO_VOYAGE, A.KODE_TPS_TUJUAN, A.KODE_GUDANG_TUJUAN, B.REF_NUMBER, B.RESPONID " + "FROM T_REQUEST_PLP A " + "INNER JOIN T_RESPON_PLP B ON A.REF_NUMBER = B.REF_NUMBER " + "WHERE A.KODE_TPS_ASAL <> 'PLDC' AND B.FL_SEND = '0'" + "AND B.REF_NUMBER = '" + RefNumber + "' AND B.RESPONID = '" + responId + "'"; //System.out.println(list.toString()); try { gx = new GeneratorXML("DOCUMENT", ""); gx.addXML("DOCUMENT", "RESPLP", ""); list = dbO.query_select_raw(colomn, query); try { if (!list.isEmpty()) { RESPONID = list.get(0).split("#")[8].split(":")[1]; gx.addXML("RESPLP", "HEADER", list.get(0).replace("#", ",")); gx.addXML("RESPLP", "DETIL", ""); //CONT colomn = "NO_CONT,UK_CONT,STATUS_PLP"; query = "SELECT NO_CONT,UK_CONT,STATUS_PLP FROM T_RESPON_PLP_CONT WHERE RESPONID = '" + RESPONID + "' AND STATUS_PLP = 'Y'"; list = dbO.query_select_raw(colomn, query); for (String isi_list : list) { gx.addXML("DETIL", "CONT", isi_list.replace("#", ",")); } } if (gx.getStringxml().length() > 100) { table = "T_RESPON_PLP"; colomn = "FL_SEND,DATE_SEND"; value = "1," + getCurrentTimeStamp(); String colwhere = "RESPONID = "; String valwhere = RESPONID; if (dbO.query_update_with_where(table, colomn, value, colwhere, valwhere, "")) { // query = "UPDATE T_RESPON_PLP SET FL_SEND = ? , DATE_SEND = ? WHERE RESPONID = ?"; // preparedStatement = mydb.preparedstmt(query); // preparedStatement.setString(1, "1"); // preparedStatement.setTimestamp(2, getCurrentTimeStamp()); // preparedStatement.setString(3, RESPONID); // mydb.execute("commit"); result = gx.getStringxml(); } } } catch (Exception e) { System.out.println("message" + e.getMessage()); } return result; } catch (Exception e) { System.out.println("message nian" + e.getMessage()); return result; } finally { list.clear(); } } private static java.sql.Timestamp getCurrentTimeStamp() { java.util.Date today = new java.util.Date(); return new java.sql.Timestamp(today.getTime()); } public static void main(String[] args) throws Exception { GenerateDW gd = new GenerateDW(); String r = gd.excute("KOJA141110367703", "9673"); System.out.println(r); } } <file_sep>/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.edii.model; /** * * @author <NAME> */ public class ModelCoarriCodecoKemasan { //Element Header String kd_dok = null; String kd_tps = null; String nm_angkut = null; String no_voy_flight = null; String call_sign = null; String tgl_tiba = null; String kd_gudang = null; String ref_number = null; //element detil kms String no_bl_awb = null; String tgl_bl_awb = null; String no_master_bl_awb = null; String tgl_master_bl_awb = null; String id_consignee = null; String consignee = null; String bruto = null; String no_bc11 = null; String tgl_bc11 = null; String no_pos_bc11 = null; String kd_timbun = null; String kd_dok_inout = null; String no_dok_inout = null; String tgl_dok_inout = null; String wk_inout = null; String kd_sar_angkut_inout = null; String no_pol = null; String pel_muat = null; String pel_transit = null; String pel_bongkar = null; String gudang_tujuan = null; String kode_kantor = null; String no_daftar_pabean = null; String tgl_daftar_pabean = null; String no_segel_bc = null; String tgl_segel_bc = null; String no_ijin_tps = null; String tgl_ijin_tps = null; String cont_asal = null; String seri_kemas = null; String kd_kemas = null; String jml_kemas = null; public String getKd_dok() { return kd_dok; } public void setKd_dok(String kd_dok) { this.kd_dok = kd_dok; } public String getKd_tps() { return kd_tps; } public void setKd_tps(String kd_tps) { this.kd_tps = kd_tps; } public String getNm_angkut() { return nm_angkut; } public void setNm_angkut(String nm_angkut) { this.nm_angkut = nm_angkut; } public String getNo_voy_flight() { return no_voy_flight; } public void setNo_voy_flight(String no_voy_flight) { this.no_voy_flight = no_voy_flight; } public String getCall_sign() { return call_sign; } public void setCall_sign(String call_sign) { this.call_sign = call_sign; } public String getTgl_tiba() { return tgl_tiba; } public void setTgl_tiba(String tgl_tiba) { this.tgl_tiba = tgl_tiba; } public String getKd_gudang() { return kd_gudang; } public void setKd_gudang(String kd_gudang) { this.kd_gudang = kd_gudang; } public String getRef_number() { return ref_number; } public void setRef_number(String ref_number) { this.ref_number = ref_number; } public String getNo_bl_awb() { return no_bl_awb; } public void setNo_bl_awb(String no_bl_awb) { this.no_bl_awb = no_bl_awb; } public String getTgl_bl_awb() { return tgl_bl_awb; } public void setTgl_bl_awb(String tgl_bl_awb) { this.tgl_bl_awb = tgl_bl_awb; } public String getNo_master_bl_awb() { return no_master_bl_awb; } public void setNo_master_bl_awb(String no_master_bl_awb) { this.no_master_bl_awb = no_master_bl_awb; } public String getTgl_master_bl_awb() { return tgl_master_bl_awb; } public void setTgl_master_bl_awb(String tgl_master_bl_awb) { this.tgl_master_bl_awb = tgl_master_bl_awb; } public String getId_consignee() { return id_consignee; } public void setId_consignee(String id_consignee) { this.id_consignee = id_consignee; } public String getConsignee() { return consignee; } public void setConsignee(String consignee) { this.consignee = consignee; } public String getBruto() { return bruto; } public void setBruto(String bruto) { this.bruto = bruto; } public String getNo_bc11() { return no_bc11; } public void setNo_bc11(String no_bc11) { this.no_bc11 = no_bc11; } public String getTgl_bc11() { return tgl_bc11; } public void setTgl_bc11(String tgl_bc11) { this.tgl_bc11 = tgl_bc11; } public String getNo_pos_bc11() { return no_pos_bc11; } public void setNo_pos_bc11(String no_pos_bc11) { this.no_pos_bc11 = no_pos_bc11; } public String getKd_timbun() { return kd_timbun; } public void setKd_timbun(String kd_timbun) { this.kd_timbun = kd_timbun; } public String getKd_dok_inout() { return kd_dok_inout; } public void setKd_dok_inout(String kd_dok_inout) { this.kd_dok_inout = kd_dok_inout; } public String getNo_dok_inout() { return no_dok_inout; } public void setNo_dok_inout(String no_dok_inout) { this.no_dok_inout = no_dok_inout; } public String getTgl_dok_inout() { return tgl_dok_inout; } public void setTgl_dok_inout(String tgl_dok_inout) { this.tgl_dok_inout = tgl_dok_inout; } public String getWk_inout() { return wk_inout; } public void setWk_inout(String wk_inout) { this.wk_inout = wk_inout; } public String getKd_sar_angkut_inout() { return kd_sar_angkut_inout; } public void setKd_sar_angkut_inout(String kd_sar_angkut_inout) { this.kd_sar_angkut_inout = kd_sar_angkut_inout; } public String getNo_pol() { return no_pol; } public void setNo_pol(String no_pol) { this.no_pol = no_pol; } public String getPel_muat() { return pel_muat; } public void setPel_muat(String pel_muat) { this.pel_muat = pel_muat; } public String getPel_transit() { return pel_transit; } public void setPel_transit(String pel_transit) { this.pel_transit = pel_transit; } public String getPel_bongkar() { return pel_bongkar; } public void setPel_bongkar(String pel_bongkar) { this.pel_bongkar = pel_bongkar; } public String getGudang_tujuan() { return gudang_tujuan; } public void setGudang_tujuan(String gudang_tujuan) { this.gudang_tujuan = gudang_tujuan; } public String getKode_kantor() { return kode_kantor; } public void setKode_kantor(String kode_kantor) { this.kode_kantor = kode_kantor; } public String getNo_daftar_pabean() { return no_daftar_pabean; } public void setNo_daftar_pabean(String no_daftar_pabean) { this.no_daftar_pabean = no_daftar_pabean; } public String getTgl_daftar_pabean() { return tgl_daftar_pabean; } public void setTgl_daftar_pabean(String tgl_daftar_pabean) { this.tgl_daftar_pabean = tgl_daftar_pabean; } public String getNo_segel_bc() { return no_segel_bc; } public void setNo_segel_bc(String no_segel_bc) { this.no_segel_bc = no_segel_bc; } public String getTgl_segel_bc() { return tgl_segel_bc; } public void setTgl_segel_bc(String tgl_segel_bc) { this.tgl_segel_bc = tgl_segel_bc; } public String getNo_ijin_tps() { return no_ijin_tps; } public void setNo_ijin_tps(String no_ijin_tps) { this.no_ijin_tps = no_ijin_tps; } public String getTgl_ijin_tps() { return tgl_ijin_tps; } public void setTgl_ijin_tps(String tgl_ijin_tps) { this.tgl_ijin_tps = tgl_ijin_tps; } public String getCont_asal() { return cont_asal; } public void setCont_asal(String cont_asal) { this.cont_asal = cont_asal; } public String getSeri_kemas() { return seri_kemas; } public void setSeri_kemas(String seri_kemas) { this.seri_kemas = seri_kemas; } public String getKd_kemas() { return kd_kemas; } public void setKd_kemas(String kd_kemas) { this.kd_kemas = kd_kemas; } public String getJml_kemas() { return jml_kemas; } public void setJml_kemas(String jml_kemas) { this.jml_kemas = jml_kemas; } } <file_sep>/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.edii.model; /** * * @author <NAME> */ public class ModelGetResponBatalPLP { //DOK PLP Element Header String kd_kantor = null; String kd_tps = null; String ref_number = null; String no_batal_plp = null; String tgl_batal_plp = null; //DOK PLP Element Dtl KMS String jns_kms = null; String jml_kms = null; String no_bl_awb = null; String tgl_bl_awb = null; String fl_setuju_kms = null; //DOK PLP Element Dtl CONT String no_cont = null; String uk_cont = null; String fl_setuju_cont = null; public String getKd_kantor() { return kd_kantor; } public void setKd_kantor(String kd_kantor) { this.kd_kantor = kd_kantor; } public String getKd_tps() { return kd_tps; } public void setKd_tps(String kd_tps) { this.kd_tps = kd_tps; } public String getRef_number() { return ref_number; } public void setRef_number(String ref_number) { this.ref_number = ref_number; } public String getNo_batal_plp() { return no_batal_plp; } public void setNo_batal_plp(String no_batal_plp) { this.no_batal_plp = no_batal_plp; } public String getTgl_batal_plp() { return tgl_batal_plp; } public void setTgl_batal_plp(String tgl_batal_plp) { this.tgl_batal_plp = tgl_batal_plp; } public String getJns_kms() { return jns_kms; } public void setJns_kms(String jns_kms) { this.jns_kms = jns_kms; } public String getJml_kms() { return jml_kms; } public void setJml_kms(String jml_kms) { this.jml_kms = jml_kms; } public String getNo_bl_awb() { return no_bl_awb; } public void setNo_bl_awb(String no_bl_awb) { this.no_bl_awb = no_bl_awb; } public String getTgl_bl_awb() { return tgl_bl_awb; } public void setTgl_bl_awb(String tgl_bl_awb) { this.tgl_bl_awb = tgl_bl_awb; } public String getFl_setuju_kms() { return fl_setuju_kms; } public void setFl_setuju_kms(String fl_setuju_kms) { this.fl_setuju_kms = fl_setuju_kms; } public String getNo_cont() { return no_cont; } public void setNo_cont(String no_cont) { this.no_cont = no_cont; } public String getUk_cont() { return uk_cont; } public void setUk_cont(String uk_cont) { this.uk_cont = uk_cont; } public String getFl_setuju_cont() { return fl_setuju_cont; } public void setFl_setuju_cont(String fl_setuju_cont) { this.fl_setuju_cont = fl_setuju_cont; } } <file_sep> package id.go.beacukai.services; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="GetBC23PermitResult" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "getBC23PermitResult" }) @XmlRootElement(name = "GetBC23PermitResponse") public class GetBC23PermitResponse { @XmlElement(name = "GetBC23PermitResult") protected String getBC23PermitResult; /** * Gets the value of the getBC23PermitResult property. * * @return * possible object is * {@link String } * */ public String getGetBC23PermitResult() { return getBC23PermitResult; } /** * Sets the value of the getBC23PermitResult property. * * @param value * allowed object is * {@link String } * */ public void setGetBC23PermitResult(String value) { this.getBC23PermitResult = value; } }
45762200e174e411436258c208f183310d1b12a0
[ "Java", "INI" ]
27
Java
malianzikri/TPS
eb757300c7c0393f1ede99cdc716545f0245d933
2b28222fac084e1fadeb4a9ac75427f2fa648f8c
refs/heads/master
<repo_name>khteh/mysql-master<file_sep>/server-id.sh #!/bin/bash export INDEX=${HOSTNAME##*-} export ID=$(( $INDEX + 1 )) sed -i '/\[mysqld\]/a server_id='$ID'' /etc/mysql/conf.d/mysql.cnf <file_sep>/Dockerfile FROM mysql:latest ADD docker-entrypoint.sh /usr/local/bin/custom-docker-entrypoint.sh ADD mysql.cnf /etc/mysql/conf.d/mysql.cnf ADD server-id.sh /usr/local/bin/server-id.sh RUN rm -f /entrypoint.sh RUN ln -s usr/local/bin/custom-docker-entrypoint.sh /entrypoint.sh # backwards compat ENTRYPOINT ["custom-docker-entrypoint.sh"] EXPOSE 3306 33060 CMD ["mysqld"] <file_sep>/build.sh #!/bin/bash docker build -t khteh/mysql-master . docker push khteh/mysql-master:latest
4a0f411288913fa09e9deff32ed9099d5772573e
[ "Dockerfile", "Shell" ]
3
Shell
khteh/mysql-master
7170c80b6917a128a78200855c1809200932d9b5
1d2a0d2bfc23789b9cdb19f8871330eec64f52f8
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PSModern.Models.Repository { interface IWorkRepository { Collection<Work> GetAll(); Collection<Work> GetByPS(int psid); Work GetById(int id); } } <file_sep>using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PSModern.Models.Repository { interface IResTypeRepository { Collection<ResType> GetAll(); ResType GetById(int id); } } <file_sep>using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PSModern.Models.Repository { interface IBNRepository { Collection<BN> GetAll(); BN GetById(int id); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PSModern.Models { public class PS { public int ID { get; set; } public Guid Bargain_Guid { get; set; } public virtual ICollection<Work> Works { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PSModern.Models.Repository { interface IWorkTypeRepository { Collection<WorkType> GetAll(); WorkType GetById(int id); } } <file_sep>using PSModern.Models; using PSModern.Models.Repository; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace PSModern.Controllers.api { [RoutePrefix("api/ps")] public class PSController : ApiController { [Route("GetAllWorks")] public Collection<Work> GetAllWorks() { IWorkRepository rep = new EFWorkRepository(); var a = rep.GetAll(); return a; } [Route("GetAllBNs")] public Collection<BN> GetAllBNs() { IBNRepository rep = new EFBNRepository(); var a = rep.GetAll(); return a; } [Route("GetAllResTypes")] public Collection<ResType> GetAllResTypes() { IResTypeRepository rep = new EFResTypeRepository(); var a = rep.GetAll(); return a; } } } <file_sep>using PSModern.Models.DAL; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PSModern.Models.Repository { public class EFResTypeRepository : IResTypeRepository { private PSContext _db; public EFResTypeRepository() { _db = new PSContext(); } public Collection<ResType> GetAll() { ObservableCollection<ResType> resTypes = new ObservableCollection<ResType>(_db.ResTypes.ToList()); return resTypes; //throw new NotImplementedException(); } public ResType GetById(int id) { var resType = _db.ResTypes.Where(x => x.ID == id).ToList(); return resType.FirstOrDefault(); //throw new NotImplementedException(); } } } <file_sep>using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PSModern.Models.DAL { public class PSConteextInitializer : CreateDatabaseIfNotExists<PSContext> { protected override void Seed(PSContext context) { base.Seed(context); } } } <file_sep>using PSModern.Models; using PSModern.Models.DAL; using PSModern.Models.Repository; using RestSharp; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Web; using System.Web.Mvc; namespace PSModern.Controllers { public class HomeController : Controller { public ActionResult Index() { //PSContext db = new PSContext(); ////db.Database.Initialize(true); //var a = db.Works.ToList(); //IWorkRepository rep = new EFWorkRepository(); //var a = rep.GetAll(); //var client = new RestClient("http://localhost:44470/"); //var request = new RestRequest("api/ps/GetAllWorks", Method.GET); //var response = client.Execute<List<Work>>(request); //var res = response.Data; return View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } } }<file_sep>using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PSModern.Models.DAL { public class PSContext : DbContext { public PSContext() : base("PSModern2") { Database.SetInitializer<PSContext>(new CreateDatabaseIfNotExists<PSContext>()); } public DbSet<WorkType> WorkTypes { get; set; } public DbSet<ResType> ResTypes { get; set; } public DbSet<BN> BNs { get; set; } public DbSet<Work> Works { get; set; } public DbSet<PS> PSs { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PSModern.Models { public class Work { [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int ID { get; set; } public string Name { get; set; } public string Executioner { get; set; } public decimal InternalPrice { get; set; } public decimal ExternalPrice { get; set; } public decimal Tax { get; set; } public decimal PMP { get; set; } public int WorkTypeID { get; set; } public int ResTypeID { get; set; } public int BNID { get; set; } public virtual WorkType WType { get; set; } public virtual ResType RType { get; set; } public virtual BN BNUnit { get; set; } } } <file_sep>var PSController = function ($scope, PSService) { //debugger; $scope.models = { helloAngular: 'I work!' }; GetAllWorks(); GetAllBNs(); GetAllResTypes(); //debugger; function GetAllWorks() { //debugger; var getData = PSService.GetAllWorks(); getData.then(function (works) { debugger; $scope.models.WorkName = works.data[0].Name; $scope.models.Works = works.data; debugger; }, function (a, b, c) { debugger; }); } function GetAllBNs() { var getData2 = PSService.GetAllBNs(); getData2.then(function (bns) { //debugger; $scope.models.BNs = bns.data; //$scope.models.bn = null; //debugger; }, function (a, b, c) { debugger; }); } function GetAllResTypes() { debugger; var getData3 = PSService.GetAllResTypes(); getData3.then(function (rTypes) { debugger; $scope.models.ResTypes = rTypes.data; debugger; }, function (a, b, c) { debugger; }); } }<file_sep>using PSModern.Models.DAL; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PSModern.Models.Repository { public class EFWorkRepository : IWorkRepository { private PSContext _db; public EFWorkRepository() { _db = new PSContext(); } public Collection<Work> GetAll() { ObservableCollection<Work> works = new ObservableCollection<Work>(_db.Works.ToList()); return works; //throw new NotImplementedException(); } public Work GetById(int id) { throw new NotImplementedException(); } public Collection<Work> GetByPS(int psid) { throw new NotImplementedException(); } } } <file_sep>using PSModern.Models.DAL; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PSModern.Models.Repository { public class EFBNRepository : IBNRepository { private PSContext _db; public EFBNRepository() { _db = new PSContext(); } public Collection<BN> GetAll() { ObservableCollection<BN> bns = new ObservableCollection<BN>(_db.BNs.ToList()); return bns; } public BN GetById(int id) { var bn = _db.BNs.Where(x => x.ID == id).ToList(); if(bn.Count() > 0) { return bn.First(); } else { return null; } } } } <file_sep>namespace PSModern.Migrations { using System; using System.Data.Entity.Migrations; public partial class InitialCreate : DbMigration { public override void Up() { CreateTable( "dbo.BN", c => new { ID = c.Int(nullable: false, identity: true), Name = c.String(), }) .PrimaryKey(t => t.ID); CreateTable( "dbo.ResType", c => new { ID = c.Int(nullable: false, identity: true), Name = c.String(), }) .PrimaryKey(t => t.ID); CreateTable( "dbo.Work", c => new { ID = c.Int(nullable: false, identity: true), Name = c.String(), Executioner = c.String(), InternalPrice = c.Decimal(nullable: false, precision: 18, scale: 2), ExternalPrice = c.Decimal(nullable: false, precision: 18, scale: 2), Tax = c.Decimal(nullable: false, precision: 18, scale: 2), PMP = c.Decimal(nullable: false, precision: 18, scale: 2), WorkTypeID = c.Int(nullable: false), ResTypeID = c.Int(nullable: false), BNID = c.Int(nullable: false), }) .PrimaryKey(t => t.ID) .ForeignKey("dbo.BN", t => t.BNID, cascadeDelete: true) .ForeignKey("dbo.ResType", t => t.ResTypeID, cascadeDelete: true) .ForeignKey("dbo.WorkType", t => t.WorkTypeID, cascadeDelete: true) .Index(t => t.WorkTypeID) .Index(t => t.ResTypeID) .Index(t => t.BNID); CreateTable( "dbo.WorkType", c => new { ID = c.Int(nullable: false, identity: true), Name = c.String(), }) .PrimaryKey(t => t.ID); } public override void Down() { DropForeignKey("dbo.Work", "WorkTypeID", "dbo.WorkType"); DropForeignKey("dbo.Work", "ResTypeID", "dbo.ResType"); DropForeignKey("dbo.Work", "BNID", "dbo.BN"); DropIndex("dbo.Work", new[] { "BNID" }); DropIndex("dbo.Work", new[] { "ResTypeID" }); DropIndex("dbo.Work", new[] { "WorkTypeID" }); DropTable("dbo.WorkType"); DropTable("dbo.Work"); DropTable("dbo.ResType"); DropTable("dbo.BN"); } } } <file_sep>using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PSModern.Models.Repository { public class EFWorkTypeRepository : IWorkTypeRepository { public Collection<WorkType> GetAll() { throw new NotImplementedException(); } public WorkType GetById(int id) { throw new NotImplementedException(); } } }
ba39903a21ac1874004ea60405e6af95db4635a6
[ "JavaScript", "C#" ]
16
C#
ninthrampart/PSModern
d51787283fa567df582dd071fd7f22b4ff2a5d6b
95edb4ebf25f4f0cae38fcf050095483e9abfa03
refs/heads/master
<repo_name>Avenge2766/Iterative_word_suggestion<file_sep>/proj/source/README.md Introduction: ------------ The program takes input string in the form of single character at a time. The partial string so far found is matched with the string present in the text file and filters it. The top 5 words with the highest frequency as in provided in the file are displayed along with the time taken. If character entered is '#' or no words can be found, the application terminates. Requirements: ------------ 1. Any 32-bit Windows machine. Recommended Modules: ------------------- Modules imported are: 1. Datetime (built-in library module) 2. Time (built-in library module) Installation: ------------ No particular installation is required. Application can be run through the .exe file. <file_sep>/proj/source/iterative_word_suggestion.py #!/usr/bin/env python # coding: utf-8 #Importing datetime module for calculating time taken for finding words import datetime import time def check(lis_word): index = 0 while(True): character = input() #Taking character from user if(character == '#'): print('Exiting') #if input is '#' then exit break start_time = datetime.datetime.now() #keeping track of start time character = character.lower() #Segregating only those words where the character at current index of the word matches the input lis_word = [x for x in lis_word if x[2]>index and x[0][index].lower() == character] end_time = datetime.datetime.now() #Time at which the calculation ends tot_time = end_time - start_time #Total time taken #if no words matches the criteria then exit if(lis_word == []): print('No match Found!!','\t',str(tot_time.microseconds)+' \u03bcs') print('Exiting') break #Printing the words for i in range(min(5, len(lis_word))): print(lis_word[i][0], end = ',') print('\t',str(tot_time.microseconds)+' \u03bcs') index += 1 time.sleep(2) def main(): #opening file file = open('../source/EnglishDictionary.txt','r') #creating empty dictionary for storing words and their respective frequencies dict_words = {} for line in file: word, frequency = line.split(',') #splitting lines in words and frequency frequency = int(frequency) dict_words[word] = frequency lis_word = [[x, -1*dict_words[x], len(x)] for x in dict_words.keys()] #creating a list of words, their frequencies in negative and length of words lis_word.sort(key = lambda x: x[1]) #Sorting list according to negative frequencies check(lis_word) #Calling function to check for each input if __name__ == "__main__": main()
b6d228c2d03b145faee7458915edc683d85ad56b
[ "Markdown", "Python" ]
2
Markdown
Avenge2766/Iterative_word_suggestion
17f2fd8b40b1a2080bb89370b529679700965122
858233bfec95539d05011554421b599c04c08ba8
refs/heads/master
<file_sep>#ifndef MPL3115A2_H #define MPL3115A2_H #include "mbed.h" //MPL3115A2 REGS #define STATUS 0x00 #define OUT_P_MSB 0x01 #define OUT_P_CSB 0x02 #define OUT_P_LSB 0x03 #define OUT_T_MSB 0x04 #define OUT_T_LSB 0x05 #define DR_STATUS 0x06 #define OUT_P_DELTA_MSB 0x07 #define OUT_P_DELTA_CSB 0x08 #define OUT_P_DELTA_LSB 0x09 #define OUT_T_DELTA_MSB 0x0A #define OUT_T_DELTA_LSB 0x0B #define WHO_AM_I 0x0C #define F_STATUS 0x0D #define F_DATA 0x0E #define F_SETUP 0x0F #define TIME_DLY 0x10 #define SYSMOD 0x11 #define INT_SOURCE 0x12 #define PT_DATA_CFG 0x13 #define BAR_IN_MSB 0x14 #define BAR_IN_LSB 0x15 #define P_TGT_MSB 0x16 #define P_TGT_LSB 0x17 #define T_TGT 0x18 #define P_WND_MSB 0x19 #define P_WND_LSB 0x1A #define T_WND 0x1B #define P_MIN_MSB 0x1C #define P_MIN_CSB 0x1D #define P_MIN_LSB 0x1E #define T_MIN_MSB 0x1F #define T_MIN_LSB 0x20 #define P_MAX_MSB 0x21 #define P_MAX_CSB 0x22 #define P_MAX_LSB 0x23 #define T_MAX_MSB 0x24 #define T_MAX_LSB 0x25 #define CTRL_REG1 0x26 #define CTRL_REG2 0x27 #define CTRL_REG3 0x28 #define CTRL_REG4 0x29 #define CTRL_REG5 0x2A #define OFF_P 0x2B #define OFF_T 0x2C #define OFF_H 0x2D #define MSB 0x00 #define CSB 0x01 #define LSB 0x02 #define MPL3115A2_ADDRESS 0xC0 // 7-bit I2C address class MPL3115A2 { public: MPL3115A2(I2C *i2c_ref) { i2c = i2c_ref; } //retrieves altitude in Meters float readAltitude(); //retrieves altitude in Feet float readAltitudeFt(); //retrieves pressures float readPressure(); //retrieves temp In Celsius float readTemp(); //retrieves temp in Fahrenheit float readTempF(); //Used for Barometer mode void setModeBarometer(); //Used for Altimeter void setModeAltimeter(); //Enables interrupts from sensor void enableEventFlags(); //Used for signal shots void toggleOneShot(); //used to change sample rate void setOversampleRate(char sampleRate); //used to set-up FIFOMode void setFIFOMode(char f_Mode); // takes out of low power mode void setModeActive(); //puts in low power mode void setModeStandby(); //gets the status bool get_status(); //check connection bool check_connection(); private: I2C *i2c; bool status; char IIC_Read(char regAddr); void IIC_Write(char regAddr, char value); }; #endif<file_sep>#include "mbed.h" #include "MPL3115A2.h" I2C i2c(I2C_SDA, I2C_SCL); I2C i2c1(D5,D7); MPL3115A2 sensor1(&i2c); MPL3115A2 sensor2(&i2c1); Serial xbee(PA_11,PA_12); //int serial_getline(char &ptr); //returns the length of the array int get_pressure(float *ptr); int get_temp(float *ptr); void hash_options(char cmd); char menu(); int testing(); bool presSensor1 = false; bool presSensor2 = false; bool tempSensor = false; int convertType = 2; float pressFact = 1; float tempFact = 1; int tempType = 0; char pressEnd[10]; char tempEnd[10]; int main() { char cmd = 0xFF; cmd = xbee.getc(); while (1) { cmd = menu(); hash_options(cmd); } return 0; } // int serial_getline(char *ptr) // { // char input; // int len = 1; // char array[19]; // while(input != '\n') // { // input = xbee.getc(); // array[len] = input; // len++; // } // ptr = array; // return len; // } //gets the pressure from the sensors int get_pressure(float *ptr) { float values[2]; int len = 0; if(presSensor1) { values[0] = pressFact * sensor1.readPressure(); len ++; } if(presSensor2) { values[1] = pressFact * sensor2.readPressure(); len ++; } ptr = values; //look up return len; } //gets tempEnd int get_temp(float *ptr) { float values[2]; int len = 0; if(presSensor1) { if(tempType == 0) { values[0] = sensor1.readTemp(); } if(tempType ==1) { values[0] = sensor1.readTempF(); } if(tempType == 2) { values[0] = tempFact + sensor1.readTempF(); } len ++; } if(presSensor2) { if(tempType == 0) { values[1] = sensor2.readTemp(); } if(tempType ==1) { values[1] = sensor2.readTempF(); } if(tempType == 2) { values[1] = tempFact + sensor2.readTempF(); } len ++; } ptr = values; return len; } //menu char menu() { char cmd; xbee.printf("******** Menu ******** \n"); xbee.printf("1: Enable/Disable Sensor 1 \n"); xbee.printf("2: Enable/Disable Sensor 2 \n"); xbee.printf("3: Enable/Disable Temperature \n"); xbee.printf("4: Display in PSI \n"); xbee.printf("5: Display in Torr \n"); xbee.printf("6: Display in kpa \n"); xbee.printf("7: Display Temperature in Celsius \n"); xbee.printf("8: Display Temperature in Fahrenheit \n"); xbee.printf("9: Display Temperature in Kelvin \n"); xbee.printf("S: Start Testing \n" ); xbee.printf("CMD: "); cmd = xbee.getc(); return cmd; } //used to hash options void hash_options(char cmd) { switch(cmd) { case '1': if(presSensor1) { presSensor1 = false; xbee.printf("Sensor 1 Disabled \n"); } else { presSensor1 = true; xbee.printf("Sensor 1 Enabled \n"); } break; case '2': if(presSensor2) { presSensor2 = false; xbee.printf("Sensor 2 Disabled \n"); } else { presSensor2 = true; xbee.printf("Sensor 2 Enabled \n"); } break; case '3': if(tempSensor) { tempSensor = false; xbee.printf("Sensor 2 Disabled \n"); } else { tempSensor = true; xbee.printf("Sensor 2 Enabled \n"); } break; case '4': convertType = 0; pressFact = 0.00014503773 ; break; case '5': convertType = 1; pressFact = 7.50061683; break; case '6': convertType = 2; pressFact = 1; break; case '7': tempType = 0; tempFact =1; break; case '8': tempType = 1; break; case '9': tempType = 2; tempFact = 273.15; break; case 'S': case 's': testing(); break; default : xbee.printf("Invalid option"); } } //used for the testing int testing() { float pressure[2]; float temp[2]; int len; char cmd = 'r'; xbee.printf("Press any key to start test \n"); xbee.getc(); if(presSensor1) { xbee.printf("Sensor 1"); switch(convertType) { case 0: xbee.printf(" PSI,"); break; case 1: xbee.printf(" Torr,"); break; case 2: xbee.printf(" Kpa,"); break; } } if(tempSensor&&presSensor1) { xbee.printf("Temp 1"); switch(convertType) { case 0: xbee.printf(" C,"); break; case 1: xbee.printf(" F,"); break; case 2: xbee.printf(" K,"); break; } } if(presSensor2) { xbee.printf("Sensor 2"); switch(convertType) { case 0: xbee.printf(" PSI,"); break; case 1: xbee.printf(" Torr,"); break; case 2: xbee.printf(" Kpa,"); break; } } if(tempSensor&&presSensor2) { xbee.printf("Temp 2"); switch(convertType) { case 0: xbee.printf(" C,"); break; case 1: xbee.printf(" F,"); break; case 2: xbee.printf(" K,"); break; } } xbee.putc('\n'); if(!presSensor1 && !presSensor2) { xbee.printf("Error No Sensors Enabled"); return -1; } while(cmd !='q' || cmd !='Q') { while(!xbee.readable()) { len = get_pressure(pressure); get_temp(temp); if(presSensor1) { xbee.printf("%3.3e,", pressure[0]); if(tempSensor) { xbee.printf("3.3f,",temp[0]); } } if(presSensor2) { xbee.printf("%3.3e,", pressure[1]); if(tempSensor) { xbee.printf("3.3f,",temp[0]); } } xbee.putc('\n'); } cmd = xbee.getc(); } xbee.printf("Done With Test"); return 1; }<file_sep>/*********************************************************************** -Authors: A.Weiss, 7/17/2012, changes <NAME> 23rd, 2013 mbed migration by <NAME> July 15 2014 -Description: This is a Driver for the MPL3115A2 Altimeter for the mbed Nucleo F401RE. -License: This code falls under Public Domian and Beerware. (If you ever meet A.Weiss buy him a beer.) Feel free to change and add to meet your needs. -Hardware Connections: This can connect to any of the I2C buses on the Nucleo. SEE http://mbed.org/platforms/ST-Nucleo-F401RE/ -Dependencies: mbed.h, MPL3115A2.h */ #include "MPL3115A2.h" #include "mbed.h" float MPL3115A2::readAltitude() { char data_write[3]; char data_read[3]; //Wait for PDR bit, indicates we have new pressure data int counter = 0; toggleOneShot(); //Toggle the OST bit causing the sensor to immediately take another reading //Wait for PDR bit, indicates we have new pressure data counter = 0; while( (IIC_Read(STATUS) & (1<<1)) == 0) { if(++counter > 100) { status = false; return(-999); //Error out } wait_ms(1); } //Commands to the data_write[0]=OUT_P_MSB; // Read pressure registers i2c->write(MPL3115A2_ADDRESS, data_write, 1,1); i2c->read(MPL3115A2_ADDRESS, data_read, 3, 0); // Address of data to get toggleOneShot(); //Toggle the OST bit causing the sensor to immediately take another reading // The least significant bytes l_altitude and l_temp are 4-bit, // fractional values, so you must cast the calculation in (float), // shift the value over 4 spots to the right and divide by 16 (since // there are 16 values in 4-bits). float tempcsb = (data_read[LSB]>>4)/16.0; float altitude = (float)( (data_read[MSB] << 8) | data_read[CSB]) + tempcsb; return(altitude); } //Returns the number of feet above sea level float MPL3115A2::readAltitudeFt() { return(readAltitude() * 3.28084); } //Reads the current pressure in Pa //Unit must be set in barometric pressure mode float MPL3115A2::readPressure() { char data_write[3]; char data_read[3]; //Wait for PDR bit, indicates we have new pressure data int counter = 0; toggleOneShot(); //Toggle the OST bit causing the sensor to immediately take another reading //Wait for PDR bit, indicates we have new pressure data counter = 0; while( (IIC_Read(STATUS) & (1<<1)) == 0) { if(++counter > 100) { status = false; return(-999); //Error out } wait_ms(1); } //Commands to the data_write[0]=OUT_P_MSB; // Read pressure registers i2c->write(MPL3115A2_ADDRESS, data_write, 1,1); i2c->read(MPL3115A2_ADDRESS, data_read, 3, 0); // Address of data to get toggleOneShot(); //Toggle the OST bit causing the sensor to immediately take another reading // Pressure comes back as a left shifted 20 bit number long pressure_whole = (long)data_read[MSB]<<16 | (long)data_read[CSB]<<8 | (long)data_read[LSB]; pressure_whole >>= 6; //Pressure is an 18 bit number with 2 bits of decimal. Get rid of decimal portion. data_read[LSB] &= 0x30; //Bits 5/4 represent the fractional component data_read[LSB] >>= 4; //Get it right aligned float pressure_decimal = static_cast<float>(data_read[LSB])/4.0; //Turn it into fraction float pressure = (float)pressure_whole + pressure_decimal; return(pressure); } float MPL3115A2::readTemp() { char data_write[3]; char data_read[3]; toggleOneShot(); //Toggle the OST bit causing the sensor to immediately take another reading //Wait for TDR bit, indicates we have new temp data int counter = 0; while( (IIC_Read(STATUS) & (1<<1)) == 0) { if(++counter > 100) { status = false; return(-999); //Error out } wait_ms(1); } // Read temperature registers data_write[0] = OUT_T_MSB; i2c->write(MPL3115A2_ADDRESS, data_write,1,1); i2c->read(MPL3115A2_ADDRESS,data_read,3,0); // Address of data to get // The least significant bytes l_altitude and l_temp are 4-bit, // fractional values, so you must cast the calculation in (float), // shift the value over 4 spots to the right and divide by 16 (since // there are 16 values in 4-bits). float templsb = (data_read[LSB]>>4)/16.0; //temp, fraction of a degree float temperature = (float)(data_read[MSB] + templsb); return(temperature); } //Give me temperature in Fahrenheit! float MPL3115A2::readTempF() { return((readTemp() * 9.0)/ 5.0 + 32.0); // Convert Celsius to Fahrenheit } //Sets the mode to Barometer //CTRL_REG1, ALT bit void MPL3115A2::setModeBarometer() { char tempSetting = IIC_Read(CTRL_REG1); //Read current settings tempSetting &= ~(1<<7); //Clear ALT bit IIC_Write(CTRL_REG1, tempSetting); } //Sets the mode to Altimeter //CTRL_REG1, ALT bit void MPL3115A2::setModeAltimeter() { char tempSetting = IIC_Read(CTRL_REG1); //Read current settings tempSetting |= (1<<7); //Set ALT bit IIC_Write(CTRL_REG1, tempSetting); } //Puts the sensor in standby mode //This is needed so that we can modify the major control registers void MPL3115A2::setModeStandby() { char tempSetting = IIC_Read(CTRL_REG1); //Read current settings tempSetting &= ~(1<<0); //Clear SBYB bit for Standby mode IIC_Write(CTRL_REG1, tempSetting); } //Puts the sensor in active mode //This is needed so that we can modify the major control registers void MPL3115A2::setModeActive() { char tempSetting = IIC_Read(CTRL_REG1); //Read current settings tempSetting |= (1<<0); //Set SBYB bit for Active mode IIC_Write(CTRL_REG1, tempSetting); } //Setup FIFO mode to one of three modes. See page 26, table 31 //From user jr4284 void MPL3115A2::setFIFOMode(char f_Mode) { if (f_Mode > 3) f_Mode = 3; // FIFO value cannot exceed 3. f_Mode <<= 6; // Shift FIFO byte left 6 to put it in bits 6, 7. char tempSetting = IIC_Read(F_SETUP); //Read current settings tempSetting &= ~(3<<6); // clear bits 6, 7 tempSetting |= f_Mode; //Mask in new FIFO bits IIC_Write(F_SETUP, tempSetting); } //Call with a rate from 0 to 7. See page 33 for table of ratios. //Sets the over sample rate. Datasheet calls for 128 but you can set it //from 1 to 128 samples. The higher the oversample rate the greater //the time between data samples. void MPL3115A2::setOversampleRate(char sampleRate) { if(sampleRate > 7) sampleRate = 7; //OS cannot be larger than 0b.0111 sampleRate <<= 3; //Align it for the CTRL_REG1 register char tempSetting = IIC_Read(CTRL_REG1); //Read current settings tempSetting &= 0xc7; //0b11000111; //Clear out old OS bits tempSetting |= sampleRate; //Mask in new OS bits IIC_Write(CTRL_REG1, tempSetting); } //Clears then sets the OST bit which causes the sensor to immediately take another reading //Needed to sample faster than 1Hz void MPL3115A2::toggleOneShot(void) { char tempSetting = IIC_Read(CTRL_REG1); //Read current settings tempSetting &= ~(1<<1); //Clear OST bit IIC_Write(CTRL_REG1, tempSetting); tempSetting = IIC_Read(CTRL_REG1); //Read current settings to be safe tempSetting |= (1<<1); //Set OST bit IIC_Write(CTRL_REG1, tempSetting); } //Enables the pressure and temp measurement event flags so that we can //test against them. This is recommended in datasheet during setup. void MPL3115A2::enableEventFlags() { IIC_Write(PT_DATA_CFG, 0x07); // Enable all three pressure and temp event flags } // These are the two I2C functions in this sketch. char MPL3115A2::IIC_Read(char regAddr) { char data_read[3]; char data_write[3]; // This function reads one byte over IIC data_write[0] =regAddr; i2c->write(MPL3115A2_ADDRESS,data_write,1,1); // Address of CTRL_REG1 i2c->read(MPL3115A2_ADDRESS,data_read,1,0); // Send data to I2C dev with option for a repeated start. THIS IS NECESSARY and not supported before Arduino V1.0.1! return data_read[0]; } void MPL3115A2::IIC_Write(char regAddr, char value) { char data_write[2]; data_write[0] = regAddr; data_write[1] = value; // This function writes one byte over IIC i2c->write(MPL3115A2_ADDRESS,data_write,2,1); } bool MPL3115A2::get_status() { return status; } bool MPL3115A2::check_connection() { int counter = 0; while( (IIC_Read(STATUS) & (1<<1)) == 0) { if(++counter > 100) { status = false; return(false); //Error out } wait_ms(1); } }
91619de116426f6a2807bc631b12e37dfaf475f3
[ "C++" ]
3
C++
JordenLuke/Mbed-PressureSensor
ad3b1bc391dddd07a5cd9be3f8ae0428ae01da67
968f18198617e800b4ec16f617db603e3683da41
refs/heads/master
<file_sep>package shell import ( "context" "fmt" "github.com/chrislusf/seaweedfs/weed/filer2" "github.com/chrislusf/seaweedfs/weed/pb/filer_pb" "io" "strings" ) func init() { commands = append(commands, &commandFsCd{}) } type commandFsCd struct { } func (c *commandFsCd) Name() string { return "fs.cd" } func (c *commandFsCd) Help() string { return `change directory to http://<filer_server>:<port>/dir/ The full path can be too long to type. For example, fs.ls http://<filer_server>:<port>/some/path/to/file_name can be simplified as fs.cd http://<filer_server>:<port>/some/path fs.ls to/file_name ` } func (c *commandFsCd) Do(args []string, commandEnv *commandEnv, writer io.Writer) (err error) { input := "" if len(args) > 0 { input = args[len(args)-1] } filerServer, filerPort, path, err := commandEnv.parseUrl(input) if err != nil { return err } dir, name := filer2.FullPath(path).DirAndName() if strings.HasSuffix(path, "/") { if path == "/" { dir, name = "/", "" } else { dir, name = filer2.FullPath(path[0:len(path)-1]).DirAndName() } } ctx := context.Background() err = commandEnv.withFilerClient(ctx, filerServer, filerPort, func(client filer_pb.SeaweedFilerClient) error { resp, listErr := client.ListEntries(ctx, &filer_pb.ListEntriesRequest{ Directory: dir, Prefix: name, StartFromFileName: name, InclusiveStartFrom: true, Limit: 1, }) if listErr != nil { return listErr } if path == "" || path == "/" { return nil } if len(resp.Entries) == 0 { return fmt.Errorf("entry not found") } if resp.Entries[0].Name != name { println("path", path, "dir", dir, "name", name, "found", resp.Entries[0].Name) return fmt.Errorf("not a valid directory, found %s", resp.Entries[0].Name) } if !resp.Entries[0].IsDirectory { return fmt.Errorf("not a directory") } return nil }) if err == nil { commandEnv.option.FilerHost = filerServer commandEnv.option.FilerPort = filerPort commandEnv.option.Directory = path } return err }
dc443bbe30b2178f24c67c19ef732013b8cabd0f
[ "Go" ]
1
Go
zhujianfeng01/seaweedfs
715a38da1e4fce05631f230ccf09ce92c99a4fd4
2d5f723291a507db3c0103bda1370273ab4a7ad3
refs/heads/master
<repo_name>wlan0/koki<file_sep>/main.go package main import "fmt" func main() { fmt.Println("Koki is no-op") } <file_sep>/README.md # Koki Koki is an open source platform for application lifecycle automation with Kubernetes. It is very simple to setup, configure and use while being powerful enough to automate any application workload. It is an orchestrator that orchestrates lifecycles of applications running on Kubernetes. Koki is a platform that leverages the power of the Kubernetes framework to deliver automation for application workloads. Koki’s aim is to provide configuration management, release management, and application lifecycle management through a declarative interface. Koki is designed to be highly extensible and it can be easily plugged into any existing system for monitoring, alerting, scaling, upgrading, snapshotting, backing up etc. It is pronounced "coke-ee" # Why Koki? There are a plethora of IT automation tools available today. Some well known names include Ansible, Chef, Puppet etc. These tools provide various levels and styles of infrastructure automation. They however mix application lifecycle management with cluster management. This means that application lifecycle designers also have to be wary of infrastructure management concerns. Coupling application lifecycle behavior with infrastructure management makes it difficult to create infrastructure agnostic deployment descriptors. i.e, deployment descriptors that can be reused by others easily and on their existing infrastructure without changes. Users of Koki can completely specify an application “sprint” without understanding the dynamics of the underlying infrastructure. This will enable modern software development teams, where each team prefers running applications in their own way, to control and maintain their application without any of the overhead of mangling their system to work with centralized infrastructure. This is designed to ease the life of IT engineers in SE teams, and help reduce the number of IT disasters by removing the human factor from this process. <file_sep>/scripts/docs.sh #!/bin/bash set -e cd $(dirname $0)/.. mkdocs build --clean #removing this because docs for short is created in the koki/short rm -r site/short aws s3 sync site/ s3://docs.koki.io/ --acl public-read <file_sep>/docs/index.md ![Koki](https://avatars2.githubusercontent.com/u/150253?s=200&v=4) Platform and Suite of tools for managing applications running on Kubernetes ## Products | Product | Description |Docs |Source | |------------|--------------------------------------------------|---------------------------------|----------------------------------| |Koki Short | A better way to create and read kubernetes YAML | [Docs](https://docs.koki.io/short) | [Koki/Short](https://github.com/koki/short) | ## Libraries | Library | Description | Docs |Source | |-----------|--------------------|--------------------------------|------------------------------------| | JSON lib | Fork of golang `encoding/json` with validation and path based error messages | [Docs](https://github.com/koki/json) | [Koki/Json](https://github.com/koki/json) |
9e892e2a7d8d0a92e6ae7c14b861ad87fec8ec66
[ "Markdown", "Go", "Shell" ]
4
Go
wlan0/koki
67a6c86ddfb567cdbcedf9a37b35d5a00e2ace7e
ea274dc618db572579c0f24ee9d3ec19cc6f6ef9
refs/heads/master
<file_sep># Project3 BaskGet is a web application that allows users to bookmark online products by creating wishlists. The user enters in information about the product and will be able to go back and refer to the list and product urls. Below is a short demo of what has been built so far. Created using HTML5, CSS3, Bootstrap, Handlebars, Animate.CSS, Node JS, Express, MongoDB, Mongoose, Passport. ![Demo: ](public/images/demo.gif)<file_sep>// var express = require('express'); // var router = express.Router(); // // Get list page // router.get('/lists', function(req, res){ // console.log("tis working"); // res.render('list'); // }); // module.exports = router;<file_sep>var mongoose = require("mongoose"); var Schema = mongoose.Schema; var ContentSchema = new Schema({ productType: { type: String //product type is a small description of the product }, productTag: { type: String //product tag will be the product vendor }, url: { type: String //product url } }); var Content = mongoose.model("Content", ContentSchema); module.exports = Content;<file_sep> var express = require('express'); var router = express.Router(); var passport = require('passport'); var mongoose = require("mongoose"); var LocalStrategy = require('passport-local').Strategy; mongoose.Promise = Promise; var User = require('../models/user'); var List = require('../models/list'); var Content = require('../models/content'); // Register router.get('/register', function(req, res){ res.render('register'); }); // Login router.get('/login', function(req, res){ res.render('login'); }); // Register User router.post('/register', function(req, res){ var name = req.body.name; var email = req.body.email; var username = req.body.username; var password = <PASSWORD>; var password2 = <PASSWORD>; // Validation req.checkBody('name', 'Name is required').notEmpty(); req.checkBody('email', 'Email is required').notEmpty(); req.checkBody('email', 'Email is not valid').isEmail(); req.checkBody('username', 'Username is required').notEmpty(); req.checkBody('password', '<PASSWORD>').notEmpty(); req.checkBody('password2', 'Passwords do not match').equals(req.body.password); var errors = req.validationErrors(); if(errors){ res.render('register',{ errors:errors }); } else { var newUser = new User({ name: name, email:email, username: username, password: <PASSWORD> }); User.createUser(newUser, function(err, user){ if(err) throw err; console.log(user); }); req.flash('success_msg', 'You are registered and can now login'); res.redirect('/users/login'); } }); passport.use(new LocalStrategy( function(username, password, done) { User.getUserByUsername(username, function(err, user){ if(err) throw err; if(!user){ return done(null, false, {message: 'Unknown User'}); } User.comparePassword(password, user.password, function(err, isMatch){ if(err) throw err; if(isMatch){ return done(null, user); } else { return done(null, false, {message: 'Invalid password'}); } }); }); })); passport.serializeUser(function(user, done) { done(null, user.id); }); passport.deserializeUser(function(id, done) { User.getUserById(id, function(err, user) { done(err, user); }); }); router.post('/login', passport.authenticate('local', {successRedirect:'/', failureRedirect:'/users/login',failureFlash: true}), function(req, res) { res.redirect('/'); }); router.get('/logout', function(req, res){ req.logout(); req.flash('success_msg', 'You are logged out'); res.redirect('/users/login'); }); // Get list page router.get('/lists/:title', function(req, res){ var titleList = req.params.title; console.log("titlelist" + titleList); res.render('list', {"title": titleList}); }) //adding content within the list router.post("/lists", function(req, res){ var lstTitle = req.body.title; var productType = req.body.productType; var productTag = req.body.productTag; var url = req.body.url; var newContent = new Content({ productType: productType, productTag: productTag, url: url }) var newList = new List({ title: lstTitle, content: newContent }) List.findOne({title: lstTitle}, function(err, found){ if(err){ console.log("error: " + err); } if(found){ console.log("found it! " + found); var found_title = found.title; updateContent(found_title, newContent); } else{ newList.save(function(err, result){ if(err){ console.log(err); } else{ found_title = result.title; console.log("this is the doc id " + found_title); updateContent(found_title, newContent); } }); } }) var updateContent = function(listTitle, content){ newContent.save(function(err, content){ if (err){ console.log(err); } else{ List.findOneAndUpdate({"title": listTitle}, {$push: {"content": content} }, {new: true}, function(err, newdoc){ if(err){ console.log(err); } else{ res.send(content); } }) } }) //update content function ending }; //end of the .post method }); //getting all the content within the list router.get("/lists/all/:title", function(req, res, next){ var titleList = req.params.title; console.log(titleList); List.find({"title": titleList}, function(err, found){ }) .populate("content") .exec(function(error, data){ if (error){ res.send("error has occurred "); } else{ res.json(data); } }) }) module.exports = router; <file_sep> // <ul class = "contents"> // <% for(var i=0; i < contents.length; i++){%> // <li class = "content"> // <span><%= contents[i].productType %></span> // </li> // <% }%> // </ul>
d079562340bd667de61eb501542cc41e5c02ba73
[ "Markdown", "JavaScript" ]
5
Markdown
prayavarapu/BaskGet
d5d4b0a72a7675260d654c34c390665efd807d3e
b8f8c1c47128550b546ec363e01ddca36f502d9f
refs/heads/master
<repo_name>DnLKnR/LogSearch<file_sep>/LogSearch.py import os, wx,sys class Window(wx.Frame): def __init__(self,parent,id,title): self.data, self.marked = [],[] wx.Frame.__init__(self,parent,style=wx.DEFAULT_FRAME_STYLE) self.menubar = wx.MenuBar() self.filemenu = wx.Menu() self.m_load = self.filemenu.Append(wx.ID_ANY,'Load\tCtrl-L','') self.menubar.Append(self.filemenu, 'File') self.Bind(wx.EVT_MENU, self.on_load, self.m_load) self.LC = wx.ListCtrl(self,-1,style=wx.LC_REPORT | wx.LC_SINGLE_SEL) self.LC.InsertColumn(0,'Line #',format=wx.LIST_FORMAT_LEFT) self.LC.InsertColumn(1,'String',format=wx.LIST_FORMAT_LEFT) # mainbox = wx.BoxSizer(wx.VERTICAL) self.input = wx.TextCtrl(self,value='') gs = wx.FlexGridSizer(2,1,1,1) gs.Add(self.input,flag = wx.ALL | wx.GROW) gs.Add(self.LC,flag = wx.ALL | wx.GROW) gs.AddGrowableCol(0) gs.AddGrowableRow(1) self.SetMenuBar(self.menubar) self.Bind(wx.EVT_TEXT,self.refresh,self.input) self.Bind(wx.EVT_LIST_ITEM_ACTIVATED,self.mark,self.LC) self.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK,self.mark,self.LC) # mainbox.Add(gs,flag = wx.GROW | wx.EXPAND) self.SetSizer(gs) gs.Fit(self) def on_load(self, event): openFileDialog = wx.FileDialog(self, "Open log file", "", "","", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) if openFileDialog.ShowModal() == wx.ID_CANCEL: return file = openFileDialog.GetPath() self.data,self.marked = Parser().read(file),[] self.refresh(-1) def refresh(self,event): search,count = self.input.GetValue().lower().strip(),0 self.LC.DeleteAllItems() for line in self.data: if search in line[1].strip().lower(): self.LC.Append((line[0],line[1])) if line[0] in self.marked: self.LC.SetItemBackgroundColour(count,'yellow') count += 1 self.LC.SetColumnWidth(0,-1) self.LC.SetColumnWidth(1,-1) def mark(self,event): index = event.GetIndex() line = self.LC.GetItemText(index) if line in self.marked: self.LC.SetItemBackgroundColour(index,'white') self.marked.remove(line) else: self.LC.SetItemBackgroundColour(index,'yellow') self.marked.append(line) class Parser: def __init__(self): self.data = [] def read(self, file): if file == '': return with open(file,'r') as log: text = log.read() self.data = text.split('\n') for index,line in enumerate(self.data): line = line.replace('\n','') line = line.replace('\r','') self.data[index] = [str(index),line] return self.data app = wx.App() app.Window = Window(None,-1,"File Search") app.Window.on_load(-1) app.Window.Show() app.MainLoop()
888d6e79143831025002b01d587fc3a67f143b61
[ "Python" ]
1
Python
DnLKnR/LogSearch
13b5eec16d6eb5b5f9284ec48fff6c5a3c5e89a1
50c70ad691bf1a318d9a346857609aac138596a5
refs/heads/master
<file_sep>var input="[search engines,icon,blue]\n(google,google.com,google.com/?=TEST,icon)\n{gmail,/gmail/,/gmail/?=TEST,icon}"; var lastCategory="others"; var lastSite=""; var category=[]; var site=[]; var subsite=[]; var contents=""; var searchEngine={google:'google.com/search?q=',duckduckgo:'duckduckgo.com/?q=search',luckyDuckduckgo:'duckduckgo.com/?q=\\'}; //, //{name:'google',adress:'google.com',search:'google.com/search?q='}, //{name:'duckduckgo',adress:'duckduckgo.com',search:"duckduckgo.com/?q=search",lucky:"duckduckgo.com/?q=%5C"} //]; document.addEventListener('DOMContentLoaded', function() { document.getElementById('file-input').addEventListener('change', readSingleFile, false); //getCategory("Google"); //alert( category.find(element => element.name == "Google").name ); //alert(category[0].name); contents=localStorage.getItem("contents"); handleFile(contents); //displayContents(contents); document.getElementById("searchQuerry").value=""; document.getElementById("searchQuerry").focus(); createTable(); }, false); function readSingleFile(e) { var file = e.target.files[0]; if (!file) { return; } var reader = new FileReader(); reader.onload = function(e) { var contents = e.target.result; localStorage.setItem("contents",contents); //alert(localStorage.getItem("contents")); }; reader.readAsText(file); window.location.reload(true); } function displayContents(file) { //alert(contents); var text=contents.split('\n'); var temp=""; temp+="Categories:<br>" for(var i=0;i<category.length;i++){ temp+=category[i].name+" "+category[i].icon+" "+category[i].color+"<br>"; } temp+="<br>"; temp+="Sites:<br>" for(var i=0;i<site.length;i++){ temp+=site[i].category+" "+site[i].name+" "+site[i].adress+" "+site[i].search+" "+site[i].icon+"<br>"; } temp+="<br>"; temp+="Subsites:<br>" for(var i=0;i<subsite.length;i++){ temp+=subsite[i].site+" "+subsite[i].name+" "+subsite[i].adress+" "+subsite[i].search+" "+subsite[i].icon+"<br>"; } for(var i=0;i<text.length;i++){ //temp+=text[i]+"<br>"; } document.getElementById('file-content').innerHTML=temp; } function handleFile(file){ var temp=file.split("\n"); temp.forEach(function(element){ //alert(file); handleLine(element); }); } function handleLineBACKUP(line){ //alert(line); var numberOfWhiteSpaces=line.match(/^[\s]*/g).length; var symbol=line[0]; line=line.substring(1,line.length-1) line=line.split(','); switch(symbol){ case '[': lastCategory=line[0]; //addCategory(); addCategory(lastCategory,line[1],line[2]); //alert("adding category "+getCategory("search engines").name); lastSite=""; break; case '(': addSite(lastCategory,line[0],line[1],line[2],line[3]); lastSite=line[0]; //alert("addin site "+line); //alert(getSite().name); break; case '{': //alert(line); addSubsite(lastSite,line[0],line[1],line[2],line[3]); //alert(getSubsite()[0].name); break; case '#': //alert("Adding coment! #"+line); break; case '/': //alert("Adding coment! /"+line); break; default: //alert("Error with file!"); } } function handleLine(line){ if(line.length==0)return false; var s=line.charAt(0); if(s=='[' || s=='(' || s=='{' || s=='#' || s=='/' || s=='\\'){ line=line.substring(1,line.length-1) line=line.split(','); switch(s){ case '[': lastCategory=line[0]; //addCategory(); addCategory(lastCategory,line[1],line[2]); //alert("adding category "+getCategory("search engines").name); lastSite=""; break; case '(': addSite(lastCategory,line[0],line[1],line[2],line[3]); lastSite=line[0]; //alert("addin site "+line); //alert(getSite().name); break; case '{': //alert(line); addSubsite(lastSite,line[0],line[1],line[2],line[3]); //alert(getSubsite()[0].name); break; case '#': //alert("Adding coment! #"+line); break; case '/': //alert("Adding coment! /"+line); break; default: //alert("Error with file!"); } }else{ var noOfWhite=line.search(/\S/); line=line.trim(); //alert(noOfWhite+" "+line); line=line.split(','); switch(noOfWhite){ case 0: //alert("new category"+line); lastCategory=line[0]; addCategory(lastCategory,line[1],line[2]); lastSite=""; break; case 1: case 4: //alert("new site"+line); addSite(lastCategory,line[0],line[1],line[2],line[3]); lastSite=line[0]; break; case 2: case 8: //alert("new subsite"+line); addSubsite(lastSite,line[0],line[1],line[2],line[3]); break; } } //alert(line); } function addCategory(name,icon,color){ category.push({ name:name, icon:icon, color:color } ); } function getCategory(name){ if(name === undefined){ return category; }else{ return category.find(element => element.name == name); } } function addSite(category,name,adress,search,icon){ if(adress === undefined){ adress=name; } if(search!==undefined){ if(search[0]=="/"){ search=adress+search; } } site.push({ category:category, name:name, adress:adress, search:search, icon:icon }); } function getSite(name){ if(name === undefined){ return site; }else{ return site.find(element => element.name == name); } } //reddit.org -site // /r/uniporn -name function addSubsite(site,name,adress,search,icon){ if(adress === undefined){ if(name[0]=="/"){ adress=getSite(site).adress+name; }else { adress=name; } } if(search!==undefined){ if(adress[0]=="/"){ adress=getSite(site).adress+adress; } if(search[0]=="/"){ search=adress+search; } } subsite.push({ site:site, name:name, adress:adress, search:search, icon:icon }); } function getSubsite(name){ if(name === undefined){ return subsite; }else{ return subsite.find(element => element.name == name); } } function countSitesOf(categoryName){ return getSite().filter(e=>e.category==categoryName).length; } function countSubsitesOf(siteAdress){ return getSubsite().filter(e=>e.site==siteAdress).length; } var x=0; var y=0; var xMax; var yMax; function setXandYonButtonClick(td){ alert(td.id); } function createTable(){ var targetDiv = document.getElementById("insert-links-here"); for(var u=0;u<category.length;u++){ var tableDiv=document.createElement("div"); tableDiv.className="table-div"; tableDiv.id=u; targetDiv.appendChild(tableDiv); var table=document.createElement("table"); tableDiv.appendChild(table); var tr=document.createElement("tr"); table.appendChild(tr); var th=document.createElement("th"); th.innerHTML=category[u].name; th.classList.add("category"); tr.appendChild(th); table.appendChild(tr); /* var td=document.createElement("td"); td.innerHTML='<button type="button">'+"Click Me!"+'</button>'; tr.appendChild(td); */ var index=0; for(var i=0;i<site.length;i++){ if(site[i].category==category[u].name){ //yMax+=site[i].name+" "; var tr=document.createElement("tr"); table.appendChild(tr); var td=document.createElement("td"); td.id=u+"x"+index; td.className="linkButton"; td.classList.add("site"); var btn=document.createElement("button"); btn.innerHTML=site[i].name; td.appendChild(btn); //td.innerHTML='<button type="button">'+site[i].name+'</button>'; tr.appendChild(td); table.appendChild(tr); index++; for(var j=0;j<subsite.length;j++){ if(subsite[j].site==site[i].name){ var tr=document.createElement("tr"); table.appendChild(tr); var td=document.createElement("td"); td.id=u+"x"+index; td.classList.add("linkButton"); td.classList.add("subsite"); var btn=document.createElement("button"); btn.innerHTML=subsite[j].name; td.appendChild(btn); //td.innerHTML='<button type="button">'+subsite[j].name+'</button>'; tr.appendChild(td); table.appendChild(tr); index++; } } } } } } document.addEventListener('click', function(e) { e = e || window.event; if(e.target.parentElement.className.includes("linkButton")){ var dimensions=e.target.parentElement.id; //alert(dimensions); dimensions=dimensions.split("x"); deSelectLink(); x=parseInt(dimensions[0]); y=parseInt(dimensions[1]); selectLink(); search(); //updateDevOutput(); } }, false); /* "search"-div with inputs is active <tab> (pressed and relased) - opens hidden text input, where you put site adress for custom search and focuses into it <enter> - launches same button as 'google search' <shift> + <enter> - launches feeling lucky search <arrowDown> - changes active div to "links" "links"-div with list of links is selected <arrowRight>/<arrowLeft> - switch between different categories <arrowDown>/<arrowUp> - 'jumps' into listo of links and activates selected ones <enter> - launches same button as 'google search' <shift> + <enter> - launches feeling lucky search */ var Menu="search"; //Menu="link"; function updateDevOutput(){ xMax=category.length; //yMax=countSubsitesOf(site[x].name); //yMax=countSitesOf(category[x].name); yMax=0; for(var i=0;i<site.length;i++){ if(site[i].category==category[x].name){ yMax++; //yMax+=site[i].name+" "; for(var j=0;j<subsite.length;j++){ if(subsite[j].site==site[i].name)yMax++;//yMax+="[s]"+subsite[j].name+" "; } } } //var temp="x:"+x+" y:"+y+" xMax:"+xMax+" yMax"+yMax+"<br>"; //document.getElementById('dev').innerHTML=temp+" "+Menu; //alert(temp); } function countLinksOfCategory(x){ var temp=0; for(var i=0;i<site.length;i++){ if(site[i].category==category[this.x].name){ temp++; //yMax+=site[i].name+" "; for(var j=0;j<subsite.length;j++){ if(subsite[j].site==site[i].name)temp++;//yMax+="[s]"+subsite[j].name+" "; } } } return temp; } var shiftPressed=false; document.addEventListener('keydown', function(event) { //on <enter> or <shift> launch searching querry. It always works no matter what Menu varaible state //if(document.activeElement.id=="searchQuerry"){ //Menu="links"; document.activeElement.blur(); if(event.key=="Enter"){ search(shiftPressed); } if(event.key=="Shift"){ shiftPressed=true; }else { shiftPressed=false; } if(Menu=="search"){ if(document.activeElement.value==""){ if(event.key=="Tab" || event.key==" " || event.key=="ArrowDown" || event.key == "ArrowLeft" || event.key == "ArrowRight" || event.key=="Backspace"){ Menu="links"; document.activeElement.blur(); } //alert(event.location); }else{ if(event.key=="Tab" || event.key=="ArrowDown"){ Menu="links"; document.activeElement.blur(); } }; } if(Menu=="links"){ deSelectLink(); //document.activeElement.blur(); if(event.key == "ArrowLeft") { //alert('Left was pressed'); if(x>0){ x--; if(y>countLinksOfCategory(x+1)-1)y=countLinksOfCategory(x)-1; } } else if(event.key == "ArrowRight") { //alert('Left was pressed'); if(x<xMax-1){ x++; if(y>countLinksOfCategory(x-1)-1)y=countLinksOfCategory(x)-1; } } else if(event.key == "ArrowUp") { //alert('Left was pressed'); if(y>0)y--; } else if(event.key == "ArrowDown") { //alert('Left was pressed'); if(y<yMax-1)y++; }else{ Menu="links"; document.getElementById("searchQuerry").focus(); return true; } updateDevOutput() selectLink(); } updateDevOutput() }); /////////////////////////////// // Here action really begins /////////////////////////////// function selectLink(){ var selectedLink=document.getElementById(x+"x"+y); selectedLink.classList.add("selectedLink"); Menu="links"; } function deSelectLink(){ var selectedLink=document.getElementById(x+"x"+y); selectedLink.classList.remove("selectedLink"); } function search(lucky){ var querry=document.getElementById("searchQuerry").value; var name=document.getElementById(x+"x"+y).firstChild.innerHTML; var site=getSite(name) || getSubsite(name); if(Menu=="search"){ if(querry==""){ alert("What You want me to do?!"); }else{ //alert("Searching '"+querry+"' using default search engine "+searchEngine[0].search+" "+"http://"+searchEngine[0].search+encodeURI(querry)); if(lucky){ window.location.href ="http://"+encodeURI(searchEngine.luckyDuckduckgo+querry); }else{ window.location.href ="http://"+encodeURI(searchEngine.google+querry); } } }else if(Menu=="links"){ if(querry==""){ window.location.href = "http://"+encodeURI(site.adress); //alert("Redirecting You to:"+site.adress); }else{ if(site.search===undefined){ //alert("Searching '"+querry+"' using default search engine and 'site:' option"); if(lucky){ //alert("Lucky button search!"); window.location.href ="http://"+encodeURI(searchEngine.luckyDuckduckgo+'site:'+site.adress+" "+querry); }else { window.location.href ="http://"+encodeURI(searchEngine.google+'site:'+site.adress+" "+querry); } }else{ //var tempSearch=site.search+querry; //alert("Searching '"+querry+"' using site search by link "+tempSearch); if(lucky){ //alert("Searching "+site.adress+" "+querry+" on feeling ducky!"); window.location.href ="http://"+encodeURI(searchEngine.luckyDuckduckgo+'site:'+site.adress+" "+querry); }else{ var tempSearch=site.search; if(site.search.includes("QUERRY")){ tempSearch=tempSearch.replace('QUERRY',querry); //alert("Going to Querred "+tempSearch) }else{ tempSearch=site.search+querry; //alert("Going to "+site.search+querry); } //alert("Going to "+tempSearch); window.location.href ="http://"+encodeURI(tempSearch); } } } }else{ alert("error in search function!"); } //alert(Menu+" "+querry+" "+site.adress); } ///////////////////////////////// // printing html table /////////////////////////// /* for(var i=0;i<site.length;i++){ if(site[i].category==category[x].name){ yMax+=site[i].name+" "; for(var j=0;j<subsite.length;j++){ if(subsite[j].site==site[i].name)yMax+="[s]"+subsite[j].name+" "; } } } document.addEventListener('keydown', function(event) { //alert(site.length); if(event.key == "ArrowLeft") { //alert('Left was pressed'); if(x>0){ x--; } } else if(event.key == "ArrowRight") { //alert('Left was pressed'); if(x<xMax-1){ x++; } } else if(event.key == "ArrowUp") { //alert('Left was pressed'); if(y>0)y--; } else if(event.key == "ArrowDown") { //alert('Left was pressed'); if(y<yMax-1)y++; } updateDevOutput() }); */ window.addEventListener("keydown", function(e) { // space and arrow keys if([ 38, 40].indexOf(e.keyCode) > -1) { e.preventDefault(); } }, false); <file_sep># Startpage This is repository for my simple startpage. It was made with customizability in mind and it's avaible for everyone [HERE](https://anteczko.github.io/startpage/). Keep in mind that you need to download file with list of websites (blank.txt) and load it first on the website. ![screenshot](https://raw.githubusercontent.com/anteczko/startpage/master/startpage_001.png)
a0ef4b47ff9e862515041d340ce46370024a9e6b
[ "JavaScript", "Markdown" ]
2
JavaScript
anteczko/startpage
d04a852b1fe008f5d36caed90036bc454d8fb63b
0ec084ec63fbb1ca3da51c2a7a8ee5bac05c70e5
refs/heads/master
<file_sep>## This assignment demonstrates how R can cache objects to save ## computations on subsequent calls. ## A matrix can be created with calling makeMatrix() ## An inverse of this matrix can be computed by calling ## cacheSolve(m). ## cacheSolve will call R solve on the first instance. ## subsequent calls to caseSolve will supply the inverse from cache ## Example: ## Create a non-singular matrix: ## > m = makeMatrix(matrix(c(1,2,3, 2,1, 3, 3,2,1),3,3)) ## now call cacheSolve(m) twice ## > cacheSolve(m) ## > cacheSolve(m) ## on the second call, it should show a message that the inverse ## is being served from cache ## Use this special function to create matrix makeMatrix <- function(x = matrix()) { inv_m <- NULL set <- function (y) { x <<- y inv_m <<- NULL } get <- function() { x } setMatrixInverse <- function (inv) { inv_m <<- inv } getMatrixInverse <- function() { inv_m } list( set = set, get = get, setMatrixInverse = setMatrixInverse, getMatrixInverse = getMatrixInverse) } ## This function can cache matrix inverse, and ## save call to solve() on subseqent inverse request cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' m_inv <- x$getMatrixInverse() if(!is.null(m_inv)) { message("getting cached data") return (m_inv) } data <- x$get() m_inv <- solve(data,...) x$setMatrixInv(m_inv) m_inv }
771418e466c8ad4dc0c84760450b366b417e41a9
[ "R" ]
1
R
alamgirm/ProgrammingAssignment2
06125a44f798e6968a46b2a2142e2cfc3e8c3b6e
32c75ca755c7d5afe92dc15f56d4b2166c7f91a0
refs/heads/master
<repo_name>WatchFindDo/Horror-Game-Tutorial-Series<file_sep>/HorrorGameTutorial/Assets/Scripts/PauseSystem.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class PauseSystem : MonoBehaviour { public static PauseSystem pauseSystem; private bool isPaused = false; [SerializeField] private GameObject pauseMenuHolder; [SerializeField] private GameObject settingsHolder; void Start () { pauseSystem = this; } void Update () { if(Input.GetKeyDown(KeyCode.Escape) && !isPaused) { if (GameManager.gameManager.inGameFunction) return; PauseGame(); } else if (Input.GetKeyDown(KeyCode.Escape) && isPaused) { ResumeGame(); } } public void PauseGame () { isPaused = true; GameManager.gameManager.inGameFunction = true; GameManager.gameManager.UnlockCursor(); GameManager.gameManager.EnableBlurEffect(); GameManager.gameManager.UpdateMotion(0); GameManager.gameManager.DisableControls(); pauseMenuHolder.SetActive(true); } public void ResumeGame() { isPaused = false; GameManager.gameManager.inGameFunction = false; GameManager.gameManager.LockCursor(); GameManager.gameManager.DisableBlurEffect(); GameManager.gameManager.UpdateMotion(1); GameManager.gameManager.EnableControls(); pauseMenuHolder.SetActive(false); settingsHolder.SetActive(false); } } <file_sep>/HorrorGameTutorial/Assets/Scripts/PauseMenuButtons.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class PauseMenuButtons : MonoBehaviour { [SerializeField] private GameObject settingsHolder; [SerializeField] private GameObject pauseMenuHolder; public void ResumeGame () { PauseSystem.pauseSystem.ResumeGame(); } public void Settings () { settingsHolder.SetActive(true); pauseMenuHolder.SetActive(false); } public void SettingsBack() { settingsHolder.SetActive(false); pauseMenuHolder.SetActive(true); } public void SettingsApply () { settingsHolder.SetActive(false); pauseMenuHolder.SetActive(true); } public void MainMenu () { Debug.Log("Go to Main Menu."); } public void QuitGame () { Application.Quit(); } } <file_sep>/README.md # Horror-Game-Tutorial-Series Horror Game tutorial series in Unity3D. By: WatchFindDo Media <file_sep>/HorrorGameTutorial/Assets/Editor/SettingsConfig_Editor.cs using UnityEditor; [CustomEditor(typeof(SettingsConfig))] public class SettingsConfig_Editor : Editor { /// <summary> /// Important to keep this script file inside the folder named "Editor"! /// </summary> public override void OnInspectorGUI() { SettingsConfig settingsConfig = (SettingsConfig)target; base.DrawDefaultInspector(); //Draw default parameters EditorGUILayout.Space(); //Create little space EditorGUILayout.LabelField("Current Settings", EditorStyles.boldLabel); //Add label EditorGUI.BeginDisabledGroup(true); //Everything inside will be disabled. float vol = EditorGUILayout.FloatField("Volume", settingsConfig.Volume); int quality = EditorGUILayout.IntField("Quality", settingsConfig.Quality); bool Effects = EditorGUILayout.Toggle("Effects", settingsConfig.Effects); bool Fullscreen = EditorGUILayout.Toggle("FullScreen", settingsConfig.Fullscreen); string res = EditorGUILayout.TextField("Resolution", settingsConfig.Resolution); bool Shadows = EditorGUILayout.Toggle("Shadows", settingsConfig.Shadows); int ShadowsQuality = EditorGUILayout.IntField("Shadows Quality", settingsConfig.ShadowsQuality); float Brightness = EditorGUILayout.FloatField("Brightness", settingsConfig.Brightness); //Everything inside will be disabled. EditorGUI.EndDisabledGroup(); } }
af1faa0adce29b18dc82e4578efb01d0fa3f764e
[ "Markdown", "C#" ]
4
C#
WatchFindDo/Horror-Game-Tutorial-Series
211bff6d9fa1442c86687f447fee631b2ef3382c
3b1a8c5cbfd2a095495d38c9584e592d0e2e8310
refs/heads/master
<repo_name>yalker24/urlcheck<file_sep>/urlcheck.py # encoding = utf-8 import re import time from html import unescape import requests from errbot import BotPlugin class urlcheck(BotPlugin): def callback_message(self, conn, mess): command = re.match('((?:(?:https?|http|ftp):(?://|\\\\)(?:www\.)?|www\.)[\w\d:#@%/;$()~_?\+,\-=\\.&]+)', mess.getBody()) if command: message = mess.getBody() if message.find(' ') > -1: clean_url = message[:message.find(' ')] else: clean_url = message try: """ get the header of the webpage, and later check if it's text/html, because if not requests loads the entire file which is a problem if somebody posts a link to a large file """ h = requests.head(clean_url, timeout=5) except requests.exceptions.RequestException as e: return """ fix the problem that would occur if someone would send an redirect link with a huge file, as requests.head just loads the header of the redirect site and not where the redirection points at (and the content type of redirects is mostly text/html) """ status_code = '{0}'.format(h.status_code) tries = 0 while (status_code.find('30') > -1) and tries < 4: clean_url = h.headers['Location'] try: h = requests.head(clean_url, timeout=5) except requests.exceptions.RequestException as e: return 'wtf bbq {0}'.format(clean_url) status_code = '{0}'.format(h.status_code) tries += 1 """ some websites do not write a content-type in the header... """ if tries >= 4: self.send(mess.getFrom(), 'Too Many Redirects', message_type=mess.getType()) return try: header = h.headers['Content-Type'] except requests.exceptions.RequestException as e: return if header.find('text/html') > -1: try: r = requests.get(clean_url, timeout=5) reddit_check = r.text """ reddit doesn't like if you issue multiple requests in a short period of time """ if reddit_check.find('Too Many Requests') > -1: time.sleep(3) r = requests.get(clean_url, timeout=5) except requests.exceptions.Timeout: failure = 'Request timed out' self.send(mess.getFrom(), failure, message_type=mess.getType()) return except requests.exceptions.RequestException as e: failure = 'Something went wrong: {0}'.format(e) self.send(mess.getFrom(), failure, message_type=mess.getType()) return else: return content = r.text """ as <title> can also haven following options (<title option=>) this searches for the beginning of the title tag and where it closes """ title_tag = content[content.find('<title'):] title_tag = title_tag[:title_tag.find('>')] distance = len(title_tag) + 1 if content.find('</title>') > -1 and distance > 1: title = content[content.find('<title') + distance:content.find('</title>')] """ some websites have whitespaces between the title tag and the actual title """ title = " ".join(title.split()) """ fixing of html encodings """ title = unescape(title) if len(title) > 101: title = '{0} ...'.format(title[:101]) else: title = 'This websites does not seem to have a valid title' self.send(mess.getFrom(), title, message_type=mess.getType()) return
e807d02003af1168ba8892168647d9a336264035
[ "Python" ]
1
Python
yalker24/urlcheck
bf3a5fc7bf2166d69aa6bad54d1a72b2fc36acfe
97c326c7deffa851e8973bf0babcb06017cdfd75
refs/heads/master
<repo_name>DBCDK/dbc-node-services<file_sep>/index.js var api = require('./lib/api'); module.exports = { init : api.init, modules : api.modules } <file_sep>/src/modules/dsx/dsx.module.js "use strict"; var transform = { search: require("./transform/dsx.search.transform"), rank: require("./transform/dsx.rank.transform") }; var dsx = require("../../clients/dsx.client"); var search = function search(data) { return dsx.search(data.query).then(transform.search); }; var recommend = function recommend(data) { return dsx.recommend(data.query).then(transform.rank); }; var rank = function rank(data) { return dsx.rank(data).then(transform.rank); }; var rankSearch = function rankSearch(data) { return search(data).then(function (result) { return { like: data.like, set: result.collections.map(function (item) { return item.id; }) }; }).then(dsx.rank).then(transform.rank); }; module.exports = { search: search, recommend: recommend, rank: rank, rankSearch: rankSearch };<file_sep>/src/modules/cart/transform/cart.transform.js "use strict"; var _ = require("lodash"); module.exports = { getCartTransform: function (response) { var cartContent = { cartContentElements: {} }; if (!_.isUndefined(response.cartContent)) { for (var key in response.cartContent) { var item = response.cartContent[key]; var pid = item.cartContentElement; var id = item.cartContentId; cartContent.cartContentElements[pid] = {}; cartContent.cartContentElements[pid].pid = pid; cartContent.cartContentElements[pid].id = id; } } return cartContent; } };<file_sep>/lib/clients/openUserinfo.client.js var baseclient = require('./base.client'); var config = baseclient.config.openuserinfo; var _default = { securityCode: config.securityCode, outputType: 'soap' }; var openUserinfo = baseclient.client(config.wsdl, _default); var options = { endpoint: config.endpoint }; module.exports = { cart: { getCart: (user) => openUserinfo.request('getCart', {userId: user}, options, true), addCartContent: (content) => openUserinfo.request('addCartContent', content, options, true), removeCartContent: (content) => openUserinfo.request('removeCartContent', content, options, true) }, user : { login : (user) => openUserinfo.request('login', {userId: user.name, userPinCode : user.password}, options) } }; <file_sep>/src/modules/holdingstatus/transform/holdings.transform.js "use strict"; module.exports = function mutateHoldingsResponse(response) { if (response.responder) { var holding = response.responder; return { pid: holding.pid, home: Date.parse(Date().slice(0, 15)) == Date.parse(new Date(holding.expectedDelivery).toLocaleDateString()), willLend: response.responder.willLend === "true", expectedDelivery: new Date(holding.expectedDelivery).toLocaleDateString() }; } else { var holding = response.error; return { pid: holding.pid, home: false, willLend: false, error: true, errorMessage: holding.errorMessage }; } };<file_sep>/src/clients/moreinfo.client.js "use strict"; var baseclient = require("./base.client"), config = baseclient.config.moreinfo, _default = { authentication: { authenticationUser: config.user, authenticationGroup: config.group, authenticationPassword: <PASSWORD> } }, moreinfo = baseclient.client(config.wsdl, _default); module.exports = { info: function (pid) { return moreinfo.request("moreInfo", { identifier: { localIdentifier: pid.split(":").pop() } }); } };<file_sep>/lib/modules/search/search.module.js var transform = require('./transform/dkabm.transform.js'); var opensearch = require('../../clients/openSearch.client'); module.exports.search = function(data) { return opensearch.search(data.query) .then(transform); } <file_sep>/src/modules/search/search.module.js "use strict"; var transform = require("./transform/dkabm.transform.js"); var opensearch = require("../../clients/openSearch.client"); module.exports.search = function (data) { return opensearch.search(data.query).then(transform); };<file_sep>/src/modules/holdingstatus/holdings.module.js "use strict"; var transform = require("./transform/holdings.transform.js"); var openHoldingstatus = require("../../clients/openHoldingstatus.client"); module.exports.getHoldings = function (data, user) { return openHoldingstatus.holdings(data).then(transform); };<file_sep>/lib/modules/user/user.module.js var openUserinfo = require('../../clients/openUserinfo.client'); module.exports.login = function(data) { return openUserinfo.user.login(data); } <file_sep>/src/modules/search/transform/dkabm.transform.js "use strict"; var transform = require("jsonpath-object-transform"); module.exports = function (result) { var template = { collections: ["$..collection.object", { id: "$..identifier", title: "$..record..title..$value", type: ["$..record.type", { value: "$..$value", type: "$..xsi:type" }], subjects: ["$..record.subject.*", { value: "$..$value", type: "$..xsi:type" }], abstract: "$..record.abstract", audience: ["$..record.audience..$value"], publisher: ["$..record.publisher"], contributor: ["$..record.contributor..$value"], creator: ["$..record.creator..$value"], date: "$..record.date", format: "$..record.format", language: "$..record.language..$value" }] }; var transformed = transform(result, template); return transformed; };<file_sep>/src/clients/openHoldingstatus.client.js "use strict"; var baseclient = require("./base.client"), config = baseclient.config.openholdingstatus, _default = {}, openHoldingsstatus = baseclient.client(config.wsdl, _default); module.exports = { holdings: function (query) { return openHoldingsstatus.request("holdingsService", { lookupRecord: query }); } };<file_sep>/src/clients/openSearch.client.js "use strict"; var baseclient = require("./base.client"), config = baseclient.config.opensearch; var _default = { agency: config.agency, profile: config.profile, start: 1, stepValue: 10, sort: "rank_frequency", collectionType: "manifestation" }; var opensearch = baseclient.client(config.wsdl, _default); module.exports = { search: function (query) { return opensearch.request("searchOperation", { query: query }); }, objectGet: function (pid) { return opensearch.request("objectGet", { pid: pid }); } };<file_sep>/README.md # dbc-node-services [![GitHub release](https://img.shields.io/github/tag/dbcdk/dbc-node-services.svg?style=flat-square)](https://github.com/DBCDK/dbc-node-services) [![David](https://img.shields.io/david/dbcdk/dbc-node-services.svg?style=flat-square)](https://david-dm.org/DBCDK/dbc-node-services#info) [![David](https://img.shields.io/david/dev/DBCDK/dbc-node-services.svg?style=flat-square)](https://david-dm.org/DBCDK/dbc-node-services#info=devDependencies) Library for integrating dbc services in node <file_sep>/Brocfile.js var babelTranspiler = require("broccoli-babel-transpiler"); module.exports = babelTranspiler('lib', {}); <file_sep>/src/api.js "use strict"; var search = require("./modules/search/search.module"); var dsx = require("./modules/dsx/dsx.module"); var holdings = require("./modules/holdingstatus/holdings.module"); var frontpage = require("./modules/frontpage/frontpage.module"); var cart = require("./modules/cart/cart.module"); var user = require("./modules/user/user.module"); var Dispatcher = require("./dispatcher"); module.exports.init = function (io) { //initiate dispatcher var dispatcher = Dispatcher(); dispatcher.init(io); // Setup search listeners dispatcher.listen("search", search.search); // Setup dsx listeners dispatcher.listen("dsxSearch", dsx.search); dispatcher.listen("dsxRecommend", dsx.recommend); dispatcher.listen("dsxRank", dsx.rank); dispatcher.listen("dsxRankSearch", dsx.rankSearch); // Setup Cart listeners dispatcher.listen("getCart", cart.getCart); dispatcher.listen("addCartContent", cart.addCartContent); dispatcher.listen("removeCartContent", cart.removeCartContent); //Setup frontpage listeners dispatcher.listen("getImages", frontpage.getImages); //Setup holdings listeners dispatcher.listen("getHoldings", holdings.getHoldings); }; module.exports.modules = { search: search, dsx: dsx, holdings: holdings, frontpage: frontpage, cart: cart, user: user };<file_sep>/src/modules/dsx/transform/dsx.search.transform.js "use strict"; var transform = require("jsonpath-object-transform"); module.exports = function (result) { var collections = result.result.map(function (element) { var fields = element.key.split("::"); return { id: element.pid, title: fields[0], creator: [fields[1]], abstract: null }; }); return { collections: collections }; };<file_sep>/lib/clients/openSearch.client.js var baseclient = require('./base.client'), config = baseclient.config.opensearch; var _default = { agency : config.agency, profile : config.profile, start : 1, stepValue : 10, sort : 'rank_frequency', collectionType : 'manifestation' } var opensearch = baseclient.client(config.wsdl, _default); module.exports = { search : (query) => opensearch.request('searchOperation', {query : query}), objectGet : (pid) => opensearch.request('objectGet', {pid : pid}) } <file_sep>/src/dispatcher.js /** * Contains all eventlisteners that should be instantiated on new connections * @type {Array} */ "use strict"; var _listeners = new Array(); var _connections = new Array(); /** * The Dispatcher is a wrapper for socket.io. It will handle all communication * between server and client * * @param {[Object]} server a node http server is needed to initialize socket.io */ function Dispatcher() { /** * Initialize dispatcher with a socket.io server * @param {IoSocketServer} io instance of socket.io * @return {null} */ function init(io) { io.on("connection", makeConnection); } /** * Callback method for new connections * @param {Socket} connection a new socket connection * @return {null} */ function makeConnection(connection) { var user = connection.request.session && connection.request.session.passport && connection.request.session.passport.user || null; _listeners.map(function (listener) { connection.on(listener.type + "Request", function (data) { listener.callback(data, user).then(function (data) { connection.emit(listener.type + "Response", data); }); }); }); } /** * Add new listener * * Listeners are added to an array of listeners that will be initiated on * new connections * * @param {String} type Type of event to listen for * @param {Function} callback Callback function on event */ function addListener(type, callback) { _listeners.push({ type: type, callback: callback }); } function emitToUser(user, type, data) { var connections = getUserConnections(user); connections.map(function (connection) { return connection.emit(type, data); }); } function getUserConnections(user) { return _connections.filter(function (connection) { return connection.user == user; }); } // Return factory, with a method for adding an event listener return { init: init, listen: addListener, emitToUser: emitToUser }; } // Export Dispatcher module module.exports = Dispatcher;<file_sep>/src/clients/openUserinfo.client.js "use strict"; var baseclient = require("./base.client"); var config = baseclient.config.openuserinfo; var _default = { securityCode: config.securityCode, outputType: "soap" }; var openUserinfo = baseclient.client(config.wsdl, _default); var options = { endpoint: config.endpoint }; module.exports = { cart: { getCart: function (user) { return openUserinfo.request("getCart", { userId: user }, options, true); }, addCartContent: function (content) { return openUserinfo.request("addCartContent", content, options, true); }, removeCartContent: function (content) { return openUserinfo.request("removeCartContent", content, options, true); } }, user: { login: function (user) { return openUserinfo.request("login", { userId: user.name, userPinCode: user.password }, options); } } };<file_sep>/lib/modules/dsx/transform/dsx.rank.transform.js var transform = require('jsonpath-object-transform'); module.exports = function(result) { console.log(result); let collections = result.result.map((element) => { let fields = element[1].ctkey.split('::'); return { id : element[0], title : fields[0], creator : [fields[1]], abstract : null } }); return { collections : collections } }; <file_sep>/src/modules/frontpage/test.js "use strict"; require("babel/register"); var http = require("http").createServer().listen(3000); client = require("./client/moreinfo.client"); client.info("870970-basis:23959798".split(":").pop()).then(console.log)["catch"](console.error);
04b7096d5f9741b3490c345ba548e36dc7bece07
[ "JavaScript", "Markdown" ]
22
JavaScript
DBCDK/dbc-node-services
5e746fca6d232d2d86d75da01a46399e19840381
b7589766981a3598104f9c39eff1d517f0ddc323
refs/heads/master
<file_sep># freudian Freudian Translator <file_sep>#Freudian Translator toword_Freud = "this is a test" tolist_Freud = list() def to_Freud(toword_Freud): print toword_Freud if toword_Freud == " ": print "" else: tolist_Freud = toword_Freud.split(" ") print tolist_Freud for i in range(len(tolist_Freud)): tolist_Freud[i] = "sex" Freudian = " ".join(tolist_Freud) print Freudian to_Freud(toword_Freud)
83a5814b1af71f7c5bf8412b7674f583e4c5db35
[ "Markdown", "Python" ]
2
Markdown
mik0153/freudian
319afd3719bab05d4983ea3b4ada26fb83e98ea8
47fea14f66d4230dc77b83be3496e11127957b0a
refs/heads/master
<file_sep>package com.mohamedhashim.healthchain import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView /** * Created by <NAME> on 6/27/2018. */ class MoviesAdapter(private val moviesList: List<Doctor>) : RecyclerView.Adapter<MoviesAdapter.MyViewHolder>() { inner class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) { var year: TextView var genre: TextView init { genre = view.findViewById<TextView>(R.id.person_name) year = view.findViewById<TextView>(R.id.person_age) } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder { val itemView = LayoutInflater.from(parent.context) .inflate(R.layout.item, parent, false) return MyViewHolder(itemView) } override fun onBindViewHolder(holder: MyViewHolder, position: Int) { val movie = moviesList[position] holder.genre.setText(movie.genre) holder.year.setText(movie.year) } override fun getItemCount(): Int { return moviesList.size } }<file_sep>package com.mohamedhashim.healthchain import android.content.Intent import android.graphics.Typeface import android.os.Bundle import android.os.Handler import android.support.v7.app.AppCompatActivity import android.widget.TextView class SplashActivity : AppCompatActivity() { private lateinit var tvAppName: TextView private lateinit var tvAppInfo: TextView private val SPLASH_TIME_OUT = 3000 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash) tvAppName = findViewById<TextView>(R.id.tv_app_name) tvAppInfo = findViewById<TextView>(R.id.tv_app_info) val cera_round_font = Typeface.createFromAsset(assets, "fonts/cera_round_pro_demo_medium.otf") tvAppName.typeface = cera_round_font tvAppInfo.typeface = cera_round_font Handler().postDelayed(Runnable { val i = Intent(this@SplashActivity, LoginActivity::class.java) startActivity(i) finish() }, SPLASH_TIME_OUT.toLong()) } } <file_sep>package com.mohamedhashim.healthchain import android.content.Context import android.content.DialogInterface import android.os.Bundle import android.support.design.widget.FloatingActionButton import android.support.design.widget.NavigationView import android.support.v4.view.GravityCompat import android.support.v4.widget.DrawerLayout import android.support.v7.app.AlertDialog import android.support.v7.app.AppCompatActivity import android.support.v7.widget.DefaultItemAnimator import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.MenuItem import android.view.View import android.widget.EditText import android.widget.Toast import com.android.volley.Request import com.android.volley.Response import com.android.volley.VolleyError import com.android.volley.toolbox.StringRequest import com.android.volley.toolbox.Volley import org.json.JSONArray import org.json.JSONObject /** * Created by <NAME> on 6/17/2018. */ class DoctorDashboardActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener { private val DoctorList = ArrayList<Doctor>() private var recyclerView: RecyclerView? = null private var mAdapter: MoviesAdapter? = null private lateinit var fab: FloatingActionButton override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_doctor_dashboard) fab = findViewById<FloatingActionButton>(R.id.fab) fab.setOnClickListener(View.OnClickListener { showChangeLangDialog() }) recyclerView = findViewById<RecyclerView>(R.id.patients_recyclerview) mAdapter = MoviesAdapter(DoctorList) val mLayoutManager = LinearLayoutManager(this) recyclerView!!.layoutManager = mLayoutManager recyclerView!!.itemAnimator = DefaultItemAnimator() recyclerView!!.adapter = mAdapter // prepareDoctorData() postNewComment(this) } // private fun prepareDoctorData() { // var Doctor = Doctor("Mad Max: Fury Road", "Action & Adventure", "2015") // DoctorList.add(Doctor) // // Doctor = Doctor("Inside Out", "Animation, Kids & Family", "2015") // DoctorList.add(Doctor) // // Doctor = Doctor("Star Wars: Episode VII - The Force Awakens", "Action", "2015") // DoctorList.add(Doctor) // // Doctor = Doctor("Shaun the Sheep", "Animation", "2015") // DoctorList.add(Doctor) // // Doctor = Doctor("The Martian", "Science Fiction & Fantasy", "2015") // DoctorList.add(Doctor) // // Doctor = Doctor("Mission: Impossible Rogue Nation", "Action", "2015") // DoctorList.add(Doctor) // // Doctor = Doctor("Up", "Animation", "2009") // DoctorList.add(Doctor) // // Doctor = Doctor("Star Trek", "Science Fiction", "2009") // DoctorList.add(Doctor) // // Doctor = Doctor("The LEGO Doctor", "Animation", "2014") // DoctorList.add(Doctor) // // Doctor = Doctor("Iron Man", "Action & Adventure", "2008") // DoctorList.add(Doctor) // // Doctor = Doctor("Aliens", "Science Fiction", "1986") // DoctorList.add(Doctor) // // Doctor = Doctor("Chicken Run", "Animation", "2000") // DoctorList.add(Doctor) // // Doctor = Doctor("Back to the Future", "Science Fiction", "1985") // DoctorList.add(Doctor) // // Doctor = Doctor("Raiders of the Lost Ark", "Action & Adventure", "1981") // DoctorList.add(Doctor) // // Doctor = Doctor("Goldfinger", "Action & Adventure", "1965") // DoctorList.add(Doctor) // // Doctor = Doctor("Guardians of the Galaxy", "Science Fiction & Fantasy", "2014") // DoctorList.add(Doctor) // // mAdapter!!.notifyDataSetChanged() // // } fun postNewComment(context: Context) { // val mPostCommentResponse: PostCommentResponseListener // mPostCommentResponsese!!.requestStarted() val queue = Volley.newRequestQueue(context) val sr = object : StringRequest(Request.Method.GET, "http://ec2-18-216-204-179.us-east-2.compute.amazonaws.com:3000/api/patient", object : Response.Listener<String> { override fun onResponse(response: String) { // mPostCommentResponse.requestCompleted() // Log.d("logs",mPostCommentResponse.toString()) // Toast.makeText(applicationContext, response, Toast.LENGTH_LONG).show() val json = JSONArray(response) for (i in 0 until json.length()) { var jsonObject: JSONObject = json.getJSONObject(i) val str_value = jsonObject.getString("fName") val str_name = jsonObject.getString("lname") // val str_age = jsonObject.getInt("Age") var Doctor = Doctor(str_value + " " + str_name, str_value + " " + str_name, "22") DoctorList.add(Doctor) mAdapter!!.notifyDataSetChanged() } } }, object : Response.ErrorListener { override fun onErrorResponse(error: VolleyError) { // mPostCommentResponse.requestEndedWithError(error) Toast.makeText(applicationContext, "ERORR " + error.toString(), Toast.LENGTH_LONG).show() } }) { // override fun getParams(): Map<String, String> { // val params = HashMap<String, String>() // params["patientID"] = "306" // params["fName"] = "Mohamed" // params["lname"] = "Hashim" // params["GenderType"] = "male" // params["Age"] = "100" // params["email"] = "<EMAIL>" // params["PhonNumber"] = "100" // params["Age"] = "100" // params["department"] = "Dentist" // val jsonAddress = JSONObject() // jsonAddress.put("city", "Cairo") // jsonAddress.put("street", "Awad Elsisy") // params["address"] = jsonAddress.toString() // val par = HashMap<String, String>() // par["data"] = params.toString() // Toast.makeText(applicationContext, par.toString(), Toast.LENGTH_LONG).show() // return par // } // @Throws(AuthFailureError::class) // override fun getHeaders(): Map<String, String> { // val params = HashMap<String, String>() // params["Accept"] = "application/json" // params["Content-Type"] = "application/json" // return params // } } queue.add(sr) } interface PostCommentResponseListener { fun requestStarted() fun requestCompleted() fun requestEndedWithError(error: VolleyError) } fun showChangeLangDialog() { val dialogBuilder = AlertDialog.Builder(this) val inflater = this.layoutInflater val dialogView = inflater.inflate(R.layout.custom_dialog, null) dialogBuilder.setView(dialogView) val edt1 = dialogView.findViewById<EditText>(R.id.edit1) val edt2 = dialogView.findViewById<EditText>(R.id.edit2) val edt3 = dialogView.findViewById<EditText>(R.id.edit3) dialogBuilder.setTitle("Patient Form") // dialogBuilder.setMessage("Enter text below") dialogBuilder.setPositiveButton("Submit", DialogInterface.OnClickListener { dialog, whichButton -> //do something with edt.getText().toString(); var Doctor = Doctor(edt1.text.toString() + " " + edt2.text.toString(), edt1.text.toString() + " " + edt2.text.toString(), edt3.text.toString()) DoctorList.add(Doctor) mAdapter!!.notifyDataSetChanged() dialog.dismiss() Toast.makeText(applicationContext, "Patient is added successfully", Toast.LENGTH_LONG).show() }) // dialogBuilder.setNegativeButton("Cancel", DialogInterface.OnClickListener { dialog, whichButton -> // //pass // }) val b = dialogBuilder.create() b.show() } override fun onNavigationItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.nav_logout -> { this.finish() } } val drawer = findViewById<DrawerLayout>(R.id.drawer_layout) drawer.closeDrawer(GravityCompat.START) return true } }<file_sep>package com.mohamedhashim.healthchain import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import br.com.simplepass.loading_button_lib.customViews.CircularProgressImageButton /** * Created by <NAME> on 6/17/2018. */ class LoginActivity : AppCompatActivity() { private lateinit var login_btn: CircularProgressImageButton override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) login_btn = findViewById<CircularProgressImageButton>(R.id.btn_login) login_btn.setOnClickListener { var intent: Intent = Intent(this, DoctorDashboardActivity::class.java) startActivity(intent) } } }
3399537725b0b3bade0942de198021b6b75f2569
[ "Kotlin" ]
4
Kotlin
MohamedHashim/HealthChain
393eb411d107e61839a639405286b23225028432
6c07d550d1c8400bf0ea970dec608f9a93a7aaec
refs/heads/master
<repo_name>JorgeFigueroa/fileio<file_sep>/src/it/engim/PetUtils.java package it.engim; import it.engim.interfaces.Anagrafe; public class PetUtils { public static void printAnagrafe(Anagrafe anagrafica) { anagrafica.stampaNomeAnimalePadrone(); } public static void main(String[] args) { // main ctrl spazio AnagrafeAnimale cani = new AnagrafeAnimale("cane", null); AnagrafeAnimale gatti = new AnagrafeAnimale("gatti", null); printAnagrafe(cani); printAnagrafe(gatti); //Anagrafe anagrafe = new AnagrafeCani(""); } } <file_sep>/src/it/engim/interfaces/Anagrafe.java package it.engim.interfaces; public interface Anagrafe { public String getNome(); public void stampaNomeAnimalePadrone(); public void stampaNomeAnimalePadrone(int i); } <file_sep>/src/it/engim/ProvaAnagrafe.java package it.engim; import it.engim.model.Cane; import it.engim.model.Persona; public class ProvaAnagrafe{ public static void main(String[] args){ // creazione coppia 1 Cane caneA = new Cane("Miky",12,'M'); Persona personaA = new Persona("Mario","Rossi","MR721"); Coppia coppiaA = new Coppia(caneA,personaA); // creazione coppia 2 Cane caneB = new Cane("Bobby",23,'M'); Persona personaB = new Persona("Pinco","Pallo","PPL"); Coppia coppiaB = new Coppia(caneB,personaB); // creazione coppia 3 Cane caneC = new Cane("Sally",10,'F'); Persona personaC = new Persona("Fiorella","Vasco","FRLVSC"); Coppia coppiaC = new Coppia(caneC,personaC); // creazione coppia 4 Cane caneD = new Cane("Fuffi",5,'M'); Coppia coppiaD = new Coppia(caneD,personaA); // creazione coppia 5 Cane caneE = new Cane("Zora",1,'F'); Coppia coppiaE = new Coppia(caneE,personaA); // creare array di coppie Coppia[] lista = new Coppia[5]; // aggiungere le coppie create lista[0]=coppiaA; lista[1]=coppiaB; lista[2]=coppiaC; lista[3]=coppiaD; lista[4]=coppiaE; AnagrafeAnimale miaAnagrafe = new AnagrafeAnimale("Engimcani",lista); System.out.println("ANAGRAFE CANI: "+ miaAnagrafe.getNome()); System.out.println("-- PROVA stampaNome --- "); miaAnagrafe.stampaNomeAnimalePadrone(0); miaAnagrafe.stampaNomeAnimalePadrone(5); miaAnagrafe.stampaNomeAnimalePadrone(-1); System.out.println("-- PROVA stampa tutti i nomi --- "); miaAnagrafe.stampaNomeAnimalePadrone(); System.out.println("-- PROVA getNomePadroneDiCane --- "); String ret = miaAnagrafe.getNomePadroneDiCane(0); System.out.println("Nome Padrone Con cane con ID 0: "+ret); ret=miaAnagrafe.getNomePadroneDiCane(5); System.out.println("Nome Padrone Con cane con ID 5: "+ret); System.out.println("-- PROVA getNomiCaniConPadrone --- "); String [] nomiCani = miaAnagrafe.getNomiCaniConPadrone("Mario"); System.out.println("Cani di Mario:"); for(int i=0;i<nomiCani.length;i++) System.out.println(nomiCani[i]); // definire e inizializzare una nuova anagrafe /* caneA = null; personaA= null; coppiaA.getPersona().getCognome(); pezzo di cod che stampa il nome del cane in // coppiaA se il padrone si chiama Bo di nome // altrimenti stampa la stringa "NO" if(coppiaA.getPersona().getNome().equals("Bo")){ System.out.println(coppiaA.getCane().getNome()); }else{ System.out.println("NO"); } */ } } <file_sep>/src/it/engim/model/Persona.java package it.engim.model; public class Persona{ private String nome; private String cognome; private String codFisc; public Persona(String nome, String cognome, String codFisc ){ this.nome=nome; this.cognome=cognome; this.codFisc=codFisc; } // GETTER nome public String getNome(){ return nome; } // SETTER nome public void setNome(String nome){ this.nome=nome; } // GETTER cognome public String getCognome(){ return cognome; } // SETTER cognome public void setCognome(String cognome){ this.cognome=cognome; } // GETTER cod fisc public String getCodFisc(){ return codFisc; } // SETTER cod fisc public void setCodFisc(String codFisc){ this.codFisc=codFisc; } } <file_sep>/src/it/engim/model/Gatto.java package it.engim.model; import it.engim.Animale; public class Gatto implements Animale{ private String nome; private int idGato; private int eta; private char sesso; public Gatto(String nome, int eta, char sesso) { this.nome = nome; //this.idGato = idGato; this.eta = eta; this.sesso = sesso; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public int getIdAnimale() { return idGato; } public void setIdAnimale(int idGatto) { this.idGato = idGatto; } public int getEta() { return eta; } public void setEta(int eta) { this.eta = eta; } public char getSesso() { return sesso; } public void setSesso(char sesso) { this.sesso = sesso; } }
8a2982da2c69f1b6053ed667dd56dd4ad4208a12
[ "Java" ]
5
Java
JorgeFigueroa/fileio
42ebbbde05e22501f131d8e4e739c095c60e6de1
70b0b7aab9bf6d625c0d4e6b22d36026feef649a
refs/heads/master
<file_sep>// Filename : approx.h // Description : This header file contains the definition of the // function to approximate the value of PI. // Author : <NAME> // Honor Code : I have not asked nor given any aunthorized help // in completing this exercise. #ifndef _APPROX_H_ #define _APPROX_H_ long double approx_pi(int); #endif // _APPROX_H_<file_sep>all: approx-pi approx.o: approx.h approx.cpp g++ -c approx.cpp main.o: main.cpp g++ -c main.cpp approx-pi: approx.o main.o g++ -o approx-pi approx.o main.o test: ./approx-pi < lab1-test.in > lab1-mine.out clean: rm -rf approx-pi *.o<file_sep>// Filename : approx.cpp // Description : This source file contains the implementation of the // function to approximate the value of PI. // Author : <NAME> // Honor Code : I have not asked nor given any aunthorized help // in completing this exercise. // Formula : 4 * (1 - 1/3 + 1/5 - 1/7 + 1/9 - ...) #include "approx.h" long double approx_pi(int n) { long double summation = 0; for (int i = 0; i < n; i++) { int denominator = 1 + (i * 2); if (i % 2 == 0) { summation += 1.0 / (long double) denominator; } else { summation -= 1.0 / (long double) denominator; } } return 4.0 * summation; }<file_sep># CSDC103 - Algorithms and Data Structures Author : <NAME> Email : <EMAIL> Course and Year : 2-BSIT ## About This is the repository of all my exercises, and other activities in **CSDC103** - *Algorithms and Data Structures*<file_sep>all: bonus bonus.o: bonus.cpp g++ -c bonus.cpp bonus: bonus.o g++ -o bonus bonus.o test: ./bonus < bonus.in > bonus.out clean: rm -rf bonus rm -rf *.o<file_sep>all: lab2 lab2.o: lab2.cpp g++ -c lab2.cpp lab2: lab2.o g++ -o lab2 lab2.o clean: rm -rf lab2 *.o<file_sep>// Filename : main.cpp // Description : This program tests the implementation of the // function to approximate the value of PI. // Author : <NAME> // Honor Code : I have not asked nor given any aunthorized help // in completing this exercise. #define FIXED_FLOAT(x) std::fixed << std::setprecision(15) << (x) #include <iostream> #include <iomanip> #include "approx.h" using namespace std; int main() { int cases; cin >> cases; for (int i = 1; i <= cases; i++) { int input; cin >> input; cout << "CASE " << i << ": " << FIXED_FLOAT(approx_pi(input)) << endl; } return 0; }<file_sep>// Filename : bonus.cpp // Description : Code that checks if a number has a digit. // Author : <NAME> // Honor Code : I have not asked nor given any aunthorized help // in completing this exercise. #include <iostream> #include <string> using namespace std; bool contains_digit(int n, int d) { // declare variables string strNum = to_string(n); string strDigit = to_string(d); size_t found = strNum.find(strDigit); // find digit in number string if (found != string::npos) return true; // if digit is found, return true return false; // otherwise, return false } int main() { int cases; cin >> cases; // get the input for number of cases for (int i = 1; i <= cases; i++) { int n, d; cin >> n >> d; // get the input for the number and digit to find if (n < 0 || d < 0) { // check if number is negative cout << "CASE " << i << ": NOT FOUND" << endl; continue; // go to the next iteration } if (contains_digit(n, d)) { // check if digit is found cout << "CASE " << i << ": FOUND" << endl; } else { cout << "CASE " << i << ": NOT FOUND" << endl; } } return 0; }
c499d5015f2cd2cb920a543435253c71a8e8f4ad
[ "Markdown", "C", "Makefile", "C++" ]
8
C
NewblyAaron/csdc103-serrano
c39a9c713d0904927d40bab54dace29d8cd9a3b8
f22007bbad5fc923429965118eaef72cb5da9048
refs/heads/master
<file_sep>/* * 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 materiasdificiles; import java.util.Random; public class MateriasDificiles extends MetodosSteve { public static int sacarPromedio(int matriz[][],int materia,int alumnos){ int i=0, promedio=0; for (i=0;i<alumnos;i++){ promedio+= matriz[i][materia]; } promedio= promedio/alumnos; return promedio; } public static void imprimirMateriaMasFacil (int promedios[],char materias[]){ switch (materias[3]){ case 'm': imprimir("La materia mas facil es Matematica. El promedio es de: "+ promedios[3]); break; case 'l': imprimir("La materia mas facil es Lengua. El promedio es de: "+ promedios[3]); break; case 'g': imprimir("La materia mas facil es Geografia. El promedio es de: "+ promedios[3]); break; case 'h': imprimir("La materia mas facil es Historia. El promedio es de: "+ promedios[3]); break; default: imprimir("Error"); } } public static void imprimirMateriaMasDificil (int promedios[],char materias[]){ switch (materias[0]){ case 'm': imprimir("La materia mas dificil es Matematica. El promedio es de: "+ promedios[0]); break; case 'l': imprimir("La materia mas dificil es Lengua. El promedio es de: "+ promedios[0]); break; case 'g': imprimir("La materia mas dificil es Geografia. El promedio es de: "+ promedios[0]); break; case 'h': imprimir("La materia mas dificil es Historia. El promedio es de: "+ promedios[0]); break; default: imprimir("Error"); } } public static void main(String[] args) { Random rand = new Random(); int cantAlumnos = 0; imprimir("Ingrese la cantidad de alumnos: "); cantAlumnos = tomarInt(); int[][] matriz = new int [cantAlumnos][4]; int[] dificultad = new int[4]; char[] posMateria= new char[4]; int i=0, j=0, auxInt=0; char auxChar=0; int promMatematica=0, promLengua=0, promGeografia=0, promHistoria=0; for (i=0; i<cantAlumnos; i++){ for (j=0; j<4;j++){ matriz[i][j]= rand.nextInt(10)+1 ; } } promMatematica= sacarPromedio(matriz, 0, cantAlumnos); posMateria[0]='m'; dificultad[0]= promMatematica; imprimir(dificultad[0]); promLengua= sacarPromedio(matriz, 1, cantAlumnos); posMateria[1]='l'; dificultad[1]= promLengua; imprimir(dificultad[1]); promGeografia= sacarPromedio(matriz, 2, cantAlumnos); posMateria[2]='g'; dificultad[2]= promGeografia; imprimir(dificultad[2]); promHistoria= sacarPromedio(matriz, 3, cantAlumnos); posMateria[3]='h'; dificultad[3]= promHistoria; imprimir(dificultad[3]); for(i=0;i<4;i++){ for(j=0;j<3;j++){ if(dificultad[j]>=dificultad[j+1]){ auxInt= dificultad[j]; auxChar= posMateria[j]; dificultad[j]= dificultad[j+1]; posMateria[j]= posMateria[j+1]; dificultad[j+1]=auxInt; posMateria[j+1]=auxChar; } } } imprimirMateriaMasFacil(dificultad, posMateria); imprimirMateriaMasDificil(dificultad, posMateria); } }
d81e653b6115c495c806c2479bddbdad8f45ecf4
[ "Java" ]
1
Java
AgusArdizzone/materiasDificiles
86d9cd952b3cdc9ac34e56d99a262f957bd94f2f
843d7ce1e90c3577ff0c2b2b4782820b65fbde54
refs/heads/main
<file_sep> # superheroR [<NAME> \| Twitter: `@Edgar_Zamora_`](https://twitter.com/Edgar_Zamora_) <div class="figure" style="text-align: center"> <img src="https://images.unsplash.com/photo-1588497859490-85d1c17db96d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1050&q=80" alt="Photo by &lt;a href=&quot;https://unsplash.com/@waldemarbrandt67w?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText&quot;&gt;<NAME>&lt;/a&gt; on &lt;a href=&quot;https://unsplash.com/s/photos/comics?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText&quot;&gt;Unsplash&lt;/a&gt;" width="90%" /> <p class="caption"> Photo by <a href="https://unsplash.com/@waldemarbrandt67w?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Waldemar Brandt</a> on <a href="https://unsplash.com/s/photos/comics?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a> </p> </div> [![lifecycle](https://img.shields.io/badge/lifecycle-experimental-orange.svg)](https://www.tidyverse.org/lifecycle/#experimental) <br> The `superheroR` package is a R wrapper that is used to request data from the [SuperHero API](https://superheroapi.com) by specific superhero. The API provides data about a superheros stats, biography, appearances, and more from over 500 superheros from both the comic universes. The only requirement is a access token which can be obtained by linking an individuals personal Facebook account. # Setting access token ``` r Sys.setenv(SUPERHERO_TOKEN = "<KEY>") ``` # Installation ``` r ## install.packages(devtools) devtools::install_github("Edgar-Zamora/superheroR") ``` # Credits <file_sep># Building complete dataset of superhero data. Sys.setenv('SUPERHERO_TOKEN' = '3<PASSWORD>') library(superheroR) library(tidyverse) library(xml2) library(rvest) library(janitor) library(dplyr) library(purrr) library(here) library(janitor) library(readr) superhero_list <- character_ids %>% distinct(id) %>% #slice(1:10) %>% pluck('id') # Getting information all superheros ## Powerstats powerstats <- superhero_list %>% map_df(~get_powerstats(character_id = .x)) ## Biography bio <- superhero_list %>% map_df(~get_bio(character_id = .x)) ## Appearance appearance <- superhero_list %>% map_df(~get_appearance(character_id = .x)) ## Work work <- superhero_list %>% map_df(~get_work(character_id = .x)) ## Connection connections <- superhero_list %>% map_df(~get_connections(character_id = .x)) ## Image image <- superhero_list %>% map_df(~get_connections(character_id = .x)) # Joining all the data together superhero_complete <- appearance %>% left_join(bio) %>% left_join(connections) %>% left_join(powerstats) %>% left_join(work) %>% clean_names() # Writing data write_csv(superhero_complete, "data-raw/superhero_complete_data.csv") save(superhero_complete, file = "data/superhero_complete_data.rda") <file_sep>#' Superhero metadata #' #' A dataset containing information about every superhero. #' #' @format A data frame with 3662 rows and 26 variables: #' \describe{ #' \item{response}{unique id for ech character} #' \item{id}{name of the superhero} #' \item{name}{superhero name} #' \item{gender}{gender of superhero} #' \item{race}{race of superhero} #' \item{height}{height in feet and cm} #' \item{weight}{weight in kg and lb} #' \item{eye_color}{superhero eye color} #' \item{hair_color}{superhero hair color} #' \item{full_name}{full name of superhero} #' \item{alter_egos}{superhero alter egos} #' \item{aliases}{superhero aliases} #' \item{place_of_birth}{birth place of superhero} #' \item{first_appearance}{first appearance of superhero} #' \item{publisher}{publisher of comic} #' \item{alignment}{superheor alignment - bad, good, neutral, unkown} #' \item{group_affiliation}{superhero affliation} #' \item{relatives}{relatives to superhero} #' \item{intelligence}{superhero intelligence, 1-100} #' \item{strength}{superhero strength, 1-100} #' \item{speed}{superhero speed, 1-100} #' \item{durability}{superhero durability, 1-100} #' \item{power}{superhero power, 1-100} #' \item{combat}{superhero combat, 1-100} #' \item{occupation}{superhero occupatoin} #' \item{base}{superhero bases} #' } "superhero_complete" <file_sep>expect_identical(10, 10) <file_sep>## code to prepare `DATASET` dataset goes here # Loading packages library(xml2) library(rvest) library(janitor) library(dplyr) library(purrr) library(here) library(readr) # Scraping site to obtain dataframe with ids and associated characters url <- "https://superheroapi.com/ids.html" character_ids <- url %>% read_html() %>% html_elements('table') %>% html_table() %>% reduce(union) %>% rename( id = X1, character = X2 ) #%>% # group_by(character) %>% # summarise( # id = min(id) # ) %>% # ungroup() # Writing data write_csv(character_ids, "data-raw/character_ids.csv") save(character_ids, file = "data/character_ids.rda") <file_sep>#' Get work/occupation for superhero #' #' @param access_token Required. Unique token obtained from the SuperHero API site. Token should be set to the environment and will be retrieved #' that way. #' @param character_id Required. The \href{https://superheroapi.com/ids.html}{Character ID} or name of the Superhero # #' @return Returns a dataframe with the work/occupation of the specific superhero. #' @export #' #' get_work <- function(access_token = Sys.getenv("SUPERHERO_TOKEN"), character_id) { if(is.character({{character_id}})) { load(file = here("data", "character_ids.rda")) cnvrt_char_str <- character_ids %>% filter(character == str_to_title({{character_id}})) %>% select(id) %>% pluck('id') base_url <- glue('https://superheroapi.com/api/{access_token}/{cnvrt_char_str}/work') results <- GET(url = base_url) work_df <- fromJSON(rawToChar(results$content)) %>% as_tibble() return(work_df) } else{ base_url <- glue('https://superheroapi.com/api/{access_token}/{character_id}/work') results <- GET(url = base_url) work_df <- fromJSON(rawToChar(results$content)) %>% as_tibble() return(work_df) } } <file_sep>#' Call that gets the appearance of a given superhero. #' #' @param access_token Required. Unique token obtained from the SuperHero API site. Token should be set to the environment and will be retrieved #' that way. #' @param character_id Required. The Character ID or name of the Superhero #' #' @return Returns a dataframe with the work/occupation of the specific superhero. #' @export #' @import dplyr #' @importFrom stringr str_to_title #' @importFrom glue glue #' @importFrom here here #' @importFrom purrr pluck #' @import httr #' @importFrom jsonlite fromJSON #' #' get_appearance <- function(access_token = Sys.getenv("SUPERHERO_TOKEN"), character_id) { if(is.character({{character_id}})) { load(file = here("data", "character_ids.rda")) cnvrt_char_str <- character_ids %>% filter(character == str_to_title({{character_id}})) %>% select(id) %>% pluck('id') base_url <- glue('https://superheroapi.com/api/{access_token}/{cnvrt_char_str}/appearance') results <- GET(url = base_url) appearance_df <- fromJSON(rawToChar(results$content)) %>% as_tibble() return(appearance_df) } else{ base_url <- glue('https://superheroapi.com/api/{access_token}/{character_id}/appearance') results <- GET(url = base_url) appearance_df <- fromJSON(rawToChar(results$content)) %>% as_tibble() return(appearance_df) } } <file_sep>#' Call that gives the biographical stats of the superhero. #' #' @param access_token Required. Unique token obtained from the SuperHero API site. Token should be set to the environment and will be retrieved #' that way. #' @param character_id Required. Required. The \href{https://superheroapi.com/ids.html}{Character ID} or name of the Superhero #' #' @return Returns a dataframe with the work/occupation of the specific superhero. #' @export #' @importFrom janitor clean_names #' #' get_bio <- function(access_token = Sys.getenv("SUPERHERO_TOKEN"), character_id) { if(is.character({{character_id}})) { load(file = here("data", "character_ids.rda")) cnvrt_char_str <- character_ids %>% filter(character == str_to_title({{character_id}})) %>% select(id) %>% pluck('id') base_url <- glue('https://superheroapi.com/api/{access_token}/{cnvrt_char_str}/biography') results <- GET(url = base_url) bio_df <- fromJSON(rawToChar(results$content)) %>% as_tibble() %>% janitor::clean_names() return(bio_df) } else{ base_url <- glue('https://superheroapi.com/api/{access_token}/{character_id}/biography') results <- GET(url = base_url) bio_df <- fromJSON(rawToChar(results$content)) %>% as_tibble() %>% clean_names() return(bio_df) } } <file_sep>--- title: "Getting Started" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Getting Started} %\VignetteEngine{knitr::rmarkdown} \usepackage[utf8]{inputenc} --- # I'm Batman! 🦇🤵🃏 ```{r batman_exmp} ``` <file_sep>library(testthat) library(superheroR) test_check("superheroR") <file_sep>#' Characters associated with each id. #' #' A dataset containing the ids associated with each superhero #' #' @format A data frame with 731 rows and 2 variables: #' \describe{ #' \item{id}{unique id for ech character} #' \item{character}{name of the superhero} #' ... #' } "character_ids" <file_sep>--- output: github_document --- ```{r setup, include=FALSE} library(knitr) library(here) knitr::opts_chunk$set(echo = TRUE) ``` # superheroR [<NAME> | Twitter: `@Edgar_Zamora_`](https://twitter.com/Edgar_Zamora_) ```{r unsplash, echo=FALSE, fig.align='center', out.width="90%", fig.cap='Photo by <a href="https://unsplash.com/@waldemarbrandt67w?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText"><NAME></a> on <a href="https://unsplash.com/s/photos/comics?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>'} include_graphics("https://images.unsplash.com/photo-1588497859490-85d1c17db96d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1050&q=80") ``` [![lifecycle](https://img.shields.io/badge/lifecycle-experimental-orange.svg)](https://www.tidyverse.org/lifecycle/#experimental) <br> The `superheroR` package is a R wrapper that is used to request data from the [SuperHero API](https://superheroapi.com) by specific superhero. The API provides data about a superheros stats, biography, appearances, and more from over 500 superheros from both the comic universes. The only requirement is a access token which can be obtained by linking an individuals personal Facebook account. # Setting access token ```{r access_token} Sys.setenv(SUPERHERO_TOKEN = "xxxxxxxxxxxxxxx") ``` # Installation ```{r installation, eval=FALSE} ## install.packages(devtools) devtools::install_github("Edgar-Zamora/superheroR") ``` # Credits <file_sep>#' Call that provides the image of the superhero. #' #' @param access_token Required. Unique token obtained from the SuperHero API site. Token should be set to the environment and will be retrieved #' that way. #' @param character_id Required. The \href{https://superheroapi.com/ids.html}{Character ID} or name of the Superhero # #' @return Returns a dataframe with the work/occupation of the specific superhero. #' @export #' #' @import magick #' get_image <- function(access_token = Sys.getenv("SUPERHERO_TOKEN"), character_id) { if(is.character({{character_id}})) { load(file = here("data", "character_ids.rda")) cnvrt_char_str <- character_ids %>% filter(character == str_to_title({{character_id}})) %>% select(id) %>% pluck('id') base_url <- glue('https://superheroapi.com/api/{access_token}/{cnvrt_char_str}/image') results <- GET(url = base_url) image_df <- fromJSON(rawToChar(results$content)) %>% as_tibble() %>% pluck('url') %>% image_read() %>% image_scale("300") return(image_df) } else{ base_url <- glue('https://superheroapi.com/api/{access_token}/{character_id}/image') results <- GET(url = base_url) image_df <- fromJSON(rawToChar(results$content)) %>% as_tibble() %>% pluck('url') %>% image_read() %>% image_scale("300") return(image_df) } }
e379d190e31e2e7a4efbad71748611c3f4d7be6b
[ "Markdown", "R", "RMarkdown" ]
13
Markdown
Edgar-Zamora/superheroR
88e9de4888566b3273c931efbb2efea585ac932f
f6ea5017797c1226c672e49714b29829cf3d036a
refs/heads/main
<repo_name>qazaqpyn/fc<file_sep>/routes/message.js let express = require('express'); let router = express.Router(); //require controller modules let message_controller = require('../controllers/messageController'); let user_controller = require('../controllers/userController'); let auth_controller = require('../controllers/authController'); const message = require('../models/message'); //message routers //get create message router.get('/message/create',message_controller.message_create_get); //post create message router.post('/message/create', message_controller.message_create_post); //get list of all messages router.get('/messages', message_controller.message_list); //get detail of message router.get('/message/:id',message_controller.message_detail); //get delete message router.get('/message/:id/delete',message_controller.message_delete_get); //post delete message router.post('/message/:id/delete', message_controller.message_delete_post); module.exports = router;<file_sep>/controllers/messageController.js const { body, validationResult } = require('express-validator'); const message = require('../models/message'); let Message = require('../models/message'); let User = require('../models/user'); const async =require('async'); //display list of all messages exports.message_list = function(req, res, next) { Message.find() .populate('user') .exec((err, list_messages) => { if (err) {return next(err);} //succesful render res.render('message_list', {title: 'Message List', message_list: list_messages}); }) }; //display details of message exports.message_detail = function(req,res,next) { Message.findById(req.params.id) .populate('user') .exec(function(err, message_detail) { if(err) {return next(err);} if(message_detail==null) { //there are no result let err = new Error('Message not found'); err.status = 404; return next(err); } res.render('message_detail', {title:message_detail.title, message: message_detail}); }) }; //display message create exports.message_create_get = function(req, res, next) { console.log(req.app.locals.userCurrent.id); User.findOne({"username":req.app.locals.userCurrent.username}) .exec(function(err,result) { if(err) {return next(err);} if(result.statusMember) { res.render('message_form', {title:'Write Message', user: result}); } else { res.redirect('/'); } }) }; //handle create exports.message_create_post = [ body('title', 'Title must not be empty').trim().isLength({min:1}).escape(), body('text', 'Text area must not be empty').trim().isLength({min:1}).escape(), (req,res,next) => { const errors = validationResult(req); let message = new Message({ title: req.body.title, user: req.app.locals.userCurrent.id, text: req.body.text }); if(!errors.isEmpty()) { //there are errors res.render('message_form', {title: 'Write message', user: req.app.locals.userCurrent, errors: errors.array()}); return; } else { message.save(function (err) { if(err) {return next(err);} //successful res.redirect("/catalog"+message.url); }); } } ]; exports.message_delete_get = function(req,res) { res.redirect('/') }; exports.message_delete_post = (req,res,next) => { async.parallel({ user: function(callback) { User.findById(req.app.locals.userCurrent.id).exec(callback); }, message: function(callback) { Message.findById(req.params.id).exec(callback); } }, function(err,results) { //error if(err) {return next(err);} if(!results.user.isAdmin) { res.redirect('/catalog'+results.message.url); } else { Message.findByIdAndRemove(req.params.id, function deleteMessage(err) { if(err) {return next(err);} //success res.redirect('/catalog/messages'); }) } }) }<file_sep>/routes/index.js var express = require('express'); var router = express.Router(); let auth_controller = require('../controllers/authController'); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Express', user: req.user }); }); // get and post requests for sign up router.get('/sign-up', auth_controller.sign_up_get); router.post('/sign-up',auth_controller.sign_up_post); //get and post requests for sign in router.get('/sign-in', auth_controller.sign_in_get); router.post('/sign-in', auth_controller.sign_in_post); router.get('/log-out', auth_controller.log_out_get); router.post('/join-club',auth_controller.join_club_post); module.exports = router; <file_sep>/models/user.js let mongoose = require('mongoose'); let Schema = mongoose.Schema; let UserSchema = new Schema( { first_name: {type: String, required: true, maxLength: 100}, last_name: {type: String, required: true, maxLength: 100}, username: {type: String, required: true, maxLength: 100}, password: {type:String, required: true}, statusMember: {type: Boolean, default: false}, isAdmin: {type: Boolean, default: false} } ); //virtual for user url UserSchema .virtual('url') .get(function(){ return '/user/' + this._id; }); //exports model module.exports = mongoose.model('User', UserSchema);<file_sep>/controllers/authController.js let User = require('../models/user'); let bcrypt = require('bcryptjs'); const { body, validationResult} = require('express-validator'); const passport = require('passport'); const user = require('../models/user'); exports.sign_up_get = function(req,res) { res.render('sign-up-form',{title:'Sign Up Form'}); } exports.sign_up_post = [ // validate and sanitise fields body('first_name', 'First name must be filled').trim().isLength({min:1}).escape(), body('last_name','Last name must be filled').trim().isLength({min:1}).escape(), body('username','username must be filled').trim().isEmail().escape(), body('password', '<PASSWORD>').trim().isLength({min:1}).escape(), body('passwordConfirmation').custom((value, {req}) => { if (value !== req.body.password) { throw new Error('Password confirmation does not match password'); } return true; }), (req,res,next) => { //extract the validation errors from a request const errors = validationResult(req); bcrypt.hash(req.body.password, 10, (err, hashedPassword) => { if(err) {return next(err);} let user = new User( { first_name: req.body.first_name, last_name: req.body.last_name, username: req.body.username, password: <PASSWORD> } ); User.findOne({'username': user.username}) .exec((err, foundUser) => { if(err) {return next(err);} //same username is already exists if(foundUser) { res.render('sign-up-form', {title: 'Sign Up form', problem: "username is taken"}); return; } else if(!errors.isEmpty()) { //there are errors. render again same form res.render('sign-up-form', {title: 'Sign Up Form', user: user, errors: errors.array()}); return; } else { //data is valid. lets save everything user.save(function(err) { if(err) {return next(err);} //successful - render some new page res.redirect('/sign-in'); }); } }) }) } ]; exports.sign_in_get = function(req,res) { res.render('sign-in-form',{title:'Sign In'}) } exports.sign_in_post = passport.authenticate('local', { successRedirect:'/', failureRedirect: '/sign-in' }) exports.log_out_get = function(req,res) { req.logout(); res.redirect('/'); } exports.join_club_post = function(req,res, next) { if(req.body.passcode==='ALA') { User.findOne({"username": req.body.username}) .exec((err, foundUser)=>{ if(err) {return next(err);} console.log('you found it'+ foundUser._id) let updatedUser = new User({ _id: foundUser._id, first_name: foundUser.first_name, last_name: foundUser.last_name, username: foundUser.username, password: <PASSWORD>, statusMember: true, messages: foundUser.messages }); User.findByIdAndUpdate(foundUser._id, updatedUser, {}, function(err, theuser) { if (err) {return next(err);} console.log('updated'); res.redirect('/'); }) }) } }<file_sep>/readme.md #Fight Club ## Members only blog - an exclusive clubhouse where your members can write anonymous posts. Inside the clubhouse, members can see who the author of a post is, but outside they can only see the story and wonder who wrote it. SKILLS: - NodeJS, Express, authentication, CRUD, MVC, MongoDB, PUG,
d918f7aa3dc39dc082d347563613b93ba923abea
[ "JavaScript", "Markdown" ]
6
JavaScript
qazaqpyn/fc
c9dfc7b68c02de72da1d71b619d1ee956bfc39d9
a9b73478feec6f2ee138b2d461723dee9afd350b
refs/heads/main
<file_sep>from django import template register = template.Library() @register.filter def page_query_string(request, page_number): query_args = request.GET.copy() query_args['page'] = page_number return query_args.urlencode() @register.simple_tag def get_companion(user, chat): for u in chat.members.all(): if u != user: return u return None<file_sep>from django import forms from django.forms import ModelForm from webapp.models import Message class SimpleSearchForm(forms.Form): search = forms.CharField(max_length=100, required=False, label="Найти") class MessageForm(ModelForm): class Meta: model = Message fields = ['message'] <file_sep># Generated by Django 2.2 on 2021-01-23 12:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('webapp', '0009_auto_20210123_1254'), ('accounts', '0005_delete_authtoken'), ] operations = [ migrations.AddField( model_name='profile', name='friends', field=models.ManyToManyField(default=None, to='webapp.Friend'), ), ] <file_sep>from django.conf import settings from django.conf.urls.static import static from django.urls import path from api.views import AddView, DeleteView app_name = 'api' urlpatterns = [ path('<int:pk>/add/', AddView.as_view(), name='add_friend'), path('<int:pk>/delete', DeleteView.as_view(), name='del_friend'), ]<file_sep># Generated by Django 2.2 on 2021-01-23 12:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('webapp', '0008_auto_20210123_1209'), ] operations = [ migrations.RemoveField( model_name='friend', name='friends', ), migrations.AddField( model_name='friend', name='friends', field=models.CharField(default=1, max_length=30), preserve_default=False, ), ] <file_sep>from django.urls import path, include from webapp.views import * app_name = 'webapp' urlpatterns = [ path('', IndexView.as_view(), name='index'), path('dialogs/', DialogsView.as_view(), name='dialogs'), path('messages/', MessagesView.as_view(), name='messages'), ]<file_sep>{% extends 'partial/../base.html' %} {% block title %}{% endblock %} {% block content %} <div class="title mt-5 pb-4" style="text-align: center"><h1>Пользователи</h1></div> {% include 'partial/users_list.html' %} {% endblock %}<file_sep># Generated by Django 2.2 on 2021-01-23 12:56 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0006_profile_friends'), ] operations = [ migrations.CreateModel( name='Friend', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('friends', models.CharField(max_length=30)), ], ), migrations.AlterField( model_name='profile', name='friends', field=models.ManyToManyField(default=None, to='accounts.Friend'), ), ] <file_sep># Generated by Django 2.2 on 2021-01-23 12:09 from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('webapp', '0007_auto_20210123_1200'), ] operations = [ migrations.RemoveField( model_name='friend', name='friend', ), migrations.RemoveField( model_name='friend', name='user', ), migrations.AddField( model_name='friend', name='friends', field=models.ManyToManyField(related_name='friends', to=settings.AUTH_USER_MODEL, verbose_name='Друзья'), ), ] <file_sep>Django==2.2 django-crispy-forms==1.9.2 Pillow==7.2.0 pytz==2020.1 sqlparse==0.3.1 django-widget-tweaks==1.4.8 djangorestframework==3.12.1<file_sep># Generated by Django 2.2 on 2021-01-23 12:56 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('accounts', '0007_auto_20210123_1256'), ('webapp', '0009_auto_20210123_1254'), ] operations = [ migrations.DeleteModel( name='Friend', ), ] <file_sep>from django.contrib.auth import get_user_model from django.contrib.auth.models import User from django.http import HttpResponse from django.shortcuts import get_object_or_404 from django.utils.decorators import method_decorator from django.views.decorators.csrf import ensure_csrf_cookie from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView class AddView(APIView): permission_classes = [IsAuthenticated] def post(self, request, *args, **kwargs): user = get_object_or_404(User, pk=kwargs['pk']) if user: request.user.profile.users.add(user) return Response(status=201) else: HttpResponse(status=400) class DeleteView(APIView): permission_classes = [IsAuthenticated] def post(self, request, *args, **kwargs): user = get_object_or_404(User, pk=kwargs['pk']) if user: request.user.profile.users.friends.remove(user) return Response(status=201) else: return HttpResponse(status=400) <file_sep># Generated by Django 2.2 on 2021-01-23 09:24 from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('webapp', '0003_auto_20210123_0702'), ] operations = [ migrations.AddField( model_name='userprofile', name='friends', field=models.ManyToManyField(related_name='friends', to=settings.AUTH_USER_MODEL, verbose_name='Друзья'), ), ] <file_sep># Generated by Django 2.2 on 2021-01-23 13:07 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('webapp', '0010_delete_friend'), ] operations = [ migrations.CreateModel( name='Chat', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('members', models.ManyToManyField(related_name='member', to=settings.AUTH_USER_MODEL, verbose_name='Участник')), ], ), migrations.CreateModel( name='Message', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('message', models.TextField(max_length=10000, verbose_name='Сообщение')), ('pub_date', models.DateTimeField(auto_now_add=True, verbose_name='Дата отправки')), ('is_readed', models.BooleanField(default=False, verbose_name='Прочитано')), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='Пользователь')), ('chat', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='webapp.Chat', verbose_name='Чат')), ], options={ 'ordering': ['pub_date'], }, ), ] <file_sep>from django.contrib.auth import get_user_model from django.contrib.auth.mixins import LoginRequiredMixin from django.db.models import Q from django.shortcuts import render, redirect from django.urls import reverse from django.views import View from django.views.generic import ListView from webapp.models import * from webapp.forms import SimpleSearchForm, MessageForm class IndexView(ListView): template_name = 'index.html' context_object_name = 'users' form_class = SimpleSearchForm paginate_by = 3 paginate_orphans = 0 def get_queryset(self): usr = get_user_model() data = usr.objects.all() if self.request.user.is_authenticated: data = usr.objects.exclude(pk=self.request.user.pk) return data class DialogsView(View): def get(self, request): chats = Chat.objects.filter(members__in=[request.user.id]) return render(request, 'dialogs.html', {'user_profile': request.user, 'chats': chats}) class MessagesView(View): def get(self, request, chat_id): try: chat = Chat.objects.get(id=chat_id) if request.user in chat.members.all(): chat.message_set.filter(is_readed=False).exclude(author=request.user).update(is_readed=True) else: chat = None except Chat.DoesNotExist: chat = None return render(request, 'messages_list.html', { 'user_profile': request.user, 'chat': chat, 'form': MessageForm() } ) def post(self, request, chat_id): form = MessageForm(data=request.POST) if form.is_valid(): message = form.save(commit=False) message.chat_id = chat_id message.author = request.user message.save() return redirect(reverse('webapp:messages', kwargs={'chat_id': chat_id}))
6b886636f5865b1b926c6ab1aee6b4ec76d8416e
[ "Python", "Text", "HTML" ]
15
Python
violettalivada/final_exam
f2f5cf5e45559beaaf9be6ebd4f28794fbd44156
a6015caed5c5026bb7fbf5cd5f0c1e413c32a814
refs/heads/master
<file_sep>from random import randint from string import ascii_uppercase as up from itertools import * from math import comb #Graph generation nodes = (up) distances = [randint(100, 1000) for _ in range(comb(len(nodes), 2))] links = tuple(zip(tuple(combinations(nodes, 2)), distances)) print(links)
a34eeaaa77c286209fed91e691110258b32086b8
[ "Python" ]
1
Python
AlessandroCometa/BothScalyRegister
a19c4a2d54678cc8e8b2c4e73053ae734fea61f0
0129e5b5755ce321f02326ea5086eb9740c86a51
refs/heads/master
<repo_name>namnitha/ce807<file_sep>/README.md # CE807: Text Analytics - Assignment 2<file_sep>/experimets/test/dt_ex2.sh #!/bin/bash # FILE: dt_ex2.sh #$ -cwd #$ -j y #$ -S /bin/bash #$ -q all.q #$ -N dt_ex2 source activate ce807 python ../../run.py -c dt -m test -f=0.2 -v=1 -b --min_ss=20 conda deactivate<file_sep>/experimets/cv/dt_ex3.sh #!/bin/bash # FILE: dt_ex3.sh #$ -cwd #$ -j y #$ -S /bin/bash #$ -q all.q #$ -N dt_ex3 #$ -pe smp 5 source activate ce807 python ../../run.py -c dt -m cv -j=5 -v=1 -b --min_ss=10 conda deactivate<file_sep>/experimets/test/dt_ex1.sh #!/bin/bash # FILE: dt_ex1.sh #$ -cwd #$ -j y #$ -S /bin/bash #$ -q all.q #$ -N dt_ex1 source activate ce807 python ../../run.py -c dt -m test -f=0.1 -v=1 -b --min_ss=20 conda deactivate<file_sep>/experimets/test/dt_ex4.sh #!/bin/bash # FILE: dt_ex4.sh #$ -cwd #$ -j y #$ -S /bin/bash #$ -q all.q #$ -N dt_ex4 source activate ce807 python ../../run.py -c dt -m test -f=1.0 -v=1 -b --min_ss=20 conda deactivate<file_sep>/experimets/test/dt_ex3.sh #!/bin/bash # FILE: dt_ex3.sh #$ -cwd #$ -j y #$ -S /bin/bash #$ -q all.q #$ -N dt_ex3 source activate ce807 python ../../run.py -c dt -m test -f=0.5 -v=1 -b --min_ss=20 conda deactivate<file_sep>/experimets/cv/dt_ex11.sh #!/bin/bash # FILE: dt_ex11.sh #$ -cwd #$ -j y #$ -S /bin/bash #$ -q all.q #$ -N dt_ex11 #$ -pe smp 5 source activate ce807 python ../../run.py -c dt -m cv -j=5 -v=1 -b --min_ss=20 --max_depth=500 conda deactivate<file_sep>/run.py import numpy as np import pandas as pd import re, argparse, datetime from timeit import default_timer from sklearn.preprocessing import MultiLabelBinarizer from sklearn.feature_extraction.text import TfidfTransformer, CountVectorizer from sklearn.model_selection import train_test_split, cross_validate from sklearn.metrics import f1_score, make_scorer from sklearn.pipeline import make_pipeline, Pipeline from sklearn.tree import DecisionTreeClassifier, ExtraTreeClassifier from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier def get_parser(): """ Builds the argument parser for the program. """ parser = argparse.ArgumentParser() parser.add_argument('-c', type=str, dest='clf_key', default='dt', choices=['dt', 'xts', 'rf'], help='A classifier to use.') parser.add_argument('-m', type=str, dest='mode', default='test', choices=['cv', 'test'], help='Mode to run the program in (cross-validation or test).') parser.add_argument('-k', type=int, dest='cv', default=5, help='Number of folds in KFold cross-validation.') parser.add_argument('-d', '--data', type=str, dest='data_name', default='econbiz', help='Name of the dataset to use (econbiz or pubmed).') parser.add_argument('-f', type=float, dest='data_fraction', default=0.1, help='The fraction of the data to be used (0, 1>.') parser.add_argument('-t', type=float, dest='test_size', default=0.1, help='Test size (0, 1>.') parser.add_argument('--max_depth', type=int, dest='max_depth', default=None, help='The maximum depth of the tree.') parser.add_argument('--min_ss', type=int, dest='min_ss', default=2, help='The minimum number of samples required to split an internal tree node.') parser.add_argument('--max_features', type=str, dest='max_features', default=None, help='The number of features to consider when looking for the best split in the tree.') parser.add_argument('-n', type=int, dest='n_estimators', default=10, help='The number of estimators in the ensemble.') parser.add_argument('-j', type=int, dest='n_jobs', default=-1, help='The number of jobs to run in parallel.') parser.add_argument('-v', type=int, dest='verbose', default=0, help='Verbosity of the program.') parser.add_argument('-b', '--batch', dest='is_batch_mode', action='store_true', default=False, help='Whether the program runs in a batch mode (affects file locations).') return parser def get_data(options): """ Loads and pre-processes the data. """ if options.verbose > 0: print(f'Loading data [dataset: {options.data_name}, fraction: {options.data_fraction}, test size: {options.test_size}]') # Load the data. location_prefix = '../../' if options.is_batch_mode else '' data = pd.read_csv(f'{location_prefix}data/{options.data_name}.csv') # Get raw values from the DataFrame. X_all = data['title'].values # Labels are separated by a '\t' character. Convert them into a list of labels per each data row. Y_all = [x.split('\t') for x in data['labels'].values] # Get only a fraction of the data if necessary if options.data_fraction < 1.0: data_slice = int(options.data_fraction * X_all.shape[0]) X_raw, Y_raw = X_all[:data_slice], Y_all[:data_slice] else: X_raw, Y_raw = X_all, Y_all # Allow for tokens fitting into the following pattern only. word_regexp = r"(?u)\b[a-zA-Z_][a-zA-Z_]+\b" # Take only the most frequent 25k words. Use unigrams. terms = CountVectorizer(input='content', stop_words='english', binary=False, token_pattern=word_regexp, max_features=25000, ngram_range=(1, 1)) X = terms.fit_transform(X_raw) # Binrize the labels (convert them into a sparse matrix of one-hot vectors). mlb = MultiLabelBinarizer(sparse_output=True) Y = mlb.fit_transform(Y_raw) return train_test_split(X, Y, test_size=options.test_size) def get_model(options): """ Prepare a classifier for training. """ classifiers = { "dt" : DecisionTreeClassifier(max_depth=options.max_depth, min_samples_split=options.min_ss, max_features=options.max_features), "xts" : ExtraTreesClassifier(n_estimators=options.n_estimators, n_jobs=options.n_jobs, max_depth=options.max_depth, min_samples_split=options.min_ss, max_features=options.max_features), "rf" : RandomForestClassifier(n_estimators=options.n_estimators, n_jobs=options.n_jobs, max_depth=options.max_depth, min_samples_split=options.min_ss, max_features=options.max_features) } # Prepare the pipeline that consists of TF-IDF representation and a classifier. trf = TfidfTransformer(sublinear_tf=False, use_idf=True, norm='l2') clf = Pipeline([("trf", trf), ("clf", classifiers[options.clf_key])]) return clf if __name__ == "__main__": # Get and parse passed arguments. parser = get_parser() options = parser.parse_args() if options.verbose > 0: print('### Starting ###') print('Arguments:', options) X_train, X_test, Y_train, Y_test = get_data(options) clf = get_model(options) # The program can be run in either a 'cross-validation' or a 'test' mode. # The former performs k-fold cross-validation, while the latter fits the selected model # on the training data and runs predictions against the test set. # Both modes report samples-based F1-score, fitting time and prediction time (in seconds). if options.mode == 'cv': if options.verbose > 0: print(f'Running {options.cv}-fold cross-validation') scores = cross_validate(clf, X_train.toarray(), Y_train.toarray(), cv=options.cv, scoring=make_scorer(f1_score, average='samples'), n_jobs=options.n_jobs, verbose=options.verbose) test_score = scores['test_score'] fit_time = scores['fit_time'] score_time = scores['score_time'] print("F1-score: %0.2f (+/- %0.2f)" % (test_score.mean(), test_score.std())) print("Fit time: %0.2f (+/- %0.2f)" % (fit_time.mean(), fit_time.std())) print("Prediction time: %0.2f (+/- %0.2f)" % (score_time.mean(), score_time.std())) else: if options.verbose > 0: print('Training the model') fit_time_start = default_timer() clf.fit(X_train.toarray(), Y_train.toarray()) fit_time_end = default_timer() if options.verbose > 0: print('Running predictions') pred_time_start = default_timer() Y_pred = clf.predict(X_test.toarray()) pred_time_end = default_timer() test_score = f1_score(Y_test.toarray(), Y_pred, average='samples') print("F1-score: %0.2f" % (test_score)) print("Fit time: %0.2f" % (fit_time_end - fit_time_start)) print("Prediction time: %0.2f" % (pred_time_end - pred_time_start))<file_sep>/experimets/test/xts_ex2.sh #!/bin/bash # FILE: xts_ex2.sh #$ -cwd #$ -j y #$ -S /bin/bash #$ -q all.q #$ -N xts_ex2 #$ -pe smp 10 source activate ce807 python ../../run.py -c xts -m test -f=0.1 -v=1 -b --min_ss=20 -n=10 -j=10 conda deactivate
031c7f665159b5110649e88dddc9747321d1fa3b
[ "Markdown", "Python", "Shell" ]
9
Markdown
namnitha/ce807
17c9b7ddd71906c018cd213a674f37cbed36856d
ae1c6dbc92cc24838c415f6f62bef34e05face06
refs/heads/master
<file_sep>#ifndef _TIME_H_ #define _TIME_H_ #include <Windows.h> #define TO_SECONDS 10000000.f class Time { public: Time(); ~Time(); // Calculate time between frames inline static void Update() { float temp = UpdateDeltaTime(); // Sometimes UpdateDeltaTime() returns a negative - ignore it if it does so if (temp > 0) m_deltaTime = temp; m_time = Now(); } inline static float DeltaTime() { return m_deltaTime; } private: inline static FILETIME& Now() { static FILETIME ft; SYSTEMTIME st; GetSystemTime(&st); SystemTimeToFileTime(&st, &ft); return ft; } inline static float UpdateDeltaTime() { return (((Now().dwHighDateTime + Now().dwLowDateTime) / TO_SECONDS) - ((m_time.dwHighDateTime + m_time.dwLowDateTime) / TO_SECONDS)); } static FILETIME m_time; static float m_deltaTime; }; #endif<file_sep>#include "Time.h" FILETIME Time::m_time; float Time::m_deltaTime = 0; Time::Time() { Update(); } Time::~Time() { }
3931890dd2b9363a84c87be26bc84abe0cb0436f
[ "C++" ]
2
C++
wyrover/Spaceships-2D
612b119a7be830be3cdfd2cdc0827f4c9c1813dc
9d9787544e307f846de320b557a60e4b4f890572
refs/heads/master
<repo_name>kluopaja/random_python_modules<file_sep>/test_argument_parser.py #!/usr/bin/env python import unittest import argument_parser class TestArgumentParser(unittest.TestCase): def test_read(self): options_without_arguments = ['A', 'a', '1'] options_with_arguments = ['B', 'b', '2'] argv = ['test.py', '-A', 'operand_1', '-B', 'b_option_argument', '-1', 'operand_2', '--', '-A', 'operand_4'] correct_option_values = {'A': None, 'B': 'b_option_argument', '1': None} correct_operands = ['operand_1', 'operand_2', '-A', 'operand_4'] correct_result = (correct_option_values, correct_operands) self.assertEqual(argument_parser.read(argv, options_without_arguments, options_with_arguments), correct_result) def test_make_option_dict(self): #two same options in a a = ['a', 'a'] b = ['c', 'd', 'e'] self.assertRaises(ValueError, argument_parser.make_option_dict, a, b) #two same options in b a = ['a', 'b'] b = ['c', 'c'] self.assertRaises(ValueError, argument_parser.make_option_dict, a, b) #same option in a and b a = ['a', 'b'] b = ['a', 'c'] self.assertRaises(ValueError, argument_parser.make_option_dict, a, b) #more same options a = ['a']*10000 b = ['a']*10000 self.assertRaises(ValueError, argument_parser.make_option_dict, a, b) try: a = ['a', 'b', 'c'] b = ['d', 'e', 'f'] argument_parser.make_option_dict(a, b) except: self.fail('make_option_dict() raised an exception with a correct input') def test_check_option_dict_validity(self): #key is not str d = {1: 'option_argument'} self.assertRaises(TypeError, argument_parser.check_option_dict_validity, d) #option is not a single character d = {'aa': 'no_option_argument'} self.assertRaises(ValueError, argument_parser.check_option_dict_validity, d) #option is not an alphanumeric character d = {'<': 'option_argument'} self.assertRaises(ValueError, argument_parser.check_option_dict_validity, d) #key is not in ['option_argument', 'no_option_argument'] d = {'a': 'b'} self.assertRaises(Exception, argument_parser.check_option_dict_validity, d) #correct input try: d = {'a': 'option_argument', 'b': 'no_option_argument', '2': 'option_argument'} argument_parser.check_option_dict_validity(d) except: self.fail('check_option_dict_validity() raised an exception with a correct input') def test_check_command_line_argument_validity(self): #argv is not a list self.assertFalse(argument_parser.check_command_line_argument_validity('string')) #argv is not a list of string self.assertFalse(argument_parser.check_command_line_argument_validity(['a', 2])) #argv is an empty list self.assertFalse(argument_parser.check_command_line_argument_validity([])) #argv has non-empty non-first elements self.assertFalse(argument_parser.check_command_line_argument_validity(['a', '', 'c'])) #correctly formatted string self.assertTrue(argument_parser.check_command_line_argument_validity(['-A', '-1', 'a', '--'])) def test_parse_command_line_arguments(self): #TODO implement pass if __name__ == '__main__': unittest.main() <file_sep>/argument_parser.py #!/usr/bin/env python import sys """Module for reading command line arguments Loosely follows the POSIX.1-2017 guidelines: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html The command line arguments should consist of options, option-arguments, operands and a special argument -- Options have to be single alphanumeric characters. Some options are followed by option-arguments. Option-arguments are not optional. So if a option O can be followed by an option-argument, then it must always be followed by an option-argument. The property of having an option-argument is defined in option_types dict. If 'utility_name -A a' is valid and 'a' is an option-argument, then 'utility_name -A' is not valid Option-arguments are strings which must not start with -. Operands are strings which usually must not with - (see next paragraph). After first -- argument every following argument is treated as an operand. This means that operands can also start with - if they are placed after --. Before the first -- or in absence of -- 1. Arguments starting with - are treated as strings of option characters 2. Every option should be in the option_types dict 3. Only options without option-arguments may be concatenated i.e. -abc 4. An option (with or without option-arguments) may occur many times but only the first occurrence is considered. Each of these repeats should be followed by an option-argument if the option requires it. 5. If an argument is not an option or option-argument, then it is handled as a operand. Usage ----- Simply call read. For example: option_values, operands = read(sys.argv, ['a', 'b'], ['c', 'd']) Now option_values will be a dict of read options and possible corresponding values. Value == None for options without arguments. Operands is a list of operands. """ def read(argv, options_without_arguments=[], options_with_arguments=[]): """Read options from an argv list. Parameters ---------- argv : list (str) Content of sys.argv. Command line arguments to be read. options_without_arguments: list (str) Elements are single alphanumeric characters options_with_arguments: list (str) Elements are single alphanumeric characters Every alphanumeric character should occur at most once and only in one of the lists Returns ------- (option_values, operands) option_values : dict (str: str) Read options and possible corresponding values. Value == None for options without arguments operands : list (str) Read operands """ #check that argv is an output of sys.argv check_command_line_argument_validity(argv) #construct a dict from the option lists option_types = make_option_dict(options_without_arguments, options_with_arguments) return parse_command_line_arguments(argv, option_types) def make_option_dict(options_without_arguments, options_with_arguments): """Construct a option dict from two lists of options """ options = {} for x in options_without_arguments: if x in options: raise ValueError("Multiple definitions of the same option") options[x] = 'no_option_argument' for x in options_with_arguments: if x in options: raise ValueError("Multiple definitions of the same option") options[x] = 'option_argument' check_option_dict_validity(options) return options def check_option_dict_validity(option_types): """Checks the validity of options and option arguments Option set is valid only if: 1. Type of every element of 'options' is correct 2. Every option name is an alphanumeric character 3. Every option-argument belongs to the set ['option_argument', 'no_option_argument'] Parameters ---------- options : dict ('str', 'str') Key is the value of the option. Value is 'option_argument' if the option has an option-argument 'no_option_argument' for an option without an option-argument. """ for key, value in option_types.items(): if not isinstance(key, str): ok = False raise TypeError("Option name not string") if len(key) != 1: raise ValueError("Option name not a single character") if not key.isalnum(): raise ValueError("Option name not alphanumeric") #NOTE #How to handle this? The user should never set these values if value not in ['option_argument', 'no_option_argument']: raise Exception("Internal error in option list processing") def check_command_line_argument_validity(argv): """Basic sanity check for argv. 1. argv is list of string 2. len(argv) > 0 3. For every element s (except the first one) should hold len(s) > 0 Parameters ---------- argv : list of strings Content of sys.argv Command line arguments to be checked. Returns ------- ok : bool True if no errors were detected False if argv is not a valid argument list TODO ---- Should only raise exceptions and not return anything """ ok = True #must be a list if not isinstance(argv, list): return False for x in argv: if not isinstance(x, str): return False #must always at least contain the program name if len(argv) < 1: ok = False #apart from the program name, every other argument must be nonempty for i in range(1, len(argv)): if len(argv[i]) == 0: ok = False return ok def parse_command_line_arguments(argv, option_types): """Extract options and operands from the argv. Parameters ---------- argv : list of strings Content of sys.argv First element is the program name For subsequent elements s should hold |s| > 0 option_types : dict (str: str) Key is the value of the option. Value is 'option_argument' if the option has an option-argument 'no_option_argument' for an option without an option-argument. Returns ------- (argv_options, operands) : tuple argv_options : dict (str: (None | str)) Options with their corresponding option-arguments or None operands : list (str) """ #options encountered in the argv #for options without option-arguments (c, None) is added #for option with option-arguments (c, d) is added where #where c is the option and d is the option-argument argv_options = {} #list of strings operands = [] #will be switched to True if -- is encountered only_operands = False #we can skip the first argument which is the file name #and should be correct pos = 1 while pos < len(argv): #after first --, every argv[i] is an operand if only_operands: operands.append(argv[pos]) else: #which to only operands mode if -- is encountered if argv[pos] == '--': only_operands = True #if new argument start with -, then it is an option elif argv[pos][0] == '-': #if at least one of the options has arguments has_argument = False for i in range(1, len(argv[pos])): if argv[pos][i] not in option_types: raise ValueError(f"Option {argv[pos]} not valid") #if the option argv[i] requires an option-argument if option_types[argv[pos][i]] == 'option_argument': has_argument = True #option cannot be empty if len(argv[pos]) == 1: raise ValueError(f'Option cannot be empty (only -)') if has_argument: if len(argv[pos]) == 2: #check that there is a option-argument in argv if pos + 1 >= len(argv): raise ValueError(f'No option-argument was provided for: {argv[pos]}') #check that the option-argument doesn't start with - if argv[pos+1][0] == '-': raise ValueError(f'Option-argument for {argv[pos]} starts with an illegal character: {argv[pos+1]}') #only update the value if not already present if argv[pos][1] not in argv_options: argv_options[argv[pos][1]] = argv[pos+1] #because we handled two elements pos += 1 #options with arguments can't be concatenated elif len(argv[pos]) > 2: raise ValueError(f'Options with option-arguments cannot be concatenated: {argv[pos]}') #we should never end up here else: raise ValueError() #if options don't require option-arguments, just add every option to argv_options else: for option in argv[pos][1:]: if option not in argv_options: argv_options[option] = None; #otherwise we will just add it to the operands else: operands.append(argv[pos]) pos += 1 return (argv_options, operands) options_without_arguments = ['A', 'a', '1'] options_with_arguments = ['B', 'b', '2'] if __name__ == "__main__": print("options_without_arguments: ", end='') print(options_without_arguments); print("options_with_arguments: ", end='') print(options_with_arguments) print("sys.argv: ", end='') print(sys.argv) result = read(sys.argv, options_without_arguments, options_with_arguments) print(result) <file_sep>/README.md # Random python modules Collection of small utilities to learn programming. <file_sep>/regex/test_regex.py #!/usr/bin/env python import unittest import regex class TestParseTreeNode(unittest.TestCase): def test_equal(self): a = regex.ParseTreeNode(meta='.') b = regex.ParseTreeNode(meta='.') self.assertTrue(a == b) a = regex.ParseTreeNode(meta='.') b = regex.ParseTreeNode(meta='|') self.assertTrue(a != b) a = regex.ParseTreeNode(normal='a') b = regex.ParseTreeNode(normal='a') self.assertTrue(a == b) a = regex.ParseTreeNode(normal='a') b = regex.ParseTreeNode(normal='b') self.assertTrue(a != b) a = regex.ParseTreeNode(normal='a') b = regex.ParseTreeNode(meta='a') self.assertTrue(a != b) a = regex.ParseTreeNode(normal='a') b = regex.ParseTreeNode(operation='|') self.assertTrue(a != b) a = regex.ParseTreeNode(operation='concatenation') b = regex.ParseTreeNode(operation='|') self.assertTrue(a != b) c1 = regex.ParseTreeNode(normal='a') c2 = regex.ParseTreeNode(normal='b') a = regex.ParseTreeNode(children=[c1], operation='*') b = regex.ParseTreeNode(children=[c2], operation='*') self.assertTrue(a != b) c1=regex.ParseTreeNode(normal='a') c2=regex.ParseTreeNode(normal='a') a = regex.ParseTreeNode(children=[c1], operation='*') b = regex.ParseTreeNode(children=[c2], operation='*') self.assertTrue(a == b) c1 = regex.ParseTreeNode(normal='a') c2 = regex.ParseTreeNode(normal='a') a = regex.ParseTreeNode(normal='a') b = regex.ParseTreeNode(normal='b') self.assertTrue(a != b) def test___str__(self): a = regex.ParseTreeNode(normal='a') a = str(a) self.assertEqual(a, "NNa") a = regex.ParseTreeNode(normal='') a = str(a) self.assertEqual(a, "NN_") a = regex.ParseTreeNode(meta='|') a = str(a) self.assertEqual(a, "N|N") a = regex.ParseTreeNode(operation='|') a = str(a) self.assertEqual(a, "|NN") a = regex.ParseTreeNode(operation='concatenation') a = str(a) self.assertEqual(a, "cNN") c1 = regex.ParseTreeNode(normal='a') a = regex.ParseTreeNode(children=[c1], operation='*') a = str(a) self.assertEqual(a, "*NN---NNa") c1 = regex.ParseTreeNode(normal='a') a = regex.ParseTreeNode(children=[c1, c1], operation='|') a = str(a) b = \ """ |NN---NNa | +-----NNa"""[1:] c1 = regex.ParseTreeNode(normal='a') a = regex.ParseTreeNode(children=[c1, c1, c1], operation='c') a = str(a) b = \ """ cNN---NNa | +-----NNa | +-----NNa"""[1:] self.assertEqual(a, b) c1 = regex.ParseTreeNode(normal='1') c2 = regex.ParseTreeNode(normal='2') c3 = regex.ParseTreeNode(normal='3') c4 = regex.ParseTreeNode(normal='4') p1 = regex.ParseTreeNode(children=[c1, c2], operation='c') p2 = regex.ParseTreeNode(children=[c3, c4], operation='|') p3 = regex.ParseTreeNode(children=[p1, p2], operation='c') a = str(p3) b = \ """ cNN---cNN---NN1 | | | +-----NN2 | +-----|NN---NN3 | +-----NN4"""[1:] self.assertEqual(a, b) class TestRegexParsing(unittest.TestCase): def test_process_union(self): a = regex.process_union([regex.ParseTreeNode(normal='a')]) b = [regex.ParseTreeNode(normal='a')] self.assertTrue(a == b) a = regex.process_union([regex.ParseTreeNode(normal='b')]) b = [regex.ParseTreeNode(normal='a')] self.assertTrue(a != b) tmp = [regex.ParseTreeNode(normal='a'), regex.ParseTreeNode(meta='|'), regex.ParseTreeNode(normal='b')] a = regex.process_union(tmp) c1 = regex.ParseTreeNode(normal='a') c2 = regex.ParseTreeNode(normal='b') b = regex.ParseTreeNode(children=[c1, c2], operation='|') b = [b] self.assertEqual(a, b) n1 = regex.ParseTreeNode(normal='a') n2 = regex.ParseTreeNode(children=[n1], operation='*') tmp = [n2, regex.ParseTreeNode(meta='|'), regex.ParseTreeNode(normal='b')] a = regex.process_union(tmp) n1 = regex.ParseTreeNode(normal='a') n2 = regex.ParseTreeNode(children=[n1], operation='*') n3 = regex.ParseTreeNode(normal='b') b = regex.ParseTreeNode(children=[n2, n3], operation='|') b = [b] self.assertEqual(a, b) tmp = [regex.ParseTreeNode(meta='|')] a = regex.process_union(tmp) n1 = regex.ParseTreeNode(normal='') n2 = regex.ParseTreeNode(normal='') b = regex.ParseTreeNode(children=[n1, n2], operation='|') b = [b] self.assertEqual(a, b) tmp = [regex.ParseTreeNode(meta='.'), regex.ParseTreeNode(meta='|'), regex.ParseTreeNode(meta='.')] a = regex.process_union(tmp) n1 = regex.ParseTreeNode(meta='.') n2 = regex.ParseTreeNode(meta='.') b = regex.ParseTreeNode(children=[n1, n2], operation='|') b = [b] self.assertEqual(a, b) tmp = [regex.ParseTreeNode(meta='|'), regex.ParseTreeNode(meta='|')] a = regex.process_union(tmp) n1 = regex.ParseTreeNode(normal='') n2 = regex.ParseTreeNode(normal='') n3 = regex.ParseTreeNode(children=[n1, n2], operation='|') n4 = regex.ParseTreeNode(normal='') b = regex.ParseTreeNode(children=[n3, n4], operation='|') b = [b] self.assertEqual(a, b) tmp = [regex.ParseTreeNode(meta='('), regex.ParseTreeNode(meta='|')] with self.assertRaises(Exception): regex.parse_union(tmp) tmp = [regex.ParseTreeNode(meta='|'), regex.ParseTreeNode(meta=')')] with self.assertRaises(Exception): regex.parse_union(tmp) def test_process_concatenation(self): a = regex.process_concatenation([regex.ParseTreeNode(normal='a')]) b = [regex.ParseTreeNode(normal='a')] self.assertEqual(a, b) tmp = [regex.ParseTreeNode(normal='a'), regex.ParseTreeNode(normal='a')] a = regex.process_concatenation(tmp) c1 = regex.ParseTreeNode(normal='a') c2 = regex.ParseTreeNode(normal='a') b = regex.ParseTreeNode(children=[c1, c2], operation='concatenation') b = [b] self.assertEqual(a, b) tmp = [regex.ParseTreeNode(normal='a'), regex.ParseTreeNode(normal='b'), regex.ParseTreeNode(normal='c')] a = regex.process_concatenation(tmp) n1 = regex.ParseTreeNode(normal='a') n2 = regex.ParseTreeNode(normal='b') n3 = regex.ParseTreeNode(normal='c') n4 = regex.ParseTreeNode(children=[n1, n2], operation='concatenation') b = regex.ParseTreeNode(children=[n4, n3], operation='concatenation') b = [b] self.assertEqual(a, b) tmp = [regex.ParseTreeNode(normal='a'), regex.ParseTreeNode(normal='b'), regex.ParseTreeNode(meta='|'), regex.ParseTreeNode(normal='c'), regex.ParseTreeNode(normal='d')] a = regex.process_concatenation(tmp) n1 = regex.ParseTreeNode(normal='a') n2 = regex.ParseTreeNode(normal='b') n3 = regex.ParseTreeNode(children=[n1, n2], operation='concatenation') n4 = regex.ParseTreeNode(normal='c') n5 = regex.ParseTreeNode(normal='d') n6 = regex.ParseTreeNode(children=[n4, n5], operation='concatenation') n7 = regex.ParseTreeNode(meta='|') b = [n3, n7, n6] self.assertEqual(a, b) def test_process_unary(self): a = regex.process_unary([regex.ParseTreeNode(normal='a')]) b = [regex.ParseTreeNode(normal='a')] self.assertEqual(a, b) tmp = [regex.ParseTreeNode(normal='a'), regex.ParseTreeNode(meta='*')] a = regex.process_unary(tmp) c1 = regex.ParseTreeNode(normal='a') b = regex.ParseTreeNode(children=[c1], operation='*') b = [b] self.assertEqual(a, b) tmp = [regex.ParseTreeNode(meta='*'), regex.ParseTreeNode(normal='a')] with self.assertRaises(ValueError): regex.process_unary(tmp) tmp = [regex.ParseTreeNode(meta='|'), regex.ParseTreeNode(meta='*')] with self.assertRaises(ValueError): regex.process_unary(tmp) tmp = [regex.ParseTreeNode(normal='a'), regex.ParseTreeNode(meta='+'), regex.ParseTreeNode(normal='b'), regex.ParseTreeNode(meta='?'), regex.ParseTreeNode(meta='|'), regex.ParseTreeNode(normal='c'), regex.ParseTreeNode(meta='*')] a = regex.process_unary(tmp) n1 = regex.ParseTreeNode(normal='a') n2 = regex.ParseTreeNode(children=[n1], operation='+') n3 = regex.ParseTreeNode(normal='b') n4 = regex.ParseTreeNode(children=[n3], operation='?') n5 = regex.ParseTreeNode(meta='|') n6 = regex.ParseTreeNode(normal='c') n7 = regex.ParseTreeNode(children=[n6], operation='*') b = [n2, n4, n5, n7] self.assertEqual(a, b) if __name__ == '__main__': unittest.main() <file_sep>/regex/regex.py #!/usr/bin/env python """ Background ---------- For more deep treatment of the topic the reader should read the Sipser book. One problem in computing is how to define a sets of strings. For example, how could one detect if a string s is a correctly formatted person's name or username. One way to do this would be to write a computer program (here means using a turing machine) that returns 1 if the string belongs to desired set or 0 if it doesn't. Such a program might consist of statements like: if s[0].isupper(): ... However, this might get somewhat complicated from both the theoretical and practical point of view. Finite languages ---------------- One simple way to define sets of strings is to use a finite automaton. For this we need some definitions: Alphabet is a finite set of symbols. String is a finite sequence of symbols where every symbol belongs to a certain alphabet. A set of strings is called a language. A concatenation of strings a and b is marked by ab and means joining strings a and b: let a='abc' and b='def', then ab = 'abcdef' A finite automaton is a simple computational model which takes a string as an input and then either accepts or rejects it. The set of strings, that is a language, recognized by a finite automaton A is marked by L(A) The set of languages defined by finite automata are called finite languages. The finite automaton is defined by 5 parameters: 1. The set of automaton states, here denoted by Q 2. An alphabet, here denoted by S 3. A transition function, here denoted by d 4. A start state, which is an element of Q, here denoted by q_0 5. A subset of Q, the accepted states, here denoted by F The transition function d is a function from a set (Q X E) to the set Q. That is, the function takes two parameters X and Y where X is an automaton state and Y is a symbol of the alphabet S. The automaton works by starting from the start state q_0, reading the input string T one symbol at a time and changing the automaton state based on the read symbol and current state as defined by the transition function d. If, after processing the whole string, the automaton is in one of the accepted states, then the automaton accepts the string. Otherwise the automaton rejects the string. In other words: Let the current state of the automaton be C. def test_string(T): C = q_0 for i in range(len(T)): C = d(C, T[i]) if C in F: return "Accept" else: return "Reject" It might be helpful to think the finite automata as a graph and function d as labeled directed edges. It is therefore quite easy to evaluate the string once the finite automaton has been constructed. The question that remains is how to construct one. It is easy to construct very simple finite automata such as those recognizing: 1. A certain symbol of the alphabet S 2. An empty string, {_} 3. Nothing at all, {} (empty set) Fortunately, also more complicated automata can be constructed from these simple automata using the following operations 1. Union If we have two finite automata A and B recognizing languages L(A) and L(B), we know how to construct a finite automaton C such that L(C) = L(A) U L(B). That is, finite automaton C recognizes strings by at least A or B. 2. Concatenation If we have two finite automata A and B recognizing L(A) and L(B), we know how to construct a finite automaton C such that if w \in L(A) and v \in L(B), then wv \in L(C), where wv is the concatenation of w and v. We mark this by L(C) = L(A)L(B) 3. Kleene star If a finite automaton A recognizes L(A), then we know how to construct a finite automaton B such that L(B) = L(A)* = {_} U L(A) U L(A)L(A) U L(A)L(A)L(A) U ... Where {_} is the language recognizing an empty string. In other words, L(A)* is the language formed by concatenating the strings of language L(A) arbitrarily (also 0 or 1) times with itselves. 4. Intersection If we have two finite automata A and B recognizing L(A) and L(B), we know how to construct a finite automaton C such that L(C) = L(A) \cap L(B). That is, automaton C recognizes string that are recognized by both A and B. 5. Negation If a finite automaton A recognizes L(A), then we know how to construct a finite automaton C such that L(C) = L(A)^C where ^C marks the complement of a set. That is, automaton C recognizes exactly those strings that automaton A doesn't recognize. It can be shown that for every finite language A, a finite automaton B, such that L(B) = A, can be constructed using only the previous operations 1-3. We might then imagine using the knowledge to construct finite automata to solve our problem of matching a string in a computer program. Perhaps our code would looks something like following: def check_string(s): #Initialize the base cases S1 = FiniteAutomaton('A') S2 = FiniteAutomaton('B') #Construct automaton A1 = union(S1, S2) A2 = concatenate(S1, S2) A3 = concatenate(A1, A2) A4 = star(A3) return A4.match(s) We would clearly benefit from having concise notation that is human readable and standardized. This leads us to regular expressions. Regular expression ------------------ Regular expressions are a way to describe regular languages. It should be noted that some regular expression implementations also allow some additional operations so that the result is no more a regular language. We will not consider such operations here. Definition: Regular expressions corresponding to the simple languages 1. a is a regular expression if a belongs to the selected alphabet. L(a) = {a} 2. @ is a regular expression such that L(@) = {} (an empty set) 3. _ is a regular expression such that L(_) = {_} (an empty string) Other regular expressions can be formed by applying the following operations: 1. Union Let R_1 and R_2 be regular expression. Then also (R_1|R_2) is a regular expression and L((R_1|R_2)) = L(R_1) U L(R_2) 2. Concatenation Let R_1 and R_2 be regular expression. Then also (R_1R_2) is a regular expression and L((R_1R_2)) = L(R_1)L(R_2) 3. Kleene star Let R be a regular expression, then also (R*) is a regular expression and L((R*)) = L(R)* What if there were two sequences of operations leading to a regular expression R but two different languages? This would not be desirable as we want to define a language with a regular expression. We note that this is clearly not the case for every regular expression consisting of only one character. By noting that every regular expression is either one letter or enclosed in parentheses we can also see that if we have a more complex regular expression R, then there is always only one operation which could have formed R. Moreover, for every operation there is only a one way to select regular expressions R1 (and R2) to form R. Thus only one way to define the language L(R). We note that if we have the instructions to construct some finite automaton based on the rules of the previous section, we can simply apply the same sequence of operations to constuct a regular expessions describing the same language. The next challenge is to do the opposite i.e. to find out the way to decompose a regular expression to the operations used to form it. This is done by forming a parse tree of the expression. Every node of the parse tree corresponds to some regular expression. The leaves are always one of our three simple languages. Lets then consider an internal node r. Node r corresponds to a regular expression formed from its child(ren) by applying some of our 3 operations. This operation is also stored at the node r. The root of the parse tree is the whole regular expression. Parsing regular expressions in the most basic form is easy and can be basically done by constructing the tree formed by the parentheses. Unfortunately for us but fortunately for the user parsing the regular expression is complicated by a few addional details: We include the following shorthand notations: (R(R*)) = (R+) (R|_) = (R?) . = (a|(b|c(... where a,b,c are the characters of the alphabet Also empty string can be denoted simply by '' (_|a) = (|a) The different operators are evaluated in the order: */+/?, concatenation, union. Operators are evaluated from left to right. All excessive parentheses can simply be left out. For example: (a(b(a(b(a))))) = ababa (a|((b*)c)) = a|b*c NOTE: Should I comment something that regular expressions are still well defined? How to prove this? To parse these we first form a tree just based on the parentheses. To be continued... """ class NFANode: """Class for NFA nodes. Id of a node is always its index in NFA.nodes Attributes ---------- self.transitions : dict (str, set) set of nodes reachable from self with the key """ def __init__(self, transitions={}): self.transitions = copy.deepcopy(transitions) def add_transition(self, target, symbol): if symbol in self.transitions: self.transitions[symbol].add(target) else: self.transitions[symbol] = {target} def transitions_with_symbol(self, symbol): if symbol in self.transitions: return list(self.transitions[symbol]) else: return [] #TODO can be removed def transition_list(self): """Returns list of transitions from self Returns ------- result : list of tuples result[i][0]: end result[i][1]: symbol """ result = [] for symbol, target in self.transitions.items(): result.append((target, symbol)) return result def copy(self): return NFANode(self.transitions) class NFA: """Implements non-deterministic finite automaton Attributes ---------- Notes ----- The NFA objects can internally be in two states: compiled and not compiled. Compilation refers to generating a list of NFANode objects according to the self.transitions. The generated list of NFANode objects can then be used to evaluate the NFA. The rationale behind compilation is that the list of transitions is easier to handle when performing operations on NFAs (concatenation, union, ...) but the list of NFANodes is easier to handle when evaluating the NFA. """ def __init__(self, n_nodes, start_node, accepted_nodes, transitions): self.n_nodes = n_nodes self.start_node = start_node self.accepted_nodes = accepted_nodes.copy() self.transitions = transitions.copy() self.compiled = False self.nodes = None @classmethod def union_of_characters(cls, characters): """Construct a small NFA for a set of characters Parameters ---------- characters : list(str) """ transitions = [(0, 1, x) for x in characters] return NFA(2, 0, 1, transitions) def evaluate(self, s): """Determine if the NFA accepts string s """ if not compiled: self.compile() node_list = [self.start_node] node_list = reachable_with_empty(node_list) for i in range(len(s)): node_list = reachable_with_symbol(node_list, s[i]) node_list = reachable_with_empty(node_list) for x in node_list: if x in self.accepted_nodes: return True return False def reachable_with_symbol(self, node_list, symbol): """Returns states which are reachable with symbol. See Notes. Parameters ---------- node_list : list (int) symbol : str Returns ------- new_node_list : list (int) Notes ----- This function always traverses edges in the tree. So calling this with symbol='' and node x will NOT return the node x unless x is part of a cycle of '' edges. Compare with reachable_with_empty. """ new_node_list = [] id_active = [False for i in range(self.n_nodes)] for i in range(len(node_list)): node_id = node_list[i] neighbours = self.nodes[node_id].transitions_with_symbol(symbol) for x in neighbours: if not id_active[x]: new_node_list.append(x) id_active[x] = True return new_node_list def reachable_with_empty(self, node_list): """Returns states that are reachable without consuming any symbols. Parameters ---------- node_list : list (int) symbol : str Returns ------- new_node_list : list(int) Notes ----- Also returns every node in node_list. Compare with reachable_with_symbol. """ new_node_list = reachable_with_symbol(node_list, '') #it is not necessary to use the empty string edges new_node_list.extend(node_list) #remove duplicates new_node_list = list(set(new_node_list)) return new_node_list def copy(self): return NFA(self.n_nodes, self.start_node, self.accepted_nodes, self.transitions) def compile(self): """Construct a graph of NFANodes with transitions from self.transitions """ self.nodes = [NFANode() for i in range(self.n_nodes)] self.process_transitions() self.compiled = True def process_transitions(self): """Adds transitions to node objects """ for x in self.transitions: self.nodes[x[0]].add_transition(x[1], x[2]) def apply_offset(self, offset): """Shifts _all_ indexes by offset. Parameters ---------- offset : non-negative integer Notes ----- Used to make the nodes in two graphs non-overlapping. """ self.compiled = False if offset < 0: raise ValueError("offset cannot be negative") self.n_nodes += offset self.start_node += offset for i in range(len(self.transitions)): self.transitios[i][0] += offset self.transitios[i][1] += offset def union(self, other): """Return union as a new NFA """ self_copy = self.copy() other_copy = other.copy() #make the node ids non-overlapping other_copy.apply_offset(self_copy.n_nodes) self_copy.n_nodes += other_copy.n_nodes self_copy.transitions.extend(other_copy.transitions) self_old_start = self_copy.start_node other_old_start = other_copy.start_node #set new start node self_copy.n_nodes += 1 self_copy.start_node = self_copy.n_nodes-1 #add edges from the new start node new_edges = [] new_edges.append((self_copy.start_node, self_old_start, '')) new_edges.append((self_copy.start_node, other_old_start, '')) self_copy.transitions.extend(new_edges) #update accepted nodes self_copy.accepted_nodes.extend(other_copy.accepted_nodes) return self_copy def concatenate(self, other): """Return concatenation as a new NFA """ self_copy = self.copy() other_copy = other.copy() #make sure the node ids are not overlapping other_copy.apply_offset(self_copy.n_nodes) self_copy.n_nodes += other_copy.n_nodes self_copy.add_transitions(other_copy.transitions) new_edges = [] for x in self_copy.accepted_nodes: new_edges.append((x, other_copy.start_node, '')) self_copy.transitions.extend(new_edges) self_copy.accepted_nodes = other_copy.accepted_nodes.copy() return self_copy def star(self): """Return a new NFA self* """ self_copy = self.copy() #add new start node and add it to accepted nodes self_copy.n_nodes += 1 self_new_start = self_copy.n_nodes-1 self_copy.accepted_nodes.append(self_new_start) #add edges from the accepted states to the old start node new_edges = [] for x in self_copy.accepted_nodes: new_edges.append((x, self_copy.start_node, '')) self_copy.transitions.extend(new_edges) self_copy.start_node = self_new_start return self_copy def plus(self): """Return a new NFA self+ = selfself* """ return self.concatenate(self.star()) def question(self): """Return a new set self? = (_|self) """ return self.union(NFA.union_of_characters([''])) class ParseTreeNode: """Used to represent the regex as a tree Attributes ---------- self.children : list (ParseTreeNode) self.meta : str or None regex metacharacter (e.g. '*+?()|.') Every character that is not directly representing a character of the mached string. Only '.' should be present in the final tree (leafs only) self.normal : str or None normal character(s) If len(self.normal) > 1, then union of the characters #NOTE: should this depend on the self.operation? Should be nonempty only in the leaves of the final tree self.operation : str or None operation applied to self.children only in the inner nodes of the final tree Also used during the parsing process when the regex is represented """ def __init__(self, children=[], meta=None, normal=None, operation=None): self.children = children #meta and normal are used for leaves self.meta = meta self.normal = normal #TODO check that the constructed node is valid! #TODO modify the @final tree@ #operation is used for internal nodes in the final tree self.operation = operation def __eq__(self, other): if not isinstance(other, ParseTreeNode): return NotImplemented if self.meta != other.meta or self.normal != other.normal \ or self.operation != other.operation: return False if len(self.children) != len(other.children): return False for i in range(len(self.children)): if self.children[i] != other.children[i]: return False return True def __repr__(self): self_repr = "(" self_repr += ", ".join([str(self.operation), str(self.meta), str(self.normal)]) self_repr += ")" if len(self.children) == 0: return self_repr return self_repr + repr(self.children) def __str__(self): """Prints tree in a user friendly format. The state of the current node is expressed by three consecutive characters. Let the characters be 'ABC'. Now self.operation == 'A', self.meta = 'B' and self.normal = 'C'. None is denoted by 'N'. Empty self.normal is denoted by '_' """ rows = self.str_helper(level_depth=3) return '\n'.join(rows) def str_helper(self, level_depth=0): """Returns list of rows of the text presentation of the tree Parameters ---------- level_depth: integer (>=0) extra space between subsequent tree levels """ if level_depth < 0: raise ValueError("level_depth must be nonnegative") prefix = 'N' if self.operation is None else self.operation[0] prefix += 'N' if self.meta is None else self.meta[0] if self.normal is None: prefix += 'N' elif self.normal is '': prefix += '_' else: prefix += self.normal[0] if len(self.children) == 0: return [prefix] out = [] child_strs = [x.str_helper(level_depth) for x in self.children] for i in range(len(child_strs)): for j in range(len(child_strs[i])): if i == 0 and j == 0: prefix += "-"*level_depth elif j == 0: prefix = "+--" prefix += "-"*level_depth elif i != len(child_strs)-1: prefix = "| " prefix += " "*level_depth else: prefix = " " prefix += " "*level_depth out.append(prefix+child_strs[i][j]) if j == len(child_strs[i])-1 and i != len(child_strs)-1: out.append('|') return out def parse_regex(regex): """Generates parse tree from regex Parameters ---------- regex : str Returns ------- root : ParseTreeNode Root of the generated parse tree corresponding to regex """ tmp = regex_to_parse_tree_nodes(regex) root = parse_nodes_to_tree(tmp) return root def regex_to_parse_tree_nodes(regex): """Processes a regex string for further use Parameters ---------- regex : str Returns ------- leafs : list (ParseTreeNode) ParseTree leafs to be converted to a parse tree Notes ----- Every character (including escaped characters) is converted to a ParseTreeNode object. """ i = 0 leafs = [] while i < len(regex): new_node = ParseTreeNode() if regex[i] == '\\': new_node.normal = regex[i+1:i+2] i += 2 else: if regex[i] in '*+?|().': new_node.meta = regex[i] else: new_node.normal = regex[i] i += 1 leafs.append(new_node) return leafs def parse_nodes_to_tree(parse_nodes): """Generates parse tree from parse_nodes Parameters ---------- parse_leafs : list of ParseTreeNodes Regex represented as a list of parse tree leafs Returns ------- root : ParseTreeNode Root of the generated parse tree generated from parse_leafs Notes ----- Handles parentheses in the regex and calls parse_wo_parentheses """ #parse node sequences without any parentheses #regex_lists[i] corresponds to a substring which is enclosed in #i (unprocessed) parentheses regex_lists = [[]] for i in range(len(regex_object_list)): if regex_object_list[i].meta == '(': regex_lists.append([]) elif regex_object_list[i].meta == ')': if len(regex_list) <= 1: raise ValueError("Incorrect parentheses in regex_object_list") tmp = parse_wo_parentheses(regex_lists[-1]) regex_lists[-2].append(tmp) regex_lists.pop() else: regex_lists[-1].append(regex_object_list[i]) root = parse_wo_parentheses(regex_lists[0]) def parse_wo_parentheses(parse_nodes): """Parses a ParseTreeNode list not containing any parentheses Parameters ---------- parse_nodes : list of characters or ParseTreeNodes Should not contain any parentheses Returns ------- root : ParseTreeNode Root of the generated parse tree corresponding to parse_nodes """ regex_object_list = process_unary(regex_object_list) regex_object_list = process_concatenation(regex_object_list) regex_object_list = process_union(regex_object_list) if len(regex_object_list) != 1: raise Exception("regex_object_list was not processed fully") return regex_object_list[0] def process_unary(parse_nodes): """Processes nodes with a metacharacters ['*', '+', '?'] """ result = [] for i in range(len(parse_nodes)): if parse_nodes[i].meta in ['*', '+', '?']: if len(result) == 0: raise ValueError("Nothing to repeat in front of */+/?") if result[-1].meta == '|': raise ValueError("| cannot be followed by */+/?") #TODO More error checking new_node = ParseTreeNode(children=[result[-1]], operation=parse_nodes[i].meta) result[-1] = new_node else: result.append(parse_nodes[i]) return result def process_concatenation(parse_nodes): result = [] for i in range(len(parse_nodes)): result.append(parse_nodes[i]) if len(result) >= 2: #TODO meta == '.' or normal is not None or something to #replace these if result[-2].meta != '|' and result[-1].meta != '|': new_node = ParseTreeNode(children=result[-2:], operation='concatenation') result[-2:] = [] result.append(new_node) return result def process_union(parse_nodes): result = [] i = 0 while i < len(parse_nodes): if parse_nodes[i].meta == '|': #in some cases we need to create empty nodes here #['|', ...] if i == 0: left_child = ParseTreeNode(normal='') #['a', '|'] elif result[-1].normal != None or result[-1].meta in ['.'] \ or result[-1].operation != None: left_child = result.pop() else: raise Exception("Unknown metacharacter before |") #[..., '|'] if i+1 == len(parse_nodes) or parse_nodes[i+1].meta == '|': right_child = ParseTreeNode(normal='') #[..., '|', 'a'] or [..., '|' elif parse_nodes[i+1].normal != None \ or parse_nodes[i+1].meta in ['.'] \ or parse_nodes[i+1].operation != None: right_child = parse_nodes[i+1] i += 1 else: raise Exception("Unknown metacharacter after |") result.append(ParseTreeNode(children=[left_child, right_child], operation='|')) else: result.append(parse_nodes[i]) i += 1 return result if __name__ == '__main__': pass
488bf1d94d7e506b38f2e1ce6453ff269f9545c7
[ "Markdown", "Python" ]
5
Python
kluopaja/random_python_modules
3aa8864d9a46b3485b49720c20545a7956163c7d
c24dd0e35b59cd7765471344724f752051440d0f
refs/heads/main
<file_sep>import axios from 'axios'; const API = axios.create({ baseURL: 'https://api.github.com/search' }); export default API;<file_sep># React interview This is a small interview project. # Goal Create an UI to search for repositories using the Github public API. # User Scenario As the user, I want to search for repositories from GitHub, So that I can get a list of repositories matching the search criteria. When I input the repository name into the search field, And I press Enter or click on the "Submit" button, Then I see the list of repositories from Github matching the criteria. ## UX/UI Up to you, probably it should include an input to enter the repository name, one area to display the repositories list. # Retrieving data ***Github API:https://help.github.com/en/github/searching-for-information-on-github/searching-for-repositories*** ***Example:https://api.github.com/search/repositories?q=react:name&sort=stars&order=desc*** # Bootstrapping We recommend using [create-react-app](https://github.com/facebook/create-react-app). # Bonus Points (not in any specific order) The list bellow are only extra points for extra work after building the basic. * Using ES6 syntax (e.g arrow functions, async/await) * Using Typescript * Adding a spinner when information is loading * Deal with errors coming from the api * Including some Unit Test or Integration Test * Having a nice UI using a components library (Bootstrap,Material UI or another) * Divide the application in different pages and use a router * Adding state management if you think is relevant * Show common tools used for you daily development environment (e.g linters, code formatter)
113a6e6cc2b9d99626f79f6a7086715450ef31bc
[ "Markdown", "TypeScript" ]
2
TypeScript
eduardoedson/GithubApi-Test
8f2da3b8574dfcc541c4e3451e470b3f5544b9c9
176454936b6e57584ef3217022a332db79e80ba6
refs/heads/master
<repo_name>daviddev/social<file_sep>/app/Http/Controllers/PostController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\URL; use Illuminate\Support\Facades\DB; use App\Post; use Auth; use App\Comment; use app\user; class PostController extends Controller { public function post(){ return view('posts/post'); } public function addPost(Request $request){ $this->validate($request,[ 'post_title' => 'required', 'post_description' => 'required', 'post_image' => 'required', 'post_image_2' => 'required', 'post_image_3' => 'required', ]); $posts = new Post; $posts->post_title = $request->input('post_title'); $posts->post_description = $request->input('post_description'); $posts->user_id = Auth::user()->id; if(Input::hasFile('post_image')){ $file = Input::file('post_image'); $file -> move(public_path().'/posts/', $file-> getClientOriginalName()); $url = URL::to("/") . '/posts/' . $file-> getClientOriginalName(); } if(Input::hasFile('post_image_2')){ $file_2 = Input::file('post_image_2'); $file_2 -> move(public_path().'/posts/', $file_2-> getClientOriginalName()); $url_2 = URL::to("/") . '/posts/' . $file_2-> getClientOriginalName(); } if(Input::hasFile('post_image_3')){ $file_3 = Input::file('post_image_3'); $file_3 -> move(public_path().'/posts/', $file_3-> getClientOriginalName()); $url_3 = URL::to("/") . '/posts/' . $file_3-> getClientOriginalName(); } $posts->post_image = $url; $posts->post_image_2 = $url_2; $posts->post_image_3 = $url_3; $posts->save(); return redirect('/home')-> with('response','Post Added Succesfully'); } public function view($post_id){ $user_perm = Auth::user()->permition; $users = User::all(); $posts = Post::where('id','=',$post_id)->get(); $comments = DB::table('users') ->join('comments','users.id','=','comments.user_id') ->join('posts','comments.post_id','=','posts.id') ->select('users.name','comments.*') ->where(['posts.id' => $post_id]) ->get(); return view('/posts/view',['posts' => $posts,'comments' => $comments,'user_perm' => $user_perm]); } public function edit($post_id){ $posts = Post::find($post_id); return view('/posts/edit',['posts' => $posts]); } public function editPost(Request $request,$post_id){ $this->validate($request,[ 'post_title' => 'required', 'post_description' => 'required', ]); $posts = new Post; $posts->post_title = $request->input('post_title'); $posts->post_description = $request->input('post_description'); $posts->user_id = Auth::user()->id; if(Input::hasFile('post_image')){ $file = Input::file('post_image'); $file -> move(public_path().'/posts/', $file-> getClientOriginalName()); $url = URL::to("/") . '/posts/' . $file-> getClientOriginalName(); } else{ $url =""; } if(Input::hasFile('post_image_2')){ $file_2 = Input::file('post_image_2'); $file_2 -> move(public_path().'/posts/', $file_2-> getClientOriginalName()); $url_2 = URL::to("/") . '/posts/' . $file_2-> getClientOriginalName(); } else{ $url_2 =""; } if(Input::hasFile('post_image_3')){ $file_3 = Input::file('post_image_3'); $file_3 -> move(public_path().'/posts/', $file_3-> getClientOriginalName()); $url_3 = URL::to("/") . '/posts/' . $file_3-> getClientOriginalName(); } else{ $url_3 =""; } $posts->post_image = $url; $posts->post_image_2 = $url_2; $posts->post_image_3 = $url_3; $data = array( 'user_id' => $posts->user_id, 'post_title' => $posts->post_title, 'post_description' => $posts->post_description, 'post_image' => $posts->post_image, 'post_image_2' => $posts->post_image_2, 'post_image_3' => $posts->post_image_3 ); Post::where('id',$post_id) ->update($data); $posts->update(); return redirect('/home')-> with('response','Post Edited Succesfully'); } public function deletePost($post_id){ Post::where('id',$post_id) ->delete(); return redirect('/home')-> with('response','Post Deleted Succesfully'); } public function comment(Request $request,$post_id){ $this->validate($request,[ 'comment' => 'required', ]); $comment = new Comment; $comment ->user_id = Auth::user()->id; $comment ->post_id = $post_id; $comment ->comment = $request -> input('comment'); $comment->save(); return redirect('/view/'.$post_id)-> with('response','Comment Added Succesfully'); } public function editComment(Request $request) { // dd($id); $data = $request->all(); // dd($data); unset($data['_token']); Comment::where('id',$data['id'])->update($data); } public function deleteComment($post_id){ Comment::where('id',$post_id) ->delete(); return redirect('/home')-> with('response','Comment Deleted Succesfully'); } } <file_sep>/public/js/main.js $( document ).ready(function() { $('.comment_edit').click(function(){ // alert(); var id = $(this).data('id'); var comment = $('#comment_'+id).html(); console.log(comment) $('#edit_comment').val(comment) $('#edit_comment_Changes').attr('data-id',id) $('#Comment_Edit_Modal').modal('show') // $('#Post_Edit_Modal').modal('show'); }); $('#edit_comment_Changes').click(function(){ var token = $('meta[name="csrf-token"]').attr('content') var id = $(this).data('id'); var comment = $('#edit_comment').val() alert(comment) $.ajax({ method:'post', url: "/comment-edit", data:{id:id,comment:comment,_token:token}, success: function(result){ window.location.reload(); }}); }) });
693fc0fd2e0ba644438cd291e9506eba6f696f9f
[ "JavaScript", "PHP" ]
2
PHP
daviddev/social
365857b6f4e22117c728043a9a59795a2f865dab
1be52bc98d3fd9e114585ee56c37f31378847a5a
refs/heads/master
<repo_name>ipatch/sample_app<file_sep>/spec/requests/static_pages_spec.rb # require 'rails_helper' # RSpec.describe "StaticPages", :type => :request do # describe "GET /static_pages" do # it "works! (now write some real specs)" do # get static_pages_index_path # expect(response.status).to be(200) # end # end # end require 'spec_helper' describe "Static pages" do describe "Home page" do before { visit root_path } it { should have_selector('h1', text: 'Sample App') } it { should have_selector('title', text: full_title('')) } it { should_not have_selector('title', text: '| Home')} end describe "Help page" do before { visit help_path } it { should have_selector('h1', :text => 'Help') } it { should have_selector('title', text: full_title('Help')) } end describe "About page" do before { visit about_path } it { should have_selector('h1', :text => 'About Us')} it { should have_selector('title', text: full_title('About Us')) } end # Old style syntax for writing tests describe "Contact page" do before { visit contact_path } it "should have the h1 'Contact'" do visit contact_path page.should have_selector('h1', :text => 'Contact') end it "should have the right title" do visit contact_path page.should have_selector('title', text: full_title('Contact')) } end it "should have the right links on the layout" do visit root_path click_link "About" page.should have_selector 'title', text: full_title('About Us') click_link "Help" page.should have_selector 'title', text: full_title('Help') click_link "Contact" page.should have_selector 'title', text: full_title('Contact') click_link "Home" click_link "Sign up now!" page.should have_selector 'title', text: full_title('Sign up') click_link "sample app" page.should have selector 'h1', text: 'Sample App' end it "should have the right links on the layout" do visit root_path click_link "Sign in" page.should have_selector 'title', text: full_title('Sign in') click_link "About" page.should have_selector 'title', text: full_title('About Us') click_link "Help" page.should have_selector 'title', text: full_title('Help') click_link "Contact" page.should have_selector 'title', text: full_title('Contact') click_link "Home" click_link "Sign up now!" page.should have_selector 'title', text: full_title('Sign up') click_link "sample app" page.should have_selector 'h1', text: 'Sample App' end end<file_sep>/spec/factories.rb FactoryGirl.define do factory :user do name "<NAME>" email "<EMAIL>" password "<PASSWORD>" password_confirmation "<PASSWORD>" end end<file_sep>/README.md # This is the Ruby on Rails sample application.
479ee154ef4dd757a608bc31f1e0d0a5c9fd2c19
[ "Markdown", "Ruby" ]
3
Ruby
ipatch/sample_app
6e8ad8169787cca2bb5713a4d44ff583d3206ca0
c8feb5e3063b5e8d5b93692975ccadb689b5afbf
refs/heads/master
<file_sep> var conString = "postgres://postgres:qwerty@localhost:5432/comicdb"; //POSTGRES DATABASE CONNECTION ADDY, FORMAT usernamer:pass@addressOrPort/dbname var pg = require("pg"), scraper = require('scraper'); //require node modules for postgres txs and scraper for scraping hurr durr function putInDb(name, src, title) { //had to make the table(comics) by hand and well psql cmds, dunno if it can autobuild a table var txtstr = "INSERT INTO comics(name, src, title) VALUES ('"+name+"', '"+src+"', '"+title+"')"; pg.connect(conString, function(error, client) { if (error) { return console.log(error); } else { return client.query(txtstr, function(error, results) { if (error) { return console.log(error); } }); } }); } function scrapeCnH(){ var k=2; //replace with the highest comic no. or w/e for (i=0; i<k; i++){ console.log(i); scraper('http://www.explosm.net/comics/'+i, function(err, jQuery) { if (err) {throw err} //check each img on the page, if the image src contains '/db/files/Comics', its the comic, add to the db jQuery('img').each(function() { var src = jQuery(this).attr( "src" ), title = jQuery('title').text(); if ( src.indexOf('/db/files/Comics') !== -1 ) { putInDb('C&H', src, title); } }); }); } } //Zen pencils is handled differently since the comic links are unique. //getNameZP goes to the archive page and retrieves the links to the comic //scrapeZP gets the img src and adds to db //also you should check out zenpencils, think you might like it function getNameZP() { scraper('http://zenpencils.com/archives/', function(err, jQuery) { if (err) {throw err} var src = jQuery('.archive-title a').attr( "href"); /* if ( src == "http://zenpencils.com/comic/127-j-k-rowling-the-fringe-benefits-of-failure/" ) { console.log(src); scrapeZP(src); } */ //Comment the following block, and uncomment the above block to test if it appears to not work //Its really slow on mine, and logs all the src's after a long wait and the next part takes the same time jQuery('.archive-title a').each(function() { var src = jQuery(this).attr( "href" ), title = jQuery(this).text(); console.log(src); scrapeZP(src); }); }); } function scrapeZP(src) { var src = src; scraper(src, function(err, jQuery) { if (err) {throw err} var src = jQuery('#comic-1 img').attr( "src" ), title = jQuery('title').text(); console.log(src + title); putInDb('zenpencils', src, title); }); } //broken or was broken function scrapeSMBC() { for (i=1; i<3; i++){ scraper( { 'uri': 'http://www.smbc-comics.com/?id=1#comic' , 'headers': { 'User-Agent': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)' } } , function(err, jQuery) { if (err) {throw err} console.log(jQuery('#main').text()); jQuery('img').each(function() { var src = jQuery(this).attr( "src" ); console.log(src); console.log(src().text()); }); } ); } } //XKCD has a JSON api so is handled differently function scrapeXKCD(){ var Client = require('node-rest-client').Client; //require node rest client for getting JSON and it can do RESTful stuff as well I guess var k = 2; //replace with highest xkcd comic number or w/e client = new Client(); for (i=0; i<k; i++){ client.get("http://xkcd.com/"+i+"/info.0.json", function(data, response){ // parsed response body as js object var dataObj = JSON.parse(data), imgSrc = dataObj['img'], title = dataObj['safe_title'] + " " + dataObj['num']; putInDb('XKCD', imgSrc, title); }); } } getNameZP(); <file_sep>node-scraper ============ some node.js scrapers I wrote for something I was working on
caa3e01b92339b65acbe47a16e497789fac201bb
[ "JavaScript", "Markdown" ]
2
JavaScript
kaustavha/node-scraper
d3d99a2eb02deb9833ff8f00fb5c4ffe10344537
604ba1f8ebea60c82190fc2b7dcc4064b48b34bf
refs/heads/master
<file_sep>#pragma once #include "IrcMessage.h" class IrcSendMessage : public IrcMessage { public: IrcSendMessage(const std::string&); ~IrcSendMessage(); virtual const CommandType GetCommandType() const; virtual const std::string GetMessageString() const; protected: virtual void ConvertMessageToCommandMessage(); virtual const CommandType GetCommandTypeFromString(const std::string& commandString) const; }; <file_sep># kIRC Simple IRC client <file_sep>#pragma once #include "IrcMessage.h" class IrcReceiveMessage : public IrcMessage { public: IrcReceiveMessage(const std::string&); ~IrcReceiveMessage(); const CommandType GetCommandType() const; const std::string GetMessageString() const; protected: void ConvertMessageToCommandMessage(); const CommandType GetCommandTypeFromString(const std::string& commandString) const; }; <file_sep>#include "stdafx.h" #include "IrcReceiveMessage.h" IrcReceiveMessage::IrcReceiveMessage(const std::string& message) :IrcMessage(message) { ConvertMessageToCommandMessage(); } IrcReceiveMessage::~IrcReceiveMessage() { } void IrcReceiveMessage::ConvertMessageToCommandMessage() { if( initialMessage_.size() > 0 && initialMessage_.at(0) == '/' ) { int spaceIndex = initialMessage_.find(" "); commandMessage_.Command = GetCommandTypeFromString(initialMessage_.substr(1, spaceIndex-1)); // If we didn't figure a specific command, just use the whole string as our message if( commandMessage_.Command == NONE ) commandMessage_.Message = initialMessage_; else commandMessage_.Message = initialMessage_.substr(spaceIndex + 1, initialMessage_.length()); } else { commandMessage_.Command = CommandType::NONE; commandMessage_.Message = initialMessage_; } } const IrcMessage::CommandType IrcReceiveMessage::GetCommandTypeFromString(const std::string& commandString) const { std::string lower = commandString; std::transform(commandString.begin(), commandString.end(), lower.begin(), ::tolower); if( lower == "ping" ) return PING; if( lower == "join" ) return JOIN; if( lower == "part" ) return PART; if( lower == "prvmsg" ) return PRVMSG; if( lower == "quit" ) return QUIT; if( lower == "notice" ) return NOTICE; else return NONE; } const std::string IrcReceiveMessage::GetMessageString() const { return commandMessage_.Message; } const IrcMessage::CommandType IrcReceiveMessage::GetCommandType() const { return commandMessage_.Command; }<file_sep>// IRCClient.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "IrcSendMessage.h" #include "IrcReceiveMessage.h" using namespace std; // Handling socket reading/writing int sendMessage(SOCKET& connectedSocket, string& message); int readMessage(SOCKET& connectedSocket); // Handling recieved/sent message parsing void parseMessage(const string& recievedMessage); void buildMessage(string& recievedMessage, string& tempMessage); void parseInput(string& command); SOCKET connectSocket = INVALID_SOCKET; string currentChannel = ""; bool isExiting = false; int main(int argc, char* argv[]) { // Some defaults if we aren't given anything string server = "chat.freenode.net"; string port = "8000"; string pass = "<PASSWORD>"; string nick = "guest6<PASSWORD>"; string user = "kIRC 8 * :kIRC"; if( argc > 1 ) { server = string(argv[1]); port = string(argv[2]); pass = string(argv[3]); nick = string(argv[4]); user = string(argv[5]); } // Initialize Winsock. WSAData wsaData; int ret = 0; ret = WSAStartup(MAKEWORD(2,2), &wsaData); if( ret != 0 ) { printf("WSAStartup Failed: %d\n", ret); return 1; } // Create a socket. struct addrinfo *result = nullptr, *ptr = nullptr, hints; ZeroMemory(&hints, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; ret = getaddrinfo(server.c_str(), port.c_str(), &hints, &result); if( ret != 0 ) { printf("getaddrinfo failed: %d\n", ret); WSACleanup(); return 1; } ptr = result; for( ; ptr != nullptr; ptr = ptr->ai_next ) { connectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol); if( connectSocket == INVALID_SOCKET ) { printf("Error at socket(): %ld\n", WSAGetLastError()); freeaddrinfo(result); WSACleanup(); return 1; } // Connect to the server. ret = connect(connectSocket, ptr->ai_addr, (int)ptr->ai_addrlen); if( ret == SOCKET_ERROR ) { closesocket(connectSocket); connectSocket = INVALID_SOCKET; continue; } break; } freeaddrinfo(result); if( connectSocket == INVALID_SOCKET ) { printf("Unable to connect to server: %d\n"); WSACleanup(); return 1; } // Create a thread to handle reading and printing recieved messages thread readThread(readMessage, connectSocket); // Log in string sendBuf; // Send Pass sendBuf = "PASS " + pass; ret = sendMessage(connectSocket, sendBuf); // Send Nick sendBuf = "NICK " + nick; ret = sendMessage(connectSocket, sendBuf); // Send User sendBuf = "USER " + user; ret = sendMessage(connectSocket, sendBuf); // Main loop string cmd; while( !isExiting ) { getline(cin, cmd); parseInput(cmd); } printf("%s", "Disconnecting...\n"); // Disconnect. ret = shutdown(connectSocket, SD_SEND); readThread.join(); if( ret == SOCKET_ERROR ) { printf("Shutdown failed: %d\n", WSAGetLastError()); closesocket(connectSocket); WSACleanup(); return 1; } printf("%s", "Disconnected.\n"); closesocket(connectSocket); WSACleanup(); return 0; } int readMessage(SOCKET& connectedSocket) { const int buf = 512; int ret; string tempMessage = ""; char recvBuf[buf]; do { memset(recvBuf, 0, buf); ret = recv(connectedSocket, recvBuf, buf-1, 0); if( ret > 0 ) { // Parse message here buildMessage(string(recvBuf), tempMessage); } else { printf("recv failed: %d\n", WSAGetLastError()); isExiting = true; } } while( !isExiting ); return ret; } void buildMessage(string& recievedMessage, string& tempMessage) { // do some parsing stuff (e.g. "PING PONG"/"PRIVMSG"/etc) int endIndex = recievedMessage.find("\r\n"); while( endIndex != -1 ) { tempMessage.append(recievedMessage.substr(0, endIndex)); cout << tempMessage << endl; tempMessage.clear(); recievedMessage = recievedMessage.substr(endIndex + 2, recievedMessage.length()); endIndex = recievedMessage.find("\r\n"); } // If we have an uncompleted message, start building it up if( recievedMessage.length() > 0 ) { tempMessage.append(recievedMessage); } } void parseMessage(const string& recievedMessage) { IrcReceiveMessage message(recievedMessage); std::string toPrint; switch( message.GetCommandType() ) { case IrcMessage::PING: { toPrint = "PONG :" + message.GetMessageString(); } break; case IrcMessage::PRVMSG: case IrcMessage::NOTICE: case IrcMessage::NONE: { toPrint = message.GetMessageString(); } break; } if( toPrint.length() > 0 ) cout << toPrint << endl; } int sendMessage(SOCKET& connectedSocket, string& message) { message += "\r\n"; int ret = send(connectedSocket, message.c_str(), (int)strlen(message.c_str()), 0); if( ret == SOCKET_ERROR ) { printf("Send failed: %d\n", WSAGetLastError()); closesocket(connectedSocket); WSACleanup(); return 1; } return ret; } void parseInput(string& input) { IrcSendMessage message(input); std::string toSend; switch( message.GetCommandType() ) { case IrcMessage::QUIT: { toSend = "QUIT"; isExiting = true; } break; case IrcMessage::JOIN: { // Grab channel name toSend = "JOIN "; string channel = message.GetMessageString(); if( channel.find("#") == -1 ) channel.insert(0, "#"); toSend += channel; currentChannel = channel; } break; case IrcMessage::PART: { toSend = "PART " + currentChannel; currentChannel = ""; } break; case IrcMessage::PING: { toSend = "PONG " + message.GetMessageString(); } case IrcMessage::PRVMSG: case IrcMessage::NONE: { // Send the input as a message to wherever we're currently looking if( currentChannel != "" && message.GetMessageString().length() > 0 ) toSend = "PRIVMSG " + currentChannel + " :" + message.GetMessageString(); } break; } if( toSend.length() > 0 ) sendMessage(connectSocket, toSend); }<file_sep>#pragma once class IrcMessage { public: IrcMessage(const std::string& message); ~IrcMessage(); enum CommandType { UKNOWN, PING, JOIN, PART, PRVMSG, NOTICE, QUIT, NONE }; virtual const CommandType GetCommandType() const = 0; virtual const std::string GetMessageString() const = 0; protected: struct CommandMessage { CommandMessage() : Command(CommandType::UKNOWN) {} std::string Message; CommandType Command; } commandMessage_; virtual void ConvertMessageToCommandMessage() = 0; virtual const CommandType GetCommandTypeFromString(const std::string& commandString) const = 0; std::string initialMessage_; }; <file_sep>#include "stdafx.h" #include "IrcMessage.h" IrcMessage::IrcMessage(const std::string& message) { initialMessage_ = message; } IrcMessage::~IrcMessage() { }
66ff9e9015deb6d2d8bacd4d6e3dc43f6bcf5c98
[ "Markdown", "C++" ]
7
C++
kbake/kIRC
1225ed858ebfed71b89d1ee47d598a76019a2829
364290e6043e81d33644455d4b56a823ccb68507
refs/heads/master
<file_sep>package com.anwesome.ui.seekedgallerylibrary; import android.app.Activity; import android.content.Context; import android.graphics.*; import android.hardware.display.DisplayManager; import android.view.*; import android.widget.ImageView; import java.util.ArrayList; import java.util.List; /** * Created by anweshmishra on 01/02/17. */ public class SeekedGallery { private float seekx = 0,seekh = 100; private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); private Activity activity; private List<Bitmap> bitmaps = new ArrayList<>(); private SeekedView seekedView; private ImageView seekedImageView; private GalleryView galleryView; private int currentIndex = 0; private long prevTime = System.currentTimeMillis(); private int interval=2000,duration=10000; private int n = 0,w=500,h=500; public SeekedGallery(Activity activity) { this.activity = activity; initDimensions(); } public void addBitmap(Bitmap bitmap) { bitmaps.add(bitmap); } private void initDimensions() { DisplayManager displayManager = (DisplayManager)activity.getSystemService(Context.DISPLAY_SERVICE); Display display = displayManager.getDisplay(0); if(display!=null) { Point size = new Point(); display.getRealSize(size); w = size.x; h = size.y; seekh = h/20; seekx = seekh/2; } } public void setInterval(int interval) { this.interval = interval; } public void addViewToParent() { seekedImageView = new ImageView(activity); galleryView = new GalleryView(activity); duration = bitmaps.size()*interval; seekedView = new SeekedView(activity); galleryView.setX(w/8); galleryView.setY(h/12); seekedView.setX(0); seekedView.setY(7*h/10); seekedImageView.setX(0); seekedImageView.setY(3*h/5); seekedImageView.setVisibility(View.INVISIBLE); activity.addContentView(seekedImageView,new ViewGroup.LayoutParams(h/7,h/7)); activity.addContentView(seekedView,new ViewGroup.LayoutParams(w,(int)seekh)); activity.addContentView(galleryView,new ViewGroup.LayoutParams(2*w/3,h/2)); } private class GalleryView extends View { public GalleryView(Context context) { super(context); } public void onDraw(Canvas canvas) { int w = canvas.getWidth(),h = canvas.getHeight(),r = w/6; if(h<w) { r = h/6; } paint.setStyle(Paint.Style.STROKE); paint.setColor(Color.parseColor("#757575")); canvas.drawRoundRect(new RectF(w/20,h/20,19*w/20,19*h/20),r,r,paint); Path path = new Path(); path.addRoundRect(new RectF(w/20,h/20,19*w/20,19*h/20),r,r, Path.Direction.CCW); canvas.clipPath(path); paint.setStyle(Paint.Style.FILL); if(bitmaps.size()>0) { Bitmap bitmap = bitmaps.get(currentIndex); bitmap = Bitmap.createScaledBitmap(bitmap, 9 * w / 10, 9 * h / 10, true); canvas.drawBitmap(bitmap, w / 20, h / 20, paint); } } } private class SeekedView extends View { private boolean animated = true; private int x = 0,time = 1; private boolean isDown = false,seeking = false; public SeekedView(Context context) { super(context); } public void onDraw(Canvas canvas) { paint.setColor(Color.parseColor("#37474F")); canvas.drawRoundRect(new RectF(0,canvas.getHeight()/4,canvas.getWidth(),3*canvas.getHeight()/4),canvas.getHeight()/4,canvas.getHeight()/4,paint); paint.setColor(Color.parseColor("#d32f2f")); canvas.drawRoundRect(new RectF(0,canvas.getHeight()/4,seekx,3*canvas.getHeight()/4),canvas.getHeight()/4,canvas.getHeight()/4,paint); canvas.drawCircle(seekx,canvas.getHeight()/2,canvas.getHeight()/2,paint); if(seekx<w-w/duration && animated) { try { if(System.currentTimeMillis()-prevTime>=1000 && !isDown) { seekx+=((w)*1000.0f)/duration; updateGallery(); if(currentIndex == bitmaps.size()-1 && !isDown) { seekx = canvas.getWidth()-canvas.getHeight()/2; animated = false; } prevTime = System.currentTimeMillis(); } invalidate(); } catch (Exception ex) { } } } public boolean onTouchEvent(MotionEvent event) { float x = event.getX(),y = event.getY(); switch(event.getAction()) { case MotionEvent.ACTION_DOWN: if(!isDown && x>=seekx-seekh/2 && x<=seekx+seekh/2 && y>=0 && y<=seekh) { isDown = true; seekx = event.getX(); } break; case MotionEvent.ACTION_MOVE: if(isDown) { seekx = event.getX(); updateSeekedImageView(); animated = true; postInvalidate(); } break; case MotionEvent.ACTION_UP: if(isDown){ updateGallery(); seekedImageView.setVisibility(INVISIBLE); isDown = false; } break; } return true; } private void updateSeekedImageView() { int tempIndex = (int)((seekx*bitmaps.size())/w); seekedImageView.setX(seekx-seekedImageView.getMeasuredWidth()/2); seekedImageView.setVisibility(VISIBLE); seekedImageView.setImageBitmap(bitmaps.get(tempIndex)); } private void updateGallery() { currentIndex = (int)((seekx*bitmaps.size())/w); if(currentIndex>=bitmaps.size()) { currentIndex = bitmaps.size()-1; } galleryView.postInvalidate(); } } } <file_sep>include ':app', ':seekedgallerylibrary'
82049a37736571870c8efd807e1c032c7676ce9b
[ "Java", "Gradle" ]
2
Java
Anwesh43/SeekedGallery
e17b7a2ed6015b6c04e2aa42db0493e4503f6264
febc20dcafb2cf8b77038e77d35b27500c54e07b
refs/heads/master
<repo_name>robertmeans/evergreenaa<file_sep>/_includes/nav-original.php <nav id="navigation" class="sm-g"> <div class="top-nav <?php if (isset($_SESSION['admin']) && ($_SESSION['mode'] == 1)) { ?>admin-logged<?php } ?>" onclick="openNav();"> <div class="menu-basket"> <div class="bar-box"> <span class="bars"></span> </div> <div class="mt">Menu</div> </div> </div> </nav> <nav id="navigation" class="lg-g"><?php // mobile nav ?> <div class="top-nav <?php if (isset($_SESSION['admin']) && ($_SESSION['mode'] == 1)) { ?>admin-logged<?php } ?>" onclick="openNav();"><i class="fas fa-bars"></i></div> </nav> <div id="side-nav" class="sidenav"> <div id="sidenav-wrapper"> <a class="closebtn" onclick="closeNav();"><i class="fas far fa-caret-square-down"></i> <div class="ctxt ctd">Close</div></a><?php // make sure session is cleared if going from login to homepage via nav if ($layout_context == 'login-page') { ?> <a href="<?= WWW_ROOT . '/logout.php' ?>" onclick="closeNav();">Homepage</a> <?php } else { ?> <a href="<?= WWW_ROOT ?>" class="<?php if ($layout_context == 'home-public' || $layout_context == 'home-private') { echo 'nav-active'; } ?>">Homepage</a> <?php } if (isset($_SESSION['admin']) && ($_SESSION['admin'] == 85 || $_SESSION['admin'] == 86)) { ?> <a href="<?= WWW_ROOT . '/logout.php' ?>" onclick="closeNav();">Homepage</a> <?php } ?> <?php // for DEVELOPMENT // it turns the Message Board link on only for me (bob id=1 (<EMAIL>) AND bobby id=2 (louifoot)) so I can see it from 2 accounts if ((isset($_SESSION['id']) && $_SESSION['id'] == 1 || $_SESSION['id'] == 2 || $_SESSION['id'] == 19) && $layout_context == 'message-board') { ?> <a href="<?= WWW_ROOT . '/message-board.php'; ?>" class="apr nav-active">Message Board</a> <?php } else if (isset($_SESSION['id']) && ($_SESSION['id'] == 1 || $_SESSION['id'] == 2 || $_SESSION['id'] == 19)) { ?> <a href="<?= WWW_ROOT . '/message-board.php'; ?>" class="apr" onclick="closeNav();"><span class="new-item">New</span><span class="mb-new">Message Board</span></a> <?php } ?> <?php // for PRODUCTION /* if ($layout_context == 'message-board') { ?> <a href="<?= WWW_ROOT . '/message-board.php'; ?>" class="apr nav-active">Message Board</a> <?php } else { ?> <a href="<?= WWW_ROOT . '/message-board.php'; ?>" class="apr" onclick="closeNav();"><span class="new-item">New</span><span class="mb-new">Message Board</span></a> <?php } */ ?> <?php if (isset($_SESSION['id']) && $layout_context == 'dashboard') { ?> <a href="manage.php" class="<?php if ($layout_context == 'dashboard') { echo 'nav-active'; } ?>">My Dashboard</a> <?php } if (isset($_SESSION['id']) && $layout_context != 'dashboard') { ?> <a href="manage.php" class="<?php if ($layout_context == 'dashboard') { echo 'nav-active'; } ?>" onclick="closeNav();">My Dashboard</a> <?php } if ((isset($_SESSION['admin']) && ($_SESSION['mode'] == 1 && ($_SESSION['admin'] == 1 || $_SESSION['admin'] == 3))) && $layout_context == 'um') { ?> <a href="user_management.php" class="<?php if ($layout_context == 'um') { echo 'nav-active'; } ?>">Manage Users</a> <?php } if ((isset($_SESSION['admin']) && ($_SESSION['mode'] == 1 && ($_SESSION['admin'] == 1 || $_SESSION['admin'] == 3))) && $layout_context != 'um') { ?> <a href="user_management.php" onclick="closeNav();">Manage Users</a> <?php } // my eyes only if (isset($_SESSION['admin']) && ($_SESSION['mode'] == 1 && $_SESSION['admin'] == 1)) { ?> <a href="email_everyone_BCC.php" class="<?php if ($layout_context == 'alt-manage') { echo 'nav-active'; } ?>" onclick="closeNav();">Email Everyone</a> <?php } if (isset($_SESSION['admin']) && (($_SESSION['admin'] == 1 || $_SESSION['admin'] == 2 || $_SESSION['admin'] == 3) && $_SESSION['mode'] == 0)) { ?> <form action="process-admin-mode.php" method="post"> <input type="hidden" name="mode" value="1"> <input type="hidden" id="url" name="url"> <a class="admin-login" onclick="$(this).closest('form').submit(); closeNav();">Enter Admin Mode</a> </form> <?php } if (isset($_SESSION['admin']) && (($_SESSION['admin'] == 1 || $_SESSION['admin'] == 2 || $_SESSION['admin'] == 3) && $_SESSION['mode'] == 1)) { ?> <form action="process-admin-mode.php" method="post"> <input type="hidden" name="mode" value="0"> <input type="hidden" id="url" name="url"> <a class="admin-logout" onclick="$(this).closest('form').submit(); closeNav();">Exit Admin Mode</a> </form> <?php } if (!isset($_SESSION['id']) && $layout_context != "login-page") { ?> <a href="login.php" class="login" onclick="closeNav();"><i class="fas far fa-power-off"></i> Login</span></a> <?php } else if ($layout_context != "login-page") { ?> <a href="logout.php" class="logout" onclick="closeNav();"><i class="fas far fa-power-off"></i> Logout</a> <?php } if (!isset($_SESSION['id']) && ($layout_context != "login-page")) { ?> <a href="<?= WWW_ROOT . '/signup.php' ?>" class="cc-x">Create an Account</a> <a id="toggle-msg-one" class="cc-x eotw">Why Join?</a> <?php } else if ($layout_context == "login-page") { ?> <a id="toggle-msg-one" class="cc-x eotw">Why Join?</a> <?php } else { ?> <a id="toggle-msg-one" class="cc-x eotw">Extras</a> <?php } ?> </div><!-- #sidenav-wrapper --> <?php if (isset($_SESSION['admin']) && $layout_context != 'login-page') { if ($_SESSION['admin'] == 1 || $_SESSION['admin'] == 2 || $_SESSION['admin'] == 3) { ?> <div class="admin-role"> <?php if ($_SESSION['admin'] == 1) { ?> The Bob <a id="toggle-role-key"><i class="fas fa-info-circle"></i></a> <?php } else if ($_SESSION['admin'] == 2) { ?> <?= $_SESSION['username'] . ': '; ?>Tier II Admin <a id="toggle-role-key"><i class="fas fa-info-circle"></i></a> <?php } else if ($_SESSION['admin'] == 3) { ?> <?= $_SESSION['username'] . ': '; ?>Top Tier Admin <a id="toggle-role-key"><i class="fas fa-info-circle"></i></a> <?php } ?> </div> <?php } else if ($_SESSION['admin'] == 85 || $_SESSION['admin'] == 86) { ?> <div class="sus-user"> <?= $_SESSION['username'] . ': '; ?>Suspended Account </div> <?php } else { ?> <div class="member-role"> Member: <?= $_SESSION['username'] . ' '; ?> <a id="toggle-role-key"><i class="fas fa-info-circle"></i></a> </div> <?php } } else { ?> <div class="visitor-role"> Welcome Visitor <a id="toggle-role-key"><i class="fas fa-info-circle"></i></a> </div> <?php } ?> </div><!-- #side-nav --> <file_sep>/email_everyone_PERSONAL.php <?php $layout_context = "email-everyone"; require_once 'config/initialize.php'; // For my eyes only! if ($_SESSION['id'] != 1) { header('location: https://www.merriam-webster.com/dictionary/go%20away'); exit(); } ?> <?php if ((is_post_request()) && (isset($_POST['email-everyone']))) { $result = find_all_users(); while($subject = mysqli_fetch_assoc($result)) { $send_to = $subject['email']; $greeting = $_POST['greeting']; $msgsubject = $_POST['msgsubject']; $user_name = $subject['username']; $emaileveryonemsg = ($_POST['greeting'] . ' ' . $user_name . ',<br><br>' . $_POST['emaileveryonemsg']) ?? ''; if ($subject['verified'] != 0) { email_everyone_PERSONAL($msgsubject, $send_to, nl2br($emaileveryonemsg)); // echo $subject['username'] . "<br>"; } } mysqli_free_result($result); header('location: manage.php'); // revise your message. } else if ((is_post_request()) && (isset($_POST['revise']))) { ?> <?php $msgsubject = $_POST['msgsubject'] ?? ''; $greeting = $_POST['greeting'] ?? ''; $emaileveryonemsg = $_POST['emaileveryonemsg'] ?? ''; ?> <?php require '_includes/head.php'; ?> <body> <?php require '_includes/nav.php'; ?> <?php require '_includes/msg-set-timezone.php'; ?> <?php require '_includes/msg-extras.php'; ?> <img class="background-image" src="_images/aa-logo-dark_mobile.gif" alt="AA Logo"> <div id="manage-wrap"> <div class="manage-simple-admin"> <h1>Email All Members</h1> <p class="admin-email"> <a href="manage.php">Back</a> | <a href="logout.php">Logout</a> </p> </div> <div class="manage-simple-email"> <form class="admin-email-form" action="email_review_PERSONAL.php" method="post"> <label>Subject</label> <input type="text" name="msgsubject" value="<?= $msgsubject; ?>"> <div class="greeting-string"> <label>Greeting</label> <input type="text" name="greeting" class="greeting" value="<?= $greeting ?>"> </div> <div class="greeting-string"> <label>&nbsp;</label> <?= "Bah-BAY!," ?> </div> <textarea name="emaileveryonemsg" id="message-body"><?= $emaileveryonemsg; ?></textarea> <div class="update-rt"> <a class="cancel" href="manage.php">CANCEL</a> <input type="submit" name="admin-email" class="submit" value="REVIEW"> </div><!-- .update-rt --> </div><!-- .btm-notes --> </form> </div> </div><!-- #manage-wrap --> <?php require '_includes/footer.php'; ?> <?php } else { // if this is your first visit to the page, here's an empty form ?> <?php require '_includes/head.php'; ?> <body> <?php require '_includes/nav.php'; ?> <?php require '_includes/msg-set-timezone.php'; ?> <?php require '_includes/msg-extras.php'; ?> <img class="background-image" src="_images/aa-logo-dark_mobile.gif" alt="AA Logo"> <div id="manage-wrap"> <div class="manage-simple-admin"> <h1>Email All Members</h1> <p class="admin-email"> <a href="manage.php">Back</a> | <a href="logout.php">Logout</a> </p> </div> <div class="manage-simple-email"> <form class="admin-email-form" action="email_review_PERSONAL.php" method="post"> <label>Subject</label> <input type="text" name="msgsubject"> <div class="greeting-string"> <label>Greeting</label> <input type="text" name="greeting" class="greeting"> </div> <div class="greeting-string"> <label>&nbsp;</label> <?= "Bah-BAY!," ?> </div> <textarea name="emaileveryonemsg"></textarea> <div class="update-rt"> <a class="cancel" href="manage.php">CANCEL</a> <input type="submit" name="admin-email" class="submit" value="REVIEW"> </div><!-- .update-rt --> </div><!-- .btm-notes --> </form> </div> </div><!-- #manage-wrap --> <?php require '_includes/footer.php'; ?> <?php } ?><file_sep>/manage_new_review.php <?php require_once 'config/initialize.php'; require_once 'config/verify_admin.php'; if ($_SESSION['admin'] == 85 || $_SESSION['admin'] == 86) { header('location: ' . WWW_ROOT); exit(); } $layout_context = "alt-manage"; if (!isset($_SESSION['id'])) { $_SESSION['message'] = "You need to be logged in to access that page."; $_SESSION['alert-class'] = "alert-danger"; header('location: ' . WWW_ROOT . '/login.php'); exit(); } if ((isset($_SESSION['id'])) && (!$_SESSION['verified'])) { header('location: ' . WWW_ROOT); exit(); } if (!isset($_GET['id'])) { header('location: ' . WWW_ROOT); } $id = $_GET['id']; $id_user = $_SESSION['id']; $role = $_SESSION['admin']; $row = edit_meeting($id); require '_includes/head.php'; ?> <body> <?php if (WWW_ROOT != 'http://localhost/evergreenaa') { ?> <div class="preload"><p>One meeting at a time.</p></div> <?php } ?> <?php require '_includes/nav.php'; ?> <?php require '_includes/msg-set-timezone.php'; ?> <?php require '_includes/msg-extras.php'; ?> <?php require '_includes/msg-role-key.php'; ?> <img class="background-image" src="_images/aa-logo-dark_mobile.gif" alt="AA Logo"> <div id="manage-wrap"> <div class="confirm">TEST & SELECT AUDIENCE</div> <div class="manage-simple intro"> <?php if ($role != 1 && $role != 2) { ?> <p>Take a look. Is everything the way you want it? If not, click the <a class="manage-edit inline" href="manage_edit.php?id=<?= h(u($id)); ?>"><i class="far fa-edit"></i> edit button</a> and polish this sucker up! Or save it for later.</p> <?php } else if ($role == 1) { ?> <p>Hey Me,</p> <p>Quit talking to yourself.</p> <?php } else { ?> <p>Hey<?= ' ' . $_SESSION['username'] . ',' ?></p> <p>Make sure everything's just right.</p> <?php } ?> <?php require '_includes/inner_nav.php'; ?> </div> <div class="manage-simple review"> <h1>Quick view</h1> <?php if ($row['id_user'] == $_SESSION['id']) { ?> <?php require '_includes/new-review-glance.php'; ?> <div class="weekday-edit-wrap"> <?php require '_includes/meeting-details.php'; ?> </div><!-- .weekday-wrap --> <form class="new-review" action="new_review_submit.php?id=<?= h(u($row['id_mtg'])); ?>" method="post"> <div class="visible"> <h1><i class="fas fa-users" style="margin-right:1em;"></i> Select your audience</h1> <div class="radio-group"> <div class='radio<?php if ($row['visible'] == "0") { echo " selected"; } ?>' value="0"> Draft | Save for later. </div> <div class='radio<?php if ($row['visible'] == "1") { echo " selected"; } ?>' value="1"> Private | Only you will see this. </div> <div class='radio<?php if ($row['visible'] == "2") { echo " selected"; } ?>' value="2"> Members Only | Only members of EvergreenAA.com.</div> <div class='radio<?php if ($row['visible'] == "3") { echo " selected"; } ?>' value="3"> Public | Share with everyone. No membership required. </div> <?php /* grab value and put it into hidden field to submit this is also in _includes/manage_new_review */ ?> <input type="hidden" name="visible" value="<?php if ($row['visible'] == "0") { echo "0"; } // Draft if ($row['visible'] == "1") { echo "1"; } // Private if ($row['visible'] == "2") { echo "2"; } // Members Only if ($row['visible'] == "3") { echo "3"; } // Public ?>" /> </div> </div><!-- .visible --> <input type="submit" name="update-mtg" class="done" value="DONE"> </form> <?php } else { echo "<p style=\"margin-top:1.5em;\">Quit trying to be sneaky.</p>"; } ?> </div> </div><!-- #manage-wrap --> <?php require '_includes/footer.php'; ?><file_sep>/_functions/functions.php <?php function apply_offset_to_meetings($results, $tz, $time_offset) { foreach($results as $k=>$v) { $from_tz_obj = new DateTimeZone('UTC'); $to_tz_obj = new DateTimeZone($tz); $cfoo = new DateTime($v['meet_time'], $from_tz_obj); $cfoo->setTimezone($to_tz_obj); if ($v['sun'] == '1') { $csun = new DateTime('Sunday ' . $v['meet_time'], $from_tz_obj); $csun->setTimezone($to_tz_obj); $nsun = $csun->format('l Hi'); if (strpos($nsun, 'Saturday') !== false) { $results[$k]['sat'] = '1'; } if ($time_offset == 'neg' && $v['mon'] != '1' && strpos($nsun, 'Sunday') === false) { $results[$k]['sun'] = '0'; } if ($time_offset == 'pos' && $v['sat'] != '1' && strpos($nsun, 'Sunday') === false) { $results[$k]['sun'] = '0'; } if (strpos($nsun, 'Monday') !== false) { $results[$k]['mon'] = '1'; } } if ($v['mon'] == '1') { $cmon = new DateTime('Monday ' . $v['meet_time'], $from_tz_obj); $cmon->setTimezone($to_tz_obj); $nmon = $cmon->format('l Hi'); if (strpos($nmon, 'Sunday') !== false) { $results[$k]['sun'] = '1'; } if ($time_offset == 'neg' && $v['tue'] != '1' && strpos($nmon, 'Monday') === false) { $results[$k]['mon'] = '0'; } if ($time_offset == 'pos' && $v['sun'] != '1' && strpos($nmon, 'Monday') === false) { $results[$k]['mon'] = '0'; } if (strpos($nmon, 'Tuesday') !== false) { $results[$k]['tue'] = '1'; } } if ($v['tue'] == '1') { $ctue = new DateTime('Tuesday ' . $v['meet_time'], $from_tz_obj); $ctue->setTimezone($to_tz_obj); $ntue = $ctue->format('l Hi'); if (strpos($ntue, 'Monday') !== false) { // if converted time contains "Monday" $results[$k]['mon'] = '1'; } if ($time_offset == 'neg' && $v['wed'] != '1' && strpos($ntue, 'Tuesday') === false) { $results[$k]['tue'] = '0'; } if ($time_offset == 'pos' && $v['mon'] != '1' && strpos($ntue, 'Tuesday') === false) { $results[$k]['tue'] = '0'; } if (strpos($ntue, 'Wednesday') !== false) { // if converted time contains "Wednesday" $results[$k]['wed'] = '1'; } } if ($v['wed'] == '1') { $cwed = new DateTime('Wednesday ' . $v['meet_time'], $from_tz_obj); $cwed->setTimezone($to_tz_obj); $nwed = $cwed->format('l Hi'); if (strpos($nwed, 'Tuesday') !== false) { $results[$k]['tue'] = '1'; } if ($time_offset == 'neg' && $v['thu'] != '1' && strpos($nwed, 'Wednesday') === false) { $results[$k]['wed'] = '0'; } if ($time_offset == 'pos' && $v['tue'] != '1' && strpos($nwed, 'Wednesday') === false) { $results[$k]['wed'] = '0'; } if (strpos($nwed, 'Thursday') !== false) { $results[$k]['thu'] = '1'; } } if ($v['thu'] == '1') { $cthu = new DateTime('Thursday ' . $v['meet_time'], $from_tz_obj); $cthu->setTimezone($to_tz_obj); $nthu = $cthu->format('l Hi'); if (strpos($nthu, 'Wednesday') !== false) { $results[$k]['wed'] = '1'; } if ($time_offset == 'neg' && $v['fri'] != '1' && strpos($nthu, 'Thursday') === false) { $results[$k]['thu'] = '0'; } if ($time_offset == 'pos' && $v['wed'] != '1' && strpos($nthu, 'Thursday') === false) { $results[$k]['thu'] = '0'; } if (strpos($nthu, 'Friday') !== false) { $results[$k]['fri'] = '1'; } } if ($v['fri'] == '1') { $cfri = new DateTime('Friday ' . $v['meet_time'], $from_tz_obj); $cfri->setTimezone($to_tz_obj); $nfri = $cfri->format('l Hi'); if (strpos($nfri, 'Thursday') !== false) { $results[$k]['thu'] = '1'; } if ($time_offset == 'neg' && $v['sat'] != '1' && strpos($nfri, 'Friday') === false) { $results[$k]['fri'] = '0'; } if ($time_offset == 'pos' && $v['thu'] != '1' && strpos($nfri, 'Friday') === false) { $results[$k]['fri'] = '0'; } if (strpos($nfri, 'Saturday') !== false) { $results[$k]['sat'] = '1'; } } if ($v['sat'] == '1') { $csat = new DateTime('Saturday ' . $v['meet_time'], $from_tz_obj); $csat->setTimezone($to_tz_obj); $nsat = $csat->format('l Hi'); if (strpos($nsat, 'Friday') !== false) { $results[$k]['fri'] = '1'; } if ($time_offset == 'neg' && $v['sun'] != '1' && strpos($nsat, 'Saturday') === false) { $results[$k]['sat'] = '0'; } if ($time_offset == 'pos' && $v['fri'] != '1' && strpos($nsat, 'Saturday') === false) { $results[$k]['sat'] = '0'; } if (strpos($nsat, 'Sunday') !== false) { $results[$k]['sun'] = '1'; } } $v['meet_time'] = $cfoo->format('Hi'); $b[] = $v['meet_time'] . ' ' . $v['group_name']; // echo print_r($b); } asort($b); foreach ($b as $k=>$v) { $c[] = $results[$k]; // echo print_r($c); } return $c; } function apply_offset_to_edit($time) { // initialize return variables $sun = '0'; $mon = '0'; $tue = '0'; $wed = '0'; $thu = '0'; $fri = '0'; $sat = '0'; $utc = 'UTC'; // $time['ut'] = $from_time (user input) // $time['tz'] = $from_tz (user's tz) // $utc = $to_tz (convert to UTC) $from_tz_obj = new DateTimeZone($utc); $to_tz_obj = new DateTimeZone($time['tz']); // $ct = "converted time" $ct = new DateTime($time['ut'], $from_tz_obj); $ct->setTimezone($to_tz_obj); if($time['sun'] == '1') { $csun = new DateTime('Sunday ' . $time['ut'], $from_tz_obj); $csun->setTimezone($to_tz_obj); $nsun = $csun->format('l Hi'); if (strpos($nsun, 'Saturday') !== false) { $sat = '1'; } if (strpos($nsun, 'Sunday') !== false) { $sun = '1'; } if (strpos($nsun, 'Monday') !== false) { $mon = '1'; } } if($time['mon'] == '1') { $cmon = new DateTime('Monday ' . $time['ut'], $from_tz_obj); $cmon->setTimezone($to_tz_obj); $nmon = $cmon->format('l Hi'); if (strpos($nmon, 'Sunday') !== false) { $sun = '1'; } if (strpos($nmon, 'Monday') !== false) { $mon = '1'; } if (strpos($nmon, 'Tuesday') !== false) { $tue = '1'; } } if($time['tue'] == '1') { $ctue = new DateTime('Tuesday ' . $time['ut'], $from_tz_obj); $ctue->setTimezone($to_tz_obj); $ntue = $ctue->format('l Hi'); if (strpos($ntue, 'Monday') !== false) { $mon = '1'; } if (strpos($ntue, 'Tuesday') !== false) { $tue = '1'; } if (strpos($ntue, 'Wednesday') !== false) { $wed = '1'; } } if($time['wed'] == '1') { $cwed = new DateTime('Wednesday ' . $time['ut'], $from_tz_obj); $cwed->setTimezone($to_tz_obj); $nwed = $cwed->format('l Hi'); if (strpos($nwed, 'Tuesday') !== false) { $tue = '1'; } if (strpos($nwed, 'Wednesday') !== false) { $wed = '1'; } if (strpos($nwed, 'Thursday') !== false) { $thu = '1'; } } if($time['thu'] == '1') { $cthu = new DateTime('Thursday ' . $time['ut'], $from_tz_obj); $cthu->setTimezone($to_tz_obj); $nthu = $cthu->format('l Hi'); if (strpos($nthu, 'Wednesday') !== false) { $wed = '1'; } if (strpos($nthu, 'Thursday') !== false) { $thu = '1'; } if (strpos($nthu, 'Friday') !== false) { $fri = '1'; } } if($time['fri'] == '1') { $cfri = new DateTime('Friday ' . $time['ut'], $from_tz_obj); $cfri->setTimezone($to_tz_obj); $nfri = $cfri->format('l Hi'); if (strpos($nfri, 'Thursday') !== false) { $thu = '1'; } if (strpos($nfri, 'Friday') !== false) { $fri = '1'; } if (strpos($nfri, 'Saturday') !== false) { $sat = '1'; } } if($time['sat'] == '1') { $csat = new DateTime('Saturday ' . $time['ut'], $from_tz_obj); $csat->setTimezone($to_tz_obj); $nsat = $csat->format('l Hi'); if (strpos($nsat, 'Friday') !== false) { $fri = '1'; } if (strpos($nsat, 'Saturday') !== false) { $sat = '1'; } if (strpos($nsat, 'Sunday') !== false) { $sun = '1'; } } return array($ct, $sun, $mon, $tue, $wed, $thu, $fri, $sat); } function day_range($today) { if ($today == 'Sunday') { $yesterday = 'Saturday'; $tomorrow = 'Monday'; } if ($today == 'Monday') { $yesterday = 'Sunday'; $tomorrow = 'Tuesday'; } if ($today == 'Tuesday') { $yesterday = 'Monday'; $tomorrow = 'Wednesday'; } if ($today == 'Wednesday') { $yesterday = 'Tuesday'; $tomorrow = 'Thursday'; } if ($today == 'Thursday') { $yesterday = 'Wednesday'; $tomorrow = 'Friday'; } if ($today == 'Friday') { $yesterday = 'Thursday'; $tomorrow = 'Saturday'; } if ($today == 'Saturday') { $yesterday = 'Friday'; $tomorrow = 'Sunday'; } $y = substr(lcfirst($yesterday), 0,3); $d = substr(lcfirst($today), 0,3); $t = substr(lcfirst($tomorrow), 0,3); return array($yesterday, $tomorrow, $y, $d, $t); } // downloads > Lynda Easy PHP TimeZone function timezone_select_options($selected_timezone="America/Denver") { $tz_idents = timezone_identifiers_list(); // $tz_indents = DateTimeZone::listIdentifiers(); $output = ""; $dt = new DateTime('now'); $output .= "<option value=\"America/New_York\""; if ($selected_timezone == 'America/New_York') { $output .= " selected"; } $output .= ">USA Eastern</option>"; $output .= "<option value=\"America/Chicago\""; if ($selected_timezone == 'America/Chicago') { $output .= " selected"; } $output .= ">USA Central</option>"; $output .= "<option value=\"America/Denver\""; if ($selected_timezone == 'America/Denver') { $output .= " selected"; } $output .= ">USA Mountain</option>"; $output .= "<option value=\"America/Phoenix\""; if ($selected_timezone == 'America/Phoenix') { $output .= " selected"; } $output .= ">USA [Phoenix, AZ]</option>"; $output .= "<option value=\"America/Los_Angeles\""; if ($selected_timezone == 'America/Los_Angeles') { $output .= " selected"; } $output .= ">USA Pacific</option>"; $output .= "<option value=\"America/Anchorage\""; if ($selected_timezone == 'America/Anchorage') { $output .= " selected"; } $output .= ">USA Alaska</option>"; $output .= "<option value=\"Pacific/Honolulu\""; if ($selected_timezone == 'Pacific/Honolulu') { $output .= " selected"; } $output .= ">USA Hawaii</option>"; $output .= "<option value=\"empty\">- - - - - - - - - - - - - - - - - - -</option>"; foreach($tz_idents as $zone) { $output .= "<option value=\"{$zone}\""; if ($selected_timezone != 'America/New_York' && $selected_timezone != 'America/Chicago' && $selected_timezone != 'America/Denver' && $selected_timezone != 'America/Phoenix' && $selected_timezone != 'America/Los_Angeles' && $selected_timezone != 'America/Anchorage' && $selected_timezone != 'Pacific/Honolulu') { if ($selected_timezone == $zone) { $output .= " selected"; } } $output .= ">"; $output .= $zone; $output .= "</option>"; } return $output; } function pretty_tz($tz) { if ($tz == 'America/New_York') { echo 'USA Eastern time'; } elseif ($tz == 'America/Chicago') { echo 'USA Central time'; } elseif ($tz == 'America/Denver') { echo 'USA Mountain time'; } elseif ($tz == 'America/Phoenix') { echo 'USA [Phoenix, AZ]'; } elseif ($tz == 'America/Los_Angeles') { echo 'USA Pacific time'; } elseif ($tz == 'America/Anchorage') { echo 'USA Alaska time'; } elseif ($tz == 'Pacific/Honolulu') { echo 'USA Hawaii time'; } elseif ($tz == 'UTC') { echo 'UTC/GMT time'; } else { echo trim(str_replace('_', ' ', substr($tz, strpos($tz, '/') + 1))) . ' time'; } // :-) return $tz; } function converted_time($time, $tz) { $utc = 'UTC'; $from_tz_obj = new DateTimeZone($utc); $to_tz_obj = new DateTimeZone($tz); $ct = new DateTime($time, $from_tz_obj); $ct->setTimezone($to_tz_obj); $nct = $ct->format('g:i A'); return $nct; } // function visitor_to_host($vdt, $vtz, $emhtz) { // $utc = $vtz; // $from_tz_obj = new DateTimeZone($utc); // $to_tz_obj = new DateTimeZone($emhtz); // $ct = new DateTime($vdt, $from_tz_obj); // $ct->setTimezone($to_tz_obj); // $nct = $ct->format('g:i A'); // return $nct; // } function convert_timezone($ey, $et, $etm, $meet_time, $yesterday, $today, $tomorrow, $tz, $time_offset) { $user_tz = new DateTimeZone($tz); // -7/dst: -6 $lc = substr(ucfirst($today), 0,3); if ($ey == '1') { $mt = new DateTime($yesterday . ' ' . $meet_time); $mt->setTimezone($user_tz); $mtz = $mt->format('D g:i A'); if (strpos($mtz, $lc) !== false) { return $mtz; } } if ($et == '1') { $mt = new DateTime($today . ' ' . $meet_time); $mt->setTimezone($user_tz); $mtz = $mt->format('D g:i A'); if (strpos($mtz, $lc) !== false) { return $mtz; } } if ($etm == '1') { $mt = new DateTime($tomorrow . ' ' . $meet_time); $mt->setTimezone($user_tz); $mtz = $mt->format('D g:i A'); if (strpos($mtz, $lc) !== false) { return $mtz; } } } function figger_it_out($time) { // initialize return variables $sun = '0'; $mon = '0'; $tue = '0'; $wed = '0'; $thu = '0'; $fri = '0'; $sat = '0'; $utc = 'UTC'; // $time['ut'] = $from_time (user input) // $time['tz'] = $from_tz (user's tz) // $utc = $to_tz (convert to UTC) $from_tz_obj = new DateTimeZone($time['tz']); $to_tz_obj = new DateTimeZone($utc); // $ct = "converted time" $ct = new DateTime($time['ut'], $from_tz_obj); $ct->setTimezone($to_tz_obj); if($time['sun'] == '1') { $csun = new DateTime('Sunday ' . $time['ut'], $from_tz_obj); $csun->setTimezone($to_tz_obj); $nsun = $csun->format('l Hi'); if (strpos($nsun, 'Saturday') !== false) { $sat = '1'; } if (strpos($nsun, 'Sunday') !== false) { $sun = '1'; } if (strpos($nsun, 'Monday') !== false) { $mon = '1'; } } if($time['mon'] == '1') { $cmon = new DateTime('Monday ' . $time['ut'], $from_tz_obj); $cmon->setTimezone($to_tz_obj); $nmon = $cmon->format('l Hi'); if (strpos($nmon, 'Sunday') !== false) { $sun = '1'; } if (strpos($nmon, 'Monday') !== false) { $mon = '1'; } if (strpos($nmon, 'Tuesday') !== false) { $tue = '1'; } } if($time['tue'] == '1') { $ctue = new DateTime('Tuesday ' . $time['ut'], $from_tz_obj); $ctue->setTimezone($to_tz_obj); $ntue = $ctue->format('l Hi'); if (strpos($ntue, 'Monday') !== false) { $mon = '1'; } if (strpos($ntue, 'Tuesday') !== false) { $tue = '1'; } if (strpos($ntue, 'Wednesday') !== false) { $wed = '1'; } } if($time['wed'] == '1') { $cwed = new DateTime('Wednesday ' . $time['ut'], $from_tz_obj); $cwed->setTimezone($to_tz_obj); $nwed = $cwed->format('l Hi'); if (strpos($nwed, 'Tuesday') !== false) { $tue = '1'; } if (strpos($nwed, 'Wednesday') !== false) { $wed = '1'; } if (strpos($nwed, 'Thursday') !== false) { $thu = '1'; } } if($time['thu'] == '1') { $cthu = new DateTime('Thursday ' . $time['ut'], $from_tz_obj); $cthu->setTimezone($to_tz_obj); $nthu = $cthu->format('l Hi'); if (strpos($nthu, 'Wednesday') !== false) { $wed = '1'; } if (strpos($nthu, 'Thursday') !== false) { $thu = '1'; } if (strpos($nthu, 'Friday') !== false) { $fri = '1'; } } if($time['fri'] == '1') { $cfri = new DateTime('Friday ' . $time['ut'], $from_tz_obj); $cfri->setTimezone($to_tz_obj); $nfri = $cfri->format('l Hi'); if (strpos($nfri, 'Thursday') !== false) { $thu = '1'; } if (strpos($nfri, 'Friday') !== false) { $fri = '1'; } if (strpos($nfri, 'Saturday') !== false) { $sat = '1'; } } if($time['sat'] == '1') { $csat = new DateTime('Saturday ' . $time['ut'], $from_tz_obj); $csat->setTimezone($to_tz_obj); $nsat = $csat->format('l Hi'); if (strpos($nsat, 'Friday') !== false) { $fri = '1'; } if (strpos($nsat, 'Saturday') !== false) { $sat = '1'; } if (strpos($nsat, 'Sunday') !== false) { $sun = '1'; } } return array($ct, $sun, $mon, $tue, $wed, $thu, $fri, $sat); } function convert_day($tz, $day, $mtg_time) { $user_tz = new DateTimeZone($tz); if($sun != '0') { $pt = new DateTime('Sunday ' . $mtg_time); $pt->setTimezone($user_tz); $ptc = $pt->format('l g:i A'); if (strpos($ptc, 'Sunday') !== false) { $utc_day = '1'; return $utc_day; } else { $utc_day = '0'; return $utc_day; } } } function find_offset($float) { $hours = floor($float); $minutes = ($float - $hours) * 60; return sprintf("%+02d:%02d", $hours, $minutes); } function u($string="") { return urlencode($string); } function h($string="") { return htmlspecialchars($string); } function is_post_request() { return $_SERVER['REQUEST_METHOD'] == 'POST'; } function is_get_request() { return $_SERVER['REQUEST_METHOD'] == 'GET'; } function display_errors($errors=array()) { $output = ''; if(!empty($errors)) { $output .= "<div class=\"errors\">"; $output .= "Please fix the following errors:"; $output .= "<ul>"; if (isset($errors['name_link1']) || isset($errors['name_link2']) || isset($errors['name_link3']) || isset($errors['name_link4'])) { $output .= "<li class=\"foobgar\">NOTE: I can't retain your file selections if there are errors. Every time there is <em>any</em> error you need to reselect the files you want to upload.</li>"; } foreach($errors as $error) { $output .= "<li>" . h($error) . "</li>"; } $output .= "</ul>"; $output .= "</div>"; } return $output; } ?><file_sep>/_includes/review-details.php <div class="meeting-details"> <?php if ($row['dedicated_om'] == 0 && $row['meet_phone'] == null && $row['meet_id'] == 0 && $row['meet_pswd'] == null && $row['meet_url'] == null) { } else { ?> <div class="details-left"> <?php /* if ($row['dedicated_om'] != 0) { ?><p class="dd-meet">Dedicated Online Meeting</p> } */ ?> <?php if ($row['meet_phone'] != null) { ?> <p class="phone-num01"><i class="fas fa-mobile-alt"></i> <a class="phone" href="tel:<?= "(" .substr($row['meet_phone'], 0, 3).") ".substr($row['meet_phone'], 3, 3)."-".substr($row['meet_phone'],6); ?>"><?= "(" .substr($row['meet_phone'], 0, 3).") ".substr($row['meet_phone'], 3, 3)."-".substr($row['meet_phone'],6); ?></a></p><?php } ?> <?php if ($row['meet_url'] != null) { ?> <p class="zoom-info">Zoom Information</p> <?php } ?> <?php if ($row['meet_id'] != '') { ?> <p class="id-num">ID: <input type="text" value="<?= h($row['meet_id']); ?>" class="day-values input-copy" onclick="select();"></p> <button type="submit" class="zoom-id btn"><i class="far fa-arrow-alt-circle-up"></i> Copy ID</button> <?php } ?> <?php if ($row['meet_pswd'] != null) { ?> <p class="id-num">Password: <input type="text" value="<?= h($row['meet_pswd']); ?>" class="day-values input-copyz" onclick="select();"></p> <button type="submit" class="zoom-id btnz"><i class="far fa-arrow-alt-circle-up"></i> Copy Password</button> <?php } ?> <?php if ($row['meet_url'] != null) { ?> <p><a href="<?= h($row['meet_url']); ?>" class="zoom" target="_blank">JOIN ZOOM: VIDEO</a></p> <?php } ?> </div><!-- .details-left --> <?php } ?> <div class="details-right" <?php if ($row['dedicated_om'] == 0 && $row['meet_phone'] == null && $row['meet_id'] == 0 && $row['meet_pswd'] == null && $row['meet_url'] == null) { echo "style=\"width:100%;\""; } ?>> <?php if ($row['meet_addr'] != null) { ?> <div id="map"> <iframe width="100%" height="180" style="border:0" loading="lazy" allowfullscreen src="https://www.google.com/maps/embed/v1/place?key=<?= MAP_KEY ?> &q=<?= preg_replace( "/\r|\n/", " ", h($row['meet_addr'])); ?>"> </iframe> </div> <?php if (($row['meet_addr'] != null) && ($row['meet_desc'] != null)) { ?> <p style="text-align:center;margin-bottom:1em;"><?= nl2br($row['meet_desc']); ?></p> <?php } else { ?> <p style="text-align:center;margin-bottom:1em;"><?= nl2br($row['meet_addr']); ?></p> <?php } ?> <a class="map-dir" href="https://maps.apple.com/?q=<?= preg_replace( "/\r|\n/", " ", h($row['meet_addr'])); ?>" target="_blank">Directions</a> <?php } ?> <p class="add-info">Additional Information</p> <ul> <?php if ($row['dedicated_om'] != 0) { ?> <li>Dedicated Online Meeting</li> <?php } if ($row['code_o'] != 0) { ?> <li>Open Meeting: Anyone may attend</li> <?php } if ($row['code_w'] != 0) { ?> <li>Women's Meeting</li> <?php } if ($row['code_m'] != 0) { ?> <li>Men's Meeting</li> <?php } if ($row['code_c'] != 0) { ?> <li>Closed Meeting</li> <?php } if ($row['code_beg'] != 0) { ?> <li>Beginner's Meeting</li> <?php } if ($row['code_h'] != 0) { ?> <li>Handicap Accessible</li> <?php } if ($row['code_d'] != 0) { ?> <li>Discussion</li> <?php } if ($row['code_b'] != 0) { ?> <li>Book Study</li> <?php } if ($row['code_ss'] != 0) { ?> <li>Step Study: We discuss the 12 steps</li> <?php } if ($row['code_sp'] != 0) { ?> <li>Speaker Meeting</li> <?php } if ($row['month_speaker'] != 0) { ?> <li>Speaker Meeting on last Sunday of month</li> <?php } if ($row['potluck'] != 0) { ?> <li>Potluck</li> <?php } ?> </ul> </div><!-- .details-right --> <?php if ($row['link1'] != '' || $row['link2'] != '' || $row['link3'] != '' || $row['link4'] != '') { ?> <div id="upload-links"> <?php if ($row['link1'] != '') { ?><a href="<?= WWW_ROOT ?>/uploads/<?= h(($row['file1'])) ?>" class="mtg-links" target="_blank"><?= h(($row['link1'])) ?></a><?php } ?> <?php if ($row['link2'] != '') { ?><a href="<?= WWW_ROOT ?>/uploads/<?= h(($row['file2'])) ?>" class="mtg-links" target="_blank"><?= h(($row['link2'])) ?></a><?php } ?> <?php if ($row['link3'] != '') { ?><a href="<?= WWW_ROOT ?>/uploads/<?= h(($row['file3'])) ?>" class="mtg-links" target="_blank"><?= h(($row['link3'])) ?></a><?php } ?> <?php if ($row['link4'] != '') { ?><a href="<?= WWW_ROOT ?>/uploads/<?= h(($row['file4'])) ?>" class="mtg-links" target="_blank"><?= h(($row['link4'])) ?></a><?php } ?> </div> <?php } ?> <?php if ($row['add_note'] != null) { ?><div id="add-note"><p><?= nl2br(h($row['add_note'])) ?></p></div><?php } ?> </div><!-- .meeting-details --><file_sep>/_includes/edit-details.php <div class="meeting-details"> <p class="mtg-tz">Your current timezone is set to: <a id="show-tz" class="inline-show-tz"><?php pretty_tz($tz); ?></a>.</p> <form id="manage-mtg" action="" method="post" enctype="multipart/form-data"> <input type="hidden" name="visible" value="<?= $row['visible']; ?>"> <div class="top-info"> <p class="days-held">Group name</p> <input type="text" class="mtg-update group-name<?php if (isset($errors['group_name'])) { echo " fixerror"; } ?>" name="group_name" value="<?php if (isset($_POST['group_name'])) { echo $_POST['group_name']; } else { echo $row['group_name']; } ?>" placeholder="Group name"> <p class="days-held">Day(s) meeting is held</p> <div class="align-days<?php if (isset($errors['pick_a_day'])) { echo " fixerror"; } ?>"> <div> <input type="hidden" name="sun" value="0"> <label><input type="checkbox" name="sun" value="1" <?php if (isset($_POST['sun']) && $_POST['sun'] != 0) { echo "checked"; } else if (isset($_POST['sun']) && $_POST['sun'] == 0) { echo ""; } else if ($row['sun'] != 0) { echo "checked"; } ?> /> <span>Sunday</span></label> | </div> <div> <input type="hidden" name="mon" value="0"> <label><input type="checkbox" name="mon" value="1" <?php if (isset($_POST['mon']) && $_POST['mon'] != 0) { echo "checked"; } else if (isset($_POST['mon']) && $_POST['mon'] == 0) { echo ""; } else if ($row['mon'] != 0) { echo "checked"; } ?> /> <span>Monday</span></label> | </div> <div> <input type="hidden" name="tue" value="0"> <label><input type="checkbox" name="tue" value="1" <?php if (isset($_POST['tue']) && $_POST['tue'] != 0) { echo "checked"; } else if (isset($_POST['tue']) && $_POST['tue'] == 0) { echo ""; } else if ($row['tue'] != 0) { echo "checked"; } ?> /> <span>Tuesday</span></label> | </div> <div> <input type="hidden" name="wed" value="0"> <label><input type="checkbox" name="wed" value="1" <?php if (isset($_POST['wed']) && $_POST['wed'] != 0) { echo "checked"; } else if (isset($_POST['wed']) && $_POST['wed'] == 0) { echo ""; } else if ($row['wed'] != 0) { echo "checked"; } ?> /> <span>Wednesday</span></label> | </div> <div> <input type="hidden" name="thu" value="0"> <label><input type="checkbox" name="thu" value="1" <?php if (isset($_POST['thu']) && $_POST['thu'] != 0) { echo "checked"; } else if (isset($_POST['thu']) && $_POST['thu'] == 0) { echo ""; } else if ($row['thu'] != 0) { echo "checked"; } ?> /> <span>Thursday</span></label> | </div> <div> <input type="hidden" name="fri" value="0"> <label><input type="checkbox" name="fri" value="1" <?php if (isset($_POST['fri']) && $_POST['fri'] != 0) { echo "checked"; } else if (isset($_POST['fri']) && $_POST['fri'] == 0) { echo ""; } else if ($row['fri'] != 0) { echo "checked"; } ?> /> <span>Friday</span></label> | </div> <div> <input type="hidden" name="sat" value="0"> <label><input type="checkbox" name="sat" value="1" <?php if (isset($_POST['sat']) && $_POST['sat'] != 0) { echo "checked"; } else if (isset($_POST['sat']) && $_POST['sat'] == 0) { echo ""; } else if ($row['sat'] != 0) { echo "checked"; } ?> /> <span>Saturday</span></label> </div> </div><!-- .align-days --> <p class="time-held">Time</p> <div class="mtg-time"> <?php /* https://timepicker.co/options/ */ ?> <input name="meet_time" class="timepicker<?php if (isset($errors['meet_time'])) { echo " fixerror"; } ?>" value="<?php if (isset($_POST['meet_time'])) { echo date('g:i A', strtotime($_POST['meet_time'])); } else { $time = $row['meet_time']; $nt = converted_time($time, $tz); echo $nt; } ?>"> </div> </div><!-- .top-info --> <div class="details-left <?php if ($row['meet_url'] != null) { echo "l-stacked"; } ?>"> <label for="meet_phone">Phone number</label> <input type="text" class="mtg-update<?php if (isset($errors['meet_phone'])) { echo " fixerror"; } ?>" name="meet_phone" <?php if (isset($_POST['meet_phone'])) { $postphone = preg_replace('/[^0-9]/', '', $_POST['meet_phone']); } if ( isset($_POST['meet_phone']) && $postphone != '' ) { echo "value=\"(" .substr($postphone, 0, 3).") ".substr($postphone, 3, 3)."-".substr($postphone, 6)."\""; } else if (isset($_POST['meet_phone']) && $_POST['meet_phone'] == '') { echo "value=\"\""; } else if (!empty($row['meet_phone'])) { echo "(" .substr(h($row['meet_phone']), 0, 3).") ".substr(h($row['meet_phone']), 3, 3)."-".substr(h($row['meet_phone']),6); } else { } ?> placeholder="10-digit phone #"> <label for="one_tap">One Tap Mobile <a id="toggle-one-tap-msg"><i class="far fa-question-circle fa-fw"></i></a></label><?php // #toggle-one-tap-msg is inside lat-long-instructions.php ?> <input type="text" class="mtg-update<?php if (isset($errors['one_tap'])) { echo " fixerror"; } ?>" name="one_tap" value="<?php if (isset($row['one_tap'])) { echo h($row['one_tap']); } ?>" placeholder="One Tap Mobile #"> <label for="meet_id">ID number</label> <input type="text" class="mtg-update<?php if (isset($errors['meet_id'])) { echo " fixerror"; } ?>" name="meet_id" value="<?php if (isset($_POST['meet_id'])) { echo $_POST['meet_id']; } else { echo $row['meet_id']; } ?>" placeholder="ID Number"> <label for="meet_pswd">Password</label> <input type="text" class="mtg-update<?php if (isset($errors['meet_pswd'])) { echo " fixerror"; } ?>" name="meet_pswd" value="<?php if (isset($_POST['meet_pswd'])) { echo $_POST['meet_pswd']; } else { echo $row['meet_pswd']; } ?>" placeholder="<PASSWORD>"> <label for="meet_url">Meeting URL</label> <textarea name="meet_url" id="meet_url" class="<?php if (isset($errors['meet_url']) || isset($errors['url_or_phy'])) { echo " fixerror"; } ?>" placeholder="https://zoom-address-here/"><?php if (isset($_POST['meet_url'])) { echo $_POST['meet_url']; } else { echo $row['meet_url']; } ?></textarea> <label for="meet_addr">Physical Address | lat°, long° accepted <a id="toggle-lat-long-msg"><i class="far fa-question-circle fa-fw"></i></a></label> <textarea name="meet_addr" id="meet_addr" class="<?php if (isset($errors['meet_url']) || isset($errors['meet_addr'])) { echo " fixerror"; } ?>" placeholder="123 Main St, Evergreen, CO"><?php if (isset($_POST['meet_addr'])) { echo $_POST['meet_addr']; } else { echo $row['meet_addr']; } ?></textarea> <label for="meet_desc">Descriptive Location <a id="toggle-descriptive-location"><i class="far fa-question-circle fa-fw"></i></a></label> <textarea name="meet_desc" id="meet_desc" placeholder="123 Main St.&#10;Evergreen, CO&#10;Around back, 2nd floor"><?php if (isset($_POST['meet_desc'])) { echo $_POST['meet_desc']; } else { echo $row['meet_desc']; } ?></textarea> </div><!-- .details-left --> <div class="details-right<?php if (isset($errors['meeting_type']) || isset($errors['url_or_phy'])) { echo " fixerror"; } ?><?php if ($row['meet_url'] != null) { echo " rt-stacked"; } ?>"> <p class="add-info<?php if (isset($errors['meeting_type']) || isset($errors['url_or_phy'])) { echo " fixerror"; } ?>">Select all that apply</p> <input type="hidden" name="dedicated_om" value="0"> <label><input type="checkbox" name="dedicated_om" <?php if (isset($_POST['dedicated_om']) && $_POST['dedicated_om'] != 0) { echo "checked"; } else if (isset($_POST['dedicated_om']) && $_POST['dedicated_om'] == 0) { } else if ($row['dedicated_om'] == "1") { echo "checked"; } ?> value="1" /> <span>Dedicated Online Meeting</span></label> <input type="hidden" name="code_o" value="0"> <label><input type="checkbox" name="code_o" class="omw oc" <?php if (isset($_POST['code_o']) && $_POST['code_o'] != 0) { echo "checked"; } else if (isset($_POST['code_o']) && $_POST['code_o'] == 0) { } else if ($row['code_o'] == "1") { echo "checked"; } ?> value="1" /> <span>Open: Anyone may attend</span></label> <input type="hidden" name="code_w" value="0"> <label><input type="checkbox" name="code_w" class="omw" <?php if (isset($_POST['code_w']) && $_POST['code_w'] != 0) { echo "checked"; } else if (isset($_POST['code_w']) && $_POST['code_w'] == 0) { } else if ($row['code_w'] == "1") { echo "checked"; } ?> value="1" /> <span>Women's Meeting</span></label> <input type="hidden" name="code_m" value="0"> <label><input type="checkbox" name="code_m" class="omw" <?php if (isset($_POST['code_m']) && $_POST['code_m'] != 0) { echo "checked"; } else if (isset($_POST['code_m']) && $_POST['code_m'] == 0) { } else if ($row['code_m'] == "1") { echo "checked"; } ?> value="1" /> <span>Men's Meeting</span></label> <input type="hidden" name="code_c" value="0"> <label><input type="checkbox" name="code_c" class="oc" <?php if (isset($_POST['code_c']) && $_POST['code_c'] != 0) { echo "checked"; } else if (isset($_POST['code_c']) && $_POST['code_c'] == 0) { } else if ($row['code_c'] == "1") { echo "checked"; } ?> value="1" /> <span>Closed Meeting</span></label> <input type="hidden" name="code_beg" value="0"> <label><input type="checkbox" name="code_beg" <?php if (isset($_POST['code_beg']) && $_POST['code_beg'] != 0) { echo "checked"; } else if (isset($_POST['code_beg']) && $_POST['code_beg'] == 0) { } else if ($row['code_beg'] == "1") { echo "checked"; } ?> value="1" /> <span>Beginner's Meeting</span></label> <input type="hidden" name="code_h" value="0"> <label><input type="checkbox" name="code_h" <?php if (isset($_POST['code_h']) && $_POST['code_h'] != 0) { echo "checked"; } else if (isset($_POST['code_h']) && $_POST['code_h'] == 0) { } else if ($row['code_h'] == "1") { echo "checked"; } ?> value="1" /> <span>Handicap</span></label> <input type="hidden" name="code_d" value="0"> <label><input type="checkbox" name="code_d" <?php if (isset($_POST['code_d']) && $_POST['code_d'] != 0) { echo "checked"; } else if (isset($_POST['code_d']) && $_POST['code_d'] == 0) { } else if ($row['code_d'] == "1") { echo "checked"; } ?> value="1" /> <span>Discussion Meeting</span></label> <input type="hidden" name="code_b" value="0"> <label><input type="checkbox" name="code_b" <?php if (isset($_POST['code_b']) && $_POST['code_b'] != 0) { echo "checked"; } else if (isset($_POST['code_b']) && $_POST['code_b'] == 0) { } else if ($row['code_b'] == "1") { echo "checked"; } ?> value="1" /> <span>Book Study</span></label> <input type="hidden" name="code_ss" value="0"> <label><input type="checkbox" name="code_ss" <?php if (isset($_POST['code_ss']) && $_POST['code_ss'] != 0) { echo "checked"; } else if (isset($_POST['code_ss']) && $_POST['code_ss'] == 0) { } else if ($row['code_ss'] == "1") { echo "checked"; } ?> value="1" /> <span>Step Study</span></label> <input type="hidden" name="code_sp" value="0"> <label><input type="checkbox" name="code_sp" <?php if (isset($_POST['code_sp']) && $_POST['code_sp'] != 0) { echo "checked"; } else if (isset($_POST['code_sp']) && $_POST['code_sp'] == 0) { } else if ($row['code_sp'] == "1") { echo "checked"; } ?> value="1" /> <span>Speaker Meeting</span></label> <input type="hidden" name="month_speaker" value="0"> <label><input type="checkbox" name="month_speaker" <?php if (isset($_POST['month_speaker']) && $_POST['month_speaker'] != 0) { echo "checked"; } else if (isset($_POST['month_speaker']) && $_POST['month_speaker'] == 0) { } else if ($row['month_speaker'] == "1") { echo "checked"; } ?> value="1" /> <span>Speaker Meeting on last Sunday of month</span></label> <input type="hidden" name="potluck" value="0"> <label><input type="checkbox" name="potluck" <?php if (isset($_POST['potluck']) && $_POST['potluck'] != 0) { echo "checked"; } else if (isset($_POST['potluck']) && $_POST['potluck'] == 0) { } else if ($row['potluck'] == "1") { echo "checked"; } ?> value="1" /> <span>Potluck</span></label> </div><!-- .details-right --> <div class="btm-notes"> <div class="file-uploads"> <p>Upload PDF Files <a id="toggle-pdf-info"><i class="far fa-question-circle fa-fw"></i></a></p> <div id="pdf1" class="pdf-wrap pdf1<?php if (isset($errors['name_link1'])) { echo " fixerror"; } ?>"> <div class="pdf-row"> <input type="hidden" id="hid-f1" name="hid_f1" value="<?php if(isset($_POST['hid_f1'])) { echo $_POST['hid_f1']; } else { echo $row['file1']; } ?>"> <input type="file" class="pdf1_name pdf-count" id="file1" name="file1" accept=".pdf"> <label class="pdf-label">Link 1 label <input type="text" class="pdf1_name" name="link1" value="<?php if (isset($_POST['link1'])) { echo trim(h($_POST['link1'])); } else { echo trim(h($row['link1'])); } ?>" maxlength="25"> <a id="toggle-link-label"><i class="far fa-question-circle fa-fw"></i></a></label> </div> <div class="pdf-remove"> <a class="pdf-remove pdf-remove-1">Remove</a> </div> </div> <div id="pdf2" class="pdf-wrap pdf2<?php if (isset($errors['name_link2'])) { echo " fixerror"; } ?>"> <div class="pdf-row"> <input type="hidden" id="hid-f2" name="hid_f2" value="<?php if(isset($_POST['hid_f2'])) { echo $_POST['hid_f2']; } else { echo $row['file2']; } ?>"> <input type="file" class="pdf2_name pdf-count" id="file2" name="file2" accept=".pdf"> <label class="pdf-label">Link 2 label <input type="text" class="pdf2_name" name="link2" value="<?php if (isset($_POST['link2'])) { echo trim(h($_POST['link2'])); } else { echo trim(h($row['link2'])); } ?>" maxlength="25"></label> </div> <div class="pdf-remove"> <a class="pdf-remove pdf-remove-2">Remove</a> </div> </div> <div id="pdf3" class="pdf-wrap pdf3<?php if (isset($errors['name_link3'])) { echo " fixerror"; } ?>"> <div class="pdf-row"> <input type="hidden" id="hid-f3" name="hid_f3" value="<?php if(isset($_POST['hid_f3'])) { echo $_POST['hid_f3']; } else { echo $row['file3']; } ?>"> <input type="file" class="pdf3_name pdf-count" id="file3" name="file3" accept=".pdf"> <label class="pdf-label">Link 3 label <input type="text" class="pdf3_name" name="link3" value="<?php if (isset($_POST['link3'])) { echo trim(h($_POST['link3'])); } else { echo trim(h($row['link3'])); } ?>" maxlength="25"></label> </div> <div class="pdf-remove"> <a class="pdf-remove pdf-remove-3">Remove</a> </div> </div> <div id="pdf4" class="pdf-wrap pdf4<?php if (isset($errors['name_link4'])) { echo " fixerror"; } ?>"> <div class="pdf-row"> <input type="hidden" id="hid-f4" name="hid_f4" value="<?php if(isset($_POST['hid_f4'])) { echo $_POST['hid_f4']; } else { echo $row['file4']; } ?>"> <input type="file" class="pdf4_name pdf-count" id="file4" name="file4" accept=".pdf"> <label class="pdf-label">Link 4 label <input type="text" class="pdf4_name" name="link4" value="<?php if (isset($_POST['link4'])) { echo trim(h($_POST['link4'])); } else { echo trim(h($row['link4'])); } ?>" maxlength="25"></label> </div> <div class="pdf-remove"> <a class="pdf-remove pdf-remove-4">Remove</a> </div> </div> <a id="file-upload"><i class="far fa-plus-square fa-fw"></i> Add a PDF | 4 Total</a> </div> <label for="add_note">Additional notes</label> <textarea name="add_note" class="meetNotes<?php if (isset($errors['add_note'])) { echo " fixerror"; } ?>" placeholder="Text only. 255 characters or less. All formatting will be stripped."><?php if (isset($_POST['add_note'])) { echo h($_POST['add_note']); } else { echo h($row['add_note']); } ?></textarea> <div class="visible"> <h1><i class="fas fa-users" style="margin-right:1em;"></i> Select your audience</h1> <div class="radio-group"> <div class='radio<?php if (isset($_POST['visible']) && (($_POST['visible'] != $row['visible']) && $_POST['visible'] == "0")) { echo " selected"; } else if (isset($_POST['visible']) && (($_POST['visible'] != $row['visible']) && $_POST['visible'] != "0")) { echo ""; } else if ($row['visible'] == "0") { echo " selected"; } ?>' value="0"> Draft | Save for later. </div> <div class='radio<?php if (isset($_POST['visible']) && (($_POST['visible'] != $row['visible']) && $_POST['visible'] == "1")) { echo " selected"; } else if (isset($_POST['visible']) && (($_POST['visible'] != $row['visible']) && $_POST['visible'] != "1")) { echo ""; } else if ($row['visible'] == "1") { echo " selected"; } ?>' value="1"> Private | Only you will see this. </div> <div class='radio<?php if (isset($_POST['visible']) && (($_POST['visible'] != $row['visible']) && $_POST['visible'] == "2")) { echo " selected"; } else if (isset($_POST['visible']) && (($_POST['visible'] != $row['visible']) && $_POST['visible'] != "2")) { echo ""; } else if ($row['visible'] == "2") { echo " selected"; } ?>' value="2"> Members Only | Only members of EvergreenAA.com.</div> <div class='radio<?php if (isset($_POST['visible']) && (($_POST['visible'] != $row['visible']) && $_POST['visible'] == "3")) { echo " selected"; } else if (isset($_POST['visible']) && (($_POST['visible'] != $row['visible']) && $_POST['visible'] != "3")) { echo ""; } else if ($row['visible'] == "3") { echo " selected"; } ?>' value="3"> Public | Share with everyone. No membership required. </div> <?php /* grab value and put it into hidden field to submit this is also in _includes/manage_new_review */ ?> <input type="hidden" name="visible" value="<?php if (isset($_POST['visible'])) { if ($_POST['visible'] == "0") { echo "0"; } // Draft if ($_POST['visible'] == "1") { echo "1"; } // Private if ($_POST['visible'] == "2") { echo "2"; } // Members Only if ($_POST['visible'] == "3") { echo "3"; } // Public } else { if ($row['visible'] == "0") { echo "0"; } // Draft if ($row['visible'] == "1") { echo "1"; } // Private if ($row['visible'] == "2") { echo "2"; } // Members Only if ($row['visible'] == "3") { echo "3"; } // Public } ?>" /> </div> </div><!-- .visible --> <div class="update-rt"> <a class="cancel" href="manage.php">CANCEL</a> <input type="submit" id="update-mtg" name="update-mtg" class="submit" value="UPDATE"> </div><!-- .update-rt --> </div><!-- .btm-notes --> </form> </div><!-- .meeting-details --> <file_sep>/post.php <?php require_once 'config/initialize.php'; // require_once 'config/verify_admin.php'; $layout_context = 'post-page'; if (isset($_SESSION['id'])) { $user_id = $_SESSION['id']; $user_role = $_SESSION['admin']; $user_posting = $_SESSION['username']; } else { $user_id = ''; $user_role = ''; $user_posting = ''; } require '_includes/head.php'; ?> <body> <?php if (WWW_ROOT != 'http://localhost/evergreenaa') { ?> <div class="preload"> <p>One day at a time.</p> </div> <?php } ?> <?php require '_includes/nav.php'; ?> <?php require '_includes/msg-set-timezone.php'; ?> <?php require '_includes/msg-why-join.php'; ?> <?php require '_includes/msg-extras.php'; ?> <?php require '_includes/msg-role-key.php'; ?> <img class="background-image" src="_images/message-board-mobile.jpg" alt="AA Logo"> <div id="wrap"> <?php if (isset($_GET['post-id'])) { $post = $_GET['post-id']; } else { $post = '0'; } $get_post = get_this_post($post); $results = mysqli_num_rows($get_post); $row = mysqli_fetch_assoc($get_post); ?> <?php if ($results > 0) { ?> <div id="mb-wrap"> <h1>Single Post</h1> <div class="new-topic"> <a href="message-board.php" class="bkpg"><i class="fas fa-backward"></i> Back</a> </div> <div class="post-content"> <input type="hidden" id="gtg" value="gtg"> <div class="pt-wrap"> <p class="mp-date"><?= date('g:i A D, M d, \'y', strtotime($row['opened'])+3600) ?> | <?= substr($row['username'], 0, 1) . '... ' ?> Posted:</p> <?php /* begin delete icon */ ?> <?php if (isset($_SESSION['id']) && ($_SESSION['id'] == $row['idt_user'] || ($_SESSION['mode'] == 1 && ($_SESSION['admin'] == 1 || $_SESSION['admin'] == 2 || $_SESSION['admin'] == 3)))) { ?> <form id="delete-post"> <input type="hidden" name="post-id" value="<?= $row['idt_topic'] ?>"> <input type="hidden" name="uid" value="<?= $row['idt_user'] ?>"> <input type="hidden" id="ybcwpb"> <?php if ($_SESSION['id'] == $row['idt_user']) { ?> <a data-id="delete-post" data-role="delete-post" class="manage-delete-mb"><div class="tooltip right"><span class="tooltiptext">Delete your Post</span><i class="far fas fa-minus-circle"></i></div></a> <?php } else if ($_SESSION['admin'] != 1 && ($row['admin'] == 1 || $row['admin'] == 3)) { ?> <a class="gtp my-stuff"><div class="tooltip right"><span class="tooltiptext">Admin Off Limits</span><i class="far fas fa-minus-circle"></i></div></a> <?php } else { ?> <a data-id="delete-post" data-role="delete-post" class="manage-delete-mb"><div class="tooltip right"><span class="tooltiptext">Delete their Post</span><i class="far fas fa-minus-circle"></i></div></a> <?php } ?> </form> <?php } ?> <?php /* end delete icon */ ?> </div><!-- .pt-wrap --> <?php if (isset($_SESSION['id']) && ($_SESSION['mode'] == 1 && ($_SESSION['admin'] == 1 || $_SESSION['admin'] == 3))) { // admin view of username + email ?> <?php if ($_SESSION['id'] == $row['idt_user']) { ?> <p class="admin-mp-info">This is your post</p> <?php } else if ($_SESSION['admin'] != 1 && ($row['admin'] == 1 || $row['admin'] == 3)) { // remember, there's only 1 ($row['admin'] = 1) ?> <p class="admin-mp-info">Admin (off limits)</p> <?php } else { ?> <a class="admin-mp-info gtp" href="user_role.php?user=<?= h(u($row['idt_user'])); ?>"><div class="tooltip"><span class="tooltiptext">Manage User</span><?= $row['username'] . ' &bullet; ' . $row['email'] ?></div></a> <?php } ?> <?php } ?> <p class="mp-title"><?= $row['mb_header'] ?></p> <p class="mb-body"><?= nl2br($row['mb_body']) ?></p> <?php mysqli_free_result($get_post); ?> </div> <div class="replies"> <ul id="replies"><?php /* magic */ ?></ul> </div> <!-- <div class="mb-reply"> <a id="toggle-post-reply" class="post-a-reply">Reply</a> </div> --> <?php if (isset($_SESSION['id'])) { ?> <div id="reply-spot"> <div id="post-error"></div> <form id="post-reply" action="" method="post"> <textarea id="mb-replyz" name="mb-reply" class="mb-reply" placeholder="Enter your reply here."></textarea> <input type="hidden" name="post-id" value="<?= $row['idt_topic'] ?>"> <input type="hidden" id="user-posting" value="<?= $user_posting ?>"> <a id="reply">Post your reply</a> </form> </div> <?php } else { ?> <div id="reply-spot" class="post-visitor"> <p>You need to be logged in to participate.</p> <div class="login-links"> <a href="login.php">Login</a> <a href="signup.php">Signup</a> </div> </div> <?php } ?> </div><!-- #mb-wrap --> <?php } else { ?> <div class="post-deleted"> <div class="pd-msg"> <h2>Nothin' to see here</h2> <p>Whatever used to be here isn't any longer or if there wasn't anything here it still isn't.</p> <div class="login-links"> <a href="message-board.php">Back to<br>Message Board</a> </div> </div> </div> <?php } ?> </div><!-- #wrap --> <script> // $("#reply-spot").hide(); $(document).ready(function() { var q = window.location.search; $('#replies').load('load-posts.php'+q); setInterval(function() { $('#replies').load('load-posts.php'+q); }, 3000); // user has clicked "Post reply" $(document).on('click','#reply', function() { if ($('#ngtg').length == 0) { var username = $('#user-posting').val().charAt(0); var reply = $('#mb-replyz').val().trim(); var empty = ''; if (reply == '') { $('#post-error').html('<p class="post-error">You can\'t submit an empty reply.</p>'); return; } // event.preventDefault(); $.ajax({ dataType: "JSON", url: "process-mb.php", type: "POST", data: $('#post-reply').serialize(), beforeSend: function(xhr) { // $('#emh-contact-msg').html('<span class="sending-msg">Posting - one moment...</span>'); }, success: function(response) { // console.log(response); if(response) { console.log(response); if(response['signal'] == 'ok') { // $('#toggle-post-reply').removeClass('active'); // $('#reply-spot').slideToggle(); $('#mb-replyz').val(empty); $('#replies').append('<li><p class="mb-date">Just now | '+username+'... Posted:</p><p class="mb-body">'+reply+'</p></li>'); $('#post-error').html(''); } else { $('#emh-contact-msg').html('<div class="alert alert-warning">' + response['msg'] + '</div>'); } } }, error: function() { $('#emh-contact-msg').html('<div class="alert alert-warning">There was an error between your IP and the server. Please try again later.</div>'); }, complete: function() { } }) } else { location.reload(); } }); $(document).on('click', 'a[data-role=delete-reply]', function() { var id = $(this).data('id'); var li_id = id.substring(id.indexOf('_') + 1); $.ajax({ dataType: "JSON", url: "process-delete-mb-reply.php", type: "POST", data: $('#'+id).serialize(), beforeSend: function(xhr) { // $('#emh-contact-msg').html('<span class="sending-msg">Posting - one moment...</span>'); }, success: function(response) { // console.log(response); if(response) { console.log(response); if(response['signal'] == 'ok') { $('#li_'+li_id).remove(); } else { //$('#li_'+id).html('<div class="alert alert-warning">' + response['msg'] + '</div>'); } } }, error: function() { $('#emh-contact-msg').html('<div class="alert alert-warning">There was an error between your IP and the server. Please try again later.</div>'); }, complete: function() { } }) }); }); </script> <?php require '_includes/footer.php'; ?> <file_sep>/process-mb.php <?php require_once 'config/initialize.php'; require_once 'config/verify_admin.php'; if (is_post_request()) { if (isset($_POST['mb-title'])) { // this is a new post $row = []; $row['id_user'] = $_SESSION['id']; $row['mb_header'] = h($_POST['mb-title']); $row['mb_body'] = h($_POST['mb-post']); $result = add_new_post($row); if ($result === true) { $signal = 'ok'; $msg = 'Transfer successful!'; } else { $signal = 'bad'; $msg = 'That didn\'t work. I\'ve got no more information for you either. Maybe restart your browser and try it again?'; } } // end new post if (isset($_POST['mb-reply'])) { // this is a reply $row = []; $row['id_user'] = $_SESSION['id']; $row['mb_topic'] = h($_POST['post-id']); $row['mb_reply'] = h($_POST['mb-reply']); $result = add_mb_reply($row); if ($result === true) { $signal = 'ok'; $msg = 'Transfer successful!'; } else { $signal = 'bad'; $msg = 'That didn\'t work. I\'ve got no more information for you either. Maybe restart your browser and try it again?'; } } // end reply } $data = array( 'signal' => $signal, 'msg' => $msg ); echo json_encode($data); // stop <file_sep>/datetime.php <?php date_default_timezone_set('America/Denver'); $script_tz = date_default_timezone_get(); if (strcmp($script_tz, ini_get('date.timezone'))){ echo 'Script timezone differs from ini-set timezone.'; } else { echo 'Script timezone and ini-set timezone match.'; } ?><br><br><?php echo 'In the Mountain timezone it\'s ' . date(' l, F j, Y') . " at " . date('g:i A'); $meet_time = strtotime('g:i A'); echo date($meet_time); ?><file_sep>/home-ORIGINAL.php <?php $layout_context = "home-public"; require_once 'config/initialize.php'; if (isset($_SESSION['id'])) { $user_id = $_SESSION['id']; $user_role = $_SESSION['admin']; } else { $user_id = 'ns'; // not set (for footer modal: submitting issues) $user_role = '0'; } require '_includes/head.php'; ?> <body> <?php if (WWW_ROOT != 'http://localhost/evergreenaa') { ?> <div class="preload"> <p>One day at a time.</p> </div> <?php } ?> <?php require '_includes/nav.php'; ?> <?php require '_includes/msg-why-join.php'; ?> <?php require '_includes/msg-role-key.php'; ?> <img class="background-image" src="_images/aa-logo-dark_mobile.gif" alt="AA Logo"> <div id="wrap"> <ul id="weekdays"> <li class="ctr-day"> <button id="open-sunday" class="day">Sunday</button> <div id="sunday-content" class="day-content"> <?php include '_includes/collapse-day.php'; ?> <?php $subject_set = get_all_public_meetings_for_today($sunday); $result = mysqli_num_rows($subject_set); if ($result > 0) { $i = 1; while ($row = mysqli_fetch_assoc($subject_set)) { $ic = 'i0_'.$i; $pc = 'p0_'.$i; $today = 'Sunday'; if ($row['issues'] < 3) { require '_includes/daily-glance.php'; ?> <div class="weekday-wrap"> <?php require '_includes/meeting-details.php'; ?> </div><!-- .weekday-wrap --> <?php } $i++; } } else { ?> <p class="no-mtgs">No meetings posted for Sunday.</p> <?php } mysqli_free_result($subject_set); ?> </div><!-- #sunday-content .day-content --> </li> <li class="ctr-day"> <button id="open-monday" class="day">Monday</button> <div id="monday-content" class="day-content"> <?php include '_includes/collapse-day.php'; ?> <?php $subject_set = get_all_public_meetings_for_today($monday); $result = mysqli_num_rows($subject_set); if ($result > 0) { $i = 1; while ($row = mysqli_fetch_assoc($subject_set)) { $ic = 'i1_'.$i; $pc = 'p1_'.$i; $today = 'Monday'; if ($row['issues'] < 3) { require '_includes/daily-glance.php'; ?> <div class="weekday-wrap"> <?php require '_includes/meeting-details.php'; ?> </div><!-- .weekday-wrap --> <?php } $i++; } } else { ?> <p class="no-mtgs">No meetings posted for Monday.</p> <?php } mysqli_free_result($subject_set); ?> </div><!-- #monday-content .day-content --> </li> <li class="ctr-day"> <button id="open-tuesday" class="day">Tuesday</button> <div id="tuesday-content" class="day-content"> <?php include '_includes/collapse-day.php'; ?> <?php $subject_set = get_all_public_meetings_for_today($tuesday); $result = mysqli_num_rows($subject_set); if ($result > 0) { $i = 1; while ($row = mysqli_fetch_assoc($subject_set)) { $ic = 'i2_'.$i; $pc = 'p2_'.$i; $today = 'Tuesday'; if ($row['issues'] < 3) { require '_includes/daily-glance.php'; ?> <div class="weekday-wrap"> <?php require '_includes/meeting-details.php'; ?> </div><!-- .weekday-wrap --> <?php } $i++; } } else { ?> <p class="no-mtgs">No meetings posted for Tuesday.</p> <?php } mysqli_free_result($subject_set); ?> </div><!-- #tuesday-content .day-content --> </li> <li class="ctr-day"> <button id="open-wednesday" class="day">Wednesday</button> <div id="wednesday-content" class="day-content"> <?php include '_includes/collapse-day.php'; ?> <?php $subject_set = get_all_public_meetings_for_today($wednesday); $result = mysqli_num_rows($subject_set); if ($result > 0) { $i = 1; while ($row = mysqli_fetch_assoc($subject_set)) { $ic = 'i3_'.$i; $pc = 'p3_'.$i; $today = 'Wednesday'; if ($row['issues'] < 3) { require '_includes/daily-glance.php'; ?> <div class="weekday-wrap"> <?php require '_includes/meeting-details.php'; ?> </div><!-- .weekday-wrap --> <?php } $i++; } } else { ?> <p class="no-mtgs">No meetings posted for Wednesday.</p> <?php } mysqli_free_result($subject_set); ?> </div><!-- #wednesday-content .day-content --> </li> <li class="ctr-day"> <button id="open-thursday" class="day">Thursday</button> <div id="thursday-content" class="day-content"> <?php include '_includes/collapse-day.php'; ?> <?php $subject_set = get_all_public_meetings_for_today($thursday); $result = mysqli_num_rows($subject_set); if ($result > 0) { $i = 1; while ($row = mysqli_fetch_assoc($subject_set)) { $ic = 'i4_'.$i; $pc = 'p4_'.$i; $today = 'Thursday'; if ($row['issues'] < 3) { require '_includes/daily-glance.php'; ?> <div class="weekday-wrap"> <?php require '_includes/meeting-details.php'; ?> </div><!-- .weekday-wrap --> <?php } $i++; } } else { ?> <p class="no-mtgs">No meetings posted for Thursday.</p> <?php } mysqli_free_result($subject_set); ?> </div><!-- #thursday-content .day-content --> </li> <li class="ctr-day"> <button id="open-friday" class="day">Friday</button> <div id="friday-content" class="day-content"> <?php include '_includes/collapse-day.php'; ?> <?php $subject_set = get_all_public_meetings_for_today($friday); $result = mysqli_num_rows($subject_set); if ($result > 0) { $i = 1; while ($row = mysqli_fetch_assoc($subject_set)) { $ic = 'i5_'.$i; $pc = 'p5_'.$i; $today = 'Friday'; if ($row['issues'] < 3) { require '_includes/daily-glance.php'; ?> <div class="weekday-wrap"> <?php require '_includes/meeting-details.php'; ?> </div><!-- .weekday-wrap --> <?php } $i++; } } else { ?> <p class="no-mtgs">No meetings posted for Friday.</p> <?php } mysqli_free_result($subject_set); ?> </div><!-- #friday-content .day-content --> </li> <li class="ctr-day"> <button id="open-saturday" class="day">Saturday</button> <div id="saturday-content" class="day-content"> <?php include '_includes/collapse-day.php'; ?> <?php $subject_set = get_all_public_meetings_for_today($saturday); $result = mysqli_num_rows($subject_set); if ($result > 0) { $i = 1; while ($row = mysqli_fetch_assoc($subject_set)) { $ic = 'i6_'.$i; $pc = 'p6_'.$i; $today = 'Saturday'; if ($row['issues'] < 3) { require '_includes/daily-glance.php'; ?> <div class="weekday-wrap"> <?php require '_includes/meeting-details.php'; ?> </div><!-- .weekday-wrap --> <?php } $i++; } } else { ?> <p class="no-mtgs">No meetings posted for Saturday.</p> <?php } mysqli_free_result($subject_set); ?> </div><!-- #saturday-content .day-content --> </li> </ul><!-- #weekdays --> </div><!-- #wrap --> <?php require '_includes/footer.php'; ?><file_sep>/manage_edit_review.php <?php require_once 'config/initialize.php'; require_once 'config/verify_admin.php'; if ($_SESSION['admin'] == 85 || $_SESSION['admin'] == 86) { header('location: ' . WWW_ROOT); exit(); } if (!isset($_SESSION['id'])) { $_SESSION['message'] = "You need to be logged in to access that page."; $_SESSION['alert-class'] = "alert-danger"; header('location: ' . WWW_ROOT . '/login.php'); exit(); } if ((isset($_SESSION['id'])) && (!$_SESSION['verified'])) { header('location: ' . WWW_ROOT); exit(); } if (!isset($_GET['id'])) { header('location: ' . WWW_ROOT); } $layout_context = "alt-manage"; $id = $_GET['id']; $id_user = $_SESSION['id']; $role = $_SESSION['admin']; $row = edit_meeting($id); // get days sorted based on TZ $time = []; $time['tz'] = $tz; $time['ut'] = $row['meet_time']; $time['sun'] = $row['sun']; $time['mon'] = $row['mon']; $time['tue'] = $row['tue']; $time['wed'] = $row['wed']; $time['thu'] = $row['thu']; $time['fri'] = $row['fri']; $time['sat'] = $row['sat']; list($ct, $sun, $mon, $tue, $wed, $thu, $fri, $sat) = apply_offset_to_edit($time); $row['sun'] = $sun; $row['mon'] = $mon; $row['tue'] = $tue; $row['wed'] = $wed; $row['thu'] = $thu; $row['fri'] = $fri; $row['sat'] = $sat; require '_includes/head.php'; ?> <body> <?php if (WWW_ROOT != 'http://localhost/evergreenaa') { ?> <div class="preload"><p>One day at a time.</p></div> <?php } ?> <?php require '_includes/nav.php'; ?> <?php require '_includes/msg-set-timezone.php'; ?> <?php require '_includes/msg-extras.php'; ?> <?php require '_includes/msg-role-key.php'; ?> <img class="background-image" src="_images/aa-logo-dark_mobile.gif" alt="AA Logo"> <div id="manage-wrap"> <div class="confirm">TEST & CONFIRM!</div> <div class="manage-simple intro"> <?php if ($role != 1 && $role != 2) { ?> <p>Take a look. Is everything the way you want it? If not, click the <a class="manage-edit inline" href="manage_edit.php?id=<?= h(u($id)); ?>"><i class="far fa-edit"></i> edit button</a> and polish this sucker up! Or save it for later.</p> <?php } else if ($role == 1) { ?> <p>Hey Me,</p> <p>Quit talking to yourself.</p> <?php } else { ?> <p>Hey<?= ' ' . $_SESSION['username'] . ',' ?></p> <p>Make sure everything's just right.</p> <?php } ?> <?php require '_includes/inner_nav.php'; ?> </div> <div class="manage-simple review"> <h1>Quick view</h1> <?php if ($row['id_user'] == $_SESSION['id'] || $_SESSION['admin'] == 1 || $_SESSION['admin'] == 2 || $_SESSION['admin'] == 3) { ?> <?php require '_includes/review-glance.php'; ?> <div class="weekday-edit-wrap"> <?php require '_includes/meeting-details.php'; ?> </div><!-- .weekday-wrap --> <a class="done" href="manage.php">DONE</a> <?php } else { echo "<p style=\"margin-top:1.5em;\">Quit trying to be sneaky.</p>"; } ?> </div> </div><!-- #manage-wrap --> <?php require '_includes/footer.php'; ?><file_sep>/load-mb-replies-DELETE.php <?php require_once 'config/initialize.php'; $post = $_GET['post-id']; $get_replies = get_mb_replies($post); $results = mysqli_num_rows($get_replies); $results = mysqli_fetch_all($get_replies, MYSQLI_ASSOC); if ($results > 0) { $i = 1; foreach ($results as $row) { // while ($row = mysqli_fetch_assoc($get_replies)) { ?> <li id="li_<?= $i ?>"> <p class="date"><p class="mb-date"><?= date('g:i A D, M d, \'y', strtotime($row['replied'])) ?> | <?= substr($row['username'], 0, 1) . '... ' ?> Replied:</p> <p class="mb-body"><?= nl2br($row['reply']) ?></p> <?php if (isset($_SESSION['id']) && $_SESSION['id'] == $row['id_user'] || ($_SESSION['mode'] == 1 && $_SESSION['admin'] == 1 || $_SESSION['admin'] == 2 || $_SESSION['admin'] == 3)) { ?> <form id="dr_<?= $i ?>" class="delete-reply"> <input type="hidden" name="id-reply" value="<?= $row['id_reply'] ?>"> <a data-id="dr_<?= $i ?>" data-role="delete-reply" class="manage-delete-mb"><div class="tooltip right"><span class="tooltiptext">Delete</span><i class="far fas fa-minus-circle"></i></div></a> </form> <?php } ?> </li> <?php $i++; } // end foreach loop ?> <?php } else { ?> <li> <p class="mb-body">No replies yet.</p> </li> <?php } ?> <file_sep>/_includes/odin-daily-glance.php <?php if ($user_id == 1) { ?> <?php /* used for all other pages */ ?> <div class="daily-glance-wrap"> <div class="daily-glance<?php if ($row['visible'] == 1 && (($row['admin'] != 1 || $row['admin'] != 2) && $row['id_user'] != $_SESSION['id']) ) { echo ' personal-other'; } if ($row['visible'] == 1 && ($row['admin'] == 1 || $row['admin'] == 2)) { echo ' personal-odin'; } ?>"> <div class="glance-mtg glance-mtg-time"> <p><?= date('g:i A', strtotime($row['meet_time'])); ?></p> </div><!-- .glance-time-day --> <div class="glance-mtg glance-group-title"> <p><?= $row['group_name'] ?></p> </div><!-- .glance-group --> <div class="glance-mtg glance-mtg-type"> <?php if ($_SESSION['admin'] == 1 || $_SESSION['admin'] == 2) { ?> <a class="manage-edit" href="user_role.php?id=<?= h(u($row['id_mtg'])) . '&user=' . h(u($row['id_user'])); ?>"><div class="tooltip"><span class="tooltiptext">Manage User</span><i class="far fas fa-user-cog"></i></div></a> <a class="manage-edit" href="manage_edit.php?id=<?= h(u($row['id_mtg'])); ?>"><div class="tooltip"><span class="tooltiptext">Edit Meeting</span><i class="far fa-edit"></i></div></a> <a class="manage-edit" href="transfer-meeting.php?id=<?= h(u($row['id_mtg'])); ?>"><div class="tooltip"><span class="tooltiptext">Transfer Meeting</span><i class="far fas fa-people-arrows"></i></div></a> <a class="manage-delete" href="manage_delete.php?id=<?= h(u($row['id_mtg'])); ?>"><div class="tooltip right"><span class="tooltiptext">Delete Meeting</span><i class="far fas fa-minus-circle"></i></div></a> <?php } ?> </div><!-- .glance-mtg-type --> </div><!-- .daily-glance --> </div> <?php } ?> <file_sep>/controllers/authController.php <?php require_once 'controllers/emailController.php'; $errors = []; $username = ""; $email = ""; $verified = ""; $admin = ""; $visible = ""; function remember_me() { global $conn; if (!empty($_COOKIE['token'])) { $token = $_COOKIE['token']; $sql = "SELECT * FROM users WHERE token=? LIMIT 1"; $stmt = $conn->prepare($sql); $stmt->bind_param('s', $token); if ($stmt->execute()) { $result = $stmt->get_result(); $user = $result->fetch_assoc(); // put variables in session $_SESSION['id'] = $user['id_user']; $_SESSION['username'] = $user['username']; $_SESSION['email'] = $user['email']; $_SESSION['verified'] = $user['verified']; $_SESSION['admin'] = $user['admin']; $_SESSION['mode'] = $user['mode']; $_SESSION['email_opt'] = $user['email_opt']; $_SESSION['db-tz'] = $user['tz']; } } } remember_me(); // sign-up if (is_post_request() && isset($_POST['submit'])) { $username = $_POST['username']; $email = strtolower($_POST['email']); $password = $_POST['<PASSWORD>']; $passwordConf = $_POST['<PASSWORD>Conf']; if (empty($username)) { $errors['username'] = "Please enter a username"; } if ((!empty($username)) && (strlen($username) > 16)) { $errors['username'] = "Keep Username 16 characters or less"; } if ((!empty($username)) && (strpos($username,','))) { $errors['username'] = "Sorry, you can't have a comma in your Username."; } if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors['email'] = "Email is invalid"; } if (empty($email)) { $errors['email'] = "Email required"; } if (empty($password)) { $errors['password'] = "Password required"; } if ((!empty($password)) && (strlen($password) <= 3)) { $errors['password'] = "Password needs at least 4 characters"; } if ((!empty($password)) && (strlen($password) > 50)) { $errors['password'] = "Keep your password under 50 characters"; } if ((!empty($password)) && (empty($passwordConf))) { $errors['password'] = "Confirm password"; } if ((empty($password)) && (empty(!$passwordConf))) { $errors['password'] = "<PASSWORD> - Type same password in both fields"; } if ( ((!empty($password)) && (empty(!$passwordConf))) && ($password !== $passwordConf)) { $errors['password'] = "Passwords don't match. Note: passwords are case sensitive."; } $emailQuery = "SELECT * FROM users WHERE email=? LIMIT 1"; $stmt = $conn->prepare($emailQuery); $stmt->bind_param('s', $email); $stmt->execute(); /* updated to PHP v7.2 on GoDaddy and unchecked mysqli and checked nd_mysqli */ /* in order to get this command to work */ $result = $stmt->get_result(); $userCount = $result->num_rows; $stmt->close(); if($userCount > 0) { $errors['email'] = "Email already exists"; } if (count($errors) === 0) { $password = password_hash($password, PASSWORD_DEFAULT); $token = bin2hex(random_bytes(50)); $verified = false; $sql = "INSERT INTO users (username, email, verified, token, password) VALUES (?, ?, ?, ?, ?)"; $stmt = $conn->prepare($sql); $stmt->bind_param('ssdss', $username, $email, $verified, $token, $password); if ($stmt-> execute()) { // login user $user_id = $conn->insert_id; $_SESSION['id'] = $user_id; $_SESSION['username'] = $username; $_SESSION['email'] = $email; // don't send a verified token because they're not verified yet! $_SESSION['verified'] = $verified; $_SESSION['admin'] = '0'; $_SESSION['mode'] = '0'; $_SESSION['email_opt'] = '1'; sendVerificationEmail($username, $email, $token); // set flash message $_SESSION['message'] = "Success! Almost there..."; $_SESSION['alert-class'] = "alert-success"; header('location:' . WWW_ROOT); exit(); } else { $errors['db_error'] = "Database error: failed to register"; } } } // if user clicks on login if (is_post_request() && isset($_POST['login'])) { $username = $_POST['username']; $password = $_POST['<PASSWORD>']; // validation if (empty($username)) { $errors['username'] = "Username or email required"; } if (empty($password)) { $errors['password'] = "<PASSWORD>"; } // $userQuery = "SELECT * FROM users WHERE username=? LIMIT 2"; $userQuery = "SELECT * FROM users WHERE LOWER(username) LIKE LOWER(?) LIMIT 2"; $stmt = $conn->prepare($userQuery); $stmt->bind_param('s', $username); $stmt->execute(); $result = $stmt->get_result(); $userCount = $result->num_rows; $stmt->close(); if($userCount > 1) { $errors['usermane'] = "There are multiple \"" . $username . "'s\" here AND you have the same password... but you don't have the same email address! You'll have to use your email address to login."; } if (count($errors) === 0) { // having to accept email or username because of how Apple/ios binds these two // in their login management // $sql = "SELECT * FROM users WHERE email=? OR username=? LIMIT 1"; $sql = "SELECT * FROM users WHERE LOWER(email) LIKE LOWER(?) OR LOWER(username) LIKE LOWER(?) LIMIT 1"; $stmt = $conn->prepare($sql); $stmt->bind_param('ss', $username, $username); $stmt->execute(); $result = $stmt->get_result(); $userCount = $result->num_rows; $user = $result->fetch_assoc(); if (password_verify($password, $user['password'])) { // login success $_SESSION['id'] = $user['id_user']; $_SESSION['username'] = $user['username']; $_SESSION['email'] = $user['email']; $_SESSION['verified'] = $user['verified']; $_SESSION['admin'] = $user['admin']; $_SESSION['mode'] = $user['mode']; $_SESSION['email_opt'] = $user['email_opt']; $_SESSION['db-tz'] = $user['tz']; $_SESSION['token'] = $user['token']; // you're not verified yet -> go see a msg telling you we're waiting for // email verification if (($user['verified']) === 0) { $_SESSION['message'] = "Email has not been verified"; $_SESSION['alert-class'] = "alert-danger"; header('location:'. WWW_ROOT); exit(); } else { // user is logged in and verified. did they check the rememberme? if (isset($_POST['remember_me'])) { $token = $_SESSION['token']; setCookie('token', $token, time() + (1825 * 24 * 60 * 60)); } // everything checks out -> you're good to go! // header('location: home_private.php'); header('location:' . WWW_ROOT); exit(); } } else if ($userCount < 1) { $errors['login_fail'] = "That user does not exist"; } else { // the combination of stuff you typed doesn't match anything in the db $errors['login_fail'] = "Wrong Username/Password combination. Note: passwords are case sensitive."; } } } // verify user by token function verifyUser($token) { global $conn; $sql = "SELECT * FROM users WHERE token='$token' LIMIT 1"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { $user = mysqli_fetch_assoc($result); $update_query = "UPDATE users SET verified=1 WHERE token='$token'"; if (mysqli_query($conn, $update_query)) { // login success $_SESSION['id'] = $user['id_user']; $_SESSION['username'] = $user['username']; $_SESSION['email'] = $user['email']; $_SESSION['verified'] = 1; $_SESSION['admin'] = $user['admin']; $_SESSION['mode'] = $user['mode']; $_SESSION['email_opt'] = $user['email_opt']; $_SESSION['db-tz'] = $user['tz']; $_SESSION['message'] = "Your email address was successfully verified! You can now login."; $_SESSION['alert-class'] = "alert-success"; header('location:'. WWW_ROOT); exit(); } } else { echo 'User not found'; } } // if user clicks on forgot password if (is_post_request() && isset($_POST['forgot-password'])) { $email = $_POST['email']; if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors['email'] = "Email is invalid"; } if (empty($email)) { $errors['email'] = "Email required"; } if (count($errors) == 0) { $sql = "SELECT * FROM users WHERE email='$email' LIMIT 1"; $result = mysqli_query($conn, $sql); $user = mysqli_fetch_assoc($result); $user_exists = mysqli_num_rows($result); if ($user_exists > 0) { $token = $user['token']; sendPasswordResetLink($email, $token); header('location: password_message.php'); exit(0); } else { $_SESSION['message'] = "There is no user here with that email address."; $_SESSION['alert-class'] = "alert-danger"; header('location:'. WWW_ROOT . '/forgot_password.php'); exit(); } } } // if user clicked on the reset password if (is_post_request() && isset($_POST['reset-password-btn'])) { $password = $_POST['password']; $passwordConf = $_POST['passwordConf']; if (empty($password) || empty($passwordConf)) { $errors['password'] = "<PASSWORD>"; } if ($password !== $passwordConf) { $errors['password'] = "Passwords don't match. Note: passwords are case sensitive."; } $password = password_hash($password, PASSWORD_DEFAULT); $email = $_SESSION['email']; if(count($errors) == 0) { $sql = "UPDATE users SET password='$password' WHERE email='$email'"; $result = mysqli_query($conn, $sql); if ($result) { $_SESSION['message'] = "Your password was changed successfully. You can now login with your new credentials."; $_SESSION['alert-class'] = "pass-reset"; header('location: login.php'); exit(0); } } } function resetPassword($token) { global $conn; $sql = "SELECT * FROM users WHERE token='$token' LIMIT 1"; $result = mysqli_query($conn, $sql); $user = mysqli_fetch_assoc($result); $_SESSION['email'] = $user['email']; header('location: reset_password.php'); exit(0); } <file_sep>/sandbox.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <?php function converted_time($time, $tz) { $utc = 'UTC'; $from_tz_obj = new DateTimeZone($utc); $to_tz_obj = new DateTimeZone($tz); $ct = new DateTime($time, $from_tz_obj); $ct->setTimezone($to_tz_obj); $nct = $ct->format('g:i A'); return $nct; } $nct = converted_time('0100', 'America/Denver'); echo $nct . '<br />'; // checks out // ------------------------------------ function apply_offset_to_edit($time) { // $utc = 'UTC'; $from_tz_obj = new DateTimeZone('UTC'); $to_tz_obj = new DateTimeZone($time['tz']); // $ct = new DateTime($time['ut'], $from_tz_obj); // $ct->setTimezone($to_tz_obj); $csun = new DateTime('Sunday ' . $time['ut'], $from_tz_obj); $csun->setTimezone($to_tz_obj); $nsun = $csun->format('l Hi'); return $nsun; } $time = []; $time['tz'] = 'America/Denver'; $time['ut'] = '0100'; $nsun = apply_offset_to_edit($time); echo $nsun . '<br />'; // checks out ?> </body> </html><file_sep>/js/google-map.js function initialize() { var map_canvas = document.getElementById('map'); var map_options = { center: new google.maps.LatLng(39.661050, -105.348790), zoom: 15, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(map_canvas, map_options); var i=new google.maps.Marker({ position:new google.maps.LatLng(39.661050, -105.348790), map:map }) } google.maps.event.addDomListener(window, 'load', initialize);<file_sep>/_includes/inner_nav.php <?php if ($layout_context == "dashboard" && ($_SESSION['admin'] == 1 || $_SESSION['admin'] == 3)) { ?> <p class="logout"> <a href="<?= WWW_ROOT ?>">Home</a> <?php if ($_SESSION['mode'] == 1) { ?> | <a href="<?= WWW_ROOT . '/user_management.php' ?>">User Management</a> <?php } ?> </p> <?php } ?> <?php if ($layout_context == "dashboard" && ($_SESSION['admin'] == 0 || $_SESSION['admin'] == 2)) { ?> <p class="logout"> <a href="<?= WWW_ROOT ?>">Home</a> </p> <?php } ?> <?php if ($layout_context == "um") { ?> <p class="logout"> <a href="<?= WWW_ROOT ?>">Home</a> | <a href="<?= WWW_ROOT . '/manage.php' ?>">Dashboard</a> </p> <?php } ?> <?php if ($layout_context == "alt-manage" && ($_SESSION['admin'] == 1 || $_SESSION['admin'] == 3)) { ?> <p class="logout"> <a href="<?= WWW_ROOT ?>">Home</a> | <a href="<?= WWW_ROOT . '/manage.php' ?>">Dashboard</a> <?php if ($_SESSION['mode'] == 1) { ?> | <a href="<?= WWW_ROOT . '/user_management.php' ?>">User Management</a> <?php } ?> </p> <?php } ?> <?php if ($layout_context == "alt-manage" && ($_SESSION['admin'] != 1 && $_SESSION['admin'] != 3)){ ?> <p class="logout"> <a href="<?= WWW_ROOT ?>">Home</a> | <a href="<?= WWW_ROOT . '/manage.php' ?>">Dashboard</a> </p> <?php } ?> <file_sep>/_includes/msg-role-key.php <?php if (!isset($_SESSION['admin'])) { // Visitor to home.php ?> <div id="role-key"> <div class="msg-bkg"> <div class="inside-msg-one"> <i class="far fa-times-circle"></i> <h1>Visitor</h1> <p>Thanks for visiting! If a single person finds a single meeting on this site that starts them towards a better life, the effort to prepare it will have been worthwhile.</p> </div><!-- .inside-msg-one --> </div><!-- .msg-bkg --> </div><!-- #msg-two --> <?php } else if ($_SESSION['admin'] == 1) { // Bob mode ?> <div id="role-key"> <div class="msg-bkg"> <div class="inside-msg-one"> <i class="far fa-times-circle"></i> <h1>Top Dog</h1> <p>You can do anything you want here while in Admin Mode including:</p> <ul> <li>Assign or revoke Top Tier Admin privileges</li> <li>Suspend or unsuspend anyone</li> <li>See other's private meetings + edit, transfer or delete them</li> <li>Edit, Transfer or Delete any meeting anywhere</li> <li>See username + email address of meeting host when viewing a meeting on the homepage</li> <li>Access Email Everyone page in order to BCC all members. *Note: At the moment it works best to just copy addresses to clipboard and use your own email client ( <em>use BCC!</em> ). Going through website is at the mercy of GoDaddy servers and they're unpredictible.</li> </ul> </div><!-- .inside-msg-one --> </div><!-- .msg-bkg --> </div><!-- #msg-two --> <?php } else if ($_SESSION['admin'] == 3) { // Top Tier Admin ?> <div id="role-key"> <div class="msg-bkg"> <div class="inside-msg-one"> <i class="far fa-times-circle"></i> <h1>Admin Top Tier privileges</h1> <p>While in Admin Mode you can:</p> <ul> <li>Edit any meeting (including Tier II Admin)</li> <li>Transfer any meeting (including Tier II Admin)</li> <li>Delete any meeting (including Tier II Admin)</li> <li>Assign or revoke Admin II privileges</li> <li>Suspend or unsuspend users</li> <li>See username + email address of meeting host when viewing a meeting on the homepage</li> </ul> </div><!-- .inside-msg-one --> </div><!-- .msg-bkg --> </div><!-- #msg-two --> <?php } else if ($_SESSION['admin'] == 2) { // Tier II Admin ?> <div id="role-key"> <div class="msg-bkg"> <div class="inside-msg-one"> <i class="far fa-times-circle"></i> <h1>Admin Tier II privileges</h1> <p>While in Admin Mode you can:</p> <ul> <li>Edit any meeting (except other Admins) - You can change other meetings to Draft or Private thereby effectively removing them from view but you cannot delete any meetings other than your own.</li> <li>Transfer any meeting (except other Admins)</li> <li>See username + email address of meeting host when viewing a meeting on the homepage</li> </ul> </div><!-- .inside-msg-one --> </div><!-- .msg-bkg --> </div><!-- #msg-two --> <?php } else { // Member ?> <div id="role-key"> <div class="msg-bkg"> <div class="inside-msg-one"> <i class="far fa-times-circle"></i> <h1>Member privileges</h1> <ul> <li>Add meetings</li> <li>Edit your meetings</li> <li>Transfer your meetings</li> <li>Delete your meetings</li> </ul> </div><!-- .inside-msg-one --> </div><!-- .msg-bkg --> </div><!-- #msg-two --> <?php } ?> <file_sep>/_includes/daily-glance-ORIGINAL.php <?php if (isset($_SESSION['id'])) { ?> <?php /* user is logged in, show them their Private, their Members and their Public meetings (1's, 2's and 3's) */ ?><?php if ((($row['id_user']) == $_SESSION['id']) && (($row['visible'] == 1) || ($row['visible'] == 2) || ($row['visible'] == 3))) { ?> <div class="daily-glance-wrap"> <div class="daily-glance<?php if ($row['visible'] == 0) { echo ' draft'; } if ($row['visible'] == 1) { echo ' personal'; } ?>"> <div class="glance-mtg glance-mtg-time"> <p><?= date('g:i A', strtotime($row['meet_time'])); ?></p> </div><!-- .glance-time-day --> <div class="glance-mtg glance-group-title"> <p><?= $row['group_name']; ?></p> </div><!-- .glance-group --> <div class="glance-mtg glance-mtg-type"> <?php if ($row['meet_url'] != null) { ?> <div class="tooltip"> <span class="tooltiptext type">Zoom Meeting</span><i class="fas far fa-video fa-fw"></i> </div> <?php } if ($row['meet_addr'] != null) { ?> <div class="tooltip"> <span class="tooltiptext type">In-Person Meeting</span><i class="fas far fa-map-marker-alt fa-fw"></i> </div> <?php } if ($row['code_o'] != 0) { ?> <div class="ctr-type"> Open meeting </div> <?php } else if ($row['code_w'] != 0) { ?> <div class="ctr-type"> Women's meeting </div> <?php } else if ($row['code_m'] != 0) { ?> <div class="ctr-type"> Men's meeting </div> <?php } else { ?> <div class="ctr-type"> Join us </div> <?php } if ($row['id_user'] == $_SESSION['id']) { ?><a class="manage-edit" href="manage_edit.php?id=<?= h(u($row['id_mtg'])); ?>"><div class="tooltip right"><span class="tooltiptext">Edit Meeting</span><i class="far fa-edit"></i></div></a> <?php } ?> </div><!-- .glance-mtg-type --> </div><!-- .daily-glance --> </div> <?php /* user is logged in. show them other people's Members (2's) and Public (3's) meetings */ ?> <?php } else if ((($row['id_user']) != $_SESSION['id']) && ((($row['visible'] == 2) || ($row['visible'] == 3)))) { ?> <div class="daily-glance-wrap"> <div class="daily-glance<?php if ($row['visible'] == 0) { echo ' draft'; } if ($row['visible'] == 1) { echo ' personal'; } ?>"> <div class="glance-mtg glance-mtg-time"> <p><?= date('g:i A', strtotime($row['meet_time'])); ?></p> </div><!-- .glance-time-day --> <div class="glance-mtg glance-group-title"> <p><?= $row['group_name']; ?></p> </div><!-- .glance-group --> <div class="glance-mtg glance-mtg-type"> <?php if ($row['meet_url'] != null) { ?> <div class="tooltip"> <span class="tooltiptext type">Zoom Meeting</span><i class="fas far fa-video fa-fw"></i> </div> <?php } if ($row['meet_addr'] != null) { ?> <div class="tooltip"> <span class="tooltiptext type">In-Person Meeting</span><i class="fas far fa-map-marker-alt fa-fw"></i> </div> <?php } if ($row['code_o'] != 0) { ?> <div class="ctr-type"> Open meeting </div> <?php } else if ($row['code_w'] != 0) { ?> <div class="ctr-type"> Women's meeting </div> <?php } else if ($row['code_m'] != 0) { ?> <div class="ctr-type"> Men's meeting </div> <?php } else { ?> <div class="ctr-type"> Join us </div> <?php } if ($row['id_user'] == $_SESSION['id']) { ?><a class="manage-edit" href="manage_edit.php?id=<?= h(u($row['id_mtg'])); ?>"><div class="tooltip right"><span class="tooltiptext">Edit Meeting</span><i class="far fa-edit"></i></div></a> <?php } ?> </div><!-- .glance-mtg-type --> </div><!-- .daily-glance --> </div> <?php } ?> <?php /* no session id set - general public - only show public (3's) meetings */ ?> <?php } else if ($row['visible'] != 0 && $row['visible'] != 1 && $row['visible'] != 2) { ?> <div class="daily-glance-wrap"> <div class="daily-glance<?php if ($row['visible'] == 0) { echo ' draft'; } if ($row['visible'] == 1) { echo ' personal'; } ?>"> <div class="glance-mtg glance-mtg-time"> <p><?= date('g:i A', strtotime($row['meet_time'])); ?></p> </div><!-- .glance-time-day --> <div class="glance-mtg glance-group-title"> <p><?= $row['group_name']; ?></p> </div><!-- .glance-group --> <div class="glance-mtg glance-mtg-type"> <?php if ($row['meet_url'] != null) { ?> <div class="tooltip"> <span class="tooltiptext type">Zoom Meeting</span><i class="fas far fa-video fa-fw"></i> </div> <?php } if ($row['meet_addr'] != null) { ?> <div class="tooltip"> <span class="tooltiptext type">In-Person Meeting</span><i class="fas far fa-map-marker-alt fa-fw"></i> </div> <?php } if ($row['code_o'] != 0) { ?> <div class="ctr-type"> Open meeting </div> <?php } else if ($row['code_w'] != 0) { ?> <div class="ctr-type"> Women's meeting </div> <?php } else if ($row['code_m'] != 0) { ?> <div class="ctr-type"> Men's meeting </div> <?php } else { ?> <div class="ctr-type"> Join us </div> <?php } ?> </div><!-- .glance-mtg-type --> </div><!-- .daily-glance --> </div> <?php } ?><file_sep>/process_change_role.php <?php require_once 'config/initialize.php'; require_once 'config/verify_admin.php'; $user_id = $_POST['user']; $role = $_POST['admin']; $reason = $_POST['reason']; $mode = $_POST['mode']; /* $mode is whether user is logged in as admin or not. 1=logged in Admin Mode, 0=not logged in Admin Mode. if they are downgraded out of Admin status then their mode needs to be changed to 0 in order to kick them out of Admin Mode if they are currently logged in and prevent them from doing anything as an Admin could or would. */ if ($role == 0 || $role == 85 || $role == 86) { $mode = '0'; } if (is_post_request()) { if ($_SESSION['admin'] != 1 && $_SESSION['admin'] != 3) { $signal = 'bad'; $msg = 'It appears you lack the necessary clearance to do this.'; } if ($_SESSION['admin'] != 1 && ($role == 1 || $role == 3)) { $signal = 'bad'; $msg = 'Are you trying to find a chink in my armor? That is no bueno and your name has been reported to the authorities. Gather your belongings and hide.'; } else { if ($role == '3') { $change_user_role = change_user_role($user_id, $role, $mode); if ($change_user_role === true) { $signal = '3'; $msg = 'Transfer successful!'; } else { $signal = 'bad'; $msg = 'I don\'t think that worked.'; } } if ($role == '2') { $change_user_role = change_user_role($user_id, $role, $mode); if ($change_user_role === true) { $signal = '2'; $msg = 'Transfer successful!'; } else { $signal = 'bad'; $msg = 'I don\'t think that worked.'; } } if ($role == '0') { $change_user_role = change_user_role($user_id, $role, $mode); if ($change_user_role === true) { $signal = '0'; $msg = 'Transfer successful!'; } else { $signal = 'bad'; $msg = 'I don\'t think that worked.'; } } } } $data = array( 'signal' => $signal, 'msg' => $msg ); echo json_encode($data); // stop ?><file_sep>/load-message-board.php <?php require_once 'config/initialize.php'; // require_once 'config/verify_admin.php'; $mb_posts = get_mb_posts(); $results = mysqli_num_rows($mb_posts); if ($results > 0) { $i = 1; while ($row = mysqli_fetch_assoc($mb_posts)) { ?> <?php $get_replies = get_mb_pg_replies($row['idt_topic']); $resultz = mysqli_num_rows($get_replies); $mt = new DateTime($row['opened'], new DateTimeZone('America/Denver')); $mt->setTimezone(new DateTimeZone($tz)); // echo $row['mb_header'] . ' | number of replies: ' . $resultz . ' topic ID: ' . $row['idr_topic']; ?> <li id="li_<?= $i ?>"> <div class="mb-individual"> <?php if (isset($_SESSION['id']) && $_SESSION['id'] == $row['idt_user']) { ?> <a class="mb-date" href="post.php?post-id=<?= $row['idt_topic'] ?>"><?= $mt->format("g:i A D, M d, 'y") ?> | You posted:</a> <?php } else { ?> <a class="mb-date" href="post.php?post-id=<?= $row['idt_topic'] ?>"><?= $mt->format("g:i A D, M d, 'y") ?> | <?= substr($row['username'], 0, 1) . '... ' ?> Posted:</a> <?php } ?> <div class="group-mb"><?php /* favicon links */ ?> <?php /* begin "Read and Reply" (comments) icon */ ?> <form id="<?= $i ?>" class="mbform" action="post.php?post-id=<?= $row['idt_topic'] ?>" method="get"> <input id="pid_<?= $i ?>" type="hidden" name="post-id" value="<?= $row['idt_topic'] ?>"> <?php if (isset($_SESSION['id']) && (($_SESSION['id'] == $row['idt_user']) || ($_SESSION['mode'] == 1 && ($_SESSION['admin'] == 1 || $_SESSION['admin'] == 2 || $_SESSION['admin'] == 3))) ) { // this is either their post which means they have a delete btn or it's an admin (in admin mode) which means they have a delete btn - either way, there's another icon to the right so don't put the class of 'right' in the tooltip div. ?> <a data-id="<?= $i ?>" data-role="go-to-post" class="gtp"><div class="tooltip"><span class="tooltiptext">Read &amp; Reply</span><i class="far fa-comments"></i></div></a> <?php } else if (isset($_SESSION['id']) && ($_SESSION['id'] != $row['idt_user'])) { // logged in but not theirs so put 'Read & Reply' in tooltip with class of right ?> <a data-id="<?= $i ?>" data-role="go-to-post" class="gtp"><div class="tooltip right"><span class="tooltiptext">Read &amp; Reply</span><i class="far fa-comments"></i></div></a> <?php } else { // put the class of 'right' in the tooltip div and just show 'Comments' in tooltip ?> <a data-id="<?= $i ?>" data-role="go-to-post" class="gtp"><div class="tooltip right"><span class="tooltiptext">Comments</span><i class="far fa-comments"></i></div></a> <?php } ?> </form> <?php /* end "Read and Reply" (comments) icon */ ?> <?php /* begin manage_user icon */ ?> <?php if (isset($_SESSION['mode']) && ($_SESSION['mode'] == 1 && ($_SESSION['admin'] == 1 || $_SESSION['admin'] == 3))) { ?> <?php if ($_SESSION['id'] == $row['idt_user']) { ?> <a class="gtp my-stuff"><div class="tooltip"><span class="tooltiptext">My Stuff</span><i class="far fas fa-user-cog"></i></div></a> <?php } else if ($_SESSION['admin'] != 1 && ($row['admin'] == 1 || $row['admin'] == 3)) { ?> <a class="gtp my-stuff"><div class="tooltip"><span class="tooltiptext">Top Tier Admin</span><i class="far fas fa-user-cog"></i></div></a> <?php } else { ?> <a class="gtp" href="user_role.php?user=<?= h(u($row['idt_user'])); ?>"><div class="tooltip"><span class="tooltiptext">Manage User</span><i class="far fas fa-user-cog"></i></div></a> <?php } ?> <?php } ?> <?php /* end manage_user icon */ ?> <?php /* begin delete icon */ ?> <?php if (isset($_SESSION['id']) && ($_SESSION['id'] == $row['idt_user'] || ($_SESSION['mode'] == 1 && ($_SESSION['admin'] == 1 || $_SESSION['admin'] == 2 || $_SESSION['admin'] == 3)))) { ?> <form id="df_<?= $i ?>"> <input type="hidden" name="post-id" value="<?= $row['idt_topic'] ?>"> <input type="hidden" name="uid" value="<?= $row['idt_user'] ?>"> <?php if ($_SESSION['id'] == $row['idt_user']) { ?> <a data-id="df_<?= $i ?>" data-role="delete-post" class="manage-delete-mb"><div class="tooltip right"><span class="tooltiptext">Delete your Post</span><i class="far fas fa-minus-circle"></i></div></a> <?php } else if ($_SESSION['admin'] != 1 && ($row['admin'] == 1 || $row['admin'] == 3)) { ?> <a class="gtp my-stuff"><div class="tooltip right"><span class="tooltiptext">Admin Off Limits</span><i class="far fas fa-minus-circle"></i></div></a> <?php } else { ?> <a data-id="df_<?= $i ?>" data-role="delete-post" class="manage-delete-mb"><div class="tooltip right"><span class="tooltiptext">Delete their Post</span><i class="far fas fa-minus-circle"></i></div></a> <?php } ?> </form> <?php } ?> <?php /* end delete icon */ ?> </div> </div> <?php /* begin username + email for Admins 1 & 3 in Admin Mode */ ?> <?php if (isset($_SESSION['id']) && ($_SESSION['mode'] == 1 && ($_SESSION['admin'] == 1 || $_SESSION['admin'] == 3))) { ?> <?php if ($_SESSION['id'] == $row['idt_user']) { ?> <p class="admin-mb-info">This is your post</p> <?php } else if ($_SESSION['admin'] != 1 && ($row['admin'] == 1 || $row['admin'] == 3)) { // remember, there's only 1 ($row['admin'] = 1) ?> <p class="admin-mb-info">Admin (off limits)</p> <?php } else { ?> <a class="admin-mb-info gtp" href="user_role.php?user=<?= h(u($row['idt_user'])); ?>"><div class="tooltip"><span class="tooltiptext">Manage User</span><?= $row['username'] . ' &bullet; ' . $row['email'] ?></div></a> <?php } ?> <?php } ?> <?php /* end username + email for Admins 1 & 3 */ ?> <a class="mb-entire" href="post.php?post-id=<?= $row['idt_topic'] ?>"> <p class="title"><?= $row['mb_header'] ?> | <span class="num-replies"><?php if ($resultz == 0 || $resultz > 1) { echo $resultz . ' replies'; } else { echo $resultz . ' reply'; } ?></span></p> <?php $firstLine = preg_split('~<br */?>|\R~i', $row['mb_body'], -1, PREG_SPLIT_NO_EMPTY)[0]; if (strlen($firstLine) > 80 || substr_count($row['mb_body'], "\n") > 0) { ?> <p class="mb-body"><?= nl2br(substr($firstLine, 0, 80)) . '...' ?></p> <?php } else { ?> <p class="mb-body"><?= nl2br($firstLine) ?></p> <?php } ?> </a> </li> <?php $i++; } // end while loop ?> <?php } else { ?> <li> <p id="npy" class="nry">There are currently no posts.</p> </li> <?php } ?> <file_sep>/process-admin-mode.php <?php require_once 'config/initialize.php'; require_once 'config/verify_admin.php'; if ($_SESSION['admin'] == 0 || $_SESSION['admin'] == 85 || $_SESSION['admin'] == 86) { header('location: ' . WWW_ROOT); exit(); } if (is_post_request()) { if(isset($_POST['mode'])) { $id = $_SESSION['id']; $mode = $_POST['mode']; $url = $_POST['url']; $result = update_admin_mode($id, $mode); if ($result === true) { $_SESSION['mode'] = $mode; header('location:' . $url); } else { $errors = $result; } } }<file_sep>/_includes/session.php <?php function message() { if (isset($_SESSION["message"])) { $output = "<div class=\"message\">"; $output .= htmlentities($_SESSION["message"]); $output .= "</div>"; // Clear message after using once $_SESSION["message"] = null; return $output; } } function delete_success_message() { if (isset($_SESSION["message"])) { $output = "<span id=\"success-fade\" class=\"contact-update-message\"><i class=\"fa fa-star\" aria-hidden=\"true\"></i>&nbsp;&nbsp;&nbsp;"; $output .= htmlentities($_SESSION["message"]); $output .= "&nbsp;&nbsp;&nbsp;<i class=\"fa fa-star\" aria-hidden=\"true\"></i></span>"; // Clear message after using once $_SESSION["message"] = null; return $output; } } ?><file_sep>/_includes/new-review-glance.php <div class="manage-glance-wrap-review"> <div class="manage-glance-review<?php if ($row['visible'] == 0) { echo ' draft'; } ?>"> <div class="glance-mtg glance-mtg-time"> <p><?php $time = $row['meet_time']; $nt = converted_time($time, $tz); echo $nt . ' '; if ($row['sun'] == 0) { } else if (($row['sun'] !=0) && (($row['mon'] != 0) || ($row['tue'] != 0) || ($row['wed'] != 0) || ($row['thu'] != 0) || ($row['fri'] != 0) || ($row['sat'] != 0))) { echo "Sun, "; } else { echo "Sun"; } if ($row['mon'] == 0) { } else if (($row['mon'] !=0) && (($row['tue'] != 0) || ($row['wed'] != 0) || ($row['thu'] != 0) || ($row['fri'] != 0) || ($row['sat'] != 0))) { echo "Mon, "; } else { echo "Mon"; } if ($row['tue'] == 0) { } else if (($row['tue'] !=0) && (($row['wed'] != 0) || ($row['thu'] != 0) || ($row['fri'] != 0) || ($row['sat'] != 0))) { echo "Tue, "; } else { echo "Tue"; } if ($row['wed'] == 0) { } else if (($row['wed'] !=0) && (($row['thu'] != 0) || ($row['fri'] != 0) || ($row['sat'] != 0))) { echo "Wed, "; } else { echo "Wed"; } if ($row['thu'] == 0) { } else if (($row['thu'] !=0) && (($row['fri'] != 0) || ($row['sat'] != 0))) { echo "Thu, "; } else { echo "Thu"; } if ($row['fri'] == 0) { } else if (($row['fri'] !=0) && ($row['sat'] != 0)) { echo "Fri, "; } else { echo "Fri"; } if ($row['sat'] == 0) { } else { echo "Sat "; } ?></p> <?php /* <?php if ($row['sun'] != 0) { echo " Sun "; } if ($row['mon'] != 0) { echo " Mon "; } if ($row['tue'] != 0) { echo " Tue "; } if ($row['wed'] != 0) { echo " Wed "; } if ($row['thu'] != 0) { echo " Thu "; } if ($row['fri'] != 0) { echo " Fri "; } if ($row['sat'] != 0) { echo " Sat "; } ?></p> */ ?> </div><!-- .glance-time-day --> <div class="glance-mtg glance-group-title"> <p><?php if ($row['meet_url'] != null) { echo '<div class="tooltip"><span class="tooltiptext">Zoom Meeting</span><i class="fas fa-video fa-fw"></i></div>'; } if ($row['meet_addr'] != null) { echo '<div class="tooltip"><span class="tooltiptext">In-Person Meeting</span><i class="fas fa-map-marker-alt fa-fw"></i></div>'; } ?> <?php // if ($row['visible'] == 0) { echo ' [DRAFT] '; } // if ($row['visible'] == 1) { echo ' [PRIVATE] '; } // if ($row['visible'] == 2) { echo ' [PUBLIC] '; } ?><?= $row['group_name']; ?></p> </div><!-- .glance-group --> <div class="glance-mtg glance-mtg-type"> <p><?php if ($row['id_user'] == $_SESSION['id']) { ?> <a class="manage-edit" href="manage_edit.php?id=<?= h(u($id)); ?>"><i class="far fa-edit"></i></a> <a class="manage-delete" href="manage_delete.php?id=<?= h(u($row['id_mtg'])); ?>"><i class="fas fa-minus-circle"></i></a> <?php } ?></p> </div><!-- .glance-mtg-type --> </div><!-- .daily-glance --> </div> <file_sep>/password_message.php <?php $layout_context = "password-message"; require_once 'config/initialize.php'; require '_includes/head.php'; ?> <body> <img class="background-image" src="_images/aa-logo-dark_mobile.gif" alt="AA Logo"> <div id="landing"> <div id="landing-content"> <h1 class="text-center">Evergreen AA</h1> <div class="pswd-recovery"> <h1 class="text-center">Help on the way!</h1> </div> <div class="alert alert-warning"> <p class="center">An email has been sent to your email address to reset your password.</p> </div> <a class="verified" href="login.php">wait at the login screen</a> </div><!-- #landing-content --> </div> </body> <?php require '_includes/footer.php'; ?><file_sep>/new_review_submit.php <?php $layout_context = "manage-update"; require_once 'config/initialize.php'; // off for local testing if (!isset($_SESSION['id'])) { header('location: ' . WWW_ROOT); exit(); } if ((isset($_SESSION['id'])) && (!$_SESSION['verified'])) { header('location: ' . WWW_ROOT); exit(); } $id = $_GET['id']; if (is_post_request()) { $row = []; $row['visible'] = $_POST['visible'] ?? ''; $result = finalize_new_meeting($id, $row); if ($result === true) { header('location: manage.php'); } else { $errors = $result; } } ?><file_sep>/manage.php <?php require_once 'config/initialize.php'; require_once 'config/verify_admin.php'; if ((isset($_SESSION['admin'])) && ($_SESSION['admin'] == 85 || $_SESSION['admin'] == 86)) { header('location: ' . WWW_ROOT); exit(); } if (!isset($_SESSION['id'])) { $_SESSION['message'] = "You need to be logged in to access your Dashboard."; $_SESSION['alert-class'] = "alert-danger"; header('location: ' . WWW_ROOT . '/login.php'); exit(); } if ((isset($_SESSION['id'])) && (!$_SESSION['verified'])) { header('location: ' . WWW_ROOT); exit(); } if (isset($_SESSION['id'])) { $user_id = $_SESSION['id']; $role = $_SESSION['admin']; } $layout_context = "dashboard"; $hide_this = "yep"; $email_opt = $_SESSION['email_opt']; require '_includes/head.php'; ?> <body> <?php if (WWW_ROOT != 'http://localhost/evergreenaa') { ?> <div class="preload-manage"> <p>Loading...</p> </div> <?php } ?> <?php require '_includes/nav.php'; ?> <?php require '_includes/msg-set-timezone.php'; ?> <?php require '_includes/msg-extras.php'; ?> <?php require '_includes/msg-role-key.php'; ?> <img class="background-image" src="_images/aa-logo-dark_mobile.gif" alt="AA Logo"> <div id="manage-wrap"> <div class="manage-simple intro"> <?php if ($role != 1 && $role != 2) { ?> <p>My Dashboard</p> <p>The goal here is simple - make AA meetings available 24-7-365. Let's connect people and save lives. <?php } else if ($role == 1) { ?> <p>The Bob's Dashboard</p> <?php } else { ?> <p>My Dashboard</p> <?php } ?> <?php $any_meetings_for_user = find_meetings_for_manage_page($user_id); $result = mysqli_num_rows($any_meetings_for_user); // find out if user has any meetings they manage ?> <form id="emailopt-form" class="email-updates"> <input type="hidden" name="email-updates" value="0"> <input type="checkbox" name="email-updates" id="email-updates" value="1" <?php if ($email_opt == '1') { echo 'checked'; } ?>> <label for="email-updates" id="opt-inout"><?php if ($email_opt == '1') { echo 'Email updates: Enabled'; } else { echo 'Email updates: OFF'; } ?></label> <div id="email-opt-msg"></div> </form> <?php require '_includes/inner_nav.php'; ?> </div> <a href="manage_new.php" class="new-mtg-btn">Add a new meeting</a> <div class="manage-simple"> <h1 class="my-meet">My Meetings</h1><?php if ($result > 1) { ?> <p class="my-sort">(sorted by time of day)</p> <?php } ?> </div> <ul class="manage-weekdays"> <?php if ($result > 0) { ?> <?php // if user has meetings to manage, display them in order: Day > time, starting with Sun ?> <?php while ($row = mysqli_fetch_assoc($any_meetings_for_user)) { ?> <?php $time = []; $time['tz'] = $tz; $time['ut'] = $row['meet_time']; $time['sun'] = $row['sun']; $time['mon'] = $row['mon']; $time['tue'] = $row['tue']; $time['wed'] = $row['wed']; $time['thu'] = $row['thu']; $time['fri'] = $row['fri']; $time['sat'] = $row['sat']; list($ct, $sun, $mon, $tue, $wed, $thu, $fri, $sat) = apply_offset_to_edit($time); $row['sun'] = $sun; $row['mon'] = $mon; $row['tue'] = $tue; $row['wed'] = $wed; $row['thu'] = $thu; $row['fri'] = $fri; $row['sat'] = $sat; ?> <?php require '_includes/manage-glance.php'; ?> <div class="weekday-wrap<?php if ('visible' == 0) { echo ' draft-bkg'; } ?>"> <?php require '_includes/meeting-details.php'; ?> </div><!-- .weekday-wrap --> <?php } ?> <?php } else { // user has no meetings to manage echo "<p style=\"margin-top:0.5em;padding:0px 1em;\">When you add a meeting it will display here and wherever else you choose. You can make your meetings public or keep them private. Add a new meeting and give it a try.</p>"; } mysqli_free_result($any_meetings_for_user); ?> </ul><!-- .manage-weekdays --> </div><!-- #manage-wrap --> <?php require '_includes/footer.php'; ?><file_sep>/forgot_password.php <?php $layout_context = "forgot-password"; require_once 'config/initialize.php'; require '_includes/head.php'; ?> <body> <?php if (WWW_ROOT != 'http://localhost/evergreenaa') { ?> <div class="preload"><p>One day at a time.</p></div> <?php } ?> <?php require '_includes/nav.php'; ?> <?php require '_includes/msg-why-join.php'; ?> <img class="background-image" src="_images/aa-logo-dark_mobile.gif" alt="AA Logo"> <div id="landing"> <form action="" method="post"> <h1 class="text-center">Recover your password</h1> <?php if(count($errors) > 0): ?> <div class="alert alert-danger"> <?php foreach($errors as $error): ?> <li><?php echo $error; ?></li> <?php endforeach; ?> </div> <?php endif; ?> <?php if(isset($_SESSION['message'])): ?> <div class="alert <?= $_SESSION['alert-class']; ?>"> <?php echo $_SESSION['message']; unset($_SESSION['message']); unset($_SESSION['alert-class']); ?> </div><!-- .alert --> <?php endif; ?> <div class="pswd-recovery"> <p class="forgot-pswd">Please enter your email address used to create your account and I will help you reset your password.</p> </div> <input type="email" class="text" name="email" placeholder="Enter your email"> <input type="submit" name="forgot-password" class="submit" value="Password recovery"> <p class="btm-p try-again">Think you remembered it? <a class="log" href="login.php">Try again</a></p> </form> </div> </body> <?php require '_includes/footer.php'; ?><file_sep>/reset_password.php <?php $layout_context = "login-page"; require_once 'config/initialize.php'; require '_includes/head.php'; ?> <body> <?php if (WWW_ROOT != 'http://localhost/evergreenaa') { ?> <div class="preload"><p>One day at a time.</p></div> <?php } ?> <?php require '_includes/nav.php'; ?> <?php require '_includes/msg-why-join.php'; ?> <?php require '_includes/msg-role-key.php'; ?> <img class="background-image" src="_images/aa-logo-dark_mobile.gif" alt="AA Logo"> <div id="landing"> <form action="" method="post"> <h1 class="text-center">Reset Your Password</h1> <?php if(count($errors) > 0): ?> <div class="alert alert-danger"> <?php foreach($errors as $error): ?> <li><?php echo $error; ?></li> <?php endforeach; ?> </div> <?php endif; ?> <input id="showPassword" type="<PASSWORD>" class="text" name="password" placeholder="<PASSWORD>"> <input id="showConf" type="<PASSWORD>" class="text" name="passwordConf" placeholder="<PASSWORD> password"> <div class="showpassword-wrap"> <div id="showSignupPass"><i class="far fa-eye"></i> Show Password</div> </div> <input type="submit" name="reset-password-btn" class="submit" value="Reset Password"> </form> </div> </body> <?php require '_includes/footer.php'; ?><file_sep>/_includes/admin-meeting-details.php <?php $emh = rand(10000, 99999); ?> <div class="meeting-details"> <?php /* if (isset($_SESSION['admin']) && $_SESSION['admin'] == "1") { */ ?> <div id="<?= $emh . '_' . $row['id_mtg']; ?>" class="email-host admin-links"> <?php // convert time based on visitor's tz for h4 title of modal // you will convert for host's tz in corresponding processing script // i.e, contact-host-process.php or log-issue-process.php $time = $row['meet_time']; $nt = converted_time($time, $tz); ?> <span data-target="vtz" style="display:none;"><?= $tz; ?></span> <span data-target="mtgtime" style="display:none;"><?= $nt; ?></span> <span data-target="mtgday" style="display:none;"><?= substr(ucfirst($today), 0,3); ?></span> <span data-target="mtgid" style="display:none;"><?= $row['id_mtg']; ?></span> <span data-target="tuid" style="display: none;"><?= $user_id ?></span> <span data-target="ri" style="display:none;"><?= $row['issues']; ?></span> <span data-target="mtgname" style="display:none;"><?php if (strlen($row['group_name']) < 22) { echo trim($row['group_name']); } else { echo trim(substr($row['group_name'], 0,22)) . '...'; } ?></span> <?php if (isset($_SESSION['admin']) && ($_SESSION['admin'] == 1 || $_SESSION['admin'] == 2 || $_SESSION['admin'] == 3)) { ?> <a class="emh-link" data-role="emh" data-id="<?= $emh . '_' . $row['id_mtg']; ?>"><i class="far fa-envelope"></i> <?= $row['username'] . ' &bullet; ' . $row['email'] ?></a> <a data-role="<?php if ((isset($row['idi_user'])) && ($row['idi_user'] == $_SESSION['id'])) { echo 'logissued'; } else { echo 'logissue'; } ?>" data-id="<?= $emh . '_' . $row['id_mtg']; ?>" class="emh-link"><i class="fas fa-exclamation-triangle"></i> Log an issue</a> <?php } else { ?> <a class="emh-link" data-role="emh" data-id="<?= $emh . '_' . $row['id_mtg']; ?>"><i class="far fa-envelope"></i> Email Host</a> <a data-role="<?php if ((isset($row['idi_user'])) && ($row['idi_user'] == $_SESSION['id'])) { echo 'logissued'; } else { echo 'logissue'; } ?>" data-id="<?= $emh . '_' . $row['id_mtg']; ?>" class="emh-link"><i class="fas fa-exclamation-triangle"></i> Log an issue</a> <?php } ?> </div> <?php if ($row['issues'] == 0) { ?> <div id="<?= $emh . '_' . $row['id_mtg'] . '_er'; ?>"></div> <?php } if ($row['issues'] == 1) { ?> <div id="<?= $emh . '_' . $row['id_mtg'] . '_er'; ?>" class="errors-reported">Attention: There has been an issue reported with this meeting that the Host has not addressed yet. If you find the meeting abandoned or any of the links do not work correctly please use the link above, &quot;Log issue&quot; to help keep the information on this site reliable. If 3 issues go unaddressed the meeting will be removed from the site until the necessary corrections are made.</div> <?php } ?> <?php if ($row['issues'] > 1) { ?> <div id="<?= $emh . '_' . $row['id_mtg'] . '_er'; ?>" class="errors-reported">Attention: There have been <?= $row['issues'] ?> issues reported with this meeting that the Host has not addressed yet. If you find the meeting abandoned or any of the links do not work correctly please use the link above, &quot;Log issue&quot; to help keep the information on this site reliable. If 3 issues go unaddressed the meeting will be removed from the site until the necessary corrections are made.</div> <?php } ?> <?php /* } */ ?> <?php if ($row['dedicated_om'] == 0 && $row['meet_phone'] == null && $row['meet_id'] == 0 && $row['meet_pswd'] == null && $row['meet_url'] == null) { } else { ?> <div class="details-left <?php if ($row['meet_url'] != null) { echo "l-stacked"; } ?>"> <?php /* if ($row['dedicated_om'] != 0) { ?><p class="dd-meet">Dedicated Online Meeting</p> } */ ?> <?php if ($row['meet_phone'] != null) { ?> <p class="phone-num01"><i class="fas fa-mobile-alt"></i> <a class="phone" href="tel:<?= "(" .substr($row['meet_phone'], 0, 3).") ".substr($row['meet_phone'], 3, 3)."-".substr($row['meet_phone'],6); ?>"><?= "(" .substr($row['meet_phone'], 0, 3).") ".substr($row['meet_phone'], 3, 3)."-".substr($row['meet_phone'],6); ?></a></p><?php } ?> <?php if ($row['meet_url'] != null) { ?> <p class="zoom-info">Zoom Information</p> <?php } ?> <?php if (($row['meet_id'] != '') && ($row['meet_id'] != 'No ID Necessary')) { ?> <p class="id-num">ID: <input id="<?php if (!isset($ic)) { echo "ic"; } else { echo $ic; } ?>" type="text" value="<?php echo $row['meet_id']; ?>" class="day-values input-copy"></p> <a data-role="ic" data-id="<?php if (!isset($ic)) { echo "ic"; } else { echo $ic; } ?>" class="zoom-id"><i class="far fa-arrow-alt-circle-up"></i> Copy ID</a> <?php } ?> <?php if ($row['meet_pswd'] != null) { ?> <p class="id-num">Password: <input id="<?php if (!isset($ic)) { echo "pc"; } else { echo $pc; } ?>" type="text" value="<?php echo $row['meet_pswd']; ?>" class="day-values input-copyz"></p> <a data-role="pc" data-id="<?php if (!isset($ic)) { echo "pc"; } else { echo $pc; } ?>" class="zoom-id"><i class="far fa-arrow-alt-circle-up"></i> Copy Password</a> <?php } ?> <?php if ($row['meet_url'] != null) { ?> <p><a href="<?= h($row['meet_url']); ?>" class="zoom" target="_blank">JOIN ZOOM: VIDEO</a></p> <?php } ?> </div><!-- .details-left --> <?php } ?> <div class="details-right <?php if ($row['meet_url'] != null) { echo "rt-stacked"; } ?>" <?php if ($row['dedicated_om'] == 0 && $row['meet_phone'] == null && $row['meet_id'] == 0 && $row['meet_pswd'] == null && $row['meet_url'] == null) { echo "style=\"width:100%;\""; } ?>> <?php if ($row['meet_addr'] != null) { ?> <div id="map"> <iframe width="100%" height="180" style="border:0" loading="lazy" allowfullscreen src="https://www.google.com/maps/embed/v1/place?key=<?= MAP_KEY ?> &q=<?= preg_replace( "/\r|\n/", " ", h($row['meet_addr'])); ?>"> </iframe> </div> <?php if (($row['meet_addr'] != null) && ($row['meet_desc'] != null)) { ?> <p style="text-align:center;margin-bottom:1em;"><?= nl2br($row['meet_desc']); ?></p> <?php } else { ?> <p style="text-align:center;margin-bottom:1em;"><?= nl2br($row['meet_addr']); ?></p> <?php } ?> <a class="map-dir" href="https://maps.apple.com/?q=<?= preg_replace( "/\r|\n/", " ", h($row['meet_addr'])); ?>" target="_blank">Directions</a> <?php } ?> <p class="add-info">Additional Information</p> <ul> <?php if ($row['dedicated_om'] != 0) { ?> <li>Dedicated Online Meeting</li> <?php } if ($row['code_o'] != 0) { ?> <li>Open Meeting: Anyone may attend</li> <?php } if ($row['code_w'] != 0) { ?> <li>Women's Meeting</li> <?php } if ($row['code_m'] != 0) { ?> <li>Men's Meeting</li> <?php } if ($row['code_c'] != 0) { ?> <li>Closed Meeting</li> <?php } if ($row['code_beg'] != 0) { ?> <li>Beginner's Meeting</li> <?php } if ($row['code_h'] != 0) { ?> <li>Handicap Accessible</li> <?php } if ($row['code_d'] != 0) { ?> <li>Discussion</li> <?php } if ($row['code_b'] != 0) { ?> <li>Book Study</li> <?php } if ($row['code_ss'] != 0) { ?> <li>Step Study: We discuss the 12 steps</li> <?php } if ($row['code_sp'] != 0) { ?> <li>Speaker Meeting</li> <?php } if ($row['month_speaker'] != 0) { ?> <li>Speaker Meeting on last Sunday of month</li> <?php } if ($row['potluck'] != 0) { ?> <li>Potluck</li> <?php } ?> </ul> </div><!-- .details-right --> <?php if ($row['link1'] != '' || $row['link2'] != '' || $row['link3'] != '' || $row['link4'] != '') { ?> <div id="upload-links"> <p class="mtg-files">Meeting files</p> <?php if ($row['link1'] != '') { ?><a href="<?= WWW_ROOT ?>/uploads/<?= h(($row['file1'])) ?>" class="mtg-links" target="_blank"><?= h(($row['link1'])) ?></a><?php } ?> <?php if ($row['link2'] != '') { ?><a href="<?= WWW_ROOT ?>/uploads/<?= h(($row['file2'])) ?>" class="mtg-links" target="_blank"><?= h(($row['link2'])) ?></a><?php } ?> <?php if ($row['link3'] != '') { ?><a href="<?= WWW_ROOT ?>/uploads/<?= h(($row['file3'])) ?>" class="mtg-links" target="_blank"><?= h(($row['link3'])) ?></a><?php } ?> <?php if ($row['link4'] != '') { ?><a href="<?= WWW_ROOT ?>/uploads/<?= h(($row['file4'])) ?>" class="mtg-links" target="_blank"><?= h(($row['link4'])) ?></a><?php } ?> </div> <?php } ?> <?php if($row['add_note'] != null) { ?><div id="add-note"><p><?= nl2br(h($row['add_note'])) ?></p></div><?php } ?> </div><!-- .meeting-details --><file_sep>/under-construction.php <?php // turn on & off in initialize.php $layout_context = "login-page"; require_once 'config/initialize.php'; include '_includes/head.php'; ?> <body> <img class="background-image" src="_images/aa-logo-dark_mobile.gif" alt="AA Logo"> <div id="landing"> <div class="uc-page"> <p>Saturday, October 16 at 1:51 PM Mountain Time</p> <p>Implementing a major update at the moment. The site will be down for about an hour. Sorry for any inconvenience.</p> </div> </div><!-- #landing --> </body> <?php require '_includes/footer.php'; ?> <?php exit() ?> <file_sep>/signup.php <?php $layout_context = "login-page"; ?> <?php require_once 'config/initialize.php'; ?> <?php include '_includes/head.php'; ?> <body> <?php require '_includes/nav.php'; ?> <?php require '_includes/msg-why-join.php'; ?> <img class="background-image" src="_images/aa-logo-dark_mobile.gif" alt="AA Logo"> <div id="landing"> <form action="" method="post"> <h1 class="text-center">Join here</h1> <?php if(count($errors) > 0): ?> <div class="alert alert-danger"> <?php foreach($errors as $error): ?> <li><?php echo $error; ?></li> <?php endforeach; ?> </div> <?php endif; ?> <input type="text" class="text" name="username" value="<?= h($username); ?>" placeholder="Username"> <input type="email" class="text" name="email" value="<?= h($email); ?>" placeholder="Email address" required> <input type="<PASSWORD>" id="showPassword" class="text" name="password" placeholder="<PASSWORD>"> <input type="<PASSWORD>" id="showConf" class="text" name="passwordConf" placeholder="<PASSWORD>"> <div class="showpassword-wrap"> <div id="showSignupPass"><i class="far fa-eye"></i> Show Passwords</div> </div> <input type="submit" name="submit" class="submit" value="Sign up"> <p class="btm-p">Already a member? <a class="log" href="login.php">Sign in</a></p> </form> </div><!-- #landing --> </body> <?php require '_includes/footer.php'; ?><file_sep>/index.php <?php require_once 'config/initialize.php'; $layout_context = "login-page"; if (isset($_GET['token'])) { $token = $_GET['token']; verifyUser($token); } if (isset($_GET['password-token'])) { $passwordToken = $_GET['password-token']; resetPassword($passwordToken); } if (!isset($_SESSION['verified'])) { require 'home.php'; exit; } if (isset($_SESSION['mode']) && $_SESSION['mode'] == 1) { require 'home_admin.php'; exit; } if (((isset($_SESSION['verified']) && ($_SESSION['verified'] != "0")) && (!isset($_SESSION['message'])))) { require 'home_private.php'; exit; } include '_includes/head.php'; ?> <body> <?php if (WWW_ROOT != 'http://localhost/evergreenaa') { ?> <div class="preload"><p>One day at a time.</p></div> <?php } ?> <?php require '_includes/nav.php'; ?> <?php require '_includes/msg-why-join.php'; ?> <img class="background-image" src="_images/aa-logo-dark_mobile.gif" alt="AA Logo"> <div id="landing"> <div id="landing-content"> <?php if(isset($_SESSION['message'])): ?> <div class="alert <?= $_SESSION['alert-class']; ?>"> <?php echo $_SESSION['message']; unset($_SESSION['message']); unset($_SESSION['alert-class']); ?> </div><!-- .alert --> <?php endif; ?> <h1 class="welcome">Welcome<?php if (isset($_SESSION['username'])) { echo ' ' . h($_SESSION['username']) . ','; } else { echo ','; } ?></h1> <?php if(!$_SESSION['verified']): ?> <div class="alert new-member"> <p>Check your email and click on the link verification that was sent to: <span class="yo-email"><?= $_SESSION['email']; ?></span></p> <p>It could take up to 2 minutes. Check Spam, Junk, etc. if you don't see it.</p> <p>&nbsp;</p> <p>If you think you are seeing this message in error...</p> <a class="verified" href="login.php">try to log in</a> </div> <?php endif; ?> <?php if($_SESSION['verified']): ?> <a class="verified" href="<?= WWW_ROOT ?>">Let me in already!</a> <?php endif; ?> </div><!-- #landing-content --> </div><!-- #landing --> </body> <?php require '_includes/footer.php'; ?><file_sep>/message-board.php <?php require_once 'config/initialize.php'; // require_once 'config/verify_admin.php'; $layout_context = 'message-board'; if (isset($_SESSION['id'])) { $user_id = $_SESSION['id']; $user_role = $_SESSION['admin']; } require '_includes/head.php'; ?> <body> <?php if (WWW_ROOT != 'http://localhost/evergreenaa') { ?> <div class="preload"> <p>One question at a time.</p> <i class="far fa-smile"></i> </div> <?php } ?> <?php require '_includes/nav.php'; ?> <?php require '_includes/msg-set-timezone.php'; ?> <?php require '_includes/msg-why-join.php'; ?> <?php require '_includes/msg-mb-notes.php'; ?> <?php require '_includes/msg-extras.php'; ?> <?php require '_includes/msg-role-key.php'; ?> <img class="background-image" src="_images/message-board-mobile.jpg" alt="AA Logo"> <div id="wrap"> <div id="mb-wrap"> <h1>All Posts</h1> <div class="new-topic"> <?php if (isset($_SESSION['id'])) { ?> <a data-role="mb">Start a new topic</a> <a id="toggle-mb-notes" class="pnd">Privacy &amp; Decorum</a> <?php } else { ?> <a id="toggle-gottajoin">Start a new topic</a> <a id="toggle-mb-notes" class="pnd">Privacy &amp; Decorum</a> <?php } ?> </div> <ul id="post-topics"><?php /* magic */ ?></ul> </div><!-- #mb-wrap --> </div><!-- #wrap --> <script> $(document).ready(function() { $('#post-topics').load('load-message-board.php'); setInterval(function() { $('#post-topics').load('load-message-board.php'); }, 3000); }); </script> <?php require '_includes/footer.php'; ?> <file_sep>/controllers/emailController-online-backup-0225231108.php <?php // Import PHPMailer classes into the global namespace // These must be at the top of your script, not inside a function use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\SMTP; use PHPMailer\PHPMailer\Exception; require_once 'vendor/autoload.php'; require_once 'config/constants.php'; function sendVerificationEmail($username, $userEmail, $token) { $mail = new PHPMailer(true); try { $mail->Host = 'localhost'; $mail->SMTPAuth = false; $mail->Username = EMAIL; $mail->Password = <PASSWORD>; //Recipients $mail->setFrom(EMAIL, 'Evergreen AA Website'); $mail->addAddress($userEmail, $username); // Add a recipient $mail->addReplyTo($userEmail); // $mail->addCC('<EMAIL>'); $mail->addBCC('<EMAIL>'); // Content $mail->isHTML(true); $mail->Subject = 'Verify Your EvergreenAA Registration'; $mail->Body = '<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Verify EvergreenAA.com Registration</title> <style> body { font-size: 16px; color: #313131; font-family: Verdana, Tahoma, Calbri, Arial, sans-serif; } .wrapper { padding: 1.5em; font-size: 1em; } </style> </head> <body> <div class="wrapper"> <p>Hello ' . $username . ',</p> <p>Welcome to this neat project!</p> <p>EvergreenAA.com provides a convenient outlet to consolidate, organize, publish and edit your meeting information. Whether you maintain this information for your own private use or make it available to everyone is up to you.</p> <p><a style="color:#0000ff;text-decoration:underline;" href="https://www.evergreenaa.com/index.php?token=' . $token . '">Click here</a> to verify your email address (or use copy &amp; paste option below).</p> <p>If you encounter issues with the site or have feature requests please email me anytime. There is a contact form at the bottom of every page labeled, "comments | questions | suggestions".</p> <p>Sincerely,<br> <NAME><br> <EMAIL></p> <p><u>Copy &amp; paste verification URL</u>:<br> https://www.evergreenaa.com/index.php?token=' . $token . ' </div> </body> </html>'; $mail->AltBody = 'Hello ' . $username . ', Please copy and paste this verification link into your browser address bar to validate your EvergreenAA.com registration: https://www.evergreenaa.com/index.php?token=' . $token; $mail->send(); } catch (Exception $e) { echo "Email verification ran into a server error. This is no bueno and brings shame to my family. If you are so inclined, please copy and paste this message into an email to: <EMAIL> -- Mailer Error: {$mail->ErrorInfo}"; } } function sendPasswordResetLink($userEmail, $token) { $mail = new PHPMailer(true); try { $mail->Host = 'localhost'; $mail->SMTPAuth = false; $mail->Username = EMAIL; $mail->Password = <PASSWORD>; //Recipients $mail->setFrom(EMAIL, 'Evergreen AA Website'); $mail->addAddress($userEmail); // Add a recipient $mail->addReplyTo($userEmail); // $mail->addCC('<EMAIL>'); $mail->addBCC('<EMAIL>'); // Content $mail->isHTML(true); $mail->Subject = 'Reset Your EvergreenAA Password'; $mail->Body = '<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Reset EvergreenAA.com Password</title> <style> .wrapper { padding: 20px; color: #444; font-size: 1.3em; } a { background-color: #2c496a; text-decoration: none; padding: 8px 15px; border-radius: 5px; color: #fff; } a:hover { background-color: #9bafc6; color: #313131; } </style> </head> <body> <div class="wrapper"> <p>Hello,</p> <p>A request has been made to change the password on your account at EvergreenAA.com. If you did not request this change you can ignore this message.</p> <p>Please click on the link below to reset your password.</p> <p><a style="padding:5px 8px;border-radius:3px;background-color:#2c496a;color:#fff;margin:0.5em 0em 0.5em;text-decoration:none;" href="https://www.evergreenaa.com/index.php?password-token=' . $token . '">Click here</a> to reset your password.</p> <p>Sincerely,<br><NAME></p> </div> </body> </html>'; $mail->AltBody = 'Hello, A request has been made to change the password on your account at EvergreenAA.com. If you did not request this change you can ignore this message. If you did make this request, please copy and paste this link into your browser address bar to reset your password: https://www.evergreenaa.com/index.php?password-token=' . $token; $mail->send(); } catch (Exception $e) { echo "Password reset reqest ran into a server error. This is no bueno and brings shame to my family. If you are so inclined, please copy and paste this message into an email to: <EMAIL> -- Mailer Error: {$mail->ErrorInfo}"; } } function email_everyone_BCC($msgsubject, $email_addresses, $message) { $mail = new PHPMailer(true); try { $mail->Host = 'localhost'; $mail->SMTPAuth = false; $mail->Username = EMAIL; $mail->Password = <PASSWORD>; //Recipients $mail->setFrom(EMAIL, 'EvergreenAA Website'); $mail->addBCC($email_addresses); // $mail->addBCC('<EMAIL>'); // Content $mail->isHTML(true); $mail->Subject = $msgsubject; $mail->Body = $message; $mail->send(); } catch (Exception $e) { echo "You hit a snag. Messages did not send. -- Mailer Error: {$mail->ErrorInfo}"; } } function email_everyone_PERSONAL($msgsubject, $send_to, $message) { $mail = new PHPMailer(true); try { $mail->Host = 'localhost'; $mail->SMTPAuth = false; $mail->Username = EMAIL; $mail->Password = <PASSWORD>; //Recipients $mail->setFrom(EMAIL, 'EvergreenAA Website'); $mail->addAddress($send_to); // Add a recipient $mail->addReplyTo($send_to); // $mail->addAddress('<EMAIL>'); // $mail->addReplyTo('<EMAIL>'); // Content $mail->isHTML(true); $mail->Subject = $msgsubject; $mail->Body = $message; $mail->send(); } catch (Exception $e) { echo "You hit a snag. Messages did not send. -- Mailer Error: {$mail->ErrorInfo}"; } } ?><file_sep>/user_role.php <?php require_once 'config/initialize.php'; require_once 'config/verify_admin.php'; // you can only manage users if you're Admin 1 or 3 if ($_SESSION['admin'] != 1 && $_SESSION['admin'] != 3) { header('location: ' . WWW_ROOT); exit(); } $layout_context = "alt-manage"; $id = $_GET['user']; $role = $_SESSION['admin']; if ($id != 1 && ($id == '' || $id == $_SESSION['id'])) { header('location: ' . WWW_ROOT); exit(); } $row = get_user_by_id($id); require '_includes/head.php'; ?> <body> <?php if (WWW_ROOT != 'http://localhost/evergreenaa') { ?> <div class="preload-manage"> <p>Loading...</p> </div> <?php } ?> <?php require '_includes/nav.php'; ?> <?php require '_includes/msg-set-timezone.php'; ?> <?php require '_includes/msg-extras.php'; ?> <?php require '_includes/msg-role-key.php'; ?> <img class="background-image" src="_images/aa-logo-dark_mobile.gif" alt="AA Logo"> <div id="host-manage-wrap"> <div class="manage-simple intro"> <?php require '_includes/inner_nav.php'; ?> </div> <?php if ($_SESSION['admin'] == 1 || $_SESSION['admin'] == 3) { ?> <?php if ($id == 1) { ?> <h2 id="role-h2" class="demote">Nope</h2> <?php } else if ($row['admin'] == 85 || $row['admin'] == 86) { ?> <h2 id="role-h2" class="change-role">Reinstate User</h2> <?php } else if ($row['admin'] == 0 || $row['admin'] == 2) { ?> <h2 id="role-h2" class="change-role">Manage User</h2> <?php } else if ($_SESSION['admin'] != 1 && ($row['admin'] == 1 || $row['admin'] == 3)) { ?> <h2 id="role-h2" class="demote">Top Tier Admin are off limits</h2> <?php } else { ?> <h2 id="role-h2" class="demote">Demote Admin</h2> <?php } ?> <div id="transfer-host"> <p id="current-role" class="current-role"><?php if ($row['admin'] == 0) { ?> Member <?php } else if ($row['admin'] == 1) { ?> Bob's stuff <?php } else if ($row['admin'] == 2) { ?> Level II Administrator <?php } else if ($row['admin'] == 85) { ?> Suspended: Meetings remain active <?php } else if ($row['admin'] == 86) { ?> Suspended: Meetings set to Draft <?php } else { ?> Top Tier Administrator <?php } ?> </p> <?php if ($id == 1) { ?> <p class="bob-1">Bob</p> <?php } else { ?> <p class="th-un">Username: <?= $row['username'] ?></p> <p class="th-em">Email: <?= $row['email'] ?></p> <?php } ?> <?php if ($_SESSION['admin'] == 1 || ($row['admin'] != 1 && $row['admin'] != 3)) { ?> <form id="suspend-form"> <div class="radio-groupz"> <?php if ($id == 1) { ?> <div class="radio-bob"> No way, José. </div> <?php } else if ($id == $_SESSION['id']) { ?> <div class="radio-bob"> Read the text below... </div> <?php } else { ?> <?php if ($_SESSION['admin'] == 1 && ($row['admin'] == 0 || $row['admin'] == 2 || $row['admin'] == 85 || $row['admin'] == 86)) { // just me ?> <div class='radioz' value="3"> Upgrade <?= $row['username'] . ' to ADMIN priviliges: TOP TIER <br> [ Manage Users + Edit + Transfer + Delete : All meetings]' ?> </div> <?php } ?> <?php if ($_SESSION['admin'] == 1 && $row['admin'] == 3) { // just me ?> <div class='radioz' value="2"> Downgrade <?= $row['username'] . ' to Level II Admin <br> [ Edit + Transfer : All meetings]' ?> </div> <div class='radioz' value="0"> Downgrade <?= $row['username'] . ' to Member' ?> </div> <?php } ?> <?php /* if ($_SESSION['admin'] == 1 && $row['admin'] == 3) { // just me ?> <div class='radioz' value="3"> Upgrade <?= $row['username'] . ' ADMIN priviliges: TOP TIER <br> [ Manage Users + Edit + Transfer + Delete : All meetings]' ?> </div> <?php } */ ?> <?php if (($_SESSION['admin'] == 1 || $_SESSION['admin'] == 3) && $row['admin'] == 2) { ?> <?php /* me + Top Tier can downgrade Level II Admin to Member */ ?> <div class='radioz' value="0"> Downgrade <?= $row['username'] . ' to Member' ?> </div> <?php } ?> <?php if ($row['admin'] != 1 && $row['admin'] != 2 && $row['admin'] != 3) { ?> <?php /* user is currently Member or suspended */ ?> <?php if ($row['admin'] == 0) { // user is Member ?> <div class='radioz' value="2"> Grant <?= $row['username'] . ' ADMIN priviliges: Level II <br> [ Edit + Transfer : All meetings]' ?> </div> <?php } else { // user is suspended ?> <?php /* <div class='radioz' value="3"> Reinstate <?= $row['username'] . ' with ADMIN priviliges: TOP TIER <br> [ Manage Users + Edit + Transfer + Delete : All meetings]' ?> </div> */ ?> <div class='radioz' value="2"> Reinstate <?= $row['username'] . ' with ADMIN priviliges: Level II <br> [ Edit + Transfer : All meetings]' ?> </div> <div class='radioz' value="0"> Reinstate <?= $row['username'] . ' as Member' ?> </div> <?php } ?> <?php } ?> <?php if ($row['admin'] != 85 && $row['admin'] != 86) { ?> <div class='radioz' value="85"> Suspend <?= $row['username'] ?> but KEEP meetings </div> <div class='radioz' value="86"> Suspend <?= $row['username'] ?> and REMOVE meetings [Draft] </div> <?php } ?> <?php } ?> <?php /* grab value and put it into hidden field to submit */ ?> <input type="hidden" name="admin"> <input type="hidden" name="mode" value="<?= $row['mode'] ?>"> </div> <input type="hidden" name="user" value="<?= $row['id_user'] ?>"> <div id="sus-reason"> <p>Reason</p><textarea id="sus-note" name="reason" maxlength="250"><?php if ($row['sus_notes'] != '') { echo $row['sus_notes']; } ?></textarea> </div> </form> <?php } ?> <div id="sus-msg"></div> <div id="whoops"></div> <div id="th-btn"> <?php if ($id == 1) { // me ?> <a id="not-yourself" class="not-odin">Bob's stuff is off limits</a> <?php } else if ($_SESSION['id'] != 1 && $row['admin'] == 3) { // someone trying to work on Top Tier other than me ?> <a id="not-yourself" class="not-odin">Off limits</a> <?php } else if ($id == $_SESSION['id']) { // they changed the $_GET in url to their # ?> <a id="not-yourself">Don't play with yourself</a> <?php } else { ?> <div id="gdtrfb"> <a id="select-role-first">Select a User Role</a> </div> <?php } ?> </div> </div> <h1 class="usr-role-mtg"><?= $row['username'] . '\'s ' ?>Meetings</h1> <?php $users_mtgs = find_meetings_for_manage_page($id); $mtg_found = mysqli_num_rows($users_mtgs); ?> <ul class="manage-weekdays"> <?php if ($mtg_found > 0) { ?> <?php // if user has meetings to manage, display them in order: Day > time, starting with Sun ?> <?php while ($row = mysqli_fetch_assoc($users_mtgs)) { ?> <?php $time = []; $time['tz'] = $tz; $time['ut'] = $row['meet_time']; $time['sun'] = $row['sun']; $time['mon'] = $row['mon']; $time['tue'] = $row['tue']; $time['wed'] = $row['wed']; $time['thu'] = $row['thu']; $time['fri'] = $row['fri']; $time['sat'] = $row['sat']; list($ct, $sun, $mon, $tue, $wed, $thu, $fri, $sat) = apply_offset_to_edit($time); $row['sun'] = $sun; $row['mon'] = $mon; $row['tue'] = $tue; $row['wed'] = $wed; $row['thu'] = $thu; $row['fri'] = $fri; $row['sat'] = $sat; ?> <?php require '_includes/manage-glance.php'; ?> <div class="weekday-wrap<?php if ('visible' == 0) { echo ' draft-bkg'; } ?>"> <?php require '_includes/meeting-details.php'; ?> </div><!-- .weekday-wrap --> <?php } ?> <?php } else { // user has no meetings to manage echo '<p style="margin-top:0.5em;padding:0px 1em;">'. $row['username'] .' does not have any meetings.</p>'; } mysqli_free_result($users_mtgs); ?> </ul><!-- .manage-weekdays --> <?php } else { echo "<p style=\"margin:1.5em 0 0 1em;\">How'd you get this far?</p>"; } ?> </div><!-- #manage-wrap --> <?php require '_includes/footer.php'; ?><file_sep>/user_management.php <?php require_once 'config/initialize.php'; require_once 'config/verify_admin.php'; if (!isset($_SESSION['mode']) || ($_SESSION['mode'] != 1 || ($_SESSION['admin'] != 1 && $_SESSION['admin'] != 3))) { header('location: ' . WWW_ROOT); exit(); } $layout_context = "um"; if (!isset($_SESSION['id'])) { $_SESSION['message'] = "You need to be logged in to access that page."; $_SESSION['alert-class'] = "alert-danger"; header('location: ' . WWW_ROOT . '/login.php'); exit(); } if ((isset($_SESSION['id'])) && (!$_SESSION['verified'])) { header('location: ' . WWW_ROOT); exit(); } $user_id = $_SESSION['id']; $role = $_SESSION['admin']; require '_includes/head.php'; ?> <body> <?php if (WWW_ROOT != 'http://localhost/evergreenaa') { ?> <div class="preload-manage"> <p>Loading...</p> </div> <?php } ?> <?php require '_includes/nav.php'; ?> <?php require '_includes/msg-set-timezone.php'; ?> <?php require '_includes/msg-extras.php'; ?> <?php require '_includes/msg-role-key.php'; ?> <img class="background-image" src="_images/aa-logo-dark_mobile.gif" alt="AA Logo"> <div id="manage-wrap"> <div class="manage-simple intro"> <?php if ($role == 1) { ?> <p>My User Management</p> <?php } else { ?> <p><?= ' ' . $_SESSION['username'] . '\'s User Management' ?></p> <?php } ?> <?php require '_includes/inner_nav.php'; ?> </div> <?php if ($role == 1 || $role == 3) { ?> <?php // dropdown list of users for admin $user_management_list = find_all_users_to_manage($user_id); $users = mysqli_num_rows($user_management_list); $results = mysqli_fetch_all($user_management_list, MYSQLI_ASSOC); if ($users > 0) { ?> <div class="tabs ump"> <ul class="tab-links"> <li class="focus"><a href="#tab1">Username</a></li> <li><a href="#tab2">Email</a></li> <li><a href="#tab3">Joined</a></li> </ul> <div class="tab-content"> <div id="tab1"> <div class="user-box"> <p>Select a user by their Username</p> <form id="user-list"> <select id="mng-usr" class="transfer-usr" name="transfer-usr"> <option value="empty">Select by Username</option> <?php foreach ($results as $li) { $user = ($li['id_user']); $username = ($li['username']); $email = ($li['email']); ?> <option value="<?php echo WWW_ROOT . '/user_role.php?user=' . $user . ',' . $email; ?>"><?= $username; ?></option> <?php } ?> <input type="hidden" id="uem"> </select> <a id="usr-role-go">GO</a> </form> </div> <div id="um-email-top"></div> </div> <div id="tab2"> <div class="user-box"> <p>Select a user by their email address</p> <form id="user-listz"> <select id="mng-usrz" class="transfer-usr" name="transfer-usr"> <option value="empty">Select by Email</option> <?php function cmp($results, $key) { foreach($results as $k=>$v) { $b[] = strtolower($v[$key]); } asort($b); foreach ($b as $k=>$v) { $c[] = $results[$k]; } return $c; } $sorted = cmp($results, 'email'); ?> <?php /* <pre><?php print_r($sorted); ?></pre> */ ?> <?php foreach ($sorted as $li) { $user = ($li['id_user']); $username = ($li['username']); $email = ($li['email']); ?> <option value="<?php echo WWW_ROOT . '/user_role.php?user=' . $user . ',' . $username; ?>"><?= strtolower($email); ?></option> <?php } ?> </select> <a id="usr-role-goz">GO</a> </form> </div> <div id="um-un-btm"></div> </div> <div id="tab3"> <div class="user-box"> <p>Select a user by date joined</p> <form id="user-listzz"> <select id="mng-usrzz" class="transfer-usr" name="transfer-usr"> <option value="empty">Select by Date Joined</option> <?php function cmpz($results, $key) { foreach($results as $k=>$v) { $b[] = strtolower($v[$key]); } foreach ($b as $k=>$v) { $c[] = $results[$k]; } rsort($c); return $c; } $sorted2 = cmpz($results, 'id_user'); ?> <?php /* <pre><?php print_r($sorted); ?></pre> */ ?> <?php foreach ($sorted2 as $li) { $joined = ($li['joined']); $user = ($li['id_user']); $username = ($li['username']); $email = ($li['email']); ?> <option value="<?php echo WWW_ROOT . '/user_role.php?user=' . $user . ',' . $username . ',' . $email; ?>"><?= date('m.d.y H:i', strtotime($joined)) . ' | ' . strtolower($username); ?></option> <?php } ?> </select> <a id="usr-role-gozz">GO</a> </form> </div> <div id="um-un-btmz"></div> <p class="btm">Listed in order of most recently joined. I figured it would be useful if you ever need to find someone who just joined and is doing stupid stuff on the site but you don't have time to look for something they've posted in order to get to them that way.</p> </div> </div><?php /* .tab-content */ ?> </div> <?php } mysqli_free_result($user_management_list); ?> <?php } ?> <?php /* -------------------- SUSPENDED USERS -------------------- */ ?> <div class="manage-simple s-a"> <?php $any_meetings_for_user = user_manage_page_glance(); $suspended_users = mysqli_num_rows($any_meetings_for_user); ?> <h1>Suspended Users</h1> </div> <ul class="manage-weekdays"> <?php if ($suspended_users > 0) { $i = 1; while ($row = mysqli_fetch_assoc($any_meetings_for_user)) { $suspended_id = $row['id_user']; ?> <?php require '_includes/user-management-user-glance.php'; ?> <?php $suspended_users_meetings = user_manage_page_details($suspended_id); $suspended_users = mysqli_num_rows($suspended_users_meetings); if ($suspended_users > 0) { ?> <div class="weekday-wrap user-mng"> <div class="notes-glance"> <span class="reason-header"> <p class="reason-note">Reason for suspension</p> <span id="a_<?= $i ?>" class="ricons"> <a data-id="<?= $i ?>" data-role="rnote" class="reason-note rt eicon"><div class="tooltip right"> <span class="tooltiptext type">Edit Note</span><i class="far fa-edit"></i></div></a> </span> </span> <div id="error_<?= $i ?>"></div> <div id="<?= $i ?>" class="note-reason"><?= $row['sus_notes'] ?></div> <div id="on_<?= $i ?>" style="display:none;"><?= $row['sus_notes'] ?></div> <div id="uid_<?= $i ?>" style="display:none;"><?= $row['id_user'] ?></div> <div id="round2_<?= $i ?>" style="display:none;"></div> </div> <?php while ($rowz = mysqli_fetch_assoc($suspended_users_meetings)) { ?> <?php require '_includes/user-management-user-meetings.php'; ?> <?php } ?> </div><!-- .weekday-wrap --> <?php } else { ?> <div class="weekday-wrap user-mng user-empty"> <div class="notes-glance"> <span class="reason-header"> <p class="reason-note">Reason for suspension</p> <span id="a_<?= $i ?>" class="ricons"> <a data-id="<?= $i ?>" data-role="rnote" class="reason-note rt eicon"><div class="tooltip right"> <span class="tooltiptext type">Edit Note</span><i class="far fa-edit"></i></div></a> </span> </span> <div id="error_<?= $i ?>"></div> <div id="<?= $i ?>" class="note-reason"><?= $row['sus_notes'] ?></div> <div id="on_<?= $i ?>" style="display:none;"><?= $row['sus_notes'] ?></div> <div id="uid_<?= $i ?>" style="display:none;"><?= $row['id_user'] ?></div> <div id="round2_<?= $i ?>" style="display:none;"></div> </div> <p style="margin-top:1em;padding:0.5em 1em;">This user has no meetings for public view.</p> </div><!-- .weekday-wrap --> <?php } ?> <?php $i++; } // end while loop ?> <?php } else { // user has no meetings to manage echo "<p style=\"margin-top:0.5em;padding:0px 1em;\">There are no members currently suspended.</p>"; } mysqli_free_result($suspended_users_meetings); mysqli_free_result($any_meetings_for_user); ?> </ul><!-- .manage-weekdays --> <?php /* -------------------- CURRENT ADMINISTRATORS -------------------- */ ?> <div class="manage-simple c-a"> <?php $any_meetings_for_admin = find_users_for_admin_glance(); $administrators = mysqli_num_rows($any_meetings_for_admin); $ca = ''; // set just to use in this block ?> <h1>Current Administrators</h1> </div> <ul class="manage-weekdays"> <?php if ($administrators > 0) { while ($row = mysqli_fetch_assoc($any_meetings_for_admin)) { $userz_id = $row['id_user']; ?> <?php require '_includes/user-management-user-glance.php'; ?> <?php $admin_meetings = user_manage_page_details($userz_id); $resultz = mysqli_num_rows($admin_meetings); if ($resultz > 0) { ?> <div class="weekday-wrap user-mng"> <?php while ($rowz = mysqli_fetch_assoc($admin_meetings)) { ?> <?php require '_includes/user-management-user-meetings.php'; ?> <?php } ?> </div><!-- .weekday-wrap --> <?php } else { ?> <div class="weekday-wrap user-mng user-empty"> <p>This user has no meetings for public view.</p> </div><!-- .weekday-wrap --> <?php } ?> <?php mysqli_free_result($admin_meetings); ?> <?php } ?> <?php } else { // user has no meetings to manage echo "<p style=\"margin-top:0.5em;padding:0px 1em;\">There are no Administrators other than you.</p>"; } mysqli_free_result($any_meetings_for_admin); ?> </ul><!-- .manage-weekdays --> </div><!-- #manage-wrap --> <?php require '_includes/footer.php'; ?><file_sep>/process-delete-mb-post.php <?php require_once 'config/initialize.php'; require_once 'config/verify_admin.php'; if (is_post_request()) { if (isset($_POST['post-id'])) { $row = []; if ($_SESSION['admin'] == 1 || $_SESSION['admin'] == 2 || $_SESSION['admin'] == 3) { // let admin delete this $row['id_user'] = $_POST['uid']; } else { $row['id_user'] = $_SESSION['id']; } $row['id_topic'] = $_POST['post-id']; $result = delete_post($row); if ($result === true) { $signal = 'ok'; $msg = 'Transfer successful!'; } else { $signal = 'bad'; $msg = 'That didn\'t work. I\'ve got no more information for you either. Maybe restart your browser and try it again?'; } } else { $signal = 'bad'; $msg = 'not getting post array...?!'; } } $data = array( 'signal' => $signal, 'msg' => $msg ); echo json_encode($data); // stop <file_sep>/manage_edit.php <?php require_once 'config/initialize.php'; require_once 'config/verify_admin.php'; $layout_context = "alt-manage"; if ($_SESSION['admin'] == 85 || $_SESSION['admin'] == 86) { header('location: ' . WWW_ROOT); exit(); } if (!isset($_SESSION['id'])) { header('location: ' . WWW_ROOT); exit(); } if ((isset($_SESSION['id'])) && (!$_SESSION['verified'])) { header('location: ' . WWW_ROOT); exit(); } $id = $_GET['id']; // If validation fails -> this page is rendered if (is_post_request()) { $rando_num = rand(100,999); $row = []; // if everything's good: file selected + label present if (!empty($_FILES['file1']['name'])) { $uploaded_file1 = $_FILES['file1']['name']; $uploaded_size1 = $_FILES['file1']['size']; $ext1 = strtolower(pathinfo($uploaded_file1, PATHINFO_EXTENSION)); $rename1 = $_SESSION['id'] . '_' . date('mdYHi') . '_01_' . $rando_num; $nf1 = $rename1 . '.' . $ext1; $fn1 = $_FILES['file1']['tmp_name']; } // whoops, they added a label but no file to upload or in hidden field (they're not renaming) if ((empty($_FILES['file1']['name'])) && (isset($_POST['hid_f1']) && isset($_POST['link1']))) { $nf1 = $_POST['hid_f1']; $fn1 = ''; } // to catch no file/label OR if they deleted the the label then delete the file reference too if ((empty($_FILES['file1']['name'])) && (!isset($_POST['hid_f1']) && !isset($_POST['link1']))) { $nf1 = ''; $fn1 = ''; } if (!empty($_FILES['file2']['name'])) { $uploaded_file2 = $_FILES['file2']['name']; $uploaded_size2 = $_FILES['file2']['size']; $ext2 = strtolower(pathinfo($uploaded_file2, PATHINFO_EXTENSION)); $rename2 = $_SESSION['id'] . '_' . date('mdYHi') . '_02_' . $rando_num; $nf2 = $rename2 . '.' . $ext2; $fn2 = $_FILES['file2']['tmp_name']; } if ((empty($_FILES['file2']['name'])) && (isset($_POST['hid_f2']) && isset($_POST['link2']))) { $nf2 = $_POST['hid_f2']; $fn2 = ''; } if ((empty($_FILES['file2']['name'])) && (!isset($_POST['hid_f2']) && !isset($_POST['link2']))) { $nf2 = ''; $fn2 = ''; } if (!empty($_FILES['file3']['name'])) { $uploaded_file3 = $_FILES['file3']['name']; $uploaded_size3 = $_FILES['file3']['size']; $ext3 = strtolower(pathinfo($uploaded_file3, PATHINFO_EXTENSION)); $rename3 = $_SESSION['id'] . '_' . date('mdYHi') . '_03_' . $rando_num; $nf3 = $rename3 . '.' . $ext3; $fn3 = $_FILES['file3']['tmp_name']; } if ((empty($_FILES['file3']['name'])) && (isset($_POST['hid_f3']) && isset($_POST['link3']))) { $nf3 = $_POST['hid_f3']; $fn3 = ''; } if ((empty($_FILES['file3']['name'])) && (!isset($_POST['hid_f3']) && !isset($_POST['link3']))) { $nf3 = ''; $fn3 = ''; } if (!empty($_FILES['file4']['name'])) { $uploaded_file4 = $_FILES['file4']['name']; $uploaded_size4 = $_FILES['file4']['size']; $ext4 = strtolower(pathinfo($uploaded_file4, PATHINFO_EXTENSION)); $rename4 = $_SESSION['id'] . '_' . date('mdYHi') . '_04_' . $rando_num; $nf4 = $rename4 . '.' . $ext4; $fn4 = $_FILES['file4']['tmp_name']; } if ((empty($_FILES['file4']['name'])) && (isset($_POST['hid_f4']) && isset($_POST['link4']))) { $nf4 = $_POST['hid_f4']; $fn4 = ''; } if ((empty($_FILES['file4']['name'])) && (!isset($_POST['hid_f4']) && !isset($_POST['link4']))) { $nf4 = ''; $fn4 = ''; } $row['visible'] = $_POST['visible'] ?? ''; $time = []; $time['tz'] = $tz; $time['ut'] = $_POST['meet_time'] ?? ''; $time['sun'] = $_POST['sun'] ?? ''; $time['mon'] = $_POST['mon'] ?? ''; $time['tue'] = $_POST['tue'] ?? ''; $time['wed'] = $_POST['wed'] ?? ''; $time['thu'] = $_POST['thu'] ?? ''; $time['fri'] = $_POST['fri'] ?? ''; $time['sat'] = $_POST['sat'] ?? ''; list($ct, $sun, $mon, $tue, $wed, $thu, $fri, $sat) = figger_it_out($time); // use this for db insert, converted to UTC -> $row['db_time'] = $ct->format('Hi'); $row['db_sun'] = $sun; $row['db_mon'] = $mon; $row['db_tue'] = $tue; $row['db_wed'] = $wed; $row['db_thu'] = $thu; $row['db_fri'] = $fri; $row['db_sat'] = $sat; // use this to populate field if there are errors on pg -> // comment when testing if (isset($_POST['meet_time'])) { $row['meet_time'] = $_POST['meet_time']; } else { $row['meet_time'] = ''; } $row['sun'] = $_POST['sun'] ?? ''; $row['mon'] = $_POST['mon'] ?? ''; $row['tue'] = $_POST['tue'] ?? ''; $row['wed'] = $_POST['wed'] ?? ''; $row['thu'] = $_POST['thu'] ?? ''; $row['fri'] = $_POST['fri'] ?? ''; $row['sat'] = $_POST['sat'] ?? ''; // for testing... -> // $row['meet_time'] = $ct->format('g:i A'); // $row['sun'] = $sun; // $row['mon'] = $mon; // $row['tue'] = $tue; // $row['wed'] = $wed; // $row['thu'] = $thu; // $row['fri'] = $fri; // $row['sat'] = $sat; $row['group_name'] = $_POST['group_name'] ?? ''; if (isset($_POST['meet_phone'])) { $row['meet_phone'] = preg_replace('/[^0-9]/', '', $_POST['meet_phone']) ?? ''; } else { $row['meet_phone'] = ''; } $row['one_tap'] = $_POST['one_tap'] ?? ''; $row['meet_id'] = $_POST['meet_id'] ?? ''; $row['meet_pswd'] = $_POST['meet_pswd'] ?? ''; $row['meet_url'] = $_POST['meet_url'] ?? ''; $row['meet_addr'] = $_POST['meet_addr'] ?? ''; $row['meet_desc'] = $_POST['meet_desc'] ?? ''; $row['dedicated_om'] = $_POST['dedicated_om'] ?? ''; $row['code_b'] = $_POST['code_b'] ?? ''; $row['code_d'] = $_POST['code_d'] ?? ''; $row['code_o'] = $_POST['code_o'] ?? ''; $row['code_w'] = $_POST['code_w'] ?? ''; $row['code_beg'] = $_POST['code_beg'] ?? ''; $row['code_h'] = $_POST['code_h'] ?? ''; $row['code_sp'] = $_POST['code_sp'] ?? ''; $row['code_c'] = $_POST['code_c'] ?? ''; $row['code_m'] = $_POST['code_m'] ?? ''; $row['code_ss'] = $_POST['code_ss'] ?? ''; $row['month_speaker'] = $_POST['month_speaker'] ?? ''; $row['potluck'] = $_POST['potluck'] ?? ''; $row['hid_f1'] = $_POST['hid_f1'] ?? ''; if (isset($_POST['link1'])) { $row['link1'] = trim($_POST['link1']) ?? ''; } else { $row['link1'] = ''; } $row['hid_f2'] = $_POST['hid_f2'] ?? ''; if (isset($_POST['link2'])) { $row['link2'] = trim($_POST['link2']) ?? ''; } else { $row['link2'] = ''; } $row['hid_f3'] = $_POST['hid_f3'] ?? ''; if (isset($_POST['link3'])) { $row['link3'] = trim($_POST['link3']) ?? ''; } else { $row['link3'] = ''; } $row['hid_f4'] = $_POST['hid_f4'] ?? ''; if (isset($_POST['link4'])) { $row['link4'] = trim($_POST['link4']) ?? ''; } else { $row['link4'] = ''; } $row['add_note'] = $_POST['add_note'] ?? ''; $result = update_meeting($id, $row, $nf1, $fn1, $nf2, $fn2, $nf3, $fn3, $nf4, $fn4); if ($result === true) { $issue_removed = remove_issue($id); // delete any instances from issues table if ($result === true) { header('location: manage_edit_review.php?id=' . $id); } else { $errors = $result; } } else { $errors = $result; } } $row = edit_meeting($id); $role = $_SESSION['admin']; // get days sorted based on TZ $time = []; $time['tz'] = $tz; $time['ut'] = $row['meet_time']; $time['sun'] = $row['sun']; $time['mon'] = $row['mon']; $time['tue'] = $row['tue']; $time['wed'] = $row['wed']; $time['thu'] = $row['thu']; $time['fri'] = $row['fri']; $time['sat'] = $row['sat']; list($ct, $sun, $mon, $tue, $wed, $thu, $fri, $sat) = apply_offset_to_edit($time); $row['sun'] = $sun; $row['mon'] = $mon; $row['tue'] = $tue; $row['wed'] = $wed; $row['thu'] = $thu; $row['fri'] = $fri; $row['sat'] = $sat; require '_includes/head.php'; ?> <body> <?php if (WWW_ROOT != 'http://localhost/evergreenaa') { ?> <div class="preload-manage"> <p>One meeting at a time.</p> </div> <?php } ?> <?php require '_includes/nav.php'; ?> <?php require '_includes/msg-set-timezone.php'; ?> <?php require '_includes/msg-extras.php'; ?> <?php require '_includes/msg-role-key.php'; ?> <?php require '_includes/lat-long-instructions.php'; ?> <?php require '_includes/descriptive-location-msg.php'; ?> <?php require '_includes/pdf-upload-txt.php'; ?> <?php require '_includes/link-label-txt.php'; ?> <img class="background-image" src="_images/aa-logo-dark_mobile.gif" alt="AA Logo"> <div id="manage-wrap"> <?php // print_r($row); ?> <div class="manage-simple intro"> <?php if (($row['id_user'] == $_SESSION['id']) || ($role != 1 && $role != 2 && $role != 3)) { ?> <p>Hey<?= ' ' . $_SESSION['username'] . ',' ?></p> <?php } else if ($role == 1) { ?> <p>Hey Me,</p> <p>Quit talking to yourself.</p> <?php } else { ?> <p>Hey<?= ' ' . $_SESSION['username'] . ',' ?></p> <p>Clean it up!</p> <?php } ?> <?php require '_includes/inner_nav.php'; ?> </div> <div class="manage-simple empty"> <?php if (!empty(display_errors($errors))) { ?> <h1 class="edit-h1">Update this Meeting</h1> <?php echo display_errors($errors); ?> <?php } else { ?> <h1 class="edit-h1">Edit this meeting</h1> <?php } ?> <?php $result = display_issues($id); $issues_found = mysqli_num_rows($result); if ($issues_found > 0) { if ($issues_found == 1) { ?> <p class="address-this">Please resolve the following issue that was submitted by another member:</p> <?php } else { ?> <p class="address-this">Please resolve the following issues that were submitted by other members.</p> <?php } while($rowz = mysqli_fetch_assoc($result)) { ?> <p class="display-issues"><?= nl2br($rowz['the_issue']); ?></p> <?php } } ?> <?php if (($row['id_user'] == $_SESSION['id']) || ($role == 1 || $role == 2 || $role == 3)) { ?> <div class="weekday-edit-wrap"> <?php require '_includes/edit-details.php'; ?> </div><!-- .weekday-wrap --> <?php } else { echo "<p style=\"margin:1.5em 0 0 1em;\">Either the Internet hiccuped and you ended up here or you're trying to be sneaky. Either way, hold your breath and try again.</p>"; } ?> </div> </div><!-- #manage-wrap --> <?php require '_includes/footer.php'; ?><file_sep>/_includes/footer-popup-msg.php <?php error_reporting(0); function ewd_copyright($startYear) { $currentYear = date('Y'); if ($startYear < $currentYear) { $currentYear = date('y'); // return "<i class=\"fas fa-peace\"></i> $startYear&ndash;$currentYear"; return "<i class=\"far fa-heart\"></i> $startYear&ndash;$currentYear"; } else { // return "<i class=\"fas fa-peace\"></i> $startYear"; return "<i class=\"far fa-heart\"></i> $startYear"; } } ?> <?php function post_captcha($user_response) { $fields_string = ''; $fields = array( 'secret' => '<KEY>', 'response' => $user_response ); foreach($fields as $key=>$value) $fields_string .= $key . '=' . $value . '&'; $fields_string = rtrim($fields_string, '&'); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify'); curl_setopt($ch, CURLOPT_POST, count($fields)); curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string); curl_setopt($ch, CURLOPT_RETURNTRANSFER, True); $result = curl_exec($ch); curl_close($ch); return json_decode($result, true); } // Call the function post_captcha /* MUTE FOR LOCAL TESTING ---------------------------------------------------------- */ $_POST['g-recaptcha-response'] = ''; $res = post_captcha($_POST['g-recaptcha-response']); if (!$res['success']) { // What happens when the CAPTCHA wasn't checked - Fallback validation // echo '<p style="color: red; padding: 10px; border: 1px solid red; background-color: white; float: left;"><b>Submission Unsuccessful</b><br />Please refresh and make sure you check the security CAPTCHA box.</p><br>'; // All error checking is handled on the front end. No need for this. } else { echo '<div id="success-wrap"><span class="success-msg">Your message was sent successfully!</span></div>'; ?> <?php // error_reporting(E_ALL ^ E_NOTICE); // set a variable to hold g-recaptcha-response so you can // leave it out of the email body when message is composed if (isset($_POST['g-recaptcha-response'])) { $captcha = $_POST['g-recaptcha-response']; } // $my_email = "<EMAIL>"; $my_email = "<EMAIL>"; // to let visitor fill in the "from" field leave string below empty $from_email = ""; $errors = array(); if (count($_COOKIE)) { foreach(array_keys($_COOKIE) as $value) { unset($_REQUEST[$value]); } } if (isset($_REQUEST['email']) && !empty($_REQUEST['email'])) { $_REQUEST['email'] = trim($_REQUEST['email']); if (substr_count($_REQUEST['email'],"@") != 1 || stristr($_REQUEST['email']," ") || stristr($_REQUEST['email'],"\\") || stristr($_REQUEST['email'],":")) { $errors[] = "Email address is invalid"; } else { $exploded_email = explode("@",$_REQUEST['email']); if (empty($exploded_email[0]) || strlen($exploded_email[0]) > 64 || empty($exploded_email[1])) { $errors[] = "Email address is invalid"; } else { if (substr_count($exploded_email[1],".") == 0) { $errors[] = "Email address is invalid"; } else { $exploded_domain = explode(".",$exploded_email[1]); if (in_array("",$exploded_domain)) { $errors[] = "Email address is invalid"; } else { foreach ($exploded_domain as $value) { if (strlen($value) > 63 || !preg_match('/^[a-z0-9-]+$/i',$value)) { $errors[] = "Email address is invalid"; break; } } } } } } } if (!(isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER']) && stristr($_SERVER['HTTP_REFERER'],$_SERVER['HTTP_HOST']))) { $errors[] = "There are many other scripts out there that are much easier to hijack. Please leave this one alone."; } function recursive_array_check_blank($element_value) { global $set; if (!is_array($element_value)) { if (!empty($element_value)) { $set = 1; } } else { foreach($element_value as $value) { if($set) { break; } recursive_array_check_blank($value); } } } recursive_array_check_blank($_REQUEST); if (!$set) { $errors[] = "<script>alert('\\n\\nYou cannot submit a blank form.');window.location.replace('index.php');</script>"; } unset($set); if (count($errors)){ foreach($errors as $value){ print "$value<br>"; } exit; } if (!defined("PHP_EOL")){ define("PHP_EOL", strtoupper(substr(PHP_OS,0,3) == "WIN") ? "\r\n" : "\n"); } function build_message($request_input){ if (!isset($message_output)) { $message_output =""; } if (!is_array($request_input)) { $message_output = $request_input; } else { foreach($request_input as $key => $value) { // check that the key of the $_POST variable is not the // g-recaptcha-response before adding it to the message if ($key != 'g-recaptcha-response') { if(!empty($value)) { if (!is_numeric($key)) { $message_output .= str_replace("_"," ",ucfirst($key)).": ".build_message($value).PHP_EOL.PHP_EOL; } else { $message_output .= build_message($value).", "; } } } } } return rtrim($message_output,", "); } $message = build_message($_REQUEST); $message = $message . PHP_EOL.PHP_EOL."".PHP_EOL.""; $message = stripslashes($message); $subject = "Message From Evergreen AA Website"; $subject = stripslashes($subject); if ($from_email) { $headers = "From: " . $from_email; $headers .= PHP_EOL; $headers .= "Reply-To: " . $_REQUEST['email']; } else { $from_name = ""; if (isset($_REQUEST['name']) && !empty($_REQUEST['name'])) { $from_name = stripslashes($_REQUEST['name']); } $headers = "From: {$from_name} <{$_REQUEST['email']}>"."\r\n"; /* BCC if needed */ // $headers .= "BCC: <EMAIL>\r\n"; } mail($my_email,$subject,$message,$headers); // must exit the else statement so it does not print the form again // break; } ?> <footer> <button id="toggle-contact-form"><i class="fa fa-star" aria-hidden="true"></i><span class="tiny-mobile">&nbsp;&nbsp;</span> comments | questions | suggestions <span class="tiny-mobile">&nbsp;&nbsp;</span><i class="fa fa-star" aria-hidden="true"></i></button> <div id="email-bob"> <p class="form-note">Note: Hosts are responsible for the content of their meetings. Contact below for technical issues and feature requests. If you would like to personalize this website <a class="ytv" href="https://youtu.be/CC1HlQcmy6c" target="_blank">please see this</a> short YouTube video. <i class="far fa-smile"></i></p> <form action="" method="post" id="contactForm" onSubmit="return validateEmail(document.forms[0].email.value);"> <ul> <li> <label class="text" for="name">Name</label> <input required name="name" type="text" id="name" tabindex="10" /> </li> <li> <label class="text" for="email" required>Email</label> <input name="email" type="email" id="email" tabindex="20" required /> </li> <li> <label class="text" for="comments">Message</label> <textarea required name="comments" id="comments" tabindex="30"></textarea> </li> <li> <div class="g-recaptcha" data-theme="dark" data-callback="recaptchaCallback" data-sitekey="<KEY>"></div> </li> <li> <button id="confirm" disabled>Check Captcha above to enable Send</button> <button id="send" class="display" disabled>Send</button> </li> </ul> </form> </div> <p class="copyright"><?= ewd_copyright(2020); ?> <a class="eb" href="http://evergreenbob.com" target="_blank"><NAME></a></p> </footer> <?php switch ($layout_context) { case 'home-private' : echo "<script type=\"text/javascript\" src=\"js/jquery.backstretch.min.js?" . time() . "\"></script>"; break; case 'home-public' : echo "<script type=\"text/javascript\" src=\"js/jquery.backstretch.min.js?" . time() . "\"></script>"; break; default : echo "<script type=\"text/javascript\" src=\"js/jquery.backstretch.landing-pgs.js?" . time() . "\"></script>"; break; } ?> <script src="js/jquery.timepicker.min.js?<?php echo time(); ?>"></script> <script src="js/scripts.js?<?php echo time(); ?>"></script> <script src="http://localhost:35729/livereload.js"></script> <div class="foot"> <h3><i class="fas fa-star dmf"></i>A Quick Thank You<i class="fas fa-star dml"></i></h3> <div class="popup-body"> <p>In case you missed it, there was a fundraiser arranged to aid in the annual costs for this site (hosting + SSL) which was met incredibly fast through remarkable generosity.</p> <p>This project represents a labor of love on behalf of my deepest respect and gratitude for this community. While the reward of helping others feeds the soul, your contributions to offset the overhead here will help feed me.</p> <p>Thank you sincerely,<br>Bob</p> <p class="close">Click anywhere to close.</p> </div> </div> </body> </html> <?php db_disconnect($db); ?><file_sep>/manage_delete.php <?php require_once 'config/initialize.php'; $layout_context = "alt-manage"; if (!isset($_SESSION['id'])) { $_SESSION['message'] = "You need to be logged in to access that page."; $_SESSION['alert-class'] = "alert-danger"; header('location: ' . WWW_ROOT . '/login.php'); exit(); } if ((isset($_SESSION['id'])) && (!$_SESSION['verified'])) { header('location: ' . WWW_ROOT); exit(); } if (!isset($_GET['id'])) { header('location: ' . WWW_ROOT); } // if user clicks UPDATE MEETING if (is_post_request()) { delete_meeting($id); header('location: manage.php'); } else { $id = $_GET['id']; } $row = edit_meeting($id); $time = []; $time['tz'] = $tz; $time['ut'] = $row['meet_time']; $time['sun'] = $row['sun']; $time['mon'] = $row['mon']; $time['tue'] = $row['tue']; $time['wed'] = $row['wed']; $time['thu'] = $row['thu']; $time['fri'] = $row['fri']; $time['sat'] = $row['sat']; list($ct, $sun, $mon, $tue, $wed, $thu, $fri, $sat) = apply_offset_to_edit($time); $row['sun'] = $sun; $row['mon'] = $mon; $row['tue'] = $tue; $row['wed'] = $wed; $row['thu'] = $thu; $row['fri'] = $fri; $row['sat'] = $sat; $role = $_SESSION['admin']; require '_includes/head.php'; ?> <body> <?php if (WWW_ROOT != 'http://localhost/evergreenaa') { ?> <div class="preload"><p>One day at a time.</p></div> <?php } ?> <?php require '_includes/nav.php'; ?> <?php require '_includes/msg-set-timezone.php'; ?> <?php require '_includes/msg-extras.php'; ?> <?php require '_includes/msg-role-key.php'; ?> <img class="background-image" src="_images/aa-logo-dark_mobile.gif" alt="AA Logo"> <div id="manage-wrap"> <div class="confirm warning">WARNING!</div> <div class="manage-simple intro"> <?php if (($row['id_user'] == $_SESSION['id']) || $role == 1 || $role == 3) { ?> <p><i class="fas fa-exclamation-triangle"></i><?php echo " " . $_SESSION['username'] . ", "; ?> Are you sure you really want to go through with this?</p> <?php } else if ($role == 1) { ?> <p>Hey Me,</p> <p>Quit talking to yourself.</p> <?php } else { ?> <p><i class="fas fa-exclamation-triangle"></i><?php echo " " . $_SESSION['username'] . ", "; ?> Are you sure you really want to go through with this?</p> <?php } ?> <?php require '_includes/inner_nav.php'; ?> </div> <div class="manage-simple empty"> <h1 class="edit-h1">DELETE this Meeting</h1> <?php if (($row['id_user'] == $_SESSION['id']) || $role == 1 || $role == 3) { ?> <?php require '_includes/delete-glance.php'; ?> <div class="weekday-edit-wrap"> <?php require '_includes/delete-details.php'; ?> </div><!-- .weekday-edit-wrap --> <?php } else if (($row['id_user'] != $_SESSION['id']) || $_SESSION['admin'] == 2) { ?> <p style="margin:1.5em 0 0 1em;">As an Admin you can do a lot of things but deleting other people's meetings is not one. You can &quot;downgrade&quot; this meeting to Draft or Private by using <a class="manage-edit spec" href="manage_edit.php?id=<?= h(u($row['id_mtg'])); ?>"><i class="far fa-edit"></i> Edit Meeting</a> instead.</p> <?php } else { ?> <p style="margin:1.5em 0 0 1em;">Either the Internet hiccuped and you ended up here or you're trying to be sneaky. Either way, hold your breath and try again.</p> <?php } ?> </div><!-- .manage-simple-content --> </div><!-- #manage-wrap --> <?php require '_includes/footer.php'; ?><file_sep>/ini_set.php <?php ini_set('date.timezone', 'America/Denver');<file_sep>/email_everyone_BCC.php <?php require_once 'config/initialize.php'; $layout_context = "alt-manage"; if ($_SESSION['id'] != 1) { header('location: https://www.merriam-webster.com/dictionary/go%20away'); exit(); } ?> <?php if ((is_post_request()) && (isset($_POST['email-everyone']))) { // $email_addresses = $_POST['email_addresses']; // for testing, comment above and uncomment below // $email_addresses = '<EMAIL>'; $email_addresses = '<EMAIL>; <EMAIL>'; // concludes testing $msgsubject = $_POST['msgsubject'] ?? ''; $emaileveryonemsg = $_POST['emaileveryonemsg'] ?? ''; // if you're happy with the message, send it and head back to manage.php email_everyone_BCC($msgsubject, $email_addresses, nl2br($emaileveryonemsg)); header('location: manage.php'); // either revise your message or submit it from here. } else if ((is_post_request()) && (isset($_POST['revise']))) { ?> <?php $msgsubject = $_POST['msgsubject'] ?? ''; $emaileveryonemsg = $_POST['emaileveryonemsg'] ?? ''; $result = find_all_users(); $emails = array(); // get email addresses ready for sending and put them in a hidden field while($subject = mysqli_fetch_assoc($result)) { $emails[] = $subject['email'] . "; "; // $emails[] = "'" . $subject['email'] . "', "; } // get rid of the last comma $email_addresses = substr(implode($emails), 0 , -2); // $email_addresses = "this some bullshiz"; // echo "<br><br><br><div style=\"width:80%;margin:0 auto;padding:1.5em;border:1px solid #fff;background-color:#fefefe;color:#313131;\">" . $email_addresses . "</div>"; ?> <?php require '_includes/head.php'; ?> <body> <?php require '_includes/nav.php'; ?> <?php require '_includes/msg-set-timezone.php'; ?> <?php require '_includes/msg-extras.php'; ?> <?php require '_includes/msg-role-key.php'; ?> <img class="background-image" src="_images/aa-logo-dark_mobile.gif" alt="AA Logo"> <div id="manage-wrap"> <div class="manage-simple-admin"> <h1>Email All Members</h1> <?php require '_includes/inner_nav.php'; ?> </div> <div class="manage-simple-email"> <form class="admin-email-form" action="email_review_BCC.php" method="post"> <input type="hidden" name="email_addresses" value="<?= $email_addresses; ?>"> <label>Subject</label> <input type="text" name="msgsubject" value="<?= $msgsubject; ?>"> <textarea name="emaileveryonemsg" id="message-body"><?= $emaileveryonemsg; ?></textarea> <div class="update-rt"> <a class="cancel" href="manage.php">CANCEL</a> <input type="submit" name="admin-email" class="submit" value="REVIEW"> </div><!-- .update-rt --> </div><!-- .btm-notes --> </form> </div> </div><!-- #manage-wrap --> <?php require '_includes/footer.php'; ?> <?php mysqli_free_result($result); } else { // if this is your first visit to the page, here's an empty form // $msgsubject = $_POST['msgsubject'] ?? ''; // $emaileveryonemsg = $_POST['emaileveryonemsg'] ?? ''; $result = find_all_users(); $emails = array(); // get email addresses ready for sending and put them in a hidden field while($subject = mysqli_fetch_assoc($result)) { $emails[] = $subject['email'] . "; "; // $emails[] = "'" . $subject['email'] . "', "; } // get rid of the last comma $email_addresses = substr(implode($emails), 0 , -2); // $email_addresses = "this some bullshiz"; // echo "<br><br><br><div style=\"width:80%;margin:0 auto;padding:1.5em;border:1px solid #fff;background-color:#fefefe;color:#313131;\">" . $email_addresses . "</div>"; ?> <?php require '_includes/head.php'; ?> <body> <?php require '_includes/nav.php'; ?> <?php require '_includes/msg-set-timezone.php'; ?> <?php require '_includes/msg-extras.php'; ?> <?php require '_includes/msg-role-key.php'; ?> <img class="background-image" src="_images/aa-logo-dark_mobile.gif" alt="AA Logo"> <div id="manage-wrap"> <div class="manage-simple intro"> <p>Email All Members</p> <?php require '_includes/inner_nav.php'; ?> </div> <div class="manage-simple-email"> <?php /* echo "<div style=\"width:100%;height:8em;margin:0 auto 1em;overflow-y:scroll;padding:.5em;border:1px solid #fff;background-color:#fefefe;color:#313131;\">" . strtolower($email_addresses) . "</div>"; */ ?> <form class="admin-email-form" action="email_review_BCC.php" method="post"> <div class="bccem"> <input id="pickitup" type="hidden" value="<?= strtolower($email_addresses); ?>" class="day-values input-copy"> <a data-role="em" data-id="pickitup"><i class="far fa-copy"></i> All Addresses</a> </div> <input type="hidden" name="email_addresses" value="<?= $email_addresses ?>"> <label>Subject</label> <input type="text" name="msgsubject"> <textarea name="emaileveryonemsg"></textarea> <div class="update-rt"> <a class="cancel" href="manage.php">CANCEL</a> <input type="submit" name="admin-email" class="submit" value="REVIEW"> </div><!-- .update-rt --> </div><!-- .btm-notes --> </form> </div> </div><!-- #manage-wrap --> <?php require '_includes/footer.php'; ?> <?php } ?><file_sep>/_assets/home_with-slideup-footer.php <?php /* to set this into working order you'll need the following in _scripts-staging.js turned on and _popup.scss enabled in sass/style.scss $(document).ready(function() { $('.foot').click(function() { if($('.foot').hasClass('slide-up')) { $('.foot').addClass('slide-down', 250, 'linear'); $('.foot').removeClass('slide-up'); } else { $('.foot').removeClass('slide-down'); $('.foot').addClass('slide-up', 250, 'linear'); } }); }); */ ?> <?php $layout_context = "home-public"; require_once 'config/initialize.php'; ?> <?php require '_includes/head.php'; ?> <body> <?php if (WWW_ROOT != 'http://localhost/evergreenaa') { ?> <div class="preload"> <p>One day at a time.</p> </div> <?php } ?> <?php require '_includes/nav.php'; ?> <?php require '_includes/public-msg-one.php'; ?> <img class="background-image" src="_images/aa-logo-dark_mobile.gif" alt="AA Logo"> <div id="wrap"> <ul id="weekdays"> <li class="ctr-day"> <button id="open-sunday" class="day">Sunday</button> <div id="sunday-content" class="day-content"> <?php include '_includes/collapse-day.php'; ?> <?php $subject_set = get_all_public_meetings_for_today($sunday); $result = mysqli_num_rows($subject_set); if ($result > 0) { while ($row = mysqli_fetch_assoc($subject_set)) { $today = 'Sunday'; require '_includes/daily-glance.php'; ?> <div class="weekday-wrap"> <?php require '_includes/meeting-details.php'; ?> </div><!-- .weekday-wrap --> <?php } } mysqli_free_result($subject_set); ?> </div><!-- #sunday-content .day-content --> </li> <li class="ctr-day"> <button id="open-monday" class="day">Monday</button> <div id="monday-content" class="day-content"> <?php include '_includes/collapse-day.php'; ?> <?php $subject_set = get_all_public_meetings_for_today($monday); $result = mysqli_num_rows($subject_set); if ($result > 0) { while ($row = mysqli_fetch_assoc($subject_set)) { $today = 'Monday'; require '_includes/daily-glance.php'; ?> <div class="weekday-wrap"> <?php require '_includes/meeting-details.php'; ?> </div><!-- .weekday-wrap --> <?php } } mysqli_free_result($subject_set); ?> </div><!-- #monday-content .day-content --> </li> <li class="ctr-day"> <button id="open-tuesday" class="day">Tuesday</button> <div id="tuesday-content" class="day-content"> <?php include '_includes/collapse-day.php'; ?> <?php $subject_set = get_all_public_meetings_for_today($tuesday); $result = mysqli_num_rows($subject_set); if ($result > 0) { while ($row = mysqli_fetch_assoc($subject_set)) { $today = 'Tuesday'; require '_includes/daily-glance.php'; ?> <div class="weekday-wrap"> <?php require '_includes/meeting-details.php'; ?> </div><!-- .weekday-wrap --> <?php } } mysqli_free_result($subject_set); ?> </div><!-- #tuesday-content .day-content --> </li> <li class="ctr-day"> <button id="open-wednesday" class="day">Wednesday</button> <div id="wednesday-content" class="day-content"> <?php include '_includes/collapse-day.php'; ?> <?php $subject_set = get_all_public_meetings_for_today($wednesday); $result = mysqli_num_rows($subject_set); if ($result > 0) { while ($row = mysqli_fetch_assoc($subject_set)) { $today = 'Wednesday'; require '_includes/daily-glance.php'; ?> <div class="weekday-wrap"> <?php require '_includes/meeting-details.php'; ?> </div><!-- .weekday-wrap --> <?php } } mysqli_free_result($subject_set); ?> </div><!-- #wednesday-content .day-content --> </li> <li class="ctr-day"> <button id="open-thursday" class="day">Thursday</button> <div id="thursday-content" class="day-content"> <?php include '_includes/collapse-day.php'; ?> <?php $subject_set = get_all_public_meetings_for_today($thursday); $result = mysqli_num_rows($subject_set); if ($result > 0) { while ($row = mysqli_fetch_assoc($subject_set)) { $today = 'Thursday'; require '_includes/daily-glance.php'; ?> <div class="weekday-wrap"> <?php require '_includes/meeting-details.php'; ?> </div><!-- .weekday-wrap --> <?php } } mysqli_free_result($subject_set); ?> </div><!-- #thursday-content .day-content --> </li> <li class="ctr-day"> <button id="open-friday" class="day">Friday</button> <div id="friday-content" class="day-content"> <?php include '_includes/collapse-day.php'; ?> <?php $subject_set = get_all_public_meetings_for_today($friday); $result = mysqli_num_rows($subject_set); if ($result > 0) { while ($row = mysqli_fetch_assoc($subject_set)) { $today = 'Friday'; require '_includes/daily-glance.php'; ?> <div class="weekday-wrap"> <?php require '_includes/meeting-details.php'; ?> </div><!-- .weekday-wrap --> <?php } } mysqli_free_result($subject_set); ?> </div><!-- #friday-content .day-content --> </li> <li class="ctr-day"> <button id="open-saturday" class="day">Saturday</button> <div id="saturday-content" class="day-content"> <?php include '_includes/collapse-day.php'; ?> <?php $subject_set = get_all_public_meetings_for_today($saturday); $result = mysqli_num_rows($subject_set); if ($result > 0) { while ($row = mysqli_fetch_assoc($subject_set)) { $today = 'Saturday'; require '_includes/daily-glance.php'; ?> <div class="weekday-wrap"> <?php require '_includes/meeting-details.php'; ?> </div><!-- .weekday-wrap --> <?php } } mysqli_free_result($subject_set); ?> </div><!-- #saturday-content .day-content --> </li> </ul><!-- #weekdays --> </div><!-- #wrap --> <div class="foot"> <h3><i class="fas fa-star dmf"></i>Did you know... ?<i class="fas fa-star dml"></i></h3> <div class="popup-body"> <p>This site is specifically designed to eliminate "Zoom Bombers". The point of this website is to provide a convenient location to organize all of your <em>PRIVATE</em> meeting information. <a class="youtube" href="https://youtu.be/OQpmtysX8Bo" target="_blank">Please watch this short video</a> for a detailed explanation of how this works.</p> <p class="close">Click here to close.</p> </div> </div> <?php require '_includes/footer.php'; ?><file_sep>/contact-host-process.php <?php include_once 'error-reporting.php'; // header('location: https://www.google.com'); use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\SMTP; use PHPMailer\PHPMailer\Exception; // require_once '_functions/functions.php'; require_once 'vendor/autoload.php'; require_once 'config/constants.php'; require_once 'config/database.php'; require_once '_functions/functions.php'; require_once 'controllers/authController.php'; require_once '_functions/query_functions.php'; $db = db_connect(); $mtgid = $_POST['mtgid']; $name = trim($_POST['name']); $email = trim($_POST['email']); $message = trim($_POST['emhmsg']); $vdt = $_POST['vdt']; // visitor's day + time (really time + day (e.g. '1:15 PM, Sun')) $vtz = $_POST['vtz']; // visitor's tz $meetname = $_POST['mtgname']; // all that's here is meeting name (no day or time) if (is_post_request()) { if($name && $email && $message) { if (filter_var($email, FILTER_VALIDATE_EMAIL)) { $emh = get_host_address($mtgid); $rowq = mysqli_fetch_assoc($emh); $emhemail = $rowq['email']; $emhuser = $rowq['username']; $emhtz = $rowq['tz']; function visitor_to_host($vdt, $vtz, $emhtz) { $from_tz_obj = new DateTimeZone($vtz); $to_tz_obj = new DateTimeZone($emhtz); $ct = new DateTime($vdt, $from_tz_obj); $ct->setTimezone($to_tz_obj); $nct = $ct->format('g:i A, D'); return $nct; } $mtgdt = visitor_to_host($vdt, $vtz, $emhtz); $mtgname = $mtgdt . ' - ' . $meetname; $mail = new PHPMailer(true); try { $mail->Host = 'localhost'; $mail->SMTPAuth = false; $mail->Username = EMAIL; $mail->Password = <PASSWORD>; // email routing set to Remote //Recipients $mail->setFrom(EMAIL, 'EvergreenAA Website'); $mail->addAddress($emhemail, $emhuser); // Add a recipient $mail->addReplyTo($email, $name); // $mail->addCC('<EMAIL>'); $mail->addBCC('<EMAIL>'); // Content $mail->isHTML(true); $mail->Subject = $mtgname; $mail->Body = 'Name: ' . $name . '<br>Email: ' . $email . '<br><br>Note: The following email is being sent from <a href="https://evergreenaa.com" target="_blank">evergreenaa.com</a> and is regarding the meeting that you (Username: ' . $emhuser . ') have posted there titled, "' . $mtgname . '". A visitor has sent you the following question/comment. When you reply to this message you will be communicating directly with them.<hr><br>' . nl2br($message); $mail->send(); // echo 'Message has been sent'; $signal = 'ok'; $msg = 'Message sent successfully'; } catch (Exception $e) { $signal = 'bad'; $msg = 'Mail Error: ' {$mail->ErrorInfo}; } } else { $signal = 'bad'; $msg = 'Invalid email address. Please fix.'; } } else { $signal = 'bad'; $msg = 'Please fill in all the fields.'; } } $data = array( 'signal' => $signal, 'msg' => $msg ); echo json_encode($data); // stop ?> <file_sep>/process-transfer-meeting.php <?php require_once 'config/initialize.php'; require_once 'config/verify_admin.php'; if ($_SESSION['admin'] == 85 || $_SESSION['admin'] == 86) { header('location: ' . WWW_ROOT); exit(); } // $current_user = $_SESSION['admin']; $mtg_id = $_POST['current-mtg']; $host_email = $_POST['host-email']; $email = strtolower(trim($_POST['email'])); if (is_post_request()) { if($email) { if (filter_var($email, FILTER_VALIDATE_EMAIL)) { $nhe = find_new_host($email); // take entered email address $exists = mysqli_num_rows($nhe); // run a query on it $newhost_id = mysqli_fetch_assoc($nhe); // put results in var $newhost_id $new_host = $newhost_id['id_user']; // now you've got the id of new user from entered email if ($exists > 0) { if ($host_email != $email) { $change_host = update_host($mtg_id, $new_host); if ($change_host === true) { $signal = 'ok'; $msg = 'Transfer successful!'; } else { $signal = 'bad'; $msg = 'uh oh... The Internet might have hiccupped while this was in process and it may or may not have transferred successfully. This is a very unique occrurance. Please confirm with the other user that they have the meeting. If it did not transfer successfully email me at the bottom of any page and I will fix it. Again, this is a really hard messge to see. Congratulations. :)'; } } else { $signal = 'bad'; $msg = 'You\'re trying to transfer this to the current owner.'; } } else { $signal = 'bad'; $msg = 'That email address is not registered here. The new host has to be a member of EvergreenAA.com before you can transfer a meeting to them.'; } } else { $signal = 'bad'; $msg = 'Invalid email address. Please fix.'; } } else { $signal = 'bad'; $msg = 'Please enter email address of the member to whom you are transferring this meeting.'; } } $data = array( 'signal' => $signal, 'msg' => $msg ); echo json_encode($data); // stop ?><file_sep>/logout.php <?php require_once 'config/initialize.php'; class Util { public function clearAuthCookie() { if (isset($_COOKIE["token"])) { setcookie("token", ""); } } } $util = new Util(); //Clear Session $_SESSION['id'] = ""; $_SESSION['username'] = ""; $_SESSION['email'] = ""; $_SESSION['verified'] = ""; $_SESSION['admin'] = ""; $_SESSION['mode'] = ""; session_destroy(); // clear cookies $util->clearAuthCookie(); header('Location:' . WWW_ROOT); ?><file_sep>/log-issue-process.php <?php include_once 'error-reporting.php'; // header('location: https://www.google.com'); use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\SMTP; use PHPMailer\PHPMailer\Exception; require_once 'vendor/autoload.php'; require_once 'config/constants.php'; require_once 'config/database.php'; require_once '_functions/functions.php'; require_once '_functions/query_functions.php'; $db = db_connect(); $user_id = $_POST['tuid']; $mtgid = $_POST['mtgid']; $message = trim($_POST['emhmsg']); $vdt = $_POST['vdt']; $vtz = $_POST['vtz']; $meetname = $_POST['mtgname']; // all that's here is meeting name (no day or time) // $subject = $mtgname; $num_issues = $_POST['ri'] + 1; if (is_post_request()) { $check_for_repeats = verify_first_issue($mtgid, $user_id); $repeat = mysqli_num_rows($check_for_repeats); if ($repeat == 0) { if(strlen($message) < 250 && $message != '') { // first update the issues number in meetings table $update_issues = update_issues_number($mtgid, $num_issues); // next, log id_user + id_mtg + the_issue into issues table $log_issue = log_into_issues_table($user_id, $mtgid, $message); $emh = get_host_address($mtgid); $rowq = mysqli_fetch_assoc($emh); $emhemail = $rowq['email']; $emhuser = $rowq['username']; $emhtz = $rowq['tz']; // this is to prevent the mail function from trying to run within an ajax call on localhost which seems to have prevented me from running tests locally. now this will only run on the server. if (WWW_ROOT != 'http://localhost/evergreenaa') { function visitor_to_host($vdt, $vtz, $emhtz) { $from_tz_obj = new DateTimeZone($vtz); $to_tz_obj = new DateTimeZone($emhtz); $ct = new DateTime($vdt, $from_tz_obj); $ct->setTimezone($to_tz_obj); $nct = $ct->format('g:i A, D'); return $nct; } $mtgdt = visitor_to_host($vdt, $vtz, $emhtz); $mtgname = $mtgdt . ' - ' . $meetname; $mail = new PHPMailer(true); try { $mail->Host = 'localhost'; $mail->SMTPAuth = false; $mail->Username = EMAIL; $mail->Password = <PASSWORD>; // email routing set to Remote //Recipients $mail->setFrom(EMAIL, 'EvergreenAA Website'); $mail->addAddress($emhemail, $emhuser); // Add a recipient $mail->addReplyTo($emhemail, $emhuser); // $mail->addCC('<EMAIL>'); $mail->addBCC('<EMAIL>'); // Content $mail->isHTML(true); $mail->Subject = $mtgname; $mail->Body = 'The following email is being sent from <a href="https://evergreenaa.com" target="_blank">evergreenaa.com</a> and is regarding the meeting that you (Username: ' . $emhuser . ') have posted there titled, "' . $mtgname . '". <br><br>There has been an issue reported about this meeting. Please log into your Dashboard and click on the edit button for this meeting to address this concern. If 3 issues are reported without your response this meeting will be set to &quot;Draft&quot; and removed from view. It will remain in your account and you will still be able to remedy the issue if you would like to.<br><br>A member reported the following issue(s).<hr><br>' . nl2br($message); $mail->send(); // echo 'Message has been sent'; $signal = 'ok'; $msg = 'Message sent successfully'; } catch (Exception $e) { $signal = 'bad'; $msg = 'Mail Error: ' {$mail->ErrorInfo}; } } // still need the 'ok' signal to be returned locally though... if (WWW_ROOT == 'http://localhost/evergreenaa') { $signal = 'ok'; $msg = 'Message sent successfully'; } } else { $signal = 'bad'; $msg = 'Please provide a brief explanation of the issue (max 250 characters).'; } } else { $signal = 'bad'; $msg = 'You have already filed an issue on this meeting. You can only file 1 issue per meeting.'; } } $data = array( 'signal' => $signal, 'msg' => $msg ); echo json_encode($data); // stop ?> <file_sep>/process_suspend_user.php <?php require_once 'config/initialize.php'; require_once 'config/verify_admin.php'; $user_id = $_POST['user']; $role = $_POST['admin']; $reason = trim(h($_POST['reason'])); if (is_post_request()) { if ($_SESSION['admin'] != 1 && $_SESSION['admin'] != 3) { $signal = 'bad'; $msg = 'It appears you lack the necessary clearance to do this.'; } else { if (trim($reason)) { if ($role == '85') { // start if (strlen($reason) < 250) { $suspend_this_user = suspend_user_partial($role, $reason, $user_id); if ($suspend_this_user === true) { $signal = '85'; $msg = 'success'; } else { $signal = 'bad'; $msg = 'I don\'t think that worked.'; } } else { $signal = 'bad'; $msg = 'Let\'s keep this to 250 characters or less. Right now you\'ve got ' . strlen($reason) . ' characters.'; } } // end if ($role == '86') { if (strlen($reason) < 250) { $suspend_this_user = suspend_user_total($role, $reason, $user_id); if ($suspend_this_user === true) { $signal = '86'; $msg = 'Transfer successful!'; } else { $signal = 'bad'; $msg = 'I don\'t think that worked.'; } } else { $signal = 'bad'; $msg = 'Let\'s keep this to 250 characters or less. Right now you\'ve got ' . strlen($reason) . ' characters.'; } } } else { $signal = 'bad'; $msg = 'Please give them some kind of reason for getting suspended.'; } } } $data = array( 'signal' => $signal, 'msg' => $msg ); echo json_encode($data); // stop ?><file_sep>/transfer-meeting.php <?php require_once 'config/initialize.php'; require_once 'config/verify_admin.php'; if ($_SESSION['admin'] == 85 || $_SESSION['admin'] == 86) { header('location: ' . WWW_ROOT); exit(); } $layout_context = "alt-manage"; if (!isset($_SESSION['id'])) { header('location: ' . WWW_ROOT); exit(); } if ((isset($_SESSION['id'])) && (!$_SESSION['verified'])) { header('location: ' . WWW_ROOT); exit(); } $id = $_GET['id']; $user_id = $_SESSION['id']; $role = $_SESSION['admin']; $row = transfer_meeting($id); require '_includes/head.php'; ?> <body> <?php if (WWW_ROOT != 'http://localhost/evergreenaa') { ?> <div class="preload-manage"> <p>Loading...</p> </div> <?php } ?> <?php require '_includes/nav.php'; ?> <?php require '_includes/msg-set-timezone.php'; ?> <?php require '_includes/msg-extras.php'; ?> <?php require '_includes/msg-role-key.php'; ?> <img class="background-image" src="_images/aa-logo-dark_mobile.gif" alt="AA Logo"> <div id="host-manage-wrap"> <div class="manage-simple intro"> <?php require '_includes/inner_nav.php'; ?> </div> <?php if ((($row['id_user'] == $_SESSION['id']) && ($row['id_mtg'] == $id)) || $_SESSION['admin'] == 1 || $_SESSION['admin'] == 2 || $_SESSION['admin'] == 3) { ?> <h2 id="trans-h2" class="trans-h2">Transfer Meeting</h2> <div id="transfer-host"> <p id="current-host" class="current-role">Host: <?= $row['username'] . ' &bullet; ' . $row['email'] ?></p> <p><?= date('g:i A', strtotime($row['meet_time'])) . ' - '; ?> <?php if ($row['sun'] == 0) { } else if (($row['sun'] !=0) && (($row['mon'] != 0) || ($row['tue'] != 0) || ($row['wed'] != 0) || ($row['thu'] != 0) || ($row['fri'] != 0) || ($row['sat'] != 0))) { echo "Sun, "; } else { echo "Sun"; } if ($row['mon'] == 0) { } else if (($row['mon'] !=0) && (($row['tue'] != 0) || ($row['wed'] != 0) || ($row['thu'] != 0) || ($row['fri'] != 0) || ($row['sat'] != 0))) { echo "Mon, "; } else { echo "Mon"; } if ($row['tue'] == 0) { } else if (($row['tue'] !=0) && (($row['wed'] != 0) || ($row['thu'] != 0) || ($row['fri'] != 0) || ($row['sat'] != 0))) { echo "Tue, "; } else { echo "Tue"; } if ($row['wed'] == 0) { } else if (($row['wed'] !=0) && (($row['thu'] != 0) || ($row['fri'] != 0) || ($row['sat'] != 0))) { echo "Wed, "; } else { echo "Wed"; } if ($row['thu'] == 0) { } else if (($row['thu'] !=0) && (($row['fri'] != 0) || ($row['sat'] != 0))) { echo "Thu, "; } else { echo "Thu"; } if ($row['fri'] == 0) { } else if (($row['fri'] !=0) && ($row['sat'] != 0)) { echo "Fri, "; } else { echo "Fri"; } if ($row['sat'] == 0) { } else { echo "Sat "; } ?> <?= ' - ' . $row['group_name'] ?></p> <?php if ($role == 1 || $role ==2 || $role == 3) { ?> <?php // dropdown for admin $user_management_list = find_all_users_to_manage($user_id); $users = mysqli_num_rows($user_management_list); $results = mysqli_fetch_all($user_management_list, MYSQLI_ASSOC); if ($users > 0) { ?> <div id="tabs" class="tabs"> <ul class="tab-links"> <li class="focus"><a href="#tab1">Username</a></li> <li><a href="#tab2">Email</a></li> </ul> <div class="tab-content"> <div id="tab1"> <div class="user-box"> <p>Select a user to transfer this meeting to:</p> <form id="transfer-form-top"> <select id="transfer-usr" class="transfer-usr" name="transfer-usr"> <option value="empty">Select by Username</option> <?php foreach ($results as $li) { $user = ($li['id_user']); $username = ($li['username']); $email = ($li['email']); ?> <option value="<?= $username . ',' . $email; ?>"><?= $username ?></option> <?php } ?> <input type="hidden" name="current-user" value="<?= $user_id ?>"> <input type="hidden" name="current-mtg" value="<?= $id ?>"> <input type="hidden" name="host-email" value="<?= $row['email'] ?>"> <input type="hidden" id="new-usrnm-top"> <input type="hidden" id="new-email-top" name="email"> </select> <a id="transfer-this-top">GO</a> </form> </div> <div id="hide-on-success"> <div id="flash-email-top"></div> <p>Click &quot;GO&quot; after selecting a new member OR manually enter an email address below like some kind of prehistoric cave baboon.</p> </div> </div> <div id="tab2"> <div class="user-box"> <p>Select a user to transfer this meeting to:</p> <form id="transfer-form-topz"> <select id="transfer-usrz" class="transfer-usr" name="transfer-usr"> <option value="empty">Select by Email</option> <?php function cmp($results, $key) { foreach($results as $k=>$v) { $b[] = strtolower($v[$key]); } asort($b); foreach ($b as $k=>$v) { $c[] = $results[$k]; } return $c; } $sorted = cmp($results, 'email'); ?> <?php /* <pre><?php print_r($sorted); ?></pre> */ ?> <?php foreach ($sorted as $li) { $user = ($li['id_user']); $username = ($li['username']); $email = ($li['email']); ?> <option value="<?= $username . ',' . $email; ?>"><?= strtolower($email) ?></option> <?php } ?> <input type="hidden" name="current-user" value="<?= $user_id ?>"> <input type="hidden" name="current-mtg" value="<?= $id ?>"> <input type="hidden" name="host-email" value="<?= $row['email'] ?>"> <input type="hidden" id="new-usrnm-topz"> <input type="hidden" id="new-email-topz" name="email"> </select> <a id="transfer-this-topz">GO</a> </form> </div> <div id="hide-on-successz"> <div id="flash-username-top"></div> <p>Click &quot;GO&quot; after selecting a new member OR manually enter an email address below like some kind of prehistoric cave baboon.</p> </div> </div> </div><?php /* .tab-content */ ?> </div> <hr> <?php } ?> <?php } ?> <form id="transfer-form"> <input type="hidden" name="current-user" value="<?= $user_id ?>"> <input type="hidden" name="current-mtg" value="<?= $id ?>"> <input type="hidden" name="host-email" value="<?= $row['email'] ?>"> <p>Email of new Host</p> <input type="email" id="new-email" name="email" placeholder="Enter member's email address"> </form> <?php if ($_SESSION['admin'] == 0) { /* only show to non-admin folks because admin can hit the "whoops" link to reload the page and transfer to someone else */ ?> <div id="trans-msg"> <p class="host-disclaimer">Note: You are transfering this meeting to someone else. It will no longer be in your account but will jump up and git on over into their account right here directly. There's no going back. It's adios amigos. Make sure you've said your goodbyes and are secure in the decisions you're making here today. Some things in life are profound. (This isn't one, however.)</p> </div> <?php } else { ?> <div id="trans-msg"></div> <?php } ?> <?php if ($_SESSION['admin'] != 0) { echo '<div id="imnadmin"></div>'; } /* this is so we have something to identify whether or not we're dealing with admin. if we are, show them the "Whoops" link after submit so they can do-over if necessary. otherwise, a regular member couldn't transfer the meeting if it's not in their account so don't bother showing them this link. (sorce in _scripts.staging.js - search: 0823211116 ) */ ?> <div id="whoops"></div> <div id="th-btn"> <a id="transfer-this" class="<?php if ($_SESSION['admin'] != 0) { echo 'ap'; } ?>">TRANSFER</a> </div> </div> <?php } else { ?> <p style="margin:1.5em 0 0 1em;width:96%;max-width:600px;">Either the Internet hiccuped and you ended up here or you're trying to be sneaky. Either way, hold your breath and try again.</p> <?php } ?> </div><!-- #manage-wrap --> <?php require '_includes/footer.php'; ?><file_sep>/login.php <?php $layout_context = "login-page"; require_once 'config/initialize.php'; include '_includes/head.php'; ?> <body> <?php if (WWW_ROOT != 'http://localhost/evergreenaa') { ?> <div class="preload"><p>One day at a time.</p></div> <?php } ?> <?php require '_includes/nav.php'; ?> <?php require '_includes/msg-why-join.php'; ?> <?php require '_includes/msg-role-key.php'; ?> <img class="background-image" src="_images/aa-logo-dark_mobile.gif" alt="AA Logo"> <div id="landing"> <form action="" method="post"> <h1 class="text-center">Login</h1> <?php if(count($errors) > 0): ?> <div class="alert alert-danger"> <?php // if(isset($rememberme_error)) { echo $rememberme_error; } ?> <?php foreach($errors as $error): ?> <li><?php echo $error; ?></li> <?php endforeach; ?> </div> <?php endif; ?> <?php if(isset($_SESSION['message'])): ?> <div class="alert <?= $_SESSION['alert-class']; ?>"> <?php echo $_SESSION['message']; unset($_SESSION['message']); unset($_SESSION['alert-class']); ?> </div><!-- .alert --> <?php endif; ?> <input type="text" class="text" name="username" value="<?= $username; ?>" placeholder="Username or Email"> <input type="<PASSWORD>" id="password" class="text login-pswd" name="password" placeholder="<PASSWORD>"> <div class="showpassword-wrap"> <div id="showLoginPass"><i class="far fa-eye"></i> Show Password</div> </div> <input type="checkbox" name="remember_me" id="remember_me"> <label for="remember_me" class="rm-checked"> <div class="rm-wrap"> <div class="aa-rm-out"> <div class="aa-rm-in"></div> </div> <span class="rm-rm">Remember me</span> </div> </label> <input type="submit" name="login" class="submit" value="Login"> <p class="btm-p">No account? <a class="log" href="signup.php">Create one</a></p> <div class="fpwd"><a href="forgot_password.php">Forgot your Password?</a></div> </form> </div><!-- #landing --> </body> <?php require '_includes/footer.php'; ?><file_sep>/load-posts.php <?php require_once 'config/initialize.php'; if (isset($_GET['post-id'])) { $post = $_GET['post-id']; } else { $post = '0'; } $get_replies = get_mb_replies($post); $any_replies = mysqli_num_rows($get_replies); $replies = mysqli_fetch_assoc($get_replies); if ($any_replies > 0) { /* both topic and reply were returned from this query */ mysqli_data_seek($get_replies, 0); $i = 1; while ($row = mysqli_fetch_assoc($get_replies)) { $mt = new DateTime($row['replied'], new DateTimeZone('America/Denver')); $mt->setTimezone(new DateTimeZone($tz)); ?> <li id="li_<?= $i ?>"> <?php if (isset($_SESSION['id']) && $_SESSION['id'] == $row['idr_user']) { ?> <p class="date"><p class="mp-date"><?= $mt->format("g:i A D, M d, 'y") ?> | You replied:</p> <?php } else { ?> <p class="date"><p class="mp-date"><?= $mt->format("g:i A D, M d, 'y") ?> | <?= substr($row['username'], 0, 1) . '... ' ?> Replied:</p> <?php } ?> <?php if (isset($_SESSION['id']) && ($_SESSION['mode'] == 1 && ($_SESSION['admin'] == 1 || $_SESSION['admin'] == 3))) { // admin view of username + email - this is for the individual posts NOT the topic (see post.php for that) ?> <?php if ($_SESSION['id'] == $row['idr_user']) { ?> <p class="admin-mp-info">This is your reply</p> <?php } else if ($_SESSION['admin'] != 1 && ($row['admin'] == 1 || $row['admin'] == 3)) { // remember, there's only 1 ($row['admin'] = 1) ?> <p class="admin-mp-info">Admin (off limits)</p> <?php } else { ?> <a class="admin-mp-info gtp" href="user_role.php?user=<?= h(u($row['idr_user'])); ?>"><div class="tooltip"><span class="tooltiptext">Manage User</span><?= $row['username'] . ' &bullet; ' . $row['email'] ?></div></a> <?php } ?> <?php } ?> <p class="mb-body"><?= nl2br($row['reply']) ?></p> <?php if ((isset($_SESSION['id'])) && ($_SESSION['id'] == $row['idr_user'] || ($_SESSION['mode'] == 1 && ($_SESSION['admin'] == 1 || $_SESSION['admin'] == 2 || $_SESSION['admin'] == 3)))) { ?> <?php if ($_SESSION['admin'] == 1 || ($_SESSION['id'] == $row['idr_user']) || ($_SESSION['admin'] == 3 && $row['admin'] != 1)) { // remember, there's only 1 admin=1 ?> <form id="dr_<?= $i ?>" class="delete-reply"> <input type="hidden" name="id-reply" value="<?= $row['id_reply'] ?>"> <input type="hidden" name="uid" value="<?= $row['idr_user'] ?>"> <a data-id="dr_<?= $i ?>" data-role="delete-reply" class="manage-delete-mb"><div class="tooltip right"><span class="tooltiptext">Delete</span><i class="far fas fa-minus-circle"></i></div></a> </form> <?php } ?> <?php } ?> </li> <?php $i++; } // end while ?> <?php } else { ?> <?php /* there's a topic but no replies */ ?> <?php mysqli_data_seek($get_replies, 0); ?> <li> <p class="nry">No replies yet.</p> </li> <?php } ?> <file_sep>/delete_meeting.php <?php $layout_context = "manage-delete"; require_once 'config/initialize.php'; require_once 'config/verify_admin.php'; if ($_SESSION['admin'] == 85 || $_SESSION['admin'] == 86) { header('location: ' . WWW_ROOT); exit(); } // off for local testing if (!isset($_SESSION['id'])) { header('location: home.php'); exit(); } if ((isset($_SESSION['id'])) && (!$_SESSION['verified'])) { header('location: home.php'); exit(); } // grab meeting id in order to edit this meeting // if it's not there -> go back to index.php if (!isset($_GET['id'])) { header('location: index.php'); } $id = $_GET['id']; // if user clicks UPDATE MEETING if (is_post_request()) { $sql = "DELETE FROM meetings "; $sql .= "WHERE id_mtg='" . $id . "' "; $sql .= "LIMIT 1"; $result = mysqli_query($db, $sql); if($result) { header('location: manage.php'); } else { // delete failed echo mysqli_error($db); db_disconnect($db); exit; } } ?><file_sep>/_includes/msg-extras.php <div id="msg-one"> <div class="msg-bkg"> <div class="inside-msg-one"> <i class="far fa-times-circle"></i> <?php /*<p>Hello <?= $_SESSION['username']; ?>,</p>*/?> <p>Hello<?php if (isset($_SESSION['username'])) { echo ' ' . h($_SESSION['username']) . ','; } else { echo ','; } ?></p> <p>Thank you for joining. If you host an online AA meeting you can post it here (go to Dashboard) or you can use this site as your own private meeting organizer.</p> <p>If something needs attention here please email at the bottom of any page.</p> <p class="info-links"> <a id="preamble" class="extras" href="https://www.aa.org/assets/en_US/smf-92_en.pdf" target="_blank">AA Preamble</a> <a id="twelvesteps" class="extras" href="https://www.aa.org/assets/en_US/smf-121_en.pdf" target="_blank">12 Steps</a> <a id="traditions" class="extras" href="https://www.aa.org/assets/en_US/smf-122_en.pdf" target="_blank">12 Traditions</a> <a id="topics" class="extras" href="_images/Meeting-Starters.pdf" target="_blank">101 Meeting Starters</a> </p> <!-- <p class="daccaa-ctr"><a id="daccaa" class="daccaa" href="http://www.daccaa.org" target="_blank">DACCAA Website</a></p> --> </div><!-- .inside-msg-one --> </div><!-- .msg-bkg --> </div><!-- #msg-one --><file_sep>/_includes/msg-set-timezone.php <?php if ($new_tz == 'member') { ?> <div class="set-tz"> <div class="tz-box"> <h3>Set Timezone</h3> <div class="tz-content"> <p>Looks like you're logged in but don't have a timezone set for your account. Set it now and I won't forget. You can always change it in the future from the Menu.</p> <p class="next-p">Select your timezone:</p> <form id="init-set-tz" action="" method="post"> <select id="init-tz-select" class="pick-tz" name="timezone"> <option value="empty"><?php echo timezone_select_options(); ?></option> </select> <input id="tz-url" type="hidden" name="tz-url"> <input type="hidden" name="set-tz"> <div id="init-pick-tz"></div> <a id="init-tz-submit" class="btn">OK</a> </form> </div> </div> </div> <?php return; } elseif ($new_tz == 'visitor') { ?> <div class="set-tz"> <div class="tz-box"> <h3>Set Timezone</h3> <div class="tz-content"> <p>Let's set your timezone for this website. You're not logged in but I will try to remember your setting on this browser. You can always change it in the future from the Menu.</p> <p class="next-p">Select your timezone:</p> <form id="init-set-tz" action="" method="post"> <select id="init-tz-select" class="pick-tz" name="timezone"> <option value="empty"><?php echo timezone_select_options(); ?></option> </select> <input id="tz-url" type="hidden" name="tz-url"> <input type="hidden" name="set-tz"> <div id="init-pick-tz"></div> <a id="init-tz-submit" class="btn">OK</a> </form> </div> </div> </div> <?php return; } elseif ($new_tz == 'no-cookies') { ?> <div class="set-tz"> <div class="tz-box"> <h3>Set Timezone</h3> <div class="tz-content"> <p>Looks like you're on a device that won't allow me to save your timezone setting. We'll need to set it on a per visit basis. If you need to change it during this visit you can do so from the Menu.</p> <p class="next-p">Select your timezone:</p> <form id="init-set-tz" action="" method="post"> <select id="init-tz-select" class="pick-tz" name="timezone"> <option value="empty"><?php echo timezone_select_options(); ?></option> </select> <input id="tz-url" type="hidden" name="tz-url"> <input type="hidden" name="set-tz"> <div id="init-pick-tz"></div> <a id="init-tz-submit" class="btn">OK</a> </form> </div> </div> </div> <?php return; } ?> <div id="tz" class="set-tz"> <div class="tz-box"> <h3>Set Timezone</h3> <div class="tz-content"> <!-- <p>Let's set the timezone for this website. I will try to remember your setting on this device. You can always change it in the future from the Menu.</p> --> <p class="next-p">Change your timezone:</p> <form id="tz-form" action="" method="post"> <select id="tz-select" class="pick-tz" name="timezone"> <option value="empty"><?php echo timezone_select_options($tz); ?></option> </select> <input id="tz-url" type="hidden" name="tz-url"> <input type="hidden" name="set-tz"> <div id="pick-tz"></div> <a id="tz-submit" class="btn">OK</a> <!-- <input type="submit" name="set-tz" value="OK"> --> <a id="hide-tz" class="btn cancel">Cancel</a> </form> </div> </div> </div> <file_sep>/_functions/query_functions.php <?php function set_timezone($timezone, $user_id) { global $db; $one = "UPDATE users "; $one .= "SET tz='" . db_escape($db, $timezone) . "' "; $one .= "WHERE id_user='" . db_escape($db, $user_id) . "'"; $result = mysqli_query($db, $one); return $result; } function get_all_public_meetings() { // for home.php global $db; // we don't need to check for who submitted an issue in this query because this is exclusively for visitors who cannot submit an issue anyway. $sql = "SELECT m.id_mtg, m.issues, m.visible, m.sun, m.mon, m.tue, m.wed, m.thu, m.fri, m.sat, m.meet_time, m.group_name, m.address, m.city, m.state, m.zip, m.address_url, m.meet_phone, m.one_tap, m.meet_id, m.meet_pswd, m.meet_url, m.meet_addr, m.meet_desc, m.dedicated_om, m.code_b, m.code_d, m.code_o, m.code_w, m.code_beg, m.code_h, m.code_sp, m.code_c, m.code_m, m.code_ss, m.month_speaker, m.potluck, m.link1, m.file1, m.link2, m.file2, m.link3, m.file3, m.link4, m.file4, m.add_note FROM meetings as m "; $sql .= "WHERE m.visible != 0 "; $sql .= "AND m.visible != 1 "; $sql .= "AND m.visible != 2;"; $result = mysqli_query($db, $sql); return $result; } function get_all_public_and_private_meetings_for_today($id_user) { // home_private.php global $db; $sql = "SELECT m.id_mtg, m.issues, m.visible, m.sun, m.mon, m.tue, m.wed, m.thu, m.fri, m.sat, m.meet_time, m.group_name, m.address, m.city, m.state, m.zip, m.address_url, m.meet_phone, m.one_tap, m.meet_id, m.meet_pswd, m.meet_url, m.meet_addr, m.meet_desc, m.dedicated_om, m.code_b, m.code_d, m.code_o, m.code_w, m.code_beg, m.code_h, m.code_sp, m.code_c, m.code_m, m.code_ss, m.month_speaker, m.potluck, m.link1, m.file1, m.link2, m.file2, m.link3, m.file3, m.link4, m.file4, m.add_note, u.id_user, u.username, u.email, u.admin, u.tz FROM meetings as m "; $sql .= "LEFT JOIN users as u ON u.id_user=m.id_user "; $sql .= "WHERE (m.visible != 0 "; $sql .= "AND m.visible != 1) "; $sql .= "OR "; $sql .= "(m.visible = 1 "; $sql .= "AND u.id_user='" . db_escape($db, $id_user) . "');"; $result = mysqli_query($db, $sql); return $result; } function get_meetings_for_members($id_user) { // home_private.php global $db; $sql = "SELECT m.id_mtg, m.issues, m.visible, m.sun, m.mon, m.tue, m.wed, m.thu, m.fri, m.sat, m.meet_time, m.group_name, m.address, m.city, m.state, m.zip, m.address_url, m.meet_phone, m.one_tap, m.meet_id, m.meet_pswd, m.meet_url, m.meet_addr, m.meet_desc, m.dedicated_om, m.code_b, m.code_d, m.code_o, m.code_w, m.code_beg, m.code_h, m.code_sp, m.code_c, m.code_m, m.code_ss, m.month_speaker, m.potluck, m.link1, m.file1, m.link2, m.file2, m.link3, m.file3, m.link4, m.file4, m.add_note, u.id_user, u.username, u.email, u.admin, u.tz FROM meetings as m "; $sql .= "LEFT JOIN users as u ON u.id_user=m.id_user "; $sql .= "WHERE (m.visible != 0 "; $sql .= "AND m.visible != 1) "; $sql .= "OR "; $sql .= "(m.visible = 1 "; $sql .= "AND u.id_user='" . db_escape($db, $id_user) . "');"; // $sql .= "ORDER BY group_name;"; $result = mysqli_query($db, $sql); return $result; } function verify_this_user($id) { global $db; $sql = "SELECT admin, mode, email_opt FROM users WHERE "; $sql .= "id_user='" . db_escape($db, $id) . "' "; $result = mysqli_query($db, $sql); confirm_result_set($result); return $result; } function get_all_public_and_private_meetings_for_odin() { // home_private.php (for admin 1 only) global $db; $sql = "SELECT m.id_mtg, m.id_user, m.issues, m.visible, m.sun, m.mon, m.tue, m.wed, m.thu, m.fri, m.sat, m.meet_time, m.group_name, m.address, m.city, m.state, m.zip, m.address_url, m.meet_phone, m.one_tap, m.meet_id, m.meet_pswd, m.meet_url, m.meet_addr, m.meet_desc, m.dedicated_om, m.code_b, m.code_d, m.code_o, m.code_w, m.code_beg, m.code_h, m.code_sp, m.code_c, m.code_m, m.code_ss, m.month_speaker, m.potluck, m.link1, m.file1, m.link2, m.file2, m.link3, m.file3, m.link4, m.file4, m.add_note, u.username, u.email, u.admin, u.mode, u.tz, u.email_opt FROM meetings as m "; $sql .= "LEFT JOIN users as u ON u.id_user=m.id_user "; // $sql .= "WHERE m." . $today . " != 0 "; $sql .= "WHERE m.visible != 0;"; $result = mysqli_query($db, $sql); return $result; } function suspend_user_info($id) { global $db; $sql = "SELECT m.id_mtg, m.visible, m.sun, m.mon, m.tue, m.wed, m.thu, m.fri, m.sat, m.meet_time, m.group_name, m.address, m.city, m.state, m.zip, m.address_url, m.meet_phone, m.one_tap, m.meet_id, m.meet_pswd, m.meet_url, m.meet_addr, m.meet_desc, m.dedicated_om, m.code_b, m.code_d, m.code_o, m.code_w, m.code_beg, m.code_h, m.code_sp, m.code_c, m.code_m, m.code_ss, m.month_speaker, m.potluck, m.link1, m.file1, m.link2, m.file2, m.link3, m.file3, m.link4, m.file4, m.add_note, u.id_user, u.username, u.email, u.admin, u.sus_notes FROM meetings as m "; $sql .= "LEFT JOIN users as u ON u.id_user=m.id_user "; $sql .= "WHERE m.id_mtg='" . db_escape($db, $id) . "' "; $sql .= "LIMIT 1"; // echo $sql; $result = mysqli_query($db, $sql); confirm_result_set($result); $row = mysqli_fetch_assoc($result); mysqli_free_result($result); return $row; } function suspended_msg($user_id) { global $db; $sql = "SELECT * FROM users WHERE "; $sql .= "id_user='" . db_escape($db, $user_id) . "' "; $result = mysqli_query($db, $sql); confirm_result_set($result); return $result; } function suspend_user_total($role, $reason, $user_id) { global $db; $one = "UPDATE users u "; $one .= "JOIN meetings m ON u.id_user=m.id_user "; $one .= "SET u.admin='" . db_escape($db, $role) . "', "; $one .= "u.sus_notes='" . db_escape($db, $reason) . "', "; $one .= "u.mode=0, "; $one .= "m.visible=0 "; $one .= "WHERE u.id_user='" . db_escape($db, $user_id) . "'"; $result = mysqli_query($db, $one); return $result; } function suspend_user_partial($role, $reason, $user_id) { global $db; $one = "UPDATE users "; // $one .= "JOIN meetings m ON u.id_user=m.id_user "; $one .= "SET admin='" . db_escape($db, $role) . "', "; $one .= "mode=0, "; $one .= "sus_notes='" . db_escape($db, $reason) . "' "; $one .= "WHERE id_user='" . db_escape($db, $user_id) . "'"; $result = mysqli_query($db, $one); return $result; } function change_user_role($user_id, $role, $mode) { global $db; $one = "UPDATE users "; // $one .= "JOIN meetings m ON u.id_user=m.id_user "; $one .= "SET admin='" . db_escape($db, $role) . "', "; $one .= "mode='" . db_escape($db, $mode) . "', "; $one .= "sus_notes='' "; $one .= "WHERE id_user='" . db_escape($db, $user_id) . "'"; $result = mysqli_query($db, $one); return $result; } function update_admin_mode($id, $mode) { global $db; $one = "UPDATE users "; $one .= "SET mode='" . db_escape($db, $mode) . "' "; $one .= "WHERE id_user='" . db_escape($db, $id) . "'"; $result = mysqli_query($db, $one); return $result; } function email_opt($id, $email_opt) { global $db; $one = "UPDATE users "; $one .= "SET email_opt='" . db_escape($db, $email_opt) . "' "; $one .= "WHERE id_user='" . db_escape($db, $id) . "'"; $result = mysqli_query($db, $one); return $result; } function update_sus_note($reason, $user) { global $db; $sql = "UPDATE users "; $sql .= "SET sus_notes='" . db_escape($db, $reason) . "' "; $sql .= "WHERE id_user='" . db_escape($db, $user) . "'"; $result = mysqli_query($db, $sql); return $result; } function get_user_by_id($id) { global $db; $sql = "SELECT * FROM users "; $sql .= "WHERE id_user='" . db_escape($db, $id) . "' "; $sql .= "LIMIT 1"; // echo $sql; $result = mysqli_query($db, $sql); confirm_result_set($result); $row = mysqli_fetch_assoc($result); mysqli_free_result($result); return $row; } function create_new_meeting($row, $nf1, $fn1, $nf2, $fn2, $nf3, $fn3, $nf4, $fn4) { global $db; $errors = validate_meeting($row, $nf1, $fn1, $nf2, $fn2, $nf3, $fn3, $nf4, $fn4); if (!empty($errors)) { return $errors; } if (isset($fn1) && ($fn1 != '')) { if (move_uploaded_file($fn1, 'uploads/' . $nf1)) { // upload successful. continue processing. } else { $errors['upload_error'] = "There was a problem uploading file in position 1. Please try again."; return $errors; } } if (isset($fn2) && ($fn2 != '')) { if (move_uploaded_file($fn2, 'uploads/' . $nf2)) { // upload successful. continue processing. } else { $errors['upload_error'] = "There was a problem uploading file in position 2. Please try again."; return $errors; } } if (isset($fn3) && ($fn3 != '')) { if (move_uploaded_file($fn3, 'uploads/' . $nf3)) { // upload successful. continue processing. } else { $errors['upload_error'] = "There was a problem uploading file in position 3. Please try again."; return $errors; } } if (isset($fn4) && ($fn4 != '')) { if (move_uploaded_file($fn4, 'uploads/' . $nf4)) { // upload successful. continue processing. } else { $errors['upload_error'] = "There was a problem uploading file in position 4. Please try again."; return $errors; } } $sql = "INSERT INTO meetings "; $sql .= "(id_user, sun, mon, tue, wed, thu, fri, sat, meet_time, group_name, meet_phone, one_tap, meet_id, meet_pswd, meet_url, meet_addr, meet_desc, dedicated_om, code_b, code_d, code_o, code_w, code_beg, code_h, code_sp, code_c, code_m, code_ss, month_speaker, potluck, file1, link1, file2, link2, file3, link3, file4, link4, add_note) "; $sql .= "VALUES ("; $sql .= "'" . db_escape($db, $row['id_user']) . "', "; $sql .= "'" . $row['db_sun'] . "', "; $sql .= "'" . $row['db_mon'] . "', "; $sql .= "'" . $row['db_tue'] . "', "; $sql .= "'" . $row['db_wed'] . "', "; $sql .= "'" . $row['db_thu'] . "', "; $sql .= "'" . $row['db_fri'] . "', "; $sql .= "'" . $row['db_sat'] . "', "; $sql .= "'" . date('Hi', strtotime($row['db_time'])) . "', "; $sql .= "'" . db_escape($db, $row['group_name']) . "', "; $sql .= "'" . db_escape($db, $row['meet_phone']) . "', "; $sql .= "'" . db_escape($db, $row['one_tap']) . "', "; $sql .= "'" . db_escape($db, $row['meet_id']) . "', "; $sql .= "'" . db_escape($db, $row['meet_pswd']) . "', "; $sql .= "'" . db_escape($db, $row['meet_url']) . "', "; $sql .= "'" . db_escape($db, $row['meet_addr']) . "', "; $sql .= "'" . db_escape($db, $row['meet_desc']) . "', "; $sql .= "'" . $row['dedicated_om'] . "', "; $sql .= "'" . $row['code_b'] . "', "; $sql .= "'" . $row['code_d'] . "', "; $sql .= "'" . $row['code_o'] . "', "; $sql .= "'" . $row['code_w'] . "', "; $sql .= "'" . $row['code_beg'] . "', "; $sql .= "'" . $row['code_h'] . "', "; $sql .= "'" . $row['code_sp'] . "', "; $sql .= "'" . $row['code_c'] . "', "; $sql .= "'" . $row['code_m'] . "', "; $sql .= "'" . $row['code_ss'] . "', "; $sql .= "'" . $row['month_speaker'] . "', "; $sql .= "'" . $row['potluck'] . "', "; $sql .= "'" . db_escape($db, $nf1) . "', "; $sql .= "'" . db_escape($db, $row['link1']) . "', "; $sql .= "'" . db_escape($db, $nf2) . "', "; $sql .= "'" . db_escape($db, $row['link2']) . "', "; $sql .= "'" . db_escape($db, $nf3) . "', "; $sql .= "'" . db_escape($db, $row['link3']) . "', "; $sql .= "'" . db_escape($db, $nf4) . "', "; $sql .= "'" . db_escape($db, $row['link4']) . "', "; $sql .= "'" . db_escape($db, $row['add_note']) . "'"; $sql .= ")"; $result = mysqli_query($db, $sql); // echo $sql; if ($result) { return true; } else { echo mysqli_error($db); db_disconnect($db); exit; } } function update_meeting($id, $row, $nf1, $fn1, $nf2, $fn2, $nf3, $fn3, $nf4, $fn4) { global $db; $errors = validate_meeting($row, $nf1, $fn1, $nf2, $fn2, $nf3, $fn3, $nf4, $fn4); if (!empty($errors)) { return $errors; } if (isset($fn1) && ($fn1 != '')) { if (move_uploaded_file($fn1, 'uploads/' . $nf1)) { // upload successful. continue processing. } else { $errors['upload_error'] = "There was a problem uploading file in position 1. Please try again."; return $errors; } } if (isset($fn2) && ($fn2 != '')) { if (move_uploaded_file($fn2, 'uploads/' . $nf2)) { // upload successful. continue processing. } else { $errors['upload_error'] = "There was a problem uploading file in position 2. Please try again."; return $errors; } } if (isset($fn3) && ($fn3 != '')) { if (move_uploaded_file($fn3, 'uploads/' . $nf3)) { // upload successful. continue processing. } else { $errors['upload_error'] = "There was a problem uploading file in position 3. Please try again."; return $errors; } } if (isset($fn4) && ($fn4 != '')) { if (move_uploaded_file($fn4, 'uploads/' . $nf4)) { // upload successful. continue processing. } else { $errors['upload_error'] = "There was a problem uploading file in position 4. Please try again."; return $errors; } } $sql = "UPDATE meetings SET "; $sql .= "issues=0, "; $sql .= "visible='" . $row['visible'] . "', "; $sql .= "sun='" . $row['db_sun'] . "', "; $sql .= "mon='" . $row['db_mon'] . "', "; $sql .= "tue='" . $row['db_tue'] . "', "; $sql .= "wed='" . $row['db_wed'] . "', "; $sql .= "thu='" . $row['db_thu'] . "', "; $sql .= "fri='" . $row['db_fri'] . "', "; $sql .= "sat='" . $row['db_sat'] . "', "; $sql .= "group_name='" . db_escape($db, $row['group_name']) . "', "; $sql .= "meet_time='" . date('Hi', strtotime($row['db_time'])) . "', "; $sql .= "meet_phone='" . db_escape($db, $row['meet_phone']) . "', "; $sql .= "one_tap='" . db_escape($db, $row['one_tap']) . "', "; $sql .= "meet_id='" . db_escape($db, $row['meet_id']) . "', "; $sql .= "meet_pswd='" . db_escape($db, $row['meet_pswd']) . "', "; $sql .= "meet_url='" . db_escape($db, $row['meet_url']) . "', "; $sql .= "meet_addr='" . db_escape($db, $row['meet_addr']) . "', "; $sql .= "meet_desc='" . db_escape($db, $row['meet_desc']) . "', "; $sql .= "dedicated_om='" . $row['dedicated_om'] . "', "; $sql .= "code_b='" . $row['code_b'] . "', "; $sql .= "code_d='" . $row['code_d'] . "', "; $sql .= "code_o='" . $row['code_o'] . "', "; $sql .= "code_w='" . $row['code_w'] . "', "; $sql .= "code_beg='" . $row['code_beg'] . "', "; $sql .= "code_h='" . $row['code_h'] . "', "; $sql .= "code_c='" . $row['code_c'] . "', "; $sql .= "code_m='" . $row['code_m'] . "', "; $sql .= "code_ss='" . $row['code_ss'] . "', "; $sql .= "code_sp='" . $row['code_sp'] . "', "; $sql .= "month_speaker='" . $row['month_speaker'] . "', "; $sql .= "potluck='" . $row['potluck'] . "', "; $sql .= "file1='" . db_escape($db, $nf1) . "', "; $sql .= "link1='" . db_escape($db, $row['link1']) . "', "; $sql .= "file2='" . db_escape($db, $nf2) . "', "; $sql .= "link2='" . db_escape($db, $row['link2']) . "', "; $sql .= "file3='" . db_escape($db, $nf3) . "', "; $sql .= "link3='" . db_escape($db, $row['link3']) . "', "; $sql .= "file4='" . db_escape($db, $nf4) . "', "; $sql .= "link4='" . db_escape($db, $row['link4']) . "', "; $sql .= "add_note='" . db_escape($db, $row['add_note']) . "' "; $sql .= "WHERE id_mtg='" . db_escape($db, $id) . "' "; $sql .= "LIMIT 1"; $result = mysqli_query($db, $sql); // UPDATE statements are true/false if($result === true) { return true; } else { // UPDATE failed echo mysqli_error($db); db_disconnect($db); exit; } } function finalize_new_meeting($id, $row) { global $db; $sql = "UPDATE meetings SET "; $sql .= "visible='" . $row['visible'] . "' "; $sql .= "WHERE id_mtg='" . db_escape($db, $id) . "' "; $sql .= "LIMIT 1"; $result = mysqli_query($db, $sql); // UPDATE statements are true/false if($result === true) { return true; } else { // UPDATE failed echo mysqli_error($db); db_disconnect($db); exit; } } function delete_meeting($id) { global $db; $sql = "DELETE FROM meetings "; $sql .= "WHERE id='" . db_escape($db, $id) . "' "; $sql .= "LIMIT 1"; $result = mysqli_query($db, $sql); if($result) { // $_SESSION["message"] = "You deleted that sucker!"; return true; } else { // delete failed echo mysqli_error($db); db_disconnect($db); exit; } } function edit_meeting($id) { global $db; // $sql = "SELECT * FROM meetings WHERE "; $sql = "SELECT m.id_mtg, m.issues, m.visible, m.sun, m.mon, m.tue, m.wed, m.thu, m.fri, m.sat, m.meet_time, m.group_name, m.address, m.city, m.state, m.zip, m.address_url, m.meet_phone, m.one_tap, m.meet_id, m.meet_pswd, m.meet_url, m.meet_addr, m.meet_desc, m.dedicated_om, m.code_b, m.code_d, m.code_o, m.code_w, m.code_beg, m.code_h, m.code_sp, m.code_c, m.code_m, m.code_ss, m.month_speaker, m.potluck, m.link1, m.file1, m.link2, m.file2, m.link3, m.file3, m.link4, m.file4, m.add_note, u.id_user, u.username, u.email, u.admin, u.tz FROM meetings as m "; $sql .= "LEFT JOIN users as u ON u.id_user=m.id_user "; $sql .= "WHERE m.id_mtg='" . db_escape($db, $id) . "' "; $sql .= "LIMIT 1"; $result = mysqli_query($db, $sql); confirm_result_set($result); $row = mysqli_fetch_assoc($result); mysqli_free_result($result); return $row; } function transfer_meeting($id) { global $db; $sql = "SELECT m.id_mtg, m.sun, m.mon, m.tue, m.wed, m.thu, m.fri, m.sat, m.meet_time, m.group_name, u.id_user, u.username, u.email FROM meetings as m "; $sql .= "LEFT JOIN users as u ON u.id_user=m.id_user "; $sql .= "WHERE m.id_mtg='" . db_escape($db, $id) . "' "; $sql .= "LIMIT 1"; // echo $sql; $result = mysqli_query($db, $sql); $row = mysqli_fetch_assoc($result); mysqli_free_result($result); return $row; } function verify_first_issue($mtgid, $user_id) { global $db; $sql = "SELECT * FROM issues WHERE "; $sql .= "idi_mtg='" . $mtgid . "' "; $sql .= "AND idi_user='" . $user_id . "' "; $sql .= "LIMIT 1"; // echo $sql; $result = mysqli_query($db, $sql); return $result; } function update_issues_number($mtgid, $num_issues) { global $db; $sql = "UPDATE meetings SET "; $sql .= "issues='". db_escape($db, $num_issues) . "' "; $sql .= "WHERE id_mtg='" . $mtgid . "' "; $sql .= "LIMIT 1"; $result = mysqli_query($db, $sql); if($result === true) { return true; } else { echo mysqli_error($db); db_disconnect($db); exit; } } function log_into_issues_table($user_id, $mtgid, $message) { global $db; $sql = "INSERT INTO issues "; $sql .= "(idi_user, idi_mtg, the_issue) "; $sql .= "VALUES ("; $sql .= "'" . db_escape($db, $user_id) . "', "; $sql .= "'" . db_escape($db, $mtgid) . "', "; $sql .= "'" . db_escape($db, $message) . "'"; $sql .= ")"; $result = mysqli_query($db, $sql); if ($result) { return true; } else { echo mysqli_error($db); db_disconnect($db); exit; } } function display_issues($id) { global $db; $sql = "SELECT * FROM issues "; $sql .= "WHERE idi_mtg='" . db_escape($db, $id) . "'"; $result = mysqli_query($db, $sql); confirm_result_set($result); return $result; } function remove_issue($id) { global $db; $sql = "DELETE FROM issues "; $sql .= "WHERE idi_mtg='" . db_escape($db, $id) . "'"; $result = mysqli_query($db, $sql); if($result) { return true; } else { echo mysqli_error($db); db_disconnect($db); exit; } } // for email_members.php, "Hosts Only" function find_all_hosts() { global $db; $sql = "SELECT m.id_mtg, m.id_user, u.email_opt, u.email FROM users as u "; $sql .= "LEFT JOIN meetings as m ON m.id_user=u.id_user "; $sql .= "WHERE m.id_user=u.id_user "; $sql .= "AND u.id_user != 1 "; $sql .= "AND u.id_user != 13 "; $sql .= "AND u.email_opt != 0 "; $sql .= "GROUP BY u.id_user "; $sql .= "ORDER BY LOWER(u.email) ASC"; $result = mysqli_query($db, $sql); confirm_result_set($result); return $result; } // for email_members.php, "All Addresses" function find_all_users() { global $db; $sql = "SELECT * FROM users "; $sql .= "WHERE id_user != 1 "; $sql .= "AND id_user != 13 "; $sql .= "AND email_opt != 0 "; $sql .= "ORDER BY LOWER(username) ASC"; $result = mysqli_query($db, $sql); confirm_result_set($result); return $result; } // for dropdown list on user_management.php // and mailing lists: email_everyone_BCC.php function find_all_users_to_manage($user_id) { global $db; $sql = "SELECT joined, id_user, username, email FROM users "; $sql .= "WHERE id_user != 1 "; $sql .= "AND id_user != 13 "; $sql .= "AND id_user != '" . $user_id . "' "; $sql .= "ORDER BY LOWER(username) ASC"; // echo $sql; $result = mysqli_query($db, $sql); confirm_result_set($result); return $result; } // transfer host function find_new_host($email) { global $db; $sql = "SELECT * FROM users "; $sql .= "WHERE LOWER(email) LIKE LOWER('" . db_escape($db, $email) . "') "; $sql .= "LIMIT 1"; $result = mysqli_query($db, $sql); confirm_result_set($result); return $result; } function update_host($mtgid, $new_host) { global $db; $sql = "UPDATE meetings SET id_user = '" . $new_host . "' "; $sql .= "WHERE id_mtg = '" . $mtgid . "' "; $sql .= "LIMIT 1"; $result = mysqli_query($db, $sql); return $result; } function get_host_address($mtgid) { global $db; $sql = "SELECT u.username, u.email, u.tz "; $sql .= "FROM meetings as m "; $sql .= "LEFT JOIN users as u ON u.id_user=m.id_user "; $sql .= "WHERE m.id_mtg='" . db_escape($db, $mtgid) . "' "; $sql .= "LIMIT 1"; // echo $sql; $result = mysqli_query($db, $sql); confirm_result_set($result); return $result; } function get_mb_posts() { global $db; $sql = "SELECT mb.opened, mb.idt_topic, mb.idt_user, mb.mb_header, mb.mb_body, u.username, u.email, u.mode, u.admin FROM mb_topics as mb "; $sql .= "LEFT JOIN users as u ON u.id_user=mb.idt_user "; $sql .= "ORDER by opened DESC"; $result = mysqli_query($db, $sql); confirm_result_set($result); return $result; } function add_new_post($row) { global $db; $sql = "INSERT INTO mb_topics "; $sql .= "(idt_user, mb_header, mb_body) VALUES "; $sql .= "('" . $row['id_user'] . "', "; $sql .= "'" . db_escape($db, $row['mb_header']) . "', "; $sql .= "'" . db_escape($db, $row['mb_body']) . "')"; $result = mysqli_query($db, $sql); if ($result) { return true; } else { echo mysqli_error($db); db_disconnect($db); exit; } } function delete_post($row) { // This is the TOPIC global $db; $sql = "DELETE FROM mb_topics "; $sql .= "WHERE idt_topic='" . db_escape($db, $row['id_topic']) . "' "; $sql .= "AND idt_user='" . db_escape($db, $row['id_user']) . "' "; $sql .= "LIMIT 1"; $result = mysqli_query($db, $sql); if($result) { return true; } else { echo mysqli_error($db); db_disconnect($db); exit; } } function delete_reply($row) { // this is a REPLY POST global $db; $sql = "DELETE FROM mb_replies "; $sql .= "WHERE id_reply='" . db_escape($db, $row['id_reply']) . "' "; $sql .= "AND idr_user='" . db_escape($db, $row['id_user']) . "' "; $sql .= "LIMIT 1"; $result = mysqli_query($db, $sql); if($result) { return true; } else { echo mysqli_error($db); db_disconnect($db); exit; } } function add_mb_reply($row) { global $db; $sql = "INSERT INTO mb_replies "; $sql .= "(idr_topic, idr_user, reply) VALUES "; $sql .= "('" . $row['mb_topic'] . "', "; $sql .= "'" . $row['id_user'] . "', "; $sql .= "'" . db_escape($db, $row['mb_reply']) . "')"; $result = mysqli_query($db, $sql); if ($result) { return true; } else { echo mysqli_error($db); db_disconnect($db); exit; } } function get_this_post($post) { global $db; $sql = "SELECT mb.opened, mb.idt_topic, mb.idt_user, mb.mb_header, mb.mb_body, u.username, u.email, u.mode, u.admin FROM mb_topics as mb "; $sql .= "LEFT JOIN users as u ON u.id_user=mb.idt_user "; $sql .= "WHERE idt_topic='" . $post . "' "; $sql .= "LIMIT 1"; $result = mysqli_query($db, $sql); confirm_result_set($result); return $result; } function get_mb_pg_replies($this_post) { global $db; $sql = "SELECT mbt.idt_user, mbr.replied, mbr.id_reply, mbr.idr_topic, mbr.idr_user, mbr.reply, u.username, u.email, u.mode, u.admin FROM mb_replies as mbr "; $sql .= "LEFT JOIN users as u ON u.id_user=mbr.idr_user "; $sql .= "LEFT JOIN mb_topics as mbt on mbt.idt_topic=mbr.idr_topic "; $sql .= "WHERE mbr.idr_topic='" . $this_post . "';"; //$sql .= "GROUP BY idr_topic"; $result = mysqli_query($db, $sql); confirm_result_set($result); return $result; } function get_mb_replies($post) { global $db; $sql = "SELECT mbt.idt_topic, mbt.idt_user, mbr.replied, mbr.id_reply, mbr.idr_topic, mbr.idr_user, mbr.reply, u.username, u.email, u.mode, u.admin FROM mb_replies as mbr "; $sql .= "LEFT JOIN users as u ON u.id_user=mbr.idr_user "; $sql .= "LEFT JOIN mb_topics as mbt on mbt.idt_topic=mbr.idr_topic "; $sql .= "WHERE mbr.idr_topic='" . $post . "'"; //$sql .= "ORDER BY mbr.replied ASC"; $result = mysqli_query($db, $sql); confirm_result_set($result); return $result; } function find_all_meetings() { global $db; $sql = "SELECT * FROM meetings "; $sql .= "ORDER BY id ASC"; // echo $sql; $result = mysqli_query($db, $sql); confirm_result_set($result); return $result; } function find_meetings_by_id($id) { global $db; $sql = "SELECT * FROM meetings WHERE "; $sql .= "id_user='" . db_escape($db, $id) . "' "; // echo $sql; $result = mysqli_query($db, $sql); confirm_result_set($result); return $result; // returns an assoc. array } function find_meetings_for_manage_page($user_id) { global $db; $sql = "SELECT m.id_mtg, m.id_user, m.issues, m.visible, m.sun, m.mon, m.tue, m.wed, m.thu, m.fri, m.sat, m.meet_time, m.group_name, m.address, m.city, m.state, m.zip, m.address_url, m.meet_phone, m.one_tap, m.meet_id, m.meet_pswd, m.meet_url, m.meet_addr, m.meet_desc, m.dedicated_om, m.code_b, m.code_d, m.code_o, m.code_w, m.code_beg, m.code_h, m.code_sp, m.code_c, m.code_m, m.code_ss, m.month_speaker, m.potluck, m.link1, m.file1, m.link2, m.file2, m.link3, m.file3, m.link4, m.file4, m.add_note, u.username, u.email, u.admin, u.tz, u.email_opt FROM meetings as m "; $sql .= "LEFT JOIN users as u ON u.id_user=m.id_user "; $sql .= "WHERE m.id_user='" . db_escape($db, $user_id) . "';"; // $sql .= "GROUP BY m.group_name "; // $sql .= "ORDER BY m.meet_time;"; // echo $sql; $result = mysqli_query($db, $sql); confirm_result_set($result); return $result; // returns an assoc. array } // just for Suspended Users list on user_management.php function user_manage_page_glance() { global $db; $sql = "SELECT * FROM users "; $sql .= "WHERE admin=85 OR admin=86 "; $sql .= "GROUP BY username "; $sql .= "ORDER BY LOWER(username) ASC;"; $result = mysqli_query($db, $sql); confirm_result_set($result); return $result; } // just for Current Administrators on user_management.php function find_users_for_admin_glance() { global $db; $sql = "SELECT * FROM users "; $sql .= "WHERE admin=2 OR admin=3 "; $sql .= "GROUP BY username "; $sql .= "ORDER BY LOWER(username) ASC;"; $result = mysqli_query($db, $sql); confirm_result_set($result); return $result; } function user_manage_page_details($userz_id) { global $db; $sql = "SELECT m.id_mtg, m.id_user, m.visible, m.sun, m.mon, m.tue, m.wed, m.thu, m.fri, m.sat, m.meet_time, m.group_name, m.address, m.city, m.state, m.zip, m.address_url, m.meet_phone, m.one_tap, m.meet_id, m.meet_pswd, m.meet_url, m.meet_addr, m.meet_desc, m.dedicated_om, m.code_b, m.code_d, m.code_o, m.code_w, m.code_beg, m.code_h, m.code_sp, m.code_c, m.code_m, m.code_ss, m.month_speaker, m.potluck, m.link1, m.file1, m.link2, m.file2, m.link3, m.file3, m.link4, m.file4, m.add_note, u.username, u.email, u.admin FROM meetings as m "; $sql .= "LEFT JOIN users as u ON u.id_user=m.id_user "; $sql .= "WHERE m.id_user='" . db_escape($db, $userz_id) . "' "; $sql .= "AND (m.visible=2 OR m.visible=3) "; // $sql .= "GROUP BY u.username "; $sql .= "ORDER BY m.meet_time;"; // echo $sql; $result = mysqli_query($db, $sql); confirm_result_set($result); return $result; // returns an assoc. array } function find_meetings_by_id_today($id, $today) { global $db; $sql = "SELECT * FROM meetings WHERE "; $sql .= "id_user='" . db_escape($db, $id) . "' AND " . $today . " !=0 "; $sql .= "ORDER BY meet_time;"; // echo $sql; $result = mysqli_query($db, $sql); confirm_result_set($result); return $result; // returns an assoc. array } function validate_meeting($row, $nf1, $fn1, $nf2, $fn2, $nf3, $fn3, $nf4, $fn4) { $errors = []; if (is_blank($row['group_name'])) { $errors['group_name'] = "Name your Meeting! Under 50 characters, please."; } else if (!has_length($row['group_name'], ['min' => 1, 'max' => 50])) { $errors['group_name'] = "Meeting Name needs to be less than 50 characters."; } if (( $row['sun'] == "0" && $row['mon'] == "0" && $row['tue'] == "0" && $row['wed'] == "0" && $row['thu'] == "0" && $row['fri'] == "0" && $row['sat'] == "0" )) { $errors['pick_a_day'] = "Pick a day or days for your meeting."; } if (is_blank($row['meet_time'])) { $errors['meet_time'] = "Please set a time."; } if (!is_blank($row['meet_phone']) && has_length_less_than($row['meet_phone'], 10)) { $errors['meet_phone'] = "Only 10-digit phone numbers."; } if (!is_blank($row['meet_phone']) && has_length_greater_than($row['meet_phone'], 10)) { $errors['meet_phone'] = "You've got too many numbers in your phone number."; } if (!is_blank($row['meet_id']) && has_length_greater_than($row['meet_id'], 15)) { $errors['meet_id'] = "Meeting ID's aren't that long! C'mon man."; } if (!is_blank($row['meet_pswd']) && has_length_greater_than($row['meet_pswd'], 25)) { $errors['meet_pswd'] = "That password is way too long."; } if (is_blank($row['meet_url']) && is_blank($row['meet_addr']) && is_blank($row['meet_desc'])) { $errors['meet_url'] = "You need either an Online URL or Physical Address to host a meeting."; } if (!is_blank($row['meet_addr']) && has_length_greater_than($row['meet_addr'], 255)) { $errors['meet_addr'] = "255 Character limit on physical address"; } if (!is_blank($row['meet_desc']) && has_length_greater_than($row['meet_desc'], 255)) { $errors['meet_addr'] = "255 Character limit on descriptive location"; } if (is_blank($row['meet_addr']) && (!is_blank($row['meet_desc'])) ) { $errors['meet_addr'] = "You need location information for your map."; } if (( $row['dedicated_om'] == "0" && $row['code_o'] == "0" && $row['code_w'] == "0" && $row['code_m'] == "0" && $row['code_c'] == "0" && $row['code_beg'] == "0" && $row['code_h'] == "0" && $row['code_d'] == "0" && $row['code_b'] == "0" && $row['code_ss'] == "0" && $row['code_sp'] == "0" && $row['month_speaker'] == "0" && $row['potluck'] == "0" )) { $errors['meeting_type'] = "Select at least ONE value for the type of meeting. Your meeting is either Open or Closed at least."; } if ($row['dedicated_om'] == "1" && $row['meet_url'] == '') { $errors['url_or_phy'] = "If it's a Dedicated Online meeting you need a URL."; } if ($row['dedicated_om'] == "1" && $row['meet_addr'] != '') { $errors['url_and_phy'] = "If it's a Dedicated Online meeting you don't need a physical address."; } // begin file errors for update/edit pages // BEGIN POSITION 1 - Notes for all positions' validation explanations contained within position 1 // ...it's good & complicated so there are a lot of notes. // 1st - check for stand-along issue (this is the only error on page). Each 1 of the 4 potential errors for files can either exist by itself or in conjunction with other errors on the page. If any other error on the page exists then you need to check for it here. // because file selections do not persist across a page refresh it needs to catch when you haven't made an error in the file area but an error exists somewhere else on the page. the whole point here is to keep error messages in order. if ((isset($fn1) && ($fn1 != '')) && is_blank($row['link1'])) { $errors['name_link1'] = "You did not name your link in position 1. Please restore file selection."; } if ((isset($fn1) && $fn1 != '') && $nf1 == '') { $errors['name_link1'] = "File upload in Position 1 needs attention. Please restore file selection."; } /* difference between new and update right here... this one's for 'new' -> if new file is not set but there's a name/label present, let them know. In the update version they are allowed to change the name because it sees that a hidden field with the file name is present. */ if (((!isset($fn1) || $fn1 == '') && (trim($row['link1']) != '')) && $row['hid_f1'] == '') { $errors['name_link1'] = "There's a name but no file to upload in position 1. Please restore file selection."; } /* this one's for 'update' -> this allows you to rename a label. it says, even though you are not uploading a file, I see that you already have one here so go ahead and rename it. (If they hit "Remove" it deletes the hidden value (via .js) from the DB + if they delete the label, it deletes the hidden value (on submit - see #3 if condition after (is_post_request()) in manage_edit.php) from the DB. I kind of covered the bases on this one.) */ if ((!isset($fn1) || ($fn1 == '') && $row['hid_f1'] == '') && (trim($row['link1']) != '')) { $errors['name_link1'] = "You set a name but no file in position 1. Please restore file selection."; } /* finally, to catch the possibility that there were no errors with the file/label area but there was another error on the page when you have hoped to upload a file, you now need to address the broken file selection. the notes (at the very bottom of the error checking stack, gets its own special if() function to manage this.) */ if (!empty($errors) && (isset($fn1) && $fn1 != '')) { $errors['name_link1'] = "Restore file selection in position 1."; } // END POSITION 1 if ((isset($fn2) && ($fn2 != '')) && is_blank($row['link2'])) { $errors['name_link2'] = "You did not name your link in position 2. Please restore file selection."; } if ((isset($fn2) && $fn2 != '') && $nf2 == '') { $errors['name_link2'] = "File upload in Position 2 needs attention. Please restore file selection."; } // for 'new' if (((!isset($fn2) || ($fn2 == '')) && (trim($row['link2']) != '')) && $row['hid_f2'] == '') { $errors['name_link2'] = "There's a name but no file to upload in position 2. Please restore file selection."; } // for 'update' if ((!isset($fn2) || ($fn2 == '') && $row['hid_f2'] == '') && (trim($row['link2']) != '')) { $errors['name_link2'] = "You set a name but no file in position 2. Please restore file selection."; } if (!empty($errors) && (isset($fn2) && $fn2 != '')) { $errors['name_link2'] = "Restore file selection in position 2."; } if ((isset($fn3) && ($fn3 != '')) && is_blank($row['link3'])) { $errors['name_link3'] = "You did not name your link in position 3. Please restore file selection."; } if ((isset($fn3) && $fn3 != '') && $nf3 == '') { $errors['name_link3'] = "File upload in Position 3 needs attention. Please restore file selection."; } // for 'new' if (((!isset($fn3) || ($fn3 == '')) && (trim($row['link3']) != '')) && $row['hid_f3'] == '') { $errors['name_link3'] = "There's a name but no file to upload in position 3. Please restore file selection."; } // for 'update' if ((!isset($fn3) || ($fn3 == '') && $row['hid_f3'] == '') && (trim($row['link3']) != '')) { $errors['name_link3'] = "You set a name but no file in position 3. Please restore file selection."; } if (!empty($errors) && (isset($fn3) && $fn3 != '')) { $errors['name_link3'] = "Restore file selection in position 3."; } if ((isset($fn4) && ($fn4 != '')) && is_blank($row['link4'])) { $errors['name_link4'] = "You did not name your link in position 4. Please restore file selection."; } if ((isset($fn4) && $fn4 != '') && $nf4 == '') { $errors['name_link4'] = "File upload in Position 4 needs attention. Please restore file selection."; } // for 'new' if (((!isset($fn4) || ($fn4 == '')) && (trim($row['link4']) != '')) && $row['hid_f4'] == '') { $errors['name_link4'] = "There's a name but no file to upload in position 4. Please restore file selection."; } // for 'update' if ((!isset($fn4) || ($fn4 == '') && $row['hid_f4'] == '') && (trim($row['link4']) != '')) { $errors['name_link4'] = "You set a name but no file in position 4. Please restore file selection."; } if (!empty($errors) && (isset($fn4) && $fn4 != '')) { $errors['name_link4'] = "Restore file selection in position 4."; } // end file errors for update/edit pages /* notes gets it's own special version of error checking since it's last. in case this is the ony error on the page and they had everything correct in the file upload area, you still want to show the file error first since combing down the page the files come before the notes. */ if ((!is_blank($row['add_note']) && has_length_greater_than($row['add_note'], 1000)) && ((isset($fn1) && $fn1 != '') || (isset($fn2) && $fn2 != '') || (isset($fn3) && $fn3 != '') || (isset($fn4) && $fn4 != ''))) { if (isset($fn1) && $fn1 != '') { $errors['name_link1'] = "Restore file selection in position 1."; } if (isset($fn2) && $fn2 != '') { $errors['name_link2'] = "Restore file selection in position 2"; } if (isset($fn3) && $fn3 != '') { $errors['name_link3'] = "Restore file selection in position 3"; } if (isset($fn4) && $fn4 != '') { $errors['name_link4'] = "Restore file selection in position 4"; } $errors['add_note'] = "You've got more than 1,000 characters in your note. Dial it down to 1,000 or less please."; } else if (!is_blank($row['add_note']) && has_length_greater_than($row['add_note'], 1000)) { $errors['add_note'] = "You've got more than 1,000 characters in your note. Dial it down to 1,000 or less please."; } return $errors; } function validate_url($url) { $path = parse_url($url, PHP_URL_PATH); $encoded_path = array_map('urlencode', explode('/', $path)); $url = str_replace($path, implode('/', $encoded_path), $url); return filter_var($url, FILTER_VALIDATE_URL) ? true : false; } function is_blank($value) { return !isset($value) || trim($value) === ''; } function has_presence($value) { return !is_blank($value); } // has_length_greater_than('abcd', 3) // * validate string length // * spaces count towards length // * use trim() if spaces should not count function has_length_greater_than($value, $min) { $length = strlen($value); return $length > $min; } // has_length_less_than('abcd', 5) // * validate string length // * spaces count towards length // * use trim() if spaces should not count function has_length_less_than($value, $max) { $length = strlen($value); return $length < $max; } // has_length('abcd', ['min' => 3, 'max' => 5]) // * validate string length // * combines functions_greater_than, _less_than, _exactly // * spaces count towards length // * use trim() if spaces should not count function has_length($value, $options) { if(isset($options['min']) && !has_length_greater_than($value, $options['min'] - 1)) { return false; } elseif(isset($options['max']) && !has_length_less_than($value, $options['max'] + 1)) { return false; } elseif(isset($options['exact']) && !has_length_exactly($value, $options['exact'])) { return false; } else { return true; } } function validate_row($row) { $errors = []; if(is_blank($row['group_name'])) { $errors[] = "You need a name for your group."; } if(!has_length($row['group_name'], ['min' => 1, 'max' => 50])) { $errors[] = "Group name can be up to 50 characters."; } return $errors; } <file_sep>/_includes/user-management-user-glance.php <div class="manage-glance-wrap u-m"> <div class="manage-glance-user"> <div class="manage-user-left"> <?php if (($row['id_user'] == $_SESSION['id']) && $row['admin'] == 2) { ?> You, of course &bullet; Tier II Admin <?php } else if (($row['id_user'] == $_SESSION['id']) && $row['admin'] == 3) { ?> You, of course &bullet; Top Tier Admin <?php } else if ($row['admin'] == 1) { ?> <?php // SQL = WHERE u.admin=2 OR u.admin=3 -> that's why this won't show... ?> <?= $row['username'] . ' &bullet; ' . strtolower($row['email']) . ' ' ?>&bullet; Website Guy <?php } else if ($row['admin'] == 2) { ?> <?= $row['username'] . ' &bullet; ' . strtolower($row['email']) . ' ' ?>&bullet; Tier II Admin <?php } else if ($row['admin'] == 3) { ?> <?= $row['username'] . ' &bullet; ' . strtolower($row['email']) . ' ' ?>&bullet; Top Tier Admin <?php } else { ?> <?= $row['username'] . ' &bullet; ' . strtolower($row['email']) . ' ' ?> <?php } ?> </div> <div class="manage-user-right"> <?php if ($row['id_user'] == $_SESSION['id']) { ?> <a class="manage-edit my-stuff"><div class="tooltip right"><span class="tooltiptext">Don't play with yourself</span><i class="far fas fa-user-cog"></i></div></a> <?php } else if ($_SESSION['admin'] != 1 && ($row['admin'] == 1 || $row['admin'] == 3)) { ?> <a class="manage-edit my-stuff"><div class="tooltip right"><span class="tooltiptext">Top Tier Admin are off limits</span><i class="far fas fa-user-cog"></i></div></a> <?php } else { ?> <a class="manage-edit" href="user_role.php?user=<?= $row['id_user'] ?>"><div class="tooltip right"><span class="tooltiptext"><?php if ($row['admin'] == 3) { ?>Demote Admin<?php } else if ($row['admin'] == 2) { ?>Change role<?php } else { ?>Reinstate User<?php } ?></span><i class="far fas fa-user-cog"></i></div></a> <?php } ?> </div> </div> </div> <file_sep>/_includes/special-admin-editing.php <ul class="manage-weekdays"> <?php $any_meetings_for_user = find_meetings_by_id($user_id); $result = mysqli_num_rows($any_meetings_for_user); // find out if user has any meetings they manage if ($result > 0) { ?> <?php // if user has meetings to manage, display on a daily basis $users_sunday_meetings = find_meetings_by_id_today($user_id, $sunday); $sunday_meetings = mysqli_num_rows($users_sunday_meetings); if ($sunday_meetings > 0) { ?> <li class="ctr-day"> <div class="manage-day-toggle day">Sunday</div> <div id="sunday-content" class="day-content"> <?php include '_includes/collapse-day.php'; ?> <?php while ($row = mysqli_fetch_assoc($users_sunday_meetings)) { ?> <?php require '_includes/manage-glance.php'; ?> <div class="weekday-wrap<?php if ('visible' == 0) { echo ' draft-bkg'; } ?>"> <?php require '_includes/meeting-details.php'; ?> </div><!-- .weekday-wrap --> <?php } mysqli_free_result($users_sunday_meetings); ?> </div><!-- #sunday-content .day-content --> </li> <?php } // if user has meetings to manage, display on a daily basis $users_monday_meetings = find_meetings_by_id_today($user_id, $monday); $monday_meetings = mysqli_num_rows($users_monday_meetings); if ($monday_meetings > 0) { ?> <li class="ctr-day"> <div class="manage-day-toggle day">Monday</div> <div id="sunday-content" class="day-content"> <?php include '_includes/collapse-day.php'; ?> <?php while ($row = mysqli_fetch_assoc($users_monday_meetings)) { ?> <?php require '_includes/manage-glance.php'; ?> <div class="weekday-wrap<?php if ('visible' == 0) { echo ' draft-bkg'; } ?>"> <?php require '_includes/meeting-details.php'; ?> </div><!-- .weekday-wrap --> <?php } mysqli_free_result($users_monday_meetings); ?> </div><!-- #sunday-content .day-content --> </li> <?php } // if user has meetings to manage, display on a daily basis $users_tuesday_meetings = find_meetings_by_id_today($user_id, $tuesday); $tuesday_meetings = mysqli_num_rows($users_tuesday_meetings); if ($tuesday_meetings > 0) { ?> <li class="ctr-day"> <div class="manage-day-toggle day">Tuesday</div> <div id="sunday-content" class="day-content"> <?php include '_includes/collapse-day.php'; ?> <?php while ($row = mysqli_fetch_assoc($users_tuesday_meetings)) { ?> <?php require '_includes/manage-glance.php'; ?> <div class="weekday-wrap<?php if ('visible' == 0) { echo ' draft-bkg'; } ?>"> <?php require '_includes/meeting-details.php'; ?> </div><!-- .weekday-wrap --> <?php } mysqli_free_result($users_tuesday_meetings); ?> </div><!-- #sunday-content .day-content --> </li> <?php } // if user has meetings to manage, display on a daily basis $users_wednesday_meetings = find_meetings_by_id_today($user_id, $wednesday); $wednesday_meetings = mysqli_num_rows($users_wednesday_meetings); if ($wednesday_meetings > 0) { ?> <li class="ctr-day"> <div class="manage-day-toggle day">Wednesday</div> <div id="sunday-content" class="day-content"> <?php include '_includes/collapse-day.php'; ?> <?php while ($row = mysqli_fetch_assoc($users_wednesday_meetings)) { ?> <?php require '_includes/manage-glance.php'; ?> <div class="weekday-wrap<?php if ('visible' == 0) { echo ' draft-bkg'; } ?>"> <?php require '_includes/meeting-details.php'; ?> </div><!-- .weekday-wrap --> <?php } mysqli_free_result($users_wednesday_meetings); ?> </div><!-- #sunday-content .day-content --> </li> <?php } // if user has meetings to manage, display on a daily basis $users_thursday_meetings = find_meetings_by_id_today($user_id, $thursday); $thursday_meetings = mysqli_num_rows($users_thursday_meetings); if ($thursday_meetings > 0) { ?> <li class="ctr-day"> <div class="manage-day-toggle day">Thursday</div> <div id="sunday-content" class="day-content"> <?php include '_includes/collapse-day.php'; ?> <?php while ($row = mysqli_fetch_assoc($users_thursday_meetings)) { ?> <?php require '_includes/manage-glance.php'; ?> <div class="weekday-wrap<?php if ('visible' == 0) { echo ' draft-bkg'; } ?>"> <?php require '_includes/meeting-details.php'; ?> </div><!-- .weekday-wrap --> <?php } mysqli_free_result($users_thursday_meetings); ?> </div><!-- #sunday-content .day-content --> </li> <?php } // if user has meetings to manage, display on a daily basis $users_friday_meetings = find_meetings_by_id_today($user_id, $friday); $friday_meetings = mysqli_num_rows($users_friday_meetings); if ($friday_meetings > 0) { ?> <li class="ctr-day"> <div class="manage-day-toggle day">Friday</div> <div id="sunday-content" class="day-content"> <?php include '_includes/collapse-day.php'; ?> <?php while ($row = mysqli_fetch_assoc($users_friday_meetings)) { ?> <?php require '_includes/manage-glance.php'; ?> <div class="weekday-wrap<?php if ('visible' == 0) { echo ' draft-bkg'; } ?>"> <?php require '_includes/meeting-details.php'; ?> </div><!-- .weekday-wrap --> <?php } mysqli_free_result($users_friday_meetings); ?> </div><!-- #sunday-content .day-content --> </li> <?php } // if user has meetings to manage, display on a daily basis $users_saturday_meetings = find_meetings_by_id_today($user_id, $saturday); $saturday_meetings = mysqli_num_rows($users_saturday_meetings); if ($saturday_meetings > 0) { ?> <li class="ctr-day"> <div class="manage-day-toggle day">Saturday</div> <div id="sunday-content" class="day-content"> <?php include '_includes/collapse-day.php'; ?> <?php while ($row = mysqli_fetch_assoc($users_saturday_meetings)) { ?> <?php require '_includes/manage-glance.php'; ?> <div class="weekday-wrap<?php if ('visible' == 0) { echo ' draft-bkg'; } ?>"> <?php require '_includes/meeting-details.php'; ?> </div><!-- .weekday-wrap --> <?php } mysqli_free_result($users_saturday_meetings); ?> </div><!-- #sunday-content .day-content --> </li> <?php } } else { // user has no meetings to manage echo "<p style=\"margin-top:0.5em;padding:0px 1em;\">When you add a meeting it will display here and wherever else you choose. You can make your meetings public or keep them private. Add a new meeting and give it a try.</p>"; } mysqli_free_result($any_meetings_for_user); ?> </ul><!-- .manage-weekdays --><file_sep>/_includes/set_timezone.php <?php require_once 'config/initialize.php'; if (isset($_SESSION['id'])) { $user_id = $_SESSION['id']; $user_role = $_SESSION['admin']; } else { $user_id = 'ns'; $user_role = '0'; } // processing has to come before if statements so it can catch a submission (duh) if (is_post_request() && isset($_POST['set-tz'])) { if ($user_id != 'ns') { $timezone = $_POST['timezone']; $url = $_POST['tz-url']; $result = set_timezone($timezone, $user_id); if ($result === true) { // setCookie('timezone', $timezone, time() + (3650 * 24 * 60 * 60), '/'); // 10 years $_SESSION['db-tz'] = $timezone; header('location:' . $url); } else { $errors = $result; } } else { $timezone = $_POST['timezone']; setCookie('sessionTZ', $timezone, time() + (3650 * 24 * 60 * 60), '/'); // 10 years $_SESSION['session-tz'] = $timezone; header('location:' . WWW_ROOT); } } $new_tz = ''; $tz = 'America/Denver'; if (isset($_SESSION['db-tz']) && $_SESSION['db-tz'] != 'not-set') { // they're logged in an their tz has already been set $tz = $_SESSION['db-tz']; return; } elseif (isset($_SESSION['db-tz']) && $_SESSION['db-tz'] == 'not-set') { // they're logged in but they haven't set their tz yet $new_tz = 'member'; $tz = 'America/Denver'; return; } elseif (!empty($_COOKIE['sessionTZ'])) { $tz = $_COOKIE['sessionTZ']; return; } elseif (isset($_SESSION['session-tz'])) { $tz = $_SESSION['session-tz']; return; } <file_sep>/js/preload.js $(window).on('load', function() { $(".preload").delay(250).fadeOut(750); }); $(window).on('load', function() { $(".preload-manage").delay(200).fadeOut(200); }); <file_sep>/manage_new.php <?php require_once 'config/initialize.php'; require_once 'config/verify_admin.php'; if ($_SESSION['admin'] == 85 || $_SESSION['admin'] == 86) { header('location: ' . WWW_ROOT); exit(); } $layout_context = "alt-manage"; if (!isset($_SESSION['id'])) { $_SESSION['message'] = "You need to be logged in to create a meeting."; $_SESSION['alert-class'] = "alert-danger"; header('location: ' . WWW_ROOT . '/login.php'); exit(); } if ((isset($_SESSION['id'])) && (!$_SESSION['verified'])) { header('location: ' . WWW_ROOT); exit(); } $role = $_SESSION['admin']; if (is_post_request() && isset($_POST['review-mtg'])) { $rando_num = rand(100,999); $row = []; if (!empty($_FILES['file1']['name'])) { $uploaded_file1 = $_FILES['file1']['name']; $uploaded_size1 = $_FILES['file1']['size']; $ext1 = strtolower(pathinfo($uploaded_file1, PATHINFO_EXTENSION)); $rename1 = $_SESSION['id'] . '_' . date('mdYHi') . '_01_' . $rando_num; $nf1 = $rename1 . '.' . $ext1; $fn1 = $_FILES['file1']['tmp_name']; } else { $nf1 = ''; // new_file $fn1 = ''; // file_name } if (!empty($_FILES['file2']['name'])) { $uploaded_file2 = $_FILES['file2']['name']; $uploaded_size2 = $_FILES['file2']['size']; $ext2 = strtolower(pathinfo($uploaded_file2, PATHINFO_EXTENSION)); $rename2 = $_SESSION['id'] . '_' . date('mdYHi') . '_02_' . $rando_num; $nf2 = $rename2 . '.' . $ext2; $fn2 = $_FILES['file2']['tmp_name']; } else { $nf2 = ''; // new_file $fn2 = ''; // file_name } if (!empty($_FILES['file3']['name'])) { $uploaded_file3 = $_FILES['file3']['name']; $uploaded_size3 = $_FILES['file3']['size']; $ext3 = strtolower(pathinfo($uploaded_file3, PATHINFO_EXTENSION)); $rename3 = $_SESSION['id'] . '_' . date('mdYHi') . '_03_' . $rando_num; $nf3 = $rename3 . '.' . $ext3; $fn3 = $_FILES['file3']['tmp_name']; } else { $nf3 = ''; // new_file $fn3 = ''; // file_name } if (!empty($_FILES['file4']['name'])) { $uploaded_file4 = $_FILES['file4']['name']; $uploaded_size4 = $_FILES['file4']['size']; $ext4 = strtolower(pathinfo($uploaded_file4, PATHINFO_EXTENSION)); $rename4 = $_SESSION['id'] . '_' . date('mdYHi') . '_04_' . $rando_num; $nf4 = $rename4 . '.' . $ext4; $fn4 = $_FILES['file4']['tmp_name']; } else { $nf4 = ''; // new_file $fn4 = ''; // file_name } $row['id_user'] = $_SESSION['id']; $time = []; $time['tz'] = $tz; $time['ut'] = $_POST['meet_time'] ?? ''; $time['sun'] = $_POST['sun'] ?? ''; $time['mon'] = $_POST['mon'] ?? ''; $time['tue'] = $_POST['tue'] ?? ''; $time['wed'] = $_POST['wed'] ?? ''; $time['thu'] = $_POST['thu'] ?? ''; $time['fri'] = $_POST['fri'] ?? ''; $time['sat'] = $_POST['sat'] ?? ''; list($ct, $sun, $mon, $tue, $wed, $thu, $fri, $sat) = figger_it_out($time); // use this for db insert, converted to UTC -> $row['db_time'] = $ct->format('Hi'); $row['db_sun'] = $sun; $row['db_mon'] = $mon; $row['db_tue'] = $tue; $row['db_wed'] = $wed; $row['db_thu'] = $thu; $row['db_fri'] = $fri; $row['db_sat'] = $sat; // use this to populate field if there are errors on pg -> // comment when testing $row['meet_time'] = $_POST['meet_time']; $row['sun'] = $_POST['sun'] ?? ''; $row['mon'] = $_POST['mon'] ?? ''; $row['tue'] = $_POST['tue'] ?? ''; $row['wed'] = $_POST['wed'] ?? ''; $row['thu'] = $_POST['thu'] ?? ''; $row['fri'] = $_POST['fri'] ?? ''; $row['sat'] = $_POST['sat'] ?? ''; // for testing... -> // $row['meet_time'] = $ct->format('g:i A'); // $row['sun'] = $sun; // $row['mon'] = $mon; // $row['tue'] = $tue; // $row['wed'] = $wed; // $row['thu'] = $thu; // $row['fri'] = $fri; // $row['sat'] = $sat; $row['group_name'] = $_POST['group_name'] ?? ''; $row['meet_phone'] = preg_replace('/[^0-9]/', '', $_POST['meet_phone']) ?? ''; $row['one_tap'] = $_POST['one_tap'] ?? ''; $row['meet_id'] = $_POST['meet_id'] ?? ''; $row['meet_pswd'] = $_POST['meet_pswd'] ?? ''; $row['meet_url'] = $_POST['meet_url'] ?? ''; $row['meet_addr'] = $_POST['meet_addr'] ?? ''; $row['meet_desc'] = $_POST['meet_desc'] ?? ''; $row['dedicated_om'] = $_POST['dedicated_om'] ?? ''; $row['code_b'] = $_POST['code_b'] ?? ''; $row['code_d'] = $_POST['code_d'] ?? ''; $row['code_o'] = $_POST['code_o'] ?? ''; $row['code_w'] = $_POST['code_w'] ?? ''; $row['code_beg'] = $_POST['code_beg'] ?? ''; $row['code_h'] = $_POST['code_h'] ?? ''; $row['code_sp'] = $_POST['code_sp'] ?? ''; $row['code_c'] = $_POST['code_c'] ?? ''; $row['code_m'] = $_POST['code_m'] ?? ''; $row['code_ss'] = $_POST['code_ss'] ?? ''; $row['month_speaker'] = $_POST['month_speaker'] ?? ''; $row['potluck'] = $_POST['potluck'] ?? ''; $row['link1'] = trim($_POST['link1']) ?? ''; $row['link2'] = trim($_POST['link2']) ?? ''; $row['link3'] = trim($_POST['link3']) ?? ''; $row['link4'] = trim($_POST['link4']) ?? ''; $row['hid_f1'] = ''; $row['hid_f2'] = ''; $row['hid_f3'] = ''; $row['hid_f4'] = ''; $row['add_note'] = $_POST['add_note'] ?? ''; $result = create_new_meeting($row, $nf1, $fn1, $nf2, $fn2, $nf3, $fn3, $nf4, $fn4); if ($result === true) { $new_id = mysqli_insert_id($db); header('location: manage_new_review.php?id=' . $new_id); } else { $errors = $result; } } // end > if (is_post_request()) { require '_includes/head.php'; ?> <body> <?php if (WWW_ROOT != 'http://localhost/evergreenaa') { ?> <div class="preload-manage"> <p>One meeting at a time.</p> </div> <?php } ?> <?php require '_includes/nav.php'; ?> <?php require '_includes/msg-set-timezone.php'; ?> <?php require '_includes/msg-extras.php'; ?> <?php require '_includes/msg-role-key.php'; ?> <?php require '_includes/lat-long-instructions.php'; ?> <?php require '_includes/descriptive-location-msg.php'; ?> <?php require '_includes/pdf-upload-txt.php'; ?> <?php require '_includes/link-label-txt.php'; ?> <img class="background-image" src="_images/aa-logo-dark_mobile.gif" alt="AA Logo"> <div id="manage-wrap"> <div class="manage-simple intro"> <?php if ($role != 1 && $role != 2) { ?> <p>Meetings save lives. <i class="fas fa-om"></i></p> <?php } else if ($role == 1) { ?> <p>Hey Me,</p> <p>Quit talking to yourself.</p> <?php } else { ?> <p>Hey<?= ' ' . $_SESSION['username'] . ',' ?></p> <p>Meetings save lives. <i class="fas fa-om"></i></p> <?php } ?> <?php require '_includes/inner_nav.php'; ?> </div> <div class="manage-simple empty"> <h1 class="edit-h1">Add a New Meeting</h1> <?php echo display_errors($errors); ?> <div class="weekday-edit-wrap"> <?php require '_includes/new-details.php'; ?> </div><!-- .weekday-wrap --> </div> </div><!-- #manage-wrap --> <?php require '_includes/footer.php'; ?><file_sep>/email_review_PERSONAL.php <?php $layout_context = "email-everyone"; require_once 'config/initialize.php'; // For my eyes only! if ($_SESSION['id'] != 1) { header('location: https://www.merriam-webster.com/dictionary/go%20away'); exit(); } ?> <?php if (is_post_request()) { // $email_addresses = $_POST['email_addresses']; $msgsubject = $_POST['msgsubject'] ?? ''; $greeting = $_POST['greeting'] ?? ''; $emaileveryonemsg = $_POST['emaileveryonemsg'] ?? ''; ?> <?php $result = find_all_users(); $emails = array(); while($subject = mysqli_fetch_assoc($result)) { $emails[] = "'" . $subject["email"] . "', "; } // get rid of the last comma $email_addresses = substr(implode($emails), 0 , -2); // echo "<br><br><br><div style=\"width:80%;margin:0 auto;padding:1.5em;border:1px solid #fff;background-color:#fefefe;color:#313131;\">" . $email_addresses . "</div>"; ?> <?php require '_includes/head.php'; ?> <body> <?php require '_includes/nav.php'; ?> <?php require '_includes/msg-set-timezone.php'; ?> <?php require '_includes/msg-extras.php'; ?> <?php require '_includes/msg-role-key.php'; ?> <img class="background-image" src="_images/aa-logo-dark_mobile.gif" alt="AA Logo"> <div id="manage-wrap"> <div class="manage-simple-admin"> <h1>Email All Members - Review Message</h1> <p class="admin-email"> <a href="manage.php">Back</a> | <a href="logout.php">Logout</a> </p> </div> <div class="manage-simple-email"> <div class="email-everyone-review"> <h3>Subject</h3> <p><?php echo $msgsubject; ?></p> <h3 class="next">Message</h3> <p><?php echo $greeting . ' Bob,<br><br>' . nl2br($emaileveryonemsg); ?></p> </div> <form class="admin-email-form" action="email_everyone_PERSONAL.php" method="post"> <input type="hidden" name="msgsubject" value="<?= $msgsubject; ?>"> <input type="hidden" name="greeting" value="<?= $greeting; ?>"> <textarea name="emaileveryonemsg" style="display:none;"><?= $emaileveryonemsg; ?></textarea> <div class="update-rt"> <a class="cancel" href="manage.php">CANCEL</a> <input type="submit" name="revise" class="revise-email" value="REVISE"> <input type="submit" name="email-everyone" class="submit-email" value="SEND"> </div><!-- .update-rt --> </div><!-- .btm-notes --> </form> </div> </div><!-- #manage-wrap --> <?php require '_includes/footer.php'; ?> <?php } //?><file_sep>/_includes/footer.php <?php error_reporting(0); function ewd_copyright($startYear) { $currentYear = date('Y'); if ($startYear < $currentYear) { $currentYear = date('y'); // return "<i class=\"fas fa-peace\"></i> $startYear&ndash;$currentYear"; return "<i class=\"far fa-heart\"></i> $startYear&ndash;$currentYear"; } else { // return "<i class=\"fas fa-peace\"></i> $startYear"; return "<i class=\"far fa-heart\"></i> $startYear"; } } ?> <footer> <div id="toggle-contact-form">comments | questions | suggestions</div> <div id="email-bob"> <p class="form-note">Note: Hosts are responsible for the content of their meetings. Contact below for technical issues and feature requests. If you would like to personalize this website <a class="ytv" href="https://youtu.be/CC1HlQcmy6c" target="_blank">please see this</a> short YouTube video. <i class="far fa-smile"></i></p> <form id="contactForm"> <ul> <li> <label class="text" for="name">Name</label> <input required name="name" type="text" id="name"> </li> <li> <label class="text" for="email" required>Email</label> <input name="email" type="email" id="email"> </li> <li> <label class="text" for="comments">Message</label> <textarea required name="comments" id="comments"></textarea> </li> <li> <div id="msg"></div> </li> <li class="embtn"> <input id="emailBob" value="Send"> </li> </ul> </form> </div> <p class="copyright"><?= ewd_copyright(2020); ?> <a class="eb" href="http://evergreenbob.com" target="_blank">Evergreen Bob</a></p> </footer> <?php if (($layout_context != 'login-page') && ($layout_context != 'message-board')) { ?> <!-- Modal --> <div id="theModal" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <a class="static closefp"><i class="fas fa-fw fa-times"></i></a> <h4 id="msg-title" class="modal-title"></h4> <h4 id="mtgname" class="modal-title"></h4> </div> <div class="modal-body"> <form id="emh-contact" class="emh-form"> <input type="hidden" name="tuid" id="tuid"> <input type="hidden" name="mtgid" id="mtgid"> <input type="hidden" name="vdt" id="vdt"> <input type="hidden" name="vtz" id="vtz"> <input type="hidden" name="mtgname" id="mtgnamez"> <input type="hidden" name="ri" id="ri"> <label id="your-name">Your name <input name="name" id="emh-name" class="edit-input link-name" type="text" maxlength="30"></label> <label id="your-email">Your email <input name="email" id="emh-email" class="edit-input link-email" type="email" maxlength="250"></label> <label><span id="msg-label"></span> <textarea name="emhmsg" id="emh-msg" class="edit-input link-msg" maxlength="2000"></textarea> </label> <div id="emh-contact-msg"></div> <div id="submit-links" class="submit-links"></div><!-- #submit-links --> </form> </div> <div class="modal-footer"> <h3>&nbsp;</h3> </div> </div> </div> </div> <?php } ?> <?php if ($layout_context == 'message-board') { ?> <!-- Modal --> <div id="theModal" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <a class="static closefp"><i class="fas fa-fw fa-times"></i></a> <h4 class="modal-title">Start a new topic</h4> <h4 id="mtgname" class="modal-title"></h4> </div> <div class="modal-body"> <form id="mb" class="emh-form"> <input type="hidden" name="mtgid" id="mtgid"> <input type="hidden" name="mtgname" id="mtgnamez"> <input type="hidden" id="user-posting" value="<?= $_SESSION['username'] ?>"> <label>Title | Topic | Headline <input id="mb-title" name="mb-title" class="edit-input link-name" type="text" maxlength="50"></label> <label>Body <textarea name="mb-post" id="emh-msg" class="edit-input link-msg" maxlength="250"></textarea> </label> <div id="emh-contact-msg"></div> <div class="submit-links"> <input type="button" id="mb-new" class="send" value="Post it"> </div><!-- #submit-links --> </form> </div> <div class="modal-footer"> <h3>&nbsp;</h3> </div> </div> </div> </div> <?php require '_includes/msg-message-board-join.php' ?> <?php } ?> <?php switch ($layout_context) { case 'home-private' : echo "<script type=\"text/javascript\" src=\"js/jquery.backstretch.min.js?" . time() . "\"></script>"; break; case 'home-public' : echo "<script type=\"text/javascript\" src=\"js/jquery.backstretch.min.js?" . time() . "\"></script>"; break; case 'message-board' : echo "<script type=\"text/javascript\" src=\"js/jquery.backstretch.msg-board.js?" . time() . "\"></script>"; break; case 'post-page' : echo "<script type=\"text/javascript\" src=\"js/jquery.backstretch.msg-board.js?" . time() . "\"></script>"; break; default : echo "<script type=\"text/javascript\" src=\"js/jquery.backstretch.landing-pgs.js?" . time() . "\"></script>"; break; } ?> <script src="js/jquery.timepicker.min.js?<?php echo time(); ?>"></script> <script src="js/scripts.js?<?php echo time(); ?>"></script> <?php if (WWW_ROOT == 'http://localhost/evergreenaa') { ?> <script src="http://localhost:35729/livereload.js"></script> <?php } ?> </body> </html> <?php db_disconnect($db); ?><file_sep>/email_members.php <?php require_once 'config/initialize.php'; $layout_context = "alt-manage"; if ($_SESSION['id'] != 1) { header('location: https://www.merriam-webster.com/dictionary/go%20away'); exit(); } $resultz = find_all_hosts(); $emailz = array(); while($subject = mysqli_fetch_assoc($resultz)) { $emailz[] = $subject['email'] . "; "; } $member_addresses = substr(implode($emailz), 0 , -2); $result = find_all_users(); $emails = array(); // get email addresses ready for sending and put them in a hidden field while($subject = mysqli_fetch_assoc($result)) { $emails[] = $subject['email'] . "; "; } // get rid of the last comma $all_email_addresses = substr(implode($emails), 0 , -2); ?> <?php require '_includes/head.php'; ?> <body> <?php require '_includes/nav.php'; ?> <?php require '_includes/msg-set-timezone.php'; ?> <?php require '_includes/msg-extras.php'; ?> <?php require '_includes/msg-role-key.php'; ?> <img class="background-image" src="_images/aa-logo-dark_mobile.gif" alt="AA Logo"> <div id="manage-wrap"> <div class="manage-simple intro"> <p>Email All Members</p> <?php require '_includes/inner_nav.php'; ?> </div> <div class="manage-simple-email"> <form class="admin-email-form" action="email_review_BCC.php" method="post"> <div class="bccem"> <input id="pickitup" type="hidden" value="<?= strtolower($member_addresses); ?>" class="day-values input-copy"> <a data-role="em" data-id="pickitup"><i class="far fa-copy"></i> Only Hosts</a> <input id="pickemup" type="hidden" value="<?= strtolower($all_email_addresses); ?>" class="day-values input-copy"> <a data-role="em" data-id="pickemup"><i class="far fa-copy"></i> All Addresses</a> </div> </div><!-- .btm-notes --> </form> </div> </div><!-- #manage-wrap --> <?php require '_includes/footer.php'; ?> <?php mysqli_free_result($result); ?> <file_sep>/error-reporting.php <?php mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // error_reporting(0); // turns off all error reporting error_reporting(-1); // reports all errors // ini_set("display_errors", "1"); // shows all errors in browser ini_set("display_errors", "0"); // hides errors from browser ini_set("log_errors", 1); ini_set("error_log", "_errors.txt"); // prints to file 'php-error.txt' so I can read it in browser. preceeding underscore is so it's at top of list and easy to find.<file_sep>/process-edit-sus_note.php <?php require_once 'config/initialize.php'; if (is_post_request()) { $reason = trim(h($_POST['reason'])); $user = $_POST['user-id']; if($reason) { $update_sus_notes = update_sus_note($reason, $user); if ($update_sus_notes === true) { $signal = 'ok'; $msg = 'Transfer successful!'; } else { $signal = 'bad'; $msg = 'Hmm, that didn\'t seem to take. You can try refreshing the page and doing it again or maybe your Internet is down? You\'d still see this message even if your Internet connection had dropped since you started this.'; } } else { $signal = 'bad'; $msg = 'Please give them some kind of reason for getting suspended.'; } } $data = array( 'signal' => $signal, 'msg' => $msg ); echo json_encode($data); <file_sep>/_includes/new-details.php <div class="meeting-details"> <p class="mtg-tz">Your current timezone is set to: <a id="show-tz" class="inline-show-tz"><?php pretty_tz($tz); ?></a>.</p> <form id="manage-mtg" action="" method="post" enctype="multipart/form-data"> <div class="top-info"> <p class="days-held">Group name</p> <input type="text" class="mtg-update group-name<?php if (isset($errors['group_name'])) { echo " fixerror"; } ?>" name="group_name" value="<?php if (isset($_POST['group_name'])) { echo $_POST['group_name']; } ?>" placeholder="Group name"> <p class="days-held">Day(s) meeting is held</p> <div class="align-days<?php if (isset($errors['pick_a_day'])) { echo " fixerror"; } ?>"> <div> <input type="hidden" name="sun" value="0"> <label><input type="checkbox" name="sun" value="1" <?php if ((isset($row['sun']) && ($row['sun'])) != 0) { echo "checked"; } ?> /> <span>Sunday</span></label> | </div> <div> <input type="hidden" name="mon" value="0"> <label><input type="checkbox" name="mon" value="1" <?php if ((isset($row['mon']) && ($row['mon'])) != 0) { echo "checked"; } ?> /> <span>Monday</span></label> | </div> <div> <input type="hidden" name="tue" value="0"> <label><input type="checkbox" name="tue" value="1" <?php if ((isset($row['tue']) && ($row['tue'])) != 0) { echo "checked"; } ?> /> <span>Tuesday</span></label> | </div> <div> <input type="hidden" name="wed" value="0"> <label><input type="checkbox" name="wed" value="1" <?php if ((isset($row['wed']) && ($row['wed'])) != 0) { echo "checked"; } ?> /> <span>Wednesday</span></label> | </div> <div> <input type="hidden" name="thu" value="0"> <label><input type="checkbox" name="thu" value="1" <?php if ((isset($row['thu']) && ($row['thu'])) != 0) { echo "checked"; } ?> /> <span>Thursday</span></label> | </div> <div> <input type="hidden" name="fri" value="0"> <label><input type="checkbox" name="fri" value="1" <?php if ((isset($row['fri']) && ($row['fri'])) != 0) { echo "checked"; } ?> /> <span>Friday</span></label> | </div> <div> <input type="hidden" name="sat" value="0"> <label><input type="checkbox" name="sat" value="1" <?php if ((isset($row['sat']) && ($row['sat'])) != 0) { echo "checked"; } ?> /> <span>Saturday</span></label> </div> </div><!-- .align-days --> <p class="time-held">Time</p> <div class="mtg-time"> <?php /* https://timepicker.co/options/ */ ?> <input name="meet_time" class="timepicker<?php if (isset($errors['meet_time'])) { echo " fixerror"; } ?>" value="<?php if (isset($row['meet_time'])) { echo $row['meet_time']; } ?>"> </div> </div><!-- .top-info --> <div class="details-left"> <label for="meet_phone">Phone number</label> <input type="text" class="mtg-update<?php if (isset($errors['meet_phone'])) { echo " fixerror"; } ?>" name="meet_phone" value="<?php if (isset($row['meet_phone']) && ($row['meet_phone'] != "")) { echo "(" .substr(h($row['meet_phone']), 0, 3).") ".substr(h($row['meet_phone']), 3, 3)."-".substr(h($row['meet_phone']),6); } ?>" placeholder="10-digit phone #"> <label for="one_tap">One Tap Mobile <a id="toggle-one-tap-msg"><i class="far fa-question-circle fa-fw"></i></a></label><?php // #toggle-one-tap-msg is inside lat-long-instructions.php ?> <input type="text" class="mtg-update<?php if (isset($errors['one_tap'])) { echo " fixerror"; } ?>" name="one_tap" value="<?php if (isset($row['one_tap'])) { echo h($row['one_tap']); } ?>" placeholder="One Tap Mobile #"> <label for="meet_id">ID number</label> <input type="text" class="mtg-update<?php if (isset($errors['meet_id'])) { echo " fixerror"; } ?>" name="meet_id" value="<?php if (isset($row['meet_id'])) { echo h($row['meet_id']); } ?>" placeholder="ID Number"> <label for="meet_pswd">Password</label> <input type="text" class="mtg-update<?php if (isset($errors['meet_pswd'])) { echo " fixerror"; } ?>" name="meet_pswd" value="<?php if (isset($row['meet_pswd'])) { echo h($row['meet_pswd']); } ?>" placeholder="<PASSWORD>"> <label for="meet_url">Online URL</label> <textarea name="meet_url" id="meet_url" class="<?php if (isset($errors['meet_url'])) { echo " fixerror"; } ?>" placeholder="https://zoom-address-here/"><?php if (isset($row['meet_url'])) { echo h($row['meet_url']); } ?></textarea> <label for="meet_addr">Physical Address | lat°, long° accepted <a id="toggle-lat-long-msg"><i class="far fa-question-circle fa-fw"></i></a></label> <textarea name="meet_addr" id="meet_addr" class="<?php if (isset($errors['meet_url']) || isset($errors['url_and_phy'])) { echo " fixerror"; } ?>" placeholder="123 Main St, Evergreen, CO"><?php if (isset($row['meet_addr'])) { echo h($row['meet_addr']); } ?></textarea> <label for="meet_desc">Descriptive Location <a id="toggle-descriptive-location"><i class="far fa-question-circle fa-fw"></i></a></label> <textarea name="meet_desc" id="meet_desc" placeholder="123 Main St.&#10;Evergreen, CO&#10;Around back, 2nd floor"><?php if (isset($row['meet_desc'])) { h($row['meet_desc']); } ?></textarea> </div><!-- .details-left --> <div class="details-right<?php if (isset($errors['meeting_type']) || isset($errors['url_or_phy'])) { echo " fixerror"; } ?>"> <p class="add-info<?php if (isset($errors['meeting_type']) || isset($errors['url_or_phy']) || isset($errors['url_and_phy'])) { echo " fixerror"; } ?>">Select all that apply</p> <input type="hidden" name="dedicated_om" value="0"> <label><input type="checkbox" name="dedicated_om" <?php if (isset($row['dedicated_om']) && $row['dedicated_om'] == "1") { echo "checked"; } ?> value="1" /> <span>Dedicated Online Meeting</span></label> <input type="hidden" name="code_o" value="0"> <label><input type="checkbox" name="code_o" class="omw oc" <?php if (isset($row['code_o']) && $row['code_o'] == "1") { echo "checked"; } ?> value="1" /> <span>Open: Anyone may attend</span></label> <input type="hidden" name="code_w" value="0"> <label><input type="checkbox" name="code_w" class="omw" <?php if (isset($row['code_w']) && $row['code_w'] == "1") { echo "checked"; } ?> value="1" /> <span>Women's Meeting</span></label> <input type="hidden" name="code_m" value="0"> <label><input type="checkbox" name="code_m" class="omw" <?php if (isset($row['code_m']) && $row['code_m'] == "1") { echo "checked"; } ?> value="1" /> <span>Men's Meeting</span></label> <input type="hidden" name="code_c" value="0"> <label><input type="checkbox" name="code_c" class="oc" <?php if (isset($row['code_c']) && $row['code_c'] == "1") { echo "checked"; } ?> value="1" /> <span>Closed Meeting</span></label> <input type="hidden" name="code_beg" value="0"> <label><input type="checkbox" name="code_beg" <?php if (isset($row['code_beg']) && $row['code_beg'] == "1") { echo "checked"; } ?> value="1" /> <span>Beginner's Meeting</span></label> <input type="hidden" name="code_h" value="0"> <label><input type="checkbox" name="code_h" <?php if (isset($row['code_h']) && $row['code_h'] == "1") { echo "checked"; } ?> value="1" /> <span>Handicap</span></label> <input type="hidden" name="code_d" value="0"> <label><input type="checkbox" name="code_d" <?php if (isset($row['code_d']) && $row['code_d'] == "1") { echo "checked"; } ?> value="1" /> <span>Discussion Meeting</span></label> <input type="hidden" name="code_b" value="0"> <label><input type="checkbox" name="code_b" <?php if (isset($row['code_b']) && $row['code_b'] == "1") { echo "checked"; } ?> value="1" /> <span>Book Study</span></label> <input type="hidden" name="code_ss" value="0"> <label><input type="checkbox" name="code_ss" <?php if (isset($row['code_ss']) && $row['code_ss'] == "1") { echo "checked"; } ?> value="1" /> <span>Step Study</span></label> <input type="hidden" name="code_sp" value="0"> <label><input type="checkbox" name="code_sp" <?php if (isset($row['code_sp']) && $row['code_sp'] == "1") { echo "checked"; } ?> value="1" /> <span>Speaker Meeting</span></label> <input type="hidden" name="month_speaker" value="0"> <label><input type="checkbox" name="month_speaker" <?php if (isset($row['month_speaker']) && $row['month_speaker'] == "1") { echo "checked"; } ?> value="1" /> <span>Speaker Meeting on last Sunday of month</span></label> <input type="hidden" name="potluck" value="0"> <label><input type="checkbox" name="potluck" <?php if (isset($row['potluck']) && $row['potluck'] == "1") { echo "checked"; } ?> value="1" /> <span>Potluck</span></label> </div><!-- .details-right --> <div class="btm-notes"> <div class="file-uploads"> <p>Upload PDF Files <a id="toggle-pdf-info"><i class="far fa-question-circle fa-fw"></i></a></p> <div id="pdf1" class="pdf-wrap pdf1<?php if (isset($errors['name_link1'])) { echo " fixerror"; } ?>"> <div class="pdf-row"> <input type="file" class="pdf1_name" id="file1" name="file1" accept=".pdf"> <label class="pdf-label">Link 1 label <input type="text" class="pdf1_name" name="link1" value="<?php if (isset($row['link1'])) { echo trim(h($row['link1'])); } ?>" maxlength="25"> <a id="toggle-link-label"><i class="far fa-question-circle fa-fw"></i></a></label> </div> <div class="pdf-remove"> <a class="pdf-remove pdf-remove-1">Remove</a> </div> </div> <div id="pdf2" class="pdf-wrap pdf2<?php if (isset($errors['name_link2'])) { echo " fixerror"; } ?>"> <div class="pdf-row"> <input type="file" class="pdf2_name" id="file2" name="file2" accept=".pdf"> <label class="pdf-label">Link 2 label <input type="text" class="pdf2_name" name="link2" value="<?php if (isset($row['link2'])) { echo trim(h($row['link2'])); } ?>" maxlength="25"></label> </div> <div class="pdf-remove"> <a class="pdf-remove pdf-remove-2">Remove</a> </div> </div> <div id="pdf3" class="pdf-wrap pdf3<?php if (isset($errors['name_link3'])) { echo " fixerror"; } ?>"> <div class="pdf-row"> <input type="file" class="pdf3_name" id="file3" name="file3" accept=".pdf"> <label class="pdf-label">Link 3 label <input type="text" class="pdf3_name" name="link3" value="<?php if (isset($row['link3'])) { echo trim(h($row['link3'])); } ?>" maxlength="25"></label> </div> <div class="pdf-remove"> <a class="pdf-remove pdf-remove-3">Remove</a> </div> </div> <div id="pdf4" class="pdf-wrap pdf4<?php if (isset($errors['name_link4'])) { echo " fixerror"; } ?>"> <div class="pdf-row"> <input type="file" class="pdf4_name" id="file4" name="file4" accept=".pdf"> <label class="pdf-label">Link 4 label <input type="text" class="pdf4_name" name="link4" value="<?php if (isset($row['link4'])) { echo trim(h($row['link4'])); } ?>" maxlength="25"></label> </div> <div class="pdf-remove"> <a class="pdf-remove pdf-remove-4">Remove</a> </div> </div> <a id="file-upload"><i class="far fa-plus-square fa-fw"></i> Add a PDF | 4 Total</a> </div> <label for="add_note">Additional notes</label> <textarea name="add_note" class="meetNotes<?php if (isset($errors['add_note'])) { echo " fixerror"; } ?>" placeholder="Text only. 1,000 characters or less. All formatting will be stripped."><?php if (isset($row['add_note']) && $row['add_note'] != '') { echo nl2br(h($row['add_note'])); } ?></textarea> <div class="update-rt"> <a class="cancel" href="manage.php">CANCEL</a> <input type="submit" id="review-mtg" name="review-mtg" class="submit" value="REVIEW"> </div><!-- .update-rt --> </div><!-- .btm-notes --> </form> </div><!-- .meeting-details --> <file_sep>/manage_create.php <?php require_once 'config/initialize.php'; require_once 'config/verify_admin.php'; if ($_SESSION['admin'] == 85 || $_SESSION['admin'] == 86) { header('location: ' . WWW_ROOT); exit(); } if (is_post_request()) { $row = []; $row['$id_user'] = $_SESSION['id'] ; $row['$sun'] = $_POST['sun'] ?? ''; $row['$mon'] = $_POST['mon'] ?? ''; $row['$tue'] = $_POST['tue'] ?? ''; $row['$wed'] = $_POST['wed'] ?? ''; $row['$thu'] = $_POST['thu'] ?? ''; $row['$fri'] = $_POST['fri'] ?? ''; $row['$sat'] = $_POST['sat'] ?? ''; $row['$meet_time'] = (preg_replace('/[^0-9]/', '', $_POST['mtgHour']) . preg_replace('/[^0-9]/', '', $_POST['mtgMinute'])) ?? ''; $row['$mtgHour'] = preg_replace('/[^0-9]/', '', $_POST['mtgHour']) ?? ''; $row['$mtgMinute'] = preg_replace('/[^0-9]/', '', $_POST['mtgMinute']) ?? ''; // $row['$mtgMinute'] = $_POST['mtgMinute'] ?? ''; $row['$am_pm'] = $_POST['am_pm'] ?? ''; $row['$group_name'] = $_POST['group_name'] ?? ''; $row['$meet_phone'] = preg_replace('/[^0-9]/', '', $_POST['meet_phone']) ?? ''; $row['$meet_id'] = $_POST['meet_id'] ?? ''; $row['$meet_pswd'] = $_POST['meet_pswd'] ?? ''; $row['$meeturl'] = $_POST['meeturl'] ?? ''; $row['$dedicated_om'] = $_POST['dedicated_om'] ?? ''; $row['$code_b'] = $_POST['code_b'] ?? ''; $row['$code_d'] = $_POST['code_d'] ?? ''; $row['$code_o'] = $_POST['code_o'] ?? ''; $row['$code_w'] = $_POST['code_w'] ?? ''; $row['$code_beg'] = $_POST['code_beg'] ?? ''; $row['$code_h'] = $_POST['code_h'] ?? ''; $row['$code_sp'] = $_POST['code_sp'] ?? ''; $row['$code_c'] = $_POST['code_c'] ?? ''; $row['$code_m'] = $_POST['code_m'] ?? ''; $row['$code_ss'] = $_POST['code_ss'] ?? ''; $row['$month_speaker'] = $_POST['month_speaker'] ?? ''; $row['$potluck'] = $_POST['potluck'] ?? ''; $row['$add_note'] = $_POST['add_note'] ?? ''; $result = create_new_meeting($row); if ($result === true) { $new_id = mysqli_insert_id($db); header('location: manage_edit_review.php?id=' . $new_id); } else { $errors = $result; } } ?><file_sep>/_includes/head.php <!DOCTYPE html> <html lang="en"> <!-- ♥ Hand coded with love by EvergreenBob.com --> <head> <meta charset="UTF-8"> <title>Evergreen AA | Online AA Meetings</title> <link rel="icon" type="image/ico" href="_images/favicon.ico"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta name="description" content="A convenient utility to consolidate and organize all of your AA meeting information in one location. For happy, beautiful people everywhere. :)"> <meta name="format-detection" content="telephone=no"> <meta property="og:url" content="https://evergreenaa.com/" /> <meta property="og:type" content="website" /> <meta property="og:title" content="Evergreen AA | Online AA Meetings" /> <meta property="og:image" content="https://evergreenaa.com/_images/aa-logo.jpg" /> <meta property="og:image:alt" content="AA Logo" /> <meta property="og:description" content="A convenient utility to consolidate and organize all of your AA meeting information in one location. For happy, beautiful people everywhere. :)" /> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.1/css/all.css"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.12.1/css/v4-shims.css"> <link href='https://fonts.googleapis.com/css?family=Architects+Daughter|Cinzel|Courier+Prime|Special+Elite|Caveat&display=block' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="style.css?<?php echo time(); ?>" type="text/css"> <script src="js/jquery-3.5.1.min.js"></script> <script src="js/jquery_1-12-1_ui_min.js"></script> <!-- Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-140046709-8"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-140046709-8'); </script> <script src="js/preload.js?<?php echo time(); ?>"></script> </head> <file_sep>/home_admin.php <?php require_once 'config/initialize.php'; require_once 'config/verify_admin.php'; $layout_context = "home-private"; // keep this bc it overrides previous setting // and allows admin to do whatever they need $user_id = $_SESSION['admin']; require '_includes/head.php'; ?> <body> <?php if (WWW_ROOT != 'http://localhost/evergreenaa') { ?> <div class="preload"> <p>One day at a time.</p> </div> <?php } ?> <?php require '_includes/nav.php'; ?> <?php require '_includes/msg-set-timezone.php'; ?> <?php require '_includes/msg-extras.php'; ?> <?php require '_includes/msg-role-key.php'; ?> <img class="background-image" src="_images/aa-logo-dark_mobile.gif" alt="AA Logo"> <div id="wrap"> <ul id="weekdays"> <?php // this block only needed once for page $dt = new DateTime('now'); $user_tz = new DateTimeZone($tz); $dt->setTimezone($user_tz); $offset = $dt->format('P'); // find offset +, - or = +00:00 if ($user_id == 1) { $subject_set = get_all_public_and_private_meetings_for_odin(); } else { $subject_set = get_all_public_and_private_meetings_for_today($user_id); } if ($offset == '+00:00') { $time_offset = '00'; $sorted = mysqli_fetch_all($subject_set, MYSQLI_ASSOC); } else if (strpos($offset, '+') !== false) { $time_offset = 'pos'; $results = mysqli_fetch_all($subject_set, MYSQLI_ASSOC); } else if (strpos($offset, '-') !== false) { $time_offset = 'neg'; $results = mysqli_fetch_all($subject_set, MYSQLI_ASSOC); } if ($time_offset != '00') { $sorted = apply_offset_to_meetings($results, $tz, $time_offset); } ?> <li class="ctr-day"> <button id="open-sunday" class="day">Sunday</button> <div id="sunday-content" class="day-content"> <?php include '_includes/collapse-day.php'; ?> <p class="inline-tz"><a class="inline-show-tz"><?php pretty_tz($tz); ?></span></a></p> <?php $today = 'Sunday'; list($yesterday, $tomorrow, $y, $d, $t) = day_range($today); $user_tz = new DateTimeZone($tz); // -7/dst: -6 // $lc = substr($t, 0,3); $i = 1; foreach ($sorted as $row) { // $mt = new DateTime($today . ' ' . $row['meet_time']); $mt = new DateTime($row['meet_time']); $mt->setTimezone($user_tz); $ic = 'i0_'.$i; $pc = 'p0_'.$i; if (($row['issues'] < 3) && ($row[$d] == '1')) { $mtgs_exist = $today; require '_includes/admin-daily-glance.php'; ?> <div class="weekday-wrap <?php if (!empty($row['add_note'])) { echo 'note-here'; } ?>"> <?php require '_includes/admin-meeting-details.php'; ?> </div><!-- .weekday-wrap --> <?php } $i++; } if (!isset($mtgs_exist) || $mtgs_exist != $today) { ?> <p class="no-mtgs">No meetings posted for <?= $today . ' ' . $offset ?>.</p> <?php } ?> </div><!-- #sunday-content .day-content --> </li> <li class="ctr-day"> <button id="open-monday" class="day">Monday</button> <div id="monday-content" class="day-content"> <?php include '_includes/collapse-day.php'; ?> <p class="inline-tz"><a class="inline-show-tz"><?php pretty_tz($tz); ?></span></a></p> <?php $today = 'Monday'; list($yesterday, $tomorrow, $y, $d, $t) = day_range($today); $i = 1; foreach ($sorted as $row) { $mt = new DateTime($row['meet_time']); $mt->setTimezone($user_tz); $ic = 'i1_'.$i; $pc = 'p1_'.$i; if (($row['issues'] < 3) && ($row[$d] == '1')) { $mtgs_exist = $today; require '_includes/admin-daily-glance.php'; ?> <div class="weekday-wrap <?php if (!empty($row['add_note'])) { echo 'note-here'; } ?>"> <?php require '_includes/admin-meeting-details.php'; ?> </div><!-- .weekday-wrap --> <?php } $i++; } if (!isset($mtgs_exist) || $mtgs_exist != $today) { ?> <p class="no-mtgs">No meetings posted for <?= $today ?>.</p> <?php } ?> </div><!-- #monday-content .day-content --> </li> <li class="ctr-day"> <button id="open-tuesday" class="day">Tuesday</button> <div id="tuesday-content" class="day-content"> <?php include '_includes/collapse-day.php'; ?> <p class="inline-tz"><a class="inline-show-tz"><?php pretty_tz($tz); ?></span></a></p> <?php $today = 'Tuesday'; list($yesterday, $tomorrow, $y, $d, $t) = day_range($today); $i = 1; foreach ($sorted as $row) { // AM meetings $mt = new DateTime($row['meet_time']); $mt->setTimezone($user_tz); $ic = 'i2_'.$i; $pc = 'p2_'.$i; if (($row['issues'] < 3) && ($row[$d] == '1')) { $mtgs_exist = $today; // echo $today . ' ' . $mtz; require '_includes/admin-daily-glance.php'; ?> <div class="weekday-wrap <?php if (!empty($row['add_note'])) { echo 'note-here'; } ?>"> <?php require '_includes/admin-meeting-details.php'; ?> </div><!-- .weekday-wrap --> <?php } $i++; } if (!isset($mtgs_exist) || $mtgs_exist != $today) { ?> <p class="no-mtgs">No meetings posted for <?= $today ?>.</p> <?php } ?> </div><!-- #tuesday-content .day-content --> </li> <li class="ctr-day"> <button id="open-wednesday" class="day">Wednesday</button> <div id="wednesday-content" class="day-content"> <?php include '_includes/collapse-day.php'; ?> <p class="inline-tz"><a class="inline-show-tz"><?php pretty_tz($tz); ?></span></a></p> <?php $today = 'Wednesday'; list($yesterday, $tomorrow, $y, $d, $t) = day_range($today); $i = 1; foreach ($sorted as $row) { $mt = new DateTime($row['meet_time']); $mt->setTimezone($user_tz); $ic = 'i3_'.$i; $pc = 'p3_'.$i; if (($row['issues'] < 3) && ($row[$d] == '1')) { $mtgs_exist = $today; require '_includes/admin-daily-glance.php'; ?> <div class="weekday-wrap <?php if (!empty($row['add_note'])) { echo 'note-here'; } ?>"> <?php require '_includes/admin-meeting-details.php'; ?> </div><!-- .weekday-wrap --> <?php } $i++; } if (!isset($mtgs_exist) || $mtgs_exist != $today) { ?> <p class="no-mtgs">No meetings posted for <?= $today ?>.</p> <?php } ?> </div><!-- #wednesday-content .day-content --> </li> <li class="ctr-day"> <button id="open-thursday" class="day">Thursday</button> <div id="thursday-content" class="day-content"> <?php include '_includes/collapse-day.php'; ?> <p class="inline-tz"><a class="inline-show-tz"><?php pretty_tz($tz); ?></span></a></p> <?php $today = 'Thursday'; list($yesterday, $tomorrow, $y, $d, $t) = day_range($today); $i = 1; foreach ($sorted as $row) { $mt = new DateTime($row['meet_time']); $mt->setTimezone($user_tz); $ic = 'i4_'.$i; $pc = 'p4_'.$i; if (($row['issues'] < 3) && ($row[$d] == '1')) { $mtgs_exist = $today; require '_includes/admin-daily-glance.php'; ?> <div class="weekday-wrap <?php if (!empty($row['add_note'])) { echo 'note-here'; } ?>"> <?php require '_includes/admin-meeting-details.php'; ?> </div><!-- .weekday-wrap --> <?php } $i++; } if (!isset($mtgs_exist) || $mtgs_exist != $today) { ?> <p class="no-mtgs">No meetings posted for <?= $today ?>.</p> <?php } ?> </div><!-- #thursday-content .day-content --> </li> <li class="ctr-day"> <button id="open-friday" class="day">Friday</button> <div id="friday-content" class="day-content"> <?php include '_includes/collapse-day.php'; ?> <p class="inline-tz"><a class="inline-show-tz"><?php pretty_tz($tz); ?></span></a></p> <?php $today = 'Friday'; list($yesterday, $tomorrow, $y, $d, $t) = day_range($today); $i = 1; foreach ($sorted as $row) { $mt = new DateTime($row['meet_time']); $mt->setTimezone($user_tz); $ic = 'i5_'.$i; $pc = 'p5_'.$i; if (($row['issues'] < 3) && ($row[$d] == '1')) { $mtgs_exist = $today; require '_includes/admin-daily-glance.php'; ?> <div class="weekday-wrap <?php if (!empty($row['add_note'])) { echo 'note-here'; } ?>"> <?php require '_includes/admin-meeting-details.php'; ?> </div><!-- .weekday-wrap --> <?php } $i++; } if (!isset($mtgs_exist) || $mtgs_exist != $today) { ?> <p class="no-mtgs">No meetings posted for <?= $today ?>.</p> <?php } ?> </div><!-- #friday-content .day-content --> </li> <li class="ctr-day"> <button id="open-saturday" class="day">Saturday</button> <div id="saturday-content" class="day-content"> <?php include '_includes/collapse-day.php'; ?> <p class="inline-tz"><a class="inline-show-tz"><?php pretty_tz($tz); ?></span></a></p> <?php $today = 'Saturday'; list($yesterday, $tomorrow, $y, $d, $t) = day_range($today); $i = 1; foreach ($sorted as $row) { $mt = new DateTime($row['meet_time']); $mt->setTimezone($user_tz); $ic = 'i6_'.$i; $pc = 'p6_'.$i; if (($row['issues'] < 3) && ($row[$d] == '1')) { $mtgs_exist = $today; require '_includes/admin-daily-glance.php'; ?> <div class="weekday-wrap <?php if (!empty($row['add_note'])) { echo 'note-here'; } ?>"> <?php require '_includes/admin-meeting-details.php'; ?> </div><!-- .weekday-wrap --> <?php } $i++; } if (!isset($mtgs_exist) || $mtgs_exist != $today) { ?> <p class="no-mtgs">No meetings posted for <?= $today ?>.</p> <?php } ?> <?php mysqli_free_result($subject_set); ?> </div><!-- #saturday-content .day-content --> </li> </ul><!-- #weekdays --> </div><!-- #wrap --> <?php require '_includes/footer.php'; ?><file_sep>/process-email-optinout.php <?php require_once 'config/initialize.php'; if (is_post_request()) { if(isset($_POST['email-updates'])) { $id = $_SESSION['id']; $email_opt = $_POST['email-updates']; $result = email_opt($id, $email_opt); if ($result === true) { $signal = 'ok'; $msg = 'Update successful!'; } else { $signal = 'bad'; $msg = 'That didn\'t work. Are you clicking over and over real fast? I may have skipped a beat somewhere. Reload this page and try again.'; } } } $data = array( 'signal' => $signal, 'msg' => $msg ); echo json_encode($data);
5db35d7296690da5933d4e494a90491810519525
[ "JavaScript", "PHP" ]
71
PHP
robertmeans/evergreenaa
f3b5401d1857a19bd122223f55f7d6fb845e44a8
b331d53012feb89ed531c20f318537ad00484bc6
refs/heads/master
<file_sep> input_file_name = "day10input.txt" if File.file?(input_file_name) # steps_string = File.open("advent_of_code_input.txt").read.to_s lines = File.readlines(input_file_name) else puts "PLEASE PROVIDE A VALID INPUT FILE" end my_ast_array = Array.new lines.each do |line| line.each_char do |c| my_ast_array.push(1) if c=="#" my_ast_array.push(0) if c=="." end end my_hash = Hash.new(0) max_hit = 0 my_ast_array.each_with_index do |element, index | if element == 1 x = index/48 y = index % 48 tmp_hash = Hash.new(0) my_ast_array.each_with_index do |e, i| if e == 1 && i != index x1 = i/48 y1 = i % 48 x_rate = x1-x y_rate = y1-y rate = x_rate.to_f / y_rate.to_f tmp_hash[[element, rate ]] = 1 if i< index tmp_hash[[-element, rate ]] = 1 if i >index end end my_hash[[x,y]] = tmp_hash.size end if my_hash[[x,y]] > max_hit max_hit = my_hash[[x,y]] end end puts "Max hit = #{max_hit}" <file_sep> input_file_name = "advent_of_code_input.txt" if File.file?(input_file_name) # steps_string = File.open("advent_of_code_input.txt").read.to_s lines = File.readlines(input_file_name) else puts "PLEASE PROVIDE A VALID INPUT FILE" end total = 0 lines.each do |step| total +=(step.to_f/3.0).floor - 2 end puts total <file_sep> input_file_name = "advent_of_code_input.txt" if File.file?(input_file_name) # steps_string = File.open("advent_of_code_input.txt").read.to_s lines = File.readlines("advent_of_code_input.txt") else puts "PLEASE PROVIDE A VALID INPUT FILE" end total = 0 lines.each do |step| inline_total = 0 mass = step.to_f # mass = 1969 loop do required_gas = (mass/3.0).floor - 2 >=0 ? (mass/3.0).floor - 2 : 0 # inline_total += (mass + required_gas) inline_total += required_gas break if required_gas <=0 mass = required_gas end total +=inline_total end puts total <file_sep> input_file_name = "day2input.txt" if File.file?(input_file_name) steps_string = File.open(input_file_name).read.to_s else puts "PLEASE PROVIDE A VALID INPUT FILE" end steps = steps_string.split(",") # outerloopbreak = false (0..99).each do |name| (0..99).each do |verb| steps[1] = name steps[2] = verb counter = 0 steps.each do |element| if counter % 4 == 0 i = counter if element.to_i == 1 first_add_element = steps[steps[i+1].to_i].to_i second_add_element = steps[steps[i+2].to_i].to_i steps[steps[i+3].to_i] = second_add_element + first_add_element elsif element.to_i == 2 first_mul_element = steps[steps[i+1].to_i].to_i second_mul_element = steps[steps[i+2].to_i].to_i steps[steps[i+3].to_i] = second_mul_element * first_mul_element elsif element.to_i == 99 break else puts "There is an error" end end counter+=1 end if steps[0] == 19690720 outerloopbreak = true puts "Name is #{name}" puts "Verb is #{verb}" puts "result is #{100 * name + verb}" break end steps = steps_string.split(",") end if outerloopbreak == true break end end <file_sep>input_file_name = "day8input.txt" if File.file?(input_file_name) steps_string = File.open(input_file_name).read.to_s else puts "PLEASE PROVIDE A VALID INPUT FILE" end layers = steps_string.scan(/.{150}/) fewest_zero_layer = "" fewest_zero_layer_count = 150 layers.each do |layer| if layer.count('0') < fewest_zero_layer_count fewest_zero_layer_count = layer.count('0') fewest_zero_layer = layer end end # puts fewest_zero_layer # puts fewest_zero_layer_count number_of_ones = fewest_zero_layer.count('1') number_of_two = fewest_zero_layer.count('2') puts result = number_of_ones * number_of_two <file_sep> input_file_name = "day7input.txt" if File.file?(input_file_name) steps_string = File.open(input_file_name).read.to_s else puts "PLEASE PROVIDE A VALID INPUT FILE" end steps = steps_string.split(",") def amplifier(steps, phase, input_elem) receive_phase_input = true output_element =0 arr_pos = 0 i = 0 loop do if i == arr_pos instructionArray = steps[i].to_s.split("") if instructionArray.length-2 >= 0 opcode = (instructionArray[instructionArray.length-2] + instructionArray[instructionArray.length-1]).to_i else opcode = (instructionArray[instructionArray.length-1]).to_i end if instructionArray.length-3 >=0 first_param_mode = instructionArray[instructionArray.length-3].to_i == 1 ? 1 : 0 else first_param_mode = 0 end if instructionArray.length-4 >=0 second_param_mode = instructionArray[instructionArray.length-4].to_i == 1 ? 1 : 0 else second_param_mode = 0 end if opcode == 1 first_operand_value = first_param_mode==1 ? steps[i+1].to_i : steps[steps[i+1].to_i].to_i second_operand_value = second_param_mode==1 ? steps[i+2].to_i : steps[steps[i+2].to_i].to_i address_to_be_written = steps[i+3].to_i steps[address_to_be_written] = first_operand_value + second_operand_value arr_pos = arr_pos + 4 elsif opcode == 2 first_operand_value = first_param_mode==1 ? steps[i+1].to_i : steps[steps[i+1].to_i].to_i second_operand_value = second_param_mode==1 ? steps[i+2].to_i : steps[steps[i+2].to_i].to_i address_to_be_written = steps[i+3].to_i steps[address_to_be_written] = first_operand_value * second_operand_value arr_pos = arr_pos + 4 elsif opcode == 3 if receive_phase_input == true first_input_element = phase receive_phase_input = false else first_input_element = input_elem end steps[steps[i+1].to_i]=first_input_element arr_pos = arr_pos + 2 elsif opcode == 4 output_element = steps[steps[i+1].to_i].to_i # puts "Output element #{output_element}" arr_pos = arr_pos + 2 elsif opcode == 5 first_operand_value = first_param_mode==1 ? steps[i+1].to_i : steps[steps[i+1].to_i].to_i second_operand_value = second_param_mode==1 ? steps[i+2].to_i : steps[steps[i+2].to_i].to_i if first_operand_value != 0 arr_pos = second_operand_value else arr_pos = arr_pos + 3 end elsif opcode == 6 first_operand_value = first_param_mode==1 ? steps[i+1].to_i : steps[steps[i+1].to_i].to_i second_operand_value = second_param_mode==1 ? steps[i+2].to_i : steps[steps[i+2].to_i].to_i if first_operand_value == 0 arr_pos = second_operand_value else arr_pos = arr_pos + 3 end elsif opcode == 7 first_operand_value = first_param_mode==1 ? steps[i+1].to_i : steps[steps[i+1].to_i].to_i second_operand_value = second_param_mode==1 ? steps[i+2].to_i : steps[steps[i+2].to_i].to_i address_to_be_written = steps[i+3].to_i if first_operand_value < second_operand_value steps[address_to_be_written] = 1 else steps[address_to_be_written] = 0 end arr_pos = arr_pos + 4 elsif opcode == 8 first_operand_value = first_param_mode==1 ? steps[i+1].to_i : steps[steps[i+1].to_i].to_i second_operand_value = second_param_mode==1 ? steps[i+2].to_i : steps[steps[i+2].to_i].to_i address_to_be_written = steps[i+3].to_i if first_operand_value == second_operand_value steps[address_to_be_written] = 1 else steps[address_to_be_written] = 0 end arr_pos = arr_pos + 4 elsif opcode == 99 break end end i+=1 if i == steps.length - 1 break end end return output_element end def generate_perm_array() a = [0,1,2,3,4] return a.permutation(5).to_a end phase_array = generate_perm_array() max_thrust = 0 phase_array.each do |p| a1 = amplifier(steps, p[0], 0) b1 = amplifier(steps, p[1], a1) c1 = amplifier(steps, p[2], b1) d1 = amplifier(steps, p[3], c1) e1 = amplifier(steps, p[4], d1) if e1 > max_thrust max_thrust = e1 end end puts max_thrust <file_sep> double_element_hash = Hash.new cypher_counter = 0 (145852..616942).each do |key| adj_condition = false there_is_one = false adj_condition2 = true order_condition = true arr = key.to_s.split("") arr.each_with_index do |e, i| element = 10 if i < arr.length-1 if arr[i] == arr[i+1] element = arr[i] double_element_hash[[key, element]] = 1 if !(double_element_hash[[key, element]] == -1) end if i< arr.length-2 if (element == arr[i+2]) double_element_hash[[key, element]] = -1 end end end (0..5).each do |j| if (double_element_hash[[key, arr[j]]] == 1) adj_condition = true end end if i < arr.length-1 order_condition = false if arr[i].to_i > arr[i+1].to_i end end if adj_condition && order_condition cypher_counter += 1 end end puts cypher_counter <file_sep> input_file_name = "day6input.txt" if File.file?(input_file_name) steps_string = File.readlines(input_file_name) else puts "PLEASE PROVIDE A VALID INPUT FILE" end nodes_hash = Hash.new(nil) steps_string.each do |orbit| arr = orbit.split(":") if nodes_hash[arr[0]].nil? nodes_hash[arr[0]] = [arr[1].delete!("\n")] else nodes_hash[arr[0]].push(arr[1].delete!("\n")) end end nodes_hash.each do |k, v| nodes_hash.each do |key, value| if value.include?(k) nodes_hash[key].concat(v).uniq! end end end total = 0 nodes_hash.each do |key, value| total = total + value.length end # puts "Total number of orbits is #{total}" # puts "total number of input is #{steps_string.length}" s1 ="YOU" s2 ="SAN" common_parents = Hash.new nodes_hash.each do |key, value| if value.include?(s1 ) && value.include?(s2 ) common_parents[key] = value end end # puts "Common parents are : #{common_parents}" first_common_parent = "" inc_flag = false common_parents.each do |k1, v1| common_parents.each do |k2, v2| if nodes_hash[k1].include?(k2) common_parents[k1] = nil end end end common_parents.each do |k, v| if !common_parents[k].nil? first_common_parent = k end end # puts "firat comoon parent : #{first_common_parent}" counterYOU = 0 counterSAN = 0 # puts nodes_hash[first_common_parent] nodes_hash[first_common_parent].each do |key| if !nodes_hash[key].nil? counterYOU +=1 if nodes_hash[key].include?("YOU") counterSAN +=1 if nodes_hash[key].include?("SAN") end end puts "SAN is #{counterSAN}, YOU is #{counterYOU} total is : #{counterSAN + counterYOU}" <file_sep># <x=-16, y=15, z=-9> # <x=-14, y=5, z=4> # <x=2, y=0, z=6> # <x=-3, y=18, z=9> # Io, Europa, Ganymede, and Callisto. # # # sp1 = [-8, -10, 0] # sp2 = [5, 5, 10] # sp3 = [2, -7, 3] # sp4 = [9, -8, -3] # 8************************* def find_cyle_on_axis(sp1, sp2, sp3, sp4) sv1 = sv2 = sv3 = sv4 = 0 # sv2 = 0 # sv3 = 0 # sv4 = 0 positions = [sp1, sp2, sp3, sp4] vels = [sv1, sv2, sv3, sv4] energy = [] counter = 1 loop do counter+=1 (0..3).each do |st| v_delta = 0 (0..3).each do |sp| if positions[st].to_i > positions[sp].to_i v_delta -=1 elsif positions[st].to_i < positions[sp].to_i v_delta +=1 end end vels[st] = vels[st] + v_delta end (0..3).each do |st| positions[st] = positions[st] + vels[st] end if positions[0] == sp1 && positions[1] == sp2 && positions[2] == sp3 && positions[3] == sp4 && sv1 ==0 && sv2 ==0 && sv3 ==0 && sv4 ==0 break end # puts counter end return counter end sp1 = -16 sp2 = -14 sp3 = 2 sp4 = -3 x_axis_peiod = find_cyle_on_axis(sp1, sp2, sp3, sp4) sp1 = 15 sp2 = 5 sp3 = 0 sp4 = 18 y_axis_peiod = find_cyle_on_axis(sp1, sp2, sp3, sp4) sp1 = -9 sp2 = 4 sp3 = 6 sp4 = 9 z_axis_peiod = find_cyle_on_axis(sp1, sp2, sp3, sp4) puts "For the answer to puzzle find the least common multipler (lcm) of #{x_axis_peiod}, #{y_axis_peiod}, #{z_axis_peiod} on Internet" <file_sep> input_file_name = "day2input.txt" if File.file?(input_file_name) steps_string = File.open(input_file_name).read.to_s else puts "PLEASE PROVIDE A VALID INPUT FILE" end steps = steps_string.split(",") steps[1] = 12 steps[2] = 2 counter = 0 steps.each do |element| if counter % 4 == 0 i = counter if element.to_i == 1 first_add_element = steps[steps[i+1].to_i].to_i second_add_element = steps[steps[i+2].to_i].to_i steps[steps[i+3].to_i] = second_add_element + first_add_element elsif element.to_i == 2 first_mul_element = steps[steps[i+1].to_i].to_i second_mul_element = steps[steps[i+2].to_i].to_i steps[steps[i+3].to_i] = second_mul_element * first_mul_element elsif element.to_i == 99 break else puts "There is an error" end end counter+=1 end puts steps[0] <file_sep> input_file_name = "day13-2input.txt" if File.file?(input_file_name) steps_string = File.open(input_file_name).read.to_s else puts "PLEASE PROVIDE A VALID INPUT FILE" end steps = steps_string.split(",") $commands_array = [] opcode_4_counter = 0 opcode_4_tmp_array = [] arr_pos = 0 i = 0 rel_base = 0 output_array = [] def find_the_direction paddle_x = 0 ball_x = 0 $commands_array.each do |tile| tile.each_with_index do |t, i| if i == 2 && t == 4 ball_x = tile[0] break end if i == 2 && t == 3 paddle_x = tile[0] break end end end if ball_x > paddle_x return 1 elsif ball_x < paddle_x return -1 else return 0 end end loop do if i == arr_pos increment_index = true instructionArray = steps[i].to_s.split("") if instructionArray.length-2 >= 0 opcode = (instructionArray[instructionArray.length-2] + instructionArray[instructionArray.length-1]).to_i else opcode = (instructionArray[instructionArray.length-1]).to_i end if instructionArray.length-3 >=0 first_param_mode = instructionArray[instructionArray.length-3].to_i else first_param_mode = 0 end if instructionArray.length-4 >=0 second_param_mode = instructionArray[instructionArray.length-4].to_i else second_param_mode = 0 end if instructionArray.length-5 >=0 third_param_mode = instructionArray[instructionArray.length-5].to_i else third_param_mode = 0 end if first_param_mode == 0 first_operand_value = steps[steps[i+1].to_i].to_i elsif first_param_mode == 2 first_operand_value = steps[steps[i+1].to_i + rel_base].to_i else first_operand_value = steps[i+1].to_i end if second_param_mode == 0 second_operand_value = steps[steps[i+2].to_i].to_i elsif second_param_mode == 2 second_operand_value = steps[steps[i+2].to_i + rel_base].to_i else second_operand_value = steps[i+2].to_i end if third_param_mode == 0 third_operand_value = steps[i+3].to_i elsif third_param_mode == 2 third_operand_value = steps[i+3].to_i + rel_base else third_operand_value = steps[i+3].to_i end if opcode == 1 address_to_be_written = steps[i+3].to_i steps[third_operand_value] = first_operand_value + second_operand_value arr_pos = arr_pos + 4 elsif opcode == 2 address_to_be_written = steps[i+3].to_i steps[third_operand_value] = first_operand_value * second_operand_value arr_pos = arr_pos + 4 elsif opcode == 3 first_input_element = find_the_direction if first_param_mode == 0 steps[steps[i+1].to_i]=first_input_element elsif first_param_mode == 2 steps[steps[i+1].to_i+rel_base]=first_input_element else steps[i+1]=first_input_element end steps[steps[i+1].to_i]=first_input_element arr_pos = arr_pos + 2 elsif opcode == 4 output_element = first_operand_value arr_pos = arr_pos + 2 opcode_4_counter +=1 opcode_4_tmp_array.push(output_element) if opcode_4_counter % 3 ==0 $commands_array.push(opcode_4_tmp_array) opcode_4_tmp_array = [] if opcode_4_tmp_array[0] == -1 print opcode_4_tmp_array puts "" end end elsif opcode == 5 if first_operand_value != 0 arr_pos = second_operand_value increment_index = false else arr_pos = arr_pos + 3 end elsif opcode == 6 if first_operand_value == 0 arr_pos = second_operand_value increment_index = false else arr_pos = arr_pos + 3 end elsif opcode == 7 address_to_be_written = steps[i+3].to_i if first_operand_value < second_operand_value steps[third_operand_value] = 1 else steps[third_operand_value] = 0 end arr_pos = arr_pos + 4 elsif opcode == 8 address_to_be_written = steps[i+3].to_i if first_operand_value == second_operand_value steps[third_operand_value] = 1 else steps[third_operand_value] = 0 end arr_pos = arr_pos + 4 elsif opcode == 9 rel_base = rel_base + first_operand_value arr_pos = arr_pos + 2 elsif opcode == 99 break end end i = arr_pos -1 i+=1 #if increment_index break if i == steps.length - 1 end counnter = 0 $commands_array.each_with_index do |v, i| if v[0] == -1 print v puts"" end end <file_sep> cypher_counter = 0 (145852..616942).each do |key| adj_condition = false order_condition = true arr = key.to_s.split("") arr.each_with_index do |e, i| if i < arr.length-1 adj_condition = true if arr[i] == arr[i+1] end if i < arr.length-1 order_condition = false if arr[i].to_i > arr[i+1].to_i end end if adj_condition && order_condition cypher_counter += 1 end end puts cypher_counter <file_sep># <x=-16, y=15, z=-9> # <x=-14, y=5, z=4> # <x=2, y=0, z=6> # <x=-3, y=18, z=9> # <NAME>, Ganymede, and Callisto. sp1 = [-16, 15, -9] sp2 = [-14, 5, 4] sp3 = [2, 0, 6] sp4 = [-3, 18, 9] sv1 = [0, 0, 0] sv2 = [0, 0, 0] sv3 = [0, 0, 0] sv4 = [0, 0, 0] positions = [sp1, sp2, sp3, sp4] vels = [sv1, sv2, sv3, sv4] energy = [] t_energy = 0 (0..999).each do |s| (0..3).each do |st| (0..2).each do |co| v_delta = 0 (0..3).each do |sp| if positions[st][co].to_i > positions[sp][co].to_i v_delta -=1 elsif positions[st][co].to_i < positions[sp][co].to_i v_delta +=1 end end vels[st][co] = vels[st][co] + v_delta end end (0..3).each do |st| (0..2).each do |co| positions[st][co] = positions[st][co] + vels[st][co] end end (0..3).each do |st| pot = 0 kin = 0 en = 0 (0..2).each do |co| pot = pot + positions[st][co].abs kin = kin + vels[st][co].abs end en = pot*kin energy[st] = en end total_energy = 0 (0..3).each do |e| total_energy = total_energy + energy[e] end # puts "total_e #{total_energy}" t_energy = total_energy end puts t_energy <file_sep>input_file_name = "day8input.txt" if File.file?(input_file_name) steps_string = File.open(input_file_name).read.to_s else puts "PLEASE PROVIDE A VALID INPUT FILE" end layers = steps_string.scan(/.{150}/) final_message = "" (0..149).each do |i| layers.each do |layers| if layers[i] != '2' final_message = final_message + layers[i] break end end end msg_arr= final_message.split("") msg_arr.collect! do |v| (v == '0') ? " " : "*" end msg_arr.each_with_index do |v,i| print " " if (i+1) % 25 == 0 puts "" end print v end <file_sep> input_file_name = "day5input.txt" if File.file?(input_file_name) steps_string = File.open(input_file_name).read.to_s else puts "PLEASE PROVIDE A VALID INPUT FILE" end steps = steps_string.split(",") increment_index = true arr_pos = 0 i = 0 loop do if i == arr_pos increment_index = true instructionArray = steps[i].to_s.split("") if instructionArray.length-2 >= 0 opcode = (instructionArray[instructionArray.length-2] + instructionArray[instructionArray.length-1]).to_i else opcode = (instructionArray[instructionArray.length-1]).to_i end if instructionArray.length-3 >=0 first_param_mode = instructionArray[instructionArray.length-3].to_i == 1 ? 1 : 0 else first_param_mode = 0 end if instructionArray.length-4 >=0 second_param_mode = instructionArray[instructionArray.length-4].to_i == 1 ? 1 : 0 else second_param_mode = 0 end if first_param_mode == 0 first_operand_value = steps[steps[i+1].to_i].to_i else first_operand_value = steps[i+1].to_i end if second_param_mode == 0 second_operand_value = steps[steps[i+2].to_i].to_i else second_operand_value = steps[i+2].to_i end if opcode == 1 address_to_be_written = steps[i+3].to_i steps[address_to_be_written] = first_operand_value + second_operand_value arr_pos = arr_pos + 4 elsif opcode == 2 address_to_be_written = steps[i+3].to_i steps[address_to_be_written] = first_operand_value * second_operand_value arr_pos = arr_pos + 4 elsif opcode == 3 first_input_element = gets.chomp.to_i steps[steps[i+1].to_i]=first_input_element arr_pos = arr_pos + 2 elsif opcode == 4 output_element = steps[steps[i+1].to_i].to_i puts "Output element #{output_element}" arr_pos = arr_pos + 2 elsif opcode == 5 if first_operand_value != 0 arr_pos = second_operand_value increment_index = false else arr_pos = arr_pos + 3 end elsif opcode == 6 if first_operand_value == 0 arr_pos = second_operand_value increment_index = false else arr_pos = arr_pos + 3 end elsif opcode == 7 address_to_be_written = steps[i+3].to_i if first_operand_value < second_operand_value steps[address_to_be_written] = 1 else steps[address_to_be_written] = 0 end arr_pos = arr_pos + 4 elsif opcode == 8 address_to_be_written = steps[i+3].to_i if first_operand_value == second_operand_value steps[address_to_be_written] = 1 else steps[address_to_be_written] = 0 end arr_pos = arr_pos + 4 elsif opcode == 99 break end end i+=1 #if increment_index break if i == steps.length - 1 end puts steps[0] <file_sep> input_file_name = "day6input.txt" if File.file?(input_file_name) steps_string = File.readlines(input_file_name) else puts "PLEASE PROVIDE A VALID INPUT FILE" end nodes_hash = Hash.new(nil) steps_string.each do |orbit| arr = orbit.split(":") if nodes_hash[arr[0]].nil? nodes_hash[arr[0]] = [arr[1].delete!("\n")] else nodes_hash[arr[0]].push(arr[1].delete!("\n")) end end nodes_hash.each do |k, v| nodes_hash.each do |key, value| if value.include?(k) nodes_hash[key].concat(v).uniq! end end end total = 0 nodes_hash.each do |key, value| total = total + value.length end puts "Total number of orbits is #{total}" # puts "total number of input is #{steps_string.length}" <file_sep>include Math input_file_name = "day10input.txt" if File.file?(input_file_name) lines = File.readlines(input_file_name) else puts "PLEASE PROVIDE A VALID INPUT FILE" end my_ast_array = Array.new lines.each do |line| line.each_char do |c| my_ast_array.push(1) if c=="#" my_ast_array.push(0) if c=="." end end size = 48 my_hash = Hash.new(0) max_hit = 0 result = 0 my_ast_array.each_with_index do |element, index | if element == 1 x = index % size y = index / size tmp_hash = Hash.new(0) my_ast_array.each_with_index do |e, i| if e == 1 && i != index x1 = i%size y1 = i / size x_rate = x-x1 y_rate = y-y1 rate = atan2(x_rate, -y_rate) tmp_hash[[ rate ]] = 1 end end my_hash[[x,y]] = tmp_hash end if my_hash[[x,y]].size > max_hit max_hit = my_hash[[x,y]].size result = [x,y] end end puts "result = #{result}" puts "Max hit = #{max_hit}" final_arr = [] my_hash[result].each do |k, v| final_arr.push(k) end # The 200th asteroid corresponds to index 198 (because index starts from 0 and don't count the current itself) puts sta= final_arr.sort![198] puts result[0] puts result[1] tp_arr = [] final_hash = Hash.new(0) my_ast_array.each_with_index do |e, i| if e==1 xt = i%size yt = i/size x_rate = result[0]-xt y_rate = result[1]-yt rate = atan2(x_rate, -y_rate) tp_arr.push(rate) tp_arr.uniq! if rate.round(7) == sta[0].round(7) puts "HIT HIT" final_hash[[xt, yt]] = rate end end end puts final_hash <file_sep> input_file_name = "day5input.txt" if File.file?(input_file_name) steps_string = File.open(input_file_name).read.to_s else puts "PLEASE PROVIDE A VALID INPUT FILE" end steps = steps_string.split(",") arr_pos = 0 steps.each_with_index do |element, i| if i == arr_pos instructionArray = element.to_s.split("") if instructionArray.length-2 >= 0 opcode = (instructionArray[instructionArray.length-2] + instructionArray[instructionArray.length-1]).to_i else opcode = (instructionArray[instructionArray.length-1]).to_i end if instructionArray.length-3 >=0 first_param_mode = instructionArray[instructionArray.length-3].to_i == 1 ? 1 : 0 else first_param_mode = 0 end if instructionArray.length-4 >=0 second_param_mode = instructionArray[instructionArray.length-4].to_i == 1 ? 1 : 0 else second_param_mode = 0 end if opcode == 1 first_operand_value = first_param_mode==1 ? steps[i+1].to_i : steps[steps[i+1].to_i].to_i second_operand_value = second_param_mode==1 ? steps[i+2].to_i : steps[steps[i+2].to_i].to_i address_to_be_written = steps[i+3].to_i steps[address_to_be_written] = first_operand_value + second_operand_value arr_pos = arr_pos + 4 elsif opcode == 2 first_operand_value = first_param_mode==1 ? steps[i+1].to_i : steps[steps[i+1].to_i].to_i second_operand_value = second_param_mode==1 ? steps[i+2].to_i : steps[steps[i+2].to_i].to_i address_to_be_written = steps[i+3].to_i steps[address_to_be_written] = first_operand_value * second_operand_value arr_pos = arr_pos + 4 elsif opcode == 3 first_input_element = gets.chomp.to_i steps[steps[i+1].to_i]=first_input_element arr_pos = arr_pos + 2 elsif opcode == 4 output_element = steps[steps[i+1].to_i].to_i puts "Output element #{output_element}" arr_pos = arr_pos + 2 elsif opcode == 99 break end end end puts steps[0] <file_sep> input_file_name = "day7input.txt" if File.file?(input_file_name) steps_string = File.open(input_file_name).read.to_s else puts "PLEASE PROVIDE A VALID INPUT FILE" end steps = steps_string.split(",") $instruction_pause_hash = Hash.new() $instruction_pause_hash["a"]=[].concat(steps) $instruction_pause_hash["b"] =[].concat(steps) $instruction_pause_hash["c"] =[].concat(steps) $instruction_pause_hash["d"] =[].concat(steps) $instruction_pause_hash["e"] =[].concat(steps) $instruction_pause_hash2 = Hash.new(0) def amplifier(phase, input_elem, number_of_run, which_ampl) steps = $instruction_pause_hash[which_ampl] receive_phase_input = true finish_condition = false output_element =0 arr_pos = 0 arr_pos = $instruction_pause_hash2[which_ampl] i = 0 loop do if i == arr_pos instructionArray = steps[i].to_s.split("") if instructionArray.length-2 >= 0 opcode = (instructionArray[instructionArray.length-2] + instructionArray[instructionArray.length-1]).to_i else opcode = (instructionArray[instructionArray.length-1]).to_i end if instructionArray.length-3 >=0 first_param_mode = instructionArray[instructionArray.length-3].to_i == 1 ? 1 : 0 else first_param_mode = 0 end if instructionArray.length-4 >=0 second_param_mode = instructionArray[instructionArray.length-4].to_i == 1 ? 1 : 0 else second_param_mode = 0 end if opcode == 1 first_operand_value = first_param_mode==1 ? steps[i+1].to_i : steps[steps[i+1].to_i].to_i second_operand_value = second_param_mode==1 ? steps[i+2].to_i : steps[steps[i+2].to_i].to_i address_to_be_written = steps[i+3].to_i steps[address_to_be_written] = first_operand_value + second_operand_value arr_pos = arr_pos + 4 elsif opcode == 2 first_operand_value = first_param_mode==1 ? steps[i+1].to_i : steps[steps[i+1].to_i].to_i second_operand_value = second_param_mode==1 ? steps[i+2].to_i : steps[steps[i+2].to_i].to_i address_to_be_written = steps[i+3].to_i steps[address_to_be_written] = first_operand_value * second_operand_value arr_pos = arr_pos + 4 elsif opcode == 3 if receive_phase_input == true && number_of_run == 0 first_input_element = phase receive_phase_input = false else first_input_element = input_elem end steps[steps[i+1].to_i]=first_input_element arr_pos = arr_pos + 2 elsif opcode == 4 output_element = steps[steps[i+1].to_i].to_i $instruction_pause_hash2[which_ampl] = arr_pos + 2 $instruction_pause_hash[which_ampl] = steps break if arr_pos = arr_pos + 2 elsif opcode == 5 first_operand_value = first_param_mode==1 ? steps[i+1].to_i : steps[steps[i+1].to_i].to_i second_operand_value = second_param_mode==1 ? steps[i+2].to_i : steps[steps[i+2].to_i].to_i if first_operand_value != 0 arr_pos = second_operand_value else arr_pos = arr_pos + 3 end elsif opcode == 6 first_operand_value = first_param_mode==1 ? steps[i+1].to_i : steps[steps[i+1].to_i].to_i second_operand_value = second_param_mode==1 ? steps[i+2].to_i : steps[steps[i+2].to_i].to_i if first_operand_value == 0 arr_pos = second_operand_value else arr_pos = arr_pos + 3 end elsif opcode == 7 first_operand_value = first_param_mode==1 ? steps[i+1].to_i : steps[steps[i+1].to_i].to_i second_operand_value = second_param_mode==1 ? steps[i+2].to_i : steps[steps[i+2].to_i].to_i address_to_be_written = steps[i+3].to_i if first_operand_value < second_operand_value steps[address_to_be_written] = 1 else steps[address_to_be_written] = 0 end arr_pos = arr_pos + 4 elsif opcode == 8 first_operand_value = first_param_mode==1 ? steps[i+1].to_i : steps[steps[i+1].to_i].to_i second_operand_value = second_param_mode==1 ? steps[i+2].to_i : steps[steps[i+2].to_i].to_i address_to_be_written = steps[i+3].to_i if first_operand_value == second_operand_value steps[address_to_be_written] = 1 else steps[address_to_be_written] = 0 end arr_pos = arr_pos + 4 elsif opcode == 99 finish_condition = true break end end i+=1 if i == steps.length - 1 i=0 $instruction_pause_hash2[which_ampl]=0 end end # puts "End of Amplifier #{which_ampl} #{[output_element, finish_condition]}" return [output_element, finish_condition] end def generate_perm_array() a = [9,8,7,6,5] return a.permutation(5).to_a end phase_array = generate_perm_array() max_thrust = 0 phase_array.each do |p| l_counter = 0 e1=[0, false] $instruction_pause_hash2["a"] = 0 $instruction_pause_hash2["b"] = 0 $instruction_pause_hash2["c"] = 0 $instruction_pause_hash2["d"] = 0 $instruction_pause_hash2["e"] = 0 $instruction_pause_hash["a"]=[].concat(steps) $instruction_pause_hash["b"] =[].concat(steps) $instruction_pause_hash["c"] =[].concat(steps) $instruction_pause_hash["d"] =[].concat(steps) $instruction_pause_hash["e"] =[].concat(steps) loop do if e1[0] > max_thrust max_thrust = e1[0] end a1 = amplifier( p[0], e1[0], l_counter, "a") b1 = amplifier( p[1], a1[0], l_counter, "b") c1 = amplifier( p[2], b1[0], l_counter, "c") d1 = amplifier( p[3], c1[0], l_counter, "d") e1 = amplifier( p[4], d1[0], l_counter, "e") if e1[0] > max_thrust max_thrust = e1[0] end break if e1[1] l_counter+=1 break if l_counter ==10 end end puts "Max Thrust #{max_thrust}"
abeef7511fcd1da540a2089038e22a3e108fb970
[ "Ruby" ]
19
Ruby
leventinceshopify/AdventOfCode2019
af5514eb49eabe28006ffe6bb3399e81cb1ed929
06361399500fbd10fde9ad282cbf2b1cb1f70a96
refs/heads/master
<repo_name>CodingIsLove/TextAdventure<file_sep>/src/Main/TextParser/InputParser.java package Main.TextParser; import Main.Enums.Directions; import Main.Graphics.Graphics; import Main.Hero.Hero; import Main.Texte.TextStorage; import java.io.*; import java.nio.charset.Charset; import java.nio.file.Files; import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; /** * Die Klasse Input parser erlaubt es uns mit einem Helden zu Interagieren. * In der "PlayMe" Klasse wird über den Scanner ein Befehl eingelesen. * Dieser String wird dem Input parser übergeben. Er versucht die entsprechende Aktion * zu finden und führt die gewünschte Funktion aus. */ public class InputParser { private Hero hero; /** * ############################### * # Konstruktor # * ###############################*/ public InputParser(Hero hero){ this.hero = hero; } public static void fileReader(String fileDestination) throws FileNotFoundException { try (BufferedReader br = new BufferedReader(new FileReader(fileDestination))) { String line = null; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } } /** * ############################### * # REGEX PATTERN # * ###############################*/ Pattern go_somewhere = Pattern.compile(TextStorage.PATTERN_GO); Pattern north = Pattern.compile(TextStorage.NORTH); Pattern east = Pattern.compile(TextStorage.EAST); Pattern south = Pattern.compile(TextStorage.SOUTH); Pattern west = Pattern.compile(TextStorage.WEST); Pattern help = Pattern.compile(TextStorage.HELP); Pattern look = Pattern.compile(TextStorage.LOOK); Pattern inspect = Pattern.compile(TextStorage.INSPECT); Pattern say = Pattern.compile(TextStorage.SAY); Pattern inventory = Pattern.compile(TextStorage.INVENTORY); Pattern i_see = Pattern.compile(TextStorage.I_SEE); Pattern where_am_i = Pattern.compile(TextStorage.WHERE_AM_I); Pattern room = Pattern.compile(TextStorage.ROOM_DESCRIPTION); Pattern interact = Pattern.compile(TextStorage.INTERACT); Pattern codeEnding = Pattern.compile(TextStorage.CODE_INPUT); Pattern map = Pattern.compile(TextStorage.MAP); Pattern manual = Pattern.compile(TextStorage.MANUAL); Pattern cheat = Pattern.compile(TextStorage.CHEAT); /** * Diese Funktion ist der Kern diese Klasse. Ein String wird auf unterschiedliche Regexpattern geprüft. * Erfüllt ein String ein bestimmtes Pattern, so wird der Held modifiziert und der Raum und die aktuellen * Parameter ändern sich * @param command Ausdruck, welcher zu analysieren ist */ public void evaluate(String command) throws FileNotFoundException { command = command.toUpperCase(); /** *Raumbeschreibung*/ if(room.matcher(command).matches()){ hero.getAktuellerRaum().getRoomHelp(); } /** * Wand fokusieren */ if(look.matcher(command).matches()){ if(north.matcher(command).matches()){ hero.getAktuellerRaum().look(Directions.NORTH); }else if(east.matcher(command).matches()){ hero.getAktuellerRaum().look(Directions.EAST); }else if(south.matcher(command).matches()){ hero.getAktuellerRaum().look(Directions.SOUTH); }else if(west.matcher(command).matches()){ hero.getAktuellerRaum().look(Directions.WEST); }else { System.out.println(TextStorage.NON_VALID_EXPRESSION); } } /** * Die Aktuelle Wand beschreiben */ if(inspect.matcher(command).matches()){ if(north.matcher(command).matches()){ hero.getAktuellerRaum().inspect(Directions.NORTH); }else if(east.matcher(command).matches()){ hero.getAktuellerRaum().inspect(Directions.NORTH.EAST); }else if(south.matcher(command).matches()){ hero.getAktuellerRaum().inspect(Directions.NORTH.SOUTH); }else if(west.matcher(command).matches()){ hero.getAktuellerRaum().inspect(Directions.NORTH.WEST); }else { hero.getAktuellerRaum().inspect(); } } /** * Die Türe verwenden */ if(go_somewhere.matcher(command).matches()){ if(north.matcher(command).matches()){ hero.changeRoom(Directions.NORTH); }else if(east.matcher(command).matches()){ hero.changeRoom(Directions.EAST); }else if(south.matcher(command).matches()){ hero.changeRoom(Directions.SOUTH); }else if(west.matcher(command).matches()){ hero.changeRoom(Directions.WEST); }else{ } } /** * Beschreibe, was ich gerade sehe */ if(i_see.matcher(command).matches()){ hero.getAktuellerRaum().look(); } /** * Gibt Auskunft übe den Aktuellen Raum */ if(where_am_i.matcher(command).matches()){ System.out.println(Colorlog.white(TextStorage.ROOM_LOCATION) + Colorlog.blue(hero.getAktuellerRaum().getRoomName())); System.out.println(Colorlog.white(TextStorage.VIEW) + Colorlog.blue(hero.getAktuellerRaum().getFocusedWall().getWallName())); } /** * interaktion mit einer Wand */ if(interact.matcher(command).matches() || say.matcher(command).matches()){ if(codeEnding.matcher(command).matches()){ hero.openKiste(Integer.parseInt(command.replaceAll("[^\\d]",""))); }else{ hero.openKiste(); } } /** * Anzeigen des Inventars */ if(inventory.matcher(command).matches()) { hero.logInventar(); } /** * Anzeigen der Karte */ if(map.matcher(command).matches()){ Graphics.printWorld(); } /** * Hilfe anzeigen */ if(help.matcher(command).matches()){ String basePath = new File("").getAbsolutePath(); if(manual.matcher(command).matches()){ InputParser.fileReader(basePath.concat("/src/Main/Texte/SpielAnleitung.txt")); }else{ InputParser.fileReader(basePath.concat("/src/Main/Texte/help.txt")); } } /** * Lösung anzeigen für ungeduldige */ if(cheat.matcher(command).matches()){ String basePath = new File("").getAbsolutePath(); InputParser.fileReader(basePath.concat("/src/Main/Texte/developerNotes.txt")); } } } <file_sep>/src/Test/TestLevelBahnhof/InteractionWithoutParser.java package Test.TestLevelBahnhof; import org.junit.Test; /** * Dieser Test simuliert alle Interaktionen, welche möglich sein sollten mit einem Raum. Dazu simulieren wir folgenden Raum: * * *------------ Raum = Welle 7 ---------------- * ########## Gittig ########## * # # * # # *Rolltreppe Bahnhof Durchgang Richtung Studienräume * # # * # # * ######## <NAME> ####### * * * *****************************Storyline, die umgesetzt werden sollte: * * Ich komme von der Rolltreppe hoch und befinde mich nun im Raum der Welle 7. Ich schaue mich um und sehe neben der Rolltreppe * mit der ich hochgekommen bin die Gittig, Wurst und Moritz und einen Durchgang, der mich zu den Studienräumen führt. Wenn ich Wurst und Moritz inspiziere sollte mich der Verkäufer erkennen. * Er fragt mich ob ich die verlorenen Prüfungen haben will, die er soeben gefunden hat. Ich kann diese Aufnehmen und in mein Inventar aufnehmen * */ public class InteractionWithoutParser { @Test public void firstLevel(){ } } <file_sep>/src/Test/Items/InventarTest.java package Test.Items; import Main.Items.Inventar; import Main.Items.genericItem; import org.junit.Test; import static org.junit.Assert.*; public class InventarTest { //Erstelle eine Inventar Inventar inventar = new Inventar(); //Erstellen von einigen dummy genericItems genericItem fussball = new genericItem("Fussball","macht spass"); genericItem schatz = new genericItem("schatz","ist viel Wert"); genericItem key = new genericItem("Schlüssel","kann türen öffnen"); // Fülle Inventar mit dummy items @Test public void addItem() { inventar.addItem(fussball); inventar.addItem(schatz); inventar.addItem(key); } @Test public void getInventar(){ inventar.addItem(fussball); inventar.addItem(schatz); inventar.addItem(key); System.out.println("------------ Get All Inventar Ausgabe "); inventar.logInventar(); } @Test public void getItemDetails() { inventar.addItem(fussball); inventar.addItem(schatz); inventar.addItem(key); System.out.println("------------ Get details Ausgabe "); inventar.getItemDetails("Fussball"); } }<file_sep>/src/Main/Hero/Hero.java package Main.Hero; import Main.Enums.Directions; import Main.Items.Inventar; import Main.Items.genericItem; import Main.Rooms.BuildingBlocks.Room; import Main.Rooms.BuildingBlocks.Wall; import Main.TextParser.Colorlog; import Main.Texte.TextStorage; import java.util.ArrayList; import java.util.concurrent.TimeUnit; public class Hero{ private Inventar inventar; private Room aktuellerRaum; /** * ##################### * # Konstruktor # * ##################### */ public Hero(Room start){ this. aktuellerRaum = start; this.inventar = new Inventar(); } /**#################### * #Setter Funktionen # * #################### */ public void changeRoom(){ if(aktuellerRaum.getFocusedWall().useDoor() != null){ this.aktuellerRaum = aktuellerRaum.getFocusedWall().useDoor(); } } public void changeRoom(Directions direction){ aktuellerRaum.setFocusedDirection(direction); if(aktuellerRaum.getFocusedWall().useDoor() != null){ this.aktuellerRaum = aktuellerRaum.getFocusedWall().useDoor(); System.out.println(TextStorage.CHANGED_ROOM + this.getAktuellerRaum().getRoomName()); }else{ System.out.println(TextStorage.NO_DOOR_HERE); } } public void openKiste(){ inventar.addItem(aktuellerRaum.openKiste()); } public void openKiste(int code){ inventar.addItem(aktuellerRaum.openKiste(code)); } /**#################### * #Getter funktionen # * #################### */ public Room getAktuellerRaum(){ return aktuellerRaum; } public void logInventar(){ inventar.logInventar(); } public ArrayList<genericItem> getInventar(){ return inventar.getInventar(); } /** * ################################ * # Help functions # * ################################ // TODO: schreiben der Help functions */ } <file_sep>/src/Test/Rooms/getNextRoomTest.java package Test.Rooms; import Main.Enums.Directions; import Main.Rooms.AllLevels; import Main.Rooms.BuildingBlocks.Room; import org.junit.Test; import static org.junit.Assert.assertEquals; public class getNextRoomTest { @Test public void WallWithDoor(){ Room currentRoom = AllLevels.bahnhof; currentRoom.getRoomHelp(); currentRoom.setFocusedDirection(Directions.EAST); currentRoom = currentRoom.getFocusedWall().useDoor(); System.out.println(); currentRoom.getRoomHelp(); } } <file_sep>/src/Main/Rooms/BuildingBlocks/Room.java package Main.Rooms.BuildingBlocks; import Main.Enums.Directions; import Main.Enums.RoomName; import Main.Items.genericItem; import Main.TextParser.Colorlog; import Main.Texte.TextStorage; public class Room { private String roomName; private RoomName id; private Wall nordWand; private Wall suedWand; private Wall ostWand; private Wall westWand; private Directions focusedDirection; // Sollte einziger parameter mit Setter Funktion sein /** * ################################ * # Raumkonstruktor # * ################################ */ /** * Konstruktor für einen Raum. Zu einem Raum gehören die 4 Wände. Damit der Spieler Jeweils mit den Wänden interagieren kann, muss er dazu eine fokusieren. * Die Fokusierte Wand wird * @param nordWand Definition der Nordwand * @param suedWand Definition der Südwand * @param ostWand Definition der Ostwand * @param westWand Definition der Westwand * @param direction Enum das angibt welche Wand zu fokusieren ist * @param roomName Name des Raumes */ public Room(Wall nordWand, Wall ostWand ,Wall suedWand, Wall westWand, String roomName, RoomName id,Enum<Directions> direction){ //Definieren der Wände this.nordWand = nordWand; this.suedWand = suedWand; this.ostWand = ostWand; this.westWand = westWand; //Eigenschaften Deklarieren this.roomName = roomName; this.id = id; //Festlegen der Fokusierten if(direction == Directions.NORTH){ this.focusedDirection = Directions.NORTH; }else if(direction == Directions.EAST){ this.focusedDirection = Directions.EAST; }else if(direction == Directions.SOUTH){ this.focusedDirection = Directions.SOUTH; }else{ this.focusedDirection = Directions.WEST; } } /** *Selber Konstruktor wie oben, nur ohne Richtungszwang */ public Room(Wall nordWand, Wall ostWand, Wall suedWand, Wall westWand, String roomName, RoomName id){ //Definieren der Wände this.nordWand = nordWand; this.suedWand = suedWand; this.ostWand = ostWand; this.westWand = westWand; this.id = id; this.roomName = roomName; } /**###################################### * # Getter Funktionen # * ######################################*/ public String getRoomName(){ return roomName; } public Directions getFocusedDirection(){ return focusedDirection; } public Wall getFocusedWall(){ //Festlegen der Fokusierten if(focusedDirection == Directions.NORTH){ return nordWand; }else if(focusedDirection == Directions.EAST){ return ostWand; }else if(focusedDirection == Directions.SOUTH){ return suedWand; }else{ return westWand; } } public RoomName getRoomId(){ return this.id; } /** * ###################### * # Looking # * ###################### * */ public void look(Directions direction){ this.setFocusedDirection(direction); this.look(); } public void look(){ if(this.getFocusedWall().getBox() != null){ System.out.println(this.getFocusedWall().getBoxName()); }else { System.out.println(this.getFocusedWall().getWallName()); } } /** * ###################### * # inspecting # * ###################### * */ public void inspect(Directions direction){ this.setFocusedDirection(direction); this.inspect(); } public void inspect(){ if(this.getFocusedWall().getBox() != null) { System.out.println(this.getFocusedWall().getBoxDescription()); }else { System.out.println(this.getFocusedWall().getWallDescription()); } } /** * ###################### * # interacting # * ###################### * */ public void interact(){ } public genericItem openKiste(){ if(this.getFocusedWall().getBox() != null){ return this.getFocusedWall().getBox().openKiste(); }else{ System.out.println(TextStorage.NO_INTERACTION); return null; } } public genericItem openKiste(int code){ if(this.getFocusedWall().getBox() != null){ return this.getFocusedWall().getBox().openKiste(code); }else{ return null; } } /**###################################### * # Setter Funktionen # * ######################################*/ public void setFocusedDirection(Directions focusedDirection){ this.focusedDirection = focusedDirection; } /**###################################### * # Allgemeine Raumfunktionen # * ######################################*/ /** * Gibt eine Beschreibung des Ganzen Raumes*/ public void getRoomHelp(){ System.out.println(Colorlog.white(TextStorage.ROOM_LOCATION)); System.out.println(Colorlog.blue(roomName)); System.out.println(Colorlog.white(TextStorage.ROOM_INSPECTION_NOTATION)); //Beschreibungen Norden System.out.println(Colorlog.green(TextStorage.DIRECTION_NORTH)); System.out.print(Colorlog.cyan(TextStorage.RIGHTARROW)); System.out.println(Colorlog.white(nordWand.getWallName())); //Beschreibungen Osten System.out.println(Colorlog.green(TextStorage.DIRECTION_EAST)); System.out.print(Colorlog.cyan(TextStorage.RIGHTARROW)); System.out.println(Colorlog.white(ostWand.getWallName())); //Beschreibungen Süden System.out.println(Colorlog.green(TextStorage.DIRECTION_SOUTH)); System.out.print(Colorlog.cyan(TextStorage.RIGHTARROW)); System.out.println(Colorlog.white(suedWand.getWallName())); //Beschreibungen West System.out.println(Colorlog.green(TextStorage.DIRECTION_WEST)); System.out.print( Colorlog.cyan(TextStorage.RIGHTARROW)); System.out.println(Colorlog.white(westWand.getWallName())); } /** * Diese Funktion gibt Informationen zu den Unterschiedlichen Wänden * @param direction ist ein Enum, welches eines von 4 Werten annehmen kann {NORTH, EAST, SOUTH, WEST} * @return Die Funktion gibt die Beschreibung der entsprechenden Wand zurück */ public String wallInfos(Directions direction){ String output; switch (direction) { case NORTH: output = nordWand.getWallName(); break; case EAST: output = ostWand.getWallName(); break; case SOUTH: output = suedWand.getWallName(); break; case WEST: output = westWand.getWallName(); break; default: output = TextStorage.OOPS; } return output; } } <file_sep>/src/Main/Rooms/BuildingBlocks/Wall.java package Main.Rooms.BuildingBlocks; import Main.Enums.RoomName; import Main.Items.Kiste; import Main.Items.genericItem; import Main.Rooms.AllLevels; import Main.TextParser.Colorlog; import Main.Texte.TextStorage; /*** * Die Klasse Wall kann unterschiedliche Objekte besitzen. Es kann sein, dass sie gar nichts hat, eine Tür oder eine Kiste besitzt */ public class Wall { private Kiste box = null; private String wallDescription; private String wallName; private RoomName nextRoom = null; /** * ################# * # Konstruktoren # * #################*/ /** * Leerer Konstruktor, wird für Testing verwendt, damit ich nicht jedesmall einen vollen Raum generieren muss */ public Wall(){}; /** * Generieren einer Wand mit beschreibung * @param wallDescription beschreibt die Wand*/ public Wall(String wallName, String wallDescription){ this.wallName = wallName; this.wallDescription = wallDescription; } /*** * Generieren einer Wand, an welcher eine Kiste * @param box ist eine Kiste. Raumnamen und Raumbeschreibung werden von der Box übernommen*/ public Wall(String wallName, String wallDescription, Kiste box){ this.wallName = wallName; this.wallDescription = wallDescription; this.box = box; } /** * Dieser Konstruktor baut einen Durchgang * @param doorName Name des Durchganges * @param doorDescription Beschreibung des Durchganges */ public Wall(String doorName,String doorDescription, RoomName nextRoom){ this.wallDescription = doorDescription; this.wallName = doorName; this.nextRoom = nextRoom; } /** * ##################### * # Getter Functions # * #####################*/ /** * Gibt den Namen der Wand zurück * @return Beschreibung der Wand*/ public String getWallName(){ if(wallName != null){ return wallName; }else{ return TextStorage.WALL_EMPTY; } } /** * Gibt die Beschreibung der Wand zurück. * @return*/ public String getWallDescription(){ if(wallDescription != null){ return wallDescription; }else{ return TextStorage.WALL_EMPTY; } } public RoomName getNextRoom(){ return nextRoom; } //################################### INTERACTION WITH THE BOX ################################ public String getBoxName(){ return box.getKistenName(); } public String getBoxDescription(){ return box.getKistenDescription(); } public genericItem openBox(){ if(box != null){ return box.openKiste(); }else{ System.out.println(TextStorage.NO_INTERACTION); return null; } } public Kiste getBox(){ return box; } public genericItem openBox(int code){ return box.openKiste(code); } /** * #################### * # Wall functions # * #################### */ public void wallInfo(){ System.out.println(Colorlog.blue(wallName)); System.out.println(Colorlog.white(wallDescription)); System.out.println(); } public Room useDoor(){ if(nextRoom != null) { for (Room singleRoom : AllLevels.AllRooms) { if (singleRoom.getRoomId() == nextRoom) { return singleRoom; } } } return null; } } <file_sep>/src/Main/Texte/TextStorage.java package Main.Texte; public final class TextStorage { //PROLOG UND EPILOG public static final String PROLOG = "Hier kommt noch ein PrologText"; //TODO: finde einen guten Intro Text public static final String EPILOG = "Hier kommt noch ein EpilogText"; //TODO: finde einen guten Epilog Text //MISC public static final String LINE_FILLER = "*** "; public static final String LINEBREAK = " \n"; public static final String RIGHTARROW = "---> "; public static final String OOPS = "Oops! Da ist etwas fehlgeschlagen!"; public static final String NO_INTERACTION = "Du kannst hier keine Interaktion tätigen"; public static int wurstCode= 10; //ITEMS public static final String ITEM_PURPOSE = "Hmmm ich weiss nicht, wozu ich diesen Gegenstand verwenden kann."; //INVENTORY public static final String EMPTY_INVENTORY = "Es befindet sich nichts in deinem Inventar!"; public static final String INVENTORY_START_MESSAGE = "Dein Inventar besteht aus: \n"; public static final String INVENTORY_DESCRIPTION = "Beschreibung: "; //BOX public static final String BOX_OPENING = "Wow! Der Code wurde geknackt und die Kiste ist nun offen!"; public static final String BOX_LOCKED = "Leider stimmt der Code nicht!"; public static final String GET_ITEM_START = "*** Gratulation "; public static final String GET_ITEM_END = " wurde deinem Inventar hinzugefügt*** "; //ROOM public static final String ROOM_LOCATION = "Du befindest dich im Raum: "; public static final String ROOM_INSPECTION_NOTATION = "Nach einer kurzen Inspektion notierst du:"; //DIRECTIONS public static final String DIRECTION_NORTH = "Im Norden:"; public static final String DIRECTION_EAST = "Im Osten:"; public static final String DIRECTION_SOUTH = "Im Süden:"; public static final String DIRECTION_WEST = "Im Westen:"; //WALL public static final String WALL_DESCRIPTION_START = "Hier befindet sich eine Tür, welche dich "; public static final String WALL_DESCRIPTION_END = " führt."; public static final String WALL_DOOR_TO_DIRECTION = "Hier befindet sich eine Tür nach: "; public static final String WALL_EMPTY = "An dieser Wand befindet sich nichts."; public static final String WALL_INSPECTION_START = "An dieser Wand befindet sich: "; public static final String WALL_INSPECTION_EMPTY = "Es gibt hier keinen Gegenstand."; //HERO public static final String INTERRUPT_EXCEPTION_WARNING = "Oops! Da gab es eine InterruptException!"; public static final String TAKE_DAMAGE = "*Seufz* - Mein Frustrationslevel steigt..."; public static final String GAME_OVER = "Du hast keine Lust mehr und gibst auf... Das Spiel ist vorbei und du gehst nach Hause."; //--------------------- Rooms --------------------------------------- // Bahnhof Bern public static final String ROOM_NAME_PLATFORM = "Bahnhof Bern"; public static final String WALL_NAME_PLATFORM ="Gleise"; public static final String WALL_DESCRIPTION_PLATFORM="Du siehst die Gleise nahe bei deinen Füssen, Abstand denkst du dir und entfernst dich wieder von dem Gleis"; public static final String WALL_NAME_DEAD_END="Kein Durchgang"; public static final String WALL_DESCRIPTION_DEAD_END="Dieser Weg führt dich nicht zum Ziel! Wir müssen herausfinden, wo die Prüfungen sind! Auf auf ins Abenteuer"; public static final String WALL_NAME_ESCALATOR = "Rolltreppe" ; public static final String WALL_DESCRIPTION_ESCALATOR = "Du siehst wie die Rollteppe Stufe für Stufe in Richtung Welle 7 hochsteigt. Dieser Weg führt in Richtung FFHS"; // Welle 7 / Erdgeschoss public static final String ROOM_NAME_WELLE7 = "Welle 7"; public static final String WALL_NAME_GITTIG ="Gittig" ; public static final String WALL_DESCRIPTION_GITTTIG = "Ach herje.... wie schön Sie zu sehen! Mir ist etwas unglaubiches Passiert. Als ich rasch im Wurst und Moritz meine gratis Wurst holen wollten \nmit meinen 10 Stempel auf der Stempelkarte"+ " entwendete jemand die Prüfungen aus meinem Büro.\nAlle Prüfungen sind Weg!!!! \n"+ "Keine Linearen Algebraprüfungen, keine Statistikprüfungen und keine GTIprüfungen mehr. Kannst du mir helfen diese zu finden? \nFalls du was findest, kannst du sie mir im Büro der FFHS abgeben." + " Ansonsten müssen alle die Prüfungen nachholen. Und sind wütend auf mich."; public static final String WALL_NAME_WURST_MORITZ = "<NAME>"; public static final String WALL_DESCRIPTION_WURST_MORITZ = "Du siehst das breite Grinsen des Wurstverkäufers. Er Spricht dich an \nWurstverkäufer: Ich habe ein Geschenk für dich, doch zuerst musst du mir" + " eine Frage beantworten. \nWie viele Stempel braucht es für eine Gratiswurst? (Hilfe: Interagiere <anzahl>)"; public static final String WALL_OPEN_MESSAGE_WURST_MORITZ = " Du scheinst ein Wahrer Kunde zu sein! Hier hast du den Stapel von Linalg Prüfungen, die ich gefunden habe"; public static final String WALL_EMPTY_MESSAGE_WURST_MORITZ =" Du hast die Prüfungen bereits geholt. Mehr kann ich dir nicht geben!"; public static final String WALL_DENY_MESSAGE_WURST_MORITZ = " Schade, dass du nichteinmal dass weisst... Du bist leider nicht so ein treuer Kunde wie Gittig. Ich bin zu tiefst entäuscht"; public static final String ITEM_NAME_LINALG = "Lineare Algebra Prüfungen"; public static final String ITEM_PURPOSE_LINALG = "Ein Stapel von Linalg Prüfungen. Leider sieht es so aus, als ob du nicht bestanden hättest"; public static final String ITEM_LOCK_MESSAGE_LINALG = "Endlich bist du wieder hier, ich dachte meinen treusten Kunden bereits verloren zu haben. Ich habe ein Geschenk für dich! \n" + "Doch zuerst must du mir beantworten wie viele Stempel es benötigt um eine Sammelkarte zu füllen"; public static final String WALL_DESCRIPTION_ESCALATOR_REVERSE = "Von der Welle 7 aus kannst du die Gleise sehen, welche dich zurück zum Bahnhof führen. Doch dort wirst du wahrscheinlich nichts finden."; public static final String DOOR_NAME_STAIRS_EG_GANG = "Rolltreppe"; public static final String DOOR_DESCRIPTION_STAIRS_EG_GANG = "Neben den modernen Liften der Welle 7, deren Funktionsweise dir bis heute ein Rätsel ist, siehst du das Treppenhaus welches dich in die 1. Etage führen kann"; // 1.Etage public static final String ROOM_NAME_GANG1 = "1. Etage"; public static final String WALL_NAME_STAIRS = "Treppe"; public static final String EAST_WALL_DESCRIPTION_FIRST_FLOOR = "Schon wieder Treppen! Diese führen dich zur zweiten Etage."; public static final String WEST_WALL_DESCRIPTION_FIRST_FLOOR = "Die Treppen hinunter befindet sich das Erdgeschoss mit den vielen Essensständen der Welle 7."; public static final String SOUTH_WALL_NAME_FIRST_FLOOR = "Lounge"; public static final String SOUTH_WALL_DESCRIPTION_FIRST_FLOOR = "Ausgefallene Möbel. Das muss wohl eine der vielen Lounges von diesem Gebäude sein!"; public static final String NORTH_WALL_NAME_FIRST_FLOOR = "Tür"; public static final String NORTH_WALL_DESCRIPTION_FIRST_FLOOR = "Über der Tür hängt ein WC-Schild. Anscheinend befinden sich hier die topmodernen Toiletten der FFHS."; // WC public static final String ROOM_NAME_WC = "Toiletten"; public static final String WALL_NAME_WINDOW = "Fenster"; public static final String WALL_DESCRIPTION_WINDOW = "Aus den Fenstern des WC's kannst du nicht viel sehen. Was hast du erwartet."; public static final String WALL_NAME_WC = "Toiletten"; public static final String WALL_DESCRIPTION_WC = "Du schaust das WC an, welches wie aus Zauberhand die Spülung betätigt. Diese Funktionalität scheint wohl ein Bad Smell zu sein, denkst du dir."; public static final String WALL_NAME_SINK="Waschbecken"; public static final String WALL_DESCRIPTION_SINK="Dieses Waschbecken sieht ganz normal aus.... Doch warte einmal! Es scheinen einige Blätter daneben auf dem Boden zu liegen!"; public static final String ITEM_NAME_STATISTIK = "Statistik"; public static final String ITEM_DESCRIPTION_STATISTIK ="Ein Stapel von Statistikprüfungen... Anscheinend warst du in dieser Prüfung nicht schlecht, doch deine 4.5 reicht nicht aus um deine schlechte Vornote zu kompensieren"; public static final String BOX_NAME_HANDTUCH = "Handtuchspender"; public static final String BOX_DESCRIPTION_HANDTUCH ="Aus dem Handtuchspender hängen ein paar Blätter. Heiliger Bimbam, das scheinen die verlorenen Statistikprüfungen zu sein! "; public static final String BOX_OPEN_MESSAGE = "Stolz ziehst du die Statistikprüfungen aus dem Handtuchspender. Welch ein Triumpf!"; public static final String BOX_EMPTY_MESSAGE = "Du kannst nichts weiters im Handtuchspender finden. Schau lieber wo anderst nach"; public static final String WALL_NAME_WC_EXIT = "Ausgang WC"; public static final String WALL_DESCRIPTION_WC_EXIT = "Die Türe öffnet sich automatisch, vor dir ist wieder der Gang, welcher dich im Westen wieder ins Erdgeschoss"+ " führt oder Richtung Osten weitergeht zu weiteren Räumen"; // Zweite Etage public static final String ROOM_NAME_2FLOOR = "2. Etage"; public static final String EAST_WALL_NAME_SECOND_FLOOR = "Lift"; public static final String EAST_WALL_DESCRIPTION_SECOND_FLOOR = "Du siehst den Lift, welchen dich zur Oberen Etage bringt."; public static final String WEST_WALL_NAME_SECOND_FLOOR = "Treppe"; public static final String WEST_WALL_DESCRIPTION_SECOND_FLOOR = "Du schaust die Treppen hinunter und siehst die erste Etage."; public static final String SOUTH_WALL_NAME_SECOND_FLOOR = "Wand"; public static final String SOUTH_WALL_DESCRIPTION_SECOND_FLOOR = "An der Wand hängt ein Bildschirm mit dem Unterrichtsplan der FFHS."; public static final String NORTH_WALL_NAME_SECOND_FLOOR = "Tür"; public static final String NORTH_WALL_DESCRIPTION_SECOND_FLOOR = "Durch die Glastür hindurch siehst du den Studienraum mit dem üblichen Möbelierungsstandard der FFHS."; //Studienraum public static final String ROOM_NAME_STUDIENRAUM = "Unterrichtsraum"; public static final String ITEM_NAME_GTI = "Grundlagen Technische Informatik Prüfung (GTI)"; public static final String ITEM_DESCRIPTION_GTI = "Ein riesen Stapel Prüfungen. Mist! Du hast diese Prüfung vergeigt und nicht bestanden!"; public static final String ITEM_UNLOCK_GTI = "Du entnimmst den Stapel GTI Prüfungen aus dem Pult."; public static final String EAST_WALL_NAME_STUDY_ROOM = "Pult"; public static final String BOX_DESCRIPTION_PULT = "Die Schublade scheint nicht geschlossen zu sein"; public static final String BOX_OPEN_MESSAGE_PULT= "Du findest die GTI Prüfungen! Es scheint so, dass diese zusammen mit Prüfungen von der Migrosklubschule hier gelandet sind. "+ "Die Migros Klubschule ist aber nicht dein Problem, weshalb du diese Prüfungen kurzerhand in die Tonne trittst"; public static final String BOX_EMPTY_MESSAGE_PULT = "Die Schublade sieht leer aus, du hast hier bereits etwas gefunden !"; public static final String EAST_WALL_DESCRIPTION_STUDY_ROOM = "Du schaust auf ein Pult, welches eine Schublade hat. Vielleicht befindet sich etwas darin."; public static final String WEST_WALL_NAME_STUDY_ROOM = "Whiteboard"; public static final String WEST_WALL_DESCRIPTION_STUDY_ROOM = "An der Wand hängt ein Whiteboard. Wahrscheinlich wird in diesem Raum unterrichtet."; public static final String SOUTH_WALL_NAME_STUDY_ROOM = "Tür"; public static final String SOUTH_WALL_DESCRIPTION_STUDY_ROOM = "Durch die Glastür hindurch siehst du die zweite Etage."; public static final String NORTH_WALL_NAME_STUDY_ROOM = "Kaffeeautomat"; public static final String NORTH_WALL_DESCRIPTION_STUDY_ROOM = "Ich wünschte der Kaffeautomat würde funktionieren. Leider ist dieser eher zur dekoration im Raum."; //Obere Etage public static final String ROOM_NAME_3FLOOR = "Obere Etage"; public static final String EAST_WALL_NAME_UPPER_FLOOR = "Tür"; public static final String EAST_WALL_DESCRIPTION_UPPER_FLOOR = "Du siehst den Lift, welchen dich zur zweiten Etage bringt."; public static final String WEST_WALL_NAME_UPPER_FLOOR = "Tür"; public static final String WEST_WALL_DESCRIPTION_UPPER_FLOOR = "Du schaust durch die Tür und siehst Herrn Gittigs Büro."; public static final String SOUTH_WALL_NAME_UPPER_FLOOR = "Wand"; public static final String SOUTH_WALL_DESCRIPTION_UPPER_FLOOR = "An der Wand hängt das FFHS Plakat mit der Aufschrift: Studieren wann Sie wollen, wo Sie wollen und wie Sie wollen. Hmmm... Akkurat."; public static final String NORTH_WALL_NAME_UPPER_FLOOR = "Fenster"; public static final String NORTH_WALL_DESCRIPTION_UPPER_FLOOR = "Du schaust aus dem Fenster und siehst in den Hinterhof der FFHS."; //Büro FFHS public static final String ROOM_NAME_OFFICE = "Büro der FFHS"; public static final String ALL_EXAMS_IN_INVENTORY_TRUE = "Ah super! Vielen Dank, ich hatte schon Angst wir müssen die Prüfungen wiederholen. Wie ich sehe hast du aber leider nicht bestanden."; public static final String ALL_EXAMS_IN_INVENTORY_FALSE = "Dir fehlen aber noch ein paar Prüfungen. Ich brauche alle, sonst müssen wir die Prüfungen wiederholen."; public static final String EAST_WALL_NAME_BUREAU = "Wand"; public static final String EAST_WALL_DESCRIPTION_BUREAU = "An der Wand hängen ein paar Bilder und Auszeichnungen von Herrn Gittig. Interessant!"; public static final String WEST_WALL_NAME_BUREAU = "Fenster"; public static final String WEST_WALL_DESCRIPTION_BUREAU = "Du schaust aus dem Fenster und siehst die Gleise vom Bahnhof Bern. Nichts besonderes."; public static final String SOUTH_WALL_NAME_BUREAU = "<NAME>"; public static final String SOUTH_WALL_DESCRIPTION_BUREAU = "Da steht ja Herr Gittig. Er scheint gestresst zu sein."; public static final String NORTH_WALL_NAME_BUREAU = "Tür"; public static final String NORTH_WALL_DESCRIPTION_BUREAU = "Du schaust durch die Tür und siehst die obere Etage."; //----------------------------------- TESTING ------------------------------------------ public static final String TEST_WALL_DESCRIPTION = "Herzlich willkommen bei Wurst und Moritz Ich habe ein Geschenk für sie wollen sie es öffnen?"; public static final String TEST_WALL_NAME = "Wurst und Moritz"; public static final String TEST_ITEM_NAME ="Linalg Prüfungen"; public static final String TEST_ITEM_DESCRIPTION ="Leider nicht bestanden"; public static final String TEST_BOX_NAME = "Pult"; public static final String TEST_UNLOCKED_BOX_DESCRIPTION = "Diese Truhe scheint nicht verschlossen zu sein"; public static final String TEST_LOCED_BOX_DESCRIPTION = "Diese Truhe schein verschlossen zu sein"; public static final String TEST_OPEN_MESSAGE = "Die Kiste wurde geöffnet"; public static final String TEST_DENY_BOX_ACCESS = " UUppps, die Kiste scheint verschlossen zu sein. Kannst du sie öffnen?"; public static final String TEST_EMPTY_MESSAGE = "Du hast die Kiste bereits geleert. Mehr gibts nicht"; //---------------------------------------- KEY WORDS ------------------------------------- // Patterns public static final String HELP = "HILFE.*"; public static final String LOOK = "SCHAUE.*"; public static final String INSPECT = "BESCHREIBE.*" ; public static final String SAY = "REDE.*"; public static final String INVENTORY = ".*INVENTAR.*"; public static final String I_SEE = "WAS SEHE ICH"; public static final String PATTERN_GO= "GEHE.*"; public static final String WHERE_AM_I = "WO BIN ICH"; public static final String ROOM_DESCRIPTION = "RAUMBESCHREIBUNG"; public static final String INTERACT = "INTERAGIERE.*"; public static final String CODE_INPUT = ".*[0-9]+"; public static final String MAP = "KARTE"; public static final String MANUAL = ".*ANLEITUNG"; public static final String CHEAT ="LÖSUNG"; //Himmelsrichtungen public static final String NORTH = ".*NORDEN" ; public static final String SOUTH = ".*SÜDEN" ; public static final String EAST = ".*OSTEN" ; public static final String WEST = ".*WESTEN" ; //------------------------------------- TEXT PARSING MESSAGES --------------------------------- public static final String NON_VALID_EXPRESSION = "Ich verstehe den Ausdruck nicht... \nMit 'hilfe' kannst du nochmals die Kommandos nachschauen"; public static final String NO_DOOR_HERE ="An der Wand, die du Betrachtest gibt es keine Türe"; public static final String CHANGED_ROOM = "Du hast den Raum gewechselt und bist nun hier --> "; public static final String VIEW = "Dein Blick fällt nach: "; } <file_sep>/src/Test/Items/genericItemTest.java package Test.Items; import Main.Items.genericItem; import Main.Texte.TextStorage; import org.junit.Test; import static org.junit.Assert.*; public class genericItemTest { //Erstellen eines Objektes und Testen des Namens und Beschreibung @Test public void generateItem(){ genericItem item = new genericItem(TextStorage.TEST_ITEM_NAME,TextStorage.TEST_ITEM_DESCRIPTION); //Test ob der Gegenstand den richtigen String liefert assertEquals(TextStorage.TEST_ITEM_NAME, item.getItemName()); } @Test public void getDescription(){ genericItem item = new genericItem(TextStorage.TEST_ITEM_NAME,TextStorage.TEST_ITEM_DESCRIPTION); System.out.println(item.getDescription()); } }<file_sep>/out/production/The_Saga_Of_The_Lost_Exams/overview.md # Todo * Wandklasse fertig schreiben mit Tests * Raumklasse fertig schreiben mit Tests * Einfacher Sprachparser schreiben * Erstes Level erstellen <file_sep>/src/Main/PlayMe.java package Main; import Main.Graphics.Graphics; import Main.Hero.Hero; import Main.Rooms.AllLevels; import Main.TextParser.InputParser; import Main.Texte.TextStorage; import org.omg.PortableInterceptor.SYSTEM_EXCEPTION; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import static Main.Rooms.AllLevels.gti; import static Main.Rooms.AllLevels.linalg; import static Main.Rooms.AllLevels.statistik; public class PlayMe { public static void main(String[] args) throws FileNotFoundException { // Erstellen der benötigten Instanzen boolean game_not_completed = true; Hero chris = new Hero(AllLevels.bahnhof); InputParser parser = new InputParser(chris); Scanner scanner = new Scanner(System.in); String basePath = new File("").getAbsolutePath(); /** * Prolog des Spieles*/ Graphics.titleScreen(); InputParser.fileReader(basePath.concat("/src/Main/Texte/Prolog.txt")); /** * In diesem Loop läuft das spiel */ while (game_not_completed){ String word = scanner.nextLine(); parser.evaluate(word); //Beende das Spiel, wenn alle Prüfungen gefunden wurden und du dich im Büro befindest if(chris.getInventar().contains(linalg)&&chris.getInventar().contains(statistik)&&chris.getInventar().contains(gti)&&chris.getAktuellerRaum()== AllLevels.office){ InputParser.fileReader(basePath.concat("/src/Main/Texte/Epilog.txt")); game_not_completed = false; } // Ein wenig mehr Abstand System.out.println(); } } } <file_sep>/src/Main/Rooms/AllLevels.java package Main.Rooms; import Main.Enums.RoomName; import Main.Items.Kiste; import Main.Items.genericItem; import Main.Rooms.BuildingBlocks.Room; import Main.Rooms.BuildingBlocks.Wall; import Main.Texte.TextStorage; import java.util.ArrayList; import java.util.Arrays; public class AllLevels { /** * ############### * # OBJEKTE # * ###############*/ public static genericItem linalg = new genericItem(TextStorage.ITEM_NAME_LINALG,TextStorage.ITEM_PURPOSE_LINALG); public static genericItem statistik = new genericItem(TextStorage.ITEM_NAME_STATISTIK,TextStorage.ITEM_DESCRIPTION_STATISTIK); public static genericItem gti = new genericItem(TextStorage.ITEM_NAME_GTI,TextStorage.ITEM_DESCRIPTION_GTI); /** * ############### * # Kisten # * ###############*/ private static Kiste wurstMoritz = new Kiste(TextStorage.WALL_NAME_WURST_MORITZ,TextStorage.WALL_DESCRIPTION_WURST_MORITZ,TextStorage.WALL_OPEN_MESSAGE_WURST_MORITZ,TextStorage.WALL_EMPTY_MESSAGE_WURST_MORITZ,linalg, TextStorage.WALL_DENY_MESSAGE_WURST_MORITZ,TextStorage.wurstCode); private static Kiste handtuchSpender = new Kiste(TextStorage.BOX_NAME_HANDTUCH,TextStorage.BOX_DESCRIPTION_HANDTUCH,TextStorage.BOX_OPEN_MESSAGE,TextStorage.BOX_EMPTY_MESSAGE,statistik); private static Kiste pult = new Kiste(TextStorage.EAST_WALL_NAME_STUDY_ROOM,TextStorage.BOX_DESCRIPTION_PULT,TextStorage.BOX_OPEN_MESSAGE_PULT,TextStorage.BOX_EMPTY_MESSAGE_PULT,gti); /** * ############### * # Räume # * ###############*/ //------------------------------------------- Bahnhof ---------------------------------------------------------------------------- private static Wall nordWand_Bahnhof = new Wall(TextStorage.WALL_NAME_PLATFORM,TextStorage.WALL_DESCRIPTION_PLATFORM); private static Wall ostWand_Bahnhof = new Wall(TextStorage.WALL_NAME_ESCALATOR,TextStorage.WALL_DESCRIPTION_ESCALATOR,RoomName.WELLE); private static Wall suedWand_Bahnhof = new Wall(TextStorage.WALL_NAME_PLATFORM,TextStorage.WALL_DESCRIPTION_PLATFORM); private static Wall westWand_Bahnhof = new Wall(TextStorage.WALL_NAME_DEAD_END,TextStorage.WALL_DESCRIPTION_DEAD_END); public static Room bahnhof = new Room(nordWand_Bahnhof,ostWand_Bahnhof,suedWand_Bahnhof,westWand_Bahnhof,TextStorage.ROOM_NAME_PLATFORM,RoomName.BHF); //------------------------------------------- Welle 7 ---------------------------------------------------------------------------- private static Wall nordWand_Welle7 = new Wall(TextStorage.WALL_NAME_GITTIG,TextStorage.WALL_DESCRIPTION_GITTTIG); private static Wall ostWand_Welle7 = new Wall(TextStorage.WEST_WALL_NAME_SECOND_FLOOR,TextStorage.DOOR_DESCRIPTION_STAIRS_EG_GANG,RoomName.ETAGE1); private static Wall suedWand_Welle7 = new Wall(TextStorage.WALL_NAME_WURST_MORITZ,TextStorage.WALL_DESCRIPTION_WURST_MORITZ,wurstMoritz); private static Wall westWand_Welle7 = new Wall(TextStorage.WALL_NAME_ESCALATOR,TextStorage.WALL_DESCRIPTION_ESCALATOR_REVERSE, RoomName.BHF); public static Room welle7 = new Room(nordWand_Welle7,ostWand_Welle7,suedWand_Welle7,westWand_Welle7,TextStorage.ROOM_NAME_WELLE7,RoomName.WELLE); //--------------------------------------------- WC ---------------------------------------------------------------------------- private static Wall nordWand_WC = new Wall(TextStorage.WALL_NAME_WC,TextStorage.WALL_DESCRIPTION_WC); private static Wall ostWand_WC = new Wall(TextStorage.WALL_NAME_SINK,TextStorage.WALL_DESCRIPTION_SINK,handtuchSpender); private static Wall suedWand_WC = new Wall(TextStorage.WALL_NAME_WC_EXIT,TextStorage.WALL_DESCRIPTION_WC_EXIT,RoomName.ETAGE1); private static Wall westWand_WC = new Wall(TextStorage.WALL_NAME_WINDOW,TextStorage.WALL_DESCRIPTION_WINDOW); public static Room wc = new Room(nordWand_WC,ostWand_WC,suedWand_WC,westWand_WC,TextStorage.ROOM_NAME_WC,RoomName.WC); //--------------------------------------------- Etage1 ---------------------------------------------------------------------------- private static Wall nordWand_Etage1 = new Wall(TextStorage.NORTH_WALL_NAME_FIRST_FLOOR,TextStorage.NORTH_WALL_DESCRIPTION_FIRST_FLOOR,RoomName.WC); private static Wall ostWand_Etage1 = new Wall(TextStorage.WALL_NAME_STAIRS,TextStorage.EAST_WALL_DESCRIPTION_FIRST_FLOOR,RoomName.ETAGE2); private static Wall suedWand_Etage1 = new Wall(TextStorage.SOUTH_WALL_NAME_FIRST_FLOOR, TextStorage.SOUTH_WALL_DESCRIPTION_FIRST_FLOOR); private static Wall westWand_Etage1 = new Wall(TextStorage.WALL_NAME_STAIRS,TextStorage.WEST_WALL_DESCRIPTION_FIRST_FLOOR,RoomName.WELLE); public static Room etage1 = new Room(nordWand_Etage1, ostWand_Etage1, suedWand_Etage1, westWand_Etage1,TextStorage.ROOM_NAME_GANG1,RoomName.ETAGE1); //--------------------------------------------- Etage 2 ---------------------------------------------------------------------------- private static Wall nordWand_Etage2 = new Wall(TextStorage.NORTH_WALL_NAME_SECOND_FLOOR, TextStorage.NORTH_WALL_DESCRIPTION_SECOND_FLOOR, RoomName.UNTERRICHTSRAUM); private static Wall ostWand_Etage2 = new Wall(TextStorage.EAST_WALL_NAME_SECOND_FLOOR, TextStorage.EAST_WALL_DESCRIPTION_SECOND_FLOOR,RoomName.OBERE_ETAGE); private static Wall suedWand_Etage2 = new Wall(TextStorage.SOUTH_WALL_NAME_SECOND_FLOOR,TextStorage.SOUTH_WALL_DESCRIPTION_SECOND_FLOOR); private static Wall westWand_Etage2 = new Wall(TextStorage.WEST_WALL_NAME_SECOND_FLOOR,TextStorage.WEST_WALL_DESCRIPTION_SECOND_FLOOR,RoomName.ETAGE1); public static Room etage2 = new Room(nordWand_Etage2,ostWand_Etage2,suedWand_Etage2,westWand_Etage2,TextStorage.ROOM_NAME_2FLOOR,RoomName.ETAGE2); //--------------------------------------------- Studienraum ---------------------------------------------------------------------------- private static Wall nordWand_Studienraum = new Wall(TextStorage.NORTH_WALL_NAME_STUDY_ROOM,TextStorage.NORTH_WALL_DESCRIPTION_STUDY_ROOM); private static Wall ostWand_Studienraum = new Wall(TextStorage.EAST_WALL_NAME_STUDY_ROOM,TextStorage.EAST_WALL_DESCRIPTION_STUDY_ROOM,pult); private static Wall suedWand_Studienraum = new Wall(TextStorage.SOUTH_WALL_NAME_STUDY_ROOM,TextStorage.SOUTH_WALL_DESCRIPTION_STUDY_ROOM,RoomName.ETAGE2); private static Wall westWand_Studienraum = new Wall(TextStorage.WEST_WALL_NAME_STUDY_ROOM,TextStorage.WEST_WALL_DESCRIPTION_STUDY_ROOM); public static Room studienraum = new Room(nordWand_Studienraum,ostWand_Studienraum,suedWand_Studienraum,westWand_Studienraum,TextStorage.ROOM_NAME_STUDIENRAUM,RoomName.UNTERRICHTSRAUM); //--------------------------------------------- Obere Etage ---------------------------------------------------------------------------- private static Wall nordWand_ObereEtage = new Wall(TextStorage.NORTH_WALL_NAME_UPPER_FLOOR,TextStorage.NORTH_WALL_DESCRIPTION_UPPER_FLOOR); private static Wall westWand_ObereEtage = new Wall(TextStorage.EAST_WALL_NAME_UPPER_FLOOR,TextStorage.EAST_WALL_DESCRIPTION_UPPER_FLOOR,RoomName.ETAGE2); private static Wall suedWand_ObereEtage = new Wall(TextStorage.SOUTH_WALL_NAME_UPPER_FLOOR,TextStorage.SOUTH_WALL_DESCRIPTION_UPPER_FLOOR); private static Wall ostWand_ObereEtage = new Wall(TextStorage.WEST_WALL_NAME_UPPER_FLOOR,TextStorage.WEST_WALL_DESCRIPTION_UPPER_FLOOR,RoomName.OFFICE); public static Room obereEtage = new Room(nordWand_ObereEtage,ostWand_ObereEtage,suedWand_ObereEtage,westWand_ObereEtage,TextStorage.ROOM_NAME_3FLOOR,RoomName.OBERE_ETAGE); //--------------------------------------------- Büro FFHS ---------------------------------------------------------------------------- private static Wall nordWand_Office = new Wall(TextStorage.NORTH_WALL_NAME_BUREAU,TextStorage.NORTH_WALL_DESCRIPTION_BUREAU,RoomName.OBERE_ETAGE); private static Wall ostWand_Office = new Wall(TextStorage.EAST_WALL_NAME_BUREAU,TextStorage.EAST_WALL_DESCRIPTION_BUREAU); private static Wall suedWand_Office= new Wall(TextStorage.SOUTH_WALL_NAME_BUREAU, TextStorage.SOUTH_WALL_DESCRIPTION_BUREAU); private static Wall westWand_Office = new Wall(TextStorage.WEST_WALL_NAME_BUREAU,TextStorage.WEST_WALL_DESCRIPTION_BUREAU); public static Room office = new Room(nordWand_Office,ostWand_Office,suedWand_Office,westWand_Office,TextStorage.ROOM_NAME_OFFICE,RoomName.OFFICE); /** * ####################################### * # Öffentliche Arraylist der Räume # * #######################################*/ public static ArrayList<Room> AllRooms = new ArrayList<>(Arrays.asList(bahnhof, welle7,wc,etage1,etage2,studienraum,obereEtage,office)); } <file_sep>/README.md <p align="center"> <img width="476" height="164" src="https://github.com/CodingIsLove/TextAdventure/blob/master/GithubTitle.png"> </p> # Gittig ## Die Sage der verlorenen Abschlussprüfungen Du studierst an der FFHS in Bern und hast deine Semesterendprüfungen seit 2 Monaten hinter dir. Die Prüfungsergebnisse hätten vor 2 Tagen online gestellt werden sollen. Seltsam, was ist da geschehen?! In "Gittig" versuchts du herauszufinden, was mit deinen Prüfungsresultaten geschehen ist und ob du das letzte Semester bestanden hast oder nicht. Wende dein Verstand an und Löse das Rätzsel um die verlorenen Prüfungen. <file_sep>/src/Test/Hero/HeroTest.java package Test.Hero; import Main.Enums.Directions; import Main.Hero.Hero; import Main.Rooms.AllLevels; import org.junit.Test; public class HeroTest { @Test public void changeRoom() { Hero chris = new Hero(AllLevels.bahnhof); // Hier sollte kein Inventar sein chris.logInventar(); chris.getAktuellerRaum().getRoomHelp(); chris.getAktuellerRaum().look(Directions.EAST); chris.changeRoom(); chris.getAktuellerRaum().getRoomHelp(); chris.getAktuellerRaum().look(Directions.NORTH); chris.getAktuellerRaum().inspect(); chris.getAktuellerRaum().look(Directions.SOUTH); chris.getAktuellerRaum().inspect(); chris.openKiste(); chris.openKiste(10); // Null sollte das inventar die Linalgprüfungen haben chris.logInventar(); } }
f926b38a9fb49b29b71997ace08688b81cd59a57
[ "Markdown", "Java" ]
14
Java
CodingIsLove/TextAdventure
9ce8216dbc106a9276db3928640b1bb17662d2bc
6efeb514ae973e13173aed1af47b76333e750623
refs/heads/master
<repo_name>IsseiTAKEUCHI/PythonOpenCVPractice<file_sep>/panorama.py # coding: UTF-8 #複数枚の画像を読み込みパノラマ合成を行う # 参考 page # http://qiita.com/bohemian916/items/4d3cf6506ec7d8f628f3 # http://authorunknown408.blog.fc2.com/blog-entry-38.html #findHomography #http://opencv.jp/opencv-2svn/cpp/camera_calibration_and_3d_reconstruction.html#cv-findhomography #python % opencv3 で siftやsurfを使うには cv2.xfeatures2d.SIFT_create()とする #http://www.pyimagesearch.com/2015/07/16/where-did-sift-and-surf-go-in-opencv-3/ import cv2 import scipy as sp import numpy as np import random VIS_FOR_DEBUG = True def visKeyPoints(img1, points1) : tmp = np.zeros(img1.shape) tmp = img1 vis = cv2.merge((tmp, tmp, tmp)) for p in points1: color = (random.uniform(1,255), random.uniform(1,255), random.uniform(1,255)) cv2.circle(vis, (int(p[0]),int(p[1])), 5, color, 2) return vis def visMatching(img1, img2, points1, points2) : H1, W1 = img1.shape[:2] H2, W2 = img2.shape[:2] print(img1.shape) print(img2.shape) gray = sp.zeros( (max(H1, H2), (W1 + W2)), sp.uint8) gray[ :H1, :W1] = img1 gray[ :H2, W1: ] = img2 visImg = cv2.merge((gray, gray, gray)) for i in range(len(points1)): if( i % 2 != 0) : continue color = (random.uniform(1,255), random.uniform(1,255), random.uniform(1,255)) p1 = ( int(points1[i][0] ), int(points1[i][1] ) ) p2 = ( int(points2[i][0] + W1), int(points2[i][1] ) ) cv2.line(visImg, p1, p2, color) return visImg #周囲に背景画素があれば背景扱い def isFore(img, j,i): if( i==0 or j==0 or j==img.shape[0]-1 or i==img.shape[1]-1) : return False return img[j,i,0] and img[j+1,i,0] and img[j,i+1,0] and img[j-1,i,0] and img[j,i-1,0] # Mat2 : Homography mat for warping img2 def margeImages( img1, img2, Mat2) : #原点が左上に位置するように平行移動 (画像左下を考慮できていない) TransMat = np.identity(3) if( Mat2[0,2] < 0 ): TransMat[0,2] = -Mat2[0,2] if( Mat2[1,2] < 0 ): TransMat[1,2] = -Mat2[1,2] Mat2 = TransMat.dot( Mat2 ) #変形を考慮して画像サイズを決定 H1, W1 = img1.shape[:2] H2, W2 = img2.shape[:2] tmp1 = Mat2.dot( np.array([[W2],[ 0],[1]]) ) tmp2 = Mat2.dot( np.array([[W2],[H2],[1]]) ) W = int( max( W1 + TransMat[0,2], max(tmp1[0]/tmp1[2],tmp2[0]/tmp2[2]) ) ) H = int( max( H1 + TransMat[1,2], max(Mat2[1,2],TransMat[1,2]) ) ) warp1 = cv2.warpPerspective(img1,TransMat,(W,H)) warp2 = cv2.warpPerspective(img2,Mat2 ,(W,H)) output= np.array(warp1) # warp1 <-- warp2 for i in range(W): for j in range(H): if ( isFore(warp1,j,i) and isFore(warp2,j,i) ) : output[j,i] = (warp1[j,i]/ 2 + warp2[j,i]/ 2) elif( isFore(warp1,j,i) ) : output[j,i] = warp1[j,i] elif( isFore(warp2,j,i) ) : output[j,i] = warp2[j,i] return warp1, warp2, output def calc_macheing_mat(grayImg1, grayImg2) : #key point detection keyPt:点配列, des:特徴ベクトル配列 #detector = cv2.xfeatures2d.SURF_create() #detector = cv2.xfeatures2d.SIFT_create() detector = cv2.AKAZE_create() keyPt1, des1 = detector.detectAndCompute(grayImg1, None) keyPt2, des2 = detector.detectAndCompute(grayImg2, None) print("feature points computed", des1.shape, len(keyPt1)) #matching key points --> trimming matches = cv2.BFMatcher( cv2.NORM_L2 ).match(des1, des2) threshold = np.array([m.distance for m in matches]).mean() * 0.8 matches_trim = [m for m in matches if m.distance < threshold] #compute 変換行列 point1 = np.array( [ np.array(keyPt1[m.queryIdx].pt) for m in matches_trim ]) point2 = np.array( [ np.array(keyPt2[m.trainIdx].pt) for m in matches_trim ]) if( VIS_FOR_DEBUG ) : ptimg1 = visKeyPoints(grayImg1, point1) ptimg2 = visKeyPoints(grayImg2, point2) visImg = visMatching(grayImg1, grayImg2, point1, point2) cv2.imshow("keyPoints1", ptimg1 ) cv2.imshow("keyPoints2", ptimg2 ) cv2.imshow("matching", visImg ) H, Hstatus = cv2.findHomography(point2,point1,cv2.RANSAC) return H def panorama(img1, img2) : gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY) gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY) Mat = calc_macheing_mat( gray1, gray2) print(Mat) warp1, warp2, res = margeImages(img1, img2, Mat) if( VIS_FOR_DEBUG ) : cv2.imshow("1", warp1) cv2.imshow("2", warp2) cv2.imshow("3", res ) cv2.waitKey(0) return res #main I1 = cv2.imread("imgs/pano1.JPG") I2 = cv2.imread("imgs/pano2.JPG") I3 = cv2.imread("imgs/pano3.JPG") I4 = cv2.imread("imgs/pano4.JPG") res = panorama( I1, I2) res = panorama(res, I3) res = panorama(res, I4) cv2.imwrite("panoramaRes.png", res) cv2.imshow("result", res) cv2.waitKey(0) <file_sep>/histogram.py # coding: UTF-8 # 画像のヒストグラム計算 import numpy as np import pylab as plt import cv2 #画像読み込み & グレースケール化 #img_gry = cv2.imread("imgs/sample.png", 0) #変換結果が汚い img = cv2.imread("imgs/sample.png") img_gry = cv2.cvtColor( img, cv2.COLOR_BGR2GRAY ) #histogram生成 hist = np.zeros(256) for y in range(img_gry.shape[0]): for x in range(img_gry.shape[1]): hist[ img_gry[y,x] ] += 1 #windowを生成して画像を表示 cv2.imshow("Image", img_gry ) #histをmatplotlibで表示 plt.plot(hist) plt.xlim([0,256]) plt.show() <file_sep>/sample.py # coding: UTF-8 import numpy as np import cv2 #画像読み込み img = cv2.imread("imgs/sample.png") print(img.shape) ##np.arrayを画像として保存 cv2.imwrite("saveTest.png", img) ##windowを生成して画像を表示 cv2.imshow("img viewer", img ) cv2.waitKey(0) #キーボード入力待ち<file_sep>/FourierImg.py # coding: UTF-8 # 画像にフーリエ変換を施し,周波数領域でマスク処理をして逆フーリエ変換する import cv2 import numpy as np import pylab as plt import itertools #画像を読み込み、フーリエ変換 img = cv2.imread("imgs/lena.png") img = cv2.cvtColor( img, cv2.COLOR_BGR2GRAY ) img_dft = cv2.dft(np.float32(img),flags = cv2.DFT_COMPLEX_OUTPUT) img_dft = np.fft.fftshift(img_dft) #gen masks LOW = 20 HIGH = 40 H = img.shape[0] W = img.shape[1] lowPass_mask = np.zeros( (H,W,2) ) highPass_mask = np.zeros( (H,W,2) ) bandPass_mask = np.zeros( (H,W,2) ) for y, x in itertools.product(range(H),range(W)): d = np.sqrt( (y-H/2)*(y-H/2) + (x-W/2)*(x-W/2) ) lowPass_mask [y,x,:] = 1.0 if d < LOW else 0. highPass_mask[y,x,:] = 1.0 if HIGH < d else 0. bandPass_mask[y,x,:] = 1.0 if LOW < d and d < HIGH else 0. #直流成分は1に lowPass_mask [int(H/2),int(W/2),:]=1.0 highPass_mask[int(H/2),int(W/2),:]=1.0 bandPass_mask[int(H/2),int(W/2),:]=1.0 #mask処理 img_dft_low = lowPass_mask * img_dft img_dft_high = highPass_mask * img_dft img_dft_band = bandPass_mask * img_dft #逆フーリエ変換(シフトしてから逆フーリエ変換する) img_dft_low_idft = cv2.idft(np.fft.ifftshift(img_dft_low ), flags=cv2.DFT_SCALE ) img_dft_high_idft = cv2.idft(np.fft.ifftshift(img_dft_high), flags=cv2.DFT_SCALE ) img_dft_band_idft = cv2.idft(np.fft.ifftshift(img_dft_band), flags=cv2.DFT_SCALE ) img_dft_power = np.zeros((H,W)) for y, x in itertools.product(range(H),range(W)): img_dft_power[y,x] = np.linalg.norm(img_dft[y,x,:]) cv2.imshow("original" , img) cv2.imshow("low pass", np.uint8(img_dft_low_idft [:,:,0])) cv2.imshow("high pass", np.uint8(img_dft_high_idft[:,:,0])) cv2.imshow("band pass", np.uint8(img_dft_band_idft[:,:,0])) cv2.imshow("lowPass_mask" , np.uint8(255.0*lowPass_mask[:,:,0])) cv2.imshow("highPass_mask", np.uint8(255.0*highPass_mask[:,:,0])) cv2.imshow("bandPass_mask", np.uint8(255.0*bandPass_mask[:,:,0])) cv2.imshow("DFT(power spectrum) ", img_dft_power*0.00005) #cv2.imwrite("0.png", np.uint8(img_dft_low_idft [:,:,0])) #cv2.imwrite("1.png", img_dft_power*0.01) #cv2.imwrite("2.png", np.uint8(img_dft_high_idft[:,:,0])) #cv2.imwrite("3.png", np.uint8(img_dft_band_idft[:,:,0])) #cv2.imwrite("4.png" , np.uint8(255.0*lowPass_mask[:,:,0])) #cv2.imwrite("5.png", np.uint8(255.0*highPass_mask[:,:,0])) #cv2.imwrite("6.png", np.uint8(255.0*bandPass_mask[:,:,0])) cv2.waitKey(0) <file_sep>/tmp.py # coding: UTF-8 import numpy as np import cv2 from scipy.stats import threshold for a = np.array([1,2,3,4,5,6,7,8]) b = threshold(a, 3) print(a) print(b) <file_sep>/dm1_13/KernelGenerator.py # -*- coding: utf-8 -*- import numpy as np import sys import cv2 import math # 2D gaussian funciton f(x,y) = 1/(2 pi s^2) exp(- (x^2+y^2) / (2*s^2) ) # its fourier transform F(u,v) = exp(- (x^2+y^2) * s^2 / 2 ) # W,H : resolution of (x,y) and (u,v) # sigma : standard deviation def gaussian_kernel ( H, W,dtype = np.float32, sigma = 3.0) : coef = 1.0 / (2.0 * math.pi * sigma * sigma) c1 = 1.0 / (2.0 * sigma * sigma) c2 = sigma * sigma / 2 kernel = np.zeros((H,W), dtype ) kernel_f = np.zeros((H,W), dtype ) for y in range ( H ) : for x in range ( W ) : px = x if( x < W / 2) else (W-x) py = y if( y < H / 2) else (H-y) pu = px * 2 * math.pi / W pv = py * 2 * math.pi / H kernel [y,x] = coef * math.exp( - c1 * (px*px + py*py) ) kernel_f[y,x] = math.exp( - c2 * (pu*pu + pv*pv) ) return kernel, kernel_f # w(y,x) = 1/(2*W) (線分上), 0 (線分上) : 線分は長さ -W ~ W, 傾きtheta # W(v,u) = def line_kernel( H, W, dtype = np.float32, width = 10, theta = 0.0) : kernel = np.zeros((H,W), dtype ) kernel_f = np.zeros((H,W), dtype ) c = math.cos(theta) s = math.sin(theta) for y in range ( H ) : for x in range ( W ) : px = x if( x < W / 2) else -(W-x) py = y if( y < H / 2) else -(H-y) pu = px * 2 * math.pi / W pv = py * 2 * math.pi / H #本来は直線を書くべきだけど少し雑な実装を if( abs( px*c + py*s) <= width + 0.1 and abs(px*s - py*c) < 0.5 ) : kernel [y,x] = 1 / (2 * width) a = (width) * ( pu * c + pv * s ) if ( abs(a) > 0.00001) : kernel_f[y,x] = math.sin( a ) / a else : kernel_f[y,x] = 1 return kernel, kernel_f def MyFourierTransform2d(img) : #出力画像を準備(グレースケール,float型) H = img.shape[0] W = img.shape[1] Rvu = np.zeros_like( img ) Ivu = np.zeros_like( img ) #Fourier transform フィルタ処理 (for文は遅いけど今回は気にしない) for v in range( H ) : for u in range( W ) : for y in range( H ) : for x in range( W ) : c = math.cos( - 2 * math.pi * ( u*x/W + v*y/H) ) s = math.sin( - 2 * math.pi * ( u*x/W + v*y/H) ) Rvu[v,u] += c * img[y,x] Ivu[v,u] += s * img[y,x] return Rvu, Ivu if __name__ == '__main__': gauss, gauss_f = gaussian_kernel( 50, 50, np.float64, 0.5) gauss_fft = np.fft.fft2(gauss) #gauss_myDftR, gauss_myDftI = MyFourierTransform2d(gauss) cv2.imwrite("kernel.png" , np.uint8( gauss * 1024 )) cv2.imwrite("kernel_f.png" , np.uint8( gauss_f * 300 )) cv2.imwrite("kernel_fft.png" , np.uint8( np.real(gauss_fft) * 300 )) #cv2.imwrite("kernel_myR.png" , np.uint8( gauss_myDftR * 1024 ) ) #cv2.imwrite("kernel_myI.png" , np.uint8( gauss_myDftI * 1024 ) ) kernel1D, kernel1D_f = line_kernel( 51, 51, np.float64, 5, math.pi * 0.1) kernel1D_fft = np.fft.fft2(kernel1D) cv2.imwrite("lineKernel.png" , np.uint8( kernel1D * 20 * 200 )) cv2.imwrite("lineKernel_f.png" , np.uint8( kernel1D_f * 100 + 128)) cv2.imwrite("lineKernel_fft.png", np.uint8( np.real(kernel1D_fft) * 100 + 128)) <file_sep>/dm1_13/deconvolution.py # -*- coding: utf-8 -*- import numpy as np import sys import cv2 import math import KernelGenerator as kernel #自作するとおそいので np.fft に頼る def export_complex_img( fname, _img) : img = np.copy(_img) img_r = np.real( img ) img_i = np.imag( img ) img_a = np.abs ( img ) #可視化時はマイナス項無視 img_a *= 255 / max( 0.1, min( 100000, np.max(img_r)) ) img_r *= 255 / max( 0.1, min( 100000, np.max(img_r)) ) img_i *= 255 / max( 0.1, min( 100000, np.max(img_i)) ) cv2.imwrite(fname + "_real.png" , np.uint8( img_r )) cv2.imwrite(fname + "_imag.png" , np.uint8( img_i )) cv2.imwrite(fname + "_abso.png" , np.uint8( img_a )) def deconvolution( img_f, kernel_f, threshold = 0.01 ) : H = img_f.shape[0] W = img_f.shape[1] img_fft1 = np.copy(img_f) img_fft2 = np.copy(img_f) img_fft3 = np.copy(img_f) img_fft4 = np.copy(img_f) for v in range ( H ) : for u in range ( W ) : #simple algorithm simple_v = kernel_f[v,u] if( abs(simple_v) < threshold) : if( simple_v < 0 ) : simple_v = -threshold else: simple_v = threshold img_fft1[v,u] /= simple_v #Weiner filter val = kernel_f[v,u] img_fft2[v,u] *= val / (val * val + 0.00001 ) img_fft3[v,u] *= val / (val * val + 0.00100 ) img_fft4[v,u] *= val / (val * val + 0.10000 ) cv2.imwrite("tmp.png" , np.uint8( 0.01 * np.abs( np.fft.fftshift(img_fft1)) )) deconv1 = np.real(np.fft.ifft2( img_fft1 )) deconv2 = np.real(np.fft.ifft2( img_fft2 )) deconv3 = np.real(np.fft.ifft2( img_fft3 )) deconv4 = np.real(np.fft.ifft2( img_fft4 )) return deconv1, deconv2, deconv3, deconv4 #2種類(1+3パターン)のgaussian kernel deconvolutionを適用し、2枚の画像を返す def deconvolution_gauss( img, sigma ) : H = img.shape[0] W = img.shape[1] img_fft = np.fft.fft2(img) gauss, gauss_f = kernel.gaussian_kernel( H,W, np.float64, sigma) return deconvolution(img_fft, gauss_f, 0.1) #4種類のgaussian kernel deconvolutionを適用し、2枚の画像を返す def deconvolution_linePSF( img, width, theta ) : H = img.shape[0] W = img.shape[1] img_fft = np.fft.fft2(img) linekernel, linekernel_f = kernel.line_kernel( H,W, np.float64, width, theta) #return deconvolution(img_fft, np.fft.fft2(linekernel)) return deconvolution(img_fft, linekernel_f, 0.1) if __name__ == '__main__': #1. load input image fname_in = sys.argv[1] img = cv2.cvtColor( cv2.imread( fname_in ), cv2.COLOR_RGB2GRAY) img = np.float64( img ) H, W = img.shape[0], img.shape[1] sigma = 6.0 gauss, gauss_f = kernel.gaussian_kernel(H,W, np.float64, sigma) width = 20.0 theta = math.pi * 0.8 lineKernel, lineKernel_f = kernel.line_kernel(H,W, np.float64, width, theta) img_noise = 0.1 * np.random.rand(img.shape[0], img.shape[1] ) #lineKernel_f = np.fft.fft2(lineKernel) #compute blurred image img_fft = np.fft.fft2 ( img ) img_gaussBlurr = np.fft.ifft2( gauss_f * img_fft) + img_noise img_lineBlurr = np.fft.ifft2( lineKernel_f * img_fft) + img_noise debug_export = 1 if( debug_export ) : cv2.imwrite("img.png" , np.uint8( img ) ) cv2.imwrite("img_noise.png" , np.uint8( 10*img_noise ) ) cv2.imwrite("img_gaussBlurr.png" , np.uint8( np.real(img_gaussBlurr) )) cv2.imwrite("img_lineBlurr.png" , np.uint8( np.real(img_lineBlurr ) )) lineblurr_fft = np.fft.fft2(img_lineBlurr) cv2.imwrite("lineblurr_fft.png" , np.uint8( 0.01 * np.abs( np.fft.fftshift(lineblurr_fft)) )) cv2.imwrite("kernelL.png" , np.uint8( width * 2 * 255 * np.fft.fftshift( lineKernel )) ) cv2.imwrite("kernelL_fft.png" , np.uint8( 120 * np.fft.fftshift( lineKernel_f ) + 127) ) cv2.imwrite("kernelG.png" , np.uint8(50000 * np.fft.fftshift( gauss) ) ) cv2.imwrite("kernelG_fft.png" , np.uint8( 255 * np.abs( np.fft.fftshift(gauss_f )) )) """ cv2.imwrite("img_fft.png" , np.uint8( np.real( np.fft.fftshift( img_fft) ) / W / H ) ) blurr_fft = np.fft.fft2(img_gaussBlurr) cv2.imwrite("blurr_fft.png" , np.uint8( 0.01 * np.abs( np.fft.fftshift(blurr_fft)) )) cv2.imwrite("img_fft.png" , np.uint8( 0.01 * np.abs( np.fft.fftshift(img_fft )) )) """ decImg1, decImg2, decImg3, decImg4 = deconvolution_gauss(img_gaussBlurr, sigma) decImg1[ decImg1 > 255] = 255 decImg2[ decImg2 > 255] = 255 cv2.imwrite("decImg1.png", np.uint8( decImg1 ) ) cv2.imwrite("decImg2.png", np.uint8( decImg2 ) ) cv2.imwrite("decImg3.png", np.uint8( decImg3 ) ) cv2.imwrite("decImg4.png", np.uint8( decImg4 ) ) decImg1, decImg2, decImg3, decImg4 = deconvolution_linePSF(img_lineBlurr, width, theta) decImg1[ decImg1 > 255] = 255 decImg2[ decImg2 > 255] = 255 cv2.imwrite("decImgLine1.png", np.uint8( decImg1 ) ) cv2.imwrite("decImgLine2.png", np.uint8( decImg2 ) ) cv2.imwrite("decImgLine3.png", np.uint8( decImg3 ) ) cv2.imwrite("decImgLine4.png", np.uint8( decImg4 ) ) <file_sep>/hough.py # coding: utf-8 import cv2 import numpy as np img_gray = cv2.imread ("imgs/book4.jpg",0) img_canny = cv2.Canny (img_gray, 75,150,apertureSize = 3) img_vis = cv2.merge ((img_gray,img_gray,img_gray)) #直線検出 ACCURACY_RHO = 1 ACCURACY_THETA = np.pi/180.0 THRESH_VOTE = 120 hough_lines = cv2.HoughLines(img_canny, ACCURACY_RHO, ACCURACY_THETA, THRESH_VOTE) #大きな円検出 CANNY_PARAM = 150 THRESH_VOTE = 500 hough_circles1 = cv2.HoughCircles(img_gray, cv2.HOUGH_GRADIENT, dp=4, minDist=5, param1=CANNY_PARAM, param2=THRESH_VOTE, minRadius=70, maxRadius=200 ) #小さな円検出 CANNY_PARAM = 150 THRESH_VOTE = 140 hough_circles2 = cv2.HoughCircles(img_gray, cv2.HOUGH_GRADIENT, dp=4, minDist=5, param1=CANNY_PARAM, param2=THRESH_VOTE, minRadius=20, maxRadius=30 ) for line in hough_lines : for rho, theta in line : cosT = np.cos(theta) sinT = np.sin(theta) x1 = int( rho*cosT + 1000*(-sinT)) y1 = int( rho*sinT + 1000*( cosT)) x2 = int( rho*cosT - 1000*(-sinT)) y2 = int( rho*sinT - 1000*( cosT)) cv2.line(img_vis, (x1,y1), (x2,y2), (0,0,255),1) if( hough_circles1 is not None ) : for c in hough_circles1 : for x,y,r in c: cv2.circle(img_vis, (x,y),r, (0,255,0), 2) if( hough_circles2 is not None ) : for c in hough_circles2 : for x,y,r in c: cv2.circle(img_vis, (x,y),r, (255,0,0), 2) cv2.imshow("c", img_canny) cv2.imshow("a", img_vis ) cv2.waitKey(0) <file_sep>/genChart3D.py # coding: UTF-8 import numpy as np import cv2 from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111, projection='3d') N = 40 #X, Y, Z = axes3d.get_test_data(0.05) X = np.zeros((N,N)) Y = np.zeros((N,N)) Z = np.zeros((N,N)) scale = 0.25 s = 1. c = 1.0 / ( 2 * np.pi * s*s ) for y in range(N) : for x in range(N) : xp = (x - N/2)* scale yp = (y - N/2)* scale X[y,x] = xp Y[y,x] = yp #simple gaussian #Z[y,x] = c * np.exp( -(xp*xp + yp*yp) / (2*s*s) ) Z[y,x] = - 2 * xp * xp - yp * yp #sinc function #sincx = 1 #sincy = 1 #if( xp != 0 ) : sincx = np.sin( np.pi * xp ) / (np.pi * xp) #if( yp != 0 ) : sincy = np.sin( np.pi * yp ) / (np.pi * yp) #Z[y,x] = c * sincx * sincy maxV = np.max(Z) img = Z / maxV cv2.imwrite( "output.bmp", np.uint8(254 * img) ) # Plot a basic wireframe. ax.plot_wireframe(X, Y, Z, rstride=1, cstride=1) plt.show() <file_sep>/FourierPaint.py # coding: UTF-8 # フーリエ変換のデモ # 画像Iを読み込み、そのフーリエ変換Fを得る # "mask"ウインドウ -- ユーザはマスクをペイントできる # "idft"ウインドウ -- ユーザが塗った部分のみを利用してFに逆フーリエ変換を適用 # "wave"ウインドウ -- 現在のマウス位置に対応する2次元waveを表示 import cv2 import numpy as np import pylab as plt def update_mask(x,y) : global img_dft,img_idft,img_mask,img_viz, img_wave, drawing img_mask[y-3:y+3,x-3:x+3,:] = 1. img_viz = img_dft * img_mask img_idft = cv2.idft(np.fft.ifftshift(img_viz), flags=cv2.DFT_SCALE ) tmp_mask = np.zeros( img_dft.shape ) tmp_mask[y,x,:] = 1 img_wave= cv2.idft(np.fft.ifftshift(tmp_mask)) img_wave = (img_wave - img_wave.min()) / (img_wave.max()-img_wave.min()) * 255.0 # mouse callback function def mouse_listener(event,x,y,flags,param): global drawing, SCALE if event == cv2.EVENT_LBUTTONDOWN: drawing = True update_mask(int(x/SCALE),int(y/SCALE)) elif event == cv2.EVENT_LBUTTONUP: drawing = False elif event == cv2.EVENT_MOUSEMOVE: if drawing == True: update_mask(int(x/SCALE),int(y/SCALE)) SCALE = 3 img = cv2.imread("imgs/lenasml.png") img = cv2.cvtColor( img, cv2.COLOR_BGR2GRAY ) img_dft = cv2.dft(np.float32(img),flags = cv2.DFT_COMPLEX_OUTPUT) img_dft = np.fft.fftshift(img_dft) img_mask = np.zeros( img_dft.shape ) img_mask[int(img_mask.shape[0]/2),int(img_mask.shape[1]/2),:] = 1. #直流成分 img_viz = img_mask * img_dft img_idft = cv2.idft(np.fft.ifftshift(img_viz), flags=cv2.DFT_SCALE ) img_wave = img_idft drawing = False cv2.namedWindow('mask') cv2.setMouseCallback('mask',mouse_listener) while(1): img_viz3 = cv2.resize(img_viz , None, fx = SCALE, fy = SCALE) img_idft3 = cv2.resize(img_idft, None, fx = SCALE, fy = SCALE) img_wave3 = cv2.resize(img_wave, None, fx = SCALE, fy = SCALE) cv2.imshow('mask',0.0001 * img_viz3 [:,:,0]) cv2.imshow('idft',np.uint8(img_idft3[:,:,0])) cv2.imshow('wave',np.uint8(img_wave3[:,:,0])) k = cv2.waitKey(1) & 0xFF if k == 27: break cv2.destroyAllWindows() <file_sep>/EigenVector.py # coding: UTF-8 # 固有値の意味理解のため,線形変換結果を可視化する # 参考 http://qiita.com/kenmatsu4/items/2a8573e3c878fc2da306 import matplotlib.pyplot as plt import numpy as np from matplotlib import animation as ani N = 30 R = 2.0 colPalet = [] for i in range(N) : colPalet.append([0.1 * (i%10), 0.3 * (i/10), 0]) if(0) : #通常行列0 A = [[ 4, 2], [ 1, 3] ] x1 = 2 v1 = [-1,1] x2 = 5 v2 = [ 2,1] elif(0) : #通常行列1 A = [[ 1, 0], [ 1, 3] ] x1 = 1 v1 = [2,-1] x2 = 3 v2 = [ 0,1] elif(0) : #通常行列2 A = [[ 1, 3], [ 2, -1] ] x1 = -np.sqrt(7) v1 = [0.5*(-np.sqrt(7) + 1), 1] x2 = np.sqrt(7) v2 = [0.5*( np.sqrt(7) + 1), 1] elif(0) : #通常行列3 A = [[ 2, 1], [ 1.5, 2] ] x1 = (-np.sqrt(6) + 4.0 ) / 2.0 v1 = [-np.sqrt(6)/3, 1] x2 = ( np.sqrt(6) + 4.0 ) / 2.0 v2 = [ np.sqrt(6)/3, 1] elif(1) : #対称行列1 A = [[ 1.0, 2.0], [ 2.0, 1.0] ] x1 = -1 v1 = [-1, 1] x2 = 3 v2 = [ 1,1] else: #対称行列1 A = [[ 1.0, -2.0], [ -2.0, 1.0] ] x1 = -1 v1 = [ 1, 1] x2 = 3 v2 = [-1, 1] fig, (figL, figR) = plt.subplots(ncols=2, figsize=(2*5,5), sharex=True ) figL.set_xlim(-10, 10) figL.set_ylim(-10, 10) figR.set_xlim(-10, 10) figR.set_ylim(-10, 10) figL.plot([-10,10],[ 0, 0],"k", linewidth=1) figL.plot([ 0, 0],[-10,10],"k", linewidth=1) figR.plot([-10,10],[ 0, 0],"k", linewidth=1) figR.plot([ 0, 0],[-10,10],"k", linewidth=1) figL.plot([0,R*x1*v1[0]],[0,R*x1*v1[1]],"k", linewidth=3, color="r") figL.plot([0,R*x2*v2[0]],[0,R*x2*v2[1]],"k", linewidth=3, color="b") figR.plot([0,R*x1*v1[0]],[0,R*x1*v1[1]],"k", linewidth=3, color="r") figR.plot([0,R*x2*v2[0]],[0,R*x2*v2[1]],"k", linewidth=3, color="b") for i in range(N) : angle = i * 2.0 * np.pi / N a = [R * np.cos(angle), R * np.sin(angle)] b = np.dot(A , a) c = colPalet[i%len(colPalet)] figL.scatter(a[0], a[1], color=c) figR.scatter(b[0], b[1], color=c) figR.plot([a[0],b[0]],[a[1],b[1]],"k" , linewidth=1) plt.show()
a3f7996035fb3df809a79e7f7c7463470ed73353
[ "Python" ]
11
Python
IsseiTAKEUCHI/PythonOpenCVPractice
e2799cb481bb0e4d0b9edce8363f8fc0df29fa09
c08159d2181cc1772f90ba6d5daf0df893434f25